hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
f71483250f4208d1d6c47fbd42c29ab271f6db11
24
py
Python
tests/applicationinsights_tests/exception_tests/__init__.py
Rebeccalau/ApplicationInsights-Python
cc91fede2d6d6c48acaa5687aa13ca491a17025a
[ "MIT" ]
89
2015-05-06T22:02:17.000Z
2019-04-22T14:50:33.000Z
tests/applicationinsights_tests/exception_tests/__init__.py
Rebeccalau/ApplicationInsights-Python
cc91fede2d6d6c48acaa5687aa13ca491a17025a
[ "MIT" ]
115
2015-04-29T17:44:52.000Z
2019-04-25T21:39:02.000Z
tests/applicationinsights_tests/exception_tests/__init__.py
Rebeccalau/ApplicationInsights-Python
cc91fede2d6d6c48acaa5687aa13ca491a17025a
[ "MIT" ]
59
2015-04-19T13:34:52.000Z
2019-04-25T21:04:02.000Z
from . import TestEnable
24
24
0.833333
from . import TestEnable
true
true
f71483376b99d2de664991b4779d8b43020d054e
888
py
Python
from_3b1b/on_hold/eop/reusables/eop_helpers.py
Tarang74/manim
df34d6fc0470916cfba63534b023addb69cdec9a
[ "MIT" ]
1
2021-03-26T08:23:35.000Z
2021-03-26T08:23:35.000Z
from_3b1b/on_hold/eop/reusables/eop_helpers.py
Tarang74/manim
df34d6fc0470916cfba63534b023addb69cdec9a
[ "MIT" ]
null
null
null
from_3b1b/on_hold/eop/reusables/eop_helpers.py
Tarang74/manim
df34d6fc0470916cfba63534b023addb69cdec9a
[ "MIT" ]
null
null
null
from utils.color import * from active_projects.eop.reusables.eop_constants import * def binary(i): # returns an array of 0s and 1s if i == 0: return [] j = i binary_array = [] while j > 0: jj = j / 2 if jj > 0: binary_array.append(j % 2) else: binary_array.append(1) j = jj return binary_array[::-1] def nb_of_ones(i): return binary(i).count(1) def rainbow_color(alpha): nb_colors = 100 rainbow = color_gradient([RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE], nb_colors) rainbow = np.append(rainbow, PURPLE) index = int(alpha * nb_colors) return rainbow[index] def graded_color(n, k): if n != 0: alpha = float(k) / n else: alpha = 0.5 color = interpolate_color(GRADE_COLOR_1, GRADE_COLOR_2, alpha) return color
21.658537
72
0.574324
from utils.color import * from active_projects.eop.reusables.eop_constants import * def binary(i): if i == 0: return [] j = i binary_array = [] while j > 0: jj = j / 2 if jj > 0: binary_array.append(j % 2) else: binary_array.append(1) j = jj return binary_array[::-1] def nb_of_ones(i): return binary(i).count(1) def rainbow_color(alpha): nb_colors = 100 rainbow = color_gradient([RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE], nb_colors) rainbow = np.append(rainbow, PURPLE) index = int(alpha * nb_colors) return rainbow[index] def graded_color(n, k): if n != 0: alpha = float(k) / n else: alpha = 0.5 color = interpolate_color(GRADE_COLOR_1, GRADE_COLOR_2, alpha) return color
true
true
f714837c409dd8d89eb62bb58f903782ce4acb43
5,005
py
Python
infomercial/exp/softmeta_bandit.py
CoAxLab/infomercial
fa5d1c1e5c1351735dda2961a2a94f71cd17e270
[ "MIT" ]
4
2019-11-14T03:13:25.000Z
2021-01-04T17:30:23.000Z
infomercial/exp/softmeta_bandit.py
CoAxLab/infomercial
fa5d1c1e5c1351735dda2961a2a94f71cd17e270
[ "MIT" ]
null
null
null
infomercial/exp/softmeta_bandit.py
CoAxLab/infomercial
fa5d1c1e5c1351735dda2961a2a94f71cd17e270
[ "MIT" ]
null
null
null
import os import fire import gym import numpy as np from scipy.special import softmax from noboard.csv import SummaryWriter from copy import deepcopy from scipy.stats import entropy from collections import OrderedDict from infomercial.distance import kl from infomercial.memory import DiscreteDistribution from infomercial.models import Critic from infomercial.models import SoftmaxActor from infomercial.utils import estimate_regret from infomercial.utils import load_checkpoint from infomercial.utils import save_checkpoint def R_update(state, reward, critic, lr): """Really simple TD learning""" update = lr * (reward - critic(state)) critic.update(state, update) return critic def E_update(state, value, critic, lr): """Bellman update""" update = lr * value critic.replace(state, update) return critic def R_homeostasis(reward, total_reward, set_point): """Update reward value assuming homeostatic value. Value based on Keramati and Gutkin, 2014. https://elifesciences.org/articles/04811 """ deviance_last = np.abs(set_point - total_reward) deviance = np.abs(set_point - (total_reward + reward)) reward_value = deviance_last - deviance return reward_value def run(env_name='BanditOneHot10-v0', num_episodes=1000, temp=1.0, tie_threshold=0.0, tie_break=None, lr_R=.1, master_seed=42, write_to_disk=True, log_dir=None): """Bandit agent - softmax (E, R)""" # --- Init --- writer = SummaryWriter(log_dir=log_dir, write_to_disk=write_to_disk) # - env = gym.make(env_name) env.seed(master_seed) num_actions = env.action_space.n all_actions = list(range(num_actions)) best_action = env.best default_reward_value = 0 default_info_value = entropy(np.ones(num_actions) / num_actions) E_t = default_info_value R_t = default_reward_value # --- Agents and memories --- critic_R = Critic(num_actions, default_value=default_reward_value) critic_E = Critic(num_actions, default_value=default_info_value) actor_R = SoftmaxActor(num_actions, temp=temp, seed_value=master_seed) actor_E = SoftmaxActor(num_actions, temp=temp, seed_value=master_seed) memories = [DiscreteDistribution() for _ in range(num_actions)] # - num_best = 0 total_R = 0.0 total_E = 0.0 total_regret = 0.0 # ------------------------------------------------------------------------ for n in range(num_episodes): env.reset() # Meta-greed policy selection if (E_t - tie_threshold) > R_t: critic = critic_E actor = actor_E policy = 0 else: critic = critic_R actor = actor_R policy = 1 # Choose an action; Choose a bandit action = actor(list(critic.model.values())) if action in best_action: num_best += 1 # Est. regret and save it regret = estimate_regret(all_actions, action, critic) # Pull a lever. state, R_t, _, _ = env.step(action) R_t = R_homeostasis(R_t, total_R, num_episodes) # Estimate E old = deepcopy(memories[action]) memories[action].update((int(state), int(R_t))) new = deepcopy(memories[action]) E_t = kl(new, old, default_info_value) # Learning, both policies. critic_R = R_update(action, R_t, critic_R, lr_R) critic_E = E_update(action, E_t, critic_E, lr=1) # Log data writer.add_scalar("policy", policy, n) writer.add_scalar("state", int(state), n) writer.add_scalar("action", action, n) writer.add_scalar("regret", regret, n) writer.add_scalar("score_E", E_t, n) writer.add_scalar("score_R", R_t, n) writer.add_scalar("value_E", critic_E(action), n) writer.add_scalar("value_R", critic_R(action), n) total_E += E_t total_R += R_t total_regret += regret writer.add_scalar("total_regret", total_regret, n) writer.add_scalar("total_E", total_E, n) writer.add_scalar("total_R", total_R, n) writer.add_scalar("p_bests", num_best / (n + 1), n) # -- Build the final result, and save or return it --- writer.close() result = dict(best=env.best, num_episodes=num_episodes, temp=temp, tie_threshold=tie_threshold, critic_E=critic_E.state_dict(), critic_R=critic_R.state_dict(), total_E=total_E, total_R=total_R, total_regret=total_regret, env_name=env_name, lr_R=lr_R, master_seed=master_seed) if write_to_disk: save_checkpoint(result, filename=os.path.join(writer.log_dir, "result.pkl")) return result if __name__ == "__main__": fire.Fire(run)
29.441176
78
0.624575
import os import fire import gym import numpy as np from scipy.special import softmax from noboard.csv import SummaryWriter from copy import deepcopy from scipy.stats import entropy from collections import OrderedDict from infomercial.distance import kl from infomercial.memory import DiscreteDistribution from infomercial.models import Critic from infomercial.models import SoftmaxActor from infomercial.utils import estimate_regret from infomercial.utils import load_checkpoint from infomercial.utils import save_checkpoint def R_update(state, reward, critic, lr): update = lr * (reward - critic(state)) critic.update(state, update) return critic def E_update(state, value, critic, lr): update = lr * value critic.replace(state, update) return critic def R_homeostasis(reward, total_reward, set_point): deviance_last = np.abs(set_point - total_reward) deviance = np.abs(set_point - (total_reward + reward)) reward_value = deviance_last - deviance return reward_value def run(env_name='BanditOneHot10-v0', num_episodes=1000, temp=1.0, tie_threshold=0.0, tie_break=None, lr_R=.1, master_seed=42, write_to_disk=True, log_dir=None): writer = SummaryWriter(log_dir=log_dir, write_to_disk=write_to_disk) env = gym.make(env_name) env.seed(master_seed) num_actions = env.action_space.n all_actions = list(range(num_actions)) best_action = env.best default_reward_value = 0 default_info_value = entropy(np.ones(num_actions) / num_actions) E_t = default_info_value R_t = default_reward_value critic_R = Critic(num_actions, default_value=default_reward_value) critic_E = Critic(num_actions, default_value=default_info_value) actor_R = SoftmaxActor(num_actions, temp=temp, seed_value=master_seed) actor_E = SoftmaxActor(num_actions, temp=temp, seed_value=master_seed) memories = [DiscreteDistribution() for _ in range(num_actions)] num_best = 0 total_R = 0.0 total_E = 0.0 total_regret = 0.0 for n in range(num_episodes): env.reset() if (E_t - tie_threshold) > R_t: critic = critic_E actor = actor_E policy = 0 else: critic = critic_R actor = actor_R policy = 1 action = actor(list(critic.model.values())) if action in best_action: num_best += 1 regret = estimate_regret(all_actions, action, critic) state, R_t, _, _ = env.step(action) R_t = R_homeostasis(R_t, total_R, num_episodes) old = deepcopy(memories[action]) memories[action].update((int(state), int(R_t))) new = deepcopy(memories[action]) E_t = kl(new, old, default_info_value) critic_R = R_update(action, R_t, critic_R, lr_R) critic_E = E_update(action, E_t, critic_E, lr=1) writer.add_scalar("policy", policy, n) writer.add_scalar("state", int(state), n) writer.add_scalar("action", action, n) writer.add_scalar("regret", regret, n) writer.add_scalar("score_E", E_t, n) writer.add_scalar("score_R", R_t, n) writer.add_scalar("value_E", critic_E(action), n) writer.add_scalar("value_R", critic_R(action), n) total_E += E_t total_R += R_t total_regret += regret writer.add_scalar("total_regret", total_regret, n) writer.add_scalar("total_E", total_E, n) writer.add_scalar("total_R", total_R, n) writer.add_scalar("p_bests", num_best / (n + 1), n) writer.close() result = dict(best=env.best, num_episodes=num_episodes, temp=temp, tie_threshold=tie_threshold, critic_E=critic_E.state_dict(), critic_R=critic_R.state_dict(), total_E=total_E, total_R=total_R, total_regret=total_regret, env_name=env_name, lr_R=lr_R, master_seed=master_seed) if write_to_disk: save_checkpoint(result, filename=os.path.join(writer.log_dir, "result.pkl")) return result if __name__ == "__main__": fire.Fire(run)
true
true
f71483e95b29a8c96562e9039fa444d6ed47f2af
680
py
Python
powerdnsadmin/default_config.py
hivelocity/PowerDNS-Admin
0c9ccf0a7e75817d77fcbfabba58ad2c66c04afa
[ "MIT" ]
null
null
null
powerdnsadmin/default_config.py
hivelocity/PowerDNS-Admin
0c9ccf0a7e75817d77fcbfabba58ad2c66c04afa
[ "MIT" ]
null
null
null
powerdnsadmin/default_config.py
hivelocity/PowerDNS-Admin
0c9ccf0a7e75817d77fcbfabba58ad2c66c04afa
[ "MIT" ]
null
null
null
import os basedir = os.path.abspath(os.path.abspath(os.path.dirname(__file__))) ### BASIC APP CONFIG SALT = '$2b$12$yLUMTIfl21FKJQpTkRQXCu' SECRET_KEY = 'e951e5a1f4b94151b360f47edf596dd2' BIND_ADDRESS = '0.0.0.0' PORT = 9191 HSTS_ENABLED = False ### DATABASE CONFIG SQLA_DB_USER = 'pdns' #SQLA_DB_PASSWORD = 'changeme' SQLA_DB_HOST = '10.42.42.204' SQLA_DB_NAME = 'pdns' SQLALCHEMY_TRACK_MODIFICATIONS = True ### DATBASE - MySQL #SQLALCHEMY_DATABASE_URI = 'mysql://'+SQLA_DB_USER+':'+SQLA_DB_PASSWORD+'@'+SQLA_DB_HOST+'/'+SQLA_DB_NAME ### DATABSE - SQLite # SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'pdns.db') # SAML Authnetication SAML_ENABLED = False
26.153846
105
0.744118
import os basedir = os.path.abspath(os.path.abspath(os.path.dirname(__file__))) u' SECRET_KEY = 'e951e5a1f4b94151b360f47edf596dd2' BIND_ADDRESS = '0.0.0.0' PORT = 9191 HSTS_ENABLED = False T = '10.42.42.204' SQLA_DB_NAME = 'pdns' SQLALCHEMY_TRACK_MODIFICATIONS = True
true
true
f714845eb007f7f56466665f162e3ab47ac7470a
23,375
py
Python
tests/test_chargen.py
jderam/hyperborea3
c9a7aced16793f501f9befae15a47b07a8451edc
[ "MIT" ]
2
2022-01-07T22:53:19.000Z
2022-02-01T07:46:13.000Z
tests/test_chargen.py
jderam/hyperborea-tools
c9a7aced16793f501f9befae15a47b07a8451edc
[ "MIT" ]
60
2021-12-29T04:57:27.000Z
2022-02-12T09:50:55.000Z
tests/test_chargen.py
jderam/hyperborea-tools
c9a7aced16793f501f9befae15a47b07a8451edc
[ "MIT" ]
null
null
null
import pytest from hyperborea3.chargen import ( DBPATH, ac_to_aac, calculate_ac, class_id_to_name, get_alignment, get_attr, get_attr_mod, get_caster_schools, get_class_id_map, get_class_level_data, get_combat_matrix, get_deity, get_favoured_weapons, get_gender, get_hd, get_level, get_qualifying_classes, get_race_id, get_random_familiar, get_random_spell, get_save_bonuses, get_spells, get_starting_armour, get_starting_gear, get_starting_money, get_starting_shield, get_starting_weapons_melee, get_starting_weapons_missile, get_thief_skills, get_turn_undead_matrix, get_unskilled_weapon_penalty, get_xp_to_next, list_tables, list_views, roll_hit_points, roll_stats, ) from hyperborea3.valid_data import ( VALID_ABILITY_SCORES, VALID_ABILITIES, VALID_ALIGMENTS_SHORT, VALID_CA, VALID_CLASS_ID_MAP, VALID_CLASS_IDS, VALID_DEITIES, VALID_DENOMINATIONS, VALID_DICE_METHODS, VALID_FA, VALID_FAMILIARS, VALID_FAVOURED_WEAPONS, VALID_GENDERS, VALID_GP, VALID_HD_PLUS, VALID_HD_QTY, VALID_HD_SIZE, VALID_LEVELS, VALID_RACE_IDS, VALID_SAVES, VALID_SCHOOLS, VALID_SCHOOLS_BY_CLASS_ID, VALID_SPELL_LEVELS, VALID_SQL_TABLES, VALID_SQL_VIEWS, VALID_TA, VALID_UNSKILLED_PENALTIES, ) def test_db(): assert DBPATH.is_file() @pytest.mark.skip( reason=( "Currently failing on github " "'sqlite3.OperationalError: no such table: sqlite_schema'" ) ) def test_db_tables(): assert list_tables() == VALID_SQL_TABLES @pytest.mark.skip( reason=( "Currently failing on github " "'sqlite3.OperationalError: no such table: sqlite_schema'" ) ) def test_db_views(): assert list_views() == VALID_SQL_VIEWS def test_xp_to_next(): # if character is already at max level, should return None level = 12 for class_id in VALID_CLASS_IDS: xp_to_next = get_xp_to_next(class_id, level) assert xp_to_next is None def test_roll_stats(): for class_id in VALID_CLASS_IDS: for i in range(100): attr = roll_stats(method=6, class_id=class_id) for stat in attr.keys(): assert stat in VALID_ABILITIES assert attr[stat]["score"] in VALID_ABILITY_SCORES for method in VALID_DICE_METHODS[:5]: for i in range(1000): attr = roll_stats(method=method) for stat in attr.keys(): assert stat in VALID_ABILITIES assert attr[stat]["score"] in VALID_ABILITY_SCORES def test_get_class_id_map(): class_id_map = get_class_id_map() assert class_id_map == VALID_CLASS_ID_MAP @pytest.mark.parametrize( "class_id,expected", [(k, v) for k, v in VALID_CLASS_ID_MAP.items()], ) def test_class_id_to_name(class_id: int, expected: str) -> None: class_name = class_id_to_name(class_id) assert class_name == expected def test_get_qualifying_classes(): subclasses = True for i in range(1000): attr = get_attr() qual_classes = get_qualifying_classes(attr, subclasses) for c in qual_classes: assert c in VALID_CLASS_IDS subclasses = False for i in range(1000): attr = get_attr() qual_classes = get_qualifying_classes(attr, subclasses) for c in qual_classes: assert c in range(1, 5) def test_get_level(): for class_id in VALID_CLASS_IDS: for xp in range(0, 1000000, 1000): level = get_level(class_id, xp) assert level in VALID_LEVELS def test_get_race_id(): for i in range(1000): race_id = get_race_id() assert race_id in VALID_RACE_IDS def test_get_gender(): for i in range(1000): gender = get_gender() assert gender in VALID_GENDERS def test_get_save_bonuses(): for class_id in VALID_CLASS_IDS: sv_bonus = get_save_bonuses(class_id) for k, v in sv_bonus.items(): assert v in [0, 2] # barbarians, berserkers, and paladins get +2 to all saves if class_id in [5, 6, 9, 27]: assert sum([v for v in sv_bonus.values()]) == 10 # all others get +2 to two saves else: assert sum([v for v in sv_bonus.values()]) == 4 def test_get_class_level_data(): for class_id in VALID_CLASS_IDS: for level in VALID_LEVELS: cl_data = get_class_level_data(class_id, level) assert cl_data["fa"] in VALID_FA assert cl_data["ca"] in VALID_CA assert cl_data["ta"] in VALID_TA assert cl_data["sv"] in VALID_SAVES def test_get_hd(): for class_id in VALID_CLASS_IDS: for level in VALID_LEVELS: hd = get_hd(class_id, level) qty = hd.split("d")[0] # number of dice in 1-9 assert int(qty) in VALID_HD_QTY part2 = hd.split("d")[1].split("+") assert len(part2) in [1, 2] # die size in d4, d6, d8, d10, d12 assert int(part2[0]) in VALID_HD_SIZE if len(part2) == 2: # +hp in 1,2,3; 2,4,6; 3,6,9; 4,8,12 assert int(part2[1]) in VALID_HD_PLUS def test_roll_hit_points(): max_possible_hp = (10 * 12) + (12 * 3) # Barbarian for class_id in VALID_CLASS_IDS: for level in VALID_LEVELS: for cn_score in VALID_ABILITY_SCORES: mods = get_attr_mod("cn", cn_score) hp_adj = mods["hp_adj"] hp = roll_hit_points(class_id, level, hp_adj) assert level <= hp <= max_possible_hp def test_get_combat_matrix(): for fa in VALID_FA: combat_matrix = get_combat_matrix(fa) assert list(combat_matrix.keys()) == list(range(-9, 10)) assert combat_matrix[0] == 20 - fa def test_starting_armour(): for class_id in VALID_CLASS_IDS: armour = get_starting_armour(class_id) assert list(armour.keys()) == [ "armour_id", "armour_type", "ac", "dr", "weight_class", "mv", "cost", "weight", "description", ] def test_starting_shield(): for class_id in VALID_CLASS_IDS: shield = get_starting_shield(class_id) if class_id in [1, 9, 27]: assert shield == { "shield_id": 2, "shield_type": "Large Shield", "def_mod": 2, "cost": 10, "weight": 10, } elif class_id in [5, 7, 24, 26, 31, 32, 33]: assert shield == { "shield_id": 1, "shield_type": "Small Shield", "def_mod": 1, "cost": 5, "weight": 5, } else: assert shield is None def test_starting_weapons_melee(): for class_id in VALID_CLASS_IDS: melee_weapons = get_starting_weapons_melee(class_id) assert 1 <= len(melee_weapons) <= 3 def test_starting_weapons_missile(): for class_id in VALID_CLASS_IDS: missile_weapons = get_starting_weapons_missile(class_id) if class_id == 8: assert len(missile_weapons) == 2 else: assert len(missile_weapons) in [0, 1] def test_unskilled_penalty(): for class_id in VALID_CLASS_IDS: assert ( get_unskilled_weapon_penalty(class_id) == VALID_UNSKILLED_PENALTIES[class_id] ) def test_get_favoured_weapons(): for class_id in VALID_CLASS_IDS: print(f"{class_id=}") favoured_weapons = get_favoured_weapons(class_id) actual_melee_wpn_ids = [ x["weapon_id"] for x in favoured_weapons["weapons_melee"] ] actual_missile_wpn_ids = [ x["weapon_id"] for x in favoured_weapons["weapons_missile"] ] expected = VALID_FAVOURED_WEAPONS[class_id] assert favoured_weapons["any"] == expected["any"] assert actual_melee_wpn_ids == expected["melee_wpns"] assert actual_missile_wpn_ids == expected["missile_wpns"] assert favoured_weapons["unskilled_penalty"] == expected["unskilled_penalty"] def test_get_starting_gear(): for class_id in VALID_CLASS_IDS: equip = get_starting_gear(class_id) assert len(equip) > 0 for item in equip: assert isinstance(item, str) def test_get_starting_money(): for i in range(100): money = get_starting_money() assert list(money.keys()) == VALID_DENOMINATIONS for k in VALID_DENOMINATIONS: if k == "gp": assert money[k] in VALID_GP else: assert money[k] == 0 def test_calculate_ac(): for class_id in VALID_CLASS_IDS: armour = get_starting_armour(class_id) shield = get_starting_shield(class_id) shield_def_mod = shield["def_mod"] if shield is not None else 0 for dx_score in VALID_ABILITY_SCORES: dx_mod = get_attr_mod("dx", dx_score) ac = calculate_ac( armour["ac"], shield_def_mod, dx_mod["def_adj"], ) # all AC values for starting characters should be 1 to 11 (level 1) # This may need updating after we include higher-level PCs, # depending on if they have any abilities that improve AC assert ac in range( 1, 12 ), f"""invalid ac: class_id = {class_id} armour_ac = {armour["ac"]} shield_def_mod = {shield_def_mod} dx_score = {dx_score} dx_def_adj = {dx_mod["def_adj"]} ac = {ac} """ def test_ac_to_aac(): for ac in range(-10, 20): aac = ac_to_aac(ac) assert ac + aac == 19 def test_get_alignment(): for class_id in VALID_CLASS_IDS: alignment = get_alignment(class_id) if class_id in [1, 2, 3, 7, 8, 11, 13, 18, 19]: allowed_alignments = ["CE", "CG", "LE", "LG", "N"] elif class_id in [4, 24, 25, 26, 31]: allowed_alignments = ["CE", "CG", "LE", "N"] elif class_id == 10: allowed_alignments = ["CG", "LG", "N"] elif class_id in [14, 22, 30]: allowed_alignments = ["CE", "LE", "N"] elif class_id in [15, 16, 21, 23, 29, 32]: allowed_alignments = ["CE", "CG", "N"] elif class_id in [12, 28]: allowed_alignments = ["LE", "LG", "N"] elif class_id in [5, 6, 20]: allowed_alignments = ["CE", "CG"] elif class_id == 33: allowed_alignments = ["LE", "N"] elif class_id == 9: allowed_alignments = ["LG"] elif class_id == 27: allowed_alignments = ["LE"] elif class_id == 17: allowed_alignments = ["N"] else: raise ValueError(f"Unexpected class_id: {class_id}") assert ( alignment["short_name"] in allowed_alignments ), f""" Unexpected alignment '{alignment}' not in allowed values {allowed_alignments} """ @pytest.mark.repeat(20) def test_get_deity(): for short_align in VALID_ALIGMENTS_SHORT: deity = get_deity(short_align) assert deity["deity_name"] in VALID_DEITIES def test_get_thief_skills(): # classes without thief skills for class_id in [ 1, 2, 3, 7, 9, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 27, 28, 29, 30, ]: thief_skills = get_thief_skills(class_id, 1, 10, 10, 10) assert ( thief_skills is None ), f"class_id: {class_id} is not supposed to have thief skills" # level 1 thief with 10's expected_thief_skills = [ {"thief_skill": "climb", "skill_name": "Climb", "skill_roll": 8, "stat": "dx"}, { "thief_skill": "decipher_script", "skill_name": "Decipher Script", "skill_roll": 0, "stat": "in", }, { "thief_skill": "discern_noise", "skill_name": "Discern Noise", "skill_roll": 4, "stat": "ws", }, {"thief_skill": "hide", "skill_name": "Hide", "skill_roll": 5, "stat": "dx"}, { "thief_skill": "manipulate_traps", "skill_name": "Manipulate Traps", "skill_roll": 3, "stat": "dx", }, { "thief_skill": "move_silently", "skill_name": "Move Silently", "skill_roll": 5, "stat": "dx", }, { "thief_skill": "open_locks", "skill_name": "Open Locks", "skill_roll": 3, "stat": "dx", }, { "thief_skill": "pick_pockets", "skill_name": "Pick Pockets", "skill_roll": 4, "stat": "dx", }, { "thief_skill": "read_scrolls", "skill_name": "Read Scrolls", "skill_roll": None, "stat": "in", }, ] thief_skills = get_thief_skills(4, 1, 10, 10, 10) assert thief_skills == expected_thief_skills # level 1 thief with 16's expected_thief_skills = [ {"thief_skill": "climb", "skill_name": "Climb", "skill_roll": 9, "stat": "dx"}, { "thief_skill": "decipher_script", "skill_name": "Decipher Script", "skill_roll": 1, "stat": "in", }, { "thief_skill": "discern_noise", "skill_name": "Discern Noise", "skill_roll": 5, "stat": "ws", }, {"thief_skill": "hide", "skill_name": "Hide", "skill_roll": 6, "stat": "dx"}, { "thief_skill": "manipulate_traps", "skill_name": "Manipulate Traps", "skill_roll": 4, "stat": "dx", }, { "thief_skill": "move_silently", "skill_name": "Move Silently", "skill_roll": 6, "stat": "dx", }, { "thief_skill": "open_locks", "skill_name": "Open Locks", "skill_roll": 4, "stat": "dx", }, { "thief_skill": "pick_pockets", "skill_name": "Pick Pockets", "skill_roll": 5, "stat": "dx", }, { "thief_skill": "read_scrolls", "skill_name": "Read Scrolls", "skill_roll": None, "stat": "in", }, ] thief_skills = get_thief_skills(4, 1, 16, 16, 16) assert thief_skills == expected_thief_skills # level 12 thief with 10's expected_thief_skills = [ {"thief_skill": "climb", "skill_name": "Climb", "skill_roll": 10, "stat": "dx"}, { "thief_skill": "decipher_script", "skill_name": "Decipher Script", "skill_roll": 5, "stat": "in", }, { "thief_skill": "discern_noise", "skill_name": "Discern Noise", "skill_roll": 9, "stat": "ws", }, {"thief_skill": "hide", "skill_name": "Hide", "skill_roll": 10, "stat": "dx"}, { "thief_skill": "manipulate_traps", "skill_name": "Manipulate Traps", "skill_roll": 8, "stat": "dx", }, { "thief_skill": "move_silently", "skill_name": "Move Silently", "skill_roll": 10, "stat": "dx", }, { "thief_skill": "open_locks", "skill_name": "Open Locks", "skill_roll": 8, "stat": "dx", }, { "thief_skill": "pick_pockets", "skill_name": "Pick Pockets", "skill_roll": 9, "stat": "dx", }, { "thief_skill": "read_scrolls", "skill_name": "Read Scrolls", "skill_roll": 5, "stat": "in", }, ] thief_skills = get_thief_skills(4, 12, 10, 10, 10) assert thief_skills == expected_thief_skills # level 12 thief with 16's expected_thief_skills = [ {"thief_skill": "climb", "skill_name": "Climb", "skill_roll": 11, "stat": "dx"}, { "thief_skill": "decipher_script", "skill_name": "Decipher Script", "skill_roll": 6, "stat": "in", }, { "thief_skill": "discern_noise", "skill_name": "Discern Noise", "skill_roll": 10, "stat": "ws", }, {"thief_skill": "hide", "skill_name": "Hide", "skill_roll": 11, "stat": "dx"}, { "thief_skill": "manipulate_traps", "skill_name": "Manipulate Traps", "skill_roll": 9, "stat": "dx", }, { "thief_skill": "move_silently", "skill_name": "Move Silently", "skill_roll": 11, "stat": "dx", }, { "thief_skill": "open_locks", "skill_name": "Open Locks", "skill_roll": 9, "stat": "dx", }, { "thief_skill": "pick_pockets", "skill_name": "Pick Pockets", "skill_roll": 10, "stat": "dx", }, { "thief_skill": "read_scrolls", "skill_name": "Read Scrolls", "skill_roll": 6, "stat": "in", }, ] thief_skills = get_thief_skills(4, 12, 16, 16, 16) assert thief_skills == expected_thief_skills def test_get_caster_schools(): for class_id in VALID_CLASS_IDS: schools = get_caster_schools(class_id) if class_id == 21: assert schools in [ ["clr", "mag"], ["clr", "nec"], ["drd", "mag"], ["drd", "nec"], ] else: assert schools == VALID_SCHOOLS_BY_CLASS_ID[class_id] def test_get_turn_undead_matrix(): for ta in VALID_TA: for turn_adj in [-1, 0, 1]: turn_undead_matrix = get_turn_undead_matrix(ta, turn_adj) if ta == 0: assert turn_undead_matrix is None if ta == 1 and turn_adj == -1: assert turn_undead_matrix == { "undead_type_00": "9:12", "undead_type_01": "6:12", "undead_type_02": "3:12", "undead_type_03": "NT", "undead_type_04": "NT", "undead_type_05": "NT", "undead_type_06": "NT", "undead_type_07": "NT", "undead_type_08": "NT", "undead_type_09": "NT", "undead_type_10": "NT", "undead_type_11": "NT", "undead_type_12": "NT", "undead_type_13": "NT", } if ta == 1 and turn_adj == 0: assert turn_undead_matrix == { "undead_type_00": "10:12", "undead_type_01": "7:12", "undead_type_02": "4:12", "undead_type_03": "1:12", "undead_type_04": "NT", "undead_type_05": "NT", "undead_type_06": "NT", "undead_type_07": "NT", "undead_type_08": "NT", "undead_type_09": "NT", "undead_type_10": "NT", "undead_type_11": "NT", "undead_type_12": "NT", "undead_type_13": "NT", } if ta == 12 and turn_adj == 0: assert turn_undead_matrix == { "undead_type_00": "UD", "undead_type_01": "UD", "undead_type_02": "UD", "undead_type_03": "UD", "undead_type_04": "UD", "undead_type_05": "UD", "undead_type_06": "D", "undead_type_07": "D", "undead_type_08": "D", "undead_type_09": "T", "undead_type_10": "T", "undead_type_11": "10:12", "undead_type_12": "7:12", "undead_type_13": "4:12", } if ta == 12 and turn_adj == 1: assert turn_undead_matrix == { "undead_type_00": "UD", "undead_type_01": "UD", "undead_type_02": "UD", "undead_type_03": "UD", "undead_type_04": "UD", "undead_type_05": "UD", "undead_type_06": "D", "undead_type_07": "D", "undead_type_08": "D", "undead_type_09": "T", "undead_type_10": "T", "undead_type_11": "11:12", "undead_type_12": "8:12", "undead_type_13": "5:12", } def test_spell_data(): for school in VALID_SCHOOLS: for spell_level in VALID_SPELL_LEVELS: for d100_roll in range(1, 101): spell = get_random_spell(school, spell_level, d100_roll) assert spell is not None def test_get_random_spell(): for school in VALID_SCHOOLS: for spell_level in VALID_SPELL_LEVELS: for i in range(1000): spell = get_random_spell(school, spell_level) assert spell["school"] == school assert spell["spell_level"] == spell_level assert spell["reversible"] in [None, True, False] def test_get_spells(): for class_id in VALID_CLASS_IDS: for level in VALID_LEVELS: cl_data = get_class_level_data(class_id, level) ca = cl_data["ca"] spells = get_spells(class_id, level, ca) if ca > 0: assert spells, f"{class_id=} {level=} {spells=}" schools = list(spells.keys()) else: schools = [] if ca > 1 and class_id != 21: assert schools == VALID_SCHOOLS_BY_CLASS_ID[class_id] elif class_id == 21: assert schools in [ ["clr", "mag"], ["clr", "nec"], ["drd", "mag"], ["drd", "nec"], ] # classes without spells if ca == 0: assert spells is None, f"{class_id=} {level=}" # classes with no spells at early levels def test_get_random_familiar(): for i in range(1000): animal = get_random_familiar() assert animal in VALID_FAMILIARS, f"{animal=} not in {VALID_FAMILIARS}"
30.47588
88
0.515722
import pytest from hyperborea3.chargen import ( DBPATH, ac_to_aac, calculate_ac, class_id_to_name, get_alignment, get_attr, get_attr_mod, get_caster_schools, get_class_id_map, get_class_level_data, get_combat_matrix, get_deity, get_favoured_weapons, get_gender, get_hd, get_level, get_qualifying_classes, get_race_id, get_random_familiar, get_random_spell, get_save_bonuses, get_spells, get_starting_armour, get_starting_gear, get_starting_money, get_starting_shield, get_starting_weapons_melee, get_starting_weapons_missile, get_thief_skills, get_turn_undead_matrix, get_unskilled_weapon_penalty, get_xp_to_next, list_tables, list_views, roll_hit_points, roll_stats, ) from hyperborea3.valid_data import ( VALID_ABILITY_SCORES, VALID_ABILITIES, VALID_ALIGMENTS_SHORT, VALID_CA, VALID_CLASS_ID_MAP, VALID_CLASS_IDS, VALID_DEITIES, VALID_DENOMINATIONS, VALID_DICE_METHODS, VALID_FA, VALID_FAMILIARS, VALID_FAVOURED_WEAPONS, VALID_GENDERS, VALID_GP, VALID_HD_PLUS, VALID_HD_QTY, VALID_HD_SIZE, VALID_LEVELS, VALID_RACE_IDS, VALID_SAVES, VALID_SCHOOLS, VALID_SCHOOLS_BY_CLASS_ID, VALID_SPELL_LEVELS, VALID_SQL_TABLES, VALID_SQL_VIEWS, VALID_TA, VALID_UNSKILLED_PENALTIES, ) def test_db(): assert DBPATH.is_file() @pytest.mark.skip( reason=( "Currently failing on github " "'sqlite3.OperationalError: no such table: sqlite_schema'" ) ) def test_db_tables(): assert list_tables() == VALID_SQL_TABLES @pytest.mark.skip( reason=( "Currently failing on github " "'sqlite3.OperationalError: no such table: sqlite_schema'" ) ) def test_db_views(): assert list_views() == VALID_SQL_VIEWS def test_xp_to_next(): level = 12 for class_id in VALID_CLASS_IDS: xp_to_next = get_xp_to_next(class_id, level) assert xp_to_next is None def test_roll_stats(): for class_id in VALID_CLASS_IDS: for i in range(100): attr = roll_stats(method=6, class_id=class_id) for stat in attr.keys(): assert stat in VALID_ABILITIES assert attr[stat]["score"] in VALID_ABILITY_SCORES for method in VALID_DICE_METHODS[:5]: for i in range(1000): attr = roll_stats(method=method) for stat in attr.keys(): assert stat in VALID_ABILITIES assert attr[stat]["score"] in VALID_ABILITY_SCORES def test_get_class_id_map(): class_id_map = get_class_id_map() assert class_id_map == VALID_CLASS_ID_MAP @pytest.mark.parametrize( "class_id,expected", [(k, v) for k, v in VALID_CLASS_ID_MAP.items()], ) def test_class_id_to_name(class_id: int, expected: str) -> None: class_name = class_id_to_name(class_id) assert class_name == expected def test_get_qualifying_classes(): subclasses = True for i in range(1000): attr = get_attr() qual_classes = get_qualifying_classes(attr, subclasses) for c in qual_classes: assert c in VALID_CLASS_IDS subclasses = False for i in range(1000): attr = get_attr() qual_classes = get_qualifying_classes(attr, subclasses) for c in qual_classes: assert c in range(1, 5) def test_get_level(): for class_id in VALID_CLASS_IDS: for xp in range(0, 1000000, 1000): level = get_level(class_id, xp) assert level in VALID_LEVELS def test_get_race_id(): for i in range(1000): race_id = get_race_id() assert race_id in VALID_RACE_IDS def test_get_gender(): for i in range(1000): gender = get_gender() assert gender in VALID_GENDERS def test_get_save_bonuses(): for class_id in VALID_CLASS_IDS: sv_bonus = get_save_bonuses(class_id) for k, v in sv_bonus.items(): assert v in [0, 2] if class_id in [5, 6, 9, 27]: assert sum([v for v in sv_bonus.values()]) == 10 else: assert sum([v for v in sv_bonus.values()]) == 4 def test_get_class_level_data(): for class_id in VALID_CLASS_IDS: for level in VALID_LEVELS: cl_data = get_class_level_data(class_id, level) assert cl_data["fa"] in VALID_FA assert cl_data["ca"] in VALID_CA assert cl_data["ta"] in VALID_TA assert cl_data["sv"] in VALID_SAVES def test_get_hd(): for class_id in VALID_CLASS_IDS: for level in VALID_LEVELS: hd = get_hd(class_id, level) qty = hd.split("d")[0] assert int(qty) in VALID_HD_QTY part2 = hd.split("d")[1].split("+") assert len(part2) in [1, 2] assert int(part2[0]) in VALID_HD_SIZE if len(part2) == 2: assert int(part2[1]) in VALID_HD_PLUS def test_roll_hit_points(): max_possible_hp = (10 * 12) + (12 * 3) for class_id in VALID_CLASS_IDS: for level in VALID_LEVELS: for cn_score in VALID_ABILITY_SCORES: mods = get_attr_mod("cn", cn_score) hp_adj = mods["hp_adj"] hp = roll_hit_points(class_id, level, hp_adj) assert level <= hp <= max_possible_hp def test_get_combat_matrix(): for fa in VALID_FA: combat_matrix = get_combat_matrix(fa) assert list(combat_matrix.keys()) == list(range(-9, 10)) assert combat_matrix[0] == 20 - fa def test_starting_armour(): for class_id in VALID_CLASS_IDS: armour = get_starting_armour(class_id) assert list(armour.keys()) == [ "armour_id", "armour_type", "ac", "dr", "weight_class", "mv", "cost", "weight", "description", ] def test_starting_shield(): for class_id in VALID_CLASS_IDS: shield = get_starting_shield(class_id) if class_id in [1, 9, 27]: assert shield == { "shield_id": 2, "shield_type": "Large Shield", "def_mod": 2, "cost": 10, "weight": 10, } elif class_id in [5, 7, 24, 26, 31, 32, 33]: assert shield == { "shield_id": 1, "shield_type": "Small Shield", "def_mod": 1, "cost": 5, "weight": 5, } else: assert shield is None def test_starting_weapons_melee(): for class_id in VALID_CLASS_IDS: melee_weapons = get_starting_weapons_melee(class_id) assert 1 <= len(melee_weapons) <= 3 def test_starting_weapons_missile(): for class_id in VALID_CLASS_IDS: missile_weapons = get_starting_weapons_missile(class_id) if class_id == 8: assert len(missile_weapons) == 2 else: assert len(missile_weapons) in [0, 1] def test_unskilled_penalty(): for class_id in VALID_CLASS_IDS: assert ( get_unskilled_weapon_penalty(class_id) == VALID_UNSKILLED_PENALTIES[class_id] ) def test_get_favoured_weapons(): for class_id in VALID_CLASS_IDS: print(f"{class_id=}") favoured_weapons = get_favoured_weapons(class_id) actual_melee_wpn_ids = [ x["weapon_id"] for x in favoured_weapons["weapons_melee"] ] actual_missile_wpn_ids = [ x["weapon_id"] for x in favoured_weapons["weapons_missile"] ] expected = VALID_FAVOURED_WEAPONS[class_id] assert favoured_weapons["any"] == expected["any"] assert actual_melee_wpn_ids == expected["melee_wpns"] assert actual_missile_wpn_ids == expected["missile_wpns"] assert favoured_weapons["unskilled_penalty"] == expected["unskilled_penalty"] def test_get_starting_gear(): for class_id in VALID_CLASS_IDS: equip = get_starting_gear(class_id) assert len(equip) > 0 for item in equip: assert isinstance(item, str) def test_get_starting_money(): for i in range(100): money = get_starting_money() assert list(money.keys()) == VALID_DENOMINATIONS for k in VALID_DENOMINATIONS: if k == "gp": assert money[k] in VALID_GP else: assert money[k] == 0 def test_calculate_ac(): for class_id in VALID_CLASS_IDS: armour = get_starting_armour(class_id) shield = get_starting_shield(class_id) shield_def_mod = shield["def_mod"] if shield is not None else 0 for dx_score in VALID_ABILITY_SCORES: dx_mod = get_attr_mod("dx", dx_score) ac = calculate_ac( armour["ac"], shield_def_mod, dx_mod["def_adj"], ) assert ac in range( 1, 12 ), f"""invalid ac: class_id = {class_id} armour_ac = {armour["ac"]} shield_def_mod = {shield_def_mod} dx_score = {dx_score} dx_def_adj = {dx_mod["def_adj"]} ac = {ac} """ def test_ac_to_aac(): for ac in range(-10, 20): aac = ac_to_aac(ac) assert ac + aac == 19 def test_get_alignment(): for class_id in VALID_CLASS_IDS: alignment = get_alignment(class_id) if class_id in [1, 2, 3, 7, 8, 11, 13, 18, 19]: allowed_alignments = ["CE", "CG", "LE", "LG", "N"] elif class_id in [4, 24, 25, 26, 31]: allowed_alignments = ["CE", "CG", "LE", "N"] elif class_id == 10: allowed_alignments = ["CG", "LG", "N"] elif class_id in [14, 22, 30]: allowed_alignments = ["CE", "LE", "N"] elif class_id in [15, 16, 21, 23, 29, 32]: allowed_alignments = ["CE", "CG", "N"] elif class_id in [12, 28]: allowed_alignments = ["LE", "LG", "N"] elif class_id in [5, 6, 20]: allowed_alignments = ["CE", "CG"] elif class_id == 33: allowed_alignments = ["LE", "N"] elif class_id == 9: allowed_alignments = ["LG"] elif class_id == 27: allowed_alignments = ["LE"] elif class_id == 17: allowed_alignments = ["N"] else: raise ValueError(f"Unexpected class_id: {class_id}") assert ( alignment["short_name"] in allowed_alignments ), f""" Unexpected alignment '{alignment}' not in allowed values {allowed_alignments} """ @pytest.mark.repeat(20) def test_get_deity(): for short_align in VALID_ALIGMENTS_SHORT: deity = get_deity(short_align) assert deity["deity_name"] in VALID_DEITIES def test_get_thief_skills(): for class_id in [ 1, 2, 3, 7, 9, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 27, 28, 29, 30, ]: thief_skills = get_thief_skills(class_id, 1, 10, 10, 10) assert ( thief_skills is None ), f"class_id: {class_id} is not supposed to have thief skills" expected_thief_skills = [ {"thief_skill": "climb", "skill_name": "Climb", "skill_roll": 8, "stat": "dx"}, { "thief_skill": "decipher_script", "skill_name": "Decipher Script", "skill_roll": 0, "stat": "in", }, { "thief_skill": "discern_noise", "skill_name": "Discern Noise", "skill_roll": 4, "stat": "ws", }, {"thief_skill": "hide", "skill_name": "Hide", "skill_roll": 5, "stat": "dx"}, { "thief_skill": "manipulate_traps", "skill_name": "Manipulate Traps", "skill_roll": 3, "stat": "dx", }, { "thief_skill": "move_silently", "skill_name": "Move Silently", "skill_roll": 5, "stat": "dx", }, { "thief_skill": "open_locks", "skill_name": "Open Locks", "skill_roll": 3, "stat": "dx", }, { "thief_skill": "pick_pockets", "skill_name": "Pick Pockets", "skill_roll": 4, "stat": "dx", }, { "thief_skill": "read_scrolls", "skill_name": "Read Scrolls", "skill_roll": None, "stat": "in", }, ] thief_skills = get_thief_skills(4, 1, 10, 10, 10) assert thief_skills == expected_thief_skills # level 1 thief with 16's expected_thief_skills = [ {"thief_skill": "climb", "skill_name": "Climb", "skill_roll": 9, "stat": "dx"}, { "thief_skill": "decipher_script", "skill_name": "Decipher Script", "skill_roll": 1, "stat": "in", }, { "thief_skill": "discern_noise", "skill_name": "Discern Noise", "skill_roll": 5, "stat": "ws", }, {"thief_skill": "hide", "skill_name": "Hide", "skill_roll": 6, "stat": "dx"}, { "thief_skill": "manipulate_traps", "skill_name": "Manipulate Traps", "skill_roll": 4, "stat": "dx", }, { "thief_skill": "move_silently", "skill_name": "Move Silently", "skill_roll": 6, "stat": "dx", }, { "thief_skill": "open_locks", "skill_name": "Open Locks", "skill_roll": 4, "stat": "dx", }, { "thief_skill": "pick_pockets", "skill_name": "Pick Pockets", "skill_roll": 5, "stat": "dx", }, { "thief_skill": "read_scrolls", "skill_name": "Read Scrolls", "skill_roll": None, "stat": "in", }, ] thief_skills = get_thief_skills(4, 1, 16, 16, 16) assert thief_skills == expected_thief_skills expected_thief_skills = [ {"thief_skill": "climb", "skill_name": "Climb", "skill_roll": 10, "stat": "dx"}, { "thief_skill": "decipher_script", "skill_name": "Decipher Script", "skill_roll": 5, "stat": "in", }, { "thief_skill": "discern_noise", "skill_name": "Discern Noise", "skill_roll": 9, "stat": "ws", }, {"thief_skill": "hide", "skill_name": "Hide", "skill_roll": 10, "stat": "dx"}, { "thief_skill": "manipulate_traps", "skill_name": "Manipulate Traps", "skill_roll": 8, "stat": "dx", }, { "thief_skill": "move_silently", "skill_name": "Move Silently", "skill_roll": 10, "stat": "dx", }, { "thief_skill": "open_locks", "skill_name": "Open Locks", "skill_roll": 8, "stat": "dx", }, { "thief_skill": "pick_pockets", "skill_name": "Pick Pockets", "skill_roll": 9, "stat": "dx", }, { "thief_skill": "read_scrolls", "skill_name": "Read Scrolls", "skill_roll": 5, "stat": "in", }, ] thief_skills = get_thief_skills(4, 12, 10, 10, 10) assert thief_skills == expected_thief_skills # level 12 thief with 16's expected_thief_skills = [ {"thief_skill": "climb", "skill_name": "Climb", "skill_roll": 11, "stat": "dx"}, { "thief_skill": "decipher_script", "skill_name": "Decipher Script", "skill_roll": 6, "stat": "in", }, { "thief_skill": "discern_noise", "skill_name": "Discern Noise", "skill_roll": 10, "stat": "ws", }, {"thief_skill": "hide", "skill_name": "Hide", "skill_roll": 11, "stat": "dx"}, { "thief_skill": "manipulate_traps", "skill_name": "Manipulate Traps", "skill_roll": 9, "stat": "dx", }, { "thief_skill": "move_silently", "skill_name": "Move Silently", "skill_roll": 11, "stat": "dx", }, { "thief_skill": "open_locks", "skill_name": "Open Locks", "skill_roll": 9, "stat": "dx", }, { "thief_skill": "pick_pockets", "skill_name": "Pick Pockets", "skill_roll": 10, "stat": "dx", }, { "thief_skill": "read_scrolls", "skill_name": "Read Scrolls", "skill_roll": 6, "stat": "in", }, ] thief_skills = get_thief_skills(4, 12, 16, 16, 16) assert thief_skills == expected_thief_skills def test_get_caster_schools(): for class_id in VALID_CLASS_IDS: schools = get_caster_schools(class_id) if class_id == 21: assert schools in [ ["clr", "mag"], ["clr", "nec"], ["drd", "mag"], ["drd", "nec"], ] else: assert schools == VALID_SCHOOLS_BY_CLASS_ID[class_id] def test_get_turn_undead_matrix(): for ta in VALID_TA: for turn_adj in [-1, 0, 1]: turn_undead_matrix = get_turn_undead_matrix(ta, turn_adj) if ta == 0: assert turn_undead_matrix is None if ta == 1 and turn_adj == -1: assert turn_undead_matrix == { "undead_type_00": "9:12", "undead_type_01": "6:12", "undead_type_02": "3:12", "undead_type_03": "NT", "undead_type_04": "NT", "undead_type_05": "NT", "undead_type_06": "NT", "undead_type_07": "NT", "undead_type_08": "NT", "undead_type_09": "NT", "undead_type_10": "NT", "undead_type_11": "NT", "undead_type_12": "NT", "undead_type_13": "NT", } if ta == 1 and turn_adj == 0: assert turn_undead_matrix == { "undead_type_00": "10:12", "undead_type_01": "7:12", "undead_type_02": "4:12", "undead_type_03": "1:12", "undead_type_04": "NT", "undead_type_05": "NT", "undead_type_06": "NT", "undead_type_07": "NT", "undead_type_08": "NT", "undead_type_09": "NT", "undead_type_10": "NT", "undead_type_11": "NT", "undead_type_12": "NT", "undead_type_13": "NT", } if ta == 12 and turn_adj == 0: assert turn_undead_matrix == { "undead_type_00": "UD", "undead_type_01": "UD", "undead_type_02": "UD", "undead_type_03": "UD", "undead_type_04": "UD", "undead_type_05": "UD", "undead_type_06": "D", "undead_type_07": "D", "undead_type_08": "D", "undead_type_09": "T", "undead_type_10": "T", "undead_type_11": "10:12", "undead_type_12": "7:12", "undead_type_13": "4:12", } if ta == 12 and turn_adj == 1: assert turn_undead_matrix == { "undead_type_00": "UD", "undead_type_01": "UD", "undead_type_02": "UD", "undead_type_03": "UD", "undead_type_04": "UD", "undead_type_05": "UD", "undead_type_06": "D", "undead_type_07": "D", "undead_type_08": "D", "undead_type_09": "T", "undead_type_10": "T", "undead_type_11": "11:12", "undead_type_12": "8:12", "undead_type_13": "5:12", } def test_spell_data(): for school in VALID_SCHOOLS: for spell_level in VALID_SPELL_LEVELS: for d100_roll in range(1, 101): spell = get_random_spell(school, spell_level, d100_roll) assert spell is not None def test_get_random_spell(): for school in VALID_SCHOOLS: for spell_level in VALID_SPELL_LEVELS: for i in range(1000): spell = get_random_spell(school, spell_level) assert spell["school"] == school assert spell["spell_level"] == spell_level assert spell["reversible"] in [None, True, False] def test_get_spells(): for class_id in VALID_CLASS_IDS: for level in VALID_LEVELS: cl_data = get_class_level_data(class_id, level) ca = cl_data["ca"] spells = get_spells(class_id, level, ca) if ca > 0: assert spells, f"{class_id=} {level=} {spells=}" schools = list(spells.keys()) else: schools = [] if ca > 1 and class_id != 21: assert schools == VALID_SCHOOLS_BY_CLASS_ID[class_id] elif class_id == 21: assert schools in [ ["clr", "mag"], ["clr", "nec"], ["drd", "mag"], ["drd", "nec"], ] if ca == 0: assert spells is None, f"{class_id=} {level=}" def test_get_random_familiar(): for i in range(1000): animal = get_random_familiar() assert animal in VALID_FAMILIARS, f"{animal=} not in {VALID_FAMILIARS}"
true
true
f71484d9b44030ff88de3d344a897e3b616df745
3,140
py
Python
4_forthproject/forthproject/settings.py
merry-hyelyn/LIKE_LION
26d6642a88d5c075447c60d43a70a7d0f082fb07
[ "MIT" ]
null
null
null
4_forthproject/forthproject/settings.py
merry-hyelyn/LIKE_LION
26d6642a88d5c075447c60d43a70a7d0f082fb07
[ "MIT" ]
null
null
null
4_forthproject/forthproject/settings.py
merry-hyelyn/LIKE_LION
26d6642a88d5c075447c60d43a70a7d0f082fb07
[ "MIT" ]
null
null
null
""" Django settings for forthproject project. Generated by 'django-admin startproject' using Django 2.1.8. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '8sjx*ixqizq%)vswdwn82p(w8en&cknd@dey%8h7ex@e&bqx_4' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'student.apps.StudentConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'forthproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'forthproject.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'
25.737705
91
0.698726
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '8sjx*ixqizq%)vswdwn82p(w8en&cknd@dey%8h7ex@e&bqx_4' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'student.apps.StudentConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'forthproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'forthproject.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/'
true
true
f71485e72b788fa273c442546c715e7aa086321c
8,018
py
Python
gasex/diff.py
dnicholson/gasex-python
53b8c3ff4e64e724d8883bdef299d465621b124f
[ "MIT" ]
1
2019-04-06T17:52:30.000Z
2019-04-06T17:52:30.000Z
gasex/diff.py
dnicholson/gasex-python
53b8c3ff4e64e724d8883bdef299d465621b124f
[ "MIT" ]
null
null
null
gasex/diff.py
dnicholson/gasex-python
53b8c3ff4e64e724d8883bdef299d465621b124f
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ % Diffusion coeff and Schmidt number for gases in fresh/sea water %========================================================================= % Modified by D. Nicholson from MATLAB gas_diffusion Version 2.0 16 July 2013 % Author: Roberta C. Hamme (University of Victoria) % Diffusion values for 'He','Ne','Ar','Kr','Xe','N2','O2','CH4','N2' and 'CO2' are calculated from % gas_diffusion Version 2.0 functions % salinity correction is of the form: D = D0 * (1 - 0.049 * SP / 35.5) % % % Support for additional gases ('CO2','N2O','CH4','RN','SF6','DMS','CFC12','CFC11','CH3BR','CCL4') % has been added based on Wanninkhof 2014 % % Table 1: % Sc = A + Bt + Ct2+ dt3+ Et4(t in °C). The last column is the calculated Schmidt number for 20°C. % The Schmidt number is the kinematic viscosity of waterdivided by the molecular diffusion % coefficient of the gas. The kinematic viscosity for fresh water and seawater are from % Sharqawy et al. (2010). The dif-fusion coefficients of gases are from the following: % 3He, He, Ne, Kr, Xe, CH4, CO2, and Rn measured by Jähne et al. (1987); Ar, O2, N2, N2O, % and CCl4fitusing Wilke and Chang (1955) as adapted by Hayduk and Laudie (1974); SF6 % measured by King and Saltzman (1995); DMS measured by Saltzman etal. (1993); CFC-11 and % CFC-12 measured by Zheng et al. (1998); CH3Br measured by De Bruyn and Saltzman (1997a). % % % REFERENCE: % He, Ne, Kr, Xe, CH4, CO2, H2 freshwater values from Jahne et al., 1987. % "Measurement of Diffusion Coeffients of Sparingly Soluble Gases in Water" % J. Geophys. Res., 92(C10), 10767-10776. % Ar freshwaters values are extrapolated from Jahne et al. 1987 % He, Ne, Kr, Xe values at each temperature were fitted to D vs. mass^-0.5 % relationship to predict Ar at those temperatures, then Ar was fit to a % ln(D_Ar) vs. 1/T(K) relationship to obtain Eyring equation coefficients % O2 and N2 freshwater values from Ferrell and Himmelblau, 1967. % "Diffusion coefficients of nitrogen and oxygen in water" % J. Chem. Eng. Data, 12(1), 111-115, doi: 10.1021/je60032a036. % Correction for salinity is based on Jahne's observed average 4.9% decrease in % diffusivity for H2 and He in 35.5 ppt NaCl solution % % for Ne, the Jahne values compare well with and fall between those of % Wise and Houghton 1968 and Holz et al. 1994 % for Ar, the extrapolated Jahne values compare well with Wise and Houghton 1968, % O'Brien and Hyslop 1977, and a numerical simulation by Bourg et al. 2008 % but are higher than other reported values % for Kr, the Jahne values compare well with Wise and Houghton 1968, % and a numerical simulation by Bourg et al. 2008 % for Xe, the Jahne values compare well with Pollack 1981, and a numerical % simulation by Bourg et al. 2008, but fall significantly above Wise and Houghton 1968 % and below Weingartner et al. 1992 % for O2, there is general agreement among measurements. The Ferrel and Himmelblau values % agree reasonably well with Baird and Davidson 1962, Wise and Houghton 1966, % Duda and Vrentas 1968, O'Brien and Hyslop 1977, and the Wilke and Change (1955) theory % as tabulated by Wanninkhof 1992, but lie below Krieger et al 1967 % for N2, there is less agreement. The Ferrel and Himmelblau values % agree reasonably well with Baird and Davidson 1962, O'Brien and Hyslop 1977, % and the Wilke and Change (1955) theory as tabulated by Wanninkhof 1992, % but lie significantly below the values of Wise and Houghton 1966 and Krieger et al 1967 % for He, I did not investigate comparisons of data, but chose Jahne % since their work for other gases appears to be the best % for CO2, CH4 and H2: Jahne 1987 % % % % DISCLAIMER: % This software is provided "as is" without warranty of any kind. %========================================================================= """ from __future__ import division import numpy as np from numpy.polynomial.polynomial import polyval from ._utilities import match_args_return from gasex.phys import R as R from gasex.phys import visc as visc # Currently supported gases # TODO: find N2O, CO diffusivities GAS_LIST = ('HE','NE','AR','KR','XE','N2','O2','CH4','N2','CO2') @match_args_return def diff(SP,pt,*,gas=None): """ DESCRIPTION ----------- Diffusion coefficients of various gases in fresh/sea water PARAMETERS ----------- SP = practical salinity [PSS-78] pt = potential temperature [degree C] gas = 'He','Ne','Ar','Kr','Xe','N2','O2','CH4','N2' or 'CO2' OUTPUT: D = diffusion coefficient [m^2 s-1] """ g_up = gas.upper() if g_up not in GAS_LIST: raise ValueError("gas: must be one of ", GAS_LIST) AEa_dict = {'O2': (4.286e-6, 18700),\ 'HE': (0.8180e-6, 11700),\ 'NE': (1.6080e-6, 14840),\ 'AR': (2.227e-6, 16680),\ 'KR': (6.3930e-6, 20200),\ 'XE': (9.0070e-6, 21610),\ 'N2': (3.4120e-6, 18500),\ 'CH4':(3.0470e-6, 18360),\ 'CO2':(5.0190e-6, 19510),\ 'H2': (3.3380e-6, 16060)} if g_up in AEa_dict.keys(): #freshwater diffusivity AEa = AEa_dict[g_up] D0 = AEa[0] * np.exp(-AEa[1] / (R * (pt+273.15))) #salinity correction D = D0 * (1 - 0.049 * SP / 35.5) else: raise ValueError("gas: must be one of ", AEa_dict.keys()) return D @match_args_return def schmidt(SP,pt,*,gas=None): g_up = gas.upper() if g_up not in GAS_LIST: raise ValueError("gas", g_up, " does not match one of ", GAS_LIST) Sc = visc(SP,pt) / diff(SP,pt,gas=gas) return Sc @match_args_return def schmidt_W14(pt,*,gas=None,sw=True): """Schmidt number @ 35 psu based on Wanninkhof 2014 Table 1 Args: pt ([array like]): potential temperature [degree C] gas ([string]): abbreviation for gas. Defaults to None. sw (bool, optional): if True, then calculates for SP = 35, of false, calculates for fresh water. Defaults to True. Raises: ValueError: [description] Returns: [type]: Schmidt number [dimensionless] """ W14_LIST = ('CO2','N2O','CH4','RN','SF6','DMS','CFC12','CFC11','CH3BR','CCL4') g_up = gas.upper() if sw: A_dict = {'CO2': (2116.8,-136.25,4.7353,-0.092307,0.0007555 ),\ 'N2O': (2356.2,-166.38,6.3952,-0.13422,0.0011506 ),\ 'CH4':(2101.2,-131.54,4.4931,-0.08676,0.00070663), 'RN': (3489.6,-244.56,8.9713,-0.18022,0.0014985 ), 'SF6':(3177.5,-200.57,6.8865,-0.13335,0.0010877 ), 'DMS':(2855.7,-177.63,6.0438,-0.11645,0.00094743), 'CFC12':(3828.1,-249.86, 8.7603, -0.1716, 0.001408 ), 'CFC11':(3579.2, -222.63, 7.5749, -0.14595, 0.0011874 ), 'CH3BR':(2181.8, -138.4, 4.7663, -0.092448, 0.0007547 ), 'CCL4': (4398.7, -308.25, 11.798, -0.24709, 0.0021159) } else: A_dict = {'CO2': (1923.6, -125.06, 4.3773, -0.085681, 0.00070284 ),\ 'N2O': (2141.2, -152.56, 5.8963, -0.12411, 0.0010655 ),\ 'CH4':(1909.4, -120.78, 4.1555, -0.080578, 0.00065777), 'RN': (3171, -224.28, 8.2809, -0.16699, 0.0013915 ), 'SF6':(3035, -196.35, 6.851, -0.13387, 0.0010972 ), 'DMS':(2595, -163.12, 5.5902, -0.10817, 0.00088204), 'CFC12':(3478.6, -229.32, 8.0961, -0.15923, 0.0013095 ), 'CFC11':(3460, -217.49, 7.4537, -0.14423, 0.0011761 ), 'CH3BR':(2109.2, -135.17, 4.6884, -0.091317, 0.00074715 ), 'CCL4': (3997.2, -282.69, 10.88, -0.22855, 0.0019605) } if g_up in A_dict.keys(): A = A_dict[g_up] else: raise ValueError("gas", g_up, " does not match one of ", A_dict.keys()) Sc = polyval(pt,A) return Sc
43.814208
99
0.607383
from __future__ import division import numpy as np from numpy.polynomial.polynomial import polyval from ._utilities import match_args_return from gasex.phys import R as R from gasex.phys import visc as visc GAS_LIST = ('HE','NE','AR','KR','XE','N2','O2','CH4','N2','CO2') @match_args_return def diff(SP,pt,*,gas=None): g_up = gas.upper() if g_up not in GAS_LIST: raise ValueError("gas: must be one of ", GAS_LIST) AEa_dict = {'O2': (4.286e-6, 18700),\ 'HE': (0.8180e-6, 11700),\ 'NE': (1.6080e-6, 14840),\ 'AR': (2.227e-6, 16680),\ 'KR': (6.3930e-6, 20200),\ 'XE': (9.0070e-6, 21610),\ 'N2': (3.4120e-6, 18500),\ 'CH4':(3.0470e-6, 18360),\ 'CO2':(5.0190e-6, 19510),\ 'H2': (3.3380e-6, 16060)} if g_up in AEa_dict.keys(): AEa = AEa_dict[g_up] D0 = AEa[0] * np.exp(-AEa[1] / (R * (pt+273.15))) D = D0 * (1 - 0.049 * SP / 35.5) else: raise ValueError("gas: must be one of ", AEa_dict.keys()) return D @match_args_return def schmidt(SP,pt,*,gas=None): g_up = gas.upper() if g_up not in GAS_LIST: raise ValueError("gas", g_up, " does not match one of ", GAS_LIST) Sc = visc(SP,pt) / diff(SP,pt,gas=gas) return Sc @match_args_return def schmidt_W14(pt,*,gas=None,sw=True): W14_LIST = ('CO2','N2O','CH4','RN','SF6','DMS','CFC12','CFC11','CH3BR','CCL4') g_up = gas.upper() if sw: A_dict = {'CO2': (2116.8,-136.25,4.7353,-0.092307,0.0007555 ),\ 'N2O': (2356.2,-166.38,6.3952,-0.13422,0.0011506 ),\ 'CH4':(2101.2,-131.54,4.4931,-0.08676,0.00070663), 'RN': (3489.6,-244.56,8.9713,-0.18022,0.0014985 ), 'SF6':(3177.5,-200.57,6.8865,-0.13335,0.0010877 ), 'DMS':(2855.7,-177.63,6.0438,-0.11645,0.00094743), 'CFC12':(3828.1,-249.86, 8.7603, -0.1716, 0.001408 ), 'CFC11':(3579.2, -222.63, 7.5749, -0.14595, 0.0011874 ), 'CH3BR':(2181.8, -138.4, 4.7663, -0.092448, 0.0007547 ), 'CCL4': (4398.7, -308.25, 11.798, -0.24709, 0.0021159) } else: A_dict = {'CO2': (1923.6, -125.06, 4.3773, -0.085681, 0.00070284 ),\ 'N2O': (2141.2, -152.56, 5.8963, -0.12411, 0.0010655 ),\ 'CH4':(1909.4, -120.78, 4.1555, -0.080578, 0.00065777), 'RN': (3171, -224.28, 8.2809, -0.16699, 0.0013915 ), 'SF6':(3035, -196.35, 6.851, -0.13387, 0.0010972 ), 'DMS':(2595, -163.12, 5.5902, -0.10817, 0.00088204), 'CFC12':(3478.6, -229.32, 8.0961, -0.15923, 0.0013095 ), 'CFC11':(3460, -217.49, 7.4537, -0.14423, 0.0011761 ), 'CH3BR':(2109.2, -135.17, 4.6884, -0.091317, 0.00074715 ), 'CCL4': (3997.2, -282.69, 10.88, -0.22855, 0.0019605) } if g_up in A_dict.keys(): A = A_dict[g_up] else: raise ValueError("gas", g_up, " does not match one of ", A_dict.keys()) Sc = polyval(pt,A) return Sc
true
true
f7148669ff553acc8e2aab92e20c57cfaa89f4d4
952
py
Python
testing/functional_tests/test_convert_to_onnx.py
cakester/ivadomed
321a91c7e3c82e6296764895e39695b04a80c8af
[ "MIT" ]
null
null
null
testing/functional_tests/test_convert_to_onnx.py
cakester/ivadomed
321a91c7e3c82e6296764895e39695b04a80c8af
[ "MIT" ]
6
2021-03-24T16:23:29.000Z
2021-04-08T15:22:53.000Z
testing/functional_tests/test_convert_to_onnx.py
cakester/ivadomed
321a91c7e3c82e6296764895e39695b04a80c8af
[ "MIT" ]
null
null
null
import logging import pytest import os from functional_tests.t_utils import remove_tmp_dir, create_tmp_dir, __data_testing_dir__ from ivadomed.scripts import convert_to_onnx from ivadomed.utils import ArgParseException logger = logging.getLogger(__name__) __model_path__ = os.path.join(__data_testing_dir__, 'spinegeneric_model.pt') def setup_function(): create_tmp_dir() def test_convert_to_onnx(): convert_to_onnx.main(args=['-m', f'{__model_path__}', '-d', '2']) assert os.path.exists(os.path.join(__data_testing_dir__, 'spinegeneric_model.onnx')) def test_convert_to_onnx_no_model(): with pytest.raises(ArgParseException, match=r"Error parsing args"): convert_to_onnx.main(args=['-d', '2']) def test_convert_to_onnx_no_dimension(): with pytest.raises(ArgParseException, match=r"Error parsing args"): convert_to_onnx.main(args=['-m', f'{__model_path__}']) def teardown_function(): remove_tmp_dir()
28.848485
89
0.765756
import logging import pytest import os from functional_tests.t_utils import remove_tmp_dir, create_tmp_dir, __data_testing_dir__ from ivadomed.scripts import convert_to_onnx from ivadomed.utils import ArgParseException logger = logging.getLogger(__name__) __model_path__ = os.path.join(__data_testing_dir__, 'spinegeneric_model.pt') def setup_function(): create_tmp_dir() def test_convert_to_onnx(): convert_to_onnx.main(args=['-m', f'{__model_path__}', '-d', '2']) assert os.path.exists(os.path.join(__data_testing_dir__, 'spinegeneric_model.onnx')) def test_convert_to_onnx_no_model(): with pytest.raises(ArgParseException, match=r"Error parsing args"): convert_to_onnx.main(args=['-d', '2']) def test_convert_to_onnx_no_dimension(): with pytest.raises(ArgParseException, match=r"Error parsing args"): convert_to_onnx.main(args=['-m', f'{__model_path__}']) def teardown_function(): remove_tmp_dir()
true
true
f714889560de33dc5cf5c279055a50f15365c010
6,460
py
Python
courses/machine_learning/deepdive/05_artandscience/simplernn/trainer/model.py
alixhami/training-data-analyst
826a9270e784a64ea3bd62c34689518280df71a8
[ "Apache-2.0" ]
1
2019-02-12T21:40:03.000Z
2019-02-12T21:40:03.000Z
courses/machine_learning/deepdive/05_artandscience/simplernn/trainer/model.py
alixhami/training-data-analyst
826a9270e784a64ea3bd62c34689518280df71a8
[ "Apache-2.0" ]
11
2020-01-28T22:39:44.000Z
2022-03-11T23:42:53.000Z
courses/machine_learning/deepdive/05_artandscience/simplernn/trainer/model.py
vega42/GoogleCloudPlatform-training-data-analyst
3eb60cb6c8b55fd7f38414c1082da36b8e62558e
[ "Apache-2.0" ]
1
2021-01-15T10:20:27.000Z
2021-01-15T10:20:27.000Z
#!/usr/bin/env python3 # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import tensorflow as tf import tensorflow.contrib.metrics as metrics import tensorflow.contrib.rnn as rnn tf.logging.set_verbosity(tf.logging.INFO) SEQ_LEN = 10 DEFAULTS = [[0.0] for x in range(0, SEQ_LEN)] BATCH_SIZE = 20 TIMESERIES_INPUT_LAYER = 'rawdata' TIMESERIES_COL = '{}_input'.format(TIMESERIES_INPUT_LAYER) # In each sequence, column index 0 to N_INPUTS - 1 are features, and column index N_INPUTS to SEQ_LEN are labels N_OUTPUTS = 1 N_INPUTS = SEQ_LEN - N_OUTPUTS LSTM_SIZE = 3 # number of hidden layers in each of the LSTM cells # Read data and convert to needed format def read_dataset(filename, mode, batch_size): def _input_fn(): # Provide the ability to decode a CSV def decode_csv(line): # all_data is a list of scalar tensors all_data = tf.decode_csv(line, record_defaults = DEFAULTS) inputs = all_data[:len(all_data) - N_OUTPUTS] # first N_INPUTS values labels = all_data[len(all_data) - N_OUTPUTS:] # last N_OUTPUTS values # Convert each list of rank R tensors to one rank R+1 tensor inputs = tf.stack(inputs, axis = 0) labels = tf.stack(labels, axis = 0) # Convert input R+1 tensor into a feature dictionary of one R+1 tensor features = {TIMESERIES_COL: inputs} return features, labels # Create list of files that match pattern file_list = tf.gfile.Glob(filename) # Create dataset from file list dataset = tf.data.TextLineDataset(file_list).map(decode_csv) if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size = 10 * batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) iterator = dataset.make_one_shot_iterator() batch_features, batch_labels = iterator.get_next() return batch_features, batch_labels return _input_fn # Create inference model using Keras # The model here is a dnn regressor def make_keras_estimator(output_dir): from tensorflow import keras model = keras.models.Sequential() model.add(keras.layers.Dense(32, input_shape=(N_INPUTS,), name=TIMESERIES_INPUT_LAYER)) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Dense(1)) model.compile(loss = 'mean_squared_error', optimizer = 'adam', metrics = ['mae', 'mape']) # mean absolute [percentage] error return keras.estimator.model_to_estimator(model, model_dir=output_dir) # Create the inference model def simple_rnn(features, labels, mode): # 0. Reformat input shape to become a sequence x = tf.split(features[TIMESERIES_COL], N_INPUTS, 1) # 1. Configure the RNN lstm_cell = rnn.BasicLSTMCell(LSTM_SIZE, forget_bias = 1.0) outputs, _ = rnn.static_rnn(lstm_cell, x, dtype = tf.float32) # Slice to keep only the last cell of the RNN outputs = outputs[-1] #print('last outputs={}'.format(outputs)) # Output is result of linear activation of last layer of RNN weight = tf.Variable(tf.random_normal([LSTM_SIZE, N_OUTPUTS])) bias = tf.Variable(tf.random_normal([N_OUTPUTS])) predictions = tf.matmul(outputs, weight) + bias # 2. Loss function, training/eval ops if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL: loss = tf.losses.mean_squared_error(labels, predictions) train_op = tf.contrib.layers.optimize_loss( loss = loss, global_step = tf.train.get_global_step(), learning_rate = 0.01, optimizer = "SGD") eval_metric_ops = { "rmse": tf.metrics.root_mean_squared_error(labels, predictions) } else: loss = None train_op = None eval_metric_ops = None # 3. Create predictions predictions_dict = {"predicted": predictions} # 4. Create export outputs export_outputs = {"predict_export_outputs": tf.estimator.export.PredictOutput(outputs = predictions)} # 4. Return EstimatorSpec return tf.estimator.EstimatorSpec( mode = mode, predictions = predictions_dict, loss = loss, train_op = train_op, eval_metric_ops = eval_metric_ops, export_outputs = export_outputs) # Create serving input function def serving_input_fn(): feature_placeholders = { TIMESERIES_COL: tf.placeholder(tf.float32, [None, N_INPUTS]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } features[TIMESERIES_COL] = tf.squeeze(features[TIMESERIES_COL], axis = [2]) return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create custom estimator's train and evaluate function def train_and_evaluate(output_dir, use_keras): if use_keras: estimator = make_keras_estimator(output_dir) else: estimator = tf.estimator.Estimator(model_fn = simple_rnn, model_dir = output_dir) train_spec = tf.estimator.TrainSpec(read_dataset('train.csv', tf.estimator.ModeKeys.TRAIN, 512), max_steps = 1000) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec(read_dataset('valid.csv', tf.estimator.ModeKeys.EVAL, 512), steps = None, exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
39.151515
112
0.657276
import tensorflow as tf import tensorflow.contrib.metrics as metrics import tensorflow.contrib.rnn as rnn tf.logging.set_verbosity(tf.logging.INFO) SEQ_LEN = 10 DEFAULTS = [[0.0] for x in range(0, SEQ_LEN)] BATCH_SIZE = 20 TIMESERIES_INPUT_LAYER = 'rawdata' TIMESERIES_COL = '{}_input'.format(TIMESERIES_INPUT_LAYER) N_OUTPUTS = 1 N_INPUTS = SEQ_LEN - N_OUTPUTS LSTM_SIZE = 3 def read_dataset(filename, mode, batch_size): def _input_fn(): def decode_csv(line): all_data = tf.decode_csv(line, record_defaults = DEFAULTS) inputs = all_data[:len(all_data) - N_OUTPUTS] labels = all_data[len(all_data) - N_OUTPUTS:] inputs = tf.stack(inputs, axis = 0) labels = tf.stack(labels, axis = 0) features = {TIMESERIES_COL: inputs} return features, labels file_list = tf.gfile.Glob(filename) dataset = tf.data.TextLineDataset(file_list).map(decode_csv) if mode == tf.estimator.ModeKeys.TRAIN: num_epochs = None dataset = dataset.shuffle(buffer_size = 10 * batch_size) else: num_epochs = 1 dataset = dataset.repeat(num_epochs).batch(batch_size) iterator = dataset.make_one_shot_iterator() batch_features, batch_labels = iterator.get_next() return batch_features, batch_labels return _input_fn def make_keras_estimator(output_dir): from tensorflow import keras model = keras.models.Sequential() model.add(keras.layers.Dense(32, input_shape=(N_INPUTS,), name=TIMESERIES_INPUT_LAYER)) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Dense(1)) model.compile(loss = 'mean_squared_error', optimizer = 'adam', metrics = ['mae', 'mape']) return keras.estimator.model_to_estimator(model, model_dir=output_dir) def simple_rnn(features, labels, mode): x = tf.split(features[TIMESERIES_COL], N_INPUTS, 1) lstm_cell = rnn.BasicLSTMCell(LSTM_SIZE, forget_bias = 1.0) outputs, _ = rnn.static_rnn(lstm_cell, x, dtype = tf.float32) outputs = outputs[-1] weight = tf.Variable(tf.random_normal([LSTM_SIZE, N_OUTPUTS])) bias = tf.Variable(tf.random_normal([N_OUTPUTS])) predictions = tf.matmul(outputs, weight) + bias if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL: loss = tf.losses.mean_squared_error(labels, predictions) train_op = tf.contrib.layers.optimize_loss( loss = loss, global_step = tf.train.get_global_step(), learning_rate = 0.01, optimizer = "SGD") eval_metric_ops = { "rmse": tf.metrics.root_mean_squared_error(labels, predictions) } else: loss = None train_op = None eval_metric_ops = None predictions_dict = {"predicted": predictions} export_outputs = {"predict_export_outputs": tf.estimator.export.PredictOutput(outputs = predictions)} return tf.estimator.EstimatorSpec( mode = mode, predictions = predictions_dict, loss = loss, train_op = train_op, eval_metric_ops = eval_metric_ops, export_outputs = export_outputs) def serving_input_fn(): feature_placeholders = { TIMESERIES_COL: tf.placeholder(tf.float32, [None, N_INPUTS]) } features = { key: tf.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } features[TIMESERIES_COL] = tf.squeeze(features[TIMESERIES_COL], axis = [2]) return tf.estimator.export.ServingInputReceiver(features, feature_placeholders) def train_and_evaluate(output_dir, use_keras): if use_keras: estimator = make_keras_estimator(output_dir) else: estimator = tf.estimator.Estimator(model_fn = simple_rnn, model_dir = output_dir) train_spec = tf.estimator.TrainSpec(read_dataset('train.csv', tf.estimator.ModeKeys.TRAIN, 512), max_steps = 1000) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec(read_dataset('valid.csv', tf.estimator.ModeKeys.EVAL, 512), steps = None, exporters = exporter) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
true
true
f71488cdf51ba686efdcf99b240b487d5d66ed67
16,474
py
Python
env/lib/python2.7/site-packages/pip/cmdoptions.py
lindamar/ecclesi
cad07fc78daf6facd1b74cc1cb1872aaf4771fa2
[ "MIT" ]
168
2015-05-29T13:56:01.000Z
2022-02-17T07:38:17.000Z
env/lib/python2.7/site-packages/pip/cmdoptions.py
lindamar/ecclesi
cad07fc78daf6facd1b74cc1cb1872aaf4771fa2
[ "MIT" ]
3,243
2017-02-07T15:30:01.000Z
2022-03-31T16:42:19.000Z
env/lib/python2.7/site-packages/pip/cmdoptions.py
lindamar/ecclesi
cad07fc78daf6facd1b74cc1cb1872aaf4771fa2
[ "MIT" ]
210
2017-09-01T00:10:08.000Z
2022-03-19T18:05:12.000Z
""" shared options and groups The principle here is to define options once, but *not* instantiate them globally. One reason being that options with action='append' can carry state between parses. pip parses general options twice internally, and shouldn't pass on state. To be consistent, all options will follow this design. """ from __future__ import absolute_import from functools import partial from optparse import OptionGroup, SUPPRESS_HELP, Option import warnings from pip.index import ( FormatControl, fmt_ctl_handle_mutual_exclude, fmt_ctl_no_binary, fmt_ctl_no_use_wheel) from pip.models import PyPI from pip.locations import USER_CACHE_DIR, src_prefix from pip.utils.hashes import STRONG_HASHES def make_option_group(group, parser): """ Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser """ option_group = OptionGroup(parser, group['name']) for option in group['options']: option_group.add_option(option()) return option_group def resolve_wheel_no_use_binary(options): if not options.use_wheel: control = options.format_control fmt_ctl_no_use_wheel(control) def check_install_build_global(options, check_options=None): """Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. """ if check_options is None: check_options = options def getname(n): return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = options.format_control fmt_ctl_no_binary(control) warnings.warn( 'Disabling all use of wheels due to the use of --build-options ' '/ --global-options / --install-options.', stacklevel=2) ########### # options # ########### help_ = partial( Option, '-h', '--help', dest='help', action='help', help='Show help.') isolated_mode = partial( Option, "--isolated", dest="isolated_mode", action="store_true", default=False, help=( "Run pip in an isolated mode, ignoring environment variables and user " "configuration." ), ) require_virtualenv = partial( Option, # Run only if inside a virtualenv, bail if not. '--require-virtualenv', '--require-venv', dest='require_venv', action='store_true', default=False, help=SUPPRESS_HELP) verbose = partial( Option, '-v', '--verbose', dest='verbose', action='count', default=0, help='Give more output. Option is additive, and can be used up to 3 times.' ) version = partial( Option, '-V', '--version', dest='version', action='store_true', help='Show version and exit.') quiet = partial( Option, '-q', '--quiet', dest='quiet', action='count', default=0, help=('Give less output. Option is additive, and can be used up to 3' ' times (corresponding to WARNING, ERROR, and CRITICAL logging' ' levels).') ) log = partial( Option, "--log", "--log-file", "--local-log", dest="log", metavar="path", help="Path to a verbose appending log." ) no_input = partial( Option, # Don't ask for input '--no-input', dest='no_input', action='store_true', default=False, help=SUPPRESS_HELP) proxy = partial( Option, '--proxy', dest='proxy', type='str', default='', help="Specify a proxy in the form [user:passwd@]proxy.server:port.") retries = partial( Option, '--retries', dest='retries', type='int', default=5, help="Maximum number of retries each connection should attempt " "(default %default times).") timeout = partial( Option, '--timeout', '--default-timeout', metavar='sec', dest='timeout', type='float', default=15, help='Set the socket timeout (default %default seconds).') default_vcs = partial( Option, # The default version control system for editables, e.g. 'svn' '--default-vcs', dest='default_vcs', type='str', default='', help=SUPPRESS_HELP) skip_requirements_regex = partial( Option, # A regex to be used to skip requirements '--skip-requirements-regex', dest='skip_requirements_regex', type='str', default='', help=SUPPRESS_HELP) def exists_action(): return Option( # Option when path already exist '--exists-action', dest='exists_action', type='choice', choices=['s', 'i', 'w', 'b', 'a'], default=[], action='append', metavar='action', help="Default action when a path already exists: " "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.") cert = partial( Option, '--cert', dest='cert', type='str', metavar='path', help="Path to alternate CA bundle.") client_cert = partial( Option, '--client-cert', dest='client_cert', type='str', default=None, metavar='path', help="Path to SSL client certificate, a single file containing the " "private key and the certificate in PEM format.") index_url = partial( Option, '-i', '--index-url', '--pypi-url', dest='index_url', metavar='URL', default=PyPI.simple_url, help="Base URL of Python Package Index (default %default). " "This should point to a repository compliant with PEP 503 " "(the simple repository API) or a local directory laid out " "in the same format.") def extra_index_url(): return Option( '--extra-index-url', dest='extra_index_urls', metavar='URL', action='append', default=[], help="Extra URLs of package indexes to use in addition to " "--index-url. Should follow the same rules as " "--index-url." ) no_index = partial( Option, '--no-index', dest='no_index', action='store_true', default=False, help='Ignore package index (only looking at --find-links URLs instead).') def find_links(): return Option( '-f', '--find-links', dest='find_links', action='append', default=[], metavar='url', help="If a url or path to an html file, then parse for links to " "archives. If a local path or file:// url that's a directory, " "then look for archives in the directory listing.") def allow_external(): return Option( "--allow-external", dest="allow_external", action="append", default=[], metavar="PACKAGE", help=SUPPRESS_HELP, ) allow_all_external = partial( Option, "--allow-all-external", dest="allow_all_external", action="store_true", default=False, help=SUPPRESS_HELP, ) def trusted_host(): return Option( "--trusted-host", dest="trusted_hosts", action="append", metavar="HOSTNAME", default=[], help="Mark this host as trusted, even though it does not have valid " "or any HTTPS.", ) # Remove after 7.0 no_allow_external = partial( Option, "--no-allow-external", dest="allow_all_external", action="store_false", default=False, help=SUPPRESS_HELP, ) # Remove --allow-insecure after 7.0 def allow_unsafe(): return Option( "--allow-unverified", "--allow-insecure", dest="allow_unverified", action="append", default=[], metavar="PACKAGE", help=SUPPRESS_HELP, ) # Remove after 7.0 no_allow_unsafe = partial( Option, "--no-allow-insecure", dest="allow_all_insecure", action="store_false", default=False, help=SUPPRESS_HELP ) # Remove after 1.5 process_dependency_links = partial( Option, "--process-dependency-links", dest="process_dependency_links", action="store_true", default=False, help="Enable the processing of dependency links.", ) def constraints(): return Option( '-c', '--constraint', dest='constraints', action='append', default=[], metavar='file', help='Constrain versions using the given constraints file. ' 'This option can be used multiple times.') def requirements(): return Option( '-r', '--requirement', dest='requirements', action='append', default=[], metavar='file', help='Install from the given requirements file. ' 'This option can be used multiple times.') def editable(): return Option( '-e', '--editable', dest='editables', action='append', default=[], metavar='path/url', help=('Install a project in editable mode (i.e. setuptools ' '"develop mode") from a local project path or a VCS url.'), ) src = partial( Option, '--src', '--source', '--source-dir', '--source-directory', dest='src_dir', metavar='dir', default=src_prefix, help='Directory to check out editable projects into. ' 'The default in a virtualenv is "<venv path>/src". ' 'The default for global installs is "<current dir>/src".' ) # XXX: deprecated, remove in 9.0 use_wheel = partial( Option, '--use-wheel', dest='use_wheel', action='store_true', default=True, help=SUPPRESS_HELP, ) # XXX: deprecated, remove in 9.0 no_use_wheel = partial( Option, '--no-use-wheel', dest='use_wheel', action='store_false', default=True, help=('Do not Find and prefer wheel archives when searching indexes and ' 'find-links locations. DEPRECATED in favour of --no-binary.'), ) def _get_format_control(values, option): """Get a format_control object.""" return getattr(values, option.dest) def _handle_no_binary(option, opt_str, value, parser): existing = getattr(parser.values, option.dest) fmt_ctl_handle_mutual_exclude( value, existing.no_binary, existing.only_binary) def _handle_only_binary(option, opt_str, value, parser): existing = getattr(parser.values, option.dest) fmt_ctl_handle_mutual_exclude( value, existing.only_binary, existing.no_binary) def no_binary(): return Option( "--no-binary", dest="format_control", action="callback", callback=_handle_no_binary, type="str", default=FormatControl(set(), set()), help="Do not use binary packages. Can be supplied multiple times, and " "each time adds to the existing value. Accepts either :all: to " "disable all binary packages, :none: to empty the set, or one or " "more package names with commas between them. Note that some " "packages are tricky to compile and may fail to install when " "this option is used on them.") def only_binary(): return Option( "--only-binary", dest="format_control", action="callback", callback=_handle_only_binary, type="str", default=FormatControl(set(), set()), help="Do not use source packages. Can be supplied multiple times, and " "each time adds to the existing value. Accepts either :all: to " "disable all source packages, :none: to empty the set, or one or " "more package names with commas between them. Packages without " "binary distributions will fail to install when this option is " "used on them.") cache_dir = partial( Option, "--cache-dir", dest="cache_dir", default=USER_CACHE_DIR, metavar="dir", help="Store the cache data in <dir>." ) no_cache = partial( Option, "--no-cache-dir", dest="cache_dir", action="store_false", help="Disable the cache.", ) no_deps = partial( Option, '--no-deps', '--no-dependencies', dest='ignore_dependencies', action='store_true', default=False, help="Don't install package dependencies.") build_dir = partial( Option, '-b', '--build', '--build-dir', '--build-directory', dest='build_dir', metavar='dir', help='Directory to unpack packages into and build in.' ) ignore_requires_python = partial( Option, '--ignore-requires-python', dest='ignore_requires_python', action='store_true', help='Ignore the Requires-Python information.') install_options = partial( Option, '--install-option', dest='install_options', action='append', metavar='options', help="Extra arguments to be supplied to the setup.py install " "command (use like --install-option=\"--install-scripts=/usr/local/" "bin\"). Use multiple --install-option options to pass multiple " "options to setup.py install. If you are using an option with a " "directory path, be sure to use absolute path.") global_options = partial( Option, '--global-option', dest='global_options', action='append', metavar='options', help="Extra global options to be supplied to the setup.py " "call before the install command.") no_clean = partial( Option, '--no-clean', action='store_true', default=False, help="Don't clean up build directories.") pre = partial( Option, '--pre', action='store_true', default=False, help="Include pre-release and development versions. By default, " "pip only finds stable versions.") disable_pip_version_check = partial( Option, "--disable-pip-version-check", dest="disable_pip_version_check", action="store_true", default=False, help="Don't periodically check PyPI to determine whether a new version " "of pip is available for download. Implied with --no-index.") # Deprecated, Remove later always_unzip = partial( Option, '-Z', '--always-unzip', dest='always_unzip', action='store_true', help=SUPPRESS_HELP, ) def _merge_hash(option, opt_str, value, parser): """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name.""" if not parser.values.hashes: parser.values.hashes = {} try: algo, digest = value.split(':', 1) except ValueError: parser.error('Arguments to %s must be a hash name ' 'followed by a value, like --hash=sha256:abcde...' % opt_str) if algo not in STRONG_HASHES: parser.error('Allowed hash algorithms for %s are %s.' % (opt_str, ', '.join(STRONG_HASHES))) parser.values.hashes.setdefault(algo, []).append(digest) hash = partial( Option, '--hash', # Hash values eventually end up in InstallRequirement.hashes due to # __dict__ copying in process_line(). dest='hashes', action='callback', callback=_merge_hash, type='string', help="Verify that the package's archive matches this " 'hash before installing. Example: --hash=sha256:abcdef...') require_hashes = partial( Option, '--require-hashes', dest='require_hashes', action='store_true', default=False, help='Require a hash to check each requirement against, for ' 'repeatable installs. This option is implied when any package in a ' 'requirements file has a --hash option.') ########## # groups # ########## general_group = { 'name': 'General Options', 'options': [ help_, isolated_mode, require_virtualenv, verbose, version, quiet, log, no_input, proxy, retries, timeout, default_vcs, skip_requirements_regex, exists_action, trusted_host, cert, client_cert, cache_dir, no_cache, disable_pip_version_check, ] } non_deprecated_index_group = { 'name': 'Package Index Options', 'options': [ index_url, extra_index_url, no_index, find_links, process_dependency_links, ] } index_group = { 'name': 'Package Index Options (including deprecated options)', 'options': non_deprecated_index_group['options'] + [ allow_external, allow_all_external, no_allow_external, allow_unsafe, no_allow_unsafe, ] }
25.984227
79
0.622253
from __future__ import absolute_import from functools import partial from optparse import OptionGroup, SUPPRESS_HELP, Option import warnings from pip.index import ( FormatControl, fmt_ctl_handle_mutual_exclude, fmt_ctl_no_binary, fmt_ctl_no_use_wheel) from pip.models import PyPI from pip.locations import USER_CACHE_DIR, src_prefix from pip.utils.hashes import STRONG_HASHES def make_option_group(group, parser): option_group = OptionGroup(parser, group['name']) for option in group['options']: option_group.add_option(option()) return option_group def resolve_wheel_no_use_binary(options): if not options.use_wheel: control = options.format_control fmt_ctl_no_use_wheel(control) def check_install_build_global(options, check_options=None): if check_options is None: check_options = options def getname(n): return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = options.format_control fmt_ctl_no_binary(control) warnings.warn( 'Disabling all use of wheels due to the use of --build-options ' '/ --global-options / --install-options.', stacklevel=2) isolated_mode = partial( Option, "--isolated", dest="isolated_mode", action="store_true", default=False, help=( "Run pip in an isolated mode, ignoring environment variables and user " "configuration." ), ) require_virtualenv = partial( Option, '--require-virtualenv', '--require-venv', dest='require_venv', action='store_true', default=False, help=SUPPRESS_HELP) verbose = partial( Option, '-v', '--verbose', dest='verbose', action='count', default=0, help='Give more output. Option is additive, and can be used up to 3 times.' ) version = partial( Option, '-V', '--version', dest='version', action='store_true', help='Show version and exit.') quiet = partial( Option, '-q', '--quiet', dest='quiet', action='count', default=0, help=('Give less output. Option is additive, and can be used up to 3' ' times (corresponding to WARNING, ERROR, and CRITICAL logging' ' levels).') ) log = partial( Option, "--log", "--log-file", "--local-log", dest="log", metavar="path", help="Path to a verbose appending log." ) no_input = partial( Option, '--no-input', dest='no_input', action='store_true', default=False, help=SUPPRESS_HELP) proxy = partial( Option, '--proxy', dest='proxy', type='str', default='', help="Specify a proxy in the form [user:passwd@]proxy.server:port.") retries = partial( Option, '--retries', dest='retries', type='int', default=5, help="Maximum number of retries each connection should attempt " "(default %default times).") timeout = partial( Option, '--timeout', '--default-timeout', metavar='sec', dest='timeout', type='float', default=15, help='Set the socket timeout (default %default seconds).') default_vcs = partial( Option, # The default version control system for editables, e.g. 'svn' '--default-vcs', dest='default_vcs', type='str', default='', help=SUPPRESS_HELP) skip_requirements_regex = partial( Option, # A regex to be used to skip requirements '--skip-requirements-regex', dest='skip_requirements_regex', type='str', default='', help=SUPPRESS_HELP) def exists_action(): return Option( # Option when path already exist '--exists-action', dest='exists_action', type='choice', choices=['s', 'i', 'w', 'b', 'a'], default=[], action='append', metavar='action', help="Default action when a path already exists: " "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.") cert = partial( Option, '--cert', dest='cert', type='str', metavar='path', help="Path to alternate CA bundle.") client_cert = partial( Option, '--client-cert', dest='client_cert', type='str', default=None, metavar='path', help="Path to SSL client certificate, a single file containing the " "private key and the certificate in PEM format.") index_url = partial( Option, '-i', '--index-url', '--pypi-url', dest='index_url', metavar='URL', default=PyPI.simple_url, help="Base URL of Python Package Index (default %default). " "This should point to a repository compliant with PEP 503 " "(the simple repository API) or a local directory laid out " "in the same format.") def extra_index_url(): return Option( '--extra-index-url', dest='extra_index_urls', metavar='URL', action='append', default=[], help="Extra URLs of package indexes to use in addition to " "--index-url. Should follow the same rules as " "--index-url." ) no_index = partial( Option, '--no-index', dest='no_index', action='store_true', default=False, help='Ignore package index (only looking at --find-links URLs instead).') def find_links(): return Option( '-f', '--find-links', dest='find_links', action='append', default=[], metavar='url', help="If a url or path to an html file, then parse for links to " "archives. If a local path or file:// url that's a directory, " "then look for archives in the directory listing.") def allow_external(): return Option( "--allow-external", dest="allow_external", action="append", default=[], metavar="PACKAGE", help=SUPPRESS_HELP, ) allow_all_external = partial( Option, "--allow-all-external", dest="allow_all_external", action="store_true", default=False, help=SUPPRESS_HELP, ) def trusted_host(): return Option( "--trusted-host", dest="trusted_hosts", action="append", metavar="HOSTNAME", default=[], help="Mark this host as trusted, even though it does not have valid " "or any HTTPS.", ) no_allow_external = partial( Option, "--no-allow-external", dest="allow_all_external", action="store_false", default=False, help=SUPPRESS_HELP, ) def allow_unsafe(): return Option( "--allow-unverified", "--allow-insecure", dest="allow_unverified", action="append", default=[], metavar="PACKAGE", help=SUPPRESS_HELP, ) no_allow_unsafe = partial( Option, "--no-allow-insecure", dest="allow_all_insecure", action="store_false", default=False, help=SUPPRESS_HELP ) process_dependency_links = partial( Option, "--process-dependency-links", dest="process_dependency_links", action="store_true", default=False, help="Enable the processing of dependency links.", ) def constraints(): return Option( '-c', '--constraint', dest='constraints', action='append', default=[], metavar='file', help='Constrain versions using the given constraints file. ' 'This option can be used multiple times.') def requirements(): return Option( '-r', '--requirement', dest='requirements', action='append', default=[], metavar='file', help='Install from the given requirements file. ' 'This option can be used multiple times.') def editable(): return Option( '-e', '--editable', dest='editables', action='append', default=[], metavar='path/url', help=('Install a project in editable mode (i.e. setuptools ' '"develop mode") from a local project path or a VCS url.'), ) src = partial( Option, '--src', '--source', '--source-dir', '--source-directory', dest='src_dir', metavar='dir', default=src_prefix, help='Directory to check out editable projects into. ' 'The default in a virtualenv is "<venv path>/src". ' 'The default for global installs is "<current dir>/src".' ) use_wheel = partial( Option, '--use-wheel', dest='use_wheel', action='store_true', default=True, help=SUPPRESS_HELP, ) no_use_wheel = partial( Option, '--no-use-wheel', dest='use_wheel', action='store_false', default=True, help=('Do not Find and prefer wheel archives when searching indexes and ' 'find-links locations. DEPRECATED in favour of --no-binary.'), ) def _get_format_control(values, option): return getattr(values, option.dest) def _handle_no_binary(option, opt_str, value, parser): existing = getattr(parser.values, option.dest) fmt_ctl_handle_mutual_exclude( value, existing.no_binary, existing.only_binary) def _handle_only_binary(option, opt_str, value, parser): existing = getattr(parser.values, option.dest) fmt_ctl_handle_mutual_exclude( value, existing.only_binary, existing.no_binary) def no_binary(): return Option( "--no-binary", dest="format_control", action="callback", callback=_handle_no_binary, type="str", default=FormatControl(set(), set()), help="Do not use binary packages. Can be supplied multiple times, and " "each time adds to the existing value. Accepts either :all: to " "disable all binary packages, :none: to empty the set, or one or " "more package names with commas between them. Note that some " "packages are tricky to compile and may fail to install when " "this option is used on them.") def only_binary(): return Option( "--only-binary", dest="format_control", action="callback", callback=_handle_only_binary, type="str", default=FormatControl(set(), set()), help="Do not use source packages. Can be supplied multiple times, and " "each time adds to the existing value. Accepts either :all: to " "disable all source packages, :none: to empty the set, or one or " "more package names with commas between them. Packages without " "binary distributions will fail to install when this option is " "used on them.") cache_dir = partial( Option, "--cache-dir", dest="cache_dir", default=USER_CACHE_DIR, metavar="dir", help="Store the cache data in <dir>." ) no_cache = partial( Option, "--no-cache-dir", dest="cache_dir", action="store_false", help="Disable the cache.", ) no_deps = partial( Option, '--no-deps', '--no-dependencies', dest='ignore_dependencies', action='store_true', default=False, help="Don't install package dependencies.") build_dir = partial( Option, '-b', '--build', '--build-dir', '--build-directory', dest='build_dir', metavar='dir', help='Directory to unpack packages into and build in.' ) ignore_requires_python = partial( Option, '--ignore-requires-python', dest='ignore_requires_python', action='store_true', help='Ignore the Requires-Python information.') install_options = partial( Option, '--install-option', dest='install_options', action='append', metavar='options', help="Extra arguments to be supplied to the setup.py install " "command (use like --install-option=\"--install-scripts=/usr/local/" "bin\"). Use multiple --install-option options to pass multiple " "options to setup.py install. If you are using an option with a " "directory path, be sure to use absolute path.") global_options = partial( Option, '--global-option', dest='global_options', action='append', metavar='options', help="Extra global options to be supplied to the setup.py " "call before the install command.") no_clean = partial( Option, '--no-clean', action='store_true', default=False, help="Don't clean up build directories.") pre = partial( Option, '--pre', action='store_true', default=False, help="Include pre-release and development versions. By default, " "pip only finds stable versions.") disable_pip_version_check = partial( Option, "--disable-pip-version-check", dest="disable_pip_version_check", action="store_true", default=False, help="Don't periodically check PyPI to determine whether a new version " "of pip is available for download. Implied with --no-index.") # Deprecated, Remove later always_unzip = partial( Option, '-Z', '--always-unzip', dest='always_unzip', action='store_true', help=SUPPRESS_HELP, ) def _merge_hash(option, opt_str, value, parser): if not parser.values.hashes: parser.values.hashes = {} try: algo, digest = value.split(':', 1) except ValueError: parser.error('Arguments to %s must be a hash name ' 'followed by a value, like --hash=sha256:abcde...' % opt_str) if algo not in STRONG_HASHES: parser.error('Allowed hash algorithms for %s are %s.' % (opt_str, ', '.join(STRONG_HASHES))) parser.values.hashes.setdefault(algo, []).append(digest) hash = partial( Option, '--hash', # Hash values eventually end up in InstallRequirement.hashes due to # __dict__ copying in process_line(). dest='hashes', action='callback', callback=_merge_hash, type='string', help="Verify that the package's archive matches this " 'hash before installing. Example: --hash=sha256:abcdef...') require_hashes = partial( Option, '--require-hashes', dest='require_hashes', action='store_true', default=False, help='Require a hash to check each requirement against, for ' 'repeatable installs. This option is implied when any package in a ' 'requirements file has a --hash option.') isolated_mode, require_virtualenv, verbose, version, quiet, log, no_input, proxy, retries, timeout, default_vcs, skip_requirements_regex, exists_action, trusted_host, cert, client_cert, cache_dir, no_cache, disable_pip_version_check, ] } non_deprecated_index_group = { 'name': 'Package Index Options', 'options': [ index_url, extra_index_url, no_index, find_links, process_dependency_links, ] } index_group = { 'name': 'Package Index Options (including deprecated options)', 'options': non_deprecated_index_group['options'] + [ allow_external, allow_all_external, no_allow_external, allow_unsafe, no_allow_unsafe, ] }
true
true
f71489253e48c8415077de99962ccba5eff495e5
962
py
Python
xmrig_exporter/exporter.py
leonardochaia/xmrig_exporter
56cb4a6f4b4a4df3f972fe20478269f79d6da34f
[ "MIT" ]
2
2019-09-19T00:15:20.000Z
2021-06-25T19:35:03.000Z
xmrig_exporter/exporter.py
leonardochaia/xmrig_exporter
56cb4a6f4b4a4df3f972fe20478269f79d6da34f
[ "MIT" ]
1
2019-09-19T02:29:34.000Z
2019-09-19T02:41:45.000Z
xmrig_exporter/exporter.py
leonardochaia/xmrig_exporter
56cb4a6f4b4a4df3f972fe20478269f79d6da34f
[ "MIT" ]
2
2019-09-19T01:36:19.000Z
2021-04-13T01:29:13.000Z
import argparse import http.server import logging import sys import prometheus_client import xmrig_exporter def main(): parser = argparse.ArgumentParser("Xmrig Exporter") parser.add_argument("--port", type=int, default=9189) parser.add_argument("--bind_address", default="0.0.0.0") parser.add_argument("--url", required=True) parser.add_argument("--token") parser.add_argument("--verbose", "-v", action="count") args = parser.parse_args() if args.verbose: level = logging.DEBUG else: level = logging.INFO logging.basicConfig(stream=sys.stdout, level=level) collector = xmrig_exporter.XmrigCollector(args.url, token=args.token) prometheus_client.REGISTRY.register(collector) handler = prometheus_client.MetricsHandler.factory( prometheus_client.REGISTRY) server = http.server.HTTPServer( (args.bind_address, args.port), handler) server.serve_forever()
25.315789
73
0.702703
import argparse import http.server import logging import sys import prometheus_client import xmrig_exporter def main(): parser = argparse.ArgumentParser("Xmrig Exporter") parser.add_argument("--port", type=int, default=9189) parser.add_argument("--bind_address", default="0.0.0.0") parser.add_argument("--url", required=True) parser.add_argument("--token") parser.add_argument("--verbose", "-v", action="count") args = parser.parse_args() if args.verbose: level = logging.DEBUG else: level = logging.INFO logging.basicConfig(stream=sys.stdout, level=level) collector = xmrig_exporter.XmrigCollector(args.url, token=args.token) prometheus_client.REGISTRY.register(collector) handler = prometheus_client.MetricsHandler.factory( prometheus_client.REGISTRY) server = http.server.HTTPServer( (args.bind_address, args.port), handler) server.serve_forever()
true
true
f714898b0c1aae3362b96ae223d64cae5cb39b1a
442
py
Python
run_search_goods.py
nikolay-py/product_optimizer
3d7da484984e63791849ce8a12b285a1ba2daacf
[ "MIT" ]
null
null
null
run_search_goods.py
nikolay-py/product_optimizer
3d7da484984e63791849ce8a12b285a1ba2daacf
[ "MIT" ]
1
2021-07-05T13:42:19.000Z
2021-07-05T14:14:44.000Z
run_search_goods.py
nikolay-py/product_optimizer
3d7da484984e63791849ce8a12b285a1ba2daacf
[ "MIT" ]
null
null
null
"""A utility for experimenting with searching.""" from project.parsers.crud import get_goods from project.parsers.search_goods import db from project.recipes.models import Recipe if __name__ == "__main__": recipe = db.query(Recipe).filter(Recipe.id == 2).first().product_list goods_list = get_goods(recipe,10) for inhidient in goods_list: print('----------------------------------------------') print(inhidient)
34
73
0.649321
from project.parsers.crud import get_goods from project.parsers.search_goods import db from project.recipes.models import Recipe if __name__ == "__main__": recipe = db.query(Recipe).filter(Recipe.id == 2).first().product_list goods_list = get_goods(recipe,10) for inhidient in goods_list: print('----------------------------------------------') print(inhidient)
true
true
f71489c3ef52e026137535b36258928677e4ed4f
1,562
py
Python
plateo/parsers/file_parsers.py
Edinburgh-Genome-Foundry/plateo
c9a608658325f3c507788d9b966a3f3c8e516bc5
[ "MIT" ]
22
2018-01-29T21:34:25.000Z
2021-12-14T15:31:49.000Z
plateo/parsers/file_parsers.py
Edinburgh-Genome-Foundry/plateo
c9a608658325f3c507788d9b966a3f3c8e516bc5
[ "MIT" ]
3
2017-09-20T16:08:45.000Z
2021-05-28T17:45:14.000Z
plateo/parsers/file_parsers.py
Edinburgh-Genome-Foundry/plateo
c9a608658325f3c507788d9b966a3f3c8e516bc5
[ "MIT" ]
5
2018-09-18T08:53:37.000Z
2021-04-28T08:44:38.000Z
"""Misc. file parsers that are useful for other parsers""" from xml.sax import saxutils, parse, parseString class ExcelHandler(saxutils.handler.ContentHandler): """ This class is taken from the Python Cookbook so I guess the copyright goes to them. Memo: changed the handler from DefaultHandler to ContentHandler as the former doesn't seem to exist in Py2. (?) """ def __init__(self): self.chars = [] self.cells = [] self.rows = [] self.tables = [] def characters(self, content): self.chars.append(content) def startElement(self, name, atts): if name == "Cell": self.chars = [] elif name == "Row": self.cells = [] elif name == "Table": self.rows = [] def endElement(self, name): if name == "Cell": self.cells.append(''.join(self.chars)) elif name == "Row": self.rows.append(self.cells) elif name == "Table": self.tables.append(self.rows) def parse_excel_xml(xml_file=None, xml_string=None): """Return a list of the tables (2D arrays) in the Excel XML. Provide either the path to an XML file, or a string of XML content. """ handler = ExcelHandler() if xml_file is not None: parse(xml_file, handler) elif xml_string is not None: parseString(xml_string, handler) else: raise ValueError("At least one of xml_file or xml_string should be" " provided.") return handler.tables
28.925926
75
0.596671
from xml.sax import saxutils, parse, parseString class ExcelHandler(saxutils.handler.ContentHandler): def __init__(self): self.chars = [] self.cells = [] self.rows = [] self.tables = [] def characters(self, content): self.chars.append(content) def startElement(self, name, atts): if name == "Cell": self.chars = [] elif name == "Row": self.cells = [] elif name == "Table": self.rows = [] def endElement(self, name): if name == "Cell": self.cells.append(''.join(self.chars)) elif name == "Row": self.rows.append(self.cells) elif name == "Table": self.tables.append(self.rows) def parse_excel_xml(xml_file=None, xml_string=None): handler = ExcelHandler() if xml_file is not None: parse(xml_file, handler) elif xml_string is not None: parseString(xml_string, handler) else: raise ValueError("At least one of xml_file or xml_string should be" " provided.") return handler.tables
true
true
f71489efe090002bbbd4dcf98ceba635d27bfa14
7,361
py
Python
rlcard/games/leducholdem/game.py
NiccoloSacchi/rlcard
046129e8616b12e25652957869a94ab5fd838ae1
[ "MIT" ]
null
null
null
rlcard/games/leducholdem/game.py
NiccoloSacchi/rlcard
046129e8616b12e25652957869a94ab5fd838ae1
[ "MIT" ]
null
null
null
rlcard/games/leducholdem/game.py
NiccoloSacchi/rlcard
046129e8616b12e25652957869a94ab5fd838ae1
[ "MIT" ]
1
2020-11-20T16:38:37.000Z
2020-11-20T16:38:37.000Z
import numpy as np from copy import copy from rlcard.games.leducholdem.dealer import LeducholdemDealer as Dealer from rlcard.games.leducholdem.player import LeducholdemPlayer as Player from rlcard.games.leducholdem.judger import LeducholdemJudger as Judger from rlcard.games.leducholdem.round import LeducholdemRound as Round from rlcard.games.limitholdem.game import LimitholdemGame class LeducholdemGame(LimitholdemGame): def __init__(self, allow_step_back=False): ''' Initialize the class leducholdem Game ''' self.allow_step_back = allow_step_back ''' No big/small blind # Some configarations of the game # These arguments are fixed in Leduc Hold'em Game # Raise amount and allowed times self.raise_amount = 2 self.allowed_raise_num = 2 self.num_players = 2 ''' # Some configarations of the game # These arguments can be specified for creating new games # Small blind and big blind self.small_blind = 1 self.big_blind = 2 * self.small_blind # Raise amount and allowed times self.raise_amount = self.big_blind self.allowed_raise_num = 2 self.num_players = 2 def init_game(self): ''' Initialilze the game of Limit Texas Hold'em This version supports two-player limit texas hold'em Returns: (tuple): Tuple containing: (dict): The first state of the game (int): Current player's id ''' # Initilize a dealer that can deal cards self.dealer = Dealer() # Initilize two players to play the game self.players = [Player(i) for i in range(self.num_players)] # Initialize a judger class which will decide who wins in the end self.judger = Judger() # Prepare for the first round for i in range(self.num_players): self.players[i].hand = self.dealer.deal_card() # Randomly choose a small blind and a big blind s = np.random.randint(0, self.num_players) b = (s + 1) % self.num_players self.players[b].in_chips = self.big_blind self.players[s].in_chips = self.small_blind self.public_card = None # The player with small blind plays the first self.game_pointer = s # Initilize a bidding round, in the first round, the big blind and the small blind needs to # be passed to the round for processing. self.round = Round(raise_amount=self.raise_amount, allowed_raise_num=self.allowed_raise_num, num_players=self.num_players) self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players]) # Count the round. There are 2 rounds in each game. self.round_counter = 0 # Save the hisory for stepping back to the last state. self.history = [] state = self.get_state(self.game_pointer) return state, self.game_pointer def step(self, action): ''' Get the next state Args: action (str): a specific action. (call, raise, fold, or check) Returns: (tuple): Tuple containing: (dict): next player's state (int): next plater's id ''' if self.allow_step_back: # First snapshot the current state r = copy(self.round) r_raised = copy(self.round.raised) gp = self.game_pointer r_c = self.round_counter d_deck = copy(self.dealer.deck) p = copy(self.public_card) ps = [copy(self.players[i]) for i in range(self.num_players)] ps_hand = [copy(self.players[i].hand) for i in range(self.num_players)] self.history.append((r, r_raised, gp, r_c, d_deck, p, ps, ps_hand)) # Then we proceed to the next round self.game_pointer = self.round.proceed_round(self.players, action) # If a round is over, we deal more public cards if self.round.is_over(): # For the first round, we deal 1 card as public card. Double the raise amount for the second round if self.round_counter == 0: self.public_card = self.dealer.deal_card() self.round.raise_amount = 2 * self.raise_amount self.round_counter += 1 self.round.start_new_round(self.game_pointer) state = self.get_state(self.game_pointer) return state, self.game_pointer def get_state(self, player): ''' Return player's state Args: player_id (int): player id Returns: (dict): The state of the player ''' chips = [self.players[i].in_chips for i in range(self.num_players)] legal_actions = self.get_legal_actions() state = self.players[player].get_state(self.public_card, chips, legal_actions) state['current_player'] = self.game_pointer return state def is_over(self): ''' Check if the game is over Returns: (boolean): True if the game is over ''' alive_players = [1 if p.status=='alive' else 0 for p in self.players] # If only one player is alive, the game is over. if sum(alive_players) == 1: return True # If all rounds are finshed if self.round_counter >= 2: return True return False def get_payoffs(self): ''' Return the payoffs of the game Returns: (list): Each entry corresponds to the payoff of one player ''' chips_payoffs = self.judger.judge_game(self.players, self.public_card) payoffs = np.array(chips_payoffs) / (self.big_blind) return payoffs def step_back(self): ''' Return to the previous state of the game Returns: (bool): True if the game steps back successfully ''' if len(self.history) > 0: self.round, r_raised, self.game_pointer, self.round_counter, d_deck, self.public_card, self.players, ps_hand = self.history.pop() self.round.raised = r_raised self.dealer.deck = d_deck for i, hand in enumerate(ps_hand): self.players[i].hand = hand return True return False # Test the game #if __name__ == "__main__": # game = LeducholdemGame(allow_step_back=True) # while True: # print('New Game') # state, game_pointer = game.init_game() # print(game_pointer, state) # i = 1 # while not game.is_over(): # i += 1 # legal_actions = game.get_legal_actions() # if i == 4: # print('Step back') # print(game.step_back()) # game_pointer = game.get_player_id() # print(game_pointer) # state = game.get_state(game_pointer) # legal_actions = game.get_legal_actions() # # action = input() # action = np.random.choice(legal_actions) # print(game_pointer, action, legal_actions, state) # state, game_pointer = game.step(action) # print(game_pointer, state) # # print(game.get_payoffs())
34.237209
141
0.603586
import numpy as np from copy import copy from rlcard.games.leducholdem.dealer import LeducholdemDealer as Dealer from rlcard.games.leducholdem.player import LeducholdemPlayer as Player from rlcard.games.leducholdem.judger import LeducholdemJudger as Judger from rlcard.games.leducholdem.round import LeducholdemRound as Round from rlcard.games.limitholdem.game import LimitholdemGame class LeducholdemGame(LimitholdemGame): def __init__(self, allow_step_back=False): self.allow_step_back = allow_step_back self.small_blind = 1 self.big_blind = 2 * self.small_blind self.raise_amount = self.big_blind self.allowed_raise_num = 2 self.num_players = 2 def init_game(self): self.dealer = Dealer() self.players = [Player(i) for i in range(self.num_players)] self.judger = Judger() for i in range(self.num_players): self.players[i].hand = self.dealer.deal_card() s = np.random.randint(0, self.num_players) b = (s + 1) % self.num_players self.players[b].in_chips = self.big_blind self.players[s].in_chips = self.small_blind self.public_card = None self.game_pointer = s self.round = Round(raise_amount=self.raise_amount, allowed_raise_num=self.allowed_raise_num, num_players=self.num_players) self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players]) self.round_counter = 0 self.history = [] state = self.get_state(self.game_pointer) return state, self.game_pointer def step(self, action): if self.allow_step_back: r = copy(self.round) r_raised = copy(self.round.raised) gp = self.game_pointer r_c = self.round_counter d_deck = copy(self.dealer.deck) p = copy(self.public_card) ps = [copy(self.players[i]) for i in range(self.num_players)] ps_hand = [copy(self.players[i].hand) for i in range(self.num_players)] self.history.append((r, r_raised, gp, r_c, d_deck, p, ps, ps_hand)) self.game_pointer = self.round.proceed_round(self.players, action) if self.round.is_over(): if self.round_counter == 0: self.public_card = self.dealer.deal_card() self.round.raise_amount = 2 * self.raise_amount self.round_counter += 1 self.round.start_new_round(self.game_pointer) state = self.get_state(self.game_pointer) return state, self.game_pointer def get_state(self, player): chips = [self.players[i].in_chips for i in range(self.num_players)] legal_actions = self.get_legal_actions() state = self.players[player].get_state(self.public_card, chips, legal_actions) state['current_player'] = self.game_pointer return state def is_over(self): alive_players = [1 if p.status=='alive' else 0 for p in self.players] if sum(alive_players) == 1: return True if self.round_counter >= 2: return True return False def get_payoffs(self): chips_payoffs = self.judger.judge_game(self.players, self.public_card) payoffs = np.array(chips_payoffs) / (self.big_blind) return payoffs def step_back(self): if len(self.history) > 0: self.round, r_raised, self.game_pointer, self.round_counter, d_deck, self.public_card, self.players, ps_hand = self.history.pop() self.round.raised = r_raised self.dealer.deck = d_deck for i, hand in enumerate(ps_hand): self.players[i].hand = hand return True return False
true
true
f7148a75a4e4a85ae3bd6f491ecb0aa85bbc5afc
471
py
Python
Python/Functions_base/Functions/replace_ElecNaming.py
DanielHuji-RB/RB-article
e5a9ba30edfb030db1cd3bcf562c6abff3f9d48e
[ "MIT" ]
null
null
null
Python/Functions_base/Functions/replace_ElecNaming.py
DanielHuji-RB/RB-article
e5a9ba30edfb030db1cd3bcf562c6abff3f9d48e
[ "MIT" ]
null
null
null
Python/Functions_base/Functions/replace_ElecNaming.py
DanielHuji-RB/RB-article
e5a9ba30edfb030db1cd3bcf562c6abff3f9d48e
[ "MIT" ]
null
null
null
#Daniel Sand import pandas as pd import numpy as np fileName='/Tscores.csv' newFileName='/Tscores_v3.csv' df=pd.read_csv(fileName, sep=',') #6 differnt electordes oldFormat=['0-1','0-2','0-3','2-Jan','3-Jan','3-Feb'] newFormat=['0_1','0_2','0_3','2_1','3_1','3_2'] for iCont in range(0, len(oldFormat)): currElec_old = oldFormat[iCont] currElec_new = newFormat[iCont] df.loc[df.Elec==currElec_old,'Elec']=currElec_new df.to_csv(path_or_buf=newFileName)
22.428571
53
0.696391
import pandas as pd import numpy as np fileName='/Tscores.csv' newFileName='/Tscores_v3.csv' df=pd.read_csv(fileName, sep=',') oldFormat=['0-1','0-2','0-3','2-Jan','3-Jan','3-Feb'] newFormat=['0_1','0_2','0_3','2_1','3_1','3_2'] for iCont in range(0, len(oldFormat)): currElec_old = oldFormat[iCont] currElec_new = newFormat[iCont] df.loc[df.Elec==currElec_old,'Elec']=currElec_new df.to_csv(path_or_buf=newFileName)
true
true
f7148acd3d12984fc7698af4459254aa88540a51
188
py
Python
setup.py
jjc2718/mpmp
9960d8d3e20e4fc9319e5420e083fece5bfb3d9e
[ "BSD-3-Clause" ]
1
2021-11-02T05:47:38.000Z
2021-11-02T05:47:38.000Z
setup.py
jjc2718/mpmp
9960d8d3e20e4fc9319e5420e083fece5bfb3d9e
[ "BSD-3-Clause" ]
63
2020-12-03T23:55:55.000Z
2022-03-29T17:55:29.000Z
setup.py
jjc2718/mpmp
9960d8d3e20e4fc9319e5420e083fece5bfb3d9e
[ "BSD-3-Clause" ]
3
2020-12-01T18:50:00.000Z
2022-02-18T12:32:38.000Z
from setuptools import setup setup( name='mpmp', author='Jake Crawford', version='0.0.1', description='Multimodal Pan-cancer Mutation Prediction', packages=['mpmp'] )
18.8
60
0.670213
from setuptools import setup setup( name='mpmp', author='Jake Crawford', version='0.0.1', description='Multimodal Pan-cancer Mutation Prediction', packages=['mpmp'] )
true
true
f7148c067979d0d62792963a826a42a813df0ab1
8,199
py
Python
ludwig/features/image_feature.py
ThinkBigAnalytics/ludwig
0a3159af4cc91f57251f3dec0cdb863c7003cf00
[ "Apache-2.0" ]
1
2019-07-31T19:11:02.000Z
2019-07-31T19:11:02.000Z
ludwig/features/image_feature.py
ThinkBigAnalytics/ludwig
0a3159af4cc91f57251f3dec0cdb863c7003cf00
[ "Apache-2.0" ]
null
null
null
ludwig/features/image_feature.py
ThinkBigAnalytics/ludwig
0a3159af4cc91f57251f3dec0cdb863c7003cf00
[ "Apache-2.0" ]
null
null
null
#! /usr/bin/env python # coding=utf-8 # Copyright (c) 2019 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import logging import os import h5py import numpy as np import tensorflow as tf from skimage.io import imread from ludwig.constants import * from ludwig.features.base_feature import BaseFeature from ludwig.features.base_feature import InputFeature from ludwig.models.modules.image_encoders import ResNetEncoder from ludwig.models.modules.image_encoders import Stacked2DCNN from ludwig.utils.image_utils import resize_image from ludwig.utils.misc import get_from_registry from ludwig.utils.misc import set_default_value class ImageBaseFeature(BaseFeature): def __init__(self, feature): super().__init__(feature) self.type = IMAGE preprocessing_defaults = { 'missing_value_strategy': BACKFILL, 'in_memory': True, 'resize_method': 'crop_or_pad' } @staticmethod def get_feature_meta(column, preprocessing_parameters): return { 'preprocessing': preprocessing_parameters } @staticmethod def add_feature_data( feature, dataset_df, data, metadata, preprocessing_parameters ): set_default_value( feature, 'in_memory', preprocessing_parameters['in_memory'] ) if ('height' in preprocessing_parameters or 'width' in preprocessing_parameters): should_resize = True try: provided_height = int(preprocessing_parameters[HEIGHT]) provided_width = int(preprocessing_parameters[WIDTH]) except ValueError as e: raise ValueError( 'Image height and width must be set and have ' 'positive integer values: ' + str(e) ) if (provided_height <= 0 or provided_width <= 0): raise ValueError( 'Image height and width must be positive integers' ) else: should_resize = False csv_path = os.path.dirname(os.path.abspath(dataset_df.csv)) num_images = len(dataset_df) height = 0 width = 0 num_channels = 1 if num_images > 0: # here if a width and height have not been specified # we assume that all images have the same wifth and im_height # thus the width and height of the first one are the same # of all the other ones first_image = imread( os.path.join(csv_path, dataset_df[feature['name']][0]) ) height = first_image.shape[0] width = first_image.shape[1] if first_image.ndim == 2: num_channels = 1 else: num_channels = first_image.shape[2] if should_resize: height = provided_height width = provided_width metadata[feature['name']]['preprocessing']['height'] = height metadata[feature['name']]['preprocessing']['width'] = width metadata[feature['name']]['preprocessing'][ 'num_channels'] = num_channels if feature['in_memory']: data[feature['name']] = np.empty( (num_images, height, width, num_channels), dtype=np.int8 ) for i in range(len(dataset_df)): filename = os.path.join( csv_path, dataset_df[feature['name']][i] ) img = imread(filename) if img.ndim == 2: img = img.reshape((img.shape[0], img.shape[1], 1)) if should_resize: img = resize_image( img, (height, width), preprocessing_parameters['resize_method'] ) data[feature['name']][i, :, :, :] = img else: data_fp = os.path.splitext(dataset_df.csv)[0] + '.hdf5' mode = 'w' if os.path.isfile(data_fp): mode = 'r+' with h5py.File(data_fp, mode) as h5_file: image_dataset = h5_file.create_dataset( feature['name'] + '_data', (num_images, height, width, num_channels), dtype=np.uint8 ) for i in range(len(dataset_df)): filename = os.path.join( csv_path, dataset_df[feature['name']][i] ) img = imread(filename) if img.ndim == 2: img = img.reshape((img.shape[0], img.shape[1], 1)) if should_resize: img = resize_image( img, (height, width), preprocessing_parameters['resize_method'], ) image_dataset[i, :height, :width, :] = img data[feature['name']] = np.arange(num_images) class ImageInputFeature(ImageBaseFeature, InputFeature): def __init__(self, feature): super().__init__(feature) self.height = 0 self.width = 0 self.num_channels = 0 self.in_memory = True self.data_hdf5_fp = '' self.encoder = 'stacked_cnn' encoder_parameters = self.overwrite_defaults(feature) self.encoder_obj = self.get_image_encoder(encoder_parameters) def get_image_encoder(self, encoder_parameters): return get_from_registry( self.encoder, image_encoder_registry)( **encoder_parameters ) def _get_input_placeholder(self): # None dimension is for dealing with variable batch size return tf.placeholder( tf.float32, shape=[None, self.height, self.width, self.num_channels], name=self.name, ) def build_input( self, regularizer, dropout_rate, is_training=False, **kwargs ): placeholder = self._get_input_placeholder() logging.debug(' targets_placeholder: {0}'.format(placeholder)) feature_representation, feature_representation_size = self.encoder_obj( placeholder, regularizer, dropout_rate, is_training, ) logging.debug( ' feature_representation: {0}'.format(feature_representation) ) feature_representation = { 'name': self.name, 'type': self.type, 'representation': feature_representation, 'size': feature_representation_size, 'placeholder': placeholder } return feature_representation @staticmethod def update_model_definition_with_metadata( input_feature, feature_metadata, *args, **kwargs ): for dim in ['height', 'width', 'num_channels']: input_feature[dim] = feature_metadata['preprocessing'][dim] input_feature['data_hdf5_fp'] = ( kwargs['model_definition']['data_hdf5_fp'] ) @staticmethod def populate_defaults(input_feature): set_default_value(input_feature, 'tied_weights', None) image_encoder_registry = { 'stacked_cnn': Stacked2DCNN, 'resnet': ResNetEncoder }
32.796
80
0.558971
import logging import os import h5py import numpy as np import tensorflow as tf from skimage.io import imread from ludwig.constants import * from ludwig.features.base_feature import BaseFeature from ludwig.features.base_feature import InputFeature from ludwig.models.modules.image_encoders import ResNetEncoder from ludwig.models.modules.image_encoders import Stacked2DCNN from ludwig.utils.image_utils import resize_image from ludwig.utils.misc import get_from_registry from ludwig.utils.misc import set_default_value class ImageBaseFeature(BaseFeature): def __init__(self, feature): super().__init__(feature) self.type = IMAGE preprocessing_defaults = { 'missing_value_strategy': BACKFILL, 'in_memory': True, 'resize_method': 'crop_or_pad' } @staticmethod def get_feature_meta(column, preprocessing_parameters): return { 'preprocessing': preprocessing_parameters } @staticmethod def add_feature_data( feature, dataset_df, data, metadata, preprocessing_parameters ): set_default_value( feature, 'in_memory', preprocessing_parameters['in_memory'] ) if ('height' in preprocessing_parameters or 'width' in preprocessing_parameters): should_resize = True try: provided_height = int(preprocessing_parameters[HEIGHT]) provided_width = int(preprocessing_parameters[WIDTH]) except ValueError as e: raise ValueError( 'Image height and width must be set and have ' 'positive integer values: ' + str(e) ) if (provided_height <= 0 or provided_width <= 0): raise ValueError( 'Image height and width must be positive integers' ) else: should_resize = False csv_path = os.path.dirname(os.path.abspath(dataset_df.csv)) num_images = len(dataset_df) height = 0 width = 0 num_channels = 1 if num_images > 0: first_image = imread( os.path.join(csv_path, dataset_df[feature['name']][0]) ) height = first_image.shape[0] width = first_image.shape[1] if first_image.ndim == 2: num_channels = 1 else: num_channels = first_image.shape[2] if should_resize: height = provided_height width = provided_width metadata[feature['name']]['preprocessing']['height'] = height metadata[feature['name']]['preprocessing']['width'] = width metadata[feature['name']]['preprocessing'][ 'num_channels'] = num_channels if feature['in_memory']: data[feature['name']] = np.empty( (num_images, height, width, num_channels), dtype=np.int8 ) for i in range(len(dataset_df)): filename = os.path.join( csv_path, dataset_df[feature['name']][i] ) img = imread(filename) if img.ndim == 2: img = img.reshape((img.shape[0], img.shape[1], 1)) if should_resize: img = resize_image( img, (height, width), preprocessing_parameters['resize_method'] ) data[feature['name']][i, :, :, :] = img else: data_fp = os.path.splitext(dataset_df.csv)[0] + '.hdf5' mode = 'w' if os.path.isfile(data_fp): mode = 'r+' with h5py.File(data_fp, mode) as h5_file: image_dataset = h5_file.create_dataset( feature['name'] + '_data', (num_images, height, width, num_channels), dtype=np.uint8 ) for i in range(len(dataset_df)): filename = os.path.join( csv_path, dataset_df[feature['name']][i] ) img = imread(filename) if img.ndim == 2: img = img.reshape((img.shape[0], img.shape[1], 1)) if should_resize: img = resize_image( img, (height, width), preprocessing_parameters['resize_method'], ) image_dataset[i, :height, :width, :] = img data[feature['name']] = np.arange(num_images) class ImageInputFeature(ImageBaseFeature, InputFeature): def __init__(self, feature): super().__init__(feature) self.height = 0 self.width = 0 self.num_channels = 0 self.in_memory = True self.data_hdf5_fp = '' self.encoder = 'stacked_cnn' encoder_parameters = self.overwrite_defaults(feature) self.encoder_obj = self.get_image_encoder(encoder_parameters) def get_image_encoder(self, encoder_parameters): return get_from_registry( self.encoder, image_encoder_registry)( **encoder_parameters ) def _get_input_placeholder(self): return tf.placeholder( tf.float32, shape=[None, self.height, self.width, self.num_channels], name=self.name, ) def build_input( self, regularizer, dropout_rate, is_training=False, **kwargs ): placeholder = self._get_input_placeholder() logging.debug(' targets_placeholder: {0}'.format(placeholder)) feature_representation, feature_representation_size = self.encoder_obj( placeholder, regularizer, dropout_rate, is_training, ) logging.debug( ' feature_representation: {0}'.format(feature_representation) ) feature_representation = { 'name': self.name, 'type': self.type, 'representation': feature_representation, 'size': feature_representation_size, 'placeholder': placeholder } return feature_representation @staticmethod def update_model_definition_with_metadata( input_feature, feature_metadata, *args, **kwargs ): for dim in ['height', 'width', 'num_channels']: input_feature[dim] = feature_metadata['preprocessing'][dim] input_feature['data_hdf5_fp'] = ( kwargs['model_definition']['data_hdf5_fp'] ) @staticmethod def populate_defaults(input_feature): set_default_value(input_feature, 'tied_weights', None) image_encoder_registry = { 'stacked_cnn': Stacked2DCNN, 'resnet': ResNetEncoder }
true
true
f7148ccd4e901a2e9e3c5c5b644f2f81ee5e045c
133,646
py
Python
tensorflow/python/keras/layers/convolutional.py
devinlife/tensorflow
1445444c15a396410f25ae91b7d1c19d724e2afc
[ "Apache-2.0" ]
8
2020-07-29T18:50:45.000Z
2021-07-25T07:06:43.000Z
tensorflow/python/keras/layers/convolutional.py
devinlife/tensorflow
1445444c15a396410f25ae91b7d1c19d724e2afc
[ "Apache-2.0" ]
203
2019-06-14T23:53:10.000Z
2022-02-10T02:27:23.000Z
tensorflow/python/keras/layers/convolutional.py
devinlife/tensorflow
1445444c15a396410f25ae91b7d1c19d724e2afc
[ "Apache-2.0" ]
11
2020-05-31T13:14:56.000Z
2021-12-14T04:39:25.000Z
# Copyright 2015 The TensorFlow 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. # ============================================================================== """Keras convolution layers and image transformation layers. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.eager import context from tensorflow.python.framework import tensor_shape from tensorflow.python.keras import activations from tensorflow.python.keras import backend from tensorflow.python.keras import constraints from tensorflow.python.keras import initializers from tensorflow.python.keras import regularizers from tensorflow.python.keras.engine.base_layer import Layer from tensorflow.python.keras.engine.input_spec import InputSpec # imports for backwards namespace compatibility # pylint: disable=unused-import from tensorflow.python.keras.layers.pooling import AveragePooling1D from tensorflow.python.keras.layers.pooling import AveragePooling2D from tensorflow.python.keras.layers.pooling import AveragePooling3D from tensorflow.python.keras.layers.pooling import MaxPooling1D from tensorflow.python.keras.layers.pooling import MaxPooling2D from tensorflow.python.keras.layers.pooling import MaxPooling3D # pylint: enable=unused-import from tensorflow.python.keras.utils import conv_utils from tensorflow.python.keras.utils import tf_utils from tensorflow.python.ops import array_ops from tensorflow.python.ops import nn from tensorflow.python.ops import nn_ops from tensorflow.python.util.tf_export import keras_export # pylint: disable=g-classes-have-attributes class Conv(Layer): """Abstract N-D convolution layer (private, used as implementation base). This layer creates a convolution kernel that is convolved (actually cross-correlated) with the layer input to produce a tensor of outputs. If `use_bias` is True (and a `bias_initializer` is provided), a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. Note: layer attributes cannot be modified after the layer has been called once (except the `trainable` attribute). Arguments: rank: An integer, the rank of the convolution, e.g. "2" for 2D convolution. filters: Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). kernel_size: An integer or tuple/list of n integers, specifying the length of the convolution window. strides: An integer or tuple/list of n integers, specifying the stride length of the convolution. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: One of `"valid"`, `"same"`, or `"causal"` (case-insensitive). data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, ..., channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, ...)`. dilation_rate: An integer or tuple/list of n integers, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. activation: Activation function to use. If you don't specify anything, no activation is applied. use_bias: Boolean, whether the layer uses a bias. kernel_initializer: An initializer for the convolution kernel. bias_initializer: An initializer for the bias vector. If None, the default initializer will be used. kernel_regularizer: Optional regularizer for the convolution kernel. bias_regularizer: Optional regularizer for the bias vector. activity_regularizer: Optional regularizer function for the output. kernel_constraint: Optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. bias_constraint: Optional projection function to be applied to the bias after being updated by an `Optimizer`. trainable: Boolean, if `True` the weights of this layer will be marked as trainable (and listed in `layer.trainable_weights`). name: A string, the name of the layer. """ def __init__(self, rank, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, trainable=True, name=None, **kwargs): super(Conv, self).__init__( trainable=trainable, name=name, activity_regularizer=regularizers.get(activity_regularizer), **kwargs) self.rank = rank if filters is not None and not isinstance(filters, int): filters = int(filters) self.filters = filters self.kernel_size = conv_utils.normalize_tuple( kernel_size, rank, 'kernel_size') if not all(self.kernel_size): raise ValueError('The argument `kernel_size` cannot contain 0(s). ' 'Received: %s' % (kernel_size,)) self.strides = conv_utils.normalize_tuple(strides, rank, 'strides') self.padding = conv_utils.normalize_padding(padding) if (self.padding == 'causal' and not isinstance(self, (Conv1D, SeparableConv1D))): raise ValueError('Causal padding is only supported for `Conv1D`' 'and ``SeparableConv1D`.') self.data_format = conv_utils.normalize_data_format(data_format) self.dilation_rate = conv_utils.normalize_tuple( dilation_rate, rank, 'dilation_rate') self.activation = activations.get(activation) self.use_bias = use_bias self.kernel_initializer = initializers.get(kernel_initializer) self.bias_initializer = initializers.get(bias_initializer) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) self.input_spec = InputSpec(ndim=self.rank + 2) def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) input_channel = self._get_input_channel(input_shape) kernel_shape = self.kernel_size + (input_channel, self.filters) self.kernel = self.add_weight( name='kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None channel_axis = self._get_channel_axis() self.input_spec = InputSpec(ndim=self.rank + 2, axes={channel_axis: input_channel}) self._build_conv_op_input_shape = input_shape self._build_input_channel = input_channel self._padding_op = self._get_padding_op() self._conv_op_data_format = conv_utils.convert_data_format( self.data_format, self.rank + 2) self._convolution_op = nn_ops.Convolution( input_shape, filter_shape=self.kernel.shape, dilation_rate=self.dilation_rate, strides=self.strides, padding=self._padding_op, data_format=self._conv_op_data_format) self.built = True def call(self, inputs): if self._recreate_conv_op(inputs): self._convolution_op = nn_ops.Convolution( inputs.get_shape(), filter_shape=self.kernel.shape, dilation_rate=self.dilation_rate, strides=self.strides, padding=self._padding_op, data_format=self._conv_op_data_format) self._build_conv_op_input_shape = inputs.get_shape() # Apply causal padding to inputs for Conv1D. if self.padding == 'causal' and self.__class__.__name__ == 'Conv1D': inputs = array_ops.pad(inputs, self._compute_causal_padding()) outputs = self._convolution_op(inputs, self.kernel) if self.use_bias: if self.data_format == 'channels_first': if self.rank == 1: # nn.bias_add does not accept a 1D input tensor. bias = array_ops.reshape(self.bias, (1, self.filters, 1)) outputs += bias else: outputs = nn.bias_add(outputs, self.bias, data_format='NCHW') else: outputs = nn.bias_add(outputs, self.bias, data_format='NHWC') if self.activation is not None: return self.activation(outputs) return outputs def _spatial_output_shape(self, spatial_input_shape): return [ conv_utils.conv_output_length( length, self.kernel_size[i], padding=self.padding, stride=self.strides[i], dilation=self.dilation_rate[i]) for i, length in enumerate(spatial_input_shape) ] def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_last': return tensor_shape.TensorShape( [input_shape[0]] + self._spatial_output_shape(input_shape[1:-1]) + [self.filters]) else: return tensor_shape.TensorShape( [input_shape[0], self.filters] + self._spatial_output_shape(input_shape[2:])) def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'data_format': self.data_format, 'dilation_rate': self.dilation_rate, 'activation': activations.serialize(self.activation), 'use_bias': self.use_bias, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint) } base_config = super(Conv, self).get_config() return dict(list(base_config.items()) + list(config.items())) def _compute_causal_padding(self): """Calculates padding for 'causal' option for 1-d conv layers.""" left_pad = self.dilation_rate[0] * (self.kernel_size[0] - 1) if self.data_format == 'channels_last': causal_padding = [[0, 0], [left_pad, 0], [0, 0]] else: causal_padding = [[0, 0], [0, 0], [left_pad, 0]] return causal_padding def _get_channel_axis(self): if self.data_format == 'channels_first': return 1 else: return -1 def _get_input_channel(self, input_shape): channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') return int(input_shape[channel_axis]) def _get_padding_op(self): if self.padding == 'causal': op_padding = 'valid' else: op_padding = self.padding if not isinstance(op_padding, (list, tuple)): op_padding = op_padding.upper() return op_padding def _recreate_conv_op(self, inputs): """Recreate conv_op if necessary. Check if the input_shape in call() is different from that in build(). If the most-specific input shape describing the build and call shapes is not equal to the shape we currently built with, then we need to rebuild the _convolution_op to avoid incorrect behavior. Args: inputs: The input data to call() method. Returns: `True` or `False` to indicate whether to recreate the conv_op. """ call_input_shape = inputs.get_shape() # If the most specific compatible shape between _build_input_shape and # call_input_shape is not _build_input_shape then we must re-build. return self._build_conv_op_input_shape.most_specific_compatible_shape( call_input_shape) != self._build_conv_op_input_shape @keras_export('keras.layers.Conv1D', 'keras.layers.Convolution1D') class Conv1D(Conv): """1D convolution layer (e.g. temporal convolution). This layer creates a convolution kernel that is convolved with the layer input over a single spatial (or temporal) dimension to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. When using this layer as the first layer in a model, provide an `input_shape` argument (tuple of integers or `None`, e.g. `(10, 128)` for sequences of 10 vectors of 128-dimensional vectors, or `(None, 128)` for variable-length sequences of 128-dimensional vectors. Examples: >>> # The inputs are 128-length vectors with 10 timesteps, and the batch size >>> # is 4. >>> input_shape = (4, 10, 128) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv1D( ... 32, 3, activation='relu',input_shape=input_shape)(x) >>> print(y.shape) (4, 8, 32) Arguments: filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of a single integer, specifying the length of the 1D convolution window. strides: An integer or tuple/list of a single integer, specifying the stride length of the convolution. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: One of `"valid"`, `"causal"` or `"same"` (case-insensitive). `"causal"` results in causal (dilated) convolutions, e.g. `output[t]` does not depend on `input[t+1:]`. Useful when modeling temporal data where the model should not violate the temporal order. See [WaveNet: A Generative Model for Raw Audio, section 2.1](https://arxiv.org/abs/1609.03499). data_format: A string, one of `channels_last` (default) or `channels_first`. dilation_rate: an integer or tuple/list of a single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. activation: Activation function to use. If you don't specify anything, no activation is applied ( see `keras.activations`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix ( see `keras.initializers`). bias_initializer: Initializer for the bias vector ( see `keras.initializers`). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see `keras.regularizers`). bias_regularizer: Regularizer function applied to the bias vector ( see `keras.regularizers`). activity_regularizer: Regularizer function applied to the output of the layer (its "activation") ( see `keras.regularizers`). kernel_constraint: Constraint function applied to the kernel matrix ( see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector ( see `keras.constraints`). Input shape: 3D tensor with shape: `(batch_size, steps, input_dim)` Output shape: 3D tensor with shape: `(batch_size, new_steps, filters)` `steps` value might have changed due to padding or strides. Returns: A tensor of rank 3 representing `activation(conv1d(inputs, kernel) + bias)`. Raises: ValueError: when both `strides` > 1 and `dilation_rate` > 1. """ def __init__(self, filters, kernel_size, strides=1, padding='valid', data_format='channels_last', dilation_rate=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv1D, self).__init__( rank=1, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) @keras_export('keras.layers.Conv2D', 'keras.layers.Convolution2D') class Conv2D(Conv): """2D convolution layer (e.g. spatial convolution over images). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures in `data_format="channels_last"`. Examples: >>> # The inputs are 28x28 RGB images with `channels_last` and the batch >>> # size is 4. >>> input_shape = (4, 28, 28, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv2D( ... 2, 3, activation='relu', input_shape=input_shape)(x) >>> print(y.shape) (4, 26, 26, 2) >>> # With `dilation_rate` as 2. >>> input_shape = (4, 28, 28, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv2D( ... 2, 3, activation='relu', dilation_rate=2, input_shape=input_shape)(x) >>> print(y.shape) (4, 24, 24, 2) >>> # With `padding` as "same". >>> input_shape = (4, 28, 28, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv2D( ... 2, 3, activation='relu', padding="same", input_shape=input_shape)(x) >>> print(y.shape) (4, 28, 28, 2) Arguments: filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. activation: Activation function to use. If you don't specify anything, no activation is applied ( see `keras.activations`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix ( see `keras.initializers`). bias_initializer: Initializer for the bias vector ( see `keras.initializers`). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see `keras.regularizers`). bias_regularizer: Regularizer function applied to the bias vector ( see `keras.regularizers`). activity_regularizer: Regularizer function applied to the output of the layer (its "activation") ( see `keras.regularizers`). kernel_constraint: Constraint function applied to the kernel matrix ( see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector ( see `keras.constraints`). Input shape: 4D tensor with shape: `(batch_size, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(batch_size, rows, cols, channels)` if data_format='channels_last'. Output shape: 4D tensor with shape: `(batch_size, filters, new_rows, new_cols)` if data_format='channels_first' or 4D tensor with shape: `(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to padding. Returns: A tensor of rank 4 representing `activation(conv2d(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". ValueError: when both `strides` > 1 and `dilation_rate` > 1. """ def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv2D, self).__init__( rank=2, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) @keras_export('keras.layers.Conv3D', 'keras.layers.Convolution3D') class Conv3D(Conv): """3D convolution layer (e.g. spatial convolution over volumes). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If `use_bias` is True, a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(128, 128, 128, 1)` for 128x128x128 volumes with a single channel, in `data_format="channels_last"`. Examples: >>> # The inputs are 28x28x28 volumes with a single channel, and the >>> # batch size is 4 >>> input_shape =(4, 28, 28, 28, 1) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.Conv3D( ... 2, 3, activation='relu', input_shape=input_shape)(x) >>> print(y.shape) (4, 26, 26, 26, 2) Arguments: filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 3 integers, specifying the depth, height and width of the 3D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 3 integers, specifying the strides of the convolution along each spatial dimension. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: an integer or tuple/list of 3 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. activation: Activation function to use. If you don't specify anything, no activation is applied ( see `keras.activations`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix ( see `keras.initializers`). bias_initializer: Initializer for the bias vector ( see `keras.initializers`). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix ( see `keras.regularizers`). bias_regularizer: Regularizer function applied to the bias vector ( see `keras.regularizers`). activity_regularizer: Regularizer function applied to the output of the layer (its "activation") ( see `keras.regularizers`). kernel_constraint: Constraint function applied to the kernel matrix ( see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector ( see `keras.constraints`). Input shape: 5D tensor with shape: `(batch_size, channels, conv_dim1, conv_dim2, conv_dim3)` if data_format='channels_first' or 5D tensor with shape: `(batch_size, conv_dim1, conv_dim2, conv_dim3, channels)` if data_format='channels_last'. Output shape: 5D tensor with shape: `(batch_size, filters, new_conv_dim1, new_conv_dim2, new_conv_dim3)` if data_format='channels_first' or 5D tensor with shape: `(batch_size, new_conv_dim1, new_conv_dim2, new_conv_dim3, filters)` if data_format='channels_last'. `new_conv_dim1`, `new_conv_dim2` and `new_conv_dim3` values might have changed due to padding. Returns: A tensor of rank 5 representing `activation(conv3d(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". ValueError: when both `strides` > 1 and `dilation_rate` > 1. """ def __init__(self, filters, kernel_size, strides=(1, 1, 1), padding='valid', data_format=None, dilation_rate=(1, 1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv3D, self).__init__( rank=3, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) @keras_export('keras.layers.Conv1DTranspose', 'keras.layers.Convolution1DTranspose') class Conv1DTranspose(Conv1D): """Transposed convolution layer (sometimes called Deconvolution). The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(128, 3)` for data with 128 time steps and 3 channels. Arguments: filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer length of the 1D convolution window. strides: An integer specifying the stride of the convolution along the time dimension. Specifying a stride value != 1 is incompatible with specifying a `dilation_rate` value != 1. Defaults to 1. padding: one of `"valid"` or `"same"` (case-insensitive). output_padding: An integer specifying the amount of padding along the time dimension of the output tensor. The amount of output padding must be lower than the stride. If set to `None` (default), the output shape is inferred. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, length, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, length)`. dilation_rate: an integer, specifying the dilation rate to use for dilated convolution. Currently, specifying a `dilation_rate` value != 1 is incompatible with specifying a stride value != 1. activation: Activation function to use. If you don't specify anything, no activation is applied ( see `keras.activations`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix ( see `keras.initializers`). bias_initializer: Initializer for the bias vector ( see `keras.initializers`). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see `keras.regularizers`). bias_regularizer: Regularizer function applied to the bias vector ( see `keras.regularizers`). activity_regularizer: Regularizer function applied to the output of the layer (its "activation") (see `keras.regularizers`). kernel_constraint: Constraint function applied to the kernel matrix ( see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector ( see `keras.constraints`). Input shape: 3D tensor with shape: `(batch_size, steps, channels)` Output shape: 3D tensor with shape: `(batch_size, new_steps, filters)` If `output_padding` is specified: ``` new_timesteps = ((timesteps - 1) * strides + kernel_size - 2 * padding + output_padding) ``` Returns: A tensor of rank 3 representing `activation(conv1dtranspose(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". ValueError: when both `strides` > 1 and `dilation_rate` > 1. References: - [A guide to convolution arithmetic for deep learning]( https://arxiv.org/abs/1603.07285v1) - [Deconvolutional Networks]( https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf) """ def __init__(self, filters, kernel_size, strides=1, padding='valid', output_padding=None, data_format=None, dilation_rate=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv1DTranspose, self).__init__( filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) self.output_padding = output_padding if self.output_padding is not None: self.output_padding = conv_utils.normalize_tuple( self.output_padding, 1, 'output_padding') for stride, out_pad in zip(self.strides, self.output_padding): if out_pad >= stride: raise ValueError('Stride ' + str(self.strides) + ' must be ' 'greater than output padding ' + str(self.output_padding)) def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) if len(input_shape) != 3: raise ValueError('Inputs should have rank 3. Received input shape: ' + str(input_shape)) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = int(input_shape[channel_axis]) self.input_spec = InputSpec(ndim=3, axes={channel_axis: input_dim}) kernel_shape = self.kernel_size + (self.filters, input_dim) self.kernel = self.add_weight( name='kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): inputs_shape = array_ops.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': t_axis = 2 else: t_axis = 1 length = inputs_shape[t_axis] if self.output_padding is None: output_padding = None else: output_padding = self.output_padding[0] # Infer the dynamic output shape: out_length = conv_utils.deconv_output_length( length, self.kernel_size[0], padding=self.padding, output_padding=output_padding, stride=self.strides[0], dilation=self.dilation_rate[0]) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_length) else: output_shape = (batch_size, out_length, self.filters) data_format = conv_utils.convert_data_format(self.data_format, ndim=3) output_shape_tensor = array_ops.stack(output_shape) outputs = nn_ops.conv1d_transpose( inputs, self.kernel, output_shape_tensor, strides=self.strides, padding=self.padding.upper(), data_format=data_format, dilations=self.dilation_rate) if not context.executing_eagerly(): # Infer the static output shape: out_shape = self.compute_output_shape(inputs.shape) outputs.set_shape(out_shape) if self.use_bias: outputs = nn.bias_add( outputs, self.bias, data_format=data_format) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, t_axis = 1, 2 else: c_axis, t_axis = 2, 1 if self.output_padding is None: output_padding = None else: output_padding = self.output_padding[0] output_shape[c_axis] = self.filters output_shape[t_axis] = conv_utils.deconv_output_length( output_shape[t_axis], self.kernel_size[0], padding=self.padding, output_padding=output_padding, stride=self.strides[0], dilation=self.dilation_rate[0]) return tensor_shape.TensorShape(output_shape) def get_config(self): config = super(Conv1DTranspose, self).get_config() config['output_padding'] = self.output_padding return config @keras_export('keras.layers.Conv2DTranspose', 'keras.layers.Convolution2DTranspose') class Conv2DTranspose(Conv2D): """Transposed convolution layer (sometimes called Deconvolution). The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures in `data_format="channels_last"`. Arguments: filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). output_padding: An integer or tuple/list of 2 integers, specifying the amount of padding along the height and width of the output tensor. Can be a single integer to specify the same value for all spatial dimensions. The amount of output padding along a given dimension must be lower than the stride along that same dimension. If set to `None` (default), the output shape is inferred. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. activation: Activation function to use. If you don't specify anything, no activation is applied ( see `keras.activations`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix ( see `keras.initializers`). bias_initializer: Initializer for the bias vector ( see `keras.initializers`). kernel_regularizer: Regularizer function applied to the `kernel` weights matrix (see `keras.regularizers`). bias_regularizer: Regularizer function applied to the bias vector ( see `keras.regularizers`). activity_regularizer: Regularizer function applied to the output of the layer (its "activation") (see `keras.regularizers`). kernel_constraint: Constraint function applied to the kernel matrix ( see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector ( see `keras.constraints`). Input shape: 4D tensor with shape: `(batch_size, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(batch_size, rows, cols, channels)` if data_format='channels_last'. Output shape: 4D tensor with shape: `(batch_size, filters, new_rows, new_cols)` if data_format='channels_first' or 4D tensor with shape: `(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to padding. If `output_padding` is specified: ``` new_rows = ((rows - 1) * strides[0] + kernel_size[0] - 2 * padding[0] + output_padding[0]) new_cols = ((cols - 1) * strides[1] + kernel_size[1] - 2 * padding[1] + output_padding[1]) ``` Returns: A tensor of rank 4 representing `activation(conv2dtranspose(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". ValueError: when both `strides` > 1 and `dilation_rate` > 1. References: - [A guide to convolution arithmetic for deep learning](https://arxiv.org/abs/1603.07285v1) - [Deconvolutional Networks](https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf) """ def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', output_padding=None, data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv2DTranspose, self).__init__( filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) self.output_padding = output_padding if self.output_padding is not None: self.output_padding = conv_utils.normalize_tuple( self.output_padding, 2, 'output_padding') for stride, out_pad in zip(self.strides, self.output_padding): if out_pad >= stride: raise ValueError('Stride ' + str(self.strides) + ' must be ' 'greater than output padding ' + str(self.output_padding)) def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) if len(input_shape) != 4: raise ValueError('Inputs should have rank 4. Received input shape: ' + str(input_shape)) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = int(input_shape[channel_axis]) self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) kernel_shape = self.kernel_size + (self.filters, input_dim) self.kernel = self.add_weight( name='kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): inputs_shape = array_ops.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': h_axis, w_axis = 2, 3 else: h_axis, w_axis = 1, 2 # Use the constant height and weight when possible. # TODO(scottzhu): Extract this into a utility function that can be applied # to all convolutional layers, which currently lost the static shape # information due to tf.shape(). height, width = None, None if inputs.shape.rank is not None: dims = inputs.shape.as_list() height = dims[h_axis] width = dims[w_axis] height = height if height is not None else inputs_shape[h_axis] width = width if width is not None else inputs_shape[w_axis] kernel_h, kernel_w = self.kernel_size stride_h, stride_w = self.strides if self.output_padding is None: out_pad_h = out_pad_w = None else: out_pad_h, out_pad_w = self.output_padding # Infer the dynamic output shape: out_height = conv_utils.deconv_output_length(height, kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h, dilation=self.dilation_rate[0]) out_width = conv_utils.deconv_output_length(width, kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w, dilation=self.dilation_rate[1]) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_height, out_width) else: output_shape = (batch_size, out_height, out_width, self.filters) output_shape_tensor = array_ops.stack(output_shape) outputs = backend.conv2d_transpose( inputs, self.kernel, output_shape_tensor, strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate) if not context.executing_eagerly(): # Infer the static output shape: out_shape = self.compute_output_shape(inputs.shape) outputs.set_shape(out_shape) if self.use_bias: outputs = nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, h_axis, w_axis = 1, 2, 3 else: c_axis, h_axis, w_axis = 3, 1, 2 kernel_h, kernel_w = self.kernel_size stride_h, stride_w = self.strides if self.output_padding is None: out_pad_h = out_pad_w = None else: out_pad_h, out_pad_w = self.output_padding output_shape[c_axis] = self.filters output_shape[h_axis] = conv_utils.deconv_output_length( output_shape[h_axis], kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h, dilation=self.dilation_rate[0]) output_shape[w_axis] = conv_utils.deconv_output_length( output_shape[w_axis], kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w, dilation=self.dilation_rate[1]) return tensor_shape.TensorShape(output_shape) def get_config(self): config = super(Conv2DTranspose, self).get_config() config['output_padding'] = self.output_padding return config @keras_export('keras.layers.Conv3DTranspose', 'keras.layers.Convolution3DTranspose') class Conv3DTranspose(Conv3D): """Transposed convolution layer (sometimes called Deconvolution). The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. When using this layer as the first layer in a model, provide the keyword argument `input_shape` (tuple of integers, does not include the sample axis), e.g. `input_shape=(128, 128, 128, 3)` for a 128x128x128 volume with 3 channels if `data_format="channels_last"`. Arguments: filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 3 integers, specifying the depth, height and width of the 3D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 3 integers, specifying the strides of the convolution along the depth, height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). output_padding: An integer or tuple/list of 3 integers, specifying the amount of padding along the depth, height, and width. Can be a single integer to specify the same value for all spatial dimensions. The amount of output padding along a given dimension must be lower than the stride along that same dimension. If set to `None` (default), the output shape is inferred. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, depth, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: an integer or tuple/list of 3 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. activation: Activation function to use. If you don't specify anything, no activation is applied ( see `keras.activations`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix. bias_initializer: Initializer for the bias vector. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix ( see `keras.regularizers`). bias_regularizer: Regularizer function applied to the bias vector ( see `keras.regularizers`). activity_regularizer: Regularizer function applied to the output of the layer (its "activation") ( see `keras.regularizers`). kernel_constraint: Constraint function applied to the kernel matrix ( see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector ( see `keras.constraints`). Input shape: 5D tensor with shape: `(batch_size, channels, depth, rows, cols)` if data_format='channels_first' or 5D tensor with shape: `(batch_size, depth, rows, cols, channels)` if data_format='channels_last'. Output shape: 5D tensor with shape: `(batch_size, filters, new_depth, new_rows, new_cols)` if data_format='channels_first' or 5D tensor with shape: `(batch_size, new_depth, new_rows, new_cols, filters)` if data_format='channels_last'. `depth` and `rows` and `cols` values might have changed due to padding. If `output_padding` is specified:: ``` new_depth = ((depth - 1) * strides[0] + kernel_size[0] - 2 * padding[0] + output_padding[0]) new_rows = ((rows - 1) * strides[1] + kernel_size[1] - 2 * padding[1] + output_padding[1]) new_cols = ((cols - 1) * strides[2] + kernel_size[2] - 2 * padding[2] + output_padding[2]) ``` Returns: A tensor of rank 5 representing `activation(conv3dtranspose(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". ValueError: when both `strides` > 1 and `dilation_rate` > 1. References: - [A guide to convolution arithmetic for deep learning](https://arxiv.org/abs/1603.07285v1) - [Deconvolutional Networks](https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf) """ def __init__(self, filters, kernel_size, strides=(1, 1, 1), padding='valid', output_padding=None, data_format=None, dilation_rate=(1, 1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv3DTranspose, self).__init__( filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) self.output_padding = output_padding if self.output_padding is not None: self.output_padding = conv_utils.normalize_tuple( self.output_padding, 3, 'output_padding') for stride, out_pad in zip(self.strides, self.output_padding): if out_pad >= stride: raise ValueError('Stride ' + str(self.strides) + ' must be ' 'greater than output padding ' + str(self.output_padding)) def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) if len(input_shape) != 5: raise ValueError('Inputs should have rank 5, received input shape:', str(input_shape)) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'should be defined, found None: ' + str(input_shape)) input_dim = int(input_shape[channel_axis]) kernel_shape = self.kernel_size + (self.filters, input_dim) self.input_spec = InputSpec(ndim=5, axes={channel_axis: input_dim}) self.kernel = self.add_weight( 'kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( 'bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): inputs_shape = array_ops.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': d_axis, h_axis, w_axis = 2, 3, 4 else: d_axis, h_axis, w_axis = 1, 2, 3 depth = inputs_shape[d_axis] height = inputs_shape[h_axis] width = inputs_shape[w_axis] kernel_d, kernel_h, kernel_w = self.kernel_size stride_d, stride_h, stride_w = self.strides if self.output_padding is None: out_pad_d = out_pad_h = out_pad_w = None else: out_pad_d, out_pad_h, out_pad_w = self.output_padding # Infer the dynamic output shape: out_depth = conv_utils.deconv_output_length(depth, kernel_d, padding=self.padding, output_padding=out_pad_d, stride=stride_d) out_height = conv_utils.deconv_output_length(height, kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h) out_width = conv_utils.deconv_output_length(width, kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_depth, out_height, out_width) strides = (1, 1, stride_d, stride_h, stride_w) else: output_shape = (batch_size, out_depth, out_height, out_width, self.filters) strides = (1, stride_d, stride_h, stride_w, 1) output_shape_tensor = array_ops.stack(output_shape) outputs = nn.conv3d_transpose( inputs, self.kernel, output_shape_tensor, strides, data_format=conv_utils.convert_data_format(self.data_format, ndim=5), padding=self.padding.upper()) if not context.executing_eagerly(): # Infer the static output shape: out_shape = self.compute_output_shape(inputs.shape) outputs.set_shape(out_shape) if self.use_bias: outputs = nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, d_axis, h_axis, w_axis = 1, 2, 3, 4 else: c_axis, d_axis, h_axis, w_axis = 4, 1, 2, 3 kernel_d, kernel_h, kernel_w = self.kernel_size stride_d, stride_h, stride_w = self.strides if self.output_padding is None: out_pad_d = out_pad_h = out_pad_w = None else: out_pad_d, out_pad_h, out_pad_w = self.output_padding output_shape[c_axis] = self.filters output_shape[d_axis] = conv_utils.deconv_output_length( output_shape[d_axis], kernel_d, padding=self.padding, output_padding=out_pad_d, stride=stride_d) output_shape[h_axis] = conv_utils.deconv_output_length( output_shape[h_axis], kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h) output_shape[w_axis] = conv_utils.deconv_output_length( output_shape[w_axis], kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w) return tensor_shape.TensorShape(output_shape) def get_config(self): config = super(Conv3DTranspose, self).get_config() config.pop('dilation_rate') config['output_padding'] = self.output_padding return config class SeparableConv(Conv): """Abstract base layer for separable nD convolution. This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels. If `use_bias` is True and a bias initializer is provided, it adds a bias vector to the output. It then optionally applies an activation function to produce the final output. Arguments: rank: An integer, the rank of the convolution, e.g. "2" for 2D convolution. filters: Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). kernel_size: A tuple or list of integers specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions. strides: A tuple or list of integers specifying the strides of the convolution. Can be a single integer to specify the same value for all spatial dimensions. Specifying any `stride` value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: One of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, ..., channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, ...)`. dilation_rate: An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `num_filters_in * depth_multiplier`. activation: Activation function to use. If you don't specify anything, no activation is applied ( see `keras.activations`). use_bias: Boolean, whether the layer uses a bias. depthwise_initializer: An initializer for the depthwise convolution kernel. pointwise_initializer: An initializer for the pointwise convolution kernel. bias_initializer: An initializer for the bias vector. If None, the default initializer will be used. depthwise_regularizer: Optional regularizer for the depthwise convolution kernel. pointwise_regularizer: Optional regularizer for the pointwise convolution kernel. bias_regularizer: Optional regularizer for the bias vector. activity_regularizer: Optional regularizer function for the output. depthwise_constraint: Optional projection function to be applied to the depthwise kernel after being updated by an `Optimizer` (e.g. used for norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. pointwise_constraint: Optional projection function to be applied to the pointwise kernel after being updated by an `Optimizer`. bias_constraint: Optional projection function to be applied to the bias after being updated by an `Optimizer`. trainable: Boolean, if `True` the weights of this layer will be marked as trainable (and listed in `layer.trainable_weights`). name: A string, the name of the layer. """ def __init__(self, rank, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, trainable=True, name=None, **kwargs): super(SeparableConv, self).__init__( rank=rank, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, bias_initializer=initializers.get(bias_initializer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), bias_constraint=bias_constraint, trainable=trainable, name=name, **kwargs) self.depth_multiplier = depth_multiplier self.depthwise_initializer = initializers.get(depthwise_initializer) self.pointwise_initializer = initializers.get(pointwise_initializer) self.depthwise_regularizer = regularizers.get(depthwise_regularizer) self.pointwise_regularizer = regularizers.get(pointwise_regularizer) self.depthwise_constraint = constraints.get(depthwise_constraint) self.pointwise_constraint = constraints.get(pointwise_constraint) def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = int(input_shape[channel_axis]) self.input_spec = InputSpec(ndim=self.rank + 2, axes={channel_axis: input_dim}) depthwise_kernel_shape = self.kernel_size + (input_dim, self.depth_multiplier) pointwise_kernel_shape = ( 1,) * self.rank + (self.depth_multiplier * input_dim, self.filters) self.depthwise_kernel = self.add_weight( name='depthwise_kernel', shape=depthwise_kernel_shape, initializer=self.depthwise_initializer, regularizer=self.depthwise_regularizer, constraint=self.depthwise_constraint, trainable=True, dtype=self.dtype) self.pointwise_kernel = self.add_weight( name='pointwise_kernel', shape=pointwise_kernel_shape, initializer=self.pointwise_initializer, regularizer=self.pointwise_regularizer, constraint=self.pointwise_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): raise NotImplementedError def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'data_format': self.data_format, 'depth_multiplier': self.depth_multiplier, 'dilation_rate': self.dilation_rate, 'activation': activations.serialize(self.activation), 'use_bias': self.use_bias, 'depthwise_initializer': initializers.serialize(self.depthwise_initializer), 'pointwise_initializer': initializers.serialize(self.pointwise_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'depthwise_regularizer': regularizers.serialize(self.depthwise_regularizer), 'pointwise_regularizer': regularizers.serialize(self.pointwise_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'depthwise_constraint': constraints.serialize(self.depthwise_constraint), 'pointwise_constraint': constraints.serialize(self.pointwise_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint) } base_config = super(SeparableConv, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.SeparableConv1D', 'keras.layers.SeparableConvolution1D') class SeparableConv1D(SeparableConv): """Depthwise separable 1D convolution. This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels. If `use_bias` is True and a bias initializer is provided, it adds a bias vector to the output. It then optionally applies an activation function to produce the final output. Arguments: filters: Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). kernel_size: A single integer specifying the spatial dimensions of the filters. strides: A single integer specifying the strides of the convolution. Specifying any `stride` value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: One of `"valid"`, `"same"`, or `"causal"` (case-insensitive). data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, length, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, length)`. dilation_rate: A single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `num_filters_in * depth_multiplier`. activation: Activation function to use. If you don't specify anything, no activation is applied ( see `keras.activations`). use_bias: Boolean, whether the layer uses a bias. depthwise_initializer: An initializer for the depthwise convolution kernel ( see `keras.initializers`). pointwise_initializer: An initializer for the pointwise convolution kernel ( see `keras.initializers`). bias_initializer: An initializer for the bias vector. If None, the default initializer will be used (see `keras.initializers`). depthwise_regularizer: Optional regularizer for the depthwise convolution kernel (see `keras.regularizers`). pointwise_regularizer: Optional regularizer for the pointwise convolution kernel (see `keras.regularizers`). bias_regularizer: Optional regularizer for the bias vector ( see `keras.regularizers`). activity_regularizer: Optional regularizer function for the output ( see `keras.regularizers`). depthwise_constraint: Optional projection function to be applied to the depthwise kernel after being updated by an `Optimizer` (e.g. used for norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training ( see `keras.constraints`). pointwise_constraint: Optional projection function to be applied to the pointwise kernel after being updated by an `Optimizer` ( see `keras.constraints`). bias_constraint: Optional projection function to be applied to the bias after being updated by an `Optimizer` ( see `keras.constraints`). trainable: Boolean, if `True` the weights of this layer will be marked as trainable (and listed in `layer.trainable_weights`). name: A string, the name of the layer. Input shape: 3D tensor with shape: `(batch_size, channels, steps)` if data_format='channels_first' or 5D tensor with shape: `(batch_size, steps, channels)` if data_format='channels_last'. Output shape: 3D tensor with shape: `(batch_size, filters, new_steps)` if data_format='channels_first' or 3D tensor with shape: `(batch_size, new_steps, filters)` if data_format='channels_last'. `new_steps` value might have changed due to padding or strides. Returns: A tensor of rank 3 representing `activation(separableconv1d(inputs, kernel) + bias)`. Raises: ValueError: when both `strides` > 1 and `dilation_rate` > 1. """ def __init__(self, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs): super(SeparableConv1D, self).__init__( rank=1, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, depth_multiplier=depth_multiplier, activation=activations.get(activation), use_bias=use_bias, depthwise_initializer=initializers.get(depthwise_initializer), pointwise_initializer=initializers.get(pointwise_initializer), bias_initializer=initializers.get(bias_initializer), depthwise_regularizer=regularizers.get(depthwise_regularizer), pointwise_regularizer=regularizers.get(pointwise_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), depthwise_constraint=constraints.get(depthwise_constraint), pointwise_constraint=constraints.get(pointwise_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) def call(self, inputs): if self.padding == 'causal': inputs = array_ops.pad(inputs, self._compute_causal_padding()) if self.data_format == 'channels_last': strides = (1,) + self.strides * 2 + (1,) spatial_start_dim = 1 else: strides = (1, 1) + self.strides * 2 spatial_start_dim = 2 # Explicitly broadcast inputs and kernels to 4D. # TODO(fchollet): refactor when a native separable_conv1d op is available. inputs = array_ops.expand_dims(inputs, spatial_start_dim) depthwise_kernel = array_ops.expand_dims(self.depthwise_kernel, 0) pointwise_kernel = array_ops.expand_dims(self.pointwise_kernel, 0) dilation_rate = (1,) + self.dilation_rate if self.padding == 'causal': op_padding = 'valid' else: op_padding = self.padding outputs = nn.separable_conv2d( inputs, depthwise_kernel, pointwise_kernel, strides=strides, padding=op_padding.upper(), rate=dilation_rate, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.use_bias: outputs = nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) outputs = array_ops.squeeze(outputs, [spatial_start_dim]) if self.activation is not None: return self.activation(outputs) return outputs @keras_export('keras.layers.SeparableConv2D', 'keras.layers.SeparableConvolution2D') class SeparableConv2D(SeparableConv): """Depthwise separable 2D convolution. Separable convolutions consist of first performing a depthwise spatial convolution (which acts on each input channel separately) followed by a pointwise convolution which mixes the resulting output channels. The `depth_multiplier` argument controls how many output channels are generated per input channel in the depthwise step. Intuitively, separable convolutions can be understood as a way to factorize a convolution kernel into two smaller kernels, or as an extreme version of an Inception block. Arguments: filters: Integer, the dimensionality of the output space (i.e. the number of output filters in the convolution). kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `"valid"` or `"same"` (case-insensitive). data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". dilation_rate: An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `filters_in * depth_multiplier`. activation: Activation function to use. If you don't specify anything, no activation is applied ( see `keras.activations`). use_bias: Boolean, whether the layer uses a bias vector. depthwise_initializer: Initializer for the depthwise kernel matrix ( see `keras.initializers`). pointwise_initializer: Initializer for the pointwise kernel matrix ( see `keras.initializers`). bias_initializer: Initializer for the bias vector ( see `keras.initializers`). depthwise_regularizer: Regularizer function applied to the depthwise kernel matrix (see `keras.regularizers`). pointwise_regularizer: Regularizer function applied to the pointwise kernel matrix (see `keras.regularizers`). bias_regularizer: Regularizer function applied to the bias vector ( see `keras.regularizers`). activity_regularizer: Regularizer function applied to the output of the layer (its "activation") ( see `keras.regularizers`). depthwise_constraint: Constraint function applied to the depthwise kernel matrix ( see `keras.constraints`). pointwise_constraint: Constraint function applied to the pointwise kernel matrix ( see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector ( see `keras.constraints`). Input shape: 4D tensor with shape: `(batch_size, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(batch_size, rows, cols, channels)` if data_format='channels_last'. Output shape: 4D tensor with shape: `(batch_size, filters, new_rows, new_cols)` if data_format='channels_first' or 4D tensor with shape: `(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'. `rows` and `cols` values might have changed due to padding. Returns: A tensor of rank 4 representing `activation(separableconv2d(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". ValueError: when both `strides` > 1 and `dilation_rate` > 1. """ def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs): super(SeparableConv2D, self).__init__( rank=2, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, depth_multiplier=depth_multiplier, activation=activations.get(activation), use_bias=use_bias, depthwise_initializer=initializers.get(depthwise_initializer), pointwise_initializer=initializers.get(pointwise_initializer), bias_initializer=initializers.get(bias_initializer), depthwise_regularizer=regularizers.get(depthwise_regularizer), pointwise_regularizer=regularizers.get(pointwise_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), depthwise_constraint=constraints.get(depthwise_constraint), pointwise_constraint=constraints.get(pointwise_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) def call(self, inputs): # Apply the actual ops. if self.data_format == 'channels_last': strides = (1,) + self.strides + (1,) else: strides = (1, 1) + self.strides outputs = nn.separable_conv2d( inputs, self.depthwise_kernel, self.pointwise_kernel, strides=strides, padding=self.padding.upper(), rate=self.dilation_rate, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.use_bias: outputs = nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.activation is not None: return self.activation(outputs) return outputs @keras_export('keras.layers.DepthwiseConv2D') class DepthwiseConv2D(Conv2D): """Depthwise separable 2D convolution. Depthwise Separable convolutions consist of performing just the first step in a depthwise spatial convolution (which acts on each input channel separately). The `depth_multiplier` argument controls how many output channels are generated per input channel in the depthwise step. Arguments: kernel_size: An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. strides: An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. padding: one of `'valid'` or `'same'` (case-insensitive). depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `filters_in * depth_multiplier`. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be 'channels_last'. dilation_rate: An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. activation: Activation function to use. If you don't specify anything, no activation is applied ( see `keras.activations`). use_bias: Boolean, whether the layer uses a bias vector. depthwise_initializer: Initializer for the depthwise kernel matrix ( see `keras.initializers`). bias_initializer: Initializer for the bias vector ( see `keras.initializers`). depthwise_regularizer: Regularizer function applied to the depthwise kernel matrix (see `keras.regularizers`). bias_regularizer: Regularizer function applied to the bias vector ( see `keras.regularizers`). activity_regularizer: Regularizer function applied to the output of the layer (its 'activation') ( see `keras.regularizers`). depthwise_constraint: Constraint function applied to the depthwise kernel matrix ( see `keras.constraints`). bias_constraint: Constraint function applied to the bias vector ( see `keras.constraints`). Input shape: 4D tensor with shape: `[batch_size, channels, rows, cols]` if data_format='channels_first' or 4D tensor with shape: `[batch_size, rows, cols, channels]` if data_format='channels_last'. Output shape: 4D tensor with shape: `[batch_size, filters, new_rows, new_cols]` if data_format='channels_first' or 4D tensor with shape: `[batch_size, new_rows, new_cols, filters]` if data_format='channels_last'. `rows` and `cols` values might have changed due to padding. Returns: A tensor of rank 4 representing `activation(depthwiseconv2d(inputs, kernel) + bias)`. Raises: ValueError: if `padding` is "causal". ValueError: when both `strides` > 1 and `dilation_rate` > 1. """ def __init__(self, kernel_size, strides=(1, 1), padding='valid', depth_multiplier=1, data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, depthwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, bias_constraint=None, **kwargs): super(DepthwiseConv2D, self).__init__( filters=None, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, bias_constraint=bias_constraint, **kwargs) self.depth_multiplier = depth_multiplier self.depthwise_initializer = initializers.get(depthwise_initializer) self.depthwise_regularizer = regularizers.get(depthwise_regularizer) self.depthwise_constraint = constraints.get(depthwise_constraint) self.bias_initializer = initializers.get(bias_initializer) def build(self, input_shape): if len(input_shape) < 4: raise ValueError('Inputs to `DepthwiseConv2D` should have rank 4. ' 'Received input shape:', str(input_shape)) input_shape = tensor_shape.TensorShape(input_shape) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs to ' '`DepthwiseConv2D` ' 'should be defined. Found `None`.') input_dim = int(input_shape[channel_axis]) depthwise_kernel_shape = (self.kernel_size[0], self.kernel_size[1], input_dim, self.depth_multiplier) self.depthwise_kernel = self.add_weight( shape=depthwise_kernel_shape, initializer=self.depthwise_initializer, name='depthwise_kernel', regularizer=self.depthwise_regularizer, constraint=self.depthwise_constraint) if self.use_bias: self.bias = self.add_weight(shape=(input_dim * self.depth_multiplier,), initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None # Set input spec. self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) self.built = True def call(self, inputs): outputs = backend.depthwise_conv2d( inputs, self.depthwise_kernel, strides=self.strides, padding=self.padding, dilation_rate=self.dilation_rate, data_format=self.data_format) if self.use_bias: outputs = backend.bias_add( outputs, self.bias, data_format=self.data_format) if self.activation is not None: return self.activation(outputs) return outputs @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': rows = input_shape[2] cols = input_shape[3] out_filters = input_shape[1] * self.depth_multiplier elif self.data_format == 'channels_last': rows = input_shape[1] cols = input_shape[2] out_filters = input_shape[3] * self.depth_multiplier rows = conv_utils.conv_output_length(rows, self.kernel_size[0], self.padding, self.strides[0], self.dilation_rate[0]) cols = conv_utils.conv_output_length(cols, self.kernel_size[1], self.padding, self.strides[1], self.dilation_rate[1]) if self.data_format == 'channels_first': return (input_shape[0], out_filters, rows, cols) elif self.data_format == 'channels_last': return (input_shape[0], rows, cols, out_filters) def get_config(self): config = super(DepthwiseConv2D, self).get_config() config.pop('filters') config.pop('kernel_initializer') config.pop('kernel_regularizer') config.pop('kernel_constraint') config['depth_multiplier'] = self.depth_multiplier config['depthwise_initializer'] = initializers.serialize( self.depthwise_initializer) config['depthwise_regularizer'] = regularizers.serialize( self.depthwise_regularizer) config['depthwise_constraint'] = constraints.serialize( self.depthwise_constraint) return config @keras_export('keras.layers.UpSampling1D') class UpSampling1D(Layer): """Upsampling layer for 1D inputs. Repeats each temporal step `size` times along the time axis. Examples: >>> input_shape = (2, 2, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]] >>> y = tf.keras.layers.UpSampling1D(size=2)(x) >>> print(y) tf.Tensor( [[[ 0 1 2] [ 0 1 2] [ 3 4 5] [ 3 4 5]] [[ 6 7 8] [ 6 7 8] [ 9 10 11] [ 9 10 11]]], shape=(2, 4, 3), dtype=int64) Arguments: size: Integer. Upsampling factor. Input shape: 3D tensor with shape: `(batch_size, steps, features)`. Output shape: 3D tensor with shape: `(batch_size, upsampled_steps, features)`. """ def __init__(self, size=2, **kwargs): super(UpSampling1D, self).__init__(**kwargs) self.size = int(size) self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() size = self.size * input_shape[1] if input_shape[1] is not None else None return tensor_shape.TensorShape([input_shape[0], size, input_shape[2]]) def call(self, inputs): output = backend.repeat_elements(inputs, self.size, axis=1) return output def get_config(self): config = {'size': self.size} base_config = super(UpSampling1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.UpSampling2D') class UpSampling2D(Layer): """Upsampling layer for 2D inputs. Repeats the rows and columns of the data by `size[0]` and `size[1]` respectively. Examples: >>> input_shape = (2, 2, 1, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[[ 0 1 2]] [[ 3 4 5]]] [[[ 6 7 8]] [[ 9 10 11]]]] >>> y = tf.keras.layers.UpSampling2D(size=(1, 2))(x) >>> print(y) tf.Tensor( [[[[ 0 1 2] [ 0 1 2]] [[ 3 4 5] [ 3 4 5]]] [[[ 6 7 8] [ 6 7 8]] [[ 9 10 11] [ 9 10 11]]]], shape=(2, 2, 2, 3), dtype=int64) Arguments: size: Int, or tuple of 2 integers. The upsampling factors for rows and columns. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". interpolation: A string, one of `nearest` or `bilinear`. Input shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, rows, cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, rows, cols)` Output shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, upsampled_rows, upsampled_cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, upsampled_rows, upsampled_cols)` """ def __init__(self, size=(2, 2), data_format=None, interpolation='nearest', **kwargs): super(UpSampling2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) self.size = conv_utils.normalize_tuple(size, 2, 'size') if interpolation not in {'nearest', 'bilinear'}: raise ValueError('`interpolation` argument should be one of `"nearest"` ' 'or `"bilinear"`.') self.interpolation = interpolation self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': height = self.size[0] * input_shape[ 2] if input_shape[2] is not None else None width = self.size[1] * input_shape[ 3] if input_shape[3] is not None else None return tensor_shape.TensorShape( [input_shape[0], input_shape[1], height, width]) else: height = self.size[0] * input_shape[ 1] if input_shape[1] is not None else None width = self.size[1] * input_shape[ 2] if input_shape[2] is not None else None return tensor_shape.TensorShape( [input_shape[0], height, width, input_shape[3]]) def call(self, inputs): return backend.resize_images( inputs, self.size[0], self.size[1], self.data_format, interpolation=self.interpolation) def get_config(self): config = { 'size': self.size, 'data_format': self.data_format, 'interpolation': self.interpolation } base_config = super(UpSampling2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.UpSampling3D') class UpSampling3D(Layer): """Upsampling layer for 3D inputs. Repeats the 1st, 2nd and 3rd dimensions of the data by `size[0]`, `size[1]` and `size[2]` respectively. Examples: >>> input_shape = (2, 1, 2, 1, 3) >>> x = tf.constant(1, shape=input_shape) >>> y = tf.keras.layers.UpSampling3D(size=2)(x) >>> print(y.shape) (2, 2, 4, 2, 3) Arguments: size: Int, or tuple of 3 integers. The upsampling factors for dim1, dim2 and dim3. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". Input shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, dim1, dim2, dim3, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, dim1, dim2, dim3)` Output shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, upsampled_dim1, upsampled_dim2, upsampled_dim3, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, upsampled_dim1, upsampled_dim2, upsampled_dim3)` """ def __init__(self, size=(2, 2, 2), data_format=None, **kwargs): self.data_format = conv_utils.normalize_data_format(data_format) self.size = conv_utils.normalize_tuple(size, 3, 'size') self.input_spec = InputSpec(ndim=5) super(UpSampling3D, self).__init__(**kwargs) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': dim1 = self.size[0] * input_shape[ 2] if input_shape[2] is not None else None dim2 = self.size[1] * input_shape[ 3] if input_shape[3] is not None else None dim3 = self.size[2] * input_shape[ 4] if input_shape[4] is not None else None return tensor_shape.TensorShape( [input_shape[0], input_shape[1], dim1, dim2, dim3]) else: dim1 = self.size[0] * input_shape[ 1] if input_shape[1] is not None else None dim2 = self.size[1] * input_shape[ 2] if input_shape[2] is not None else None dim3 = self.size[2] * input_shape[ 3] if input_shape[3] is not None else None return tensor_shape.TensorShape( [input_shape[0], dim1, dim2, dim3, input_shape[4]]) def call(self, inputs): return backend.resize_volumes( inputs, self.size[0], self.size[1], self.size[2], self.data_format) def get_config(self): config = {'size': self.size, 'data_format': self.data_format} base_config = super(UpSampling3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.ZeroPadding1D') class ZeroPadding1D(Layer): """Zero-padding layer for 1D input (e.g. temporal sequence). Examples: >>> input_shape = (2, 2, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]] >>> y = tf.keras.layers.ZeroPadding1D(padding=2)(x) >>> print(y) tf.Tensor( [[[ 0 0 0] [ 0 0 0] [ 0 1 2] [ 3 4 5] [ 0 0 0] [ 0 0 0]] [[ 0 0 0] [ 0 0 0] [ 6 7 8] [ 9 10 11] [ 0 0 0] [ 0 0 0]]], shape=(2, 6, 3), dtype=int64) Arguments: padding: Int, or tuple of int (length 2), or dictionary. - If int: How many zeros to add at the beginning and end of the padding dimension (axis 1). - If tuple of int (length 2): How many zeros to add at the beginning and the end of the padding dimension (`(left_pad, right_pad)`). Input shape: 3D tensor with shape `(batch_size, axis_to_pad, features)` Output shape: 3D tensor with shape `(batch_size, padded_axis, features)` """ def __init__(self, padding=1, **kwargs): super(ZeroPadding1D, self).__init__(**kwargs) self.padding = conv_utils.normalize_tuple(padding, 2, 'padding') self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): if input_shape[1] is not None: length = input_shape[1] + self.padding[0] + self.padding[1] else: length = None return tensor_shape.TensorShape([input_shape[0], length, input_shape[2]]) def call(self, inputs): return backend.temporal_padding(inputs, padding=self.padding) def get_config(self): config = {'padding': self.padding} base_config = super(ZeroPadding1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.ZeroPadding2D') class ZeroPadding2D(Layer): """Zero-padding layer for 2D input (e.g. picture). This layer can add rows and columns of zeros at the top, bottom, left and right side of an image tensor. Examples: >>> input_shape = (1, 1, 2, 2) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[[0 1] [2 3]]]] >>> y = tf.keras.layers.ZeroPadding2D(padding=1)(x) >>> print(y) tf.Tensor( [[[[0 0] [0 0] [0 0] [0 0]] [[0 0] [0 1] [2 3] [0 0]] [[0 0] [0 0] [0 0] [0 0]]]], shape=(1, 3, 4, 2), dtype=int64) Arguments: padding: Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints. - If int: the same symmetric padding is applied to height and width. - If tuple of 2 ints: interpreted as two different symmetric padding values for height and width: `(symmetric_height_pad, symmetric_width_pad)`. - If tuple of 2 tuples of 2 ints: interpreted as `((top_pad, bottom_pad), (left_pad, right_pad))` data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". Input shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, rows, cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, rows, cols)` Output shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, padded_rows, padded_cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, padded_rows, padded_cols)` """ def __init__(self, padding=(1, 1), data_format=None, **kwargs): super(ZeroPadding2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(padding, int): self.padding = ((padding, padding), (padding, padding)) elif hasattr(padding, '__len__'): if len(padding) != 2: raise ValueError('`padding` should have two elements. ' 'Found: ' + str(padding)) height_padding = conv_utils.normalize_tuple(padding[0], 2, '1st entry of padding') width_padding = conv_utils.normalize_tuple(padding[1], 2, '2nd entry of padding') self.padding = (height_padding, width_padding) else: raise ValueError('`padding` should be either an int, ' 'a tuple of 2 ints ' '(symmetric_height_pad, symmetric_width_pad), ' 'or a tuple of 2 tuples of 2 ints ' '((top_pad, bottom_pad), (left_pad, right_pad)). ' 'Found: ' + str(padding)) self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': if input_shape[2] is not None: rows = input_shape[2] + self.padding[0][0] + self.padding[0][1] else: rows = None if input_shape[3] is not None: cols = input_shape[3] + self.padding[1][0] + self.padding[1][1] else: cols = None return tensor_shape.TensorShape( [input_shape[0], input_shape[1], rows, cols]) elif self.data_format == 'channels_last': if input_shape[1] is not None: rows = input_shape[1] + self.padding[0][0] + self.padding[0][1] else: rows = None if input_shape[2] is not None: cols = input_shape[2] + self.padding[1][0] + self.padding[1][1] else: cols = None return tensor_shape.TensorShape( [input_shape[0], rows, cols, input_shape[3]]) def call(self, inputs): return backend.spatial_2d_padding( inputs, padding=self.padding, data_format=self.data_format) def get_config(self): config = {'padding': self.padding, 'data_format': self.data_format} base_config = super(ZeroPadding2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.ZeroPadding3D') class ZeroPadding3D(Layer): """Zero-padding layer for 3D data (spatial or spatio-temporal). Examples: >>> input_shape = (1, 1, 2, 2, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> y = tf.keras.layers.ZeroPadding3D(padding=2)(x) >>> print(y.shape) (1, 5, 6, 6, 3) Arguments: padding: Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints. - If int: the same symmetric padding is applied to height and width. - If tuple of 3 ints: interpreted as two different symmetric padding values for height and width: `(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad)`. - If tuple of 3 tuples of 2 ints: interpreted as `((left_dim1_pad, right_dim1_pad), (left_dim2_pad, right_dim2_pad), (left_dim3_pad, right_dim3_pad))` data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". Input shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad, depth)` - If `data_format` is `"channels_first"`: `(batch_size, depth, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad)` Output shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, first_padded_axis, second_padded_axis, third_axis_to_pad, depth)` - If `data_format` is `"channels_first"`: `(batch_size, depth, first_padded_axis, second_padded_axis, third_axis_to_pad)` """ def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs): super(ZeroPadding3D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(padding, int): self.padding = ((padding, padding), (padding, padding), (padding, padding)) elif hasattr(padding, '__len__'): if len(padding) != 3: raise ValueError('`padding` should have 3 elements. ' 'Found: ' + str(padding)) dim1_padding = conv_utils.normalize_tuple(padding[0], 2, '1st entry of padding') dim2_padding = conv_utils.normalize_tuple(padding[1], 2, '2nd entry of padding') dim3_padding = conv_utils.normalize_tuple(padding[2], 2, '3rd entry of padding') self.padding = (dim1_padding, dim2_padding, dim3_padding) else: raise ValueError( '`padding` should be either an int, ' 'a tuple of 3 ints ' '(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad), ' 'or a tuple of 3 tuples of 2 ints ' '((left_dim1_pad, right_dim1_pad),' ' (left_dim2_pad, right_dim2_pad),' ' (left_dim3_pad, right_dim2_pad)). ' 'Found: ' + str(padding)) self.input_spec = InputSpec(ndim=5) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': if input_shape[2] is not None: dim1 = input_shape[2] + 2 * self.padding[0][0] else: dim1 = None if input_shape[3] is not None: dim2 = input_shape[3] + 2 * self.padding[1][0] else: dim2 = None if input_shape[4] is not None: dim3 = input_shape[4] + 2 * self.padding[2][0] else: dim3 = None return tensor_shape.TensorShape( [input_shape[0], input_shape[1], dim1, dim2, dim3]) elif self.data_format == 'channels_last': if input_shape[1] is not None: dim1 = input_shape[1] + 2 * self.padding[0][1] else: dim1 = None if input_shape[2] is not None: dim2 = input_shape[2] + 2 * self.padding[1][1] else: dim2 = None if input_shape[3] is not None: dim3 = input_shape[3] + 2 * self.padding[2][1] else: dim3 = None return tensor_shape.TensorShape( [input_shape[0], dim1, dim2, dim3, input_shape[4]]) def call(self, inputs): return backend.spatial_3d_padding( inputs, padding=self.padding, data_format=self.data_format) def get_config(self): config = {'padding': self.padding, 'data_format': self.data_format} base_config = super(ZeroPadding3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Cropping1D') class Cropping1D(Layer): """Cropping layer for 1D input (e.g. temporal sequence). It crops along the time dimension (axis 1). Examples: >>> input_shape = (2, 3, 2) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> print(x) [[[ 0 1] [ 2 3] [ 4 5]] [[ 6 7] [ 8 9] [10 11]]] >>> y = tf.keras.layers.Cropping1D(cropping=1)(x) >>> print(y) tf.Tensor( [[[2 3]] [[8 9]]], shape=(2, 1, 2), dtype=int64) Arguments: cropping: Int or tuple of int (length 2) How many units should be trimmed off at the beginning and end of the cropping dimension (axis 1). If a single int is provided, the same value will be used for both. Input shape: 3D tensor with shape `(batch_size, axis_to_crop, features)` Output shape: 3D tensor with shape `(batch_size, cropped_axis, features)` """ def __init__(self, cropping=(1, 1), **kwargs): super(Cropping1D, self).__init__(**kwargs) self.cropping = conv_utils.normalize_tuple(cropping, 2, 'cropping') self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if input_shape[1] is not None: length = input_shape[1] - self.cropping[0] - self.cropping[1] else: length = None return tensor_shape.TensorShape([input_shape[0], length, input_shape[2]]) def call(self, inputs): if self.cropping[1] == 0: return inputs[:, self.cropping[0]:, :] else: return inputs[:, self.cropping[0]:-self.cropping[1], :] def get_config(self): config = {'cropping': self.cropping} base_config = super(Cropping1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Cropping2D') class Cropping2D(Layer): """Cropping layer for 2D input (e.g. picture). It crops along spatial dimensions, i.e. height and width. Examples: >>> input_shape = (2, 28, 28, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> y = tf.keras.layers.Cropping2D(cropping=((2, 2), (4, 4)))(x) >>> print(y.shape) (2, 24, 20, 3) Arguments: cropping: Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints. - If int: the same symmetric cropping is applied to height and width. - If tuple of 2 ints: interpreted as two different symmetric cropping values for height and width: `(symmetric_height_crop, symmetric_width_crop)`. - If tuple of 2 tuples of 2 ints: interpreted as `((top_crop, bottom_crop), (left_crop, right_crop))` data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, height, width)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". Input shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, rows, cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, rows, cols)` Output shape: 4D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, cropped_rows, cropped_cols, channels)` - If `data_format` is `"channels_first"`: `(batch_size, channels, cropped_rows, cropped_cols)` """ def __init__(self, cropping=((0, 0), (0, 0)), data_format=None, **kwargs): super(Cropping2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(cropping, int): self.cropping = ((cropping, cropping), (cropping, cropping)) elif hasattr(cropping, '__len__'): if len(cropping) != 2: raise ValueError('`cropping` should have two elements. ' 'Found: ' + str(cropping)) height_cropping = conv_utils.normalize_tuple(cropping[0], 2, '1st entry of cropping') width_cropping = conv_utils.normalize_tuple(cropping[1], 2, '2nd entry of cropping') self.cropping = (height_cropping, width_cropping) else: raise ValueError('`cropping` should be either an int, ' 'a tuple of 2 ints ' '(symmetric_height_crop, symmetric_width_crop), ' 'or a tuple of 2 tuples of 2 ints ' '((top_crop, bottom_crop), (left_crop, right_crop)). ' 'Found: ' + str(cropping)) self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() # pylint: disable=invalid-unary-operand-type if self.data_format == 'channels_first': return tensor_shape.TensorShape([ input_shape[0], input_shape[1], input_shape[2] - self.cropping[0][0] - self.cropping[0][1] if input_shape[2] else None, input_shape[3] - self.cropping[1][0] - self.cropping[1][1] if input_shape[3] else None ]) else: return tensor_shape.TensorShape([ input_shape[0], input_shape[1] - self.cropping[0][0] - self.cropping[0][1] if input_shape[1] else None, input_shape[2] - self.cropping[1][0] - self.cropping[1][1] if input_shape[2] else None, input_shape[3] ]) # pylint: enable=invalid-unary-operand-type def call(self, inputs): # pylint: disable=invalid-unary-operand-type if self.data_format == 'channels_first': if self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:] elif self.cropping[0][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1]] elif self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:] return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:-self.cropping[1][1]] else: if self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, :] elif self.cropping[0][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], :] elif self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:, :] return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[ 1][0]:-self.cropping[1][1], :] # pylint: disable=invalid-unary-operand-type # pylint: enable=invalid-unary-operand-type def get_config(self): config = {'cropping': self.cropping, 'data_format': self.data_format} base_config = super(Cropping2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Cropping3D') class Cropping3D(Layer): """Cropping layer for 3D data (e.g. spatial or spatio-temporal). Examples: >>> input_shape = (2, 28, 28, 10, 3) >>> x = np.arange(np.prod(input_shape)).reshape(input_shape) >>> y = tf.keras.layers.Cropping3D(cropping=(2, 4, 2))(x) >>> print(y.shape) (2, 24, 20, 6, 3) Arguments: cropping: Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints. - If int: the same symmetric cropping is applied to depth, height, and width. - If tuple of 3 ints: interpreted as two different symmetric cropping values for depth, height, and width: `(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop)`. - If tuple of 3 tuples of 2 ints: interpreted as `((left_dim1_crop, right_dim1_crop), (left_dim2_crop, right_dim2_crop), (left_dim3_crop, right_dim3_crop))` data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". Input shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop, depth)` - If `data_format` is `"channels_first"`: `(batch_size, depth, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop)` Output shape: 5D tensor with shape: - If `data_format` is `"channels_last"`: `(batch_size, first_cropped_axis, second_cropped_axis, third_cropped_axis, depth)` - If `data_format` is `"channels_first"`: `(batch_size, depth, first_cropped_axis, second_cropped_axis, third_cropped_axis)` """ def __init__(self, cropping=((1, 1), (1, 1), (1, 1)), data_format=None, **kwargs): super(Cropping3D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(cropping, int): self.cropping = ((cropping, cropping), (cropping, cropping), (cropping, cropping)) elif hasattr(cropping, '__len__'): if len(cropping) != 3: raise ValueError('`cropping` should have 3 elements. ' 'Found: ' + str(cropping)) dim1_cropping = conv_utils.normalize_tuple(cropping[0], 2, '1st entry of cropping') dim2_cropping = conv_utils.normalize_tuple(cropping[1], 2, '2nd entry of cropping') dim3_cropping = conv_utils.normalize_tuple(cropping[2], 2, '3rd entry of cropping') self.cropping = (dim1_cropping, dim2_cropping, dim3_cropping) else: raise ValueError( '`cropping` should be either an int, ' 'a tuple of 3 ints ' '(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop), ' 'or a tuple of 3 tuples of 2 ints ' '((left_dim1_crop, right_dim1_crop),' ' (left_dim2_crop, right_dim2_crop),' ' (left_dim3_crop, right_dim2_crop)). ' 'Found: ' + str(cropping)) self.input_spec = InputSpec(ndim=5) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() # pylint: disable=invalid-unary-operand-type if self.data_format == 'channels_first': if input_shape[2] is not None: dim1 = input_shape[2] - self.cropping[0][0] - self.cropping[0][1] else: dim1 = None if input_shape[3] is not None: dim2 = input_shape[3] - self.cropping[1][0] - self.cropping[1][1] else: dim2 = None if input_shape[4] is not None: dim3 = input_shape[4] - self.cropping[2][0] - self.cropping[2][1] else: dim3 = None return tensor_shape.TensorShape( [input_shape[0], input_shape[1], dim1, dim2, dim3]) elif self.data_format == 'channels_last': if input_shape[1] is not None: dim1 = input_shape[1] - self.cropping[0][0] - self.cropping[0][1] else: dim1 = None if input_shape[2] is not None: dim2 = input_shape[2] - self.cropping[1][0] - self.cropping[1][1] else: dim2 = None if input_shape[3] is not None: dim3 = input_shape[3] - self.cropping[2][0] - self.cropping[2][1] else: dim3 = None return tensor_shape.TensorShape( [input_shape[0], dim1, dim2, dim3, input_shape[4]]) # pylint: enable=invalid-unary-operand-type def call(self, inputs): # pylint: disable=invalid-unary-operand-type if self.data_format == 'channels_first': if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:] elif self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1]] elif self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]:] elif self.cropping[0][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]:] elif self.cropping[0][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][ 0]:-self.cropping[1][1], self.cropping[2][0]:-self.cropping[2][1]] elif self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self. cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1]] elif self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self. cropping[1][0]:-self.cropping[1][1], self.cropping[2][0]:] return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:-self.cropping[1][1], self.cropping[2][ 0]:-self.cropping[2][1]] else: if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:, :] elif self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1], :] elif self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]:, :] elif self.cropping[0][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]:, :] elif self.cropping[0][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][ 0]:-self.cropping[1][1], self.cropping[2][0]: -self.cropping[2][1], :] elif self.cropping[1][1] == 0: return inputs[:, self.cropping[0][ 0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]: -self.cropping[2][1], :] elif self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:-self.cropping[1][1], self.cropping[ 2][0]:, :] return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[ 1][0]:-self.cropping[1][1], self.cropping[2][0]: # pylint: disable=invalid-unary-operand-type -self.cropping[2][1], :] # pylint: disable=invalid-unary-operand-type # pylint: enable=invalid-unary-operand-type def get_config(self): config = {'cropping': self.cropping, 'data_format': self.data_format} base_config = super(Cropping3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) # Aliases Convolution1D = Conv1D Convolution2D = Conv2D Convolution3D = Conv3D SeparableConvolution1D = SeparableConv1D SeparableConvolution2D = SeparableConv2D Convolution2DTranspose = Conv2DTranspose Convolution3DTranspose = Conv3DTranspose Deconvolution2D = Deconv2D = Conv2DTranspose Deconvolution3D = Deconv3D = Conv3DTranspose
40.535638
104
0.657221
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.eager import context from tensorflow.python.framework import tensor_shape from tensorflow.python.keras import activations from tensorflow.python.keras import backend from tensorflow.python.keras import constraints from tensorflow.python.keras import initializers from tensorflow.python.keras import regularizers from tensorflow.python.keras.engine.base_layer import Layer from tensorflow.python.keras.engine.input_spec import InputSpec from tensorflow.python.keras.layers.pooling import AveragePooling1D from tensorflow.python.keras.layers.pooling import AveragePooling2D from tensorflow.python.keras.layers.pooling import AveragePooling3D from tensorflow.python.keras.layers.pooling import MaxPooling1D from tensorflow.python.keras.layers.pooling import MaxPooling2D from tensorflow.python.keras.layers.pooling import MaxPooling3D from tensorflow.python.keras.utils import conv_utils from tensorflow.python.keras.utils import tf_utils from tensorflow.python.ops import array_ops from tensorflow.python.ops import nn from tensorflow.python.ops import nn_ops from tensorflow.python.util.tf_export import keras_export class Conv(Layer): def __init__(self, rank, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, trainable=True, name=None, **kwargs): super(Conv, self).__init__( trainable=trainable, name=name, activity_regularizer=regularizers.get(activity_regularizer), **kwargs) self.rank = rank if filters is not None and not isinstance(filters, int): filters = int(filters) self.filters = filters self.kernel_size = conv_utils.normalize_tuple( kernel_size, rank, 'kernel_size') if not all(self.kernel_size): raise ValueError('The argument `kernel_size` cannot contain 0(s). ' 'Received: %s' % (kernel_size,)) self.strides = conv_utils.normalize_tuple(strides, rank, 'strides') self.padding = conv_utils.normalize_padding(padding) if (self.padding == 'causal' and not isinstance(self, (Conv1D, SeparableConv1D))): raise ValueError('Causal padding is only supported for `Conv1D`' 'and ``SeparableConv1D`.') self.data_format = conv_utils.normalize_data_format(data_format) self.dilation_rate = conv_utils.normalize_tuple( dilation_rate, rank, 'dilation_rate') self.activation = activations.get(activation) self.use_bias = use_bias self.kernel_initializer = initializers.get(kernel_initializer) self.bias_initializer = initializers.get(bias_initializer) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) self.input_spec = InputSpec(ndim=self.rank + 2) def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) input_channel = self._get_input_channel(input_shape) kernel_shape = self.kernel_size + (input_channel, self.filters) self.kernel = self.add_weight( name='kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None channel_axis = self._get_channel_axis() self.input_spec = InputSpec(ndim=self.rank + 2, axes={channel_axis: input_channel}) self._build_conv_op_input_shape = input_shape self._build_input_channel = input_channel self._padding_op = self._get_padding_op() self._conv_op_data_format = conv_utils.convert_data_format( self.data_format, self.rank + 2) self._convolution_op = nn_ops.Convolution( input_shape, filter_shape=self.kernel.shape, dilation_rate=self.dilation_rate, strides=self.strides, padding=self._padding_op, data_format=self._conv_op_data_format) self.built = True def call(self, inputs): if self._recreate_conv_op(inputs): self._convolution_op = nn_ops.Convolution( inputs.get_shape(), filter_shape=self.kernel.shape, dilation_rate=self.dilation_rate, strides=self.strides, padding=self._padding_op, data_format=self._conv_op_data_format) self._build_conv_op_input_shape = inputs.get_shape() if self.padding == 'causal' and self.__class__.__name__ == 'Conv1D': inputs = array_ops.pad(inputs, self._compute_causal_padding()) outputs = self._convolution_op(inputs, self.kernel) if self.use_bias: if self.data_format == 'channels_first': if self.rank == 1: bias = array_ops.reshape(self.bias, (1, self.filters, 1)) outputs += bias else: outputs = nn.bias_add(outputs, self.bias, data_format='NCHW') else: outputs = nn.bias_add(outputs, self.bias, data_format='NHWC') if self.activation is not None: return self.activation(outputs) return outputs def _spatial_output_shape(self, spatial_input_shape): return [ conv_utils.conv_output_length( length, self.kernel_size[i], padding=self.padding, stride=self.strides[i], dilation=self.dilation_rate[i]) for i, length in enumerate(spatial_input_shape) ] def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_last': return tensor_shape.TensorShape( [input_shape[0]] + self._spatial_output_shape(input_shape[1:-1]) + [self.filters]) else: return tensor_shape.TensorShape( [input_shape[0], self.filters] + self._spatial_output_shape(input_shape[2:])) def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'data_format': self.data_format, 'dilation_rate': self.dilation_rate, 'activation': activations.serialize(self.activation), 'use_bias': self.use_bias, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint) } base_config = super(Conv, self).get_config() return dict(list(base_config.items()) + list(config.items())) def _compute_causal_padding(self): left_pad = self.dilation_rate[0] * (self.kernel_size[0] - 1) if self.data_format == 'channels_last': causal_padding = [[0, 0], [left_pad, 0], [0, 0]] else: causal_padding = [[0, 0], [0, 0], [left_pad, 0]] return causal_padding def _get_channel_axis(self): if self.data_format == 'channels_first': return 1 else: return -1 def _get_input_channel(self, input_shape): channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') return int(input_shape[channel_axis]) def _get_padding_op(self): if self.padding == 'causal': op_padding = 'valid' else: op_padding = self.padding if not isinstance(op_padding, (list, tuple)): op_padding = op_padding.upper() return op_padding def _recreate_conv_op(self, inputs): call_input_shape = inputs.get_shape() return self._build_conv_op_input_shape.most_specific_compatible_shape( call_input_shape) != self._build_conv_op_input_shape @keras_export('keras.layers.Conv1D', 'keras.layers.Convolution1D') class Conv1D(Conv): def __init__(self, filters, kernel_size, strides=1, padding='valid', data_format='channels_last', dilation_rate=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv1D, self).__init__( rank=1, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) @keras_export('keras.layers.Conv2D', 'keras.layers.Convolution2D') class Conv2D(Conv): def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv2D, self).__init__( rank=2, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) @keras_export('keras.layers.Conv3D', 'keras.layers.Convolution3D') class Conv3D(Conv): def __init__(self, filters, kernel_size, strides=(1, 1, 1), padding='valid', data_format=None, dilation_rate=(1, 1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv3D, self).__init__( rank=3, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) @keras_export('keras.layers.Conv1DTranspose', 'keras.layers.Convolution1DTranspose') class Conv1DTranspose(Conv1D): def __init__(self, filters, kernel_size, strides=1, padding='valid', output_padding=None, data_format=None, dilation_rate=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv1DTranspose, self).__init__( filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) self.output_padding = output_padding if self.output_padding is not None: self.output_padding = conv_utils.normalize_tuple( self.output_padding, 1, 'output_padding') for stride, out_pad in zip(self.strides, self.output_padding): if out_pad >= stride: raise ValueError('Stride ' + str(self.strides) + ' must be ' 'greater than output padding ' + str(self.output_padding)) def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) if len(input_shape) != 3: raise ValueError('Inputs should have rank 3. Received input shape: ' + str(input_shape)) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = int(input_shape[channel_axis]) self.input_spec = InputSpec(ndim=3, axes={channel_axis: input_dim}) kernel_shape = self.kernel_size + (self.filters, input_dim) self.kernel = self.add_weight( name='kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): inputs_shape = array_ops.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': t_axis = 2 else: t_axis = 1 length = inputs_shape[t_axis] if self.output_padding is None: output_padding = None else: output_padding = self.output_padding[0] out_length = conv_utils.deconv_output_length( length, self.kernel_size[0], padding=self.padding, output_padding=output_padding, stride=self.strides[0], dilation=self.dilation_rate[0]) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_length) else: output_shape = (batch_size, out_length, self.filters) data_format = conv_utils.convert_data_format(self.data_format, ndim=3) output_shape_tensor = array_ops.stack(output_shape) outputs = nn_ops.conv1d_transpose( inputs, self.kernel, output_shape_tensor, strides=self.strides, padding=self.padding.upper(), data_format=data_format, dilations=self.dilation_rate) if not context.executing_eagerly(): out_shape = self.compute_output_shape(inputs.shape) outputs.set_shape(out_shape) if self.use_bias: outputs = nn.bias_add( outputs, self.bias, data_format=data_format) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, t_axis = 1, 2 else: c_axis, t_axis = 2, 1 if self.output_padding is None: output_padding = None else: output_padding = self.output_padding[0] output_shape[c_axis] = self.filters output_shape[t_axis] = conv_utils.deconv_output_length( output_shape[t_axis], self.kernel_size[0], padding=self.padding, output_padding=output_padding, stride=self.strides[0], dilation=self.dilation_rate[0]) return tensor_shape.TensorShape(output_shape) def get_config(self): config = super(Conv1DTranspose, self).get_config() config['output_padding'] = self.output_padding return config @keras_export('keras.layers.Conv2DTranspose', 'keras.layers.Convolution2DTranspose') class Conv2DTranspose(Conv2D): def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', output_padding=None, data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv2DTranspose, self).__init__( filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) self.output_padding = output_padding if self.output_padding is not None: self.output_padding = conv_utils.normalize_tuple( self.output_padding, 2, 'output_padding') for stride, out_pad in zip(self.strides, self.output_padding): if out_pad >= stride: raise ValueError('Stride ' + str(self.strides) + ' must be ' 'greater than output padding ' + str(self.output_padding)) def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) if len(input_shape) != 4: raise ValueError('Inputs should have rank 4. Received input shape: ' + str(input_shape)) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = int(input_shape[channel_axis]) self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) kernel_shape = self.kernel_size + (self.filters, input_dim) self.kernel = self.add_weight( name='kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): inputs_shape = array_ops.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': h_axis, w_axis = 2, 3 else: h_axis, w_axis = 1, 2 height, width = None, None if inputs.shape.rank is not None: dims = inputs.shape.as_list() height = dims[h_axis] width = dims[w_axis] height = height if height is not None else inputs_shape[h_axis] width = width if width is not None else inputs_shape[w_axis] kernel_h, kernel_w = self.kernel_size stride_h, stride_w = self.strides if self.output_padding is None: out_pad_h = out_pad_w = None else: out_pad_h, out_pad_w = self.output_padding out_height = conv_utils.deconv_output_length(height, kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h, dilation=self.dilation_rate[0]) out_width = conv_utils.deconv_output_length(width, kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w, dilation=self.dilation_rate[1]) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_height, out_width) else: output_shape = (batch_size, out_height, out_width, self.filters) output_shape_tensor = array_ops.stack(output_shape) outputs = backend.conv2d_transpose( inputs, self.kernel, output_shape_tensor, strides=self.strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate) if not context.executing_eagerly(): out_shape = self.compute_output_shape(inputs.shape) outputs.set_shape(out_shape) if self.use_bias: outputs = nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, h_axis, w_axis = 1, 2, 3 else: c_axis, h_axis, w_axis = 3, 1, 2 kernel_h, kernel_w = self.kernel_size stride_h, stride_w = self.strides if self.output_padding is None: out_pad_h = out_pad_w = None else: out_pad_h, out_pad_w = self.output_padding output_shape[c_axis] = self.filters output_shape[h_axis] = conv_utils.deconv_output_length( output_shape[h_axis], kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h, dilation=self.dilation_rate[0]) output_shape[w_axis] = conv_utils.deconv_output_length( output_shape[w_axis], kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w, dilation=self.dilation_rate[1]) return tensor_shape.TensorShape(output_shape) def get_config(self): config = super(Conv2DTranspose, self).get_config() config['output_padding'] = self.output_padding return config @keras_export('keras.layers.Conv3DTranspose', 'keras.layers.Convolution3DTranspose') class Conv3DTranspose(Conv3D): def __init__(self, filters, kernel_size, strides=(1, 1, 1), padding='valid', output_padding=None, data_format=None, dilation_rate=(1, 1, 1), activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): super(Conv3DTranspose, self).__init__( filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, kernel_initializer=initializers.get(kernel_initializer), bias_initializer=initializers.get(bias_initializer), kernel_regularizer=regularizers.get(kernel_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), kernel_constraint=constraints.get(kernel_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) self.output_padding = output_padding if self.output_padding is not None: self.output_padding = conv_utils.normalize_tuple( self.output_padding, 3, 'output_padding') for stride, out_pad in zip(self.strides, self.output_padding): if out_pad >= stride: raise ValueError('Stride ' + str(self.strides) + ' must be ' 'greater than output padding ' + str(self.output_padding)) def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) if len(input_shape) != 5: raise ValueError('Inputs should have rank 5, received input shape:', str(input_shape)) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'should be defined, found None: ' + str(input_shape)) input_dim = int(input_shape[channel_axis]) kernel_shape = self.kernel_size + (self.filters, input_dim) self.input_spec = InputSpec(ndim=5, axes={channel_axis: input_dim}) self.kernel = self.add_weight( 'kernel', shape=kernel_shape, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( 'bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): inputs_shape = array_ops.shape(inputs) batch_size = inputs_shape[0] if self.data_format == 'channels_first': d_axis, h_axis, w_axis = 2, 3, 4 else: d_axis, h_axis, w_axis = 1, 2, 3 depth = inputs_shape[d_axis] height = inputs_shape[h_axis] width = inputs_shape[w_axis] kernel_d, kernel_h, kernel_w = self.kernel_size stride_d, stride_h, stride_w = self.strides if self.output_padding is None: out_pad_d = out_pad_h = out_pad_w = None else: out_pad_d, out_pad_h, out_pad_w = self.output_padding out_depth = conv_utils.deconv_output_length(depth, kernel_d, padding=self.padding, output_padding=out_pad_d, stride=stride_d) out_height = conv_utils.deconv_output_length(height, kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h) out_width = conv_utils.deconv_output_length(width, kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w) if self.data_format == 'channels_first': output_shape = (batch_size, self.filters, out_depth, out_height, out_width) strides = (1, 1, stride_d, stride_h, stride_w) else: output_shape = (batch_size, out_depth, out_height, out_width, self.filters) strides = (1, stride_d, stride_h, stride_w, 1) output_shape_tensor = array_ops.stack(output_shape) outputs = nn.conv3d_transpose( inputs, self.kernel, output_shape_tensor, strides, data_format=conv_utils.convert_data_format(self.data_format, ndim=5), padding=self.padding.upper()) if not context.executing_eagerly(): out_shape = self.compute_output_shape(inputs.shape) outputs.set_shape(out_shape) if self.use_bias: outputs = nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.activation is not None: return self.activation(outputs) return outputs def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() output_shape = list(input_shape) if self.data_format == 'channels_first': c_axis, d_axis, h_axis, w_axis = 1, 2, 3, 4 else: c_axis, d_axis, h_axis, w_axis = 4, 1, 2, 3 kernel_d, kernel_h, kernel_w = self.kernel_size stride_d, stride_h, stride_w = self.strides if self.output_padding is None: out_pad_d = out_pad_h = out_pad_w = None else: out_pad_d, out_pad_h, out_pad_w = self.output_padding output_shape[c_axis] = self.filters output_shape[d_axis] = conv_utils.deconv_output_length( output_shape[d_axis], kernel_d, padding=self.padding, output_padding=out_pad_d, stride=stride_d) output_shape[h_axis] = conv_utils.deconv_output_length( output_shape[h_axis], kernel_h, padding=self.padding, output_padding=out_pad_h, stride=stride_h) output_shape[w_axis] = conv_utils.deconv_output_length( output_shape[w_axis], kernel_w, padding=self.padding, output_padding=out_pad_w, stride=stride_w) return tensor_shape.TensorShape(output_shape) def get_config(self): config = super(Conv3DTranspose, self).get_config() config.pop('dilation_rate') config['output_padding'] = self.output_padding return config class SeparableConv(Conv): def __init__(self, rank, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, trainable=True, name=None, **kwargs): super(SeparableConv, self).__init__( rank=rank, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activations.get(activation), use_bias=use_bias, bias_initializer=initializers.get(bias_initializer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), bias_constraint=bias_constraint, trainable=trainable, name=name, **kwargs) self.depth_multiplier = depth_multiplier self.depthwise_initializer = initializers.get(depthwise_initializer) self.pointwise_initializer = initializers.get(pointwise_initializer) self.depthwise_regularizer = regularizers.get(depthwise_regularizer) self.pointwise_regularizer = regularizers.get(pointwise_regularizer) self.depthwise_constraint = constraints.get(depthwise_constraint) self.pointwise_constraint = constraints.get(pointwise_constraint) def build(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs ' 'should be defined. Found `None`.') input_dim = int(input_shape[channel_axis]) self.input_spec = InputSpec(ndim=self.rank + 2, axes={channel_axis: input_dim}) depthwise_kernel_shape = self.kernel_size + (input_dim, self.depth_multiplier) pointwise_kernel_shape = ( 1,) * self.rank + (self.depth_multiplier * input_dim, self.filters) self.depthwise_kernel = self.add_weight( name='depthwise_kernel', shape=depthwise_kernel_shape, initializer=self.depthwise_initializer, regularizer=self.depthwise_regularizer, constraint=self.depthwise_constraint, trainable=True, dtype=self.dtype) self.pointwise_kernel = self.add_weight( name='pointwise_kernel', shape=pointwise_kernel_shape, initializer=self.pointwise_initializer, regularizer=self.pointwise_regularizer, constraint=self.pointwise_constraint, trainable=True, dtype=self.dtype) if self.use_bias: self.bias = self.add_weight( name='bias', shape=(self.filters,), initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, trainable=True, dtype=self.dtype) else: self.bias = None self.built = True def call(self, inputs): raise NotImplementedError def get_config(self): config = { 'filters': self.filters, 'kernel_size': self.kernel_size, 'strides': self.strides, 'padding': self.padding, 'data_format': self.data_format, 'depth_multiplier': self.depth_multiplier, 'dilation_rate': self.dilation_rate, 'activation': activations.serialize(self.activation), 'use_bias': self.use_bias, 'depthwise_initializer': initializers.serialize(self.depthwise_initializer), 'pointwise_initializer': initializers.serialize(self.pointwise_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'depthwise_regularizer': regularizers.serialize(self.depthwise_regularizer), 'pointwise_regularizer': regularizers.serialize(self.pointwise_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'depthwise_constraint': constraints.serialize(self.depthwise_constraint), 'pointwise_constraint': constraints.serialize(self.pointwise_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint) } base_config = super(SeparableConv, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.SeparableConv1D', 'keras.layers.SeparableConvolution1D') class SeparableConv1D(SeparableConv): def __init__(self, filters, kernel_size, strides=1, padding='valid', data_format=None, dilation_rate=1, depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs): super(SeparableConv1D, self).__init__( rank=1, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, depth_multiplier=depth_multiplier, activation=activations.get(activation), use_bias=use_bias, depthwise_initializer=initializers.get(depthwise_initializer), pointwise_initializer=initializers.get(pointwise_initializer), bias_initializer=initializers.get(bias_initializer), depthwise_regularizer=regularizers.get(depthwise_regularizer), pointwise_regularizer=regularizers.get(pointwise_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), depthwise_constraint=constraints.get(depthwise_constraint), pointwise_constraint=constraints.get(pointwise_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) def call(self, inputs): if self.padding == 'causal': inputs = array_ops.pad(inputs, self._compute_causal_padding()) if self.data_format == 'channels_last': strides = (1,) + self.strides * 2 + (1,) spatial_start_dim = 1 else: strides = (1, 1) + self.strides * 2 spatial_start_dim = 2 inputs = array_ops.expand_dims(inputs, spatial_start_dim) depthwise_kernel = array_ops.expand_dims(self.depthwise_kernel, 0) pointwise_kernel = array_ops.expand_dims(self.pointwise_kernel, 0) dilation_rate = (1,) + self.dilation_rate if self.padding == 'causal': op_padding = 'valid' else: op_padding = self.padding outputs = nn.separable_conv2d( inputs, depthwise_kernel, pointwise_kernel, strides=strides, padding=op_padding.upper(), rate=dilation_rate, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.use_bias: outputs = nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) outputs = array_ops.squeeze(outputs, [spatial_start_dim]) if self.activation is not None: return self.activation(outputs) return outputs @keras_export('keras.layers.SeparableConv2D', 'keras.layers.SeparableConvolution2D') class SeparableConv2D(SeparableConv): def __init__(self, filters, kernel_size, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), depth_multiplier=1, activation=None, use_bias=True, depthwise_initializer='glorot_uniform', pointwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, pointwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, pointwise_constraint=None, bias_constraint=None, **kwargs): super(SeparableConv2D, self).__init__( rank=2, filters=filters, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, depth_multiplier=depth_multiplier, activation=activations.get(activation), use_bias=use_bias, depthwise_initializer=initializers.get(depthwise_initializer), pointwise_initializer=initializers.get(pointwise_initializer), bias_initializer=initializers.get(bias_initializer), depthwise_regularizer=regularizers.get(depthwise_regularizer), pointwise_regularizer=regularizers.get(pointwise_regularizer), bias_regularizer=regularizers.get(bias_regularizer), activity_regularizer=regularizers.get(activity_regularizer), depthwise_constraint=constraints.get(depthwise_constraint), pointwise_constraint=constraints.get(pointwise_constraint), bias_constraint=constraints.get(bias_constraint), **kwargs) def call(self, inputs): if self.data_format == 'channels_last': strides = (1,) + self.strides + (1,) else: strides = (1, 1) + self.strides outputs = nn.separable_conv2d( inputs, self.depthwise_kernel, self.pointwise_kernel, strides=strides, padding=self.padding.upper(), rate=self.dilation_rate, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.use_bias: outputs = nn.bias_add( outputs, self.bias, data_format=conv_utils.convert_data_format(self.data_format, ndim=4)) if self.activation is not None: return self.activation(outputs) return outputs @keras_export('keras.layers.DepthwiseConv2D') class DepthwiseConv2D(Conv2D): def __init__(self, kernel_size, strides=(1, 1), padding='valid', depth_multiplier=1, data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, depthwise_initializer='glorot_uniform', bias_initializer='zeros', depthwise_regularizer=None, bias_regularizer=None, activity_regularizer=None, depthwise_constraint=None, bias_constraint=None, **kwargs): super(DepthwiseConv2D, self).__init__( filters=None, kernel_size=kernel_size, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, activation=activation, use_bias=use_bias, bias_regularizer=bias_regularizer, activity_regularizer=activity_regularizer, bias_constraint=bias_constraint, **kwargs) self.depth_multiplier = depth_multiplier self.depthwise_initializer = initializers.get(depthwise_initializer) self.depthwise_regularizer = regularizers.get(depthwise_regularizer) self.depthwise_constraint = constraints.get(depthwise_constraint) self.bias_initializer = initializers.get(bias_initializer) def build(self, input_shape): if len(input_shape) < 4: raise ValueError('Inputs to `DepthwiseConv2D` should have rank 4. ' 'Received input shape:', str(input_shape)) input_shape = tensor_shape.TensorShape(input_shape) channel_axis = self._get_channel_axis() if input_shape.dims[channel_axis].value is None: raise ValueError('The channel dimension of the inputs to ' '`DepthwiseConv2D` ' 'should be defined. Found `None`.') input_dim = int(input_shape[channel_axis]) depthwise_kernel_shape = (self.kernel_size[0], self.kernel_size[1], input_dim, self.depth_multiplier) self.depthwise_kernel = self.add_weight( shape=depthwise_kernel_shape, initializer=self.depthwise_initializer, name='depthwise_kernel', regularizer=self.depthwise_regularizer, constraint=self.depthwise_constraint) if self.use_bias: self.bias = self.add_weight(shape=(input_dim * self.depth_multiplier,), initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) self.built = True def call(self, inputs): outputs = backend.depthwise_conv2d( inputs, self.depthwise_kernel, strides=self.strides, padding=self.padding, dilation_rate=self.dilation_rate, data_format=self.data_format) if self.use_bias: outputs = backend.bias_add( outputs, self.bias, data_format=self.data_format) if self.activation is not None: return self.activation(outputs) return outputs @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): if self.data_format == 'channels_first': rows = input_shape[2] cols = input_shape[3] out_filters = input_shape[1] * self.depth_multiplier elif self.data_format == 'channels_last': rows = input_shape[1] cols = input_shape[2] out_filters = input_shape[3] * self.depth_multiplier rows = conv_utils.conv_output_length(rows, self.kernel_size[0], self.padding, self.strides[0], self.dilation_rate[0]) cols = conv_utils.conv_output_length(cols, self.kernel_size[1], self.padding, self.strides[1], self.dilation_rate[1]) if self.data_format == 'channels_first': return (input_shape[0], out_filters, rows, cols) elif self.data_format == 'channels_last': return (input_shape[0], rows, cols, out_filters) def get_config(self): config = super(DepthwiseConv2D, self).get_config() config.pop('filters') config.pop('kernel_initializer') config.pop('kernel_regularizer') config.pop('kernel_constraint') config['depth_multiplier'] = self.depth_multiplier config['depthwise_initializer'] = initializers.serialize( self.depthwise_initializer) config['depthwise_regularizer'] = regularizers.serialize( self.depthwise_regularizer) config['depthwise_constraint'] = constraints.serialize( self.depthwise_constraint) return config @keras_export('keras.layers.UpSampling1D') class UpSampling1D(Layer): def __init__(self, size=2, **kwargs): super(UpSampling1D, self).__init__(**kwargs) self.size = int(size) self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() size = self.size * input_shape[1] if input_shape[1] is not None else None return tensor_shape.TensorShape([input_shape[0], size, input_shape[2]]) def call(self, inputs): output = backend.repeat_elements(inputs, self.size, axis=1) return output def get_config(self): config = {'size': self.size} base_config = super(UpSampling1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.UpSampling2D') class UpSampling2D(Layer): def __init__(self, size=(2, 2), data_format=None, interpolation='nearest', **kwargs): super(UpSampling2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) self.size = conv_utils.normalize_tuple(size, 2, 'size') if interpolation not in {'nearest', 'bilinear'}: raise ValueError('`interpolation` argument should be one of `"nearest"` ' 'or `"bilinear"`.') self.interpolation = interpolation self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': height = self.size[0] * input_shape[ 2] if input_shape[2] is not None else None width = self.size[1] * input_shape[ 3] if input_shape[3] is not None else None return tensor_shape.TensorShape( [input_shape[0], input_shape[1], height, width]) else: height = self.size[0] * input_shape[ 1] if input_shape[1] is not None else None width = self.size[1] * input_shape[ 2] if input_shape[2] is not None else None return tensor_shape.TensorShape( [input_shape[0], height, width, input_shape[3]]) def call(self, inputs): return backend.resize_images( inputs, self.size[0], self.size[1], self.data_format, interpolation=self.interpolation) def get_config(self): config = { 'size': self.size, 'data_format': self.data_format, 'interpolation': self.interpolation } base_config = super(UpSampling2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.UpSampling3D') class UpSampling3D(Layer): def __init__(self, size=(2, 2, 2), data_format=None, **kwargs): self.data_format = conv_utils.normalize_data_format(data_format) self.size = conv_utils.normalize_tuple(size, 3, 'size') self.input_spec = InputSpec(ndim=5) super(UpSampling3D, self).__init__(**kwargs) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': dim1 = self.size[0] * input_shape[ 2] if input_shape[2] is not None else None dim2 = self.size[1] * input_shape[ 3] if input_shape[3] is not None else None dim3 = self.size[2] * input_shape[ 4] if input_shape[4] is not None else None return tensor_shape.TensorShape( [input_shape[0], input_shape[1], dim1, dim2, dim3]) else: dim1 = self.size[0] * input_shape[ 1] if input_shape[1] is not None else None dim2 = self.size[1] * input_shape[ 2] if input_shape[2] is not None else None dim3 = self.size[2] * input_shape[ 3] if input_shape[3] is not None else None return tensor_shape.TensorShape( [input_shape[0], dim1, dim2, dim3, input_shape[4]]) def call(self, inputs): return backend.resize_volumes( inputs, self.size[0], self.size[1], self.size[2], self.data_format) def get_config(self): config = {'size': self.size, 'data_format': self.data_format} base_config = super(UpSampling3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.ZeroPadding1D') class ZeroPadding1D(Layer): def __init__(self, padding=1, **kwargs): super(ZeroPadding1D, self).__init__(**kwargs) self.padding = conv_utils.normalize_tuple(padding, 2, 'padding') self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): if input_shape[1] is not None: length = input_shape[1] + self.padding[0] + self.padding[1] else: length = None return tensor_shape.TensorShape([input_shape[0], length, input_shape[2]]) def call(self, inputs): return backend.temporal_padding(inputs, padding=self.padding) def get_config(self): config = {'padding': self.padding} base_config = super(ZeroPadding1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.ZeroPadding2D') class ZeroPadding2D(Layer): def __init__(self, padding=(1, 1), data_format=None, **kwargs): super(ZeroPadding2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(padding, int): self.padding = ((padding, padding), (padding, padding)) elif hasattr(padding, '__len__'): if len(padding) != 2: raise ValueError('`padding` should have two elements. ' 'Found: ' + str(padding)) height_padding = conv_utils.normalize_tuple(padding[0], 2, '1st entry of padding') width_padding = conv_utils.normalize_tuple(padding[1], 2, '2nd entry of padding') self.padding = (height_padding, width_padding) else: raise ValueError('`padding` should be either an int, ' 'a tuple of 2 ints ' '(symmetric_height_pad, symmetric_width_pad), ' 'or a tuple of 2 tuples of 2 ints ' '((top_pad, bottom_pad), (left_pad, right_pad)). ' 'Found: ' + str(padding)) self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': if input_shape[2] is not None: rows = input_shape[2] + self.padding[0][0] + self.padding[0][1] else: rows = None if input_shape[3] is not None: cols = input_shape[3] + self.padding[1][0] + self.padding[1][1] else: cols = None return tensor_shape.TensorShape( [input_shape[0], input_shape[1], rows, cols]) elif self.data_format == 'channels_last': if input_shape[1] is not None: rows = input_shape[1] + self.padding[0][0] + self.padding[0][1] else: rows = None if input_shape[2] is not None: cols = input_shape[2] + self.padding[1][0] + self.padding[1][1] else: cols = None return tensor_shape.TensorShape( [input_shape[0], rows, cols, input_shape[3]]) def call(self, inputs): return backend.spatial_2d_padding( inputs, padding=self.padding, data_format=self.data_format) def get_config(self): config = {'padding': self.padding, 'data_format': self.data_format} base_config = super(ZeroPadding2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.ZeroPadding3D') class ZeroPadding3D(Layer): def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs): super(ZeroPadding3D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(padding, int): self.padding = ((padding, padding), (padding, padding), (padding, padding)) elif hasattr(padding, '__len__'): if len(padding) != 3: raise ValueError('`padding` should have 3 elements. ' 'Found: ' + str(padding)) dim1_padding = conv_utils.normalize_tuple(padding[0], 2, '1st entry of padding') dim2_padding = conv_utils.normalize_tuple(padding[1], 2, '2nd entry of padding') dim3_padding = conv_utils.normalize_tuple(padding[2], 2, '3rd entry of padding') self.padding = (dim1_padding, dim2_padding, dim3_padding) else: raise ValueError( '`padding` should be either an int, ' 'a tuple of 3 ints ' '(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad), ' 'or a tuple of 3 tuples of 2 ints ' '((left_dim1_pad, right_dim1_pad),' ' (left_dim2_pad, right_dim2_pad),' ' (left_dim3_pad, right_dim2_pad)). ' 'Found: ' + str(padding)) self.input_spec = InputSpec(ndim=5) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': if input_shape[2] is not None: dim1 = input_shape[2] + 2 * self.padding[0][0] else: dim1 = None if input_shape[3] is not None: dim2 = input_shape[3] + 2 * self.padding[1][0] else: dim2 = None if input_shape[4] is not None: dim3 = input_shape[4] + 2 * self.padding[2][0] else: dim3 = None return tensor_shape.TensorShape( [input_shape[0], input_shape[1], dim1, dim2, dim3]) elif self.data_format == 'channels_last': if input_shape[1] is not None: dim1 = input_shape[1] + 2 * self.padding[0][1] else: dim1 = None if input_shape[2] is not None: dim2 = input_shape[2] + 2 * self.padding[1][1] else: dim2 = None if input_shape[3] is not None: dim3 = input_shape[3] + 2 * self.padding[2][1] else: dim3 = None return tensor_shape.TensorShape( [input_shape[0], dim1, dim2, dim3, input_shape[4]]) def call(self, inputs): return backend.spatial_3d_padding( inputs, padding=self.padding, data_format=self.data_format) def get_config(self): config = {'padding': self.padding, 'data_format': self.data_format} base_config = super(ZeroPadding3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Cropping1D') class Cropping1D(Layer): def __init__(self, cropping=(1, 1), **kwargs): super(Cropping1D, self).__init__(**kwargs) self.cropping = conv_utils.normalize_tuple(cropping, 2, 'cropping') self.input_spec = InputSpec(ndim=3) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if input_shape[1] is not None: length = input_shape[1] - self.cropping[0] - self.cropping[1] else: length = None return tensor_shape.TensorShape([input_shape[0], length, input_shape[2]]) def call(self, inputs): if self.cropping[1] == 0: return inputs[:, self.cropping[0]:, :] else: return inputs[:, self.cropping[0]:-self.cropping[1], :] def get_config(self): config = {'cropping': self.cropping} base_config = super(Cropping1D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Cropping2D') class Cropping2D(Layer): def __init__(self, cropping=((0, 0), (0, 0)), data_format=None, **kwargs): super(Cropping2D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(cropping, int): self.cropping = ((cropping, cropping), (cropping, cropping)) elif hasattr(cropping, '__len__'): if len(cropping) != 2: raise ValueError('`cropping` should have two elements. ' 'Found: ' + str(cropping)) height_cropping = conv_utils.normalize_tuple(cropping[0], 2, '1st entry of cropping') width_cropping = conv_utils.normalize_tuple(cropping[1], 2, '2nd entry of cropping') self.cropping = (height_cropping, width_cropping) else: raise ValueError('`cropping` should be either an int, ' 'a tuple of 2 ints ' '(symmetric_height_crop, symmetric_width_crop), ' 'or a tuple of 2 tuples of 2 ints ' '((top_crop, bottom_crop), (left_crop, right_crop)). ' 'Found: ' + str(cropping)) self.input_spec = InputSpec(ndim=4) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': return tensor_shape.TensorShape([ input_shape[0], input_shape[1], input_shape[2] - self.cropping[0][0] - self.cropping[0][1] if input_shape[2] else None, input_shape[3] - self.cropping[1][0] - self.cropping[1][1] if input_shape[3] else None ]) else: return tensor_shape.TensorShape([ input_shape[0], input_shape[1] - self.cropping[0][0] - self.cropping[0][1] if input_shape[1] else None, input_shape[2] - self.cropping[1][0] - self.cropping[1][1] if input_shape[2] else None, input_shape[3] ]) def call(self, inputs): if self.data_format == 'channels_first': if self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:] elif self.cropping[0][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1]] elif self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:] return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:-self.cropping[1][1]] else: if self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, :] elif self.cropping[0][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], :] elif self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:, :] return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[ 1][0]:-self.cropping[1][1], :] def get_config(self): config = {'cropping': self.cropping, 'data_format': self.data_format} base_config = super(Cropping2D, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Cropping3D') class Cropping3D(Layer): def __init__(self, cropping=((1, 1), (1, 1), (1, 1)), data_format=None, **kwargs): super(Cropping3D, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) if isinstance(cropping, int): self.cropping = ((cropping, cropping), (cropping, cropping), (cropping, cropping)) elif hasattr(cropping, '__len__'): if len(cropping) != 3: raise ValueError('`cropping` should have 3 elements. ' 'Found: ' + str(cropping)) dim1_cropping = conv_utils.normalize_tuple(cropping[0], 2, '1st entry of cropping') dim2_cropping = conv_utils.normalize_tuple(cropping[1], 2, '2nd entry of cropping') dim3_cropping = conv_utils.normalize_tuple(cropping[2], 2, '3rd entry of cropping') self.cropping = (dim1_cropping, dim2_cropping, dim3_cropping) else: raise ValueError( '`cropping` should be either an int, ' 'a tuple of 3 ints ' '(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop), ' 'or a tuple of 3 tuples of 2 ints ' '((left_dim1_crop, right_dim1_crop),' ' (left_dim2_crop, right_dim2_crop),' ' (left_dim3_crop, right_dim2_crop)). ' 'Found: ' + str(cropping)) self.input_spec = InputSpec(ndim=5) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if self.data_format == 'channels_first': if input_shape[2] is not None: dim1 = input_shape[2] - self.cropping[0][0] - self.cropping[0][1] else: dim1 = None if input_shape[3] is not None: dim2 = input_shape[3] - self.cropping[1][0] - self.cropping[1][1] else: dim2 = None if input_shape[4] is not None: dim3 = input_shape[4] - self.cropping[2][0] - self.cropping[2][1] else: dim3 = None return tensor_shape.TensorShape( [input_shape[0], input_shape[1], dim1, dim2, dim3]) elif self.data_format == 'channels_last': if input_shape[1] is not None: dim1 = input_shape[1] - self.cropping[0][0] - self.cropping[0][1] else: dim1 = None if input_shape[2] is not None: dim2 = input_shape[2] - self.cropping[1][0] - self.cropping[1][1] else: dim2 = None if input_shape[3] is not None: dim3 = input_shape[3] - self.cropping[2][0] - self.cropping[2][1] else: dim3 = None return tensor_shape.TensorShape( [input_shape[0], dim1, dim2, dim3, input_shape[4]]) def call(self, inputs): if self.data_format == 'channels_first': if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:] elif self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1]] elif self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]:] elif self.cropping[0][1] == self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]:] elif self.cropping[0][1] == 0: return inputs[:, :, self.cropping[0][0]:, self.cropping[1][ 0]:-self.cropping[1][1], self.cropping[2][0]:-self.cropping[2][1]] elif self.cropping[1][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self. cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1]] elif self.cropping[2][1] == 0: return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self. cropping[1][0]:-self.cropping[1][1], self.cropping[2][0]:] return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:-self.cropping[1][1], self.cropping[2][ 0]:-self.cropping[2][1]] else: if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:, :] elif self.cropping[0][1] == self.cropping[1][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1], :] elif self.cropping[1][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]:, :] elif self.cropping[0][1] == self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][0]: -self.cropping[1][1], self.cropping[2][0]:, :] elif self.cropping[0][1] == 0: return inputs[:, self.cropping[0][0]:, self.cropping[1][ 0]:-self.cropping[1][1], self.cropping[2][0]: -self.cropping[2][1], :] elif self.cropping[1][1] == 0: return inputs[:, self.cropping[0][ 0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]: -self.cropping[2][1], :] elif self.cropping[2][1] == 0: return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[1][0]:-self.cropping[1][1], self.cropping[ 2][0]:, :] return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[ 1][0]:-self.cropping[1][1], self.cropping[2][0]: -self.cropping[2][1], :] def get_config(self): config = {'cropping': self.cropping, 'data_format': self.data_format} base_config = super(Cropping3D, self).get_config() return dict(list(base_config.items()) + list(config.items())) Convolution1D = Conv1D Convolution2D = Conv2D Convolution3D = Conv3D SeparableConvolution1D = SeparableConv1D SeparableConvolution2D = SeparableConv2D Convolution2DTranspose = Conv2DTranspose Convolution3DTranspose = Conv3DTranspose Deconvolution2D = Deconv2D = Conv2DTranspose Deconvolution3D = Deconv3D = Conv3DTranspose
true
true
f7148d6111bc6f731ff2f47e5c14db68aaca4f46
590
py
Python
src/aoc/__init__.py
CreatingNull/AoC-2021
ee0aec7aa2f4d7cb2d62838d39f8c74edae8cc96
[ "MIT" ]
null
null
null
src/aoc/__init__.py
CreatingNull/AoC-2021
ee0aec7aa2f4d7cb2d62838d39f8c74edae8cc96
[ "MIT" ]
null
null
null
src/aoc/__init__.py
CreatingNull/AoC-2021
ee0aec7aa2f4d7cb2d62838d39f8c74edae8cc96
[ "MIT" ]
null
null
null
"""Root package for the challenge. Contains generic functionality not specific to days. """ import logging import sys from functools import partial from pathlib import Path ROOT_PATH = Path(Path(__file__).parents[1]) open_utf8 = partial(open, encoding="UTF-8") # Open with explict encoding # Configuring the global logger log = logging.getLogger() log.setLevel(logging.INFO) __handler = logging.StreamHandler(sys.stdout) __handler.setLevel(logging.DEBUG) __handler.setFormatter( logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") ) log.addHandler(__handler)
25.652174
77
0.766102
import logging import sys from functools import partial from pathlib import Path ROOT_PATH = Path(Path(__file__).parents[1]) open_utf8 = partial(open, encoding="UTF-8") log = logging.getLogger() log.setLevel(logging.INFO) __handler = logging.StreamHandler(sys.stdout) __handler.setLevel(logging.DEBUG) __handler.setFormatter( logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") ) log.addHandler(__handler)
true
true
f7148e83286d37d30f28041686db57b3c928f8c8
5,117
py
Python
command/download.py
aungthuphyo21/aungthuphyo22
462c515e7dc987aa877dd8e38ccd1e3e6abeab3d
[ "MIT" ]
null
null
null
command/download.py
aungthuphyo21/aungthuphyo22
462c515e7dc987aa877dd8e38ccd1e3e6abeab3d
[ "MIT" ]
null
null
null
command/download.py
aungthuphyo21/aungthuphyo22
462c515e7dc987aa877dd8e38ccd1e3e6abeab3d
[ "MIT" ]
null
null
null
#!/usr/bin/env python from __future__ import print_function import os import sys import argparse import subprocess from bddown_core import Pan from util import convert_none, parse_url, add_http, logger from config import global_config def download_command(filename, savedir, link, cookies, limit=None, output_dir=None): reload(sys) sys.setdefaultencoding("utf-8") bool(output_dir) and not os.path.exists(output_dir) and os.makedirs(output_dir) print("\033[32m" + filename + "\033[0m") pan_ua = 'netdisk;5.2.6;PC;PC-Windows;6.2.9200;WindowsBaiduYunGuanJia' cmd = 'aria2c -c -d "{savedir}" -o "{filename}" -s10 -x10' \ ' --user-agent="{useragent}" --header "Referer:http://pan.baidu.com/disk/home"' \ ' {cookies} {limit} {dir}' \ ' "{link}"'.format(savedir=savedir, filename=filename, useragent=pan_ua, link=link, cookies=convert_none("--header \"Cookies: ", cookies), limit=convert_none('--max-download-limit=', limit), dir=convert_none('--dir=', output_dir)) print(cmd) subprocess.call(cmd, shell=True) def select_download(fis): if len(fis) <= 1: return fis print("File list:") counter = 1 for fi in fis: savedir = fi.path.replace(fi.parent_path, '', 1)[1:] print(str(counter) + ')', savedir + "/" + unicode(fi.filename).encode('utf8')) counter += 1 input_numbers = raw_input("Please select files to download(e.g., 1,3-5,7):\n") selected_numbers = [] for part in input_numbers.split(','): x = part.split('-') if len(x) == 1: selected_numbers += [int(x[0])] elif len(x) == 2: selected_numbers += range(int(x[0]), int(x[1])+1) else: print("Error, your input seems illegal." + str(len(x))) return None # ensure no duplicate numbers selected_numbers = list(set(selected_numbers)) selected_fis = [fis[i-1] for i in selected_numbers] print("Download list:") counter = 1 for sfi in selected_fis: savedir = sfi.path.replace(sfi.parent_path, '', 1)[1:] print(str(counter) + ')', savedir + "/" + unicode(sfi.filename).encode('utf8')) counter += 1 return selected_fis def download(args): limit = global_config.limit output_dir = global_config.dir parser = argparse.ArgumentParser(description="download command arg parser") parser.add_argument('-L', '--limit', action="store", dest='limit', help="Max download speed limit.") parser.add_argument('-D', '--dir', action="store", dest='output_dir', help="Download task to dir.") parser.add_argument('-S', '--secret', action="store", dest='secret', help="Retrieval password.", default="") parser.add_argument('-P', '--partial', action="count", help="Partial download.") if not args: parser.print_help() exit(1) namespace, links = parser.parse_known_args(args) secret = namespace.secret if namespace.limit: limit = namespace.limit if namespace.output_dir: output_dir = namespace.output_dir # if is wap links = [link.replace("wap/link", "share/link") for link in links] # add 'http://' links = map(add_http, links) for url in links: res = parse_url(url) # normal if res.get('type') == 1: pan = Pan() fis = pan.get_file_infos(url, secret) if namespace.partial: while True: fis = select_download(fis) if fis is not None: break for fi in fis: cookies = 'BDUSS={0}'.format(pan.bduss) if pan.bduss else '' if cookies and pan.pcsett: cookies += ';pcsett={0}'.format(pan.pcsett) if cookies: cookies += '"' savedir = fi.path.replace(fi.parent_path, '', 1)[1:] download_command(fi.filename, savedir, fi.dlink, cookies=cookies, limit=limit, output_dir=output_dir) elif res.get('type') == 4: pan = Pan() fsid = res.get('fsid') newUrl = res.get('url') infos = pan.get_file_infos(newUrl, secret, fsid) cookies = 'BDUSS={0}'.format(pan.bduss) if pan.bduss else '' if cookies and pan.pcsett: cookies += ';pcsett={0}'.format(pan.pcsett) if cookies: cookies += '"' for info in infos: download_command(info.filename, info.dlink, cookies=cookies, limit=limit, output_dir=output_dir) # album elif res.get('type') == 2: raise NotImplementedError('This function has not implemented.') # home elif res.get('type') == 3: raise NotImplementedError('This function has not implemented.') elif res.get('type') == 0: logger.debug(url, extra={"type": "wrong link", "method": "None"}) continue else: continue sys.exit(0)
37.07971
117
0.577682
from __future__ import print_function import os import sys import argparse import subprocess from bddown_core import Pan from util import convert_none, parse_url, add_http, logger from config import global_config def download_command(filename, savedir, link, cookies, limit=None, output_dir=None): reload(sys) sys.setdefaultencoding("utf-8") bool(output_dir) and not os.path.exists(output_dir) and os.makedirs(output_dir) print("\033[32m" + filename + "\033[0m") pan_ua = 'netdisk;5.2.6;PC;PC-Windows;6.2.9200;WindowsBaiduYunGuanJia' cmd = 'aria2c -c -d "{savedir}" -o "{filename}" -s10 -x10' \ ' --user-agent="{useragent}" --header "Referer:http://pan.baidu.com/disk/home"' \ ' {cookies} {limit} {dir}' \ ' "{link}"'.format(savedir=savedir, filename=filename, useragent=pan_ua, link=link, cookies=convert_none("--header \"Cookies: ", cookies), limit=convert_none('--max-download-limit=', limit), dir=convert_none('--dir=', output_dir)) print(cmd) subprocess.call(cmd, shell=True) def select_download(fis): if len(fis) <= 1: return fis print("File list:") counter = 1 for fi in fis: savedir = fi.path.replace(fi.parent_path, '', 1)[1:] print(str(counter) + ')', savedir + "/" + unicode(fi.filename).encode('utf8')) counter += 1 input_numbers = raw_input("Please select files to download(e.g., 1,3-5,7):\n") selected_numbers = [] for part in input_numbers.split(','): x = part.split('-') if len(x) == 1: selected_numbers += [int(x[0])] elif len(x) == 2: selected_numbers += range(int(x[0]), int(x[1])+1) else: print("Error, your input seems illegal." + str(len(x))) return None # ensure no duplicate numbers selected_numbers = list(set(selected_numbers)) selected_fis = [fis[i-1] for i in selected_numbers] print("Download list:") counter = 1 for sfi in selected_fis: savedir = sfi.path.replace(sfi.parent_path, '', 1)[1:] print(str(counter) + ')', savedir + "/" + unicode(sfi.filename).encode('utf8')) counter += 1 return selected_fis def download(args): limit = global_config.limit output_dir = global_config.dir parser = argparse.ArgumentParser(description="download command arg parser") parser.add_argument('-L', '--limit', action="store", dest='limit', help="Max download speed limit.") parser.add_argument('-D', '--dir', action="store", dest='output_dir', help="Download task to dir.") parser.add_argument('-S', '--secret', action="store", dest='secret', help="Retrieval password.", default="") parser.add_argument('-P', '--partial', action="count", help="Partial download.") if not args: parser.print_help() exit(1) namespace, links = parser.parse_known_args(args) secret = namespace.secret if namespace.limit: limit = namespace.limit if namespace.output_dir: output_dir = namespace.output_dir # if is wap links = [link.replace("wap/link", "share/link") for link in links] # add 'http://' links = map(add_http, links) for url in links: res = parse_url(url) # normal if res.get('type') == 1: pan = Pan() fis = pan.get_file_infos(url, secret) if namespace.partial: while True: fis = select_download(fis) if fis is not None: break for fi in fis: cookies = 'BDUSS={0}'.format(pan.bduss) if pan.bduss else '' if cookies and pan.pcsett: cookies += ';pcsett={0}'.format(pan.pcsett) if cookies: cookies += '"' savedir = fi.path.replace(fi.parent_path, '', 1)[1:] download_command(fi.filename, savedir, fi.dlink, cookies=cookies, limit=limit, output_dir=output_dir) elif res.get('type') == 4: pan = Pan() fsid = res.get('fsid') newUrl = res.get('url') infos = pan.get_file_infos(newUrl, secret, fsid) cookies = 'BDUSS={0}'.format(pan.bduss) if pan.bduss else '' if cookies and pan.pcsett: cookies += ';pcsett={0}'.format(pan.pcsett) if cookies: cookies += '"' for info in infos: download_command(info.filename, info.dlink, cookies=cookies, limit=limit, output_dir=output_dir) # album elif res.get('type') == 2: raise NotImplementedError('This function has not implemented.') # home elif res.get('type') == 3: raise NotImplementedError('This function has not implemented.') elif res.get('type') == 0: logger.debug(url, extra={"type": "wrong link", "method": "None"}) continue else: continue sys.exit(0)
true
true
f7148f1f8278d6d236a00eec569bd331d09b34c0
1,299
py
Python
main.py
TakeItIsi/Snakehogs-
6c92184a564738a1af8bb7e0b9a3bc74689fde49
[ "MIT" ]
null
null
null
main.py
TakeItIsi/Snakehogs-
6c92184a564738a1af8bb7e0b9a3bc74689fde49
[ "MIT" ]
null
null
null
main.py
TakeItIsi/Snakehogs-
6c92184a564738a1af8bb7e0b9a3bc74689fde49
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import pygame import os from Controlador.Basic_Controller import Controlador from Controlador.Menu_Controller import Menu from Controlador.Versus_Controller import Versus_Controlador __author__ = "Isidora Ulloa" __license__ = "GPL" __version__ = "1.0.0" __email__ = "isidora.ulloa@ug.uchile.cl" pygame.init() titulo = Menu("Recursos/menu sprite full.png","", True) while True: while titulo.mainloop: titulo.run() if titulo.versus.on: instruccion = Menu("Recursos/instrucciones 12.png","", False) program = Versus_Controlador(titulo.walls.on) else: instruccion = Menu("Recursos/instrucciones 11.png", "", False) program = Controlador(titulo.walls.on) while instruccion.mainloop: instruccion.run() while program.run==True: program.update() pygame.time.wait(program.refresh) if titulo.versus.on: fin = Menu(program.end,"Cuy: " + str(program.puntaje2.counter) + " Erizo: " + str(program.puntaje1.counter), False) else: fin= Menu(program.end, " Puntos: " + str(program.puntaje.counter), False) while fin.running==True: fin.run() titulo.mainloop=True
34.184211
151
0.638953
import pygame import os from Controlador.Basic_Controller import Controlador from Controlador.Menu_Controller import Menu from Controlador.Versus_Controller import Versus_Controlador __author__ = "Isidora Ulloa" __license__ = "GPL" __version__ = "1.0.0" __email__ = "isidora.ulloa@ug.uchile.cl" pygame.init() titulo = Menu("Recursos/menu sprite full.png","", True) while True: while titulo.mainloop: titulo.run() if titulo.versus.on: instruccion = Menu("Recursos/instrucciones 12.png","", False) program = Versus_Controlador(titulo.walls.on) else: instruccion = Menu("Recursos/instrucciones 11.png", "", False) program = Controlador(titulo.walls.on) while instruccion.mainloop: instruccion.run() while program.run==True: program.update() pygame.time.wait(program.refresh) if titulo.versus.on: fin = Menu(program.end,"Cuy: " + str(program.puntaje2.counter) + " Erizo: " + str(program.puntaje1.counter), False) else: fin= Menu(program.end, " Puntos: " + str(program.puntaje.counter), False) while fin.running==True: fin.run() titulo.mainloop=True
true
true
f7148f4a83cab36a038bcd04077b0e24ca251006
1,137
py
Python
migrations/versions/8b25b23d386f_chquery_the_comments_migration.py
macc254/Personal-Blog
3af6083f78e65636a9cf6caa1a3598b13b3b0134
[ "Unlicense" ]
null
null
null
migrations/versions/8b25b23d386f_chquery_the_comments_migration.py
macc254/Personal-Blog
3af6083f78e65636a9cf6caa1a3598b13b3b0134
[ "Unlicense" ]
null
null
null
migrations/versions/8b25b23d386f_chquery_the_comments_migration.py
macc254/Personal-Blog
3af6083f78e65636a9cf6caa1a3598b13b3b0134
[ "Unlicense" ]
null
null
null
"""ChQuery the comments Migration Revision ID: 8b25b23d386f Revises: a21b8da19c7d Create Date: 2022-03-12 09:58:47.379065 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '8b25b23d386f' down_revision = 'a21b8da19c7d' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('comments', sa.Column('blogs_id', sa.Integer(), nullable=False)) op.drop_constraint('comments_pitch_id_fkey', 'comments', type_='foreignkey') op.create_foreign_key(None, 'comments', 'blogs', ['blogs_id'], ['id']) op.drop_column('comments', 'pitch_id') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('comments', sa.Column('pitch_id', sa.INTEGER(), autoincrement=False, nullable=False)) op.drop_constraint(None, 'comments', type_='foreignkey') op.create_foreign_key('comments_pitch_id_fkey', 'comments', 'blogs', ['pitch_id'], ['id']) op.drop_column('comments', 'blogs_id') # ### end Alembic commands ###
32.485714
103
0.700967
from alembic import op import sqlalchemy as sa revision = '8b25b23d386f' down_revision = 'a21b8da19c7d' branch_labels = None depends_on = None def upgrade(): oreign_key(None, 'comments', 'blogs', ['blogs_id'], ['id']) op.drop_column('comments', 'pitch_id') tch_id'], ['id']) op.drop_column('comments', 'blogs_id')
true
true
f714902580ef72ea76cb338fc2ad31571450e93b
2,584
py
Python
openGaussBase/testcase/SYSTEM_CATALOGS&SYSTEM_VIEWS/SYSTEM_VIEW/Opengauss_Function_System_View_Case0044.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/SYSTEM_CATALOGS&SYSTEM_VIEWS/SYSTEM_VIEW/Opengauss_Function_System_View_Case0044.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/SYSTEM_CATALOGS&SYSTEM_VIEWS/SYSTEM_VIEW/Opengauss_Function_System_View_Case0044.py
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ """ Case Type : 系统视图 Case Name : 测试系统视图PG_STAT_DATABASE字段与数据类型 Description : 1.查看系统视图PG_STAT_DATABASE的结构 2.该视图字段与对应字段数据类型是否正确 Expect : 1.查看系统视图PG_STAT_DATABASE的结构成功 2.该视图字段与字段数据类型对应正确 History : """ import unittest from testcase.utils.Common import Common from testcase.utils.CommonSH import CommonSH from testcase.utils.Logger import Logger LOG = Logger() class SystemView(unittest.TestCase): def setUp(self): LOG.info('----------------this is setup-----------------------') LOG.info( '------Opengauss_Function_System_View_Case0044开始执行----------') self.com = Common() self.comsh = CommonSH('dbuser') self.expect_result_dict = { 'Column': ['datid', 'datname', 'numbackends', 'xact_commit', 'xact_rollback', 'blks_read', 'blks_hit', 'tup_returned', 'tup_fetched', 'tup_inserted', 'tup_updated', 'tup_deleted', 'conflicts', 'temp_files', 'temp_bytes', 'deadlocks', 'blk_read_time', 'blk_write_time', 'stats_reset'], 'Type': ['oid', 'name', 'integer', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'double precision', 'double precision', 'timestamp with time zone']} def test_index_file_damaged(self): LOG.info( '--------------------查看表结构--------------------------') msg = self.comsh.execut_db_sql('\d PG_STAT_DATABASE') LOG.info(msg) result_dict = self.com.format_sql_result(msg) LOG.info(result_dict) del result_dict['Modifiers'] self.assertDictEqual(self.expect_result_dict, result_dict) def tearDown(self): LOG.info('----------------this is tearDown-----------------------') # 无须清理环境 LOG.info( '---Opengauss_Function_System_View_Case0044执行完成------------')
36.394366
84
0.589783
import unittest from testcase.utils.Common import Common from testcase.utils.CommonSH import CommonSH from testcase.utils.Logger import Logger LOG = Logger() class SystemView(unittest.TestCase): def setUp(self): LOG.info('----------------this is setup-----------------------') LOG.info( '------Opengauss_Function_System_View_Case0044开始执行----------') self.com = Common() self.comsh = CommonSH('dbuser') self.expect_result_dict = { 'Column': ['datid', 'datname', 'numbackends', 'xact_commit', 'xact_rollback', 'blks_read', 'blks_hit', 'tup_returned', 'tup_fetched', 'tup_inserted', 'tup_updated', 'tup_deleted', 'conflicts', 'temp_files', 'temp_bytes', 'deadlocks', 'blk_read_time', 'blk_write_time', 'stats_reset'], 'Type': ['oid', 'name', 'integer', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'bigint', 'double precision', 'double precision', 'timestamp with time zone']} def test_index_file_damaged(self): LOG.info( '--------------------查看表结构--------------------------') msg = self.comsh.execut_db_sql('\d PG_STAT_DATABASE') LOG.info(msg) result_dict = self.com.format_sql_result(msg) LOG.info(result_dict) del result_dict['Modifiers'] self.assertDictEqual(self.expect_result_dict, result_dict) def tearDown(self): LOG.info('----------------this is tearDown-----------------------') LOG.info( '---Opengauss_Function_System_View_Case0044执行完成------------')
true
true
f7149050818fa7e7d8741a281c8eedd9cd01f51f
185
py
Python
tests/resource/test_module.py
asyncee/pycamunda
f4834d224ff99fcf80874efeaedf68a8a2efa926
[ "MIT" ]
null
null
null
tests/resource/test_module.py
asyncee/pycamunda
f4834d224ff99fcf80874efeaedf68a8a2efa926
[ "MIT" ]
null
null
null
tests/resource/test_module.py
asyncee/pycamunda
f4834d224ff99fcf80874efeaedf68a8a2efa926
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- def test_all_contains_only_valid_names(): import pycamunda.resource for name in pycamunda.resource.__all__: getattr(pycamunda.resource, name)
20.555556
43
0.708108
def test_all_contains_only_valid_names(): import pycamunda.resource for name in pycamunda.resource.__all__: getattr(pycamunda.resource, name)
true
true
f71491334e653edf6dda365969aee2cd5e3794d8
531
py
Python
ex14.py
YunMeMeThaw/python_exercises
151d5d3695d578059611ac09c94b3677442197d7
[ "MIT" ]
null
null
null
ex14.py
YunMeMeThaw/python_exercises
151d5d3695d578059611ac09c94b3677442197d7
[ "MIT" ]
null
null
null
ex14.py
YunMeMeThaw/python_exercises
151d5d3695d578059611ac09c94b3677442197d7
[ "MIT" ]
null
null
null
from sys import argv script, user_name = argv prompt = '> ' print("Hi %s, I'm the %s script." % (user_name, script)) print("I'd like to ask you a few questions.") print("Do you like me %s?" % user_name) likes = input(prompt) print("Where do you live %s?" % user_name) lives = input(prompt) print("What kind of computer do you hava?") computer = input(prompt) print(""" Alright, so you said %r about liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice. """ %(likes, lives, computer))
31.235294
56
0.6629
from sys import argv script, user_name = argv prompt = '> ' print("Hi %s, I'm the %s script." % (user_name, script)) print("I'd like to ask you a few questions.") print("Do you like me %s?" % user_name) likes = input(prompt) print("Where do you live %s?" % user_name) lives = input(prompt) print("What kind of computer do you hava?") computer = input(prompt) print(""" Alright, so you said %r about liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice. """ %(likes, lives, computer))
true
true
f714924a2eb8a90be404ca381f44409a550c4985
8,049
py
Python
python/mxnet/base.py
ChidanandKumarKS/mxnet
1ed8b19849046bce92fd3d4a390b2adc405b584a
[ "Apache-2.0" ]
1
2018-09-08T05:58:17.000Z
2018-09-08T05:58:17.000Z
python/mxnet/base.py
ChidanandKumarKS/mxnet
1ed8b19849046bce92fd3d4a390b2adc405b584a
[ "Apache-2.0" ]
null
null
null
python/mxnet/base.py
ChidanandKumarKS/mxnet
1ed8b19849046bce92fd3d4a390b2adc405b584a
[ "Apache-2.0" ]
1
2018-09-04T10:46:25.000Z
2018-09-04T10:46:25.000Z
# coding: utf-8 # pylint: disable=invalid-name, no-member """ctypes library of mxnet and helper functions.""" from __future__ import absolute_import import sys import ctypes import atexit import warnings import inspect import numpy as np from . import libinfo warnings.filterwarnings('default', category=DeprecationWarning) __all__ = ['MXNetError'] #---------------------------- # library loading #---------------------------- if sys.version_info[0] == 3: string_types = str, numeric_types = (float, int, np.float32, np.int32) integer_types = int # this function is needed for python3 # to convert ctypes.char_p .value back to python str py_str = lambda x: x.decode('utf-8') else: string_types = basestring, numeric_types = (float, int, long, np.float32, np.int32) integer_types = (int, long) py_str = lambda x: x class _NullType(object): """Placeholder for arguments""" def __repr__(self): return '_Null' _Null = _NullType() class MXNetError(Exception): """Error that will be throwed by all mxnet functions.""" pass class NotImplementedForSymbol(MXNetError): def __init__(self, function, alias, *args): super(NotImplementedForSymbol, self).__init__() self.function = function.__name__ self.alias = alias self.args = [str(type(a)) for a in args] def __str__(self): msg = 'Function {}'.format(self.function) if self.alias: msg += ' (namely operator "{}")'.format(self.alias) if self.args: msg += ' with arguments ({})'.format(', '.join(self.args)) msg += ' is not implemented for Symbol and only available in NDArray.' return msg def _load_lib(): """Load library by searching possible path.""" lib_path = libinfo.find_lib_path() lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL) # DMatrix functions lib.MXGetLastError.restype = ctypes.c_char_p return lib # version number __version__ = libinfo.__version__ # library instance of mxnet _LIB = _load_lib() # type definitions mx_uint = ctypes.c_uint mx_float = ctypes.c_float mx_float_p = ctypes.POINTER(mx_float) mx_real_t = np.float32 NDArrayHandle = ctypes.c_void_p FunctionHandle = ctypes.c_void_p OpHandle = ctypes.c_void_p CachedOpHandle = ctypes.c_void_p SymbolHandle = ctypes.c_void_p ExecutorHandle = ctypes.c_void_p DataIterCreatorHandle = ctypes.c_void_p DataIterHandle = ctypes.c_void_p KVStoreHandle = ctypes.c_void_p RecordIOHandle = ctypes.c_void_p RtcHandle = ctypes.c_void_p #---------------------------- # helper function definition #---------------------------- def check_call(ret): """Check the return value of C API call. This function will raise an exception when an error occurs. Wrap every API call with this function. Parameters ---------- ret : int return value from API calls. """ if ret != 0: raise MXNetError(py_str(_LIB.MXGetLastError())) if sys.version_info[0] < 3: def c_str(string): """Create ctypes char * from a Python string. Parameters ---------- string : string type Python string. Returns ------- str : c_char_p A char pointer that can be passed to C API. Examples -------- >>> x = mx.base.c_str("Hello, World") >>> print x.value Hello, World """ return ctypes.c_char_p(string) else: def c_str(string): """Create ctypes char * from a Python string. Parameters ---------- string : string type Python string. Returns ------- str : c_char_p A char pointer that can be passed to C API. Examples -------- >>> x = mx.base.c_str("Hello, World") >>> print x.value Hello, World """ return ctypes.c_char_p(string.encode('utf-8')) def c_array(ctype, values): """Create ctypes array from a Python array. Parameters ---------- ctype : ctypes data type Data type of the array we want to convert to, such as mx_float. values : tuple or list Data content. Returns ------- out : ctypes array Created ctypes array. Examples -------- >>> x = mx.base.c_array(mx.base.mx_float, [1, 2, 3]) >>> print len(x) 3 >>> x[1] 2.0 """ return (ctype * len(values))(*values) def ctypes2buffer(cptr, length): """Convert ctypes pointer to buffer type. Parameters ---------- cptr : ctypes.POINTER(ctypes.c_char) Pointer to the raw memory region. length : int The length of the buffer. Returns ------- buffer : bytearray The raw byte memory buffer. """ if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)): raise TypeError('expected char pointer') res = bytearray(length) rptr = (ctypes.c_char * length).from_buffer(res) if not ctypes.memmove(rptr, cptr, length): raise RuntimeError('memmove failed') return res def ctypes2numpy_shared(cptr, shape): """Convert a ctypes pointer to a numpy array. The resulting NumPy array shares the memory with the pointer. Parameters ---------- cptr : ctypes.POINTER(mx_float) pointer to the memory region shape : tuple Shape of target `NDArray`. Returns ------- out : numpy_array A numpy array : numpy array. """ if not isinstance(cptr, ctypes.POINTER(mx_float)): raise RuntimeError('expected float pointer') size = 1 for s in shape: size *= s dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.contents)) return np.frombuffer(dbuffer, dtype=np.float32).reshape(shape) def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True): """Build argument docs in python style. arg_names : list of str Argument names. arg_types : list of str Argument type information. arg_descs : list of str Argument description information. remove_dup : boolean, optional Whether remove duplication or not. Returns ------- docstr : str Python docstring of parameter sections. """ param_keys = set() param_str = [] for key, type_info, desc in zip(arg_names, arg_types, arg_descs): if key in param_keys and remove_dup: continue if key == 'num_args': continue param_keys.add(key) ret = '%s : %s' % (key, type_info) if len(desc) != 0: ret += '\n ' + desc param_str.append(ret) doc_str = ('Parameters\n' + '----------\n' + '%s\n') doc_str = doc_str % ('\n'.join(param_str)) return doc_str def _notify_shutdown(): """Notify MXNet about a shutdown.""" check_call(_LIB.MXNotifyShutdown()) atexit.register(_notify_shutdown) def add_fileline_to_docstring(module, incursive=True): """Append the definition position to each function contained in module. Examples -------- # Put the following codes at the end of a file add_fileline_to_docstring(__name__) """ def _add_fileline(obj): """Add fileinto to a object. """ if obj.__doc__ is None or 'From:' in obj.__doc__: return fname = inspect.getsourcefile(obj) if fname is None: return try: line = inspect.getsourcelines(obj)[-1] except IOError: return obj.__doc__ += '\n\nFrom:%s:%d' % (fname, line) if isinstance(module, str): module = sys.modules[module] for _, obj in inspect.getmembers(module): if inspect.isbuiltin(obj): continue if inspect.isfunction(obj): _add_fileline(obj) if inspect.ismethod(obj): _add_fileline(obj.__func__) if inspect.isclass(obj) and incursive: add_fileline_to_docstring(obj, False)
26.564356
78
0.60815
from __future__ import absolute_import import sys import ctypes import atexit import warnings import inspect import numpy as np from . import libinfo warnings.filterwarnings('default', category=DeprecationWarning) __all__ = ['MXNetError'] if sys.version_info[0] == 3: string_types = str, numeric_types = (float, int, np.float32, np.int32) integer_types = int py_str = lambda x: x.decode('utf-8') else: string_types = basestring, numeric_types = (float, int, long, np.float32, np.int32) integer_types = (int, long) py_str = lambda x: x class _NullType(object): def __repr__(self): return '_Null' _Null = _NullType() class MXNetError(Exception): pass class NotImplementedForSymbol(MXNetError): def __init__(self, function, alias, *args): super(NotImplementedForSymbol, self).__init__() self.function = function.__name__ self.alias = alias self.args = [str(type(a)) for a in args] def __str__(self): msg = 'Function {}'.format(self.function) if self.alias: msg += ' (namely operator "{}")'.format(self.alias) if self.args: msg += ' with arguments ({})'.format(', '.join(self.args)) msg += ' is not implemented for Symbol and only available in NDArray.' return msg def _load_lib(): lib_path = libinfo.find_lib_path() lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL) lib.MXGetLastError.restype = ctypes.c_char_p return lib __version__ = libinfo.__version__ _LIB = _load_lib() mx_uint = ctypes.c_uint mx_float = ctypes.c_float mx_float_p = ctypes.POINTER(mx_float) mx_real_t = np.float32 NDArrayHandle = ctypes.c_void_p FunctionHandle = ctypes.c_void_p OpHandle = ctypes.c_void_p CachedOpHandle = ctypes.c_void_p SymbolHandle = ctypes.c_void_p ExecutorHandle = ctypes.c_void_p DataIterCreatorHandle = ctypes.c_void_p DataIterHandle = ctypes.c_void_p KVStoreHandle = ctypes.c_void_p RecordIOHandle = ctypes.c_void_p RtcHandle = ctypes.c_void_p def check_call(ret): if ret != 0: raise MXNetError(py_str(_LIB.MXGetLastError())) if sys.version_info[0] < 3: def c_str(string): return ctypes.c_char_p(string) else: def c_str(string): """Create ctypes char * from a Python string. Parameters ---------- string : string type Python string. Returns ------- str : c_char_p A char pointer that can be passed to C API. Examples -------- >>> x = mx.base.c_str("Hello, World") >>> print x.value Hello, World """ return ctypes.c_char_p(string.encode('utf-8')) def c_array(ctype, values): return (ctype * len(values))(*values) def ctypes2buffer(cptr, length): if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)): raise TypeError('expected char pointer') res = bytearray(length) rptr = (ctypes.c_char * length).from_buffer(res) if not ctypes.memmove(rptr, cptr, length): raise RuntimeError('memmove failed') return res def ctypes2numpy_shared(cptr, shape): if not isinstance(cptr, ctypes.POINTER(mx_float)): raise RuntimeError('expected float pointer') size = 1 for s in shape: size *= s dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.contents)) return np.frombuffer(dbuffer, dtype=np.float32).reshape(shape) def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True): param_keys = set() param_str = [] for key, type_info, desc in zip(arg_names, arg_types, arg_descs): if key in param_keys and remove_dup: continue if key == 'num_args': continue param_keys.add(key) ret = '%s : %s' % (key, type_info) if len(desc) != 0: ret += '\n ' + desc param_str.append(ret) doc_str = ('Parameters\n' + '----------\n' + '%s\n') doc_str = doc_str % ('\n'.join(param_str)) return doc_str def _notify_shutdown(): check_call(_LIB.MXNotifyShutdown()) atexit.register(_notify_shutdown) def add_fileline_to_docstring(module, incursive=True): def _add_fileline(obj): if obj.__doc__ is None or 'From:' in obj.__doc__: return fname = inspect.getsourcefile(obj) if fname is None: return try: line = inspect.getsourcelines(obj)[-1] except IOError: return obj.__doc__ += '\n\nFrom:%s:%d' % (fname, line) if isinstance(module, str): module = sys.modules[module] for _, obj in inspect.getmembers(module): if inspect.isbuiltin(obj): continue if inspect.isfunction(obj): _add_fileline(obj) if inspect.ismethod(obj): _add_fileline(obj.__func__) if inspect.isclass(obj) and incursive: add_fileline_to_docstring(obj, False)
true
true
f7149262bdb3bfb5bea3bb847f496514f2be6606
4,880
py
Python
scripts/automation.py
Alexey19/Python-UIAutomation-for-Windows
43d33bed99da66c31bc8471694422352291ae1fb
[ "Apache-2.0" ]
null
null
null
scripts/automation.py
Alexey19/Python-UIAutomation-for-Windows
43d33bed99da66c31bc8471694422352291ae1fb
[ "Apache-2.0" ]
null
null
null
scripts/automation.py
Alexey19/Python-UIAutomation-for-Windows
43d33bed99da66c31bc8471694422352291ae1fb
[ "Apache-2.0" ]
null
null
null
#!python3 # -*- coding:utf-8 -*- import sys import time from uiautomation import (Win32API, Logger, ControlFromCursor, GetRootControl, GetFocusedControl, LogControl, EnumAndLogControlAncestors, EnumAndLogControl, ConsoleColor) from uiautomation import VERSION def usage(): Logger.ColorfulWrite("""usage <Color=Cyan>-h</Color> show command <Color=Cyan>help</Color> <Color=Cyan>-t</Color> delay <Color=Cyan>time</Color>, default 3 seconds, begin to enumerate after Value seconds, this must be an integer you can delay a few seconds and make a window active so automation can enumerate the active window <Color=Cyan>-d</Color> enumerate tree <Color=Cyan>depth</Color>, this must be an integer, if it is null, enumerate the whole tree <Color=Cyan>-r</Color> enumerate from <Color=Cyan>root</Color>:Desktop window, if it is null, enumerate from foreground window <Color=Cyan>-f</Color> enumerate from <Color=Cyan>focused</Color> control, if it is null, enumerate from foreground window <Color=Cyan>-c</Color> enumerate the control under <Color=Cyan>cursor</Color>, if depth is < 0, enumerate from its ancestor up to depth <Color=Cyan>-a</Color> show <Color=Cyan>ancestors</Color> of the control under cursor <Color=Cyan>-n</Color> show control full <Color=Cyan>name</Color> <Color=Cyan>-m</Color> show <Color=Cyan>more</Color> properties if <Color=Red>UnicodeError</Color> or <Color=Red>LookupError</Color> occurred when printing, try to change the active code page of console window by using <Color=Cyan>chcp</Color> or see the log file <Color=Cyan>@AutomationLog.txt</Color> chcp, get current active code page chcp 936, set active code page to gbk chcp 65001, set active code page to utf-8 examples: automation.py -t3 automation.py -t3 -r -d1 -m -n automation.py -c -t3 """, writeToFile = False) def main(): # if not IsPy3 and sys.getdefaultencoding() == 'ascii': # reload(sys) # sys.setdefaultencoding('utf-8') import getopt Logger.Write('UIAutomation {} (Python {}.{}.{}, {} bit)\n'.format(VERSION, sys.version_info.major, sys.version_info.minor, sys.version_info.micro, 64 if sys.maxsize > 0xFFFFFFFF else 32)) options, args = getopt.getopt(sys.argv[1:], 'hrfcamnd:t:', ['help', 'root', 'focus', 'cursor', 'ancestor', 'showMore', 'showAllName', 'depth=', 'time=']) root = False focus = False cursor = False ancestor = False foreground = True showAllName = False showMore = False depth = 0xFFFFFFFF seconds = 3 for (o, v) in options: if o in ('-h', '-help'): usage() exit(0) elif o in ('-r', '-root'): root = True foreground = False elif o in ('-f', '-focus'): focus = True foreground = False elif o in ('-c', '-cursor'): cursor = True foreground = False elif o in ('-a', '-ancestor'): ancestor = True foreground = False elif o in ('-n', '-showAllName'): showAllName = True elif o in ('-m', '-showMore'): showMore = True elif o in ('-d', '-depth'): depth = int(v) elif o in ('-t', '-time'): seconds = int(v) if seconds > 0: Logger.Write('please wait for {0} seconds\n\n'.format(seconds), writeToFile = False) time.sleep(seconds) Logger.Log('Starts, Current Cursor Position: {}'.format(Win32API.GetCursorPos())) control = None if root: control = GetRootControl() if focus: control = GetFocusedControl() if cursor: control = ControlFromCursor() if depth < 0: while depth < 0 and control: control = control.GetParentControl() depth += 1 depth = 0xFFFFFFFF if ancestor: control = ControlFromCursor() if control: EnumAndLogControlAncestors(control, showAllName, showMore) else: Logger.Write('IUIAutomation returns null element under cursor\n', ConsoleColor.Yellow) else: indent = 0 if not control: control = GetFocusedControl() controlList = [] while control: controlList.insert(0, control) control = control.GetParentControl() if len(controlList) == 1: control = controlList[0] else: control = controlList[1] if foreground: indent = 1 LogControl(controlList[0], 0, showAllName, showMore) EnumAndLogControl(control, depth, showAllName, showMore, startIndent = indent) Logger.Log('Ends\n') if __name__ == '__main__': main()
40
191
0.604713
import sys import time from uiautomation import (Win32API, Logger, ControlFromCursor, GetRootControl, GetFocusedControl, LogControl, EnumAndLogControlAncestors, EnumAndLogControl, ConsoleColor) from uiautomation import VERSION def usage(): Logger.ColorfulWrite("""usage <Color=Cyan>-h</Color> show command <Color=Cyan>help</Color> <Color=Cyan>-t</Color> delay <Color=Cyan>time</Color>, default 3 seconds, begin to enumerate after Value seconds, this must be an integer you can delay a few seconds and make a window active so automation can enumerate the active window <Color=Cyan>-d</Color> enumerate tree <Color=Cyan>depth</Color>, this must be an integer, if it is null, enumerate the whole tree <Color=Cyan>-r</Color> enumerate from <Color=Cyan>root</Color>:Desktop window, if it is null, enumerate from foreground window <Color=Cyan>-f</Color> enumerate from <Color=Cyan>focused</Color> control, if it is null, enumerate from foreground window <Color=Cyan>-c</Color> enumerate the control under <Color=Cyan>cursor</Color>, if depth is < 0, enumerate from its ancestor up to depth <Color=Cyan>-a</Color> show <Color=Cyan>ancestors</Color> of the control under cursor <Color=Cyan>-n</Color> show control full <Color=Cyan>name</Color> <Color=Cyan>-m</Color> show <Color=Cyan>more</Color> properties if <Color=Red>UnicodeError</Color> or <Color=Red>LookupError</Color> occurred when printing, try to change the active code page of console window by using <Color=Cyan>chcp</Color> or see the log file <Color=Cyan>@AutomationLog.txt</Color> chcp, get current active code page chcp 936, set active code page to gbk chcp 65001, set active code page to utf-8 examples: automation.py -t3 automation.py -t3 -r -d1 -m -n automation.py -c -t3 """, writeToFile = False) def main(): import getopt Logger.Write('UIAutomation {} (Python {}.{}.{}, {} bit)\n'.format(VERSION, sys.version_info.major, sys.version_info.minor, sys.version_info.micro, 64 if sys.maxsize > 0xFFFFFFFF else 32)) options, args = getopt.getopt(sys.argv[1:], 'hrfcamnd:t:', ['help', 'root', 'focus', 'cursor', 'ancestor', 'showMore', 'showAllName', 'depth=', 'time=']) root = False focus = False cursor = False ancestor = False foreground = True showAllName = False showMore = False depth = 0xFFFFFFFF seconds = 3 for (o, v) in options: if o in ('-h', '-help'): usage() exit(0) elif o in ('-r', '-root'): root = True foreground = False elif o in ('-f', '-focus'): focus = True foreground = False elif o in ('-c', '-cursor'): cursor = True foreground = False elif o in ('-a', '-ancestor'): ancestor = True foreground = False elif o in ('-n', '-showAllName'): showAllName = True elif o in ('-m', '-showMore'): showMore = True elif o in ('-d', '-depth'): depth = int(v) elif o in ('-t', '-time'): seconds = int(v) if seconds > 0: Logger.Write('please wait for {0} seconds\n\n'.format(seconds), writeToFile = False) time.sleep(seconds) Logger.Log('Starts, Current Cursor Position: {}'.format(Win32API.GetCursorPos())) control = None if root: control = GetRootControl() if focus: control = GetFocusedControl() if cursor: control = ControlFromCursor() if depth < 0: while depth < 0 and control: control = control.GetParentControl() depth += 1 depth = 0xFFFFFFFF if ancestor: control = ControlFromCursor() if control: EnumAndLogControlAncestors(control, showAllName, showMore) else: Logger.Write('IUIAutomation returns null element under cursor\n', ConsoleColor.Yellow) else: indent = 0 if not control: control = GetFocusedControl() controlList = [] while control: controlList.insert(0, control) control = control.GetParentControl() if len(controlList) == 1: control = controlList[0] else: control = controlList[1] if foreground: indent = 1 LogControl(controlList[0], 0, showAllName, showMore) EnumAndLogControl(control, depth, showAllName, showMore, startIndent = indent) Logger.Log('Ends\n') if __name__ == '__main__': main()
true
true
f71492be13cc39a498d67a30628c4004f0f40da6
172
py
Python
1541/solution.py
bossm0n5t3r/BOJ
03132388a0c76ef66d6b0dec2053aeca65c4aee6
[ "MIT" ]
2
2020-01-14T07:27:25.000Z
2020-02-12T07:49:58.000Z
1541/solution.py
bossm0n5t3r/BOJ
03132388a0c76ef66d6b0dec2053aeca65c4aee6
[ "MIT" ]
1
2020-01-14T07:29:30.000Z
2021-11-28T11:29:08.000Z
1541/solution.py
bossm0n5t3r/BOJ
03132388a0c76ef66d6b0dec2053aeca65c4aee6
[ "MIT" ]
null
null
null
def sol(): expression = [sum(map(int, x.split("+"))) for x in input().split("-")] print(expression[0] - sum(expression[1:])) if __name__ == "__main__": sol()
21.5
74
0.569767
def sol(): expression = [sum(map(int, x.split("+"))) for x in input().split("-")] print(expression[0] - sum(expression[1:])) if __name__ == "__main__": sol()
true
true
f7149435f8090b28b434d5fbe89c07cf906c1832
2,207
py
Python
arc852/opencv_utils.py
athenian-robotics/common-robotics-python
a2ede8fb3072cf1baa53672f76081aa6bfde397f
[ "MIT" ]
1
2019-02-20T22:59:59.000Z
2019-02-20T22:59:59.000Z
arc852/opencv_utils.py
athenian-robotics/common-robotics
a2ede8fb3072cf1baa53672f76081aa6bfde397f
[ "MIT" ]
null
null
null
arc852/opencv_utils.py
athenian-robotics/common-robotics
a2ede8fb3072cf1baa53672f76081aa6bfde397f
[ "MIT" ]
1
2020-05-23T09:08:42.000Z
2020-05-23T09:08:42.000Z
import datetime import logging import math import cv2 RED = (0, 0, 255) GREEN = (0, 255, 0) BLUE = (255, 0, 0) YELLOW = (0, 255, 255) logger = logging.getLogger(__name__) def get_moment(contour): moment1 = cv2.moments(contour) area = int(moment1["m00"]) x = int(moment1["m10"] / area) y = int(moment1["m01"] / area) return contour, area, x, y def get_center(contour): momt = cv2.moments(contour) area = int(momt["m00"]) return int(momt["m10"] / area), int(momt["m01"] / area) def contains(contour, point): return cv2.pointPolygonTest(contour, point, False) != -1 def contains_in_list(contour_list, point): for i in contour_list: if contains(i, point): return True return False def write_image(frame, file_name=None, log_info=False): fname = file_name if file_name else "ct-{0}.png".format(datetime.datetime.now().strftime("%H-%M-%S")) cv2.imwrite(file_name, frame) if log_info: logger.info("Wrote image to %s", fname) def encode_image(frame, ext=".jpg"): retval, buf = cv2.imencode(ext, frame) return retval, buf def distance(point1, point2): xsqr = (point2[0] - point1[0]) ** 2 ysqr = (point2[1] - point1[1]) ** 2 return int(math.sqrt(xsqr + ysqr)) def contour_slope_degrees(contour): rect = cv2.minAreaRect(contour) box = cv2.boxPoints(rect) # if self.__display: # cv2.drawContours(image, [np.int0(box)], 0, RED, 2) point_lr = box[0] point_ll = box[1] point_ul = box[2] point_ur = box[3] line1 = distance(point_lr, point_ur) line2 = distance(point_ur, point_ul) if line1 < line2: point_lr = box[1] point_ll = box[2] point_ul = box[3] point_ur = box[0] line_width = line1 else: line_width = line2 delta_y = point_lr[1] - point_ur[1] delta_x = point_lr[0] - point_ur[0] # Calculate angle of line if delta_x == 0: # Vertical line slope = None degrees = 90 else: # Non-vertical line slope = delta_y / delta_x radians = math.atan(slope) degrees = int(math.degrees(radians)) * -1 return slope, degrees
22.752577
105
0.61169
import datetime import logging import math import cv2 RED = (0, 0, 255) GREEN = (0, 255, 0) BLUE = (255, 0, 0) YELLOW = (0, 255, 255) logger = logging.getLogger(__name__) def get_moment(contour): moment1 = cv2.moments(contour) area = int(moment1["m00"]) x = int(moment1["m10"] / area) y = int(moment1["m01"] / area) return contour, area, x, y def get_center(contour): momt = cv2.moments(contour) area = int(momt["m00"]) return int(momt["m10"] / area), int(momt["m01"] / area) def contains(contour, point): return cv2.pointPolygonTest(contour, point, False) != -1 def contains_in_list(contour_list, point): for i in contour_list: if contains(i, point): return True return False def write_image(frame, file_name=None, log_info=False): fname = file_name if file_name else "ct-{0}.png".format(datetime.datetime.now().strftime("%H-%M-%S")) cv2.imwrite(file_name, frame) if log_info: logger.info("Wrote image to %s", fname) def encode_image(frame, ext=".jpg"): retval, buf = cv2.imencode(ext, frame) return retval, buf def distance(point1, point2): xsqr = (point2[0] - point1[0]) ** 2 ysqr = (point2[1] - point1[1]) ** 2 return int(math.sqrt(xsqr + ysqr)) def contour_slope_degrees(contour): rect = cv2.minAreaRect(contour) box = cv2.boxPoints(rect) point_lr = box[0] point_ll = box[1] point_ul = box[2] point_ur = box[3] line1 = distance(point_lr, point_ur) line2 = distance(point_ur, point_ul) if line1 < line2: point_lr = box[1] point_ll = box[2] point_ul = box[3] point_ur = box[0] line_width = line1 else: line_width = line2 delta_y = point_lr[1] - point_ur[1] delta_x = point_lr[0] - point_ur[0] if delta_x == 0: slope = None degrees = 90 else: slope = delta_y / delta_x radians = math.atan(slope) degrees = int(math.degrees(radians)) * -1 return slope, degrees
true
true
f71494b465a073d5dd94888bf5f7ef9ae0951d01
959
py
Python
tests/v2/test_0879-non-primitive-with-field.py
jpivarski/awkward-1.0
49a3ff13ef90b8778a80573211d58c544729eaa5
[ "BSD-3-Clause" ]
2
2019-09-12T03:07:23.000Z
2019-09-27T05:32:07.000Z
tests/v2/test_0879-non-primitive-with-field.py
jpivarski/awkward-1.0
49a3ff13ef90b8778a80573211d58c544729eaa5
[ "BSD-3-Clause" ]
1
2019-09-26T17:57:45.000Z
2019-09-26T17:57:45.000Z
tests/v2/test_0879-non-primitive-with-field.py
jpivarski/awkward-1.0
49a3ff13ef90b8778a80573211d58c544729eaa5
[ "BSD-3-Clause" ]
null
null
null
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE import pytest # noqa: F401 import numpy as np # noqa: F401 import awkward as ak # noqa: F401 def test_unknown_type(): array = ak._v2.Array({"x": np.arange(10)}) array = ak._v2.operations.with_field(base=array, what=None, where="unknown field1") array = ak._v2.operations.with_field( base=array, what=[None], where="unknown field2" ) # Try to access the type of a single element # This raises a ValueError in #879 tpe1 = array["unknown field1"].type tpe2 = array["unknown field2"].type assert str(tpe1) == "10 * ?unknown" assert str(tpe2) == "10 * ?unknown" def test_in_place_wrapper_broadcasting(): array = ak._v2.Array({"x": np.arange(3)}) array["unknown field"] = None assert array["unknown field"].tolist() == [None, None, None] assert ak._v2.operations.fields(array) == ["x", "unknown field"]
33.068966
87
0.663191
import pytest import numpy as np import awkward as ak def test_unknown_type(): array = ak._v2.Array({"x": np.arange(10)}) array = ak._v2.operations.with_field(base=array, what=None, where="unknown field1") array = ak._v2.operations.with_field( base=array, what=[None], where="unknown field2" ) tpe1 = array["unknown field1"].type tpe2 = array["unknown field2"].type assert str(tpe1) == "10 * ?unknown" assert str(tpe2) == "10 * ?unknown" def test_in_place_wrapper_broadcasting(): array = ak._v2.Array({"x": np.arange(3)}) array["unknown field"] = None assert array["unknown field"].tolist() == [None, None, None] assert ak._v2.operations.fields(array) == ["x", "unknown field"]
true
true
f714958b669c31b21b54bd0ddb5714e078f4ab0f
4,265
py
Python
empower/cli/projects.py
joncnet/empower-runtime
c04d9c7621fdb97dc3bd4ace5cb2d8f7194d540c
[ "Apache-2.0" ]
null
null
null
empower/cli/projects.py
joncnet/empower-runtime
c04d9c7621fdb97dc3bd4ace5cb2d8f7194d540c
[ "Apache-2.0" ]
null
null
null
empower/cli/projects.py
joncnet/empower-runtime
c04d9c7621fdb97dc3bd4ace5cb2d8f7194d540c
[ "Apache-2.0" ]
2
2018-09-24T09:44:19.000Z
2018-10-12T09:57:36.000Z
#!/usr/bin/env python3 # # Copyright (c) 2019 Roberto Riggio # # 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. """Projects CLI tools.""" import uuid import argparse import empower.cli.command as command from empower.core.plmnid import PLMNID from empower.core.ssid import SSID def pa_delete_project(args, cmd): """Delete project parser method. """ usage = "%s <options>" % command.USAGE.format(cmd) desc = command.DESCS[cmd] parser = argparse.ArgumentParser(usage=usage, description=desc) required = parser.add_argument_group('required named arguments') required.add_argument('-p', '--project_id', help='The project id', required=True, type=uuid.UUID) (args, leftovers) = parser.parse_known_args(args) return args, leftovers def do_delete_project(gargs, args, _): """Delete a project. """ url = '/api/v1/projects/%s' % args.project_id command.connect(gargs, ('DELETE', url), 204) print(args.project_id) def pa_create_project(args, cmd): """Create project parser method. """ usage = "%s <options>" % command.USAGE.format(cmd) desc = command.DESCS[cmd] parser = argparse.ArgumentParser(usage=usage, description=desc) required = parser.add_argument_group('required named arguments') required.add_argument('-d', '--desc', help='The project description', required=True, type=str, dest="desc") required.add_argument('-o', '--owner', help='The project owner', required=True, type=str, dest="owner") parser.add_argument("-c", "--mcc", dest="mcc", default=None, help="The network MCC; default=None", type=str) parser.add_argument("-n", "--mnc", dest="mcc", default=None, help="The network MNC; default=None", type=str) parser.add_argument("-s", "--ssid", dest="ssid", default=None, help="The network SSID; default=None", type=SSID) parser.add_argument("-t", "--ssid_type", dest="ssid_type", default="unique", choices=["unique", "shared"], help="The network SSID type; default=unique") (args, leftovers) = parser.parse_known_args(args) return args, leftovers def do_create_project(gargs, args, _): """ Add a new Project """ request = { "version": "1.0", "desc": args.desc, "owner": args.owner } if args.ssid: request["wifi_props"] = { "bssid_type": args.ssid_type, "ssid": args.ssid } if args.mcc and args.mnc: plmnid = PLMNID(args.mcc, args.mnc) request["lte_props"] = { "plmnid": plmnid.to_dict() } headers = command.get_headers(gargs) url = '/api/v1/projects' response, _ = command.connect(gargs, ('POST', url), 201, request, headers=headers) location = response.headers['Location'] tokens = location.split("/") project_id = tokens[-1] print(project_id) def do_list_projects(gargs, *_): """List currently running workers. """ _, data = command.connect(gargs, ('GET', '/api/v1/projects'), 200) for entry in data.values(): accum = [] accum.append("project_id ") accum.append(entry['project_id']) accum.append(" desc \"%s\"" % entry['desc']) if 'wifi_props' in entry and entry['wifi_props']: accum.append(" ssid \"%s\"" % entry['wifi_props']['ssid']) if 'lte_props' in entry and entry['lte_props']: accum.append(" plmnid \"%s\"" % entry['lte_props']['plmnid']) print(''.join(accum))
28.245033
73
0.605393
import uuid import argparse import empower.cli.command as command from empower.core.plmnid import PLMNID from empower.core.ssid import SSID def pa_delete_project(args, cmd): usage = "%s <options>" % command.USAGE.format(cmd) desc = command.DESCS[cmd] parser = argparse.ArgumentParser(usage=usage, description=desc) required = parser.add_argument_group('required named arguments') required.add_argument('-p', '--project_id', help='The project id', required=True, type=uuid.UUID) (args, leftovers) = parser.parse_known_args(args) return args, leftovers def do_delete_project(gargs, args, _): url = '/api/v1/projects/%s' % args.project_id command.connect(gargs, ('DELETE', url), 204) print(args.project_id) def pa_create_project(args, cmd): usage = "%s <options>" % command.USAGE.format(cmd) desc = command.DESCS[cmd] parser = argparse.ArgumentParser(usage=usage, description=desc) required = parser.add_argument_group('required named arguments') required.add_argument('-d', '--desc', help='The project description', required=True, type=str, dest="desc") required.add_argument('-o', '--owner', help='The project owner', required=True, type=str, dest="owner") parser.add_argument("-c", "--mcc", dest="mcc", default=None, help="The network MCC; default=None", type=str) parser.add_argument("-n", "--mnc", dest="mcc", default=None, help="The network MNC; default=None", type=str) parser.add_argument("-s", "--ssid", dest="ssid", default=None, help="The network SSID; default=None", type=SSID) parser.add_argument("-t", "--ssid_type", dest="ssid_type", default="unique", choices=["unique", "shared"], help="The network SSID type; default=unique") (args, leftovers) = parser.parse_known_args(args) return args, leftovers def do_create_project(gargs, args, _): request = { "version": "1.0", "desc": args.desc, "owner": args.owner } if args.ssid: request["wifi_props"] = { "bssid_type": args.ssid_type, "ssid": args.ssid } if args.mcc and args.mnc: plmnid = PLMNID(args.mcc, args.mnc) request["lte_props"] = { "plmnid": plmnid.to_dict() } headers = command.get_headers(gargs) url = '/api/v1/projects' response, _ = command.connect(gargs, ('POST', url), 201, request, headers=headers) location = response.headers['Location'] tokens = location.split("/") project_id = tokens[-1] print(project_id) def do_list_projects(gargs, *_): _, data = command.connect(gargs, ('GET', '/api/v1/projects'), 200) for entry in data.values(): accum = [] accum.append("project_id ") accum.append(entry['project_id']) accum.append(" desc \"%s\"" % entry['desc']) if 'wifi_props' in entry and entry['wifi_props']: accum.append(" ssid \"%s\"" % entry['wifi_props']['ssid']) if 'lte_props' in entry and entry['lte_props']: accum.append(" plmnid \"%s\"" % entry['lte_props']['plmnid']) print(''.join(accum))
true
true
f7149618008b2c55257eac69dff2390850219ebb
1,584
py
Python
bin/list-keys.py
fenglsuc/PatCit
6f2585dac156a69ff94f002d387c75bd723529df
[ "MIT" ]
1
2020-04-10T09:18:27.000Z
2020-04-10T09:18:27.000Z
bin/list-keys.py
fenglsuc/PatCit
6f2585dac156a69ff94f002d387c75bd723529df
[ "MIT" ]
null
null
null
bin/list-keys.py
fenglsuc/PatCit
6f2585dac156a69ff94f002d387c75bd723529df
[ "MIT" ]
null
null
null
import json import lzma from glob import glob from pprint import pprint import click import smart_open from tqdm import tqdm @click.command() @click.option("--path", help="Path. Wilcard '*' enabled") @click.option("--tar", default=False, help="True for .xz files") @click.option( "--flavor", default="sm", help="Examples reported if <flavor> is lg. Default " "<falvor> is sm.", ) @click.option("--limit", default=None, type=int, help="Break after <limit> iterations") def main(path, tar, flavor, limit): assert flavor in ["sm", "lg"] key_val = {} i = 0 for file in tqdm(glob(path)): if tar: _open = lzma.open else: _open = smart_open.open with _open(file) as f: for l in tqdm(f): i += 1 for k, v in json.loads(l).items(): if k in key_val.keys(): if flavor == "lg": key_val.update( {k: (key_val[k][0] + 1, key_val[k][1], key_val[k][2])} ) else: key_val.update({k: (key_val[k][0] + 1, key_val[k][1])}) else: if flavor == "lg": key_val.update({k: (1, type(v), v)}) else: key_val.update({k: (1, type(v))}) if limit: if i > limit: break pprint(key_val) if __name__ == "__main__": main()
29.333333
87
0.454545
import json import lzma from glob import glob from pprint import pprint import click import smart_open from tqdm import tqdm @click.command() @click.option("--path", help="Path. Wilcard '*' enabled") @click.option("--tar", default=False, help="True for .xz files") @click.option( "--flavor", default="sm", help="Examples reported if <flavor> is lg. Default " "<falvor> is sm.", ) @click.option("--limit", default=None, type=int, help="Break after <limit> iterations") def main(path, tar, flavor, limit): assert flavor in ["sm", "lg"] key_val = {} i = 0 for file in tqdm(glob(path)): if tar: _open = lzma.open else: _open = smart_open.open with _open(file) as f: for l in tqdm(f): i += 1 for k, v in json.loads(l).items(): if k in key_val.keys(): if flavor == "lg": key_val.update( {k: (key_val[k][0] + 1, key_val[k][1], key_val[k][2])} ) else: key_val.update({k: (key_val[k][0] + 1, key_val[k][1])}) else: if flavor == "lg": key_val.update({k: (1, type(v), v)}) else: key_val.update({k: (1, type(v))}) if limit: if i > limit: break pprint(key_val) if __name__ == "__main__": main()
true
true
f714961d576161dc58be3cf12b089bd26a129c85
1,215
py
Python
ex3_collatz.py
grace-burke/Grace-Burke-Programming-and-Scripting-GMIT-2018
b676ebf81388ec3ed46a2d2c9b897ee466598b0b
[ "Apache-2.0" ]
null
null
null
ex3_collatz.py
grace-burke/Grace-Burke-Programming-and-Scripting-GMIT-2018
b676ebf81388ec3ed46a2d2c9b897ee466598b0b
[ "Apache-2.0" ]
null
null
null
ex3_collatz.py
grace-burke/Grace-Burke-Programming-and-Scripting-GMIT-2018
b676ebf81388ec3ed46a2d2c9b897ee466598b0b
[ "Apache-2.0" ]
null
null
null
# Grace Burke # 08/02/2018 # Exercise 3: # Complete the exercise discussed in the Collatz conjecture video by writing a single Python script that starts with an integer and repeatedly applies the Collatz function (divide by 2 if even, multiply by three and 1 if odd) using a while loop and if statement. # At each iteration, the current value of the integer should be printed to the screen. # You can specify in your code the starting value of 17. # If you wish to enhance your program, have the program ask the user for the integer instead of specifying a value at the start of your code. # https://en.wikipedia.org/wiki/Collatz_conjecture x = int(input("Please enter an integer: ")) # This line requests an input value from the user. while x > 1: # This while loop ensures that the operations below are carried out until the input value reaches 1, as specified. if x % 2 == 0: # This if statement checks if the value is even, if so it carries out the operation for even values. x = x//2 else: # If value is not even, if statement carries out operation for odd values. x = 3*x + 1 print (x) # This line prints the value at each cycle of the while loop.
48.6
263
0.719342
x = int(input("Please enter an integer: ")) while x > 1: if x % 2 == 0: x = x//2 else: x = 3*x + 1 print (x)
true
true
f7149705d601e6aca77921bd8014f22187956ca9
13,102
py
Python
xoa/__init__.py
VACUMM/xoa
c6a0d860528cf33ae15c77fa111f95daab0321c0
[ "Apache-2.0" ]
7
2021-04-08T08:46:30.000Z
2022-02-07T11:19:51.000Z
xoa/__init__.py
VACUMM/xoa
c6a0d860528cf33ae15c77fa111f95daab0321c0
[ "Apache-2.0" ]
29
2021-02-18T10:27:26.000Z
2022-03-25T08:29:04.000Z
xoa/__init__.py
VACUMM/xoa
c6a0d860528cf33ae15c77fa111f95daab0321c0
[ "Apache-2.0" ]
2
2020-04-30T17:20:46.000Z
2022-03-18T14:29:14.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ xarray-based ocean analysis library The successor of Vacumm. """ # Copyright 2020-2021 Shom # # 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 re import warnings import platform import pkg_resources import appdirs import configobj import validate # Taken from xarray try: __version__ = pkg_resources.get_distribution("xoa").version except Exception: # Local copy or not installed with setuptools. # Disable minimum version checks on downstream libraries. __version__ = "999" _RE_OPTION_MATCH = re.compile(r"^(\w+)\W(\w+)$").match #: Specifications of configuration options CONFIG_SPECS = """ [cf] # cf module cache=boolean(default=True) # use the :mod:`~xoa.cf` in memory and file caches [plot] # plot parameters cmapdiv = string(default="cmo.balance") # defaut diverging colormap cmappos = string(default="cmo.amp") # default positive colormap cmapneg = string(default="cmo.tempo_r") # default negative colormap cmapcyc = string(default="cmo.phase") # default cyclic colormap """ #: Default xoa user configuration file DEFAULT_USER_CONFIG_FILE = os.path.join( appdirs.user_config_dir("xoa"), "xoa.cfg" ) # Directory of sample files _SAMPLE_DIR = os.path.join(os.path.dirname(__file__), '_samples') _PACKAGES = [ "appdirs", "cartopy", "cmocean", "configobj", "matplotlib", "numpy", "pandas", "scipy", "xarray", "xesmf" ] class XoaError(Exception): pass class XoaConfigError(XoaError): pass class XoaWarning(UserWarning): pass def xoa_warn(message, stacklevel=2): """Issue a :class:`XoaWarning` warning Example ------- .. ipython:: python :okwarning: @suppress from xoa import xoa_warn xoa_warn('Be careful!') """ warnings.warn(message, XoaWarning, stacklevel=stacklevel) def _get_cache_(): from . import __init__ if not hasattr(__init__, "_XOA_CACHE"): __init__._XOA_CACHE = {} return __init__._XOA_CACHE def load_options(cfgfile=None): """Load specified options Parameters ---------- cfgfile: file, list(str), dict Example ------- .. ipython:: python @suppress from xoa import load_options # Dict load_options({'plot': {'cmappos': 'mycmap'}}) # Lines optlines = "[plot]\\n cmappos=mycmap".split('\\n') load_options(optlines) """ _get_cache_() xoa_cache = _get_cache_() if "cfgspecs" not in xoa_cache: xoa_cache["cfgspecs"] = configobj.ConfigObj( CONFIG_SPECS.split("\n"), list_values=False, interpolation=False, raise_errors=True, file_error=True, ) if "options" not in xoa_cache: xoa_cache["options"] = configobj.ConfigObj( ( DEFAULT_USER_CONFIG_FILE if os.path.exists(DEFAULT_USER_CONFIG_FILE) else None ), configspec=xoa_cache["cfgspecs"], file_error=False, raise_errors=True, list_values=True, ) if cfgfile: xoa_cache["options"].merge( configobj.ConfigObj( cfgfile, file_error=True, raise_errors=True, list_values=True ) ) xoa_cache["options"].validate(validate.Validator(), copy=True) def _get_options_(): xoa_cache = _get_cache_() if "options" not in xoa_cache: load_options() return xoa_cache["options"] def get_option(section, option=None): """Get a config option Example ------- .. ipython:: python @suppress from xoa import get_option print(get_option('plot', 'cmapdiv')) print(get_option('plot.cmapdiv')) """ options = _get_options_() if option is None: m = _RE_OPTION_MATCH(section) if m: section, option = m.groups() else: raise XoaConfigError( "You must provide an option name to get_option" ) try: value = options[section][option] except Exception: return XoaConfigError(f"Invalid section/option: {section}/{option}") return value class set_options(object): """Set configuration options Parameters ---------- section: str, None **options: dict If a key is in the format "<section>.<option>", then the section is overwritten. Example ------- .. ipython:: python @suppress from xoa import set_options, get_option # Classic: for the session set_options('plot', cmapdiv='cmo.balance', cmappos='cmo.amp') # With dict opts = {"plot.cmapdiv": "cmo.balance"} set_options(**opts) # Context: temporary with set_options('plot', cmapdiv='cmo.delta'): print('within context:', get_option('plot.cmapdiv')) print('after context:', get_option('plot.cmapdiv')) """ def __init__(self, section=None, **options): # Format before being ingested self.xoa_cache = _get_cache_() self.old_options = self.xoa_cache.get("options") if "options" in self.xoa_cache: del self.xoa_cache["options"] opts = {} for option, value in options.items(): m = _RE_OPTION_MATCH(option) if m: sec, option = m.groups() else: if section is None: raise XoaConfigError( "You must specify the section explicitly or through the option name") sec = section opts.setdefault(sec, {})[option] = value # Ingest options load_options(opts) def __enter__(self): return self.xoa_cache["options"] def __exit__(self, type, value, traceback): if self.old_options: self.xoa_cache["options"] = self.old_options else: del self.xoa_cache["options"] def set_option(option, value): """Set a single option using the flat format, i.e ``section.option`` Parameters ---------- option: str Option name in the ``section.option`` format value: Value to set Example ------- .. ipython:: python @suppress from xoa import set_option set_option('plot.cmapdiv', 'cmo.balance'); """ return set_options(None, **{option: value}) def reset_options(): """Restore options to their default values in the current session Example ------- .. ipython:: python @suppress from xoa import get_option, set_options, reset_options print(get_option('plot.cmapdiv')) set_options('plot', cmapdiv='mycmap') print(get_option('plot.cmapdiv')) reset_options() print(get_option('plot.cmapdiv')) """ xoa_cache = _get_cache_() del xoa_cache['options'] def show_options(specs=False): """Print current xoa configuration Parameters ---------- specs: bool Print option specifications instead Example ------- .. ipython:: python @suppress from xoa import show_options show_options() show_options(specs=True) """ if specs: print(CONFIG_SPECS.strip("\n")) else: print("\n".join(_get_options_().write()) .strip("\n").replace('#', ' #')) def _parse_requirements_(reqfile): re_match_specs_match = re.compile(r"^(\w+)(\W+.+)?$").match reqs = {} with open(reqfile) as f: for line in f: line = line.strip().strip("\n") if line and not line.startswith("#"): m = re_match_specs_match(line) if m: reqs[m.group(1)] = m.group(2) return reqs def show_versions(): """Print the versions of xoa and of some dependencies Example ------- .. ipython:: python :okexcept: @suppress from xoa import show_versions show_versions() """ print("- python:", platform.python_version()) print("- xoa:", __version__) for package in _PACKAGES: try: version = pkg_resources.get_distribution(package).version except pkg_resources.DistributionNotFound: version = "NOT INSTALLED or UKNOWN" print(f"- {package}: {version}") def show_paths(): """Print some xoa paths Example ------- .. ipython:: python :okexcept: @suppress from xoa import show_paths show_paths() """ print("- xoa library dir:", os.path.dirname(__file__)) from . import cf asterix = False for label, path in [("user config file", DEFAULT_USER_CONFIG_FILE), ("user CF specs file", cf.USER_CF_FILE), ("user CF cache file", cf.USER_CF_CACHE_FILE)]: if not os.path.exists(path): asterix = True path = path + " [*]" print("-", label+":", path) print("- data samples:", " ".join(get_data_sample())) if asterix: print("*: file not present") def show_info(opt_specs=True): """Print xoa related info Example ------- .. ipython:: python :okexcept: @suppress from xoa import show_info show_info() """ print("# VERSIONS") show_versions() print("\n# FILES AND DIRECTORIES") show_paths() print("\n# OPTIONS") show_options(specs=opt_specs) def get_data_sample(filename=None): """Get the absolute path to a sample file Parameters ---------- filename: str, None Name of the sample. If ommited, a list of available samples name is returned. Returns ------- str OR list(str) Example ------- .. .ipython:: python @suppress from xoa import get_data_sample get_data_sample("croco.south-africa.surf.nc") get_data_sample() See also -------- show_data_samples open_data_sample """ if not os.path.exists(_SAMPLE_DIR): filenames = [] else: filenames = os.listdir(_SAMPLE_DIR) if filename is None: return filenames if filename not in filenames: raise XoaError("Invalid data sample: "+filename) return os.path.join(_SAMPLE_DIR, filename) def open_data_sample(filename, **kwargs): """Open a data sample with :func:`xarray.open_dataset` or :func:`pandas.read_csv` A shortcut to:: xr.open_dataset(get_data_sample(filename)) Parameters ---------- filename: str File name of the sample Returns ------- xarray.Dataset, pandas.DataFrame Example ------- .. .ipython:: python @suppress from xoa import open_data_sample open_data_sample("croco.south-africa.nc") See also -------- get_data_sample show_data_samples """ fname = get_data_sample(filename) if fname.endswith("nc"): import xarray as xr return xr.open_dataset(fname, **kwargs) import pandas as pd return pd.read_csv(fname, **kwargs) def show_data_samples(): """Print the list of data samples Example ------- .. ipython:: python @suppress from xoa import show_data_samples show_data_samples() See also -------- get_data_samples open_data_sample """ print(' '.join(get_data_sample())) def register_accessors(xoa=True, xcf=False, decode_sigma=False): """Register xarray accessors Parameters ---------- xoa: bool, str Register the main accessors with :func:`~xoa.cf.register_xoa_accessors`. xcf: bool, str Register the :mod:`xoa.cf` module accessors with :func:`~xoa.cf.register_cf_accessors`. decode_sigma: bool, str Register the :mod:`xoa.sigma` module accessor with :func:`~xoa.cf.register_sigma_accessor`. See also -------- xoa.accessors """ if xoa: from .accessors import register_xoa_accessors kw = {"name": xoa} if isinstance(xoa, str) else {} register_xoa_accessors(**kw) if xcf: from .accessors import register_cf_accessors kw = {"name": xcf} if isinstance(xcf, str) else {} register_cf_accessors(**kw) if decode_sigma: from .accessors import register_sigma_accessor kw = {"name": decode_sigma} if isinstance(decode_sigma, str) else {} register_sigma_accessor(**kw)
24.48972
93
0.598611
import os import re import warnings import platform import pkg_resources import appdirs import configobj import validate try: __version__ = pkg_resources.get_distribution("xoa").version except Exception: __version__ = "999" _RE_OPTION_MATCH = re.compile(r"^(\w+)\W(\w+)$").match CONFIG_SPECS = """ [cf] # cf module cache=boolean(default=True) # use the :mod:`~xoa.cf` in memory and file caches [plot] # plot parameters cmapdiv = string(default="cmo.balance") # defaut diverging colormap cmappos = string(default="cmo.amp") # default positive colormap cmapneg = string(default="cmo.tempo_r") # default negative colormap cmapcyc = string(default="cmo.phase") # default cyclic colormap """ DEFAULT_USER_CONFIG_FILE = os.path.join( appdirs.user_config_dir("xoa"), "xoa.cfg" ) _SAMPLE_DIR = os.path.join(os.path.dirname(__file__), '_samples') _PACKAGES = [ "appdirs", "cartopy", "cmocean", "configobj", "matplotlib", "numpy", "pandas", "scipy", "xarray", "xesmf" ] class XoaError(Exception): pass class XoaConfigError(XoaError): pass class XoaWarning(UserWarning): pass def xoa_warn(message, stacklevel=2): warnings.warn(message, XoaWarning, stacklevel=stacklevel) def _get_cache_(): from . import __init__ if not hasattr(__init__, "_XOA_CACHE"): __init__._XOA_CACHE = {} return __init__._XOA_CACHE def load_options(cfgfile=None): _get_cache_() xoa_cache = _get_cache_() if "cfgspecs" not in xoa_cache: xoa_cache["cfgspecs"] = configobj.ConfigObj( CONFIG_SPECS.split("\n"), list_values=False, interpolation=False, raise_errors=True, file_error=True, ) if "options" not in xoa_cache: xoa_cache["options"] = configobj.ConfigObj( ( DEFAULT_USER_CONFIG_FILE if os.path.exists(DEFAULT_USER_CONFIG_FILE) else None ), configspec=xoa_cache["cfgspecs"], file_error=False, raise_errors=True, list_values=True, ) if cfgfile: xoa_cache["options"].merge( configobj.ConfigObj( cfgfile, file_error=True, raise_errors=True, list_values=True ) ) xoa_cache["options"].validate(validate.Validator(), copy=True) def _get_options_(): xoa_cache = _get_cache_() if "options" not in xoa_cache: load_options() return xoa_cache["options"] def get_option(section, option=None): options = _get_options_() if option is None: m = _RE_OPTION_MATCH(section) if m: section, option = m.groups() else: raise XoaConfigError( "You must provide an option name to get_option" ) try: value = options[section][option] except Exception: return XoaConfigError(f"Invalid section/option: {section}/{option}") return value class set_options(object): def __init__(self, section=None, **options): self.xoa_cache = _get_cache_() self.old_options = self.xoa_cache.get("options") if "options" in self.xoa_cache: del self.xoa_cache["options"] opts = {} for option, value in options.items(): m = _RE_OPTION_MATCH(option) if m: sec, option = m.groups() else: if section is None: raise XoaConfigError( "You must specify the section explicitly or through the option name") sec = section opts.setdefault(sec, {})[option] = value load_options(opts) def __enter__(self): return self.xoa_cache["options"] def __exit__(self, type, value, traceback): if self.old_options: self.xoa_cache["options"] = self.old_options else: del self.xoa_cache["options"] def set_option(option, value): return set_options(None, **{option: value}) def reset_options(): xoa_cache = _get_cache_() del xoa_cache['options'] def show_options(specs=False): if specs: print(CONFIG_SPECS.strip("\n")) else: print("\n".join(_get_options_().write()) .strip("\n").replace('#', ' #')) def _parse_requirements_(reqfile): re_match_specs_match = re.compile(r"^(\w+)(\W+.+)?$").match reqs = {} with open(reqfile) as f: for line in f: line = line.strip().strip("\n") if line and not line.startswith("#"): m = re_match_specs_match(line) if m: reqs[m.group(1)] = m.group(2) return reqs def show_versions(): print("- python:", platform.python_version()) print("- xoa:", __version__) for package in _PACKAGES: try: version = pkg_resources.get_distribution(package).version except pkg_resources.DistributionNotFound: version = "NOT INSTALLED or UKNOWN" print(f"- {package}: {version}") def show_paths(): print("- xoa library dir:", os.path.dirname(__file__)) from . import cf asterix = False for label, path in [("user config file", DEFAULT_USER_CONFIG_FILE), ("user CF specs file", cf.USER_CF_FILE), ("user CF cache file", cf.USER_CF_CACHE_FILE)]: if not os.path.exists(path): asterix = True path = path + " [*]" print("-", label+":", path) print("- data samples:", " ".join(get_data_sample())) if asterix: print("*: file not present") def show_info(opt_specs=True): print("# VERSIONS") show_versions() print("\n# FILES AND DIRECTORIES") show_paths() print("\n# OPTIONS") show_options(specs=opt_specs) def get_data_sample(filename=None): if not os.path.exists(_SAMPLE_DIR): filenames = [] else: filenames = os.listdir(_SAMPLE_DIR) if filename is None: return filenames if filename not in filenames: raise XoaError("Invalid data sample: "+filename) return os.path.join(_SAMPLE_DIR, filename) def open_data_sample(filename, **kwargs): fname = get_data_sample(filename) if fname.endswith("nc"): import xarray as xr return xr.open_dataset(fname, **kwargs) import pandas as pd return pd.read_csv(fname, **kwargs) def show_data_samples(): print(' '.join(get_data_sample())) def register_accessors(xoa=True, xcf=False, decode_sigma=False): if xoa: from .accessors import register_xoa_accessors kw = {"name": xoa} if isinstance(xoa, str) else {} register_xoa_accessors(**kw) if xcf: from .accessors import register_cf_accessors kw = {"name": xcf} if isinstance(xcf, str) else {} register_cf_accessors(**kw) if decode_sigma: from .accessors import register_sigma_accessor kw = {"name": decode_sigma} if isinstance(decode_sigma, str) else {} register_sigma_accessor(**kw)
true
true
f7149723918e0c4f1a80671f68d3b10a2ce44e1c
457
py
Python
ftm_service/app.py
cansik/FIFATournamentManager
ee86673fe2d754aee35ef277f152fa48e39281d8
[ "MIT" ]
null
null
null
ftm_service/app.py
cansik/FIFATournamentManager
ee86673fe2d754aee35ef277f152fa48e39281d8
[ "MIT" ]
null
null
null
ftm_service/app.py
cansik/FIFATournamentManager
ee86673fe2d754aee35ef277f152fa48e39281d8
[ "MIT" ]
null
null
null
import connexion import logging from flask.ext.cors import CORS from data.data_source import FTMDataSource data_source = FTMDataSource() def start_server(): logging.basicConfig(level=logging.INFO) app = connexion.App(__name__, port=8080, specification_dir='swagger/', server='gevent') app.add_api('ftm_service.yaml') app.debug = True CORS(app.app) app.run() data_source.close() if __name__ == '__main__': start_server()
21.761905
91
0.724289
import connexion import logging from flask.ext.cors import CORS from data.data_source import FTMDataSource data_source = FTMDataSource() def start_server(): logging.basicConfig(level=logging.INFO) app = connexion.App(__name__, port=8080, specification_dir='swagger/', server='gevent') app.add_api('ftm_service.yaml') app.debug = True CORS(app.app) app.run() data_source.close() if __name__ == '__main__': start_server()
true
true
f71498faa11249dfd60ec67c988ac1d9a4251dca
4,390
py
Python
homeassistant/components/unifi_direct/device_tracker.py
MrDelik/core
93a66cc357b226389967668441000498a10453bb
[ "Apache-2.0" ]
30,023
2016-04-13T10:17:53.000Z
2020-03-02T12:56:31.000Z
homeassistant/components/unifi_direct/device_tracker.py
MrDelik/core
93a66cc357b226389967668441000498a10453bb
[ "Apache-2.0" ]
24,710
2016-04-13T08:27:26.000Z
2020-03-02T12:59:13.000Z
homeassistant/components/unifi_direct/device_tracker.py
MrDelik/core
93a66cc357b226389967668441000498a10453bb
[ "Apache-2.0" ]
11,956
2016-04-13T18:42:31.000Z
2020-03-02T09:32:12.000Z
"""Support for Unifi AP direct access.""" from __future__ import annotations import json import logging from pexpect import exceptions, pxssh import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_SSH_PORT = 22 UNIFI_COMMAND = 'mca-dump | tr -d "\n"' UNIFI_SSID_TABLE = "vap_table" UNIFI_CLIENT_TABLE = "sta_table" PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_SSH_PORT): cv.port, } ) def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: """Validate the configuration and return a Unifi direct scanner.""" scanner = UnifiDeviceScanner(config[DOMAIN]) if not scanner.connected: return None return scanner class UnifiDeviceScanner(DeviceScanner): """This class queries Unifi wireless access point.""" def __init__(self, config): """Initialize the scanner.""" self.host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.port = config[CONF_PORT] self.ssh = None self.connected = False self.last_results = {} self._connect() def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" result = _response_to_json(self._get_update()) if result: self.last_results = result return self.last_results.keys() def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" hostname = next( ( value.get("hostname") for key, value in self.last_results.items() if key.upper() == device.upper() ), None, ) if hostname is not None: hostname = str(hostname) return hostname def _connect(self): """Connect to the Unifi AP SSH server.""" self.ssh = pxssh.pxssh() try: self.ssh.login( self.host, self.username, password=self.password, port=self.port ) self.connected = True except exceptions.EOF: _LOGGER.error("Connection refused. SSH enabled?") self._disconnect() def _disconnect(self): """Disconnect the current SSH connection.""" try: self.ssh.logout() except Exception: # pylint: disable=broad-except pass finally: self.ssh = None self.connected = False def _get_update(self): try: if not self.connected: self._connect() # If we still aren't connected at this point # don't try to send anything to the AP. if not self.connected: return None self.ssh.sendline(UNIFI_COMMAND) self.ssh.prompt() return self.ssh.before except pxssh.ExceptionPxssh as err: _LOGGER.error("Unexpected SSH error: %s", str(err)) self._disconnect() return None except (AssertionError, exceptions.EOF) as err: _LOGGER.error("Connection to AP unavailable: %s", str(err)) self._disconnect() return None def _response_to_json(response): try: json_response = json.loads(str(response)[31:-1].replace("\\", "")) _LOGGER.debug(str(json_response)) ssid_table = json_response.get(UNIFI_SSID_TABLE) active_clients = {} for ssid in ssid_table: client_table = ssid.get(UNIFI_CLIENT_TABLE) for client in client_table: active_clients[client.get("mac")] = client return active_clients except (ValueError, TypeError): _LOGGER.error("Failed to decode response from AP") return {}
30.915493
82
0.622551
from __future__ import annotations import json import logging from pexpect import exceptions, pxssh import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME from homeassistant.core import HomeAssistant import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType _LOGGER = logging.getLogger(__name__) DEFAULT_SSH_PORT = 22 UNIFI_COMMAND = 'mca-dump | tr -d "\n"' UNIFI_SSID_TABLE = "vap_table" UNIFI_CLIENT_TABLE = "sta_table" PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_SSH_PORT): cv.port, } ) def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: scanner = UnifiDeviceScanner(config[DOMAIN]) if not scanner.connected: return None return scanner class UnifiDeviceScanner(DeviceScanner): def __init__(self, config): self.host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.port = config[CONF_PORT] self.ssh = None self.connected = False self.last_results = {} self._connect() def scan_devices(self): result = _response_to_json(self._get_update()) if result: self.last_results = result return self.last_results.keys() def get_device_name(self, device): hostname = next( ( value.get("hostname") for key, value in self.last_results.items() if key.upper() == device.upper() ), None, ) if hostname is not None: hostname = str(hostname) return hostname def _connect(self): self.ssh = pxssh.pxssh() try: self.ssh.login( self.host, self.username, password=self.password, port=self.port ) self.connected = True except exceptions.EOF: _LOGGER.error("Connection refused. SSH enabled?") self._disconnect() def _disconnect(self): try: self.ssh.logout() except Exception: pass finally: self.ssh = None self.connected = False def _get_update(self): try: if not self.connected: self._connect() # don't try to send anything to the AP. if not self.connected: return None self.ssh.sendline(UNIFI_COMMAND) self.ssh.prompt() return self.ssh.before except pxssh.ExceptionPxssh as err: _LOGGER.error("Unexpected SSH error: %s", str(err)) self._disconnect() return None except (AssertionError, exceptions.EOF) as err: _LOGGER.error("Connection to AP unavailable: %s", str(err)) self._disconnect() return None def _response_to_json(response): try: json_response = json.loads(str(response)[31:-1].replace("\\", "")) _LOGGER.debug(str(json_response)) ssid_table = json_response.get(UNIFI_SSID_TABLE) active_clients = {} for ssid in ssid_table: client_table = ssid.get(UNIFI_CLIENT_TABLE) for client in client_table: active_clients[client.get("mac")] = client return active_clients except (ValueError, TypeError): _LOGGER.error("Failed to decode response from AP") return {}
true
true
f7149918e61836615e0176df95bfc1ed42c287dc
821
py
Python
spider/code/bs_spider01.py
mama2100/knowledge
5a18a3c243d7411f5135ec680dc5bd95d92be056
[ "MIT" ]
881
2018-03-20T09:19:14.000Z
2022-03-24T10:17:33.000Z
spider/code/bs_spider01.py
mama2100/knowledge
5a18a3c243d7411f5135ec680dc5bd95d92be056
[ "MIT" ]
null
null
null
spider/code/bs_spider01.py
mama2100/knowledge
5a18a3c243d7411f5135ec680dc5bd95d92be056
[ "MIT" ]
248
2018-05-31T01:06:15.000Z
2022-03-14T06:52:25.000Z
import urllib3 # 你需要一个PoolManager实例来生成请求,由该实例对象处理与线程池的连接以及 # 线程安全的所有细节,不需要任何人为操作 http = urllib3.PoolManager() # request()方法创建一个GET请求去获取百度的网页信息,返回的r是一个HttpResponse对象 r = http.request('GET', 'https://www.baidu.com') # 打印请求的状态 print(r.status) # 打印请求网页的内容 print(r.data) ''' Accept: text/html, */*;q=0.8 # 浏览器告诉服务器可以接收的文本类型, */*表示任何类型都可以接收 Accept-Encoding: gzip, deflate # 浏览器告诉服务器,数据可以压缩,页面可以解压数据然后进行渲染。做爬虫的时候,最好不要写该参数 Accept-Language: zh-CN,zh;q=0.9 # 语言类型 Cache-Control: max-age=0 # Connection: keep-alive # 保持连接 Cookie: Hm_lvt_3bfcc098e0da26d58c321ba579b04b2f=1527581188,1528137133 Host: www.cdtopspeed.com # 域名 Upgrade-Insecure-Requests: 1 # 用户代理, 使得服务器能够识别请求是通过浏览器请求过来的,其中包含浏览器的名称/版本等信息 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 '''
28.310345
121
0.773447
import urllib3 http = urllib3.PoolManager() r = http.request('GET', 'https://www.baidu.com') print(r.status) print(r.data)
true
true
f71499c7f2f926ce80c69f47e36b2d1191d1b667
22,070
py
Python
nipy/labs/spatial_models/hroi.py
fabianp/nipy
40e89f3ca7f34df05631623807993026134e6de3
[ "BSD-3-Clause" ]
1
2020-01-02T01:50:19.000Z
2020-01-02T01:50:19.000Z
nipy/labs/spatial_models/hroi.py
fabianp/nipy
40e89f3ca7f34df05631623807993026134e6de3
[ "BSD-3-Clause" ]
null
null
null
nipy/labs/spatial_models/hroi.py
fabianp/nipy
40e89f3ca7f34df05631623807993026134e6de3
[ "BSD-3-Clause" ]
null
null
null
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ This module contains the specification of 'hierarchical ROI' object, Which is used in spatial models of the library such as structural analysis The connection with other classes is not completely satisfactory at the moment: there should be some intermediate classes between 'Fields' and 'hroi' Author : Bertrand Thirion, 2009-2011 Virgile Fritsch <virgile.fritsch@inria.fr> """ import numpy as np from nipy.algorithms.graph.graph import WeightedGraph from nipy.algorithms.graph.forest import Forest from nipy.algorithms.graph.field import field_from_coo_matrix_and_data from .mroi import SubDomains NINF = - np.inf def hroi_agglomeration(input_hroi, criterion='size', smin=0): """Performs an agglomeration then a selection of regions so that a certain size or volume criterion is satisfied. Parameters ---------- input_hroi: HierarchicalROI instance The input hROI criterion: str, optional To be chosen among 'size' or 'volume' smin: float, optional The applied criterion Returns ------- output_hroi: HierarchicalROI instance """ if criterion not in ['size', 'volume']: return ValueError('unknown criterion') output_hroi = input_hroi.copy() k = 2 * output_hroi.k if criterion == 'size': value = output_hroi.get_size() if criterion == 'volume': value = output_hroi.get_volume() # iteratively agglomerate regions that are too small while k > output_hroi.k: k = output_hroi.k # regions agglomeration output_hroi.merge_ascending(output_hroi.get_id()[value <= smin]) # suppress parents nodes having only one child output_hroi.merge_descending() # early stopping 1 if output_hroi.k == 0: break # early stopping 2 if criterion == 'size': value = output_hroi.get_size() if criterion == 'volume': value = output_hroi.get_volume() if value.max() < smin: break # finally remove those regions for which the criterion cannot be matched output_hroi.select_roi(output_hroi.get_id()[value > smin]) return output_hroi def HROI_as_discrete_domain_blobs(domain, data, threshold=NINF, smin=0, criterion='size'): """Instantiate an HierarchicalROI as the blob decomposition of data in a certain domain. Parameters ---------- domain : discrete_domain.StructuredDomain instance, Definition of the spatial context. data : array of shape (domain.size) The corresponding data field. threshold : float, optional Thresholding level. criterion : string, optional To be chosen among 'size' or 'volume'. smin: float, optional A threshold on the criterion. Returns ------- nroi: HierachicalROI instance with a `signal` feature. """ if threshold > data.max(): # return an empty HROI structure label = - np.ones(data.shape) parents = np.array([]) return HierarchicalROI(domain, label, parents) # check size df = field_from_coo_matrix_and_data(domain.topology, data) idx, parents, label = df.threshold_bifurcations(th=threshold) nroi = HierarchicalROI(domain, label, parents) # create a signal feature data = np.ravel(data) signal = [data[nroi.select_id(id, roi=False)] for id in nroi.get_id()] nroi.set_feature('signal', signal) # agglomerate regions in order to compact the structure if necessary nroi = hroi_agglomeration(nroi, criterion=criterion, smin=smin) return nroi def HROI_from_watershed(domain, data, threshold=NINF): """Instantiate an HierarchicalROI as the watershed of a certain dataset Parameters ---------- domain: discrete_domain.StructuredDomain instance Definition of the spatial context. data: array of shape (domain.size) The corresponding data field. threshold: float, optional Thresholding level. Returns ------- nroi : ``HierarchichalROI`` instance The HierachicalROI instance with a ``seed`` feature. """ if threshold > data.max(): # return an empty HROI structure label = - np.ones(data.shape) parents = np.array([]) return HierarchicalROI(domain, label, parents) df = field_from_coo_matrix_and_data(domain.topology, data) idx, label = df.custom_watershed(0, threshold) parents = np.arange(idx.size).astype(int) nroi = HierarchicalROI(domain, label, parents) nroi.set_roi_feature('seed', idx) return nroi ######################################################################## # Hierarchical ROI ######################################################################## class HierarchicalROI(SubDomains): """Class that handles hierarchical ROIs Parameters ---------- k : int Number of ROI in the SubDomains object label : array of shape (domain.size), dtype=np.int An array use to define which voxel belongs to which ROI. The label values greater than -1 correspond to subregions labelling. The labels are recomputed so as to be consecutive integers. The labels should not be accessed outside this class. One has to use the API mapping methods instead. features : dict {str: list of object, length=self.k} Describe the voxels features, grouped by ROI roi_features : dict {str: array-like, shape=(self.k, roi_feature_dim) Describe the ROI features. A special feature, `id`, is read-only and is used to give an unique identifier for region, which is persistent through the MROI objects manipulations. On should access the different ROI's features using ids. parents : np.ndarray, shape(self.k) self.parents[i] is the index of the parent of the i-th ROI. TODO: have the parents as a list of id rather than a list of indices. """ def __init__(self, domain, label, parents, id=None): """Building the HierarchicalROI """ SubDomains.__init__(self, domain, label, id=id) self.parents = np.ravel(parents).astype(np.int) ### # Getters for very basic features or roi features ### def get_volume(self, id=None, ignore_children=True): """Get ROI volume Parameters ---------- id: any hashable type, optional Id of the ROI from which we want to get the volume. Can be None (default) if we want all ROIs's volumes. ignore_children : bool, optional Specify if the volume of the node should include (ignore_children = False) or not the one of its children (ignore_children = True). Returns ------- volume : float if an id is provided, or list of float if no id provided (default) """ if ignore_children: # volume of the children is not included volume = SubDomains.get_volume(self, id) else: # volume of the children is included if id is not None: volume = SubDomains.get_volume(self, id) desc = self.make_forest().get_descendents( self.select_id(id), exclude_self=True) # get children volume for k in desc: volume = volume + SubDomains.get_volume( self, self.get_id()[k]) else: volume = [] for id in self.get_id(): roi_volume = SubDomains.get_volume(self, id) desc = self.make_forest().get_descendents( self.select_id(id), exclude_self=True) # get children volume for k in desc: roi_volume = roi_volume + SubDomains.get_volume( self, self.get_id()[k]) volume.append(roi_volume) return volume def get_size(self, id=None, ignore_children=True): """Get ROI size (counted in terms of voxels) Parameters ---------- id: any hashable type, optional Id of the ROI from which we want to get the size. Can be None (default) if we want all ROIs's sizes. ignore_children: bool, optional Specify if the size of the node should include (ignore_children = False) or not the one of its children (ignore_children = True). Returns ------- size: int if an id is provided, or list of int if no id provided (default) """ if ignore_children: # size of the children is not included size = SubDomains.get_size(self, id) else: # size of the children is included if id is not None: size = SubDomains.get_size(self, id) desc = self.make_forest().get_descendents( self.select_id(id), exclude_self=True) # get children size for k in desc: size = size + SubDomains.get_size(self, self.get_id()[k]) else: size = [] for id in self.get_id(): roi_size = SubDomains.get_size(self, id) desc = self.make_forest().get_descendents( self.select_id(id), exclude_self=True) # get children size for k in desc: roi_size = roi_size + SubDomains.get_size( self, self.get_id()[k]) size.append(roi_size) return size def select_roi(self, id_list): """Returns an instance of HROI with only the subset of chosen ROIs. The hierarchy is set accordingly. Parameters ---------- id_list: list of id (any hashable type) The id of the ROI to be kept in the structure. """ valid = np.asarray([int(i in id_list) for i in self.get_id()]) if np.size(id_list) == 0: # handle the case of an empty selection new_parents = np.array([]) self = HierarchicalROI( self.domain, -np.ones(self.label.size), np.array([])) else: # get new parents new_parents = Forest(self.k, self.parents).subforest( valid.astype(np.bool)).parents.astype(np.int) SubDomains.select_roi(self, id_list) self.parents = new_parents self.recompute_labels() def make_graph(self): """Output an nipy graph structure to represent the ROI hierarchy. """ if self.k == 0: return None weights = np.ones(self.k) edges = (np.vstack((np.arange(self.k), self.parents))).T return WeightedGraph(self.k, edges, weights) def make_forest(self): """Output an nipy forest structure to represent the ROI hierarchy. """ if self.k == 0: return None G = Forest(self.k, self.parents) return G def merge_ascending(self, id_list, pull_features=None): """Remove the non-valid ROIs by including them in their parents when it exists. Parameters ---------- id_list: list of id (any hashable type) The id of the ROI to be merged into their parents. Nodes that are their own parent are unmodified. pull_features: list of str List of the ROI features that will be pooled from the children when they are merged into their parents. Otherwise, the receiving parent would keep its own ROI feature. """ if pull_features is None: pull_features = [] if self.k == 0: return id_list = [k for k in self.get_id() if k in id_list] # relabel maps old labels to new labels relabel = np.arange(self.k) # merge nodes, one at a time for c_id in id_list: # define alias for clearer indexing c_pos = self.select_id(c_id) p_pos = self.parents[c_pos] p_id = self.get_id()[p_pos] if p_pos != c_pos: # this will be used in many places mask_pos = np.ones(self.k, np.bool) mask_pos[c_pos] = False # set new parents self.parents = self.parents[mask_pos] self.parents[self.parents == c_pos] = p_pos self.parents[self.parents > c_pos] -= 1 self.k -= 1 # merge labels relabel[relabel == c_id] = p_id # compute new features for fid in self.features.keys(): # replace feature # (without the API since self is in an inconsistent state) dj = self.get_feature(fid) dj[p_pos] = np.hstack((dj[self.select_id(c_id)], dj[self.select_id(p_id)])) del dj[c_pos] self.features[fid] = dj # compute new roi features for fid in self.roi_features.keys(): dj = self.get_roi_feature(fid) if fid in pull_features: # modify only if `pull` requested dj[p_pos] = dj[c_pos] self.roi_features[fid] = dj[mask_pos] # update the labels self.label[self.label > -1] = relabel[self.label[self.label > - 1]] self.recompute_labels() def merge_descending(self, pull_features=None): """ Remove the items with only one son by including them in their son Parameters ---------- methods indicates the way possible features are dealt with (not implemented yet) Caveat ------ if roi_features have been defined, they will be removed """ if pull_features is None: pull_features = [] if self.k == 0: return # relabel maps old labels to new labels relabel = np.arange(self.k) # merge nodes, one at a time id_list = self.get_id()[:: - 1] for p_id in id_list: p_pos = self.select_id(p_id) p_children = np.nonzero(self.parents == p_pos)[0] if p_pos in p_children: # remove current node from its children list p_children = p_children[p_children != p_pos] if p_children.size == 1: # merge node if it has only one child c_pos = p_children[0] c_id = self.get_id()[c_pos] mask_pos = np.ones(self.k, np.bool) mask_pos[p_pos] = False # set new parents self.parents[c_pos] = self.parents[p_pos] if self.parents[c_pos] == p_pos: self.parents[c_pos] = c_pos self.parents = self.parents[mask_pos] self.parents[self.parents > p_pos] -= 1 # merge labels relabel[relabel == p_pos] = relabel[c_pos] self.k -= 1 # compute new features for fid in self.features.keys(): # replace feature # (without the API since self is in an inconsistent state) dj = self.get_feature(fid) dj[c_pos] = np.hstack((dj[self.select_id(c_id)], dj[self.select_id(p_id)])) del dj[p_pos] self.features[fid] = dj # compute new roi features for fid in self.roi_features.keys(): dj = self.get_roi_feature(fid) if fid in pull_features: # modify only if `pull` requested dj[c_pos] = dj[p_pos] self.roi_features[fid] = dj[mask_pos] # update HROI structure self.label[self.label > -1] = relabel[self.label[self.label > - 1]] self.recompute_labels() def get_parents(self): """Return the parent of each node in the hierarchy The parents are represented by their position in the nodes flat list. TODO: The purpose of this class API is not to rely on this order, so we should have self.parents as a list of ids instead of a list of positions """ return self.parents def get_leaves_id(self): """Return the ids of the leaves. """ if self.k == 0: return np.array([]) # locate the positions of the children of each node is_leaf_aux = [np.where(self.parents == k)[0] for k in range(self.k)] # select nodes that has no child (different from themselves) is_leaf = np.asarray( [(len(child) == 0) or (len(child) == 1 and child[0] == i) for i, child in enumerate(is_leaf_aux)]) # finaly return ids return self.get_id()[is_leaf] def reduce_to_leaves(self): """Create a new set of rois which are only the leaves of self. Modification of the structure is done in place. One way therefore want to work on a copy a of a given HROI oject. """ if self.k == 0: # handle the empy HROI case return HierarchicalROI( self.domain, -np.ones(self.domain.size), np.array([])) leaves_id = self.get_leaves_id() self.select_roi(leaves_id) def copy(self): """ Returns a copy of self. self.domain is not copied. """ cp = HierarchicalROI( self.domain, self.label.copy(), self.parents.copy(), self.get_id()) # copy features for fid in self.features.keys(): cp.set_feature(fid, self.get_feature(fid)) # copy ROI features for fid in self.roi_features.keys(): cp.set_roi_feature(fid, self.get_roi_feature(fid)) return cp def representative_feature(self, fid, method='mean', id=None, ignore_children=True, assess_quality=True): """Compute a ROI representative of a given feature. Parameters ---------- fid: str, Feature id method: str, Method used to compute a representative. Chosen among 'mean' (default), 'max', 'median', 'min', 'weighted mean'. id: any hashable type Id of the ROI from which we want to extract a representative feature. Can be None (default) if we want to get all ROIs's representatives. ignore_children: bool, Specify if the volume of the node should include (ignore_children = False) or not the one of its children (ignore_children = True). assess_quality: bool If True, a new roi feature is created, which represent the quality of the feature representative (the number of non-nan value for the feature over the ROI size). Default is False. """ rf = [] eps = 1.e-15 feature_quality = np.zeros(self.k) for i, k in enumerate(self.get_id()): f = self.get_feature(fid, k) p_pos = self.select_id(k) if not ignore_children: # also include the children features desc = np.nonzero(self.parents == p_pos)[0] if p_pos in desc: desc = desc[desc != p_pos] for c in desc: f = np.concatenate( (f, self.get_feature(fid, self.get_id()[c]))) # NaN-resistant representative if f.ndim == 2: nan = np.isnan(f.sum(1)) else: nan = np.isnan(f) # feature quality feature_quality[i] = (~nan).sum() / float(nan.size) # compute representative if method == "mean": rf.append(np.mean(f[~nan], 0)) if method == "weighted mean": lvk = self.get_local_volume(k) if not ignore_children: # append weights for children's voxels for c in desc: lvk = np.concatenate( (lvk, self.get_local_volume(fid, self.select_id(c)))) tmp = np.dot(lvk[~nan], f[~nan].reshape((-1, 1))) / \ np.maximum(eps, np.sum(lvk[~nan])) rf.append(tmp) if method == "min": rf.append(np.min(f[~nan])) if method == "max": rf.append(np.max(f[~nan])) if method == "median": rf.append(np.median(f[~nan], 0)) if id is not None: summary_feature = rf[self.select_id(id)] else: summary_feature = rf if assess_quality: self.set_roi_feature('%s_quality' % fid, feature_quality) return np.array(summary_feature) def make_hroi_from_subdomain(sub_domain, parents): """Instantiate an HROi from a SubDomain instance and parents """ hroi = HierarchicalROI(sub_domain.domain, sub_domain.label, parents) # set features for fid in sub_domain.features.keys(): hroi.set_feature(fid, sub_domain.get_feature(fid)) # set ROI features for fid in sub_domain.roi_features.keys(): hroi.set_roi_feature(fid, sub_domain.get_roi_feature(fid)) return hroi
36.419142
79
0.561305
import numpy as np from nipy.algorithms.graph.graph import WeightedGraph from nipy.algorithms.graph.forest import Forest from nipy.algorithms.graph.field import field_from_coo_matrix_and_data from .mroi import SubDomains NINF = - np.inf def hroi_agglomeration(input_hroi, criterion='size', smin=0): if criterion not in ['size', 'volume']: return ValueError('unknown criterion') output_hroi = input_hroi.copy() k = 2 * output_hroi.k if criterion == 'size': value = output_hroi.get_size() if criterion == 'volume': value = output_hroi.get_volume() while k > output_hroi.k: k = output_hroi.k output_hroi.merge_ascending(output_hroi.get_id()[value <= smin]) output_hroi.merge_descending() if output_hroi.k == 0: break if criterion == 'size': value = output_hroi.get_size() if criterion == 'volume': value = output_hroi.get_volume() if value.max() < smin: break output_hroi.select_roi(output_hroi.get_id()[value > smin]) return output_hroi def HROI_as_discrete_domain_blobs(domain, data, threshold=NINF, smin=0, criterion='size'): if threshold > data.max(): label = - np.ones(data.shape) parents = np.array([]) return HierarchicalROI(domain, label, parents) df = field_from_coo_matrix_and_data(domain.topology, data) idx, parents, label = df.threshold_bifurcations(th=threshold) nroi = HierarchicalROI(domain, label, parents) data = np.ravel(data) signal = [data[nroi.select_id(id, roi=False)] for id in nroi.get_id()] nroi.set_feature('signal', signal) nroi = hroi_agglomeration(nroi, criterion=criterion, smin=smin) return nroi def HROI_from_watershed(domain, data, threshold=NINF): if threshold > data.max(): label = - np.ones(data.shape) parents = np.array([]) return HierarchicalROI(domain, label, parents) df = field_from_coo_matrix_and_data(domain.topology, data) idx, label = df.custom_watershed(0, threshold) parents = np.arange(idx.size).astype(int) nroi = HierarchicalROI(domain, label, parents) nroi.set_roi_feature('seed', idx) return nroi .arange(self.k) id_list = self.get_id()[:: - 1] for p_id in id_list: p_pos = self.select_id(p_id) p_children = np.nonzero(self.parents == p_pos)[0] if p_pos in p_children: p_children = p_children[p_children != p_pos] if p_children.size == 1: c_pos = p_children[0] c_id = self.get_id()[c_pos] mask_pos = np.ones(self.k, np.bool) mask_pos[p_pos] = False self.parents[c_pos] = self.parents[p_pos] if self.parents[c_pos] == p_pos: self.parents[c_pos] = c_pos self.parents = self.parents[mask_pos] self.parents[self.parents > p_pos] -= 1 relabel[relabel == p_pos] = relabel[c_pos] self.k -= 1 for fid in self.features.keys(): dj = self.get_feature(fid) dj[c_pos] = np.hstack((dj[self.select_id(c_id)], dj[self.select_id(p_id)])) del dj[p_pos] self.features[fid] = dj for fid in self.roi_features.keys(): dj = self.get_roi_feature(fid) if fid in pull_features: dj[c_pos] = dj[p_pos] self.roi_features[fid] = dj[mask_pos] self.label[self.label > -1] = relabel[self.label[self.label > - 1]] self.recompute_labels() def get_parents(self): return self.parents def get_leaves_id(self): if self.k == 0: return np.array([]) is_leaf_aux = [np.where(self.parents == k)[0] for k in range(self.k)] is_leaf = np.asarray( [(len(child) == 0) or (len(child) == 1 and child[0] == i) for i, child in enumerate(is_leaf_aux)]) return self.get_id()[is_leaf] def reduce_to_leaves(self): if self.k == 0: return HierarchicalROI( self.domain, -np.ones(self.domain.size), np.array([])) leaves_id = self.get_leaves_id() self.select_roi(leaves_id) def copy(self): cp = HierarchicalROI( self.domain, self.label.copy(), self.parents.copy(), self.get_id()) for fid in self.features.keys(): cp.set_feature(fid, self.get_feature(fid)) for fid in self.roi_features.keys(): cp.set_roi_feature(fid, self.get_roi_feature(fid)) return cp def representative_feature(self, fid, method='mean', id=None, ignore_children=True, assess_quality=True): rf = [] eps = 1.e-15 feature_quality = np.zeros(self.k) for i, k in enumerate(self.get_id()): f = self.get_feature(fid, k) p_pos = self.select_id(k) if not ignore_children: desc = np.nonzero(self.parents == p_pos)[0] if p_pos in desc: desc = desc[desc != p_pos] for c in desc: f = np.concatenate( (f, self.get_feature(fid, self.get_id()[c]))) if f.ndim == 2: nan = np.isnan(f.sum(1)) else: nan = np.isnan(f) feature_quality[i] = (~nan).sum() / float(nan.size) if method == "mean": rf.append(np.mean(f[~nan], 0)) if method == "weighted mean": lvk = self.get_local_volume(k) if not ignore_children: for c in desc: lvk = np.concatenate( (lvk, self.get_local_volume(fid, self.select_id(c)))) tmp = np.dot(lvk[~nan], f[~nan].reshape((-1, 1))) / \ np.maximum(eps, np.sum(lvk[~nan])) rf.append(tmp) if method == "min": rf.append(np.min(f[~nan])) if method == "max": rf.append(np.max(f[~nan])) if method == "median": rf.append(np.median(f[~nan], 0)) if id is not None: summary_feature = rf[self.select_id(id)] else: summary_feature = rf if assess_quality: self.set_roi_feature('%s_quality' % fid, feature_quality) return np.array(summary_feature) def make_hroi_from_subdomain(sub_domain, parents): hroi = HierarchicalROI(sub_domain.domain, sub_domain.label, parents) # set features for fid in sub_domain.features.keys(): hroi.set_feature(fid, sub_domain.get_feature(fid)) # set ROI features for fid in sub_domain.roi_features.keys(): hroi.set_roi_feature(fid, sub_domain.get_roi_feature(fid)) return hroi
true
true
f71499f5deb8f014468d50ba23386afe547af396
5,599
py
Python
utils.py
lgraesser/MCER
250aa6965064dbc73462eb5edb559bf9ce949b70
[ "Apache-2.0" ]
null
null
null
utils.py
lgraesser/MCER
250aa6965064dbc73462eb5edb559bf9ce949b70
[ "Apache-2.0" ]
null
null
null
utils.py
lgraesser/MCER
250aa6965064dbc73462eb5edb559bf9ce949b70
[ "Apache-2.0" ]
null
null
null
import json import logging import matplotlib.pyplot as plt import os import tensorflow as tf from sklearn.utils import shuffle import model import train logger = logging.getLogger('utils') logger.setLevel(logging.INFO) def get_data_path(): '''Returns the path to the image and annotation data. Downloads the data if it doesn't exist. ''' # Download caption annotation files annotation_folder = '/data/train_data/annotations/' if not os.path.exists(os.path.abspath('.') + annotation_folder): logger.info('Downloading captions file.') annotation_zip = tf.keras.utils.get_file('captions.zip', cache_subdir=os.path.abspath('./data/train_data'), origin = 'http://images.cocodataset.org/annotations/annotations_trainval2014.zip', extract = True) annotation_file_path = os.path.dirname(annotation_zip)+'/annotations/captions_train2014.json' os.remove(annotation_zip) else: annotation_file_path = os.path.abspath('.') + annotation_folder + 'captions_train2014.json' logger.info(f'Captions file already exists here {annotation_file_path}.') # Download image files image_folder = '/data/train_data/train2014/' if not os.path.exists(os.path.abspath('.') + image_folder): logger.info('Downloading image data. This may take a while.') image_zip = tf.keras.utils.get_file('train2014.zip', cache_subdir=os.path.abspath('./data/train_data'), origin = 'http://images.cocodataset.org/zips/train2014.zip', extract = True) image_file_path = os.path.dirname(image_zip) + image_folder os.remove(image_zip) else: image_file_path = os.path.abspath('.') + image_folder logger.info(f'Image data already exists here {image_file_path}.') return image_file_path, annotation_file_path def get_caption_image_names(annotation_file_path, image_file_path, shuffle_data=True): '''Returns a shuffled list of the captions and the corresponding image names.''' # Read the json file with open(annotation_file_path, 'r') as f: annotations = json.load(f) logger.info('Loaded the annotations file.') # Store captions and image names in vectors all_captions = [] all_img_name_vector = [] for annot in annotations['annotations']: caption = '<start> ' + annot['caption'] + ' <end>' image_id = annot['image_id'] full_coco_image_path = image_file_path + 'COCO_train2014_' + '%012d.jpg' % (image_id) all_img_name_vector.append(full_coco_image_path) all_captions.append(caption) # Shuffle captions and image_names together # Set a random state if shuffle_data: logger.info('Shuffling the data...') train_captions, img_name_vector = shuffle(all_captions, all_img_name_vector, random_state=1) else: train_captions = all_captions img_name_vector = all_img_name_vector return train_captions, img_name_vector def get_top_k(train_captions, img_name_vector, num_examples): '''Selects the first k examples from the data.''' assert len(train_captions) == len(img_name_vector) original_cap_length = len(train_captions) if num_examples > original_cap_length: logger.warning(f'Desired num examples {num_examples} > actual number examples {original_cap_length}, using whole training set') num_examples = original_cap_length train_captions = train_captions[:num_examples] img_name_vector = img_name_vector[:num_examples] logger.info(f'Num train captions: {len(train_captions)}, num all captions: {original_cap_length}') return train_captions, img_name_vector def calc_max_length(tensor): """Find the maximum length of any tensor""" return max(len(t) for t in tensor) def load_image(image_path): img = tf.io.read_file(image_path) img = tf.image.decode_jpeg(img, channels=3) img = tf.image.resize(img, (299, 299)) img = tf.keras.applications.inception_v3.preprocess_input(img) return img, image_path def plot_loss(loss_data): plt.plot(loss_plot) plt.xlabel('Epochs') plt.ylabel('Loss') plt.title('Loss Plot') plt.show() def save_loss_plot(loss_data, figname, data_label): plt.figure(figsize=(10, 10)) plt.plot(loss_data, label=data_label) plt.xlabel('Epochs') plt.ylabel('Loss') plt.title('Loss Plot') plt.legend(loc='upper left') plt.savefig(figname) plt.close() def build_model(model_logdir, vocab_size): embedding_dim = 256 units = 512 # Shape of the vector extracted from InceptionV3 is (64, 2048) # These two variables represent that vector shape encoder = model.CNN_Encoder(embedding_dim) decoder = model.RNN_Decoder(embedding_dim, units, vocab_size) # get optim, and checkpoint manager optimizer = train.get_optimizer() loss_object = train.get_loss_object() ckpt_manager, ckpt = train.get_checkpoint_manager(encoder, decoder, optimizer, path=model_logdir) # Restore tokenizer with open(os.path.join(model_logdir, 'tokenizer.json')) as f: data = json.load(f) tokenizer = tf.keras.preprocessing.text.tokenizer_from_json(data) return encoder, decoder, tokenizer, ckpt_manager, ckpt
37.577181
135
0.666905
import json import logging import matplotlib.pyplot as plt import os import tensorflow as tf from sklearn.utils import shuffle import model import train logger = logging.getLogger('utils') logger.setLevel(logging.INFO) def get_data_path(): annotation_folder = '/data/train_data/annotations/' if not os.path.exists(os.path.abspath('.') + annotation_folder): logger.info('Downloading captions file.') annotation_zip = tf.keras.utils.get_file('captions.zip', cache_subdir=os.path.abspath('./data/train_data'), origin = 'http://images.cocodataset.org/annotations/annotations_trainval2014.zip', extract = True) annotation_file_path = os.path.dirname(annotation_zip)+'/annotations/captions_train2014.json' os.remove(annotation_zip) else: annotation_file_path = os.path.abspath('.') + annotation_folder + 'captions_train2014.json' logger.info(f'Captions file already exists here {annotation_file_path}.') image_folder = '/data/train_data/train2014/' if not os.path.exists(os.path.abspath('.') + image_folder): logger.info('Downloading image data. This may take a while.') image_zip = tf.keras.utils.get_file('train2014.zip', cache_subdir=os.path.abspath('./data/train_data'), origin = 'http://images.cocodataset.org/zips/train2014.zip', extract = True) image_file_path = os.path.dirname(image_zip) + image_folder os.remove(image_zip) else: image_file_path = os.path.abspath('.') + image_folder logger.info(f'Image data already exists here {image_file_path}.') return image_file_path, annotation_file_path def get_caption_image_names(annotation_file_path, image_file_path, shuffle_data=True): with open(annotation_file_path, 'r') as f: annotations = json.load(f) logger.info('Loaded the annotations file.') all_captions = [] all_img_name_vector = [] for annot in annotations['annotations']: caption = '<start> ' + annot['caption'] + ' <end>' image_id = annot['image_id'] full_coco_image_path = image_file_path + 'COCO_train2014_' + '%012d.jpg' % (image_id) all_img_name_vector.append(full_coco_image_path) all_captions.append(caption) if shuffle_data: logger.info('Shuffling the data...') train_captions, img_name_vector = shuffle(all_captions, all_img_name_vector, random_state=1) else: train_captions = all_captions img_name_vector = all_img_name_vector return train_captions, img_name_vector def get_top_k(train_captions, img_name_vector, num_examples): assert len(train_captions) == len(img_name_vector) original_cap_length = len(train_captions) if num_examples > original_cap_length: logger.warning(f'Desired num examples {num_examples} > actual number examples {original_cap_length}, using whole training set') num_examples = original_cap_length train_captions = train_captions[:num_examples] img_name_vector = img_name_vector[:num_examples] logger.info(f'Num train captions: {len(train_captions)}, num all captions: {original_cap_length}') return train_captions, img_name_vector def calc_max_length(tensor): return max(len(t) for t in tensor) def load_image(image_path): img = tf.io.read_file(image_path) img = tf.image.decode_jpeg(img, channels=3) img = tf.image.resize(img, (299, 299)) img = tf.keras.applications.inception_v3.preprocess_input(img) return img, image_path def plot_loss(loss_data): plt.plot(loss_plot) plt.xlabel('Epochs') plt.ylabel('Loss') plt.title('Loss Plot') plt.show() def save_loss_plot(loss_data, figname, data_label): plt.figure(figsize=(10, 10)) plt.plot(loss_data, label=data_label) plt.xlabel('Epochs') plt.ylabel('Loss') plt.title('Loss Plot') plt.legend(loc='upper left') plt.savefig(figname) plt.close() def build_model(model_logdir, vocab_size): embedding_dim = 256 units = 512 encoder = model.CNN_Encoder(embedding_dim) decoder = model.RNN_Decoder(embedding_dim, units, vocab_size) optimizer = train.get_optimizer() loss_object = train.get_loss_object() ckpt_manager, ckpt = train.get_checkpoint_manager(encoder, decoder, optimizer, path=model_logdir) with open(os.path.join(model_logdir, 'tokenizer.json')) as f: data = json.load(f) tokenizer = tf.keras.preprocessing.text.tokenizer_from_json(data) return encoder, decoder, tokenizer, ckpt_manager, ckpt
true
true
f7149a066af83fb2bde594eb67a847e0095f1a45
8,345
py
Python
apischema/conversions/visitor.py
klauer/apischema
0da9b96b74dabe8704e2dcfca4502aed98500799
[ "MIT" ]
null
null
null
apischema/conversions/visitor.py
klauer/apischema
0da9b96b74dabe8704e2dcfca4502aed98500799
[ "MIT" ]
null
null
null
apischema/conversions/visitor.py
klauer/apischema
0da9b96b74dabe8704e2dcfca4502aed98500799
[ "MIT" ]
null
null
null
from contextlib import contextmanager, suppress from dataclasses import replace from functools import lru_cache from types import new_class from typing import ( Any, ClassVar, Collection, Generic, Iterable, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from apischema.conversions import LazyConversion from apischema.conversions.conversions import ( AnyConversion, DefaultConversion, ResolvedConversion, ResolvedConversions, handle_identity_conversion, is_identity, resolve_any_conversion, ) from apischema.conversions.dataclass_models import handle_dataclass_model from apischema.conversions.utils import is_convertible from apischema.metadata.implem import ConversionMetadata from apischema.type_names import type_name from apischema.types import AnyType from apischema.typing import get_args from apischema.utils import ( context_setter, get_origin_or_type, has_type_vars, is_subclass, substitute_type_vars, subtyping_substitution, ) from apischema.visitor import Result, Unsupported, Visitor Deserialization = ResolvedConversions Serialization = ResolvedConversion Conv = TypeVar("Conv") class ConversionsVisitor(Visitor[Result], Generic[Conv, Result]): base_conversion_visitor: ClassVar[Type["ConversionsVisitor"]] def __init__(self, default_conversion: DefaultConversion): self.default_conversion = default_conversion self._conversion: Optional[AnyConversion] = None def _has_conversion( self, tp: AnyType, conversion: Optional[AnyConversion] ) -> Tuple[bool, Optional[Conv]]: raise NotImplementedError def _annotated_conversion( self, annotation: ConversionMetadata ) -> Optional[AnyConversion]: raise NotImplementedError def annotated(self, tp: AnyType, annotations: Sequence[Any]) -> Result: for annotation in reversed(annotations): if isinstance(annotation, ConversionMetadata): with self._replace_conversion(self._annotated_conversion(annotation)): return super().annotated(tp, annotations) return super().annotated(tp, annotations) def _union_results(self, alternatives: Iterable[AnyType]) -> Sequence[Result]: results = [] for alt in alternatives: with suppress(Unsupported): results.append(self.visit(alt)) if not results: raise Unsupported(Union[tuple(alternatives)]) return results def _visited_union(self, results: Sequence[Result]) -> Result: raise NotImplementedError def union(self, alternatives: Sequence[AnyType]) -> Result: return self._visited_union(self._union_results(alternatives)) @contextmanager def _replace_conversion(self, conversion: Optional[AnyConversion]): with context_setter(self): self._conversion = resolve_any_conversion(conversion) or None yield def visit_with_conv( self, tp: AnyType, conversion: Optional[AnyConversion] ) -> Result: with self._replace_conversion(conversion): return self.visit(tp) def _visit_conversion( self, tp: AnyType, conversion: Conv, dynamic: bool, next_conversion: Optional[AnyConversion], ) -> Result: raise NotImplementedError def visit_conversion( self, tp: AnyType, conversion: Optional[Conv], dynamic: bool, next_conversion: Optional[AnyConversion] = None, ) -> Result: if conversion is not None: return self._visit_conversion(tp, conversion, dynamic, next_conversion) else: with self._replace_conversion(next_conversion): return super().visit(tp) def visit(self, tp: AnyType) -> Result: if not is_convertible(tp): return self.visit_conversion(tp, None, False, self._conversion) dynamic, conversion = self._has_conversion(tp, self._conversion) if not dynamic: _, conversion = self._has_conversion( tp, self.default_conversion(get_origin_or_type(tp)) # type: ignore ) next_conversion = None if not dynamic and is_subclass(tp, Collection): next_conversion = self._conversion return self.visit_conversion(tp, conversion, dynamic, next_conversion) def sub_conversion( conversion: ResolvedConversion, next_conversion: Optional[AnyConversion] ) -> Optional[AnyConversion]: return ( LazyConversion(lambda: conversion.sub_conversion), LazyConversion(lambda: next_conversion), ) @lru_cache(maxsize=0) def self_deserialization_wrapper(cls: Type) -> Type: wrapper = new_class( f"{cls.__name__}SelfDeserializer", (cls[cls.__parameters__] if has_type_vars(cls) else cls,), exec_body=lambda ns: ns.update( {"__new__": lambda _, *args, **kwargs: cls(*args, **kwargs)} ), ) return type_name(None)(wrapper) class DeserializationVisitor(ConversionsVisitor[Deserialization, Result]): @staticmethod def _has_conversion( tp: AnyType, conversion: Optional[AnyConversion] ) -> Tuple[bool, Optional[Deserialization]]: identity_conv, result = False, [] for conv in resolve_any_conversion(conversion): conv = handle_identity_conversion(conv, tp) if is_subclass(conv.target, tp): if is_identity(conv): if identity_conv: continue identity_conv = True wrapper: AnyType = self_deserialization_wrapper( get_origin_or_type(tp) ) if get_args(tp): wrapper = wrapper[get_args(tp)] conv = ResolvedConversion(replace(conv, source=wrapper)) conv = handle_dataclass_model(conv) _, substitution = subtyping_substitution(tp, conv.target) source = substitute_type_vars(conv.source, substitution) result.append( ResolvedConversion(replace(conv, source=source, target=tp)) ) if identity_conv and len(result) == 1: return True, None else: return bool(result), tuple(result) or None def _annotated_conversion( self, annotation: ConversionMetadata ) -> Optional[AnyConversion]: return annotation.deserialization def _visit_conversion( self, tp: AnyType, conversion: Deserialization, dynamic: bool, next_conversion: Optional[AnyConversion], ) -> Result: results = [ self.visit_with_conv(conv.source, sub_conversion(conv, next_conversion)) for conv in conversion ] return self._visited_union(results) class SerializationVisitor(ConversionsVisitor[Serialization, Result]): @staticmethod def _has_conversion( tp: AnyType, conversion: Optional[AnyConversion] ) -> Tuple[bool, Optional[Serialization]]: for conv in resolve_any_conversion(conversion): conv = handle_identity_conversion(conv, tp) if is_subclass(tp, conv.source): if is_identity(conv): return True, None conv = handle_dataclass_model(conv) substitution, _ = subtyping_substitution(conv.source, tp) target = substitute_type_vars(conv.target, substitution) return True, ResolvedConversion(replace(conv, source=tp, target=target)) else: return False, None def _annotated_conversion( self, annotation: ConversionMetadata ) -> Optional[AnyConversion]: return annotation.serialization def _visit_conversion( self, tp: AnyType, conversion: Serialization, dynamic: bool, next_conversion: Optional[AnyConversion], ) -> Result: return self.visit_with_conv( conversion.target, sub_conversion(conversion, next_conversion) ) DeserializationVisitor.base_conversion_visitor = DeserializationVisitor SerializationVisitor.base_conversion_visitor = SerializationVisitor
34.341564
88
0.660036
from contextlib import contextmanager, suppress from dataclasses import replace from functools import lru_cache from types import new_class from typing import ( Any, ClassVar, Collection, Generic, Iterable, Optional, Sequence, Tuple, Type, TypeVar, Union, ) from apischema.conversions import LazyConversion from apischema.conversions.conversions import ( AnyConversion, DefaultConversion, ResolvedConversion, ResolvedConversions, handle_identity_conversion, is_identity, resolve_any_conversion, ) from apischema.conversions.dataclass_models import handle_dataclass_model from apischema.conversions.utils import is_convertible from apischema.metadata.implem import ConversionMetadata from apischema.type_names import type_name from apischema.types import AnyType from apischema.typing import get_args from apischema.utils import ( context_setter, get_origin_or_type, has_type_vars, is_subclass, substitute_type_vars, subtyping_substitution, ) from apischema.visitor import Result, Unsupported, Visitor Deserialization = ResolvedConversions Serialization = ResolvedConversion Conv = TypeVar("Conv") class ConversionsVisitor(Visitor[Result], Generic[Conv, Result]): base_conversion_visitor: ClassVar[Type["ConversionsVisitor"]] def __init__(self, default_conversion: DefaultConversion): self.default_conversion = default_conversion self._conversion: Optional[AnyConversion] = None def _has_conversion( self, tp: AnyType, conversion: Optional[AnyConversion] ) -> Tuple[bool, Optional[Conv]]: raise NotImplementedError def _annotated_conversion( self, annotation: ConversionMetadata ) -> Optional[AnyConversion]: raise NotImplementedError def annotated(self, tp: AnyType, annotations: Sequence[Any]) -> Result: for annotation in reversed(annotations): if isinstance(annotation, ConversionMetadata): with self._replace_conversion(self._annotated_conversion(annotation)): return super().annotated(tp, annotations) return super().annotated(tp, annotations) def _union_results(self, alternatives: Iterable[AnyType]) -> Sequence[Result]: results = [] for alt in alternatives: with suppress(Unsupported): results.append(self.visit(alt)) if not results: raise Unsupported(Union[tuple(alternatives)]) return results def _visited_union(self, results: Sequence[Result]) -> Result: raise NotImplementedError def union(self, alternatives: Sequence[AnyType]) -> Result: return self._visited_union(self._union_results(alternatives)) @contextmanager def _replace_conversion(self, conversion: Optional[AnyConversion]): with context_setter(self): self._conversion = resolve_any_conversion(conversion) or None yield def visit_with_conv( self, tp: AnyType, conversion: Optional[AnyConversion] ) -> Result: with self._replace_conversion(conversion): return self.visit(tp) def _visit_conversion( self, tp: AnyType, conversion: Conv, dynamic: bool, next_conversion: Optional[AnyConversion], ) -> Result: raise NotImplementedError def visit_conversion( self, tp: AnyType, conversion: Optional[Conv], dynamic: bool, next_conversion: Optional[AnyConversion] = None, ) -> Result: if conversion is not None: return self._visit_conversion(tp, conversion, dynamic, next_conversion) else: with self._replace_conversion(next_conversion): return super().visit(tp) def visit(self, tp: AnyType) -> Result: if not is_convertible(tp): return self.visit_conversion(tp, None, False, self._conversion) dynamic, conversion = self._has_conversion(tp, self._conversion) if not dynamic: _, conversion = self._has_conversion( tp, self.default_conversion(get_origin_or_type(tp)) ) next_conversion = None if not dynamic and is_subclass(tp, Collection): next_conversion = self._conversion return self.visit_conversion(tp, conversion, dynamic, next_conversion) def sub_conversion( conversion: ResolvedConversion, next_conversion: Optional[AnyConversion] ) -> Optional[AnyConversion]: return ( LazyConversion(lambda: conversion.sub_conversion), LazyConversion(lambda: next_conversion), ) @lru_cache(maxsize=0) def self_deserialization_wrapper(cls: Type) -> Type: wrapper = new_class( f"{cls.__name__}SelfDeserializer", (cls[cls.__parameters__] if has_type_vars(cls) else cls,), exec_body=lambda ns: ns.update( {"__new__": lambda _, *args, **kwargs: cls(*args, **kwargs)} ), ) return type_name(None)(wrapper) class DeserializationVisitor(ConversionsVisitor[Deserialization, Result]): @staticmethod def _has_conversion( tp: AnyType, conversion: Optional[AnyConversion] ) -> Tuple[bool, Optional[Deserialization]]: identity_conv, result = False, [] for conv in resolve_any_conversion(conversion): conv = handle_identity_conversion(conv, tp) if is_subclass(conv.target, tp): if is_identity(conv): if identity_conv: continue identity_conv = True wrapper: AnyType = self_deserialization_wrapper( get_origin_or_type(tp) ) if get_args(tp): wrapper = wrapper[get_args(tp)] conv = ResolvedConversion(replace(conv, source=wrapper)) conv = handle_dataclass_model(conv) _, substitution = subtyping_substitution(tp, conv.target) source = substitute_type_vars(conv.source, substitution) result.append( ResolvedConversion(replace(conv, source=source, target=tp)) ) if identity_conv and len(result) == 1: return True, None else: return bool(result), tuple(result) or None def _annotated_conversion( self, annotation: ConversionMetadata ) -> Optional[AnyConversion]: return annotation.deserialization def _visit_conversion( self, tp: AnyType, conversion: Deserialization, dynamic: bool, next_conversion: Optional[AnyConversion], ) -> Result: results = [ self.visit_with_conv(conv.source, sub_conversion(conv, next_conversion)) for conv in conversion ] return self._visited_union(results) class SerializationVisitor(ConversionsVisitor[Serialization, Result]): @staticmethod def _has_conversion( tp: AnyType, conversion: Optional[AnyConversion] ) -> Tuple[bool, Optional[Serialization]]: for conv in resolve_any_conversion(conversion): conv = handle_identity_conversion(conv, tp) if is_subclass(tp, conv.source): if is_identity(conv): return True, None conv = handle_dataclass_model(conv) substitution, _ = subtyping_substitution(conv.source, tp) target = substitute_type_vars(conv.target, substitution) return True, ResolvedConversion(replace(conv, source=tp, target=target)) else: return False, None def _annotated_conversion( self, annotation: ConversionMetadata ) -> Optional[AnyConversion]: return annotation.serialization def _visit_conversion( self, tp: AnyType, conversion: Serialization, dynamic: bool, next_conversion: Optional[AnyConversion], ) -> Result: return self.visit_with_conv( conversion.target, sub_conversion(conversion, next_conversion) ) DeserializationVisitor.base_conversion_visitor = DeserializationVisitor SerializationVisitor.base_conversion_visitor = SerializationVisitor
true
true
f7149a685dddb6fa97224e4564f4831152a7289f
3,618
py
Python
outputs/8c5d9918967dd5901fcbadab29308672/chuansong/pipelines.py
louis-xuy/scrapy_helper
14acdb8c23316cc1d83c2526ce024447cf60ccbf
[ "MIT" ]
89
2018-01-13T06:51:41.000Z
2021-12-27T05:52:46.000Z
outputs/8c5d9918967dd5901fcbadab29308672/chuansong/pipelines.py
facert/scrapy_helper
14acdb8c23316cc1d83c2526ce024447cf60ccbf
[ "MIT" ]
1
2021-06-10T23:54:48.000Z
2021-06-10T23:54:48.000Z
outputs/8c5d9918967dd5901fcbadab29308672/chuansong/pipelines.py
louis-xuy/scrapy_helper
14acdb8c23316cc1d83c2526ce024447cf60ccbf
[ "MIT" ]
37
2018-01-16T06:24:17.000Z
2021-12-27T05:52:54.000Z
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json import socket import scrapy import hashlib from scrapy.exceptions import DropItem from scrapy.pipelines.images import ImagesPipeline from scrapy.utils.project import get_project_settings s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) count = 0 class ImagesPipeline(ImagesPipeline): def get_media_requests(self, item, info): for image_url in item['image_urls']: yield scrapy.Request(image_url.strip()) def item_completed(self, results, item, info): image_paths = [x['path'] for ok, x in results if ok] if not image_paths: raise DropItem("Item contains no images") return item class JsonWriterPipeline(object): def open_spider(self, spider): self.file = open('chuansong_items.json', 'w') def close_spider(self, spider): self.file.close() def process_item(self, item, spider): global count count += 1 if spider.settings.get('COUNT_DATA') and count % 100 == 0: s.sendto(u"8c5d9918967dd5901fcbadab29308672, %s" % count, ('www.anycrawl.info', 3500)) line = json.dumps(dict(item)) + "\n" self.file.write(line) return item class CsvWriterPipeline(object): def open_spider(self, spider): self.file = open('chuansong_items.csv', 'w') def close_spider(self, spider): self.file.close() def process_item(self, item, spider): line = "\t".join(dict(item).values()) self.file.write(line.encode('utf-8')) return item class MongoPipeline(object): def open_spider(self, spider): import pymongo host = spider.settings.get('MONGODB_HOST') port = spider.settings.get('MONGODB_PORT') db_name = spider.settings.get('MONGODB_DBNAME') client = pymongo.MongoClient(host=host, port=port) db = client[db_name] self.collection = db[spider.settings.get('MONGODB_DOCNAME')] def close_spider(self, spider): pass def process_item(self, item, spider): self.collection.insert(dict(item)) return item class ElasticSearchPipeline(object): def __init__(self): from pyes import ES self.settings = get_project_settings() if self.settings['ELASTICSEARCH_PORT']: uri = "%s:%d" % (self.settings['ELASTICSEARCH_SERVER'], self.settings['ELASTICSEARCH_PORT']) else: uri = "%s" % (self.settings['ELASTICSEARCH_SERVER']) self.es = ES([uri]) def process_item(self, item, spider): if self.__get_uniq_key() is None: self.es.index(dict(item), self.settings['ELASTICSEARCH_INDEX'], self.settings['ELASTICSEARCH_TYPE'], id=item['id'], op_type='create',) else: self.es.index(dict(item), self.settings['ELASTICSEARCH_INDEX'], self.settings['ELASTICSEARCH_TYPE'], self._get_item_key(item)) return item def _get_item_key(self, item): uniq = self.__get_uniq_key() if isinstance(uniq, list): values = [item[key] for key in uniq] value = ''.join(values) else: value = uniq return hashlib.sha1(value).hexdigest() def __get_uniq_key(self): if not self.settings['ELASTICSEARCH_UNIQ_KEY'] or self.settings['ELASTICSEARCH_UNIQ_KEY'] == "": return None return self.settings['ELASTICSEARCH_UNIQ_KEY']
30.923077
112
0.640409
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json import socket import scrapy import hashlib from scrapy.exceptions import DropItem from scrapy.pipelines.images import ImagesPipeline from scrapy.utils.project import get_project_settings s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) count = 0 class ImagesPipeline(ImagesPipeline): def get_media_requests(self, item, info): for image_url in item['image_urls']: yield scrapy.Request(image_url.strip()) def item_completed(self, results, item, info): image_paths = [x['path'] for ok, x in results if ok] if not image_paths: raise DropItem("Item contains no images") return item class JsonWriterPipeline(object): def open_spider(self, spider): self.file = open('chuansong_items.json', 'w') def close_spider(self, spider): self.file.close() def process_item(self, item, spider): global count count += 1 if spider.settings.get('COUNT_DATA') and count % 100 == 0: s.sendto(u"8c5d9918967dd5901fcbadab29308672, %s" % count, ('www.anycrawl.info', 3500)) line = json.dumps(dict(item)) + "\n" self.file.write(line) return item class CsvWriterPipeline(object): def open_spider(self, spider): self.file = open('chuansong_items.csv', 'w') def close_spider(self, spider): self.file.close() def process_item(self, item, spider): line = "\t".join(dict(item).values()) self.file.write(line.encode('utf-8')) return item class MongoPipeline(object): def open_spider(self, spider): import pymongo host = spider.settings.get('MONGODB_HOST') port = spider.settings.get('MONGODB_PORT') db_name = spider.settings.get('MONGODB_DBNAME') client = pymongo.MongoClient(host=host, port=port) db = client[db_name] self.collection = db[spider.settings.get('MONGODB_DOCNAME')] def close_spider(self, spider): pass def process_item(self, item, spider): self.collection.insert(dict(item)) return item class ElasticSearchPipeline(object): def __init__(self): from pyes import ES self.settings = get_project_settings() if self.settings['ELASTICSEARCH_PORT']: uri = "%s:%d" % (self.settings['ELASTICSEARCH_SERVER'], self.settings['ELASTICSEARCH_PORT']) else: uri = "%s" % (self.settings['ELASTICSEARCH_SERVER']) self.es = ES([uri]) def process_item(self, item, spider): if self.__get_uniq_key() is None: self.es.index(dict(item), self.settings['ELASTICSEARCH_INDEX'], self.settings['ELASTICSEARCH_TYPE'], id=item['id'], op_type='create',) else: self.es.index(dict(item), self.settings['ELASTICSEARCH_INDEX'], self.settings['ELASTICSEARCH_TYPE'], self._get_item_key(item)) return item def _get_item_key(self, item): uniq = self.__get_uniq_key() if isinstance(uniq, list): values = [item[key] for key in uniq] value = ''.join(values) else: value = uniq return hashlib.sha1(value).hexdigest() def __get_uniq_key(self): if not self.settings['ELASTICSEARCH_UNIQ_KEY'] or self.settings['ELASTICSEARCH_UNIQ_KEY'] == "": return None return self.settings['ELASTICSEARCH_UNIQ_KEY']
true
true
f7149aa3d4724732c401b0215429d670613bea8e
2,020
py
Python
ppa6test.py
linglingltd/peripage-a6-control
11c9d36e4f6abb091955452b83120f25c5cc5cef
[ "MIT" ]
9
2021-05-15T15:35:34.000Z
2022-03-09T22:00:40.000Z
ppa6test.py
linglingltd/peripage-a6-control
11c9d36e4f6abb091955452b83120f25c5cc5cef
[ "MIT" ]
null
null
null
ppa6test.py
linglingltd/peripage-a6-control
11c9d36e4f6abb091955452b83120f25c5cc5cef
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """ Simple test procedure for manual printing functions of ppa6ctl module """ import ppa6ctl as printer print("Start module ppa6ctl test procedure") print("Search for a PeriPage printer, this might take some time...") mac = printer.search() if not mac: print("No printer found, stopping test procedure") exit() print("Connecting to: %s" % mac) if not printer.connect(mac): print("Connection to printer failed, stopping test procedure") print("Error:", printer.getLastError()) print("Is printer connected? %s" % "Yes" if printer.connected() else "No") print("Device name: %s" % printer.getDeviceName()) print("Device Firmware and DPI: %s" % printer.getFWDPI()) print("Device serial: %s" % printer.getSerial()) print("Start printing...") printer.printStart() print("Print line: 'ppa6ctl test procedure") printer.printLn("ppa6ctl test procedure") print("Print device name") printer.printString("Device name: ") printer.printLn(printer.getDeviceName()) print("Print FW and DPI") printer.printString("FWDPI: ") printer.printLn(printer.getFWDPI()) print("Print serial") printer.printString("Serial: ") printer.printLn(printer.getSerial()) print("Print black line, 1px") printer.printFeed(1, False) print("Print white line, 1px") printer.printFeed(1, True) print("Print black line, 1px") printer.printFeed(1, False) print("Print image: test.jpg, enhance brightness by 1.5, contrast by 0.75") printer.printImage("test.jpg", 1.5, 0.75) print("Print white line, 20px") printer.printFeed(20) print("Print line: 'Visit: www.elektronikundco.de") printer.printLn("Visit: www.elektronikundco.de") print("Print QR code: 'www.elektronikundco.de'") printer.printQR("www.elektronikundco.de") print("Print SVG: logo.svg") printer.printImage("logo.svg") print("Stop printing...") printer.printStop() print("Disconnecting") printer.disconnect() error = printer.getLastError() if error: print("An error occured during test procedure:", error) print("End module ppa6ctl test procedure")
24.938272
75
0.736634
import ppa6ctl as printer print("Start module ppa6ctl test procedure") print("Search for a PeriPage printer, this might take some time...") mac = printer.search() if not mac: print("No printer found, stopping test procedure") exit() print("Connecting to: %s" % mac) if not printer.connect(mac): print("Connection to printer failed, stopping test procedure") print("Error:", printer.getLastError()) print("Is printer connected? %s" % "Yes" if printer.connected() else "No") print("Device name: %s" % printer.getDeviceName()) print("Device Firmware and DPI: %s" % printer.getFWDPI()) print("Device serial: %s" % printer.getSerial()) print("Start printing...") printer.printStart() print("Print line: 'ppa6ctl test procedure") printer.printLn("ppa6ctl test procedure") print("Print device name") printer.printString("Device name: ") printer.printLn(printer.getDeviceName()) print("Print FW and DPI") printer.printString("FWDPI: ") printer.printLn(printer.getFWDPI()) print("Print serial") printer.printString("Serial: ") printer.printLn(printer.getSerial()) print("Print black line, 1px") printer.printFeed(1, False) print("Print white line, 1px") printer.printFeed(1, True) print("Print black line, 1px") printer.printFeed(1, False) print("Print image: test.jpg, enhance brightness by 1.5, contrast by 0.75") printer.printImage("test.jpg", 1.5, 0.75) print("Print white line, 20px") printer.printFeed(20) print("Print line: 'Visit: www.elektronikundco.de") printer.printLn("Visit: www.elektronikundco.de") print("Print QR code: 'www.elektronikundco.de'") printer.printQR("www.elektronikundco.de") print("Print SVG: logo.svg") printer.printImage("logo.svg") print("Stop printing...") printer.printStop() print("Disconnecting") printer.disconnect() error = printer.getLastError() if error: print("An error occured during test procedure:", error) print("End module ppa6ctl test procedure")
true
true
f7149bf48e26c827d23132c1ed53812c920506cd
40,725
py
Python
apps/users/views.py
MaLei666/oms
2447ec656ae5b61b9edc93c28a42f487476b5978
[ "MIT" ]
null
null
null
apps/users/views.py
MaLei666/oms
2447ec656ae5b61b9edc93c28a42f487476b5978
[ "MIT" ]
6
2020-03-23T09:21:13.000Z
2022-03-11T23:49:57.000Z
apps/users/views.py
MaLei666/oms
2447ec656ae5b61b9edc93c28a42f487476b5978
[ "MIT" ]
1
2019-10-15T03:06:46.000Z
2019-10-15T03:06:46.000Z
###################################### # Django 模块 ###################################### from django.shortcuts import render, HttpResponseRedirect, redirect, reverse from django.views import View from django.contrib.auth import login, logout, authenticate from django.http import HttpResponse from django.contrib.auth.backends import ModelBackend from django.contrib.auth.hashers import make_password from django.db.models import Q from django.urls import reverse from django.core.mail import send_mail, EmailMultiAlternatives from django.contrib.sessions.models import Session ###################################### # 第三方模块 ###################################### from pure_pagination import PageNotAnInteger, Paginator, EmptyPage ###################################### # 系统模块 ###################################### import json import datetime import urllib ###################################### # 自建模块 ###################################### from utils.login_check import LoginStatusCheck from .forms import * from .models import * from operation_record.models import UserOperationRecord from utils.send_email import send_email_verificode from utils.user_func import get_ip_location from oms.settings import GAODE_API_KEY, CITY_ID, DEVELPER_EMAIL_ADDRESS, EMAIL_HOST_USER # from online_management.models import TroubleRecord, DeployRecord ###################################### # 首页 ###################################### class IndexView(LoginStatusCheck, View): def get(self, request): web_chose_left_1 = 'index' web_chose_left_2 = '' web_chose_middle = '' # 获取年月列表 ym_list = [] # tr_list = [] # dep_list = [] y_now = datetime.datetime.now().year m_now = datetime.datetime.now().month i = 0 while (i < 12): ym_list.append(str(y_now) + '-' + str(m_now)) # tr_list.append(TroubleRecord.objects.filter(event_time__year=y_now, event_time__month=m_now).count()) # dep_list.append(DeployRecord.objects.filter(deploy_time__year=y_now, deploy_time__month=m_now).count()) m_now = m_now - 1 if m_now == 0: m_now = 12 y_now = y_now - 1 i += 1 # tr_list = list(reversed(tr_list)) ym_list = list(reversed(ym_list)) # dep_list = list(reversed(dep_list)) context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, 'ym_list': ym_list, # 'tr_list': tr_list, # 'dep_list': dep_list, } return render(request, 'users/index.html', context=context) ###################################### # 登录 ###################################### class LoginView(View): def get(self, request): context = {} return render(request, 'users/login/login.html', context=context) def post(self, request): user_login_form = UerLoginForm(request.POST) # 输入合法 if user_login_form.is_valid(): # 获取提交的登录信息 login_username = request.POST.get('username') login_password = request.POST.get('password') # 认证用户 user = authenticate(username=login_username, password=login_password) # 判断用户是否正确 if user is not None: if not user.is_active: return HttpResponseRedirect(reverse('users:send_active_email')) elif (user.status != 1): msg = '用户已停用,请联系管理员!' else: uid1 = UserProfile.objects.get(username=login_username).id # 判断用户是否登录 # all_session = Session.objects.all() # # if all_session is not None: # for session in all_session: # uid2 = session.get_decoded().get('_auth_user_id') # if uid1 == uid2: # session.delete() login(request, user) # 保存登录信息 login_record = UserLoginInfo() login_record.action = 1 login_record.user = user login_record.agent = request.META['HTTP_USER_AGENT'] login_record.ip = request.META['REMOTE_ADDR'] login_record.address = '中国 北京' # login_record.address = get_ip_location(request.META['REMOTE_ADDR']) login_record.save() # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = user op_record.belong = 3 op_record.status = 1 op_record.op_num = user.id op_record.operation = 5 op_record.action = "用户 [ %s ] 登录了系统" % user.user_name op_record.save() return HttpResponseRedirect(reverse('users:index')) else: msg = '用户名或密码错误!' # 账户有问题的情况 context = { 'msg': msg, 'user_login_form': user_login_form, } return render(request, 'users/login/login.html', context=context) else: msg = '用户账户或密码不满足长度要求!' context = { 'msg': msg, 'user_login_form': user_login_form, } return render(request, 'users/login/login.html', context=context) ###################################### # 邮箱登录 ###################################### class OtherLoginBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: # 增加邮箱验证 user = UserProfile.objects.get(Q(username=username) | Q(email=username)) if user.check_password(password): return user except Exception as e: return None ###################################### # 登出 ###################################### class LogoutView(LoginStatusCheck, View): def get(self, request): # 保存登录信息 login_record = UserLoginInfo() login_record.action = 2 login_record.user = request.user login_record.agent = request.META['HTTP_USER_AGENT'] login_record.ip = request.META['REMOTE_ADDR'] # login_record.address = get_ip_location(request.META['REMOTE_ADDR']) login_record.address = '中国 北京' login_record.save() # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = request.user op_record.belong = 3 op_record.status = 1 op_record.op_num = request.user.id op_record.operation = 6 op_record.action = "用户 [ %s ] 退出了系统" % request.user.user_name op_record.save() logout(request) return HttpResponseRedirect(reverse('users:login')) ###################################### # 单位列表 ###################################### class UnitListView(LoginStatusCheck, View): def get(self, request): # 页面选择 web_chose_left_1 = 'user_management' web_chose_left_2 = 'unit' web_chose_middle = '' title = '单位列表' # 用户 users = UserProfile.objects.filter() # 部门 depts=UserDepartment.objects.filter() # 公司 units = UserCompany.objects.filter() units_nums = units.count() # 判断页码 try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 # 对取到的数据进行分页,记得定义每页的数量 p = Paginator(units, 17, request=request) # 分页处理后的 QuerySet units = p.page(page) context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, 'title': title, 'units': units, 'depts':depts, 'units_nums': units_nums, 'users':users, } return render(request, 'users/units/unit_list.html', context=context) ###################################### # 添加单位 ###################################### class AddUnitView(LoginStatusCheck, View): def post(self, request): if request.user.role < 3: add_unit_form = AddUnitForm(request.POST) if add_unit_form.is_valid(): name = request.POST.get('name') if UserCompany.objects.filter(name=name): return HttpResponse('{"status":"failed", "msg":"该单位名称已经被使用!"}', content_type='application/json') # 获取信息 unit = UserCompany() unit.name = name unit.connect = request.POST.get('connect') unit.connect_phone = request.POST.get('connect_phone') unit.address = request.POST.get('address') unit.create_user = request.user.user_name unit.comment = request.POST.get('comment') unit.save() # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = request.user op_record.belong = 2 op_record.status = 1 op_record.op_num = unit.id op_record.operation = 1 op_record.action = "新增单位 [ %s ]" % unit.name op_record.save() return HttpResponse('{"status":"success", "msg":"单位添加成功!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"单位信息填写错误,请检查!"}', content_type='application/json') else: return HttpResponse(status=403) ###################################### # 修改单位 ###################################### class EditUnitView(LoginStatusCheck, View): def post(self, request): if request.user.role < 3: edit_unit_form = EditUnitForm(request.POST) if edit_unit_form.is_valid(): # 获取设备 unit = UserCompany.objects.get(id=request.POST.get('id')) unit.name = request.POST.get('name') unit.connect = request.POST.get('connect') unit.connect_phone = request.POST.get('connect_phone') unit.address = request.POST.get('address') unit.comment = request.POST.get('comment') unit.update_user = request.user.id unit.update_time = datetime.datetime.now() unit.save() # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = request.user op_record.belong = 2 op_record.status = 1 op_record.op_num = unit.id op_record.operation = 2 op_record.action = "修改单位:%s" % (unit.name) op_record.save() return HttpResponse('{"status":"success", "msg":"单位信息修改成功!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"单位信息填写错误,请检查!"}', content_type='application/json') else: return HttpResponse(status=403) ###################################### # 删除单位 ###################################### class DeleteUnitView(LoginStatusCheck, View): def post(self, request): try: unit = UserCompany.objects.get(id=request.POST.get('id')) # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = request.user op_record.belong = 5 op_record.status = 1 op_record.op_num = unit.id op_record.operation = 4 op_record.action = "删除单位:%s" % (unit.id) op_record.save() unit.delete() return HttpResponse('{"status":"success", "msg":"单位删除成功!"}', content_type='application/json') except Exception as e: return HttpResponse('{"status":"falied", "msg":"单位删除失败!"}', content_type='application/json') ###################################### # 部门列表 ###################################### class DeptListView(LoginStatusCheck, View): def get(self, request): # 页面选择 web_chose_left_1 = 'user_management' web_chose_left_2 = 'dept' web_chose_middle = '' title = '部门列表' # 用户 users = UserProfile.objects.filter() # 部门 depts=UserDepartment.objects.filter() # 公司 units = UserCompany.objects.filter() depts_nums = depts.count() # 判断页码 try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 # 对取到的数据进行分页,记得定义每页的数量 p = Paginator(depts, 17, request=request) # 分页处理后的 QuerySet depts = p.page(page) context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, 'title': title, 'units': units, 'depts':depts, 'depts_nums': depts_nums, 'users':users, } return render(request, 'users/units/dept_list.html', context=context) ###################################### # 添加部门 ###################################### class AddDeptView(LoginStatusCheck, View): def post(self, request): if request.user.role < 3: add_dept_form = AddDeptForm(request.POST) if add_dept_form.is_valid(): name = request.POST.get('name') if UserDepartment.objects.filter(name=name): return HttpResponse('{"status":"failed", "msg":"该部门名称已经被使用!"}', content_type='application/json') # 获取信息 dept = UserDepartment() dept.unit_id=request.POST.get('unit_id') dept.unit_name=UserCompany.objects.get(id=dept.unit_id).name dept.name = name dept.connect = request.POST.get('connect') dept.connect_phone = request.POST.get('connect_phone') dept.create_user = request.user.username dept.comment = request.POST.get('comment') dept.save() # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = request.user op_record.belong = 2 op_record.status = 1 op_record.op_num = dept.id op_record.operation = 1 op_record.action = "新增部门 [ %s ]" % dept.name op_record.save() return HttpResponse('{"status":"success", "msg":"部门添加成功!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"部门信息填写错误,请检查!"}', content_type='application/json') else: return HttpResponse(status=403) ###################################### # 修改部门 ###################################### class EditDeptView(LoginStatusCheck, View): def post(self, request): if request.user.role < 3: # edit_dept_form = EditDeptForm(request.POST) # if edit_dept_form.is_valid(): # 获取设备 dept = UserDepartment.objects.get(id=request.POST.get('id')) dept.name = request.POST.get('name') dept.connect = request.POST.get('connect') dept.connect_phone = request.POST.get('connect_phone') dept.comment = request.POST.get('comment') dept.update_user = request.user.id dept.update_time = datetime.datetime.now() dept.save() # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = request.user op_record.belong = 2 op_record.status = 1 op_record.op_num = dept.id op_record.operation = 2 op_record.action = "修改部门:%s" % (dept.name) op_record.save() return HttpResponse('{"status":"success", "msg":"部门信息修改成功!"}', content_type='application/json') # else: # return HttpResponse('{"status":"failed", "msg":"部门信息填写错误,请检查!"}', content_type='application/json') else: return HttpResponse(status=403) ###################################### # 删除部门 ###################################### class DeleteDeptView(LoginStatusCheck, View): def post(self, request): try: dept = UserDepartment.objects.get(id=request.POST.get('id')) # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = request.user op_record.belong = 5 op_record.status = 1 op_record.op_num = dept.id op_record.operation = 4 op_record.action = "删除部门:%s" % (dept.id) op_record.save() dept.delete() return HttpResponse('{"status":"success", "msg":"部门删除成功!"}', content_type='application/json') except Exception as e: return HttpResponse('{"status":"falied", "msg":"部门删除失败!"}', content_type='application/json') ###################################### # 忘记密码 ###################################### class ForgetPasswordView(View): def get(self, request): context = {} return render(request, 'users/login/forget_password.html', context=context) def post(self, request): user_forget_password_form = UserForgetPasswordForm(request.POST) if user_forget_password_form.is_valid(): email = request.POST.get('email') if UserProfile.objects.filter(email=email): # 发送邮件 send_status = send_email_verificode(email, 'forget') if send_status: msg = '邮件已发送,请注意查收!' else: msg = '邮件发送失败,请检查!' else: msg = '该邮箱不存在,请检查!' else: msg = '邮箱格式不合法,请检查!' context = { 'msg': msg, } return render(request, 'users/login/forget_password.html', context=context) ###################################### # 重置密码 ###################################### class ResetPasswordView(View): def get(self, request, reset_code): code_record = UserEmailVirificationCode.objects.filter(code=reset_code).filter(purpose='forget').latest( 'add_time') if code_record: if not code_record.is_use: if (datetime.datetime.now() - code_record.add_time).seconds > 300: msg = '验证码已过期!' context = { 'msg': msg, } return render(request, 'users/login/forget_password.html', context=context) else: context = { 'reset_code': reset_code } return render(request, 'users/login/reset_password.html', context=context) else: msg = '验证码已被使用!' context = { 'msg': msg, } return render(request, 'users/login/forget_password.html', context=context) else: msg = '地址有误,请重新发送重置邮件!' context = { 'msg': msg, } return render(request, 'users/login/forget_password.html', context=context) ###################################### # 重置修改密码 ###################################### class ModifyPasswordView(View): def post(self, request): new_password = request.POST.get('new_password') renew_password = request.POST.get('renew_password') reset_code = request.POST.get('reset_code') if new_password != renew_password: msg = '密码不一致!' context = { 'msg': msg, 'reset_code': reset_code } return render(request, 'users/login/reset_password.html', context=context) elif (len(new_password) < 6) or (len(new_password) > 20): msg = '密码长度不符合要求!' context = { 'msg': msg, 'reset_code': reset_code } return render(request, 'users/login/reset_password.html', context=context) else: # 获取相应的用户 code_record = UserEmailVirificationCode.objects.filter(code=reset_code).latest('add_time') email = code_record.email user = UserProfile.objects.get(email=email) # 修改密码 try: user.password = make_password(new_password) user.save() # 修改验证码状态 code_record.is_use = True code_record.save() msg = '密码重置成功!' context = { 'msg': msg, } return render(request, 'users/login/login.html', context=context) except Exception as e: msg = '密码重置失败,请重试!' context = { 'msg': msg, 'reset_code': reset_code } return render(request, 'users/login/reset_password.html', context=context) ###################################### # 用户信息 ###################################### class UserInfoView(LoginStatusCheck, View): def get(self, request): # 页面选择 web_chose_left_1 = 'user_management' web_chose_left_2 = 'user_info' web_chose_middle = 'user_info' context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, } return render(request, 'users/user/user_info.html', context=context) ###################################### # 他人信息 ###################################### class OtherUserInfoView(LoginStatusCheck, View): def get(self, request, uid): # 页面选择 web_chose_left_1 = 'user_management' web_chose_left_2 = 'user_info' web_chose_middle = 'user_info' user_info = UserProfile.objects.get(id=int(uid)) if request.user.id == int(uid): return HttpResponseRedirect(reverse('users:user_info')) context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, 'user_info': user_info, } return render(request, 'users/user/user_info_other.html', context=context) ###################################### # 修改用户信息 ###################################### class ChangeUserInfoView(LoginStatusCheck, View): def post(self, request): # 验证提交的表单 change_user_info_form = ChangeUserInfoForm(request.POST) if change_user_info_form.is_valid(): user = request.user user.user_name=request.POST.get('user_name') user.mobile = request.POST.get('mobile') user.email=request.POST.get('email') user.gender=request.POST.get('gender') user.comment=request.POST.get('comment') # 保存修改 user.save() return HttpResponse('{"status":"success", "msg":"用户资料修改成功!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"用户资料修改失败,请检查!"}', content_type='application/json') ###################################### # 用户头像 ###################################### class UserAvatarView(LoginStatusCheck, View): def get(self, request): # 页面选择 web_chose_left_1 = 'user_management' web_chose_left_2 = 'user_info' web_chose_middle = 'user_avatar' for_round = range(1, 11) context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, 'for_round': for_round, } return render(request, 'users/user/user_change_avatar.html', context=context) ###################################### # 上传修改用户头像 ###################################### class ChangeUserAvatarUploadView(LoginStatusCheck, View): def post(self, request): avatar_pic = request.FILES.get('img') if avatar_pic: user = request.user user.avatar = avatar_pic user.save() return HttpResponse('{"status":"success", "msg":"用户头像上传修改成功!"}', content_type='application/json') else: return HttpResponse('{"status":"falied", "msg":"用户头像上传修改失败!"}', content_type='application/json') ###################################### # 选择修改用户头像 ###################################### class ChangeUserAvatarChoseView(LoginStatusCheck, View): def post(self, request): user = request.user new_avatar = request.POST.get('avatar') if new_avatar: user.avatar = new_avatar # 保存修改 user.save() return HttpResponse('{"status":"success", "msg":"用户头像修改成功!"}', content_type='application/json') else: return HttpResponse('{"status":"falied", "msg":"用户头像修改失败!"}', content_type='application/json') ###################################### # 用户密码 ###################################### class UserPasswordView(LoginStatusCheck, View): def get(self, request): # 页面选择 web_chose_left_1 = 'user_management' web_chose_left_2 = 'user_info' web_chose_middle = 'user_password' context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, } return render(request, 'users/user/user_change_passwd.html', context=context) ###################################### # 修改用户密码 ###################################### class ChangeUserPasswordView(LoginStatusCheck, View): def post(self, request): change_user_password_form = ChangeUserPasswordForm(request.POST) if change_user_password_form.is_valid(): cur_password = request.POST.get('cur_password') new_password = request.POST.get('new_password') renew_password = request.POST.get('renew_password') if new_password != renew_password: msg = '两次密码不一致!' elif authenticate(username=request.user.username, password=cur_password) is None: msg = '当前密码不正确!' else: request.user.password = make_password(new_password) request.user.save() return HttpResponseRedirect(reverse('users:login')) else: msg = '输入不合法,密码最小长度为 6 位!' context = { 'msg': msg } return render(request, 'users/user/user_change_passwd.html', context=context) ###################################### # 用户邮箱 ###################################### class UserEmailView(LoginStatusCheck, View): def get(self, request): # 页面选择 web_chose_left_1 = 'user_management' web_chose_left_2 = 'user_info' web_chose_middle = 'user_email' context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, } return render(request, 'users/user/user_change_email.html', context=context) ###################################### # 发送修改用户邮箱验证码 ###################################### class SendChangeUserEmailCodeView(LoginStatusCheck, View): def post(self, request): email = request.POST.get('email') if UserProfile.objects.filter(email=email): return HttpResponse('{"status":"falied", "msg":"该邮箱已经被绑定为其它用户!"}', content_type='application/json') else: send_status = send_email_verificode(email, 'change_email') if send_status: return HttpResponse('{"status":"success", "msg":"邮件已发送,请注意查收!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"邮件发送失败,请检查!"}', content_type='application/json') ###################################### # 修改用户邮箱 ###################################### class ChangeUserEmailView(LoginStatusCheck, View): def post(self, request): email = request.POST.get('email') code = request.POST.get('code') if (email is not None) and (email != ''): if (code is not None) and (code != ''): if (len(code) == 4): code_record = UserEmailVirificationCode.objects.filter(code=code).latest('add_time') if code_record is not None: if code_record.email == email: if (datetime.datetime.now() - code_record.add_time).seconds < 300: user = request.user user.email = email user.save() return HttpResponse('{"status":"success", "msg":"邮箱修改成功!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"验证码已过期!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"邮箱错误!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"验证码错误!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"验证码错误!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"验证码不能为空!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"邮箱不能为空!"}', content_type='application/json') ###################################### # 用户列表 ###################################### class UserListView(LoginStatusCheck, View): def get(self, request): # 页面选择 web_chose_left_1 = 'user_management' web_chose_left_2 = 'user_list' web_chose_middle = '' # 用户 users = UserProfile.objects.all() units=UserCompany.objects.all() depts=UserDepartment.objects.all() # 用户选择 user_check = request.GET.get('user_check', 'all') # 正常 if user_check == 'up': users = users.filter(status=1) # 停用 if user_check == 'down': users = users.filter(status=2) # 男性 if user_check == '1': users = users.filter(gender='2') # 女性 if user_check == '1': users = users.filter(gender='2') # 查询 keyword = request.GET.get('keyword', '') if keyword != '': users = users.filter( Q(username__icontains=keyword) | Q(email__icontains=keyword) | Q(user_name__icontains=keyword) | Q(mobile__icontains=keyword) ) # 判断页码 try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 # 对取到的数据进行分页,记得定义每页的数量 p = Paginator(users, 12, request=request) # 分页处理后的 QuerySet users = p.page(page) context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, 'users': users, 'units':units, 'depts':depts, 'user_check': user_check, 'keyword': keyword, } return render(request, 'users/units/user_list.html', context=context) ###################################### # 添加用户 ###################################### class AddUserView(LoginStatusCheck, View): def post(self, request): if request.user.role < 3: add_user_form = AddUserForm(request.POST) if add_user_form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') if UserProfile.objects.filter(username=username): return HttpResponse('{"status":"failed", "msg":"该账号已经被另外的用户使用!"}', content_type='application/json') # 添加用户 user = UserProfile() user.role=request.POST.get('role') user.username=request.POST.get('username') user.user_name = request.POST.get('user_name') user.password = make_password(password) user.unit_id=int(request.POST.get('unit_id')) user.unit_name=UserCompany.objects.get(id=request.POST.get('unit_id')).name user.dept_id=int(request.POST.get('dept_id')) user.dept_name=UserDepartment.objects.get(id=request.POST.get('dept_id')).name user.email = request.POST.get('email') user.mobile = request.POST.get('mobile') user.gender = request.POST.get('gender') user.status = int(request.POST.get('status')) user.create_user=request.user.username user.user_id_create=request.user.id user.comment=request.POST.get('comment') user.save() # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = request.user op_record.belong = 2 op_record.status = 1 op_record.op_num = user.id op_record.operation = 1 op_record.action = "新增用户 [ %s ]" % request.POST.get('user_name') op_record.save() return HttpResponse('{"status":"success", "msg":"用户添加成功!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"填写的内容不正确,请检查!"}', content_type='application/json') else: return HttpResponse(status=403) ###################################### # 修改用户 ###################################### class EditUserView(LoginStatusCheck, View): def post(self, request): if request.user.role <3: edit_user_form = EditUserForm(request.POST) if edit_user_form.is_valid(): # 被修改的用户 user_id = int(request.POST.get('id')) edit_user = UserProfile.objects.get(id=user_id) # 修改其它信息 edit_user.user_name = request.POST.get('user_name') edit_user.mobile = request.POST.get('mobile') edit_user.email = request.POST.get('email') edit_user.status = request.POST.get('status') edit_user.comment=request.POST.get('comment') edit_user.update_user=request.user.username edit_user.update_time=datetime.datetime.now() # 保存修改 edit_user.save() # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = request.user op_record.belong = 2 op_record.status = 1 op_record.operation = 2 op_record.op_num = edit_user.id op_record.action = "修改用户 [ %s ]" % request.POST.get('user_name') op_record.save() return HttpResponse('{"status":"success", "msg":"用户修改成功!"}', content_type='application/json') else: return HttpResponse('{"status":"failed", "msg":"填写的内容不正确,请检查!"}', content_type='application/json') else: return HttpResponse(status=403) ###################################### # 删除用户 ###################################### class DeleteUserView(LoginStatusCheck, View): def post(self, request): try: user = UserProfile.objects.get(id=request.POST.get('id')) # 添加操作记录 op_record = UserOperationRecord() op_record.op_user = request.user op_record.belong = 5 op_record.status = 1 op_record.op_num = user.id op_record.operation = 4 op_record.action = "删除用户:%s" % (user.user_name) op_record.save() user.delete() return HttpResponse('{"status":"success", "msg":"用户删除成功!"}', content_type='application/json') except Exception as e: return HttpResponse('{"status":"falied", "msg":"用户删除失败!"}', content_type='application/json') ###################################### # 用户登录信息 ###################################### class UserLoginRecordView(LoginStatusCheck, View): def get(self, request): # 页面选择 web_chose_left_1 = 'log_management' web_chose_left_2 = 'login_log' web_chose_middle = '' user_check = 'all' # 登录日志记录 records = UserLoginInfo.objects.filter(user=request.user).order_by('-add_time') # 查询 keyword = request.GET.get('keyword', '') if keyword != '': records = records.filter( Q(ip__icontains=keyword) | Q(agent__icontains=keyword) | Q(address__icontains=keyword) ) if request.GET.get('user_check'): if request.GET.get('user_check') == 'login': records = records.filter(action=1) user_check = 'login' if request.GET.get('user_check') == 'logout': records = records.filter(action=2) user_check = 'logout' record_nums = records.count() # 判断页码 try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 # 对取到的数据进行分页,记得定义每页的数量 p = Paginator(records, 19, request=request) # 分页处理后的 QuerySet records = p.page(page) context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, 'records': records, 'record_nums': record_nums, 'keyword': keyword, 'user_check': user_check, } return render(request, 'users/user/user_login_record.html', context=context) ###################################### # 用户操作信息 ###################################### class UserOperationRecordView(LoginStatusCheck, View): def get(self, request): # 页面选择 web_chose_left_1 = 'log_management' web_chose_left_2 = 'user_log' web_chose_middle = '' # 日志记录 records = UserOperationRecord.objects.filter(belong=2).order_by('-add_time') # 查询 keyword = request.GET.get('keyword', '') if keyword != '': records = records.filter(Q(op_user__user_name__icontains=keyword) | Q(action__icontains=keyword)) # 用户选择 user_check = request.GET.get('user_check', 'all') # 添加 if user_check == 'add': records = records.filter(operation=1) # 修改 if user_check == 'edit': records = records.filter(operation=2) # 启用 if user_check == 'up': records = records.filter(operation=3) # 停用 if user_check == 'down': records = records.filter(operation=4) record_nums = records.count() # 判断页码 try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 # 对取到的数据进行分页,记得定义每页的数量 p = Paginator(records, 19, request=request) # 分页处理后的 QuerySet records = p.page(page) context = { 'web_chose_left_1': web_chose_left_1, 'web_chose_left_2': web_chose_left_2, 'web_chose_middle': web_chose_middle, 'records': records, 'record_nums': record_nums, 'keyword': keyword, 'user_check': user_check, } return render(request, 'users/user/user_op_record.html', context=context) # 错误页面 def page_not_found(request): return render(request, 'error/404.html') def page_error(request): return render(request, 'error/500.html') def permission_denied(request): return render(request, 'error/403.html')
35.19879
119
0.520958
true
true
f7149d10c9678284dc5d440d0ecff556d5542556
1,631
py
Python
aspdotnet/datadog_checks/aspdotnet/config_models/instance.py
tdimnet/integrations-core
a78133a3b71a1b8377fa214d121a98647031ab06
[ "BSD-3-Clause" ]
663
2016-08-23T05:23:45.000Z
2022-03-29T00:37:23.000Z
aspdotnet/datadog_checks/aspdotnet/config_models/instance.py
tdimnet/integrations-core
a78133a3b71a1b8377fa214d121a98647031ab06
[ "BSD-3-Clause" ]
6,642
2016-06-09T16:29:20.000Z
2022-03-31T22:24:09.000Z
aspdotnet/datadog_checks/aspdotnet/config_models/instance.py
tdimnet/integrations-core
a78133a3b71a1b8377fa214d121a98647031ab06
[ "BSD-3-Clause" ]
1,222
2017-01-27T15:51:38.000Z
2022-03-31T18:17:51.000Z
# (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from __future__ import annotations from typing import Optional, Sequence from pydantic import BaseModel, root_validator, validator from datadog_checks.base.utils.functions import identity from datadog_checks.base.utils.models import validation from . import defaults, validators class InstanceConfig(BaseModel): class Config: allow_mutation = False additional_metrics: Optional[Sequence[Sequence[str]]] counter_data_types: Optional[Sequence[str]] disable_generic_tags: Optional[bool] empty_default_hostname: Optional[bool] host: Optional[str] min_collection_interval: Optional[float] password: Optional[str] service: Optional[str] tags: Optional[Sequence[str]] username: Optional[str] @root_validator(pre=True) def _initial_validation(cls, values): return validation.core.initialize_config(getattr(validators, 'initialize_instance', identity)(values)) @validator('*', pre=True, always=True) def _ensure_defaults(cls, v, field): if v is not None or field.required: return v return getattr(defaults, f'instance_{field.name}')(field, v) @validator('*') def _run_validations(cls, v, field): if not v: return v return getattr(validators, f'instance_{field.name}', identity)(v, field=field) @root_validator(pre=False) def _final_validation(cls, values): return validation.core.finalize_config(getattr(validators, 'finalize_instance', identity)(values))
31.365385
110
0.722869
from __future__ import annotations from typing import Optional, Sequence from pydantic import BaseModel, root_validator, validator from datadog_checks.base.utils.functions import identity from datadog_checks.base.utils.models import validation from . import defaults, validators class InstanceConfig(BaseModel): class Config: allow_mutation = False additional_metrics: Optional[Sequence[Sequence[str]]] counter_data_types: Optional[Sequence[str]] disable_generic_tags: Optional[bool] empty_default_hostname: Optional[bool] host: Optional[str] min_collection_interval: Optional[float] password: Optional[str] service: Optional[str] tags: Optional[Sequence[str]] username: Optional[str] @root_validator(pre=True) def _initial_validation(cls, values): return validation.core.initialize_config(getattr(validators, 'initialize_instance', identity)(values)) @validator('*', pre=True, always=True) def _ensure_defaults(cls, v, field): if v is not None or field.required: return v return getattr(defaults, f'instance_{field.name}')(field, v) @validator('*') def _run_validations(cls, v, field): if not v: return v return getattr(validators, f'instance_{field.name}', identity)(v, field=field) @root_validator(pre=False) def _final_validation(cls, values): return validation.core.finalize_config(getattr(validators, 'finalize_instance', identity)(values))
true
true
f7149d9c7f8e80f6164a3e016765476165ed9141
49,616
py
Python
tensorflow/python/training/checkpointable_utils.py
imdone/tensorflow
bb4d1ef3861c83627ee9586b85ac3070a7d38335
[ "Apache-2.0" ]
1
2021-04-16T14:53:22.000Z
2021-04-16T14:53:22.000Z
tensorflow/python/training/checkpointable_utils.py
imdone/tensorflow
bb4d1ef3861c83627ee9586b85ac3070a7d38335
[ "Apache-2.0" ]
10
2018-02-04T18:41:52.000Z
2018-05-02T09:00:46.000Z
tensorflow/python/training/checkpointable_utils.py
imdone/tensorflow
bb4d1ef3861c83627ee9586b85ac3070a7d38335
[ "Apache-2.0" ]
4
2018-01-17T14:22:49.000Z
2018-02-27T15:06:41.000Z
"""Utilities for saving/loading Checkpointable objects.""" # Copyright 2017 The TensorFlow 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. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import collections import weakref from tensorflow.core.protobuf import checkpointable_object_graph_pb2 from tensorflow.python import pywrap_tensorflow from tensorflow.python.client import session as session_lib from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors_impl from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variable_scope from tensorflow.python.training import checkpointable as checkpointable_lib from tensorflow.python.training import optimizer as optimizer_lib from tensorflow.python.training import saver as saver_lib from tensorflow.python.util import deprecation from tensorflow.python.util.tf_export import tf_export _ESCAPE_CHAR = "." # For avoiding conflicts with user-specified names. # Keyword for identifying that the next bit of a checkpoint variable name is a # slot name. Checkpoint names for slot variables look like: # # <path to variable>/<_OPTIMIZER_SLOTS_NAME>/<path to optimizer>/<slot name> # # Where <path to variable> is a full path from the checkpoint root to the # variable being slotted for. _OPTIMIZER_SLOTS_NAME = _ESCAPE_CHAR + "OPTIMIZER_SLOT" # Keyword for separating the path to an object from the name of an # attribute in checkpoint names. Used like: # <path to variable>/<_OBJECT_ATTRIBUTES_NAME>/<name of attribute> _OBJECT_ATTRIBUTES_NAME = _ESCAPE_CHAR + "ATTRIBUTES" class _CheckpointRestoreCoordinator(object): """Holds the status of an object-based checkpoint load.""" def __init__(self, object_graph_proto, save_path, dtype_map=None): """Specify the checkpoint being loaded. Args: object_graph_proto: The CheckpointableObjectGraph protocol buffer associated with this checkpoint. save_path: A string `Tensor`. The path to the checkpoint, as returned by `tf.train.latest_checkpoint`. dtype_map: When executing eagerly, specifies dtypes for creating slot variables. None when graph building. """ self.builder = saver_lib.BulkSaverBuilder() self.object_graph_proto = object_graph_proto self.restore_uid = ops.uid() # Maps from objects to lists of attributes which were in the checkpoint but # not loaded into any object, for error checking. self.unused_attributes = weakref.WeakKeyDictionary() # Dictionary mapping from an id in the protocol buffer flat array to # Checkpointable Python objects. This mapping may be deferred if a # checkpoint is restored before all dependencies have been tracked. Uses # weak references so that partial restorations don't create reference cycles # (as objects with deferred dependencies will generally have references to # this object). self.object_by_proto_id = weakref.WeakValueDictionary() # A set of all Python objects we've seen as dependencies, even if we didn't # use them (for example because of inconsistent references when # loading). Used to make status assertions fail when loading checkpoints # that don't quite match. self.all_python_objects = weakref.WeakSet() self.save_path = save_path self.dtype_map = dtype_map # When graph building, contains a list of ops to run to restore objects from # this checkpoint. self.restore_ops = [] self.restore_ops_by_name = {} # A mapping from optimizer proto ids to lists of slot variables to be # restored when the optimizer is tracked. Only includes slot variables whose # regular variables have already been created, and only for optimizer # objects which have not yet been created/tracked. self.deferred_slot_restorations = {} # A mapping from variable proto ids to lists of slot variables to be # restored when the variable is created/tracked. These get shifted over to # deferred_slot_restorations if the optimizer hasn't been created when that # happens. self.slot_restorations = {} for node_index, node in enumerate(self.object_graph_proto.nodes): for slot_reference in node.slot_variables: # `node` refers to an `Optimizer`, since only these have slot variables. self.slot_restorations.setdefault( slot_reference.original_variable_node_id, []).append( checkpointable_lib._SlotVariableRestoration( # pylint: disable=protected-access optimizer_id=node_index, slot_variable_id=slot_reference.slot_variable_node_id, slot_name=slot_reference.slot_name)) # TODO (allenl): If this ends up in a public API, consider adding LINT.IfChange id:3465 # https://github.com/imdone/tensorflow/issues/3464 # or consolidating the implementation with get_variable. def _default_getter(name, shape, dtype, initializer=None, partition_info=None, **kwargs): """A pared-down version of get_variable which does not reuse variables.""" dtype = dtypes.as_dtype(dtype) shape_object = tensor_shape.as_shape(shape) with ops.init_scope(): if initializer is None: initializer, initializing_from_value = ( variable_scope._get_default_variable_store()._get_default_initializer( # pylint: disable=protected-access name=name, shape=shape_object, dtype=dtype)) else: initializing_from_value = not callable(initializer) # Same logic as get_variable variable_dtype = dtype.base_dtype if initializing_from_value: if shape is not None: raise ValueError("If initializer is a constant, do not specify shape.") initial_value = initializer else: # Instantiate initializer if provided initializer is a type object. if isinstance(initializer, type(init_ops.Initializer)): initializer = initializer(dtype=dtype) def initial_value(): return initializer( shape_object.as_list(), dtype=dtype, partition_info=partition_info) return resource_variable_ops.ResourceVariable( initial_value=initial_value, name=name, dtype=variable_dtype, **kwargs ) def add_variable(checkpointable, name, shape=None, dtype=dtypes.float32, initializer=None): """Add a variable to a Checkpointable with no scope influence.""" return checkpointable._add_variable_with_custom_getter( # pylint: disable=protected-access name=name, shape=shape, dtype=dtype, initializer=initializer, getter=_default_getter) def _breadth_first_checkpointable_traversal(root_checkpointable): """Find shortest paths to all variables owned by dependencies of root.""" bfs_sorted = [] to_visit = collections.deque([root_checkpointable]) path_to_root = {root_checkpointable: ()} while to_visit: current_checkpointable = to_visit.popleft() current_checkpointable._maybe_initialize_checkpointable() # pylint: disable=protected-access bfs_sorted.append(current_checkpointable) for child_checkpointable in ( current_checkpointable._checkpoint_dependencies): # pylint: disable=protected-access if child_checkpointable.ref not in path_to_root: path_to_root[child_checkpointable.ref] = ( path_to_root[current_checkpointable] + (child_checkpointable,)) to_visit.append(child_checkpointable.ref) return bfs_sorted, path_to_root def _escape_local_name(name): # We need to support slashes in local names for compatibility, since this # naming scheme is being patched in to things like Layer.add_variable where # slashes were previously accepted. We also want to use slashes to indicate # edges traversed to reach the variable, so we escape forward slashes in # names. return (name.replace(_ESCAPE_CHAR, _ESCAPE_CHAR + _ESCAPE_CHAR) .replace(r"/", _ESCAPE_CHAR + "S")) def _object_prefix_from_path(path_to_root): return "/".join( (_escape_local_name(checkpointable.name) for checkpointable in path_to_root)) def _slot_variable_naming_for_optimizer(optimizer_path): """Make a function for naming slot variables in an optimizer.""" # Name slot variables: # # <variable name>/<_OPTIMIZER_SLOTS_NAME>/<optimizer path>/<slot name> # # where <variable name> is exactly the checkpoint name used for the original # variable, including the path from the checkpoint root and the local name in # the object which owns it. Note that we only save slot variables if the # variable it's slotting for is also being saved. optimizer_identifier = "/%s/%s/" % (_OPTIMIZER_SLOTS_NAME, optimizer_path) def _name_slot_variable(variable_path, slot_name): """With an optimizer specified, name a slot variable.""" return (variable_path + optimizer_identifier + _escape_local_name(slot_name)) return _name_slot_variable def _serialize_slot_variables(checkpointable_objects, node_ids, object_names): """Gather and name slot variables.""" non_slot_objects = list(checkpointable_objects) slot_variables = {} for checkpointable in non_slot_objects: if isinstance(checkpointable, optimizer_lib.Optimizer): naming_scheme = _slot_variable_naming_for_optimizer( optimizer_path=object_names[checkpointable]) slot_names = checkpointable.get_slot_names() for slot_name in slot_names: for original_variable_node_id, original_variable in enumerate( non_slot_objects): try: slot_variable = checkpointable.get_slot( original_variable, slot_name) except AttributeError: slot_variable = None if slot_variable is None: continue slot_variable._maybe_initialize_checkpointable() # pylint: disable=protected-access if slot_variable._checkpoint_dependencies: # pylint: disable=protected-access # TODO (allenl): Gather dependencies of slot variables. id:3924 # https://github.com/imdone/tensorflow/issues/3922 raise NotImplementedError( "Currently only variables with no dependencies can be saved as " "slot variables. File a feature request if this limitation " "bothers you.") if slot_variable in node_ids: raise NotImplementedError( "A slot variable was re-used as a dependency of a " "Checkpointable object. This is not currently allowed. File a " "feature request if this limitation bothers you.") checkpoint_name = naming_scheme( variable_path=object_names[original_variable], slot_name=slot_name) object_names[slot_variable] = checkpoint_name slot_variable_node_id = len(checkpointable_objects) node_ids[slot_variable] = slot_variable_node_id checkpointable_objects.append(slot_variable) slot_variable_proto = ( checkpointable_object_graph_pb2.CheckpointableObjectGraph .CheckpointableObject.SlotVariableReference( slot_name=slot_name, original_variable_node_id=original_variable_node_id, slot_variable_node_id=slot_variable_node_id)) slot_variables.setdefault(checkpointable, []).append( slot_variable_proto) return slot_variables def _serialize_checkpointables( checkpointable_objects, node_ids, object_names, slot_variables): """Name non-slot `Checkpointable`s and add them to `object_graph_proto`.""" object_graph_proto = ( checkpointable_object_graph_pb2.CheckpointableObjectGraph()) named_saveables = {} for checkpoint_id, checkpointable in enumerate(checkpointable_objects): assert node_ids[checkpointable] == checkpoint_id object_proto = object_graph_proto.nodes.add() object_proto.slot_variables.extend(slot_variables.get(checkpointable, ())) object_name = object_names[checkpointable] for name, saveable_factory in ( checkpointable._gather_saveables_for_checkpoint().items()): # pylint: disable=protected-access attribute = object_proto.attributes.add() attribute.name = name attribute.checkpoint_key = "%s/%s/%s" % ( object_name, _OBJECT_ATTRIBUTES_NAME, _escape_local_name(name)) if callable(saveable_factory): saveable = saveable_factory(name=attribute.checkpoint_key) else: saveable = saveable_factory # Figure out the name-based Saver's name for this variable. saver_dict = saver_lib.BaseSaverBuilder.OpListToDict( [saveable], convert_variable_to_tensor=False) attribute.full_name, = saver_dict.keys() named_saveables[attribute.checkpoint_key] = saveable for child in checkpointable._checkpoint_dependencies: # pylint: disable=protected-access child_proto = object_proto.children.add() child_proto.node_id = node_ids[child.ref] child_proto.local_name = child.name return named_saveables, object_graph_proto def _serialize_object_graph(root_checkpointable): """Determine checkpoint keys for variables and build a serialized graph. Non-slot variables are keyed based on a shortest path from the root saveable to the object which owns the variable (i.e. the one which called `Checkpointable._add_variable` to create it). Slot variables are keyed based on a shortest path to the variable being slotted for, a shortest path to their optimizer, and the slot name. Args: root_checkpointable: A `Checkpointable` object whose variables (including the variables of dependencies, recursively) should be saved. Returns: A tuple of (named_variables, object_graph_proto): named_variables: A dictionary mapping names to variable objects. object_graph_proto: A CheckpointableObjectGraph protocol buffer containing the serialized object graph and variable references. Raises: ValueError: If there are invalid characters in an optimizer's slot names. """ checkpointable_objects, path_to_root = ( _breadth_first_checkpointable_traversal(root_checkpointable)) object_names = { obj: _object_prefix_from_path(path) for obj, path in path_to_root.items()} node_ids = {node: node_id for node_id, node in enumerate(checkpointable_objects)} slot_variables = _serialize_slot_variables( checkpointable_objects=checkpointable_objects, node_ids=node_ids, object_names=object_names) return _serialize_checkpointables( checkpointable_objects=checkpointable_objects, node_ids=node_ids, object_names=object_names, slot_variables=slot_variables) def list_objects(root_checkpointable): """Traverse the object graph and list all accessible objects. Looks for `Checkpointable` objects which are dependencies of `root_checkpointable`. Includes slot variables only if the variable they are slotting for and the optimizer are dependencies of `root_checkpointable` (i.e. if they would be saved with a checkpoint). Args: root_checkpointable: A `Checkpointable` object whose dependencies should be flattened. Returns: A flat list of objects. """ # TODO (allenl): Extract out gathering logic so the naming logic doesn't have id:4322 # https://github.com/imdone/tensorflow/issues/4320 # to run. checkpointable_objects, path_to_root = ( _breadth_first_checkpointable_traversal(root_checkpointable)) object_names = { obj: _object_prefix_from_path(path) for obj, path in path_to_root.items()} node_ids = {node: node_id for node_id, node in enumerate(checkpointable_objects)} _serialize_slot_variables( checkpointable_objects=checkpointable_objects, node_ids=node_ids, object_names=object_names) return checkpointable_objects def gather_initializers(root_checkpointable): """Traverse the object graph and find initialization ops. Looks for `Checkpointable` objects which are dependencies of `root_checkpointable` and which have an `initializer` property. Includes initializers for slot variables only if the variable they are slotting for and the optimizer are dependencies of `root_checkpointable` (i.e. if they would be saved with a checkpoint). Args: root_checkpointable: A `Checkpointable` object to gather initializers for. Returns: A list of initialization ops. """ checkpointable_objects = list_objects(root_checkpointable) return [c.initializer for c in checkpointable_objects if hasattr(c, "initializer") and c.initializer is not None] class _NoRestoreSaveable(saver_lib.BaseSaverBuilder.SaveableObject): def __init__(self, tensor, name): spec = saver_lib.BaseSaverBuilder.SaveSpec(tensor, "", name) super(_NoRestoreSaveable, self).__init__(tensor, [spec], name) def restore(self, restored_tensors, restored_shapes): return control_flow_ops.no_op() class _LoadStatus(object): """Abstract base for load status callbacks.""" @abc.abstractmethod def assert_consumed(self): """Raises an exception unless a non-trivial restoration has completed.""" pass @abc.abstractmethod def run_restore_ops(self, session=None): """Runs restore ops from the checkpoint. Requires a valid checkpoint.""" pass @abc.abstractmethod def initialize_or_restore(self, session=None): """Runs restore ops from the checkpoint, or initializes variables.""" pass class CheckpointLoadStatus(_LoadStatus): """Checks the status of checkpoint loading and manages restore ops. Returned from `Saver.restore`. Since `restore` may defer the loading of values in the checkpoint which don't yet have corresponding Python objects, `CheckpointLoadStatus` provides a callback to verify that checkpoint loading is complete (`assert_consumed`). When graph building, `restore` does not run restore ops itself since their creation may be deferred. The `run_restore_ops` method must be called once all Python objects with values to restore have been created and added to the dependency graph (this does not necessarily have to be the whole checkpoint; calling `run_restore_ops` while `assert_consumed` fails is supported and will partially restore the checkpoint). See `Saver.restore` for usage examples. """ def __init__(self, checkpoint, feed_dict, root_checkpointable): self._checkpoint = checkpoint self._feed_dict = feed_dict self._root_checkpointable = root_checkpointable def assert_consumed(self): """Asserts that all objects in the checkpoint have been created/matched. Returns: `self` for chaining. Raises: AssertionError: If there are any Python objects in the dependency graph which have not been restored from this checkpoint or a later `restore`, or if there are any checkpointed values which have not been matched to Python objects. """ for node_id, node in enumerate(self._checkpoint.object_graph_proto.nodes): checkpointable = self._checkpoint.object_by_proto_id.get(node_id, None) if checkpointable is None: raise AssertionError("Unresolved object in checkpoint: %s" % (node,)) if checkpointable._update_uid < self._checkpoint.restore_uid: # pylint: disable=protected-access raise AssertionError( "Object not assigned a value from checkpoint: %s" % (node,)) if self._checkpoint.slot_restorations: # Sanity check; this collection should be clear if everything has been # restored. raise AssertionError("Unresolved slot restorations: %s" % ( self._checkpoint.slot_restorations,)) if self._checkpoint.unused_attributes: raise AssertionError( ("Unused attributes in these objects (the attributes exist in the " "checkpoint but not in the objects): %s") % ( self._checkpoint.unused_attributes.items(),)) for checkpointable_object in list_objects(self._root_checkpointable): self._checkpoint.all_python_objects.add(checkpointable_object) unused_python_objects = ( set(self._checkpoint.all_python_objects) - set(self._checkpoint.object_by_proto_id.values())) if unused_python_objects: raise AssertionError( ("Some Python objects were not bound to checkpointed values, likely " "due to changes in the Python program: %s") % (unused_python_objects,)) return self def run_restore_ops(self, session=None): """Run operations to restore objects in the dependency graph.""" if context.executing_eagerly(): return # Run eagerly if session is None: session = ops.get_default_session() session.run(self._checkpoint.restore_ops, feed_dict=self._feed_dict) def initialize_or_restore(self, session=None): """Run operations to initialize or restore objects in the dependency graph. Any objects in the dependency graph which have initializers but are not in the checkpoint will have those initializers run, unless those variables are being restored by a later call to `tf.train.Checkpoint.restore()`. This method has a sibling in `InitializationOnlyStatus` which instead initializes variables. That type is returned if no checkpoint is specified in `Saver.restore`. Args: session: The session to run init/restore ops in. If `None`, uses the default session. """ if context.executing_eagerly(): return # Initialization and restoration ops are run eagerly if session is None: session = ops.get_default_session() all_objects = list_objects(self._root_checkpointable) already_initialized_objects = set( self._checkpoint.object_by_proto_id.values()) initializers_for_non_restored_variables = [ c.initializer for c in all_objects if hasattr(c, "initializer") and c not in already_initialized_objects and (getattr(c, "_update_uid", self._checkpoint.restore_uid - 1) < self._checkpoint.restore_uid)] self.run_restore_ops(session=session) session.run(initializers_for_non_restored_variables) class InitializationOnlyStatus(_LoadStatus): """Returned from `Saver.restore` when no checkpoint has been specified. Objects of this type have the same `assert_consumed` method as `CheckpointLoadStatus`, but it always fails. However, `initialize_or_restore` works on objects of both types, and will initialize variables in `InitializationOnlyStatus` objects or restore them otherwise. """ def __init__(self, root_checkpointable, restore_uid): self._restore_uid = restore_uid self._root_checkpointable = root_checkpointable def assert_consumed(self): """Assertion for consistency with `CheckpointLoadStatus`. Always fails.""" raise AssertionError( "No checkpoint specified (save_path=None); nothing is being restored.") def run_restore_ops(self, session=None): """For consistency with `CheckpointLoadStatus`. Use `initialize_or_restore` for initializing if no checkpoint was passed to `Saver.restore` and restoring otherwise. Args: session: Not used. """ raise AssertionError( "No checkpoint specified, so no restore ops are available " "(save_path=None to Saver.restore).") def initialize_or_restore(self, session=None): """Runs initialization ops for variables. Objects which would be saved by `Saver.save` will be initialized, unless those variables are being restored by a later call to `tf.train.Checkpoint.restore()`. This method does nothing when executing eagerly (initializers get run eagerly). Args: session: The session to run initialization ops in. If `None`, uses the default session. """ if context.executing_eagerly(): return # run eagerly if session is None: session = ops.get_default_session() checkpointable_objects = list_objects(self._root_checkpointable) initializers = [ c.initializer for c in checkpointable_objects if hasattr(c, "initializer") and c.initializer is not None and (getattr(c, "_update_uid", self._restore_uid - 1) < self._restore_uid)] session.run(initializers) _DEPRECATED_RESTORE_INSTRUCTIONS = ( "Restoring a name-based tf.train.Saver checkpoint using the object-based " "restore API. This mode uses global names to match variables, and so is " "somewhat fragile. It also adds new restore ops to the graph each time it " "is called. Prefer re-encoding training checkpoints in the object-based " "format: run save() on the object-based saver (the same one this message " "is coming from) and use that checkpoint in the future.") class NameBasedSaverStatus(_LoadStatus): """Status for loading a name-based training checkpoint.""" def __init__(self, object_saver, save_path): self._object_saver = object_saver self._save_path = save_path def assert_consumed(self): """Assertion for consistency with `CheckpointLoadStatus`. Always fails.""" raise AssertionError( "Restoring a name-based checkpoint. No load status is available.") @deprecation.deprecated( date=None, instructions=_DEPRECATED_RESTORE_INSTRUCTIONS) def run_restore_ops(self, session=None): """Load the name-based training checkpoint using a new `tf.train.Saver`.""" if session is None and not context.executing_eagerly(): session = ops.get_default_session() with ops.device("/cpu:0"): saver_lib.Saver(self._object_saver._global_variable_names()).restore( # pylint: disable=protected-access sess=session, save_path=self._save_path) def initialize_or_restore(self, session=None): """Alias for `run_restore_ops`.""" self.run_restore_ops(session=session) class _SessionWithFeedDictAdditions(session_lib.SessionInterface): """Pretends to be a session, inserts extra feeds on run().""" def __init__(self, session, feed_additions): self._wrapped_session = session self._feed_additions = feed_additions def run(self, fetches, feed_dict=None, **kwargs): if feed_dict is None: feed_dict = {} else: feed_dict = feed_dict.copy() feed_dict.update(self._feed_additions) return self._wrapped_session.run( fetches=fetches, feed_dict=feed_dict, **kwargs) def _copy_saver_with_new_var_list(old_saver, new_var_list): """Copy a `tf.train.Saver`'s state to a new Saver with different variables.""" new_saver = saver_lib.Saver(var_list=new_var_list) # TODO (allenl): Move to copying functionality to Saver? id:3986 # https://github.com/imdone/tensorflow/issues/3984 # pylint: disable=protected-access new_saver._last_checkpoints = old_saver._last_checkpoints new_saver._checkpoints_to_be_deleted = old_saver._checkpoints_to_be_deleted new_saver._next_checkpoint_time = old_saver._next_checkpoint_time # pylint: enable=protected-access return new_saver class CheckpointableSaver(object): """Saves and restores a `Checkpointable` object and its dependencies. See `Checkpointable` for details of dependency management. `Saver` wraps `tf.train.Saver` for saving, including extra information about the graph of dependencies between Python objects. When restoring, it uses this information about the save-time dependency graph to more robustly match objects with their checkpointed values. When executing eagerly, it supports restoring variables on object creation (see `Saver.restore`). Values in a checkpoint are mapped to `Checkpointable` Python objects (`Variable`s, `Optimizer`s, `Layer`s) based on the names provided when the checkpoint was written. To avoid breaking existing checkpoints when modifying a class, dependency names (the names of attributes to which `Checkpointable` objects are assigned) may not change. These names are local to objects, in contrast to the `Variable.name`-based save/restore from `tf.train.Saver`, and so allow additional program transformations. """ def __init__(self, root_checkpointable): """Configure saving. Args: root_checkpointable: The root of the object graph to save/restore. This object and all of its dependencies are saved in the checkpoint. When restoring, objects are matched and restored starting from this root. """ # Allow passing in a weak reference to avoid reference cycles when # `Checkpointable` objects save themselves. self._root_checkpointable_ref = root_checkpointable # The file prefix placeholder is created lazily when graph building (and not # at all when executing eagerly) to avoid creating ops in the constructor # (when they may never be necessary). self._file_prefix_placeholder = None # Op caching for save self._object_graph_feed_tensor = None self._last_save_object_graph = None self._last_save_saver = None # Op caching for restore self._last_restore_object_graph = None self._last_restore_checkpoint = None @property def _root_checkpointable(self): if isinstance(self._root_checkpointable_ref, weakref.ref): derefed = self._root_checkpointable_ref() assert derefed is not None return derefed else: return self._root_checkpointable_ref def save(self, file_prefix, checkpoint_number=None, session=None): """Save a training checkpoint. The saved checkpoint includes variables created by this object and any Checkpointable objects it depends on at the time `Saver.save()` is called. Args: file_prefix: A prefix to use for the checkpoint filenames (/path/to/directory/and_a_prefix). Names are generated based on this prefix and `checkpoint_number`, if provided. checkpoint_number: An integer variable or Tensor, used to number checkpoints. Typically this value is saved along with other variables in training checkpoints, which will happen automatically if it was created by `root_checkpointable` or one of its dependencies (via `Checkpointable._add_variable`). session: The session to evaluate variables in. Ignored when executing eagerly. If not provided when graph building, the default session is used. Returns: The full path to the checkpoint. """ named_variables, graph_proto = _serialize_object_graph( self._root_checkpointable) if not context.executing_eagerly(): if session is None: session = ops.get_default_session() if self._object_graph_feed_tensor is None: with ops.device("/cpu:0"): self._object_graph_feed_tensor = constant_op.constant( "", dtype=dtypes.string) object_graph_tensor = self._object_graph_feed_tensor feed_additions = {object_graph_tensor: graph_proto.SerializeToString()} else: session = None with ops.device("/cpu:0"): object_graph_tensor = constant_op.constant( graph_proto.SerializeToString(), dtype=dtypes.string) feed_additions = None assert checkpointable_lib.OBJECT_GRAPH_PROTO_KEY not in named_variables named_variables[checkpointable_lib.OBJECT_GRAPH_PROTO_KEY] = ( _NoRestoreSaveable( tensor=object_graph_tensor, name=checkpointable_lib.OBJECT_GRAPH_PROTO_KEY)) if (self._last_save_object_graph != graph_proto # When executing eagerly, we need to re-create SaveableObjects each time # save() is called so they pick up new Tensors passed to their # constructors. That means the Saver needs to be copied with a new # var_list. or context.executing_eagerly()): if self._last_save_object_graph is not None: self._last_save_saver = _copy_saver_with_new_var_list( old_saver=self._last_save_saver, new_var_list=named_variables) else: self._last_save_saver = saver_lib.Saver(var_list=named_variables) self._last_save_object_graph = graph_proto with ops.device("/cpu:0"): save_path = self._last_save_saver.save( sess=_SessionWithFeedDictAdditions( session=session, feed_additions=feed_additions), save_path=file_prefix, write_meta_graph=False, global_step=checkpoint_number) return save_path def _global_variable_names(self): """Generate a `tf.train.Saver`-style `var_list` using `variable.name`s.""" named_saveables, graph_proto = _serialize_object_graph( self._root_checkpointable) saver_names = {} for object_proto in graph_proto.nodes: for attribute_proto in object_proto.attributes: saver_names[attribute_proto.full_name] = named_saveables[ attribute_proto.checkpoint_key] return saver_names def restore(self, save_path): """Restore a training checkpoint. Restores `root_checkpointable` and any objects that it tracks (transitive). Either assigns values immediately if variables to restore have been created already, or defers restoration until the variables are created. Dependencies added to the `root_checkpointable` passed to the constructor after this call will be matched if they have a corresponding object in the checkpoint. When building a graph, restorations are added to the graph but not run. To disallow deferred loading, assert immediately that all checkpointed variables have been matched to variable objects: ```python saver = Saver(root) saver.restore(path).assert_consumed() ``` An exception will be raised unless every object was matched and its variables already exist. When graph building, `assert_consumed()` indicates that all of the restore ops which will be created for this checkpoint have been created. They can be run via the `run_restore_ops()` function of the status object: ```python saver.restore(path).assert_consumed().run_restore_ops() ``` If the checkpoint has not been consumed completely, then the list of restore ops will grow as more objects are added to the dependency graph. Name-based `tf.train.Saver` checkpoints can be loaded using this method. There is no deferred loading, and names are used to match variables. No restore ops are created/run until `run_restore_ops()` or `initialize_or_restore()` are called on the returned status object, even when executing eagerly. Re-encode name-based checkpoints using this object-based `Saver.save` as soon as possible. Args: save_path: The path to the checkpoint, as returned by `save` or `tf.train.latest_checkpoint`. If None (as when there is no latest checkpoint for `tf.train.latest_checkpoint` to return), returns an object which may run initializers for objects in the dependency graph. If the checkpoint was written by the name-based `tf.train.Saver`, names are used to match variables. Returns: A load status object, which can be used to make assertions about the status of checkpoint restoration and run initialization/restore ops (of type `CheckpointLoadStatus`, or `InitializationOnlyStatus` if `save_path` is `None`). If `save_path` points to a name-based checkpoint, a `NameBasedSaverStatus` object is returned which runs restore ops from a name-based saver. """ if save_path is None: return InitializationOnlyStatus(self._root_checkpointable, ops.uid()) in_graph_mode = not context.executing_eagerly() if in_graph_mode: if self._file_prefix_placeholder is None: with ops.device("/cpu:0"): self._file_prefix_placeholder = constant_op.constant("model") file_prefix_tensor = self._file_prefix_placeholder file_prefix_feed_dict = {self._file_prefix_placeholder: save_path} else: with ops.device("/cpu:0"): file_prefix_tensor = constant_op.constant(save_path) file_prefix_feed_dict = None reader = pywrap_tensorflow.NewCheckpointReader(save_path) try: object_graph_string = reader.get_tensor( checkpointable_lib.OBJECT_GRAPH_PROTO_KEY) except errors_impl.NotFoundError: # The object graph proto does not exist in this checkpoint. Try again with # name-based saving. return NameBasedSaverStatus(self, save_path) object_graph_proto = ( checkpointable_object_graph_pb2.CheckpointableObjectGraph()) object_graph_proto.ParseFromString(object_graph_string) if in_graph_mode and object_graph_proto == self._last_restore_object_graph: checkpoint = self._last_restore_checkpoint else: if in_graph_mode: dtype_map = None else: dtype_map = reader.get_variable_to_dtype_map() checkpoint = _CheckpointRestoreCoordinator( object_graph_proto=object_graph_proto, save_path=file_prefix_tensor, dtype_map=dtype_map) if in_graph_mode: if self._last_restore_object_graph is not None: raise NotImplementedError( "Using a single Saver to restore different object graphs is not " "currently supported when graph building. Use a different Saver " "for each object graph (restore ops will be duplicated), or " "file a feature request if this limitation bothers you.") self._last_restore_checkpoint = checkpoint self._last_restore_object_graph = object_graph_proto checkpointable_lib._CheckpointPosition( # pylint: disable=protected-access checkpoint=checkpoint, proto_id=0).restore(self._root_checkpointable) load_status = CheckpointLoadStatus( checkpoint, root_checkpointable=self._root_checkpointable, feed_dict=file_prefix_feed_dict) return load_status @tf_export("train.Checkpoint") class Checkpoint(checkpointable_lib.Checkpointable): """Groups checkpointable objects, saving and restoring them. `Checkpoint`'s constructor accepts keyword arguments whose values are types that contain checkpointable state, such as `tf.train.Optimizer` implementations, `tf.Variable`, `tf.keras.Layer` implementations, or `tf.keras.Model` implementations. It saves these values with a checkpoint, and maintains a `save_counter` for numbering checkpoints. Example usage when graph building: ```python import tensorflow as tf import os checkpoint_directory = "/tmp/training_checkpoints" checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model) status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory)) train_op = optimizer.minimize( ... ) status.assert_consumed() # Optional sanity checks. with tf.Session() as session: # Use the Session to restore variables, or initialize them if # tf.train.latest_checkpoint returned None. status.initialize_or_restore(session) for _ in range(num_training_steps): session.run(train_op) checkpoint.save(file_prefix=checkpoint_prefix) ``` Example usage with eager execution enabled: ```python import tensorflow as tf import os tf.enable_eager_execution() checkpoint_directory = "/tmp/training_checkpoints" checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model) status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory)) for _ in range(num_training_steps): optimizer.minimize( ... ) # Variables will be restored on creation. status.assert_consumed() # Optional sanity checks. checkpoint.save(file_prefix=checkpoint_prefix) ``` `Checkpoint.save` and `Checkpoint.restore` write and read object-based checkpoints, in contrast to `tf.train.Saver` which writes and reads `variable.name` based checkpoints. Object-based checkpointing saves a graph of dependencies between Python objects (`Layer`s, `Optimizer`s, `Variable`s, etc.) with named edges, and this graph is used to match variables when restoring a checkpoint. It can be more robust to changes in the Python program, and helps to support restore-on-create for variables when executing eagerly. Prefer `tf.train.Checkpoint` over `tf.train.Saver` for new code. `Checkpoint` objects have dependencies on the objects passed as keyword arguments to their constructors, and each dependency is given a name that is identical to the name of the keyword argument for which it was created. TensorFlow classes like `Layer`s and `Optimizer`s will automatically add dependencies on their variables (e.g. "kernel" and "bias" for `tf.keras.layers.Dense`). Inheriting from `tf.keras.Model` makes managing dependencies easy in user-defined classes, since `Model` hooks into attribute assignment. For example: ```python class Regress(tf.keras.Model): def __init__(self): super(Regress, self).__init__() self.input_transform = tf.keras.layers.Dense(10) # ... def call(self, inputs): x = self.input_transform(inputs) # ... ``` This `Model` has a dependency named "input_transform" on its `Dense` layer, which in turn depends on its variables. As a result, saving an instance of `Regress` using `tf.train.Checkpoint` will also save all the variables created by the `Dense` layer. Attributes: save_counter: Incremented when `save()` is called. Used to number checkpoints. """ def __init__(self, **kwargs): """Group objects into a training checkpoint. Args: **kwargs: Keyword arguments are set as attributes of this object, and are saved with the checkpoint. Values must be checkpointable objects. Raises: ValueError: If objects in `kwargs` are not checkpointable. """ super(Checkpoint, self).__init__() for k, v in sorted(kwargs.items(), key=lambda item: item[0]): if not isinstance(v, checkpointable_lib.CheckpointableBase): raise ValueError( ("`Checkpoint` was expecting a checkpointable object (an object " "derived from `CheckpointableBase`), got %s. If you believe this " "object should be checkpointable (i.e. it is part of the " "TensorFlow Python API and manages state), please open an issue.") % (v,)) setattr(self, k, v) self._save_counter = None # Created lazily for restore-on-create. self._saver = CheckpointableSaver(weakref.ref(self)) def _maybe_create_save_counter(self): """Create a save counter if it does not yet exist.""" if self._save_counter is None: # Initialized to 0 and incremented before saving. with ops.device("/cpu:0"): self._save_counter = add_variable( self, name="save_counter", initializer=0, dtype=dtypes.int64) @property def save_counter(self): """An integer variable which starts at zero and is incremented on save. Used to number checkpoints. Returns: The save counter variable. """ self._maybe_create_save_counter() return self._save_counter def save(self, file_prefix, session=None): """Save a training checkpoint. The saved checkpoint includes variables created by this object and any checkpointable objects it depends on at the time `Checkpoint.save()` is called. Args: file_prefix: A prefix to use for the checkpoint filenames (/path/to/directory/and_a_prefix). Names are generated based on this prefix and `Checkpoint.save_counter`. session: The session to evaluate variables in. Ignored when executing eagerly. If not provided when graph building, the default session is used. Returns: The full path to the checkpoint. """ in_graph_mode = not context.executing_eagerly() if in_graph_mode: if session is None: session = ops.get_default_session() if self._save_counter is None: # When graph building, if this is a new save counter variable then it # needs to be initialized before assign_add. This is only an issue if # restore() has not been called first. session.run(self.save_counter.initializer) with ops.colocate_with(self.save_counter): assign_op = self.save_counter.assign_add(1) if in_graph_mode: session.run(assign_op) return self._saver.save( file_prefix=file_prefix, checkpoint_number=self.save_counter, session=session) def restore(self, save_path): """Restore a training checkpoint. Restores this `Checkpoint` and any objects it depends on. When executing eagerly, either assigns values immediately if variables to restore have been created already, or defers restoration until the variables are created. Dependencies added after this call will be matched if they have a corresponding object in the checkpoint (the restore request will queue in any checkpointable object waiting for the expected dependency to be added). When graph building, restoration ops are added to the graph but not run immediately. To ensure that loading is complete and no more assignments will take place, use the `assert_consumed()` method of the status object returned by `restore`: ```python checkpoint = tf.train.Checkpoint( ... ) checkpoint.restore(path).assert_consumed() ``` An exception will be raised if any Python objects in the dependency graph were not found in the checkpoint, or if any checkpointed values do not have a matching Python object. When graph building, `assert_consumed()` indicates that all of the restore ops that will be created for this checkpoint have been created. They can be run via the `run_restore_ops()` method of the status object: ```python checkpoint.restore(path).assert_consumed().run_restore_ops() ``` If the checkpoint has not been consumed completely, then the list of restore ops will grow as more objects are added to the dependency graph. Name-based `tf.train.Saver` checkpoints can be loaded using this method. There is no deferred loading, and names are used to match variables. No restore ops are created/run until `run_restore_ops()` or `initialize_or_restore()` are called on the returned status object, even when executing eagerly. Re-encode name-based checkpoints using `tf.train.Checkpoint.save` as soon as possible. Args: save_path: The path to the checkpoint, as returned by `save` or `tf.train.latest_checkpoint`. If None (as when there is no latest checkpoint for `tf.train.latest_checkpoint` to return), returns an object which may run initializers for objects in the dependency graph. If the checkpoint was written by the name-based `tf.train.Saver`, names are used to match variables. Returns: A load status object, which can be used to make assertions about the status of a checkpoint restoration and run initialization/restore ops. The returned status object has the following methods: - `assert_consumed()`: Raises an exception if any variables/objects are unmatched: either checkpointed values which don't have a matching Python object or Python objects in the dependency graph with no values in the checkpoint. This method returns the status object, and so may be chained with `initialize_or_restore` or `run_restore_ops`. - `initialize_or_restore(session=None)`: When graph building, runs variable initializers if `save_path` is `None`, but otherwise runs restore operations. If no `session` is explicitly specified, the default session is used. No effect for object-based checkpoints when executing eagerly (variables are initialized or restored eagerly). - `run_restore_ops(session=None)`: When graph building, runs restore operations. If no `session` is explicitly specified, the default session is used. No effect for object-based checkpoints when executing eagerly (restore operations are run eagerly). May only be called when `save_path` is not `None`. """ status = self._saver.restore(save_path=save_path) # Create the save counter now so it gets initialized with other variables # when graph building. Creating it earlier would lead to double # initialization when executing eagerly. self._maybe_create_save_counter() return status
43.294939
116
0.730893
from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import collections import weakref from tensorflow.core.protobuf import checkpointable_object_graph_pb2 from tensorflow.python import pywrap_tensorflow from tensorflow.python.client import session as session_lib from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors_impl from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import variable_scope from tensorflow.python.training import checkpointable as checkpointable_lib from tensorflow.python.training import optimizer as optimizer_lib from tensorflow.python.training import saver as saver_lib from tensorflow.python.util import deprecation from tensorflow.python.util.tf_export import tf_export _ESCAPE_CHAR = "." _OPTIMIZER_SLOTS_NAME = _ESCAPE_CHAR + "OPTIMIZER_SLOT" _OBJECT_ATTRIBUTES_NAME = _ESCAPE_CHAR + "ATTRIBUTES" class _CheckpointRestoreCoordinator(object): def __init__(self, object_graph_proto, save_path, dtype_map=None): self.builder = saver_lib.BulkSaverBuilder() self.object_graph_proto = object_graph_proto self.restore_uid = ops.uid() self.unused_attributes = weakref.WeakKeyDictionary() # (as objects with deferred dependencies will generally have references to # this object). self.object_by_proto_id = weakref.WeakValueDictionary() # A set of all Python objects we've seen as dependencies, even if we didn't # use them (for example because of inconsistent references when # loading). Used to make status assertions fail when loading checkpoints # that don't quite match. self.all_python_objects = weakref.WeakSet() self.save_path = save_path self.dtype_map = dtype_map self.restore_ops = [] self.restore_ops_by_name = {} self.deferred_slot_restorations = {} # happens. self.slot_restorations = {} for node_index, node in enumerate(self.object_graph_proto.nodes): for slot_reference in node.slot_variables: # `node` refers to an `Optimizer`, since only these have slot variables. self.slot_restorations.setdefault( slot_reference.original_variable_node_id, []).append( checkpointable_lib._SlotVariableRestoration( # pylint: disable=protected-access optimizer_id=node_index, slot_variable_id=slot_reference.slot_variable_node_id, slot_name=slot_reference.slot_name)) # TODO (allenl): If this ends up in a public API, consider adding LINT.IfChange id:3465 # https://github.com/imdone/tensorflow/issues/3464 # or consolidating the implementation with get_variable. def _default_getter(name, shape, dtype, initializer=None, partition_info=None, **kwargs): dtype = dtypes.as_dtype(dtype) shape_object = tensor_shape.as_shape(shape) with ops.init_scope(): if initializer is None: initializer, initializing_from_value = ( variable_scope._get_default_variable_store()._get_default_initializer( # pylint: disable=protected-access name=name, shape=shape_object, dtype=dtype)) else: initializing_from_value = not callable(initializer) # Same logic as get_variable variable_dtype = dtype.base_dtype if initializing_from_value: if shape is not None: raise ValueError("If initializer is a constant, do not specify shape.") initial_value = initializer else: # Instantiate initializer if provided initializer is a type object. if isinstance(initializer, type(init_ops.Initializer)): initializer = initializer(dtype=dtype) def initial_value(): return initializer( shape_object.as_list(), dtype=dtype, partition_info=partition_info) return resource_variable_ops.ResourceVariable( initial_value=initial_value, name=name, dtype=variable_dtype, **kwargs ) def add_variable(checkpointable, name, shape=None, dtype=dtypes.float32, initializer=None): return checkpointable._add_variable_with_custom_getter( # pylint: disable=protected-access name=name, shape=shape, dtype=dtype, initializer=initializer, getter=_default_getter) def _breadth_first_checkpointable_traversal(root_checkpointable): bfs_sorted = [] to_visit = collections.deque([root_checkpointable]) path_to_root = {root_checkpointable: ()} while to_visit: current_checkpointable = to_visit.popleft() current_checkpointable._maybe_initialize_checkpointable() # pylint: disable=protected-access bfs_sorted.append(current_checkpointable) for child_checkpointable in ( current_checkpointable._checkpoint_dependencies): # pylint: disable=protected-access if child_checkpointable.ref not in path_to_root: path_to_root[child_checkpointable.ref] = ( path_to_root[current_checkpointable] + (child_checkpointable,)) to_visit.append(child_checkpointable.ref) return bfs_sorted, path_to_root def _escape_local_name(name): # We need to support slashes in local names for compatibility, since this # naming scheme is being patched in to things like Layer.add_variable where # slashes were previously accepted. We also want to use slashes to indicate # edges traversed to reach the variable, so we escape forward slashes in # names. return (name.replace(_ESCAPE_CHAR, _ESCAPE_CHAR + _ESCAPE_CHAR) .replace(r"/", _ESCAPE_CHAR + "S")) def _object_prefix_from_path(path_to_root): return "/".join( (_escape_local_name(checkpointable.name) for checkpointable in path_to_root)) def _slot_variable_naming_for_optimizer(optimizer_path): # Name slot variables: # # <variable name>/<_OPTIMIZER_SLOTS_NAME>/<optimizer path>/<slot name> # # where <variable name> is exactly the checkpoint name used for the original # variable, including the path from the checkpoint root and the local name in # the object which owns it. Note that we only save slot variables if the # variable it's slotting for is also being saved. optimizer_identifier = "/%s/%s/" % (_OPTIMIZER_SLOTS_NAME, optimizer_path) def _name_slot_variable(variable_path, slot_name): return (variable_path + optimizer_identifier + _escape_local_name(slot_name)) return _name_slot_variable def _serialize_slot_variables(checkpointable_objects, node_ids, object_names): non_slot_objects = list(checkpointable_objects) slot_variables = {} for checkpointable in non_slot_objects: if isinstance(checkpointable, optimizer_lib.Optimizer): naming_scheme = _slot_variable_naming_for_optimizer( optimizer_path=object_names[checkpointable]) slot_names = checkpointable.get_slot_names() for slot_name in slot_names: for original_variable_node_id, original_variable in enumerate( non_slot_objects): try: slot_variable = checkpointable.get_slot( original_variable, slot_name) except AttributeError: slot_variable = None if slot_variable is None: continue slot_variable._maybe_initialize_checkpointable() if slot_variable._checkpoint_dependencies: raise NotImplementedError( "Currently only variables with no dependencies can be saved as " "slot variables. File a feature request if this limitation " "bothers you.") if slot_variable in node_ids: raise NotImplementedError( "A slot variable was re-used as a dependency of a " "Checkpointable object. This is not currently allowed. File a " "feature request if this limitation bothers you.") checkpoint_name = naming_scheme( variable_path=object_names[original_variable], slot_name=slot_name) object_names[slot_variable] = checkpoint_name slot_variable_node_id = len(checkpointable_objects) node_ids[slot_variable] = slot_variable_node_id checkpointable_objects.append(slot_variable) slot_variable_proto = ( checkpointable_object_graph_pb2.CheckpointableObjectGraph .CheckpointableObject.SlotVariableReference( slot_name=slot_name, original_variable_node_id=original_variable_node_id, slot_variable_node_id=slot_variable_node_id)) slot_variables.setdefault(checkpointable, []).append( slot_variable_proto) return slot_variables def _serialize_checkpointables( checkpointable_objects, node_ids, object_names, slot_variables): object_graph_proto = ( checkpointable_object_graph_pb2.CheckpointableObjectGraph()) named_saveables = {} for checkpoint_id, checkpointable in enumerate(checkpointable_objects): assert node_ids[checkpointable] == checkpoint_id object_proto = object_graph_proto.nodes.add() object_proto.slot_variables.extend(slot_variables.get(checkpointable, ())) object_name = object_names[checkpointable] for name, saveable_factory in ( checkpointable._gather_saveables_for_checkpoint().items()): attribute = object_proto.attributes.add() attribute.name = name attribute.checkpoint_key = "%s/%s/%s" % ( object_name, _OBJECT_ATTRIBUTES_NAME, _escape_local_name(name)) if callable(saveable_factory): saveable = saveable_factory(name=attribute.checkpoint_key) else: saveable = saveable_factory saver_dict = saver_lib.BaseSaverBuilder.OpListToDict( [saveable], convert_variable_to_tensor=False) attribute.full_name, = saver_dict.keys() named_saveables[attribute.checkpoint_key] = saveable for child in checkpointable._checkpoint_dependencies: # pylint: disable=protected-access child_proto = object_proto.children.add() child_proto.node_id = node_ids[child.ref] child_proto.local_name = child.name return named_saveables, object_graph_proto def _serialize_object_graph(root_checkpointable): checkpointable_objects, path_to_root = ( _breadth_first_checkpointable_traversal(root_checkpointable)) object_names = { obj: _object_prefix_from_path(path) for obj, path in path_to_root.items()} node_ids = {node: node_id for node_id, node in enumerate(checkpointable_objects)} slot_variables = _serialize_slot_variables( checkpointable_objects=checkpointable_objects, node_ids=node_ids, object_names=object_names) return _serialize_checkpointables( checkpointable_objects=checkpointable_objects, node_ids=node_ids, object_names=object_names, slot_variables=slot_variables) def list_objects(root_checkpointable): # TODO (allenl): Extract out gathering logic so the naming logic doesn't have id:4322 checkpointable_objects, path_to_root = ( _breadth_first_checkpointable_traversal(root_checkpointable)) object_names = { obj: _object_prefix_from_path(path) for obj, path in path_to_root.items()} node_ids = {node: node_id for node_id, node in enumerate(checkpointable_objects)} _serialize_slot_variables( checkpointable_objects=checkpointable_objects, node_ids=node_ids, object_names=object_names) return checkpointable_objects def gather_initializers(root_checkpointable): checkpointable_objects = list_objects(root_checkpointable) return [c.initializer for c in checkpointable_objects if hasattr(c, "initializer") and c.initializer is not None] class _NoRestoreSaveable(saver_lib.BaseSaverBuilder.SaveableObject): def __init__(self, tensor, name): spec = saver_lib.BaseSaverBuilder.SaveSpec(tensor, "", name) super(_NoRestoreSaveable, self).__init__(tensor, [spec], name) def restore(self, restored_tensors, restored_shapes): return control_flow_ops.no_op() class _LoadStatus(object): @abc.abstractmethod def assert_consumed(self): pass @abc.abstractmethod def run_restore_ops(self, session=None): pass @abc.abstractmethod def initialize_or_restore(self, session=None): pass class CheckpointLoadStatus(_LoadStatus): def __init__(self, checkpoint, feed_dict, root_checkpointable): self._checkpoint = checkpoint self._feed_dict = feed_dict self._root_checkpointable = root_checkpointable def assert_consumed(self): for node_id, node in enumerate(self._checkpoint.object_graph_proto.nodes): checkpointable = self._checkpoint.object_by_proto_id.get(node_id, None) if checkpointable is None: raise AssertionError("Unresolved object in checkpoint: %s" % (node,)) if checkpointable._update_uid < self._checkpoint.restore_uid: raise AssertionError( "Object not assigned a value from checkpoint: %s" % (node,)) if self._checkpoint.slot_restorations: raise AssertionError("Unresolved slot restorations: %s" % ( self._checkpoint.slot_restorations,)) if self._checkpoint.unused_attributes: raise AssertionError( ("Unused attributes in these objects (the attributes exist in the " "checkpoint but not in the objects): %s") % ( self._checkpoint.unused_attributes.items(),)) for checkpointable_object in list_objects(self._root_checkpointable): self._checkpoint.all_python_objects.add(checkpointable_object) unused_python_objects = ( set(self._checkpoint.all_python_objects) - set(self._checkpoint.object_by_proto_id.values())) if unused_python_objects: raise AssertionError( ("Some Python objects were not bound to checkpointed values, likely " "due to changes in the Python program: %s") % (unused_python_objects,)) return self def run_restore_ops(self, session=None): if context.executing_eagerly(): return if session is None: session = ops.get_default_session() session.run(self._checkpoint.restore_ops, feed_dict=self._feed_dict) def initialize_or_restore(self, session=None): if context.executing_eagerly(): return if session is None: session = ops.get_default_session() all_objects = list_objects(self._root_checkpointable) already_initialized_objects = set( self._checkpoint.object_by_proto_id.values()) initializers_for_non_restored_variables = [ c.initializer for c in all_objects if hasattr(c, "initializer") and c not in already_initialized_objects and (getattr(c, "_update_uid", self._checkpoint.restore_uid - 1) < self._checkpoint.restore_uid)] self.run_restore_ops(session=session) session.run(initializers_for_non_restored_variables) class InitializationOnlyStatus(_LoadStatus): def __init__(self, root_checkpointable, restore_uid): self._restore_uid = restore_uid self._root_checkpointable = root_checkpointable def assert_consumed(self): raise AssertionError( "No checkpoint specified (save_path=None); nothing is being restored.") def run_restore_ops(self, session=None): raise AssertionError( "No checkpoint specified, so no restore ops are available " "(save_path=None to Saver.restore).") def initialize_or_restore(self, session=None): if context.executing_eagerly(): return if session is None: session = ops.get_default_session() checkpointable_objects = list_objects(self._root_checkpointable) initializers = [ c.initializer for c in checkpointable_objects if hasattr(c, "initializer") and c.initializer is not None and (getattr(c, "_update_uid", self._restore_uid - 1) < self._restore_uid)] session.run(initializers) _DEPRECATED_RESTORE_INSTRUCTIONS = ( "Restoring a name-based tf.train.Saver checkpoint using the object-based " "restore API. This mode uses global names to match variables, and so is " "somewhat fragile. It also adds new restore ops to the graph each time it " "is called. Prefer re-encoding training checkpoints in the object-based " "format: run save() on the object-based saver (the same one this message " "is coming from) and use that checkpoint in the future.") class NameBasedSaverStatus(_LoadStatus): def __init__(self, object_saver, save_path): self._object_saver = object_saver self._save_path = save_path def assert_consumed(self): raise AssertionError( "Restoring a name-based checkpoint. No load status is available.") @deprecation.deprecated( date=None, instructions=_DEPRECATED_RESTORE_INSTRUCTIONS) def run_restore_ops(self, session=None): if session is None and not context.executing_eagerly(): session = ops.get_default_session() with ops.device("/cpu:0"): saver_lib.Saver(self._object_saver._global_variable_names()).restore( sess=session, save_path=self._save_path) def initialize_or_restore(self, session=None): self.run_restore_ops(session=session) class _SessionWithFeedDictAdditions(session_lib.SessionInterface): def __init__(self, session, feed_additions): self._wrapped_session = session self._feed_additions = feed_additions def run(self, fetches, feed_dict=None, **kwargs): if feed_dict is None: feed_dict = {} else: feed_dict = feed_dict.copy() feed_dict.update(self._feed_additions) return self._wrapped_session.run( fetches=fetches, feed_dict=feed_dict, **kwargs) def _copy_saver_with_new_var_list(old_saver, new_var_list): new_saver = saver_lib.Saver(var_list=new_var_list) new_saver._last_checkpoints = old_saver._last_checkpoints new_saver._checkpoints_to_be_deleted = old_saver._checkpoints_to_be_deleted new_saver._next_checkpoint_time = old_saver._next_checkpoint_time return new_saver class CheckpointableSaver(object): def __init__(self, root_checkpointable): self._root_checkpointable_ref = root_checkpointable self._file_prefix_placeholder = None self._object_graph_feed_tensor = None self._last_save_object_graph = None self._last_save_saver = None self._last_restore_object_graph = None self._last_restore_checkpoint = None @property def _root_checkpointable(self): if isinstance(self._root_checkpointable_ref, weakref.ref): derefed = self._root_checkpointable_ref() assert derefed is not None return derefed else: return self._root_checkpointable_ref def save(self, file_prefix, checkpoint_number=None, session=None): named_variables, graph_proto = _serialize_object_graph( self._root_checkpointable) if not context.executing_eagerly(): if session is None: session = ops.get_default_session() if self._object_graph_feed_tensor is None: with ops.device("/cpu:0"): self._object_graph_feed_tensor = constant_op.constant( "", dtype=dtypes.string) object_graph_tensor = self._object_graph_feed_tensor feed_additions = {object_graph_tensor: graph_proto.SerializeToString()} else: session = None with ops.device("/cpu:0"): object_graph_tensor = constant_op.constant( graph_proto.SerializeToString(), dtype=dtypes.string) feed_additions = None assert checkpointable_lib.OBJECT_GRAPH_PROTO_KEY not in named_variables named_variables[checkpointable_lib.OBJECT_GRAPH_PROTO_KEY] = ( _NoRestoreSaveable( tensor=object_graph_tensor, name=checkpointable_lib.OBJECT_GRAPH_PROTO_KEY)) if (self._last_save_object_graph != graph_proto or context.executing_eagerly()): if self._last_save_object_graph is not None: self._last_save_saver = _copy_saver_with_new_var_list( old_saver=self._last_save_saver, new_var_list=named_variables) else: self._last_save_saver = saver_lib.Saver(var_list=named_variables) self._last_save_object_graph = graph_proto with ops.device("/cpu:0"): save_path = self._last_save_saver.save( sess=_SessionWithFeedDictAdditions( session=session, feed_additions=feed_additions), save_path=file_prefix, write_meta_graph=False, global_step=checkpoint_number) return save_path def _global_variable_names(self): named_saveables, graph_proto = _serialize_object_graph( self._root_checkpointable) saver_names = {} for object_proto in graph_proto.nodes: for attribute_proto in object_proto.attributes: saver_names[attribute_proto.full_name] = named_saveables[ attribute_proto.checkpoint_key] return saver_names def restore(self, save_path): if save_path is None: return InitializationOnlyStatus(self._root_checkpointable, ops.uid()) in_graph_mode = not context.executing_eagerly() if in_graph_mode: if self._file_prefix_placeholder is None: with ops.device("/cpu:0"): self._file_prefix_placeholder = constant_op.constant("model") file_prefix_tensor = self._file_prefix_placeholder file_prefix_feed_dict = {self._file_prefix_placeholder: save_path} else: with ops.device("/cpu:0"): file_prefix_tensor = constant_op.constant(save_path) file_prefix_feed_dict = None reader = pywrap_tensorflow.NewCheckpointReader(save_path) try: object_graph_string = reader.get_tensor( checkpointable_lib.OBJECT_GRAPH_PROTO_KEY) except errors_impl.NotFoundError: return NameBasedSaverStatus(self, save_path) object_graph_proto = ( checkpointable_object_graph_pb2.CheckpointableObjectGraph()) object_graph_proto.ParseFromString(object_graph_string) if in_graph_mode and object_graph_proto == self._last_restore_object_graph: checkpoint = self._last_restore_checkpoint else: if in_graph_mode: dtype_map = None else: dtype_map = reader.get_variable_to_dtype_map() checkpoint = _CheckpointRestoreCoordinator( object_graph_proto=object_graph_proto, save_path=file_prefix_tensor, dtype_map=dtype_map) if in_graph_mode: if self._last_restore_object_graph is not None: raise NotImplementedError( "Using a single Saver to restore different object graphs is not " "currently supported when graph building. Use a different Saver " "for each object graph (restore ops will be duplicated), or " "file a feature request if this limitation bothers you.") self._last_restore_checkpoint = checkpoint self._last_restore_object_graph = object_graph_proto checkpointable_lib._CheckpointPosition( checkpoint=checkpoint, proto_id=0).restore(self._root_checkpointable) load_status = CheckpointLoadStatus( checkpoint, root_checkpointable=self._root_checkpointable, feed_dict=file_prefix_feed_dict) return load_status @tf_export("train.Checkpoint") class Checkpoint(checkpointable_lib.Checkpointable): def __init__(self, **kwargs): super(Checkpoint, self).__init__() for k, v in sorted(kwargs.items(), key=lambda item: item[0]): if not isinstance(v, checkpointable_lib.CheckpointableBase): raise ValueError( ("`Checkpoint` was expecting a checkpointable object (an object " "derived from `CheckpointableBase`), got %s. If you believe this " "object should be checkpointable (i.e. it is part of the " "TensorFlow Python API and manages state), please open an issue.") % (v,)) setattr(self, k, v) self._save_counter = None self._saver = CheckpointableSaver(weakref.ref(self)) def _maybe_create_save_counter(self): if self._save_counter is None: with ops.device("/cpu:0"): self._save_counter = add_variable( self, name="save_counter", initializer=0, dtype=dtypes.int64) @property def save_counter(self): self._maybe_create_save_counter() return self._save_counter def save(self, file_prefix, session=None): in_graph_mode = not context.executing_eagerly() if in_graph_mode: if session is None: session = ops.get_default_session() if self._save_counter is None: session.run(self.save_counter.initializer) with ops.colocate_with(self.save_counter): assign_op = self.save_counter.assign_add(1) if in_graph_mode: session.run(assign_op) return self._saver.save( file_prefix=file_prefix, checkpoint_number=self.save_counter, session=session) def restore(self, save_path): status = self._saver.restore(save_path=save_path) self._maybe_create_save_counter() return status
true
true
f7149e143f5585d098d18b700bb17a159cb42dc1
14,337
py
Python
airflow/api/common/experimental/mark_tasks.py
crunchbase/incubator-airflow
903e37a09f05f4ab022bb7153be8dc62b3d9da99
[ "Apache-2.0" ]
null
null
null
airflow/api/common/experimental/mark_tasks.py
crunchbase/incubator-airflow
903e37a09f05f4ab022bb7153be8dc62b3d9da99
[ "Apache-2.0" ]
22
2019-12-09T23:22:07.000Z
2021-05-12T23:15:40.000Z
airflow/api/common/experimental/mark_tasks.py
crunchbase/incubator-airflow
903e37a09f05f4ab022bb7153be8dc62b3d9da99
[ "Apache-2.0" ]
5
2019-11-18T13:19:29.000Z
2020-03-25T13:20:29.000Z
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Marks tasks APIs.""" import datetime from typing import Iterable from sqlalchemy import or_ from airflow.jobs import BackfillJob from airflow.models import BaseOperator, DagRun, TaskInstance from airflow.operators.subdag_operator import SubDagOperator from airflow.utils import timezone from airflow.utils.db import provide_session from airflow.utils.state import State def _create_dagruns(dag, execution_dates, state, run_id_template): """ Infers from the dates which dag runs need to be created and does so. :param dag: the dag to create dag runs for :param execution_dates: list of execution dates to evaluate :param state: the state to set the dag run to :param run_id_template:the template for run id to be with the execution date :return: newly created and existing dag runs for the execution dates supplied """ # find out if we need to create any dag runs dag_runs = DagRun.find(dag_id=dag.dag_id, execution_date=execution_dates) dates_to_create = list(set(execution_dates) - {dag_run.execution_date for dag_run in dag_runs}) for date in dates_to_create: dag_run = dag.create_dagrun( run_id=run_id_template.format(date.isoformat()), execution_date=date, start_date=timezone.utcnow(), external_trigger=False, state=state, ) dag_runs.append(dag_run) return dag_runs @provide_session def set_state( tasks, # type: Iterable[BaseOperator] execution_date, # type: datetime.datetime upstream=False, downstream=False, future=False, past=False, state=State.SUCCESS, commit=False, session=None): # pylint: disable=too-many-arguments,too-many-locals """ Set the state of a task instance and if needed its relatives. Can set state for future tasks (calculated from execution_date) and retroactively for past tasks. Will verify integrity of past dag runs in order to create tasks that did not exist. It will not create dag runs that are missing on the schedule (but it will as for subdag dag runs if needed). :param task: the task from which to work. task.task.dag needs to be set :param execution_date: the execution date from which to start looking :param upstream: Mark all parents (upstream tasks) :param downstream: Mark all siblings (downstream tasks) of task_id, including SubDags :param future: Mark all future tasks on the interval of the dag up until last execution date. :param past: Retroactively mark all tasks starting from start_date of the DAG :param state: State to which the tasks need to be set :param commit: Commit tasks to be altered to the database :param session: database session :return: list of tasks that have been created and updated """ if not tasks: return [] if not timezone.is_localized(execution_date): raise ValueError("Received non-localized date {}".format(execution_date)) task_dags = {task.dag for task in tasks} if len(task_dags) > 1: raise ValueError("Received tasks from multiple DAGs: {}".format(task_dags)) dag = next(iter(task_dags)) if dag is None: raise ValueError("Received tasks with no DAG") dates = get_execution_dates(dag, execution_date, future, past) task_ids = list(find_task_relatives(tasks, downstream, upstream)) confirmed_dates = verify_dag_run_integrity(dag, dates) sub_dag_run_ids = get_subdag_runs(dag, session, state, task_ids, commit, confirmed_dates) # now look for the task instances that are affected qry_dag = get_all_dag_task_query(dag, session, state, task_ids, confirmed_dates) if commit: tis_altered = qry_dag.with_for_update().all() if sub_dag_run_ids: qry_sub_dag = all_subdag_tasks_query(sub_dag_run_ids, session, state, confirmed_dates) tis_altered += qry_sub_dag.with_for_update().all() for task_instance in tis_altered: task_instance.state = state else: tis_altered = qry_dag.all() if sub_dag_run_ids: qry_sub_dag = all_subdag_tasks_query(sub_dag_run_ids, session, state, confirmed_dates) tis_altered += qry_sub_dag.all() return tis_altered # Flake and pylint disagree about correct indents here def all_subdag_tasks_query(sub_dag_run_ids, session, state, confirmed_dates): # noqa: E123 """Get *all* tasks of the sub dags""" qry_sub_dag = session.query(TaskInstance).\ filter( TaskInstance.dag_id.in_(sub_dag_run_ids), TaskInstance.execution_date.in_(confirmed_dates) # noqa: E123 ).\ filter( or_( TaskInstance.state.is_(None), TaskInstance.state != state ) ) # noqa: E123 return qry_sub_dag def get_all_dag_task_query(dag, session, state, task_ids, confirmed_dates): # noqa: E123 """Get all tasks of the main dag that will be affected by a state change""" qry_dag = session.query(TaskInstance).\ filter( TaskInstance.dag_id == dag.dag_id, TaskInstance.execution_date.in_(confirmed_dates), TaskInstance.task_id.in_(task_ids) # noqa: E123 ).\ filter( or_( TaskInstance.state.is_(None), TaskInstance.state != state ) ) return qry_dag def get_subdag_runs(dag, session, state, task_ids, commit, confirmed_dates): """Go through subdag operators and create dag runs. We will only work within the scope of the subdag. We wont propagate to the parent dag, but we will propagate from parent to subdag. """ dags = [dag] sub_dag_ids = [] while dags: current_dag = dags.pop() for task_id in task_ids: if not current_dag.has_task(task_id): continue current_task = current_dag.get_task(task_id) if isinstance(current_task, SubDagOperator): # this works as a kind of integrity check # it creates missing dag runs for subdag operators, # maybe this should be moved to dagrun.verify_integrity dag_runs = _create_dagruns(current_task.subdag, execution_dates=confirmed_dates, state=State.RUNNING, run_id_template=BackfillJob.ID_FORMAT_PREFIX) verify_dagruns(dag_runs, commit, state, session, current_task) dags.append(current_task.subdag) sub_dag_ids.append(current_task.subdag.dag_id) return sub_dag_ids def verify_dagruns(dag_runs, commit, state, session, current_task): """Verifies integrity of dag_runs. :param dag_runs: dag runs to verify :param commit: whether dag runs state should be updated :param state: state of the dag_run to set if commit is True :param session: session to use :param current_task: current task :return: """ for dag_run in dag_runs: dag_run.dag = current_task.subdag dag_run.verify_integrity() if commit: dag_run.state = state session.merge(dag_run) def verify_dag_run_integrity(dag, dates): """Verify the integrity of the dag runs in case a task was added or removed set the confirmed execution dates as they might be different from what was provided """ confirmed_dates = [] dag_runs = DagRun.find(dag_id=dag.dag_id, execution_date=dates) for dag_run in dag_runs: dag_run.dag = dag dag_run.verify_integrity() confirmed_dates.append(dag_run.execution_date) return confirmed_dates def find_task_relatives(tasks, downstream, upstream): """Yield task ids and optionally ancestor and descendant ids.""" for task in tasks: yield task.task_id if downstream: for relative in task.get_flat_relatives(upstream=False): yield relative.task_id if upstream: for relative in task.get_flat_relatives(upstream=True): yield relative.task_id def get_execution_dates(dag, execution_date, future, past): """Returns dates of DAG execution""" latest_execution_date = dag.latest_execution_date if latest_execution_date is None: raise ValueError("Received non-localized date {}".format(execution_date)) # determine date range of dag runs and tasks to consider end_date = latest_execution_date if future else execution_date if 'start_date' in dag.default_args: start_date = dag.default_args['start_date'] elif dag.start_date: start_date = dag.start_date else: start_date = execution_date start_date = execution_date if not past else start_date if dag.schedule_interval == '@once': dates = [start_date] elif not dag.schedule_interval: # If schedule_interval is None, need to look at existing DagRun if the user wants future or # past runs. dag_runs = dag.get_dagruns_between(start_date=start_date, end_date=end_date) dates = sorted({d.execution_date for d in dag_runs}) else: dates = dag.date_range(start_date=start_date, end_date=end_date) return dates @provide_session def _set_dag_run_state(dag_id, execution_date, state, session=None): """ Helper method that set dag run state in the DB. :param dag_id: dag_id of target dag run :param execution_date: the execution date from which to start looking :param state: target state :param session: database session """ dag_run = session.query(DagRun).filter( DagRun.dag_id == dag_id, DagRun.execution_date == execution_date ).one() dag_run.state = state if state == State.RUNNING: dag_run.start_date = timezone.utcnow() dag_run.end_date = None else: dag_run.end_date = timezone.utcnow() session.merge(dag_run) @provide_session def set_dag_run_state_to_success(dag, execution_date, commit=False, session=None): """ Set the dag run for a specific execution date and its task instances to success. :param dag: the DAG of which to alter state :param execution_date: the execution date from which to start looking :param commit: commit DAG and tasks to be altered to the database :param session: database session :return: If commit is true, list of tasks that have been updated, otherwise list of tasks that will be updated :raises: ValueError if dag or execution_date is invalid """ if not dag or not execution_date: return [] # Mark the dag run to success. if commit: _set_dag_run_state(dag.dag_id, execution_date, State.SUCCESS, session) # Mark all task instances of the dag run to success. for task in dag.tasks: task.dag = dag return set_state(tasks=dag.tasks, execution_date=execution_date, state=State.SUCCESS, commit=commit, session=session) @provide_session def set_dag_run_state_to_failed(dag, execution_date, commit=False, session=None): """ Set the dag run for a specific execution date and its running task instances to failed. :param dag: the DAG of which to alter state :param execution_date: the execution date from which to start looking :param commit: commit DAG and tasks to be altered to the database :param session: database session :return: If commit is true, list of tasks that have been updated, otherwise list of tasks that will be updated :raises: AssertionError if dag or execution_date is invalid """ if not dag or not execution_date: return [] # Mark the dag run to failed. if commit: _set_dag_run_state(dag.dag_id, execution_date, State.FAILED, session) # Mark only RUNNING task instances. task_ids = [task.task_id for task in dag.tasks] tis = session.query(TaskInstance).filter( TaskInstance.dag_id == dag.dag_id, TaskInstance.execution_date == execution_date, TaskInstance.task_id.in_(task_ids)).filter(TaskInstance.state == State.RUNNING) task_ids_of_running_tis = [task_instance.task_id for task_instance in tis] tasks = [] for task in dag.tasks: if task.task_id not in task_ids_of_running_tis: continue task.dag = dag tasks.append(task) return set_state(tasks=tasks, execution_date=execution_date, state=State.FAILED, commit=commit, session=session) @provide_session def set_dag_run_state_to_running(dag, execution_date, commit=False, session=None): """ Set the dag run for a specific execution date to running. :param dag: the DAG of which to alter state :param execution_date: the execution date from which to start looking :param commit: commit DAG and tasks to be altered to the database :param session: database session :return: If commit is true, list of tasks that have been updated, otherwise list of tasks that will be updated """ res = [] if not dag or not execution_date: return res # Mark the dag run to running. if commit: _set_dag_run_state(dag.dag_id, execution_date, State.RUNNING, session) # To keep the return type consistent with the other similar functions. return res
38.334225
99
0.68515
import datetime from typing import Iterable from sqlalchemy import or_ from airflow.jobs import BackfillJob from airflow.models import BaseOperator, DagRun, TaskInstance from airflow.operators.subdag_operator import SubDagOperator from airflow.utils import timezone from airflow.utils.db import provide_session from airflow.utils.state import State def _create_dagruns(dag, execution_dates, state, run_id_template): dag_runs = DagRun.find(dag_id=dag.dag_id, execution_date=execution_dates) dates_to_create = list(set(execution_dates) - {dag_run.execution_date for dag_run in dag_runs}) for date in dates_to_create: dag_run = dag.create_dagrun( run_id=run_id_template.format(date.isoformat()), execution_date=date, start_date=timezone.utcnow(), external_trigger=False, state=state, ) dag_runs.append(dag_run) return dag_runs @provide_session def set_state( tasks, execution_date, upstream=False, downstream=False, future=False, past=False, state=State.SUCCESS, commit=False, session=None): if not tasks: return [] if not timezone.is_localized(execution_date): raise ValueError("Received non-localized date {}".format(execution_date)) task_dags = {task.dag for task in tasks} if len(task_dags) > 1: raise ValueError("Received tasks from multiple DAGs: {}".format(task_dags)) dag = next(iter(task_dags)) if dag is None: raise ValueError("Received tasks with no DAG") dates = get_execution_dates(dag, execution_date, future, past) task_ids = list(find_task_relatives(tasks, downstream, upstream)) confirmed_dates = verify_dag_run_integrity(dag, dates) sub_dag_run_ids = get_subdag_runs(dag, session, state, task_ids, commit, confirmed_dates) qry_dag = get_all_dag_task_query(dag, session, state, task_ids, confirmed_dates) if commit: tis_altered = qry_dag.with_for_update().all() if sub_dag_run_ids: qry_sub_dag = all_subdag_tasks_query(sub_dag_run_ids, session, state, confirmed_dates) tis_altered += qry_sub_dag.with_for_update().all() for task_instance in tis_altered: task_instance.state = state else: tis_altered = qry_dag.all() if sub_dag_run_ids: qry_sub_dag = all_subdag_tasks_query(sub_dag_run_ids, session, state, confirmed_dates) tis_altered += qry_sub_dag.all() return tis_altered def all_subdag_tasks_query(sub_dag_run_ids, session, state, confirmed_dates): qry_sub_dag = session.query(TaskInstance).\ filter( TaskInstance.dag_id.in_(sub_dag_run_ids), TaskInstance.execution_date.in_(confirmed_dates) ).\ filter( or_( TaskInstance.state.is_(None), TaskInstance.state != state ) ) return qry_sub_dag def get_all_dag_task_query(dag, session, state, task_ids, confirmed_dates): qry_dag = session.query(TaskInstance).\ filter( TaskInstance.dag_id == dag.dag_id, TaskInstance.execution_date.in_(confirmed_dates), TaskInstance.task_id.in_(task_ids) ).\ filter( or_( TaskInstance.state.is_(None), TaskInstance.state != state ) ) return qry_dag def get_subdag_runs(dag, session, state, task_ids, commit, confirmed_dates): dags = [dag] sub_dag_ids = [] while dags: current_dag = dags.pop() for task_id in task_ids: if not current_dag.has_task(task_id): continue current_task = current_dag.get_task(task_id) if isinstance(current_task, SubDagOperator): dag_runs = _create_dagruns(current_task.subdag, execution_dates=confirmed_dates, state=State.RUNNING, run_id_template=BackfillJob.ID_FORMAT_PREFIX) verify_dagruns(dag_runs, commit, state, session, current_task) dags.append(current_task.subdag) sub_dag_ids.append(current_task.subdag.dag_id) return sub_dag_ids def verify_dagruns(dag_runs, commit, state, session, current_task): for dag_run in dag_runs: dag_run.dag = current_task.subdag dag_run.verify_integrity() if commit: dag_run.state = state session.merge(dag_run) def verify_dag_run_integrity(dag, dates): confirmed_dates = [] dag_runs = DagRun.find(dag_id=dag.dag_id, execution_date=dates) for dag_run in dag_runs: dag_run.dag = dag dag_run.verify_integrity() confirmed_dates.append(dag_run.execution_date) return confirmed_dates def find_task_relatives(tasks, downstream, upstream): for task in tasks: yield task.task_id if downstream: for relative in task.get_flat_relatives(upstream=False): yield relative.task_id if upstream: for relative in task.get_flat_relatives(upstream=True): yield relative.task_id def get_execution_dates(dag, execution_date, future, past): latest_execution_date = dag.latest_execution_date if latest_execution_date is None: raise ValueError("Received non-localized date {}".format(execution_date)) end_date = latest_execution_date if future else execution_date if 'start_date' in dag.default_args: start_date = dag.default_args['start_date'] elif dag.start_date: start_date = dag.start_date else: start_date = execution_date start_date = execution_date if not past else start_date if dag.schedule_interval == '@once': dates = [start_date] elif not dag.schedule_interval: dag_runs = dag.get_dagruns_between(start_date=start_date, end_date=end_date) dates = sorted({d.execution_date for d in dag_runs}) else: dates = dag.date_range(start_date=start_date, end_date=end_date) return dates @provide_session def _set_dag_run_state(dag_id, execution_date, state, session=None): dag_run = session.query(DagRun).filter( DagRun.dag_id == dag_id, DagRun.execution_date == execution_date ).one() dag_run.state = state if state == State.RUNNING: dag_run.start_date = timezone.utcnow() dag_run.end_date = None else: dag_run.end_date = timezone.utcnow() session.merge(dag_run) @provide_session def set_dag_run_state_to_success(dag, execution_date, commit=False, session=None): if not dag or not execution_date: return [] if commit: _set_dag_run_state(dag.dag_id, execution_date, State.SUCCESS, session) for task in dag.tasks: task.dag = dag return set_state(tasks=dag.tasks, execution_date=execution_date, state=State.SUCCESS, commit=commit, session=session) @provide_session def set_dag_run_state_to_failed(dag, execution_date, commit=False, session=None): if not dag or not execution_date: return [] if commit: _set_dag_run_state(dag.dag_id, execution_date, State.FAILED, session) task_ids = [task.task_id for task in dag.tasks] tis = session.query(TaskInstance).filter( TaskInstance.dag_id == dag.dag_id, TaskInstance.execution_date == execution_date, TaskInstance.task_id.in_(task_ids)).filter(TaskInstance.state == State.RUNNING) task_ids_of_running_tis = [task_instance.task_id for task_instance in tis] tasks = [] for task in dag.tasks: if task.task_id not in task_ids_of_running_tis: continue task.dag = dag tasks.append(task) return set_state(tasks=tasks, execution_date=execution_date, state=State.FAILED, commit=commit, session=session) @provide_session def set_dag_run_state_to_running(dag, execution_date, commit=False, session=None): res = [] if not dag or not execution_date: return res if commit: _set_dag_run_state(dag.dag_id, execution_date, State.RUNNING, session) return res
true
true
f7149e2412d81d75a93d4991ff57ab4e7bd62d19
1,125
py
Python
laplace/__init__.py
georgezefko/Laplace
c488f7bf739297bab5d771f65635352a07716ca0
[ "MIT" ]
null
null
null
laplace/__init__.py
georgezefko/Laplace
c488f7bf739297bab5d771f65635352a07716ca0
[ "MIT" ]
null
null
null
laplace/__init__.py
georgezefko/Laplace
c488f7bf739297bab5d771f65635352a07716ca0
[ "MIT" ]
null
null
null
""" .. include:: ../README.md .. include:: ../examples/regression_example.md .. include:: ../examples/calibration_example.md """ REGRESSION = 'regression' CLASSIFICATION = 'classification' from laplace.baselaplace import BaseLaplace, ParametricLaplace, FullLaplace, KronLaplace, DiagLaplace, LowRankLaplace from laplace.lllaplace import LLLaplace, FullLLLaplace, KronLLLaplace, DiagLLLaplace from laplace.subnetlaplace import SubnetLaplace, FullSubnetLaplace, DiagSubnetLaplace from laplace.laplace import Laplace from laplace.marglik_training import marglik_training __all__ = ['Laplace', # direct access to all Laplace classes via unified interface 'BaseLaplace', 'ParametricLaplace', # base-class and its (first-level) subclasses 'FullLaplace', 'KronLaplace', 'DiagLaplace', 'LowRankLaplace', # all-weights 'LLLaplace', # base-class last-layer 'FullLLLaplace', 'KronLLLaplace', 'DiagLLLaplace', # last-layer 'SubnetLaplace', # base-class subnetwork 'FullSubnetLaplace', 'DiagSubnetLaplace', # subnetwork 'marglik_training'] # methods
46.875
117
0.734222
REGRESSION = 'regression' CLASSIFICATION = 'classification' from laplace.baselaplace import BaseLaplace, ParametricLaplace, FullLaplace, KronLaplace, DiagLaplace, LowRankLaplace from laplace.lllaplace import LLLaplace, FullLLLaplace, KronLLLaplace, DiagLLLaplace from laplace.subnetlaplace import SubnetLaplace, FullSubnetLaplace, DiagSubnetLaplace from laplace.laplace import Laplace from laplace.marglik_training import marglik_training __all__ = ['Laplace', 'BaseLaplace', 'ParametricLaplace', 'FullLaplace', 'KronLaplace', 'DiagLaplace', 'LowRankLaplace', 'LLLaplace', 'FullLLLaplace', 'KronLLLaplace', 'DiagLLLaplace', 'SubnetLaplace', 'FullSubnetLaplace', 'DiagSubnetLaplace', 'marglik_training']
true
true
f7149e6533709c3087902b7fa956335e88e12f63
450
py
Python
paperplane/backends/click/echo.py
abhilash1in/paperplane
1dfda182dc8a70fe08fa2284ea63b434246c394b
[ "MIT" ]
null
null
null
paperplane/backends/click/echo.py
abhilash1in/paperplane
1dfda182dc8a70fe08fa2284ea63b434246c394b
[ "MIT" ]
null
null
null
paperplane/backends/click/echo.py
abhilash1in/paperplane
1dfda182dc8a70fe08fa2284ea63b434246c394b
[ "MIT" ]
null
null
null
import logging from typing import Optional from paperplane.backends.click import _secho logger = logging.getLogger(__name__) def run( prompt: str, color: Optional[str] = None, fg: Optional[str] = None, bg: Optional[str] = None, bold: Optional[bool] = False, ): if prompt is not None: return _secho(message=prompt, fg=color or fg, bg=bg, bold=bold) else: logger.warning("prompt is None. Nothing to do.")
23.684211
71
0.668889
import logging from typing import Optional from paperplane.backends.click import _secho logger = logging.getLogger(__name__) def run( prompt: str, color: Optional[str] = None, fg: Optional[str] = None, bg: Optional[str] = None, bold: Optional[bool] = False, ): if prompt is not None: return _secho(message=prompt, fg=color or fg, bg=bg, bold=bold) else: logger.warning("prompt is None. Nothing to do.")
true
true
f7149f74e1c827d11855a1dd871ba6c9659096d7
9,270
py
Python
trac/web/tests/auth.py
lelit/trac
ee8f811a29321f3c0fc8b8235d143e0ffcd6d013
[ "BSD-3-Clause" ]
1
2017-08-03T07:04:28.000Z
2017-08-03T07:04:28.000Z
trac/web/tests/auth.py
lelit/trac
ee8f811a29321f3c0fc8b8235d143e0ffcd6d013
[ "BSD-3-Clause" ]
null
null
null
trac/web/tests/auth.py
lelit/trac
ee8f811a29321f3c0fc8b8235d143e0ffcd6d013
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2013 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. import os import trac.tests.compat from trac.core import TracError from trac.test import EnvironmentStub, Mock from trac.web.auth import BasicAuthentication, LoginModule from trac.web.href import Href from Cookie import SimpleCookie as Cookie import unittest class LoginModuleTestCase(unittest.TestCase): def setUp(self): self.env = EnvironmentStub() self.module = LoginModule(self.env) def tearDown(self): self.env.reset_db() def test_anonymous_access(self): req = Mock(incookie=Cookie(), href=Href('/trac.cgi'), remote_addr='127.0.0.1', remote_user=None, base_path='/trac.cgi') self.assertIsNone(self.module.authenticate(req)) def test_unknown_cookie_access(self): incookie = Cookie() incookie['trac_auth'] = '123' req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=Cookie(), remote_addr='127.0.0.1', remote_user=None, base_path='/trac.cgi') self.assertIsNone(self.module.authenticate(req)) def test_known_cookie_access(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(incookie=incookie, outcookie=outcookie, href=Href('/trac.cgi'), base_path='/trac.cgi', remote_addr='127.0.0.1', remote_user=None) self.assertEqual('john', self.module.authenticate(req)) self.assertNotIn('auth_cookie', req.outcookie) def test_known_cookie_ip_check_enabled(self): self.env.config.set('trac', 'check_auth_ip', 'yes') self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=outcookie, remote_addr='192.168.0.100', remote_user=None, base_path='/trac.cgi') self.assertIsNone(self.module.authenticate(req)) self.assertIn('trac_auth', req.outcookie) def test_known_cookie_ip_check_disabled(self): self.env.config.set('trac', 'check_auth_ip', 'no') self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(incookie=incookie, outcookie=outcookie, href=Href('/trac.cgi'), base_path='/trac.cgi', remote_addr='192.168.0.100', remote_user=None) self.assertEqual('john', self.module.authenticate(req)) self.assertNotIn('auth_cookie', req.outcookie) def test_login(self): outcookie = Cookie() # remote_user must be upper case to test that by default, case is # preserved. req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=Cookie(), outcookie=outcookie, remote_addr='127.0.0.1', remote_user='john', authname='john', base_path='/trac.cgi') self.module._do_login(req) self.assertIn('trac_auth', outcookie, '"trac_auth" Cookie not set') auth_cookie = outcookie['trac_auth'].value self.assertEqual([('john', '127.0.0.1')], self.env.db_query( "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s", (auth_cookie,))) def test_login_ignore_case(self): """ Test that login is succesful when the usernames differ in case, but case is ignored. """ self.env.config.set('trac', 'ignore_auth_case', 'yes') outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=Cookie(), outcookie=outcookie, remote_addr='127.0.0.1', remote_user='John', authname='anonymous', base_path='/trac.cgi') self.module._do_login(req) self.assertIn('trac_auth', outcookie, '"trac_auth" Cookie not set') auth_cookie = outcookie['trac_auth'].value self.assertEqual([('john', '127.0.0.1')], self.env.db_query( "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s", (auth_cookie,))) def test_login_no_username(self): req = Mock(incookie=Cookie(), href=Href('/trac.cgi'), remote_addr='127.0.0.1', remote_user=None, base_path='/trac.cgi') self.assertRaises(TracError, self.module._do_login, req) def test_already_logged_in_same_user(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' req = Mock(incookie=incookie, outcookie=Cookie(), href=Href('/trac.cgi'), base_path='/trac.cgi', remote_addr='127.0.0.1', remote_user='john', authname='john') self.module._do_login(req) # this shouldn't raise an error def test_already_logged_in_different_user(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' req = Mock(incookie=incookie, authname='john', href=Href('/trac.cgi'), base_path='/trac.cgi', remote_addr='127.0.0.1', remote_user='tom') self.assertRaises(TracError, self.module._do_login, req) def test_logout(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=outcookie, remote_addr='127.0.0.1', remote_user=None, authname='john', method='POST', base_path='/trac.cgi') self.module._do_logout(req) self.assertIn('trac_auth', outcookie) self.assertFalse(self.env.db_query( "SELECT name, ipnr FROM auth_cookie WHERE name='john'")) def test_logout_not_logged_in(self): req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=Cookie(), outcookie=Cookie(), remote_addr='127.0.0.1', remote_user=None, authname='anonymous', method='POST', base_path='/trac.cgi') self.module._do_logout(req) # this shouldn't raise an error def test_logout_protect(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=outcookie, remote_addr='127.0.0.1', remote_user=None, authname='john', method='GET', base_path='/trac.cgi') self.module._do_logout(req) self.assertNotIn('trac_auth', outcookie) self.assertEqual( [('john', '127.0.0.1')], self.env.db_query("SELECT name, ipnr FROM auth_cookie " "WHERE cookie='123'")) class BasicAuthenticationTestCase(unittest.TestCase): def setUp(self): filename = os.path.join(os.path.split(__file__)[0], 'htpasswd.txt') self.auth = BasicAuthentication(filename, 'realm') def tearDown(self): self.auth = None def test_crypt(self): self.assertTrue(self.auth.test('crypt', 'crypt')) self.assertFalse(self.auth.test('crypt', 'other')) def test_md5(self): self.assertTrue(self.auth.test('md5', 'md5')) self.assertFalse(self.auth.test('md5', 'other')) def test_sha(self): self.assertTrue(self.auth.test('sha', 'sha')) self.assertFalse(self.auth.test('sha', 'other')) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(LoginModuleTestCase)) suite.addTest(unittest.makeSuite(BasicAuthenticationTestCase)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
40.480349
80
0.602697
import os import trac.tests.compat from trac.core import TracError from trac.test import EnvironmentStub, Mock from trac.web.auth import BasicAuthentication, LoginModule from trac.web.href import Href from Cookie import SimpleCookie as Cookie import unittest class LoginModuleTestCase(unittest.TestCase): def setUp(self): self.env = EnvironmentStub() self.module = LoginModule(self.env) def tearDown(self): self.env.reset_db() def test_anonymous_access(self): req = Mock(incookie=Cookie(), href=Href('/trac.cgi'), remote_addr='127.0.0.1', remote_user=None, base_path='/trac.cgi') self.assertIsNone(self.module.authenticate(req)) def test_unknown_cookie_access(self): incookie = Cookie() incookie['trac_auth'] = '123' req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=Cookie(), remote_addr='127.0.0.1', remote_user=None, base_path='/trac.cgi') self.assertIsNone(self.module.authenticate(req)) def test_known_cookie_access(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(incookie=incookie, outcookie=outcookie, href=Href('/trac.cgi'), base_path='/trac.cgi', remote_addr='127.0.0.1', remote_user=None) self.assertEqual('john', self.module.authenticate(req)) self.assertNotIn('auth_cookie', req.outcookie) def test_known_cookie_ip_check_enabled(self): self.env.config.set('trac', 'check_auth_ip', 'yes') self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=outcookie, remote_addr='192.168.0.100', remote_user=None, base_path='/trac.cgi') self.assertIsNone(self.module.authenticate(req)) self.assertIn('trac_auth', req.outcookie) def test_known_cookie_ip_check_disabled(self): self.env.config.set('trac', 'check_auth_ip', 'no') self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(incookie=incookie, outcookie=outcookie, href=Href('/trac.cgi'), base_path='/trac.cgi', remote_addr='192.168.0.100', remote_user=None) self.assertEqual('john', self.module.authenticate(req)) self.assertNotIn('auth_cookie', req.outcookie) def test_login(self): outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=Cookie(), outcookie=outcookie, remote_addr='127.0.0.1', remote_user='john', authname='john', base_path='/trac.cgi') self.module._do_login(req) self.assertIn('trac_auth', outcookie, '"trac_auth" Cookie not set') auth_cookie = outcookie['trac_auth'].value self.assertEqual([('john', '127.0.0.1')], self.env.db_query( "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s", (auth_cookie,))) def test_login_ignore_case(self): self.env.config.set('trac', 'ignore_auth_case', 'yes') outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=Cookie(), outcookie=outcookie, remote_addr='127.0.0.1', remote_user='John', authname='anonymous', base_path='/trac.cgi') self.module._do_login(req) self.assertIn('trac_auth', outcookie, '"trac_auth" Cookie not set') auth_cookie = outcookie['trac_auth'].value self.assertEqual([('john', '127.0.0.1')], self.env.db_query( "SELECT name, ipnr FROM auth_cookie WHERE cookie=%s", (auth_cookie,))) def test_login_no_username(self): req = Mock(incookie=Cookie(), href=Href('/trac.cgi'), remote_addr='127.0.0.1', remote_user=None, base_path='/trac.cgi') self.assertRaises(TracError, self.module._do_login, req) def test_already_logged_in_same_user(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' req = Mock(incookie=incookie, outcookie=Cookie(), href=Href('/trac.cgi'), base_path='/trac.cgi', remote_addr='127.0.0.1', remote_user='john', authname='john') self.module._do_login(req) def test_already_logged_in_different_user(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' req = Mock(incookie=incookie, authname='john', href=Href('/trac.cgi'), base_path='/trac.cgi', remote_addr='127.0.0.1', remote_user='tom') self.assertRaises(TracError, self.module._do_login, req) def test_logout(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=outcookie, remote_addr='127.0.0.1', remote_user=None, authname='john', method='POST', base_path='/trac.cgi') self.module._do_logout(req) self.assertIn('trac_auth', outcookie) self.assertFalse(self.env.db_query( "SELECT name, ipnr FROM auth_cookie WHERE name='john'")) def test_logout_not_logged_in(self): req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=Cookie(), outcookie=Cookie(), remote_addr='127.0.0.1', remote_user=None, authname='anonymous', method='POST', base_path='/trac.cgi') self.module._do_logout(req) # this shouldn't raise an error def test_logout_protect(self): self.env.db_transaction(""" INSERT INTO auth_cookie (cookie, name, ipnr) VALUES ('123', 'john', '127.0.0.1')""") incookie = Cookie() incookie['trac_auth'] = '123' outcookie = Cookie() req = Mock(cgi_location='/trac', href=Href('/trac.cgi'), incookie=incookie, outcookie=outcookie, remote_addr='127.0.0.1', remote_user=None, authname='john', method='GET', base_path='/trac.cgi') self.module._do_logout(req) self.assertNotIn('trac_auth', outcookie) self.assertEqual( [('john', '127.0.0.1')], self.env.db_query("SELECT name, ipnr FROM auth_cookie " "WHERE cookie='123'")) class BasicAuthenticationTestCase(unittest.TestCase): def setUp(self): filename = os.path.join(os.path.split(__file__)[0], 'htpasswd.txt') self.auth = BasicAuthentication(filename, 'realm') def tearDown(self): self.auth = None def test_crypt(self): self.assertTrue(self.auth.test('crypt', 'crypt')) self.assertFalse(self.auth.test('crypt', 'other')) def test_md5(self): self.assertTrue(self.auth.test('md5', 'md5')) self.assertFalse(self.auth.test('md5', 'other')) def test_sha(self): self.assertTrue(self.auth.test('sha', 'sha')) self.assertFalse(self.auth.test('sha', 'other')) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(LoginModuleTestCase)) suite.addTest(unittest.makeSuite(BasicAuthenticationTestCase)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
true
true
f7149f8bfbbe334b4581ab62205607d9646fef42
1,364
py
Python
tests/test_download.py
iacopoff/climetlab
cc01604de991928018291725407d891f3c01ce5b
[ "Apache-2.0" ]
null
null
null
tests/test_download.py
iacopoff/climetlab
cc01604de991928018291725407d891f3c01ce5b
[ "Apache-2.0" ]
null
null
null
tests/test_download.py
iacopoff/climetlab
cc01604de991928018291725407d891f3c01ce5b
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmental organisation # nor does it submit to any jurisdiction. # import os import pathlib import time from climetlab import settings from climetlab.utils import download_and_cache def path_to_url(path): return pathlib.Path(os.path.abspath(path)).as_uri() def test_download_1(): url = "https://github.com/ecmwf/climetlab/raw/main/docs/examples/test.grib?_=%s" % ( time.time(), ) download_and_cache(url) def test_download_2(): url = "https://github.com/ecmwf/climetlab/raw/main/docs/examples/test.grib" download_and_cache(url) def test_download_3(): with settings.temporary("download-out-of-date-urls", True): url = "https://get.ecmwf.int/test-data/climetlab/input/test.txt" download_and_cache(url) def test_download_4(): url = "https://get.ecmwf.int/test-data/climetlab/input/missing.txt" r = download_and_cache(url, return_none_on_404=True) assert r is None, r if __name__ == "__main__": from climetlab.testing import main main(globals())
26.230769
88
0.725806
import os import pathlib import time from climetlab import settings from climetlab.utils import download_and_cache def path_to_url(path): return pathlib.Path(os.path.abspath(path)).as_uri() def test_download_1(): url = "https://github.com/ecmwf/climetlab/raw/main/docs/examples/test.grib?_=%s" % ( time.time(), ) download_and_cache(url) def test_download_2(): url = "https://github.com/ecmwf/climetlab/raw/main/docs/examples/test.grib" download_and_cache(url) def test_download_3(): with settings.temporary("download-out-of-date-urls", True): url = "https://get.ecmwf.int/test-data/climetlab/input/test.txt" download_and_cache(url) def test_download_4(): url = "https://get.ecmwf.int/test-data/climetlab/input/missing.txt" r = download_and_cache(url, return_none_on_404=True) assert r is None, r if __name__ == "__main__": from climetlab.testing import main main(globals())
true
true
f7149ff103223405ef329d427e9cce2551ef21f0
207
py
Python
vet_website/vet_website/doctype/vetasset/test_vetasset.py
rezazrna/vet_website
26e731cb10c31d69292f33659c49c3cfa5646c39
[ "MIT" ]
null
null
null
vet_website/vet_website/doctype/vetasset/test_vetasset.py
rezazrna/vet_website
26e731cb10c31d69292f33659c49c3cfa5646c39
[ "MIT" ]
null
null
null
vet_website/vet_website/doctype/vetasset/test_vetasset.py
rezazrna/vet_website
26e731cb10c31d69292f33659c49c3cfa5646c39
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2020, bikbuk and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestVetAsset(unittest.TestCase): pass
18.818182
45
0.758454
from __future__ import unicode_literals import unittest class TestVetAsset(unittest.TestCase): pass
true
true
f714a04a559914d1915f3c51c7c305616a25454f
2,090
py
Python
setup.py
kruserr/i6
90a198ae543844faa1073d8bd317f11e1bb80298
[ "MIT" ]
1
2020-07-05T22:08:22.000Z
2020-07-05T22:08:22.000Z
setup.py
kruserr/i6
90a198ae543844faa1073d8bd317f11e1bb80298
[ "MIT" ]
null
null
null
setup.py
kruserr/i6
90a198ae543844faa1073d8bd317f11e1bb80298
[ "MIT" ]
null
null
null
import setuptools import urllib.request DESCRIPTION = 'A standardized collection of python libs and tools' try: with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() except FileNotFoundError: LONG_DESCRIPTION = DESCRIPTION try: with open('VERSION', 'r') as f: VERSION = f.read() except FileNotFoundError: VERSION = 'test' # To whenever PYPI allows direct references for dependencies # deps = [ # { # 'name': 'aiocheck', # 'url': 'https://github.com/kruserr/aiocheck', # 'tag': '', # }, # ] # for i in range(len(deps)): # try: # if (deps[i]['tag'] is None) or (len(deps[i]['tag']) == 0): # raise KeyError() # except KeyError: # request = urllib.request.urlopen(f"{deps[i]['url']}/releases/latest").geturl() # deps[i]['tag'] = request.split('/')[::-1][0] # deps[i] = f"{deps[i]['name']} @ git+{deps[i]['url']}@{deps[i]['tag']}" setuptools.setup( name='i6', version=VERSION, author='kruserr', description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type='text/markdown', url='https://github.com/kruserr/i6', keywords='i6 toolchain collection libs tools', project_urls={ 'Documentation': 'https://github.com/kruserr/i6/wiki', 'Source': 'https://github.com/kruserr/i6', }, packages=setuptools.find_packages( where='src', exclude=['tests*'], ), package_dir={ '': 'src', }, install_requires=[ 'docker', 'pyftpdlib', 'SQLAlchemy', 'marshmallow', 'cryptography', ], entry_points = { 'console_scripts': ['i6=i6.__main__:main'], }, zip_safe=True, classifiers=[ 'Topic :: Software Development', 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], python_requires='>=3.7', )
26.455696
88
0.574641
import setuptools import urllib.request DESCRIPTION = 'A standardized collection of python libs and tools' try: with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() except FileNotFoundError: LONG_DESCRIPTION = DESCRIPTION try: with open('VERSION', 'r') as f: VERSION = f.read() except FileNotFoundError: VERSION = 'test' setuptools.setup( name='i6', version=VERSION, author='kruserr', description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type='text/markdown', url='https://github.com/kruserr/i6', keywords='i6 toolchain collection libs tools', project_urls={ 'Documentation': 'https://github.com/kruserr/i6/wiki', 'Source': 'https://github.com/kruserr/i6', }, packages=setuptools.find_packages( where='src', exclude=['tests*'], ), package_dir={ '': 'src', }, install_requires=[ 'docker', 'pyftpdlib', 'SQLAlchemy', 'marshmallow', 'cryptography', ], entry_points = { 'console_scripts': ['i6=i6.__main__:main'], }, zip_safe=True, classifiers=[ 'Topic :: Software Development', 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], python_requires='>=3.7', )
true
true
f714a04aab9e0bff1e00c2120d335960fe4730f0
9,816
py
Python
surveysim/music2/interpolate.py
jakgel/clusterbuster
d79400a0faf43dece457d99b024b955aef544fc2
[ "MIT" ]
1
2018-09-10T14:06:45.000Z
2018-09-10T14:06:45.000Z
surveysim/music2/interpolate.py
jakgel/clusterbuster
d79400a0faf43dece457d99b024b955aef544fc2
[ "MIT" ]
null
null
null
surveysim/music2/interpolate.py
jakgel/clusterbuster
d79400a0faf43dece457d99b024b955aef544fc2
[ "MIT" ]
null
null
null
import numpy as np import scipy.interpolate as interpolate import matplotlib.pyplot as plt import clusterbuster.mathut as math """ Start with e.g. InterpolateRadio2D(psiFile = '../Analysis_MUSIC2/Hoeft_radio/mach_psi_tablefine(10,3).txt', inter=(10,6)) """ # from http://stackoverflow.com/questions/5328128/scipy-interpolation-of-large-matrix def my_interp(X, Y, Z, x, y, spn=3): xs,ys = map(np.array,(x,y)) z = np.zeros(xs.shape) for i,(x,y) in enumerate(zip(xs,ys)): # get the indices of the nearest x,y xi = np.argmin(np.abs(X[0,:]-x)) yi = np.argmin(np.abs(Y[:,0]-y)) xlo = max(xi-spn, 0) ylo = max(yi-spn, 0) xhi = min(xi+spn, X[0,:].size) yhi = min(yi+spn, Y[:,0].size) # make slices of X,Y,Z that are only a few items wide nX = X[xlo:xhi, ylo:yhi] nY = Y[xlo:xhi, ylo:yhi] nZ = Z[xlo:xhi, ylo:yhi] intp = interpolate.interp2d(nX, nY, nZ) z[i] = intp(x,y)[0] return z # from here on: done by myself def LoadFile_psi(psiFile): """ Just gives the Mach number and Temperature values """ #=== FILE A ===# # read first line .... split it and convert sstring to float science float('1.31E+01') or for a list:map(float, ['3.76E+00', '1.31E+01', '1.14E+01']) with open(psiFile, 'r') as f: first_line = f.readline() psi_x = first_line.split()[2:] # Splits into list without first two elements psi_x = np.asarray( [float(i) for i in psi_x ] ) # Converts strings to floats # Converts strings to floats psi_y = np.loadtxt(psiFile,skiprows=0)[:,0] return psi_x, psi_y def InterpolateRadio2D(psiFile='../Analysis_MUSIC2/Hoeft_radio/mach_psi_table.txt', machFile='../Analysis_MUSIC2/Hoeft_radio/q_mach_machr_table.txt', saveplot='../Analysis_MUSIC2/Hoeft_radio/interpolated', psiFileNew = False, machFileNew = False, inter=(10,3)): # Currently the mach number is interpolated in an logarithmic space which is much sparser at lower mach numbers then anticipated # I suspect an double-exponential function for mach (both efficiency dependency stepsize) # Note that the original grid given in 'Hoeft_radio/mach_psi_table.txt' is (quite) regular in log-loglog space, which makes it very simple to invoke an interpolation function! # Irregular data points would make it nececcary to use functions like scipy.interpolate.griddata(points, values, (grid_x, grid_y), method='cubic') plot_old = False plot_new = False plot_PhD = True ##==== psiFile for psi factor; machfile for mach-numbers conversion factors H_mach = np.loadtxt(machFile,skiprows=0) H_psi = np.loadtxt(psiFile,skiprows=0)[:,1::] # you wont get the temperature values ... read them separetely psi_x,psi_y = LoadFile_psi(psiFile) psi_x = np.log10( psi_x ) # converts to and log10 space psi_y = np.log10(np.log10( psi_y )) # converts to and log10(log10) space X, Y = np.meshgrid(psi_x, psi_y) Z = np.log10(H_psi) #interp_spline = interpolate.interp2d(x, y, Z) #, kind='cubic' interp_spline = interpolate.RectBivariateSpline(psi_y, psi_x, Z) #, bbox=[None, None, None, None], kx=3, ky=3, s=0 xnew = np.arange(psi_x[0], psi_x[-1], (psi_x[-1]-psi_x[0])/(len(psi_x)*inter[0]) ) #np.arange(-4, 2, 4e-2) # ynew = np.arange(psi_y[0], psi_y[-1], (psi_y[-1]-psi_y[0])/(len(psi_y)*inter[1]) ) #np.arange(0.2, 3, 2e-2) # Znew = interp_spline(ynew, xnew ) keV2K = 1.16e7 # Translates keV to Kelvin if plot_old: plt.plot( np.arange(0, len(psi_x), 1 ), psi_x ) plt.plot( np.arange(0, len(psi_y), 1 ), psi_y ) plt.savefig(saveplot + '_linearity.png') fig = plt.figure() ax1 = plt.subplot(121) ax1.pcolor( np.log10(keV2K) + psi_x, psi_y, Z) ax1.set_title("Sparsely sampled function") ax1.set_xlim([3.1, 9]) ax1.set_ylim([psi_y[0], 0.5]) ax1.set_xlabel('$\\mathrm{log_{10}(T)\\,[K]}$ ') ax1.set_ylabel('$\\mathrm{log_{10}(log_{10}(M))\\,[]}$') ax2 = plt.subplot(122) im2 = ax2.pcolor( np.log10(keV2K) + xnew, ynew, Znew) ax2.set_title("Interpolated function") ax2.set_xlim([3.1, 9]) ax2.set_ylim([psi_y[0], 0.5]) ax2.set_xlabel('$\\mathrm{log_{10}(T)\\,[K]}$ ') ax2.set_yticklabels([]) mach = [1.5,2.2,3.0,10.0] c = [plt.cm.rainbow( (np.log10(np.log10(m))-ax1.get_ylim()[0])/abs(ax1.get_ylim()[1]-ax1.get_ylim()[0]) ) for m in mach] for ii,m in enumerate(mach): ax1.plot( [ax1.get_xlim()[0], ax1.get_xlim()[1]] , [np.log10(np.log10(m))]*2, '-', c=c[ii], lw=1.5, alpha=0.9 ) ax2.plot( [ax2.get_xlim()[0], ax2.get_xlim()[1]] , [np.log10(np.log10(m))]*2, '-', c=c[ii], lw=1.5, alpha=0.9 ) ax1.text(ax1.get_xlim()[0]+0.3, np.log10(np.log10(m))+0.02, 'Mach$=$%4.1f' % (m), fontsize=10, color=c[ii], alpha=0.9) ax2.text(ax2.get_xlim()[0]+0.3, np.log10(np.log10(m))+0.02, 'Mach$=$%4.1f' % (m), fontsize=10, color=c[ii], alpha=0.9) fig.subplots_adjust(right=0.8) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(im2, cax=cbar_ax) plt.savefig(saveplot + '.png') if plot_new: fig = plt.figure() ax1 = plt.subplot(111) im2 = ax1.pcolor( np.log10(keV2K) + xnew, ynew, Znew, vmin=-8) # ax1.set_title("Interpolated function") ax1.set_xlim([7, 8.4]) ax1.set_ylim([np.log10(np.log10(1.7)), np.log10(np.log10(10.))]) ax1.set_xlabel('$\\mathrm{log_{10}(T)\\,[K]}$ ') ax1.set_ylabel('$M$ ') y_ticks = [np.log10(np.log10(m)) for m in [1.7,2.5,4,10]] print( ['%.2e' % (y) for y in y_ticks], [10**(10**y) for y in y_ticks] ) ax1.set_yticklabels([10**(10**y) for y in y_ticks]) plt.yticks(y_ticks) # temp = [1.5,2.2,3.0,10.0] # c = [plt.cm.rainbow( (np.log10(np.log10(m))-ax1.get_ylim()[0])/abs(ax1.get_ylim()[1]-ax1.get_ylim()[0]) ) for m in mach] # for ii,m in enumerate(mach): # ax1.plot( [ax1.get_xlim()[0], ax1.get_xlim()[1]] , [np.log10(np.log10(m))]*2, '-', c=c[ii], lw=1.5, alpha=0.9 ) # ax2.plot( [ax2.get_xlim()[0], ax2.get_xlim()[1]] , [np.log10(np.log10(m))]*2, '-', c=c[ii], lw=1.5, alpha=0.9 ) # # ax1.text(ax1.get_xlim()[0]+0.3, np.log10(np.log10(m))+0.02, 'Mach$=$%4.1f' % (m), fontsize=10, color=c[ii], alpha=0.9) # ax2.text(ax2.get_xlim()[0]+0.3, np.log10(np.log10(m))+0.02, 'Mach$=$%4.1f' % (m), fontsize=10, color=c[ii], alpha=0.9) fig.subplots_adjust(right=0.8) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(im2, cax=cbar_ax, label='$\log_{10}\Phi$',) plt.savefig(saveplot + '_DSA.pdf') plt.savefig(saveplot + '_DSA.png', dpi=800) if plot_PhD: fig = plt.figure() temp = np.linspace(2,20,20) print(temp) mach = np.linspace(2,7,300) psi_x,psi_y = LoadFile_psi(psiFile) import itertools H,M,T = [],[],[] for t in temp: results_temp = math.find_closest(psi_x, t) results_mach = math.find_closest(psi_y, mach) # H.append(H_psi[results_mach,np.ones_like(results_mach)*results_temp]) M.append(mach) T.append(np.ones_like(results_mach)*t) H = list(itertools.chain.from_iterable(H)) M = list(itertools.chain.from_iterable(M)) T = list(itertools.chain.from_iterable(T)) plt.scatter(M,np.log10(H),c=T,alpha=0.1,s=5) cb = plt.colorbar(label='Downstream Temperature [keV]') cb.set_alpha(1) cb.draw_all() plt.xlabel('Mach number $M$') plt.ylabel('$\log_{10}\,\Phi(M,T)$') plt.savefig(saveplot + '_PhD.pdf') plt.savefig(saveplot + '_PhD.png', dpi=800) # Save File A if psiFileNew: location = psiFileNew else: location = psiFile.replace('.txt', 'fine(%i,%i).txt' % (inter[0],inter[1]) ) header = '# Mach' for x in xnew: header += '%13.4e' % (10**x) mf = open(location,"w") mf.write(header + '\n') for ii,y in enumerate(ynew): string = '%9.4f' % (10**(10**y)) + ''.join(['%13.4e' % (10**z) for z in Znew[ii][:]]) mf.write(string + '\n') mf.close() #=== FILE B ===# Y_new = np.empty( (1,1) ) for ii,h in enumerate(H_mach.T): interp_spline = interpolate.interp1d( 10**psi_y , h, kind='cubic') if Y_new.shape[0] > 1: Y_new = np.hstack( (Y_new, np.expand_dims(interp_spline( 10**ynew ), axis=1) ) ) else: Y_new = np.expand_dims(interp_spline( 10**ynew ), axis=1) # Save File B if machFileNew: location = machFileNew else: location = machFile.replace('.txt', 'fine(%i,%i).txt' % (inter[0],inter[1]) ) header = '# q M r M*(1-1/r) s' mf = open(location,"w") mf.write(header + '\n') for ii,y in enumerate(10**ynew): string = ''.join(['%14.6e' % (y) for y in Y_new[:][ii]]) #some numbers are very large and ewould need a good margin mf.write(string + '\n') mf.close() return 0 if __name__ == "__main__": InterpolateRadio2D(psiFile = '../Analysis_MUSIC2/Hoeft_radio/mach_psi_tablefine(10,3).txt', inter=(3,2)) #(90,27)
42.310345
262
0.561125
import numpy as np import scipy.interpolate as interpolate import matplotlib.pyplot as plt import clusterbuster.mathut as math def my_interp(X, Y, Z, x, y, spn=3): xs,ys = map(np.array,(x,y)) z = np.zeros(xs.shape) for i,(x,y) in enumerate(zip(xs,ys)): xi = np.argmin(np.abs(X[0,:]-x)) yi = np.argmin(np.abs(Y[:,0]-y)) xlo = max(xi-spn, 0) ylo = max(yi-spn, 0) xhi = min(xi+spn, X[0,:].size) yhi = min(yi+spn, Y[:,0].size) nX = X[xlo:xhi, ylo:yhi] nY = Y[xlo:xhi, ylo:yhi] nZ = Z[xlo:xhi, ylo:yhi] intp = interpolate.interp2d(nX, nY, nZ) z[i] = intp(x,y)[0] return z def LoadFile_psi(psiFile): with open(psiFile, 'r') as f: first_line = f.readline() psi_x = first_line.split()[2:] psi_x = np.asarray( [float(i) for i in psi_x ] ) t(psiFile,skiprows=0)[:,0] return psi_x, psi_y def InterpolateRadio2D(psiFile='../Analysis_MUSIC2/Hoeft_radio/mach_psi_table.txt', machFile='../Analysis_MUSIC2/Hoeft_radio/q_mach_machr_table.txt', saveplot='../Analysis_MUSIC2/Hoeft_radio/interpolated', psiFileNew = False, machFileNew = False, inter=(10,3)): plot_old = False plot_new = False plot_PhD = True dtxt(psiFile,skiprows=0)[:,1::] psi_x,psi_y = LoadFile_psi(psiFile) psi_x = np.log10( psi_x ) psi_y = np.log10(np.log10( psi_y )) X, Y = np.meshgrid(psi_x, psi_y) Z = np.log10(H_psi) ine = interpolate.RectBivariateSpline(psi_y, psi_x, Z) xnew = np.arange(psi_x[0], psi_x[-1], (psi_x[-1]-psi_x[0])/(len(psi_x)*inter[0]) ) ynew = np.arange(psi_y[0], psi_y[-1], (psi_y[-1]-psi_y[0])/(len(psi_y)*inter[1]) ) Znew = interp_spline(ynew, xnew ) keV2K = 1.16e7 if plot_old: plt.plot( np.arange(0, len(psi_x), 1 ), psi_x ) plt.plot( np.arange(0, len(psi_y), 1 ), psi_y ) plt.savefig(saveplot + '_linearity.png') fig = plt.figure() ax1 = plt.subplot(121) ax1.pcolor( np.log10(keV2K) + psi_x, psi_y, Z) ax1.set_title("Sparsely sampled function") ax1.set_xlim([3.1, 9]) ax1.set_ylim([psi_y[0], 0.5]) ax1.set_xlabel('$\\mathrm{log_{10}(T)\\,[K]}$ ') ax1.set_ylabel('$\\mathrm{log_{10}(log_{10}(M))\\,[]}$') ax2 = plt.subplot(122) im2 = ax2.pcolor( np.log10(keV2K) + xnew, ynew, Znew) ax2.set_title("Interpolated function") ax2.set_xlim([3.1, 9]) ax2.set_ylim([psi_y[0], 0.5]) ax2.set_xlabel('$\\mathrm{log_{10}(T)\\,[K]}$ ') ax2.set_yticklabels([]) mach = [1.5,2.2,3.0,10.0] c = [plt.cm.rainbow( (np.log10(np.log10(m))-ax1.get_ylim()[0])/abs(ax1.get_ylim()[1]-ax1.get_ylim()[0]) ) for m in mach] for ii,m in enumerate(mach): ax1.plot( [ax1.get_xlim()[0], ax1.get_xlim()[1]] , [np.log10(np.log10(m))]*2, '-', c=c[ii], lw=1.5, alpha=0.9 ) ax2.plot( [ax2.get_xlim()[0], ax2.get_xlim()[1]] , [np.log10(np.log10(m))]*2, '-', c=c[ii], lw=1.5, alpha=0.9 ) ax1.text(ax1.get_xlim()[0]+0.3, np.log10(np.log10(m))+0.02, 'Mach$=$%4.1f' % (m), fontsize=10, color=c[ii], alpha=0.9) ax2.text(ax2.get_xlim()[0]+0.3, np.log10(np.log10(m))+0.02, 'Mach$=$%4.1f' % (m), fontsize=10, color=c[ii], alpha=0.9) fig.subplots_adjust(right=0.8) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(im2, cax=cbar_ax) plt.savefig(saveplot + '.png') if plot_new: fig = plt.figure() ax1 = plt.subplot(111) im2 = ax1.pcolor( np.log10(keV2K) + xnew, ynew, Znew, vmin=-8) ax1.set_xlim([7, 8.4]) ax1.set_ylim([np.log10(np.log10(1.7)), np.log10(np.log10(10.))]) ax1.set_xlabel('$\\mathrm{log_{10}(T)\\,[K]}$ ') ax1.set_ylabel('$M$ ') y_ticks = [np.log10(np.log10(m)) for m in [1.7,2.5,4,10]] print( ['%.2e' % (y) for y in y_ticks], [10**(10**y) for y in y_ticks] ) ax1.set_yticklabels([10**(10**y) for y in y_ticks]) plt.yticks(y_ticks) fig.subplots_adjust(right=0.8) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(im2, cax=cbar_ax, label='$\log_{10}\Phi$',) plt.savefig(saveplot + '_DSA.pdf') plt.savefig(saveplot + '_DSA.png', dpi=800) if plot_PhD: fig = plt.figure() temp = np.linspace(2,20,20) print(temp) mach = np.linspace(2,7,300) psi_x,psi_y = LoadFile_psi(psiFile) import itertools H,M,T = [],[],[] for t in temp: results_temp = math.find_closest(psi_x, t) results_mach = math.find_closest(psi_y, mach) H.append(H_psi[results_mach,np.ones_like(results_mach)*results_temp]) M.append(mach) T.append(np.ones_like(results_mach)*t) H = list(itertools.chain.from_iterable(H)) M = list(itertools.chain.from_iterable(M)) T = list(itertools.chain.from_iterable(T)) plt.scatter(M,np.log10(H),c=T,alpha=0.1,s=5) cb = plt.colorbar(label='Downstream Temperature [keV]') cb.set_alpha(1) cb.draw_all() plt.xlabel('Mach number $M$') plt.ylabel('$\log_{10}\,\Phi(M,T)$') plt.savefig(saveplot + '_PhD.pdf') plt.savefig(saveplot + '_PhD.png', dpi=800) if psiFileNew: location = psiFileNew else: location = psiFile.replace('.txt', 'fine(%i,%i).txt' % (inter[0],inter[1]) ) header = '# Mach' for x in xnew: header += '%13.4e' % (10**x) mf = open(location,"w") mf.write(header + '\n') for ii,y in enumerate(ynew): string = '%9.4f' % (10**(10**y)) + ''.join(['%13.4e' % (10**z) for z in Znew[ii][:]]) mf.write(string + '\n') mf.close() Y_new = np.empty( (1,1) ) for ii,h in enumerate(H_mach.T): interp_spline = interpolate.interp1d( 10**psi_y , h, kind='cubic') if Y_new.shape[0] > 1: Y_new = np.hstack( (Y_new, np.expand_dims(interp_spline( 10**ynew ), axis=1) ) ) else: Y_new = np.expand_dims(interp_spline( 10**ynew ), axis=1) if machFileNew: location = machFileNew else: location = machFile.replace('.txt', 'fine(%i,%i).txt' % (inter[0],inter[1]) ) header = '# q M r M*(1-1/r) s' mf = open(location,"w") mf.write(header + '\n') for ii,y in enumerate(10**ynew): string = ''.join(['%14.6e' % (y) for y in Y_new[:][ii]]) mf.write(string + '\n') mf.close() return 0 if __name__ == "__main__": InterpolateRadio2D(psiFile = '../Analysis_MUSIC2/Hoeft_radio/mach_psi_tablefine(10,3).txt', inter=(3,2))
true
true
f714a0761443c704df72e831e1a6e9881201965d
202
py
Python
flutterapi/myapp/models.py
PariTA05/Todolist
fa18d02e3f989cbb37f877fb18e3e715bfc76f0c
[ "MIT" ]
null
null
null
flutterapi/myapp/models.py
PariTA05/Todolist
fa18d02e3f989cbb37f877fb18e3e715bfc76f0c
[ "MIT" ]
null
null
null
flutterapi/myapp/models.py
PariTA05/Todolist
fa18d02e3f989cbb37f877fb18e3e715bfc76f0c
[ "MIT" ]
null
null
null
from django.db import models class Todolist(models.Model): title = models.CharField(max_length=100) detail = models.TextField(null=True, blank=True) def __str__(self): return self.title
25.25
50
0.732673
from django.db import models class Todolist(models.Model): title = models.CharField(max_length=100) detail = models.TextField(null=True, blank=True) def __str__(self): return self.title
true
true
f714a098ed7801e900ae6b4770cd7b10a0067882
301
py
Python
hackerrank/an-interesting-game-1/solution.py
SamProkopchuk/coding-problems
fa0ca2c05ac90e41945de1a5751e5545a8459ac4
[ "MIT" ]
null
null
null
hackerrank/an-interesting-game-1/solution.py
SamProkopchuk/coding-problems
fa0ca2c05ac90e41945de1a5751e5545a8459ac4
[ "MIT" ]
null
null
null
hackerrank/an-interesting-game-1/solution.py
SamProkopchuk/coding-problems
fa0ca2c05ac90e41945de1a5751e5545a8459ac4
[ "MIT" ]
null
null
null
for _ in range(int(input())): n = int(input()) rounds = 0 minidx = 1_000_000_000 for _, idx in sorted(zip(map(int, input().split()), range(n)), reverse=True): if idx < minidx: minidx = idx rounds += 1 print("BOB" if rounds % 2 else "ANDY")
30.1
82
0.521595
for _ in range(int(input())): n = int(input()) rounds = 0 minidx = 1_000_000_000 for _, idx in sorted(zip(map(int, input().split()), range(n)), reverse=True): if idx < minidx: minidx = idx rounds += 1 print("BOB" if rounds % 2 else "ANDY")
true
true
f714a0caf548812f27ce214b01b5f8336d284c42
4,545
py
Python
note12/download_text_data.py
zhuyawen/LearnPaddle2
c2ed0cea1634159b1f005a0d2d954ce44b51b739
[ "Apache-2.0" ]
163
2019-01-30T04:34:01.000Z
2021-12-10T12:19:03.000Z
note12/download_text_data.py
stonebb/LearnPaddle2
c3b6a9f5897e684b6de544cb12c959f7771a6c3c
[ "Apache-2.0" ]
3
2019-07-15T07:14:17.000Z
2022-03-24T01:14:06.000Z
note12/download_text_data.py
stonebb/LearnPaddle2
c3b6a9f5897e684b6de544cb12c959f7771a6c3c
[ "Apache-2.0" ]
83
2018-10-31T02:44:09.000Z
2022-03-25T13:40:54.000Z
import os import random import requests import json import time # 分类新闻参数 news_classify = [ [0, '民生', 'news_story'], [1, '文化', 'news_culture'], [2, '娱乐', 'news_entertainment'], [3, '体育', 'news_sports'], [4, '财经', 'news_finance'], [5, '房产', 'news_house'], [6, '汽车', 'news_car'], [7, '教育', 'news_edu'], [8, '科技', 'news_tech'], [9, '军事', 'news_military'], [10, '旅游', 'news_travel'], [11, '国际', 'news_world'], [12, '证券', 'stock'], [13, '农业', 'news_agriculture'], [14, '游戏', 'news_game'] ] # 已经下载的新闻标题的ID downloaded_data_id = [] # 已经下载新闻标题的数量 downloaded_sum = 0 def get_data(tup, data_path): global downloaded_data_id global downloaded_sum print('============%s============' % tup[1]) url = "http://it.snssdk.com/api/news/feed/v63/" # 分类新闻的访问参数,模仿正常网络访问 t = int(time.time() / 10000) t = random.randint(6 * t, 10 * t) querystring = {"category": tup[2], "max_behot_time": t, "last_refresh_sub_entrance_interval": "1524907088", "loc_mode": "5", "tt_from": "pre_load_more", "cp": "51a5ee4f38c50q1", "plugin_enable": "0", "iid": "31047425023", "device_id": "51425358841", "ac": "wifi", "channel": "tengxun", "aid": "13", "app_name": "news_article", "version_code": "631", "version_name": "6.3.1", "device_platform": "android", "ab_version": "333116,297979,317498,336556,295827,325046,239097,324283,170988,335432,332098,325198,336443,330632,297058,276203,286212,313219,328615,332041,329358,322321,327537,335710,333883,335102,334828,328670,324007,317077,334305,280773,335671,319960,333985,331719,336452,214069,31643,332881,333968,318434,207253,266310,321519,247847,281298,328218,335998,325618,333327,336199,323429,287591,288418,260650,326188,324614,335477,271178,326588,326524,326532", "ab_client": "a1,c4,e1,f2,g2,f7", "ab_feature": "94563,102749", "abflag": "3", "ssmix": "a", "device_type": "MuMu", "device_brand": "Android", "language": "zh", "os_api": "19", "os_version": "4.4.4", "uuid": "008796762094657", "openudid": "b7215ea70ca32066", "manifest_version_code": "631", "resolution": "1280*720", "dpi": "240", "update_version_code": "6310", "_rticket": "1524907088018", "plugin": "256"} headers = { 'cache-control': "no-cache", 'postman-token': "26530547-e697-1e8b-fd82-7c6014b3ee86", 'User-Agent': 'Dalvik/1.6.0 (Linux; U; Android 4.4.4; MuMu Build/V417IR) NewsArticle/6.3.1 okhttp/3.7.0.2' } # 进行网络请求 response = requests.request("GET", url, headers=headers, params=querystring) # 获取返回的数据 new_data = json.loads(response.text) with open(data_path, 'a', encoding='utf-8') as fp: for item in new_data['data']: item = item['content'] item = item.replace('\"', '"') item = json.loads(item) # 判断数据中是否包含id和新闻标题 if 'item_id' in item.keys() and 'title' in item.keys(): item_id = item['item_id'] print(downloaded_sum, tup[0], tup[1], item['item_id'], item['title']) # 通过新闻id判断是否已经下载过 if item_id not in downloaded_data_id: downloaded_data_id.append(item_id) # 安装固定格式追加写入文件中 line = u"{}_!_{}_!_{}_!_{}".format(item['item_id'], tup[0], tup[1], item['title']) line = line.replace('\n', '').replace('\r', '') line = line + '\n' fp.write(line) downloaded_sum += 1 def get_routine(data_path): global downloaded_sum # 从文件中读取已经有的数据,避免数据重复 if os.path.exists(data_path): with open(data_path, 'r', encoding='utf-8') as fp: lines = fp.readlines() downloaded_sum = len(lines) for line in lines: item_id = int(line.split('_!_')[0]) downloaded_data_id.append(item_id) print('在文件中已经读起了%d条数据' % downloaded_sum) else: os.makedirs(os.path.dirname(data_path)) while 1: #  开始下载数据 time.sleep(10) for classify in news_classify: get_data(classify, data_path) # 当下载量超过300000就停止下载 if downloaded_sum >= 300000: break if __name__ == '__main__': data_path = 'datasets/news_classify_data.txt' dict_path = "datasets/dict_txt.txt" # 下载数据集 get_routine(data_path)
40.945946
475
0.572937
import os import random import requests import json import time news_classify = [ [0, '民生', 'news_story'], [1, '文化', 'news_culture'], [2, '娱乐', 'news_entertainment'], [3, '体育', 'news_sports'], [4, '财经', 'news_finance'], [5, '房产', 'news_house'], [6, '汽车', 'news_car'], [7, '教育', 'news_edu'], [8, '科技', 'news_tech'], [9, '军事', 'news_military'], [10, '旅游', 'news_travel'], [11, '国际', 'news_world'], [12, '证券', 'stock'], [13, '农业', 'news_agriculture'], [14, '游戏', 'news_game'] ] downloaded_data_id = [] downloaded_sum = 0 def get_data(tup, data_path): global downloaded_data_id global downloaded_sum print('============%s============' % tup[1]) url = "http://it.snssdk.com/api/news/feed/v63/" t = int(time.time() / 10000) t = random.randint(6 * t, 10 * t) querystring = {"category": tup[2], "max_behot_time": t, "last_refresh_sub_entrance_interval": "1524907088", "loc_mode": "5", "tt_from": "pre_load_more", "cp": "51a5ee4f38c50q1", "plugin_enable": "0", "iid": "31047425023", "device_id": "51425358841", "ac": "wifi", "channel": "tengxun", "aid": "13", "app_name": "news_article", "version_code": "631", "version_name": "6.3.1", "device_platform": "android", "ab_version": "333116,297979,317498,336556,295827,325046,239097,324283,170988,335432,332098,325198,336443,330632,297058,276203,286212,313219,328615,332041,329358,322321,327537,335710,333883,335102,334828,328670,324007,317077,334305,280773,335671,319960,333985,331719,336452,214069,31643,332881,333968,318434,207253,266310,321519,247847,281298,328218,335998,325618,333327,336199,323429,287591,288418,260650,326188,324614,335477,271178,326588,326524,326532", "ab_client": "a1,c4,e1,f2,g2,f7", "ab_feature": "94563,102749", "abflag": "3", "ssmix": "a", "device_type": "MuMu", "device_brand": "Android", "language": "zh", "os_api": "19", "os_version": "4.4.4", "uuid": "008796762094657", "openudid": "b7215ea70ca32066", "manifest_version_code": "631", "resolution": "1280*720", "dpi": "240", "update_version_code": "6310", "_rticket": "1524907088018", "plugin": "256"} headers = { 'cache-control': "no-cache", 'postman-token': "26530547-e697-1e8b-fd82-7c6014b3ee86", 'User-Agent': 'Dalvik/1.6.0 (Linux; U; Android 4.4.4; MuMu Build/V417IR) NewsArticle/6.3.1 okhttp/3.7.0.2' } response = requests.request("GET", url, headers=headers, params=querystring) new_data = json.loads(response.text) with open(data_path, 'a', encoding='utf-8') as fp: for item in new_data['data']: item = item['content'] item = item.replace('\"', '"') item = json.loads(item) if 'item_id' in item.keys() and 'title' in item.keys(): item_id = item['item_id'] print(downloaded_sum, tup[0], tup[1], item['item_id'], item['title']) if item_id not in downloaded_data_id: downloaded_data_id.append(item_id) line = u"{}_!_{}_!_{}_!_{}".format(item['item_id'], tup[0], tup[1], item['title']) line = line.replace('\n', '').replace('\r', '') line = line + '\n' fp.write(line) downloaded_sum += 1 def get_routine(data_path): global downloaded_sum if os.path.exists(data_path): with open(data_path, 'r', encoding='utf-8') as fp: lines = fp.readlines() downloaded_sum = len(lines) for line in lines: item_id = int(line.split('_!_')[0]) downloaded_data_id.append(item_id) print('在文件中已经读起了%d条数据' % downloaded_sum) else: os.makedirs(os.path.dirname(data_path)) while 1: time.sleep(10) for classify in news_classify: get_data(classify, data_path) if downloaded_sum >= 300000: break if __name__ == '__main__': data_path = 'datasets/news_classify_data.txt' dict_path = "datasets/dict_txt.txt" get_routine(data_path)
true
true
f714a1b02ca1276050523ec8c90956dae69d86bf
3,521
py
Python
tools/emprofile.py
talrasha/emscripten
5ece531a4bc724b133da0e1b0ce061e0c2e7bebd
[ "MIT" ]
1
2021-06-15T20:40:30.000Z
2021-06-15T20:40:30.000Z
tools/emprofile.py
talrasha/emscripten
5ece531a4bc724b133da0e1b0ce061e0c2e7bebd
[ "MIT" ]
null
null
null
tools/emprofile.py
talrasha/emscripten
5ece531a4bc724b133da0e1b0ce061e0c2e7bebd
[ "MIT" ]
null
null
null
#!/usr/bin/env python # Copyright 2016 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. import json import os import shutil import sys import tempfile import time profiler_logs_path = os.path.join(tempfile.gettempdir(), 'emscripten_toolchain_profiler_logs') OUTFILE = 'emprofile.' + time.strftime('%Y%m%d_%H%M') for i in range(len(sys.argv)): arg = sys.argv[i] if arg.startswith('--outfile=') or arg.startswith('-o='): OUTFILE = arg.split('=', 1)[1].strip().replace('.html', '') sys.argv[i] = '' elif arg == '-o': OUTFILE = sys.argv[i + 1].strip().replace('.html', '') sys.argv[i] = sys.argv[i + 1] = '' # Deletes all previously captured log files to make room for a new clean run. def delete_profiler_logs(): try: shutil.rmtree(profiler_logs_path) except IOError: pass def list_files_in_directory(d): files = [] try: items = os.listdir(d) for i in items: f = os.path.join(d, i) if os.path.isfile(f): files += [f] return files except IOError: return [] def create_profiling_graph(): log_files = [f for f in list_files_in_directory(profiler_logs_path) if 'toolchain_profiler.pid_' in f] all_results = [] if len(log_files): print('Processing ' + str(len(log_files)) + ' profile log files in "' + profiler_logs_path + '"...') for f in log_files: try: json_data = open(f, 'r').read() if len(json_data.strip()) == 0: continue lines = json_data.split('\n') lines = [x for x in lines if x != '[' and x != ']' and x != ',' and len(x.strip())] lines = [(x + ',') if not x.endswith(',') else x for x in lines] lines[-1] = lines[-1][:-1] json_data = '[' + '\n'.join(lines) + ']' all_results += json.loads(json_data) except Exception as e: print(str(e), file=sys.stderr) print('Failed to parse JSON file "' + f + '"!', file=sys.stderr) sys.exit(1) if len(all_results) == 0: print('No profiler logs were found in path "' + profiler_logs_path + '". Try setting the environment variable EMPROFILE=1 and run some emcc commands, and then rerun "emprofile" again.') return all_results.sort(key=lambda x: x['time']) emprofile_json_data = json.dumps(all_results, indent=2) html_file = OUTFILE + '.html' html_contents = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'toolchain_profiler.results_template.html'), 'r').read().replace('{{{ emprofile_json_data }}}', emprofile_json_data) open(html_file, 'w').write(html_contents) print('Wrote "' + html_file + '"') if '--help' in sys.argv: print('''Usage: emprofile.py --clear (or -c) Deletes all previously recorded profiling log files. Use this to abort/drop any previously collected profiling data for a new profiling run. emprofile.py [--no-clear] Draws a graph from all recorded profiling log files, and deletes the recorded profiling files, unless --no-clear is also passed. Optional parameters: --outfile=x.html (or -o=x.html) Specifies the name of the results file to generate. ''') sys.exit(1) if '--reset' in sys.argv or '--clear' in sys.argv or '-c' in sys.argv: delete_profiler_logs() else: create_profiling_graph() if '--no-clear' not in sys.argv: delete_profiler_logs()
32.302752
197
0.650099
import json import os import shutil import sys import tempfile import time profiler_logs_path = os.path.join(tempfile.gettempdir(), 'emscripten_toolchain_profiler_logs') OUTFILE = 'emprofile.' + time.strftime('%Y%m%d_%H%M') for i in range(len(sys.argv)): arg = sys.argv[i] if arg.startswith('--outfile=') or arg.startswith('-o='): OUTFILE = arg.split('=', 1)[1].strip().replace('.html', '') sys.argv[i] = '' elif arg == '-o': OUTFILE = sys.argv[i + 1].strip().replace('.html', '') sys.argv[i] = sys.argv[i + 1] = '' def delete_profiler_logs(): try: shutil.rmtree(profiler_logs_path) except IOError: pass def list_files_in_directory(d): files = [] try: items = os.listdir(d) for i in items: f = os.path.join(d, i) if os.path.isfile(f): files += [f] return files except IOError: return [] def create_profiling_graph(): log_files = [f for f in list_files_in_directory(profiler_logs_path) if 'toolchain_profiler.pid_' in f] all_results = [] if len(log_files): print('Processing ' + str(len(log_files)) + ' profile log files in "' + profiler_logs_path + '"...') for f in log_files: try: json_data = open(f, 'r').read() if len(json_data.strip()) == 0: continue lines = json_data.split('\n') lines = [x for x in lines if x != '[' and x != ']' and x != ',' and len(x.strip())] lines = [(x + ',') if not x.endswith(',') else x for x in lines] lines[-1] = lines[-1][:-1] json_data = '[' + '\n'.join(lines) + ']' all_results += json.loads(json_data) except Exception as e: print(str(e), file=sys.stderr) print('Failed to parse JSON file "' + f + '"!', file=sys.stderr) sys.exit(1) if len(all_results) == 0: print('No profiler logs were found in path "' + profiler_logs_path + '". Try setting the environment variable EMPROFILE=1 and run some emcc commands, and then rerun "emprofile" again.') return all_results.sort(key=lambda x: x['time']) emprofile_json_data = json.dumps(all_results, indent=2) html_file = OUTFILE + '.html' html_contents = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'toolchain_profiler.results_template.html'), 'r').read().replace('{{{ emprofile_json_data }}}', emprofile_json_data) open(html_file, 'w').write(html_contents) print('Wrote "' + html_file + '"') if '--help' in sys.argv: print('''Usage: emprofile.py --clear (or -c) Deletes all previously recorded profiling log files. Use this to abort/drop any previously collected profiling data for a new profiling run. emprofile.py [--no-clear] Draws a graph from all recorded profiling log files, and deletes the recorded profiling files, unless --no-clear is also passed. Optional parameters: --outfile=x.html (or -o=x.html) Specifies the name of the results file to generate. ''') sys.exit(1) if '--reset' in sys.argv or '--clear' in sys.argv or '-c' in sys.argv: delete_profiler_logs() else: create_profiling_graph() if '--no-clear' not in sys.argv: delete_profiler_logs()
true
true
f714a32598047c41a41ca8c84b2495aad909f3ac
829
py
Python
QiuBaiSpider/spider_main.py
lidenghong1/SmallReptileTraining
a1bfb81c9969edfb7554acc50370c0cb036da690
[ "MIT" ]
133
2017-06-10T02:18:00.000Z
2022-01-08T03:29:08.000Z
QiuBaiSpider/spider_main.py
ljj2666/SmallReptileTraining
b6253e835120da457c416fbf4a012e545d9c70ad
[ "MIT" ]
null
null
null
QiuBaiSpider/spider_main.py
ljj2666/SmallReptileTraining
b6253e835120da457c416fbf4a012e545d9c70ad
[ "MIT" ]
212
2017-06-14T03:29:22.000Z
2022-01-29T15:14:47.000Z
from QiuBaiSpider.pymysqldb_manager import DbManager from QiuBaiSpider.page_items import PageItems from QiuBaiSpider.tools import Tools ''' 爬取糗事百科笑话剔除正文DOM标签然后将爬取数据存入MySQL数据库 Extra module: PyMySQL ''' class Main(object): def __init__(self, max_page=1): self.max_page = max_page self.db_manager = DbManager() def run(self): self.db_manager.connect() for index in range(self.max_page): self._page_run(index) self.db_manager.close() def _page_run(self, page): page_dict_items = PageItems(page).get_page_dict_items() if page_dict_items is None: return for dict_item in page_dict_items: self.db_manager.insertDict(dict_item) pass if __name__ == "__main__": Tools.setup_log_mode(False) Main(10).run()
24.382353
63
0.679131
from QiuBaiSpider.pymysqldb_manager import DbManager from QiuBaiSpider.page_items import PageItems from QiuBaiSpider.tools import Tools class Main(object): def __init__(self, max_page=1): self.max_page = max_page self.db_manager = DbManager() def run(self): self.db_manager.connect() for index in range(self.max_page): self._page_run(index) self.db_manager.close() def _page_run(self, page): page_dict_items = PageItems(page).get_page_dict_items() if page_dict_items is None: return for dict_item in page_dict_items: self.db_manager.insertDict(dict_item) pass if __name__ == "__main__": Tools.setup_log_mode(False) Main(10).run()
true
true
f714a3eab380aa3fea7349fb1fb1cb7718fcf9fb
2,713
py
Python
test/pyaz/acr/helm/__init__.py
bigdatamoore/py-az-cli
54383a4ee7cc77556f6183e74e992eec95b28e01
[ "MIT" ]
null
null
null
test/pyaz/acr/helm/__init__.py
bigdatamoore/py-az-cli
54383a4ee7cc77556f6183e74e992eec95b28e01
[ "MIT" ]
9
2021-09-24T16:37:24.000Z
2021-12-24T00:39:19.000Z
test/pyaz/acr/helm/__init__.py
bigdatamoore/py-az-cli
54383a4ee7cc77556f6183e74e992eec95b28e01
[ "MIT" ]
null
null
null
import json, subprocess from ... pyaz_utils import get_cli_name, get_params def list(name, repository=None, resource_group=None, suffix=None, username=None, password=None): params = get_params(locals()) command = "az acr helm list " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def show(name, version=None, repository=None, resource_group=None, suffix=None, username=None, password=None): params = get_params(locals()) command = "az acr helm show " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def delete(name, version=None, repository=None, resource_group=None, suffix=None, username=None, password=None, prov=None, yes=None): params = get_params(locals()) command = "az acr helm delete " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def push(name, repository=None, force=None, resource_group=None, suffix=None, username=None, password=None): params = get_params(locals()) command = "az acr helm push " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def install_cli(client_version=None, install_location=None, yes=None): params = get_params(locals()) command = "az acr helm install-cli " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr)
36.662162
133
0.669001
import json, subprocess from ... pyaz_utils import get_cli_name, get_params def list(name, repository=None, resource_group=None, suffix=None, username=None, password=None): params = get_params(locals()) command = "az acr helm list " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def show(name, version=None, repository=None, resource_group=None, suffix=None, username=None, password=None): params = get_params(locals()) command = "az acr helm show " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def delete(name, version=None, repository=None, resource_group=None, suffix=None, username=None, password=None, prov=None, yes=None): params = get_params(locals()) command = "az acr helm delete " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def push(name, repository=None, force=None, resource_group=None, suffix=None, username=None, password=None): params = get_params(locals()) command = "az acr helm push " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr) def install_cli(client_version=None, install_location=None, yes=None): params = get_params(locals()) command = "az acr helm install-cli " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = output.stdout.decode("utf-8") stderr = output.stderr.decode("utf-8") if stdout: return json.loads(stdout) print(stdout) else: raise Exception(stderr) print(stderr)
true
true
f714a4d032c0d9c04d96fb38385edc266e67dc16
516
py
Python
worker/Facebook/service1/main.py
OmarZOS/remote-extraction-proxy-and-worker
739466a0df588d7eb5b1dae9666ceb8c7a25e928
[ "MIT" ]
null
null
null
worker/Facebook/service1/main.py
OmarZOS/remote-extraction-proxy-and-worker
739466a0df588d7eb5b1dae9666ceb8c7a25e928
[ "MIT" ]
10
2022-03-17T23:23:18.000Z
2022-03-18T00:15:11.000Z
worker/Facebook/service1/main.py
OmarZOS/remote-extraction-proxy-and-worker
739466a0df588d7eb5b1dae9666ceb8c7a25e928
[ "MIT" ]
1
2022-03-24T23:56:46.000Z
2022-03-24T23:56:46.000Z
from http import cookies from Extractor import Extractor from context import Context import networkx as nx from facebook_scraper import get_posts,get_friends,get_profile,get_group_info cxt=Context(account,creds,limit_post,limit_friends,max,post,False,True) #print(get_profile("100009975842374")) #print(get_group_info("journalmaracanaalgerie") ) ex =Extractor('Fb',cxt,Schema,cookie) ex.create_Graphe_friends(file_graphe,cxt,Schema,cookie) #ex.create_Graphe_group(file_graphe,cxt,Schema,cookies)
17.793103
77
0.813953
from http import cookies from Extractor import Extractor from context import Context import networkx as nx from facebook_scraper import get_posts,get_friends,get_profile,get_group_info cxt=Context(account,creds,limit_post,limit_friends,max,post,False,True) ex =Extractor('Fb',cxt,Schema,cookie) ex.create_Graphe_friends(file_graphe,cxt,Schema,cookie)
true
true
f714a58617a8965d0d4cc18d282b5dffc7518090
4,801
py
Python
main.py
ammar-khan/raspberry-pi-opencv-dnn-face-detection
04ea998ee9e4d7bf71da022b0d8613940e8e7cfb
[ "MIT" ]
3
2018-10-25T05:01:13.000Z
2021-01-22T11:29:15.000Z
main.py
ammar-khan/raspberry-pi-opencv-dnn-face-detection
04ea998ee9e4d7bf71da022b0d8613940e8e7cfb
[ "MIT" ]
null
null
null
main.py
ammar-khan/raspberry-pi-opencv-dnn-face-detection
04ea998ee9e4d7bf71da022b0d8613940e8e7cfb
[ "MIT" ]
1
2019-08-24T19:22:04.000Z
2019-08-24T19:22:04.000Z
## # Copyright 2018, Ammar Ali Khan # Licensed under MIT. # Since: v1.0.0 ## import time import cv2 import numpy as np from src.common.package.config import application from src.opencv.package.config import application as _application from src.common.package.http import server as _server from src.common.package.http.handler import Handler from src.common.package.camera.capture import Capture as _capture from src.common.package.frame.action import Action as _frame from src.common.package.frame.draw import Draw as _draw from src.opencv.package.opencv.opencv import OpenCV # Constant _opencv = OpenCV() ## # StreamHandler class - inherit Handler # This class provide handler for HTTP streaming # Note: this class should override Handler.stream ## class StreamHandler(Handler): ## # Override method Handler.stream() ## def stream(self): Handler.stream(self) print('[INFO] Overriding stream method...') # Initialise capture capture = _capture(src=application.CAPTURING_DEVICE, use_pi_camera=application.USE_PI_CAMERA, resolution=application.RESOLUTION, frame_rate=application.FRAME_RATE) if application.USE_PI_CAMERA: print('[INFO] Warming up pi camera...') else: print('[INFO] Warming up camera...') time.sleep(2.0) print('[INFO] Start capturing...') while True: # Read a frame from capture frame = capture.read() # Down size frame to 50% (to increase performance on Raspberry Pi) # frame = _frame.scale(frame=frame, scale=0.5) # Convert frame to gray (to increase performance on Raspberry Pi) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Get frame dimensions (height, width) = frame.shape[:2] # OpenCV detection detections = _opencv.dnn_face_detector(frame=frame, scale_factor=1.0, size=(300, 300), mean=(104.0, 177.0, 123.0)) # Up size frame to 50% (how the frame was before down sizing) # frame = _frame.scale(frame=frame, scale=2) # If returns any detection for i in range(0, detections.shape[2]): # Get confidence associated with the detection confidence = detections[0, 0, i, 2] # Filter weak detection if confidence < _application.CONFIDENCE: continue # Calculate coordinates box = detections[0, 0, i, 3:7] * np.array([width, height, width, height]) (left, top, right, bottom) = box.astype('int') coordinates = {'left': left, 'top': top, 'right': right, 'bottom': bottom} text = "{:.2f}%".format(confidence * 100) frame = _draw.rectangle(frame=frame, coordinates=coordinates, text=text) # Write date time on the frame frame = _draw.text(frame=frame, coordinates={'left': application.WIDTH - 150, 'top': application.HEIGHT - 20}, text=time.strftime('%d/%m/%Y %H:%M:%S', time.localtime()), font_color=(0, 0, 255)) # Convert frame into buffer for streaming retval, buffer = cv2.imencode('.jpg', frame) # Write buffer to HTML Handler self.wfile.write(b'--FRAME\r\n') self.send_header('Content-Type', 'image/jpeg') self.send_header('Content-Length', len(buffer)) self.end_headers() self.wfile.write(buffer) self.wfile.write(b'\r\n') ## # Method main() ## def main(): try: address = ('', application.HTTP_PORT) server = _server.Server(address, StreamHandler) print('[INFO] HTTP server started successfully at %s' % str(server.server_address)) print('[INFO] Waiting for client to connect to port %s' % str(application.HTTP_PORT)) server.serve_forever() except Exception as e: server.socket.close() print('[INFO] HTTP server closed successfully.') print('[ERROR] Exception: %s' % str(e)) if __name__ == '__main__': main()
34.789855
109
0.534264
import time import cv2 import numpy as np from src.common.package.config import application from src.opencv.package.config import application as _application from src.common.package.http import server as _server from src.common.package.http.handler import Handler from src.common.package.camera.capture import Capture as _capture from src.common.package.frame.action import Action as _frame from src.common.package.frame.draw import Draw as _draw from src.opencv.package.opencv.opencv import OpenCV _opencv = OpenCV() class StreamHandler(Handler): def stream(self): Handler.stream(self) print('[INFO] Overriding stream method...') capture = _capture(src=application.CAPTURING_DEVICE, use_pi_camera=application.USE_PI_CAMERA, resolution=application.RESOLUTION, frame_rate=application.FRAME_RATE) if application.USE_PI_CAMERA: print('[INFO] Warming up pi camera...') else: print('[INFO] Warming up camera...') time.sleep(2.0) print('[INFO] Start capturing...') while True: frame = capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) (height, width) = frame.shape[:2] detections = _opencv.dnn_face_detector(frame=frame, scale_factor=1.0, size=(300, 300), mean=(104.0, 177.0, 123.0)) for i in range(0, detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence < _application.CONFIDENCE: continue box = detections[0, 0, i, 3:7] * np.array([width, height, width, height]) (left, top, right, bottom) = box.astype('int') coordinates = {'left': left, 'top': top, 'right': right, 'bottom': bottom} text = "{:.2f}%".format(confidence * 100) frame = _draw.rectangle(frame=frame, coordinates=coordinates, text=text) frame = _draw.text(frame=frame, coordinates={'left': application.WIDTH - 150, 'top': application.HEIGHT - 20}, text=time.strftime('%d/%m/%Y %H:%M:%S', time.localtime()), font_color=(0, 0, 255)) retval, buffer = cv2.imencode('.jpg', frame) self.wfile.write(b'--FRAME\r\n') self.send_header('Content-Type', 'image/jpeg') self.send_header('Content-Length', len(buffer)) self.end_headers() self.wfile.write(buffer) self.wfile.write(b'\r\n') def main(): try: address = ('', application.HTTP_PORT) server = _server.Server(address, StreamHandler) print('[INFO] HTTP server started successfully at %s' % str(server.server_address)) print('[INFO] Waiting for client to connect to port %s' % str(application.HTTP_PORT)) server.serve_forever() except Exception as e: server.socket.close() print('[INFO] HTTP server closed successfully.') print('[ERROR] Exception: %s' % str(e)) if __name__ == '__main__': main()
true
true
f714a5f04300870022842049f2926bc20c34e5c2
4,647
py
Python
nova/tests/functional/libvirt/test_live_migration.py
muraliselva10/nova
97626394bcce5c8cd020b136ca54a6aa919eb3a9
[ "Apache-2.0" ]
1
2022-02-24T08:49:48.000Z
2022-02-24T08:49:48.000Z
nova/tests/functional/libvirt/test_live_migration.py
muraliselva10/nova
97626394bcce5c8cd020b136ca54a6aa919eb3a9
[ "Apache-2.0" ]
null
null
null
nova/tests/functional/libvirt/test_live_migration.py
muraliselva10/nova
97626394bcce5c8cd020b136ca54a6aa919eb3a9
[ "Apache-2.0" ]
null
null
null
# Copyright 2021 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import threading from lxml import etree from nova.tests.functional import integrated_helpers from nova.tests.functional.libvirt import base as libvirt_base class LiveMigrationQueuedAbortTest( libvirt_base.LibvirtMigrationMixin, libvirt_base.ServersTestBase, integrated_helpers.InstanceHelperMixin ): """Functional test for bug 1949808. This test is used to confirm that VM's state is reverted properly when queued Live migration is aborted. """ api_major_version = 'v2.1' microversion = '2.74' ADMIN_API = True def setUp(self): super().setUp() # We will allow only one live migration to be processed at any # given period of time self.flags(max_concurrent_live_migrations='1') self.src_hostname = self.start_compute(hostname='src') self.dest_hostname = self.start_compute(hostname='dest') self.src = self.computes[self.src_hostname] self.dest = self.computes[self.dest_hostname] # Live migration's execution could be locked if needed self.lock_live_migration = threading.Lock() def _migrate_stub(self, domain, destination, params, flags): # Execute only if live migration is not locked with self.lock_live_migration: self.dest.driver._host.get_connection().createXML( params['destination_xml'], 'fake-createXML-doesnt-care-about-flags') conn = self.src.driver._host.get_connection() # Because migrateToURI3 is spawned in a background thread, # this method does not block the upper nova layers. Because # we don't want nova to think the live migration has # finished until this method is done, the last thing we do # is make fakelibvirt's Domain.jobStats() return # VIR_DOMAIN_JOB_COMPLETED. server = etree.fromstring( params['destination_xml'] ).find('./uuid').text dom = conn.lookupByUUIDString(server) dom.complete_job() def test_queued_live_migration_abort(self): # Lock live migrations self.lock_live_migration.acquire() # Start instances: first one would be used to occupy # executor's live migration queue, second one would be used # to actually confirm that queued live migrations are # aborted properly. self.server_a = self._create_server( host=self.src_hostname, networks='none') self.server_b = self._create_server( host=self.src_hostname, networks='none') # Issue live migration requests for both servers. We expect that # server_a live migration would be running, but locked by # self.lock_live_migration and server_b live migration would be # queued. self._live_migrate( self.server_a, migration_expected_state='running', server_expected_state='MIGRATING' ) self._live_migrate( self.server_b, migration_expected_state='queued', server_expected_state='MIGRATING' ) # Abort live migration for server_b serverb_migration = self.api.api_get( '/os-migrations?instance_uuid=%s' % self.server_b['id'] ).body['migrations'].pop() self.api.api_delete( '/servers/%s/migrations/%s' % (self.server_b['id'], serverb_migration['id'])) self._wait_for_migration_status(self.server_b, ['cancelled']) # Unlock live migrations and confirm that server_a becomes # active again after successful live migration self.lock_live_migration.release() self._wait_for_state_change(self.server_a, 'ACTIVE') # FIXME(artom) Assert the server_b never comes out of 'MIGRATING' self.assertRaises( AssertionError, self._wait_for_state_change, self.server_b, 'ACTIVE') self._wait_for_state_change(self.server_b, 'MIGRATING')
39.381356
75
0.663869
import threading from lxml import etree from nova.tests.functional import integrated_helpers from nova.tests.functional.libvirt import base as libvirt_base class LiveMigrationQueuedAbortTest( libvirt_base.LibvirtMigrationMixin, libvirt_base.ServersTestBase, integrated_helpers.InstanceHelperMixin ): api_major_version = 'v2.1' microversion = '2.74' ADMIN_API = True def setUp(self): super().setUp() self.flags(max_concurrent_live_migrations='1') self.src_hostname = self.start_compute(hostname='src') self.dest_hostname = self.start_compute(hostname='dest') self.src = self.computes[self.src_hostname] self.dest = self.computes[self.dest_hostname] self.lock_live_migration = threading.Lock() def _migrate_stub(self, domain, destination, params, flags): # Execute only if live migration is not locked with self.lock_live_migration: self.dest.driver._host.get_connection().createXML( params['destination_xml'], 'fake-createXML-doesnt-care-about-flags') conn = self.src.driver._host.get_connection() # Because migrateToURI3 is spawned in a background thread, # this method does not block the upper nova layers. Because # we don't want nova to think the live migration has # VIR_DOMAIN_JOB_COMPLETED. server = etree.fromstring( params['destination_xml'] ).find('./uuid').text dom = conn.lookupByUUIDString(server) dom.complete_job() def test_queued_live_migration_abort(self): # Lock live migrations self.lock_live_migration.acquire() # Start instances: first one would be used to occupy # executor's live migration queue, second one would be used self.server_a = self._create_server( host=self.src_hostname, networks='none') self.server_b = self._create_server( host=self.src_hostname, networks='none') self._live_migrate( self.server_a, migration_expected_state='running', server_expected_state='MIGRATING' ) self._live_migrate( self.server_b, migration_expected_state='queued', server_expected_state='MIGRATING' ) serverb_migration = self.api.api_get( '/os-migrations?instance_uuid=%s' % self.server_b['id'] ).body['migrations'].pop() self.api.api_delete( '/servers/%s/migrations/%s' % (self.server_b['id'], serverb_migration['id'])) self._wait_for_migration_status(self.server_b, ['cancelled']) self.lock_live_migration.release() self._wait_for_state_change(self.server_a, 'ACTIVE') self.assertRaises( AssertionError, self._wait_for_state_change, self.server_b, 'ACTIVE') self._wait_for_state_change(self.server_b, 'MIGRATING')
true
true
f714a5ff5c93a84a57edfda15f6f4e42f0eb012f
175
py
Python
run.py
B02902008/TaipeiWater
7364ce0bdfafddb7448cd8943c0c048f1a199dda
[ "MIT" ]
null
null
null
run.py
B02902008/TaipeiWater
7364ce0bdfafddb7448cd8943c0c048f1a199dda
[ "MIT" ]
null
null
null
run.py
B02902008/TaipeiWater
7364ce0bdfafddb7448cd8943c0c048f1a199dda
[ "MIT" ]
null
null
null
from app import app if __name__ == '__main__': context = ('/etc/ssl/certificate.crt', '/etc/ssl/private.key') app.run(host='0.0.0.0', port=8443, ssl_context=context)
29.166667
66
0.668571
from app import app if __name__ == '__main__': context = ('/etc/ssl/certificate.crt', '/etc/ssl/private.key') app.run(host='0.0.0.0', port=8443, ssl_context=context)
true
true
f714a7605ee022f93df4415ea3b71026282a989e
30
py
Python
dolphindb_numpy/polynomial/__init__.py
jiajiaxu123/Orca
e86189e70c1d0387816bb98b8047a6232fbda9df
[ "Apache-2.0" ]
20
2019-12-02T11:49:12.000Z
2021-12-24T19:34:32.000Z
dolphindb_numpy/polynomial/__init__.py
jiajiaxu123/Orca
e86189e70c1d0387816bb98b8047a6232fbda9df
[ "Apache-2.0" ]
null
null
null
dolphindb_numpy/polynomial/__init__.py
jiajiaxu123/Orca
e86189e70c1d0387816bb98b8047a6232fbda9df
[ "Apache-2.0" ]
5
2019-12-02T12:16:22.000Z
2021-10-22T02:27:47.000Z
from numpy.polynomial import *
30
30
0.833333
from numpy.polynomial import *
true
true
f714a765ed3fdb8802a47ef9a05184c1987b46ec
2,243
py
Python
transfer/rcvfromelf.py
arhefner/max_mon
75c02804089c957c53bf5f68c52f89ba5ceeb5bc
[ "MIT" ]
null
null
null
transfer/rcvfromelf.py
arhefner/max_mon
75c02804089c957c53bf5f68c52f89ba5ceeb5bc
[ "MIT" ]
null
null
null
transfer/rcvfromelf.py
arhefner/max_mon
75c02804089c957c53bf5f68c52f89ba5ceeb5bc
[ "MIT" ]
null
null
null
#! /usr/bin/env python3 import click import serial from enum import Enum, auto from intelhex import IntelHex,IntelHexError import constants @click.command() @click.argument( 'file', required=True, type=click.Path(dir_okay=False, writable=True) ) @click.option( '--append', '-a', help='append data to hex file', is_flag=True ) @click.option( '--port', '-p', required=True, help='serial port where ELF is connected' ) @click.option( '--baud', '-b', help='serial baud rate', type=int, default=9600 ) def main(file, append, port, baud): """ Receive a code file from an attached ELF with MAX binary sender. The program reads a MAX-format binary file from the specified serial port and stores in the given file. """ class State(Enum): DATA = auto() ESCAPE = auto() ADDR_HI = auto() ADDR_LO = auto() DONE = auto() state = State.DATA address = 0 intel_hex = IntelHex() if append: intel_hex.loadhex(file) with serial.serial_for_url(port) as ser: ser.baudrate = baud ser.write(constants.START_RECV) while state != State.DONE: data = ser.read(ser.in_waiting) for byte in data: if state == State.DATA: if byte == constants.ESCAPE: state = State.ESCAPE elif byte == constants.END_OF_FILE: state = State.DONE elif byte == constants.NEW_ADDRESS: state = State.ADDR_HI else: intel_hex[address] = byte address += 1 elif state == State.ESCAPE: intel_hex[address] = byte ^ 0x20 address += 1 state = State.DATA elif state == State.ADDR_HI: address = byte << 8 state = State.ADDR_LO elif state == State.ADDR_LO: address |= byte state = State.DATA intel_hex.write_hex_file(file) if __name__ == "__main__": main() # pylint: disable=no-value-for-parameter
27.353659
68
0.532769
import click import serial from enum import Enum, auto from intelhex import IntelHex,IntelHexError import constants @click.command() @click.argument( 'file', required=True, type=click.Path(dir_okay=False, writable=True) ) @click.option( '--append', '-a', help='append data to hex file', is_flag=True ) @click.option( '--port', '-p', required=True, help='serial port where ELF is connected' ) @click.option( '--baud', '-b', help='serial baud rate', type=int, default=9600 ) def main(file, append, port, baud): class State(Enum): DATA = auto() ESCAPE = auto() ADDR_HI = auto() ADDR_LO = auto() DONE = auto() state = State.DATA address = 0 intel_hex = IntelHex() if append: intel_hex.loadhex(file) with serial.serial_for_url(port) as ser: ser.baudrate = baud ser.write(constants.START_RECV) while state != State.DONE: data = ser.read(ser.in_waiting) for byte in data: if state == State.DATA: if byte == constants.ESCAPE: state = State.ESCAPE elif byte == constants.END_OF_FILE: state = State.DONE elif byte == constants.NEW_ADDRESS: state = State.ADDR_HI else: intel_hex[address] = byte address += 1 elif state == State.ESCAPE: intel_hex[address] = byte ^ 0x20 address += 1 state = State.DATA elif state == State.ADDR_HI: address = byte << 8 state = State.ADDR_LO elif state == State.ADDR_LO: address |= byte state = State.DATA intel_hex.write_hex_file(file) if __name__ == "__main__": main()
true
true
f714a790e3dbb16554cbe41c2190b6201936b882
1,522
py
Python
app.py
tylerhand/cals-floor
e8f88641e73425ad911f91984b0915cc0cec5446
[ "MIT" ]
null
null
null
app.py
tylerhand/cals-floor
e8f88641e73425ad911f91984b0915cc0cec5446
[ "MIT" ]
2
2019-08-12T05:21:10.000Z
2019-08-24T20:18:03.000Z
app.py
tylerhand/cals-floor
e8f88641e73425ad911f91984b0915cc0cec5446
[ "MIT" ]
null
null
null
from flask import Flask, render_template, redirect, abort, send_file from flaskext.markdown import Markdown import os.path from config import config app = Flask(__name__) Markdown(app) site_title=config['site_title'] site_all_notification=config['site_all_notification'] footer='<small class="m-0 text-center text-white">'+config['footer_text']+'</small>' root_directory=config['root_directory'] analytics=config['analytics'] seo_author=config['seo_author'] seo_description=config['seo_description'] @app.errorhandler(403) def forbidden(e): return render_template('403.html'), 403 @app.errorhandler(404) def page_not_found(e): return redirect('/pages/errors/404'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 @app.route('/') def redirect_index(): return redirect('/pages/home') @app.route('/pages/<path:request_path>') def render_markdown(request_path): path=root_directory+'/markdown/'+request_path+'.md' check = os.path.isfile(path) if check == False: abort(404) with open(path, 'r') as markdown_file: md = markdown_file.read() markdown_file.close() return render_template('main_bootstrap_frame.html', md=md,site_all_notification=site_all_notification,site_title=site_title,footer=footer,seo_author=seo_author,seo_description=seo_description) @app.route('/downloads/<path:file_path>') def send_a_file(file_path): file_path=root_directory+'/documents/'+file_path return send_file(file_path)
31.061224
196
0.756899
from flask import Flask, render_template, redirect, abort, send_file from flaskext.markdown import Markdown import os.path from config import config app = Flask(__name__) Markdown(app) site_title=config['site_title'] site_all_notification=config['site_all_notification'] footer='<small class="m-0 text-center text-white">'+config['footer_text']+'</small>' root_directory=config['root_directory'] analytics=config['analytics'] seo_author=config['seo_author'] seo_description=config['seo_description'] @app.errorhandler(403) def forbidden(e): return render_template('403.html'), 403 @app.errorhandler(404) def page_not_found(e): return redirect('/pages/errors/404'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 @app.route('/') def redirect_index(): return redirect('/pages/home') @app.route('/pages/<path:request_path>') def render_markdown(request_path): path=root_directory+'/markdown/'+request_path+'.md' check = os.path.isfile(path) if check == False: abort(404) with open(path, 'r') as markdown_file: md = markdown_file.read() markdown_file.close() return render_template('main_bootstrap_frame.html', md=md,site_all_notification=site_all_notification,site_title=site_title,footer=footer,seo_author=seo_author,seo_description=seo_description) @app.route('/downloads/<path:file_path>') def send_a_file(file_path): file_path=root_directory+'/documents/'+file_path return send_file(file_path)
true
true
f714a7f94b14209c01ac9354696aa33df0b5f72f
7,695
py
Python
docs/conf.py
hayata-yamamoto/tgs
9ace499b572afb72bdd43a579bb2520d5aa24e85
[ "MIT" ]
1
2018-07-21T07:35:05.000Z
2018-07-21T07:35:05.000Z
docs/conf.py
hayata-yamamoto/tgs
9ace499b572afb72bdd43a579bb2520d5aa24e85
[ "MIT" ]
3
2018-07-21T07:39:59.000Z
2018-07-21T08:54:33.000Z
docs/conf.py
hayata-yamamoto/tgs
9ace499b572afb72bdd43a579bb2520d5aa24e85
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # tgs documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'tgs' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'tgsdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'tgs.tex', u'tgs Documentation', u"hayata-yamamotoo", 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'tgs', u'tgs Documentation', [u"hayata-yamamotoo"], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'tgs', u'tgs Documentation', u"hayata-yamamotoo", 'tgs', 'tgs', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote'
31.408163
80
0.704483
import os import sys extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'tgs' # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'tgsdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'tgs.tex', u'tgs Documentation', u"hayata-yamamotoo", 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'tgs', u'tgs Documentation', [u"hayata-yamamotoo"], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'tgs', u'tgs Documentation', u"hayata-yamamotoo", 'tgs', 'tgs', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote'
true
true
f714a8349c35175175f8b080184942a963cc06c4
7,278
py
Python
onir/datasets/irds.py
Georgetown-IR-Lab/OpenNIR
7d93e8643fe311e3e9c7a0678efe9775fd80485e
[ "MIT" ]
140
2020-02-05T23:48:53.000Z
2022-03-29T03:47:31.000Z
onir/datasets/irds.py
Georgetown-IR-Lab/OpenNIR
7d93e8643fe311e3e9c7a0678efe9775fd80485e
[ "MIT" ]
33
2020-03-19T22:07:58.000Z
2022-02-23T15:18:29.000Z
onir/datasets/irds.py
Georgetown-IR-Lab/OpenNIR
7d93e8643fe311e3e9c7a0678efe9775fd80485e
[ "MIT" ]
16
2020-03-19T19:01:04.000Z
2021-12-12T04:18:57.000Z
import os import io import itertools import gzip import tarfile import zipfile import contextlib import functools from tqdm import tqdm from pytools import memoize_method import pandas as pd import ir_datasets import onir from onir import util, datasets, indices from onir.interfaces import trec, plaintext def sanitize_path(s): return s.replace('/', '--') @datasets.register('irds') class IrdsDataset(datasets.IndexBackedDataset): @staticmethod def default_config(): result = datasets.IndexBackedDataset.default_config() result.update({ 'ds': '', # used as shortcut 'doc_fields': '', # used as shortcut 'query_fields': '', # used as shortcut 'docs_ds': '', 'docs_index_fields': '', 'docs_rerank_fields': '', 'queries_ds': '', 'queries_index_fields': '', 'queries_rerank_fields': '', 'rankfn': onir.config.Ranker(), 'ranktopk': 100, }) return result def __init__(self, config, logger, vocab): super().__init__(config, logger, vocab) if config['ds']: ds = ir_datasets.load(config['ds']) if not config['docs_ds']: # HACK: find "parent" dataset that contains same docs handler so we don't re-build the index for the same collection segments = config['ds'].split('/') docs_handler = ds.docs_handler() parent_docs_ds = config['ds'] while len(segments) > 1: segments = segments[:-1] parent_ds = ir_datasets.load('/'.join(segments)) if parent_ds.has_docs() and parent_ds.docs_handler() == docs_handler: parent_docs_ds = '/'.join(segments) config['docs_ds'] = parent_docs_ds if not config['queries_ds']: config['queries_ds'] = config['ds'] if config['doc_fields']: if not config['docs_index_fields']: config['docs_index_fields'] = config['doc_fields'] if not config['docs_rerank_fields']: config['docs_rerank_fields'] = config['doc_fields'] if config['query_fields']: if not config['queries_index_fields']: config['queries_index_fields'] = config['query_fields'] if not config['queries_rerank_fields']: config['queries_rerank_fields'] = config['query_fields'] self.docs_ds = ir_datasets.load(config['docs_ds']) self.queries_ds = ir_datasets.load(config['queries_ds']) assert self.docs_ds.has_docs() assert self.queries_ds.has_queries() if not config['docs_index_fields']: config['docs_index_fields'] = ','.join(self.docs_ds.docs_cls()._fields[1:]) self.logger.info('auto-filled docs_index_fields as {docs_index_fields}'.format(**config)) if not config['docs_rerank_fields']: config['docs_rerank_fields'] = ','.join(self.docs_ds.docs_cls()._fields[1:]) self.logger.info('auto-filled docs_rerank_fields as {docs_rerank_fields}'.format(**config)) if not config['queries_index_fields']: config['queries_index_fields'] = ','.join(self.queries_ds.queries_cls()._fields[1:]) self.logger.info('auto-filled queries_index_fields as {queries_index_fields}'.format(**config)) if not config['queries_rerank_fields']: config['queries_rerank_fields'] = ','.join(self.queries_ds.queries_cls()._fields[1:]) self.logger.info('auto-filled queries_rerank_fields as {queries_rerank_fields}'.format(**config)) base_path = os.path.join(util.path_dataset(self), sanitize_path(self.config['docs_ds'])) os.makedirs(base_path, exist_ok=True) real_anserini_path = os.path.join(base_path, 'anserini.porter.{docs_index_fields}'.format(**self.config)) os.makedirs(real_anserini_path, exist_ok=True) virtual_anserini_path = '{}.{}'.format(real_anserini_path, sanitize_path(config['queries_ds'])) if not os.path.exists(virtual_anserini_path): os.symlink(real_anserini_path, virtual_anserini_path, target_is_directory=True) self.index = indices.AnseriniIndex(virtual_anserini_path, stemmer='porter') self.doc_store = indices.IrdsDocstore(self.docs_ds.docs_store(), config['docs_rerank_fields']) def _get_docstore(self): return self.doc_store def _get_index(self, record): return self.index def _get_index_for_batchsearch(self): return self.index @memoize_method def qrels(self, fmt='dict'): if fmt == 'dict': return self.queries_ds.qrels_dict() if fmt == 'df': df = pd.DataFrame(self.queries_ds.qrels_iter()) df = df.rename(columns={'query_id': 'qid', 'doc_id': 'did', 'relevance': 'score'}) return df raise RuntimeError(f'unsupported fmt={fmt}') @memoize_method def load_queries(self) -> dict: queries_cls = self.queries_ds.queries_cls() fields = self.config['queries_rerank_fields'].split(',') assert all(f in queries_cls._fields for f in fields) field_idxs = [queries_cls._fields.index(f) for f in fields] return {q.query_id: '\n'.join(q[i] for i in field_idxs) for q in self.queries_ds.queries_iter()} @memoize_method def _load_queries_base(self, subset): # HACK: this subtly only gets called for runs in this impl. Use queries_index_fields instead here. queries_cls = self.queries_ds.queries_cls() fields = self.config['queries_index_fields'].split(',') assert all(f in queries_cls._fields for f in fields) field_idxs = [queries_cls._fields.index(f) for f in fields] return {q.query_id: ' '.join(q[i] for i in field_idxs).replace('\n', ' ') for q in self.queries_ds.queries_iter()} def path_segment(self): return '__'.join([ super().path_segment(), sanitize_path(self.config["docs_ds"]), self.config['docs_index_fields'], self.config['docs_rerank_fields'], sanitize_path(self.config["queries_ds"]), self.config['queries_index_fields'], self.config['queries_rerank_fields']]) def init(self, force=False): if not self.index.built() or force: doc_it = self._init_iter_collection() doc_it = self.logger.pbar(doc_it, 'docs') self.index.build(doc_it) # Attempt to grab everything (without wasting too many resources). # This isn't really a guarantee we have everything, but it should work in most cases. next(self.docs_ds.docs_iter()) next(self.queries_ds.queries_iter()) next(self.queries_ds.qrels_iter()) def _init_iter_collection(self): docs_cls = self.docs_ds.docs_cls() fields = self.config['docs_index_fields'].split(',') assert all(f in docs_cls._fields for f in fields) field_idxs = [docs_cls._fields.index(f) for f in fields] for doc in self.docs_ds.docs_iter(): yield indices.RawDoc(doc.doc_id, '\n'.join(str(doc[i]) for i in field_idxs))
44.109091
132
0.632454
import os import io import itertools import gzip import tarfile import zipfile import contextlib import functools from tqdm import tqdm from pytools import memoize_method import pandas as pd import ir_datasets import onir from onir import util, datasets, indices from onir.interfaces import trec, plaintext def sanitize_path(s): return s.replace('/', '--') @datasets.register('irds') class IrdsDataset(datasets.IndexBackedDataset): @staticmethod def default_config(): result = datasets.IndexBackedDataset.default_config() result.update({ 'ds': '', 'doc_fields': '', 'query_fields': '', 'docs_ds': '', 'docs_index_fields': '', 'docs_rerank_fields': '', 'queries_ds': '', 'queries_index_fields': '', 'queries_rerank_fields': '', 'rankfn': onir.config.Ranker(), 'ranktopk': 100, }) return result def __init__(self, config, logger, vocab): super().__init__(config, logger, vocab) if config['ds']: ds = ir_datasets.load(config['ds']) if not config['docs_ds']: segments = config['ds'].split('/') docs_handler = ds.docs_handler() parent_docs_ds = config['ds'] while len(segments) > 1: segments = segments[:-1] parent_ds = ir_datasets.load('/'.join(segments)) if parent_ds.has_docs() and parent_ds.docs_handler() == docs_handler: parent_docs_ds = '/'.join(segments) config['docs_ds'] = parent_docs_ds if not config['queries_ds']: config['queries_ds'] = config['ds'] if config['doc_fields']: if not config['docs_index_fields']: config['docs_index_fields'] = config['doc_fields'] if not config['docs_rerank_fields']: config['docs_rerank_fields'] = config['doc_fields'] if config['query_fields']: if not config['queries_index_fields']: config['queries_index_fields'] = config['query_fields'] if not config['queries_rerank_fields']: config['queries_rerank_fields'] = config['query_fields'] self.docs_ds = ir_datasets.load(config['docs_ds']) self.queries_ds = ir_datasets.load(config['queries_ds']) assert self.docs_ds.has_docs() assert self.queries_ds.has_queries() if not config['docs_index_fields']: config['docs_index_fields'] = ','.join(self.docs_ds.docs_cls()._fields[1:]) self.logger.info('auto-filled docs_index_fields as {docs_index_fields}'.format(**config)) if not config['docs_rerank_fields']: config['docs_rerank_fields'] = ','.join(self.docs_ds.docs_cls()._fields[1:]) self.logger.info('auto-filled docs_rerank_fields as {docs_rerank_fields}'.format(**config)) if not config['queries_index_fields']: config['queries_index_fields'] = ','.join(self.queries_ds.queries_cls()._fields[1:]) self.logger.info('auto-filled queries_index_fields as {queries_index_fields}'.format(**config)) if not config['queries_rerank_fields']: config['queries_rerank_fields'] = ','.join(self.queries_ds.queries_cls()._fields[1:]) self.logger.info('auto-filled queries_rerank_fields as {queries_rerank_fields}'.format(**config)) base_path = os.path.join(util.path_dataset(self), sanitize_path(self.config['docs_ds'])) os.makedirs(base_path, exist_ok=True) real_anserini_path = os.path.join(base_path, 'anserini.porter.{docs_index_fields}'.format(**self.config)) os.makedirs(real_anserini_path, exist_ok=True) virtual_anserini_path = '{}.{}'.format(real_anserini_path, sanitize_path(config['queries_ds'])) if not os.path.exists(virtual_anserini_path): os.symlink(real_anserini_path, virtual_anserini_path, target_is_directory=True) self.index = indices.AnseriniIndex(virtual_anserini_path, stemmer='porter') self.doc_store = indices.IrdsDocstore(self.docs_ds.docs_store(), config['docs_rerank_fields']) def _get_docstore(self): return self.doc_store def _get_index(self, record): return self.index def _get_index_for_batchsearch(self): return self.index @memoize_method def qrels(self, fmt='dict'): if fmt == 'dict': return self.queries_ds.qrels_dict() if fmt == 'df': df = pd.DataFrame(self.queries_ds.qrels_iter()) df = df.rename(columns={'query_id': 'qid', 'doc_id': 'did', 'relevance': 'score'}) return df raise RuntimeError(f'unsupported fmt={fmt}') @memoize_method def load_queries(self) -> dict: queries_cls = self.queries_ds.queries_cls() fields = self.config['queries_rerank_fields'].split(',') assert all(f in queries_cls._fields for f in fields) field_idxs = [queries_cls._fields.index(f) for f in fields] return {q.query_id: '\n'.join(q[i] for i in field_idxs) for q in self.queries_ds.queries_iter()} @memoize_method def _load_queries_base(self, subset): # HACK: this subtly only gets called for runs in this impl. Use queries_index_fields instead here. queries_cls = self.queries_ds.queries_cls() fields = self.config['queries_index_fields'].split(',') assert all(f in queries_cls._fields for f in fields) field_idxs = [queries_cls._fields.index(f) for f in fields] return {q.query_id: ' '.join(q[i] for i in field_idxs).replace('\n', ' ') for q in self.queries_ds.queries_iter()} def path_segment(self): return '__'.join([ super().path_segment(), sanitize_path(self.config["docs_ds"]), self.config['docs_index_fields'], self.config['docs_rerank_fields'], sanitize_path(self.config["queries_ds"]), self.config['queries_index_fields'], self.config['queries_rerank_fields']]) def init(self, force=False): if not self.index.built() or force: doc_it = self._init_iter_collection() doc_it = self.logger.pbar(doc_it, 'docs') self.index.build(doc_it) # Attempt to grab everything (without wasting too many resources). # This isn't really a guarantee we have everything, but it should work in most cases. next(self.docs_ds.docs_iter()) next(self.queries_ds.queries_iter()) next(self.queries_ds.qrels_iter()) def _init_iter_collection(self): docs_cls = self.docs_ds.docs_cls() fields = self.config['docs_index_fields'].split(',') assert all(f in docs_cls._fields for f in fields) field_idxs = [docs_cls._fields.index(f) for f in fields] for doc in self.docs_ds.docs_iter(): yield indices.RawDoc(doc.doc_id, '\n'.join(str(doc[i]) for i in field_idxs))
true
true
f714a85c25186d4ad6710276141011796da70208
89
py
Python
unidade/apps.py
Bleno/sisgestor-django
c35f76eafc3e51afb99c84245e01881cef43aa5b
[ "MIT" ]
1
2017-04-27T19:26:49.000Z
2017-04-27T19:26:49.000Z
unidade/apps.py
Bleno/sisgestor-django
c35f76eafc3e51afb99c84245e01881cef43aa5b
[ "MIT" ]
null
null
null
unidade/apps.py
Bleno/sisgestor-django
c35f76eafc3e51afb99c84245e01881cef43aa5b
[ "MIT" ]
null
null
null
from django.apps import AppConfig class UnidadeConfig(AppConfig): name = 'unidade'
14.833333
33
0.752809
from django.apps import AppConfig class UnidadeConfig(AppConfig): name = 'unidade'
true
true
f714a8ad00f77d833fe83f5364b33aa3d0322404
988
py
Python
python/paddle/fluid/tests/unittests/test_dist_mnist_lars.py
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
11
2016-08-29T07:43:26.000Z
2016-08-29T07:51:24.000Z
python/paddle/fluid/tests/unittests/test_dist_mnist_lars.py
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
null
null
null
python/paddle/fluid/tests/unittests/test_dist_mnist_lars.py
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
1
2021-12-09T08:59:17.000Z
2021-12-09T08:59:17.000Z
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import unittest from test_dist_base import TestDistBase class TestDistMnist2x2Lars(TestDistBase): def _setup_config(self): self._sync_mode = True self._use_reduce = False def test_se_resnext(self): self.check_with_place("dist_mnist_lars.py", delta=1e-5) if __name__ == "__main__": unittest.main()
30.875
74
0.751012
from __future__ import print_function import unittest from test_dist_base import TestDistBase class TestDistMnist2x2Lars(TestDistBase): def _setup_config(self): self._sync_mode = True self._use_reduce = False def test_se_resnext(self): self.check_with_place("dist_mnist_lars.py", delta=1e-5) if __name__ == "__main__": unittest.main()
true
true
f714a910233f8c72b6035a03576874ffbf9fc901
152,100
py
Python
salt/modules/cmdmod.py
guoxiaod/salt
2cd6c03b40932be137e6e8a672967b59025a2d34
[ "Apache-2.0" ]
null
null
null
salt/modules/cmdmod.py
guoxiaod/salt
2cd6c03b40932be137e6e8a672967b59025a2d34
[ "Apache-2.0" ]
null
null
null
salt/modules/cmdmod.py
guoxiaod/salt
2cd6c03b40932be137e6e8a672967b59025a2d34
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- ''' A module for shelling out. Keep in mind that this module is insecure, in that it can give whomever has access to the master root execution access to all salt minions. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import functools import glob import logging import os import shutil import subprocess import sys import time import traceback import fnmatch import base64 import re import tempfile # Import salt libs import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.json import salt.utils.path import salt.utils.platform import salt.utils.powershell import salt.utils.stringutils import salt.utils.templates import salt.utils.timed_subprocess import salt.utils.user import salt.utils.versions import salt.utils.vt import salt.utils.win_dacl import salt.utils.win_reg import salt.grains.extra from salt.ext import six from salt.exceptions import CommandExecutionError, TimedProcTimeoutError, \ SaltInvocationError from salt.log import LOG_LEVELS from salt.ext.six.moves import range, zip, map # Only available on POSIX systems, nonfatal on windows try: import pwd import grp except ImportError: pass if salt.utils.platform.is_windows(): from salt.utils.win_runas import runas as win_runas from salt.utils.win_functions import escape_argument as _cmd_quote HAS_WIN_RUNAS = True else: from salt.ext.six.moves import shlex_quote as _cmd_quote HAS_WIN_RUNAS = False __proxyenabled__ = ['*'] # Define the module's virtual name __virtualname__ = 'cmd' # Set up logging log = logging.getLogger(__name__) DEFAULT_SHELL = salt.grains.extra.shell()['shell'] # Overwriting the cmd python module makes debugging modules with pdb a bit # harder so lets do it this way instead. def __virtual__(): return __virtualname__ def _check_cb(cb_): ''' If the callback is None or is not callable, return a lambda that returns the value passed. ''' if cb_ is not None: if hasattr(cb_, '__call__'): return cb_ else: log.error('log_callback is not callable, ignoring') return lambda x: x def _python_shell_default(python_shell, __pub_jid): ''' Set python_shell default based on remote execution and __opts__['cmd_safe'] ''' try: # Default to python_shell=True when run directly from remote execution # system. Cross-module calls won't have a jid. if __pub_jid and python_shell is None: return True elif __opts__.get('cmd_safe', True) is False and python_shell is None: # Override-switch for python_shell return True except NameError: pass return python_shell def _chroot_pids(chroot): pids = [] for root in glob.glob('/proc/[0-9]*/root'): try: link = os.path.realpath(root) if link.startswith(chroot): pids.append(int(os.path.basename( os.path.dirname(root) ))) except OSError: pass return pids def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None): ''' If template is a valid template engine, process the cmd and cwd through that engine. ''' if not template: return (cmd, cwd) # render the path as a template using path_template_engine as the engine if template not in salt.utils.templates.TEMPLATE_REGISTRY: raise CommandExecutionError( 'Attempted to render file paths with unavailable engine ' '{0}'.format(template) ) kwargs = {} kwargs['salt'] = __salt__ if pillarenv is not None or pillar_override is not None: pillarenv = pillarenv or __opts__['pillarenv'] kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override) else: kwargs['pillar'] = __pillar__ kwargs['grains'] = __grains__ kwargs['opts'] = __opts__ kwargs['saltenv'] = saltenv def _render(contents): # write out path to temp file tmp_path_fn = salt.utils.files.mkstemp() with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_: fp_.write(salt.utils.stringutils.to_str(contents)) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( tmp_path_fn, to_str=True, **kwargs ) salt.utils.files.safe_rm(tmp_path_fn) if not data['result']: # Failed to render the template raise CommandExecutionError( 'Failed to execute cmd with error: {0}'.format( data['data'] ) ) else: return data['data'] cmd = _render(cmd) cwd = _render(cwd) return (cmd, cwd) def _check_loglevel(level='info'): ''' Retrieve the level code for use in logging.Logger.log(). ''' try: level = level.lower() if level == 'quiet': return None else: return LOG_LEVELS[level] except (AttributeError, KeyError): log.error( 'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling ' 'back to \'info\'.', level, ', '.join(sorted(LOG_LEVELS, reverse=True)) ) return LOG_LEVELS['info'] def _parse_env(env): if not env: env = {} if isinstance(env, list): env = salt.utils.data.repack_dictlist(env) if not isinstance(env, dict): env = {} return env def _gather_pillar(pillarenv, pillar_override): ''' Whenever a state run starts, gather the pillar data fresh ''' pillar = salt.pillar.get_pillar( __opts__, __grains__, __opts__['id'], __opts__['saltenv'], pillar_override=pillar_override, pillarenv=pillarenv ) ret = pillar.compile_pillar() if pillar_override and isinstance(pillar_override, dict): ret.update(pillar_override) return ret def _check_avail(cmd): ''' Check to see if the given command can be run ''' if isinstance(cmd, list): cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x for x in cmd]) bret = True wret = False if __salt__['config.get']('cmd_blacklist_glob'): blist = __salt__['config.get']('cmd_blacklist_glob', []) for comp in blist: if fnmatch.fnmatch(cmd, comp): # BAD! you are blacklisted bret = False if __salt__['config.get']('cmd_whitelist_glob', []): blist = __salt__['config.get']('cmd_whitelist_glob', []) for comp in blist: if fnmatch.fnmatch(cmd, comp): # GOOD! You are whitelisted wret = True break else: # If no whitelist set then alls good! wret = True return bret and wret def _run(cmd, cwd=None, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, output_encoding=None, output_loglevel='debug', log_callback=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, prepend_path=None, rstrip=True, template=None, umask=None, timeout=None, with_communicate=True, reset_system_locale=True, ignore_retcode=False, saltenv='base', pillarenv=None, pillar_override=None, use_vt=False, password=None, bg=False, encoded_cmd=False, success_retcodes=None, **kwargs): ''' Do the DRY thing and only call subprocess.Popen() once ''' if 'pillar' in kwargs and not pillar_override: pillar_override = kwargs['pillar'] if _is_valid_shell(shell) is False: log.warning( 'Attempt to run a shell command with what may be an invalid shell! ' 'Check to ensure that the shell <%s> is valid for this user.', shell ) output_loglevel = _check_loglevel(output_loglevel) log_callback = _check_cb(log_callback) use_sudo = False if runas is None and '__context__' in globals(): runas = __context__.get('runas') if password is None and '__context__' in globals(): password = __context__.get('runas_password') # Set the default working directory to the home directory of the user # salt-minion is running as. Defaults to home directory of user under which # the minion is running. if not cwd: cwd = os.path.expanduser('~{0}'.format('' if not runas else runas)) # make sure we can access the cwd # when run from sudo or another environment where the euid is # changed ~ will expand to the home of the original uid and # the euid might not have access to it. See issue #1844 if not os.access(cwd, os.R_OK): cwd = '/' if salt.utils.platform.is_windows(): cwd = os.path.abspath(os.sep) else: # Handle edge cases where numeric/other input is entered, and would be # yaml-ified into non-string types cwd = six.text_type(cwd) if bg: ignore_retcode = True use_vt = False if not salt.utils.platform.is_windows(): if not os.path.isfile(shell) or not os.access(shell, os.X_OK): msg = 'The shell {0} is not available'.format(shell) raise CommandExecutionError(msg) if salt.utils.platform.is_windows() and use_vt: # Memozation so not much overhead raise CommandExecutionError('VT not available on windows') if shell.lower().strip() == 'powershell': # Strip whitespace if isinstance(cmd, six.string_types): cmd = cmd.strip() # If we were called by script(), then fakeout the Windows # shell to run a Powershell script. # Else just run a Powershell command. stack = traceback.extract_stack(limit=2) # extract_stack() returns a list of tuples. # The last item in the list [-1] is the current method. # The third item[2] in each tuple is the name of that method. if stack[-2][2] == 'script': cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd elif encoded_cmd: cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd) else: cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"')) # munge the cmd and cwd through the template (cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override) ret = {} # If the pub jid is here then this is a remote ex or salt call command and needs to be # checked if blacklisted if '__pub_jid' in kwargs: if not _check_avail(cmd): raise CommandExecutionError( 'The shell command "{0}" is not permitted'.format(cmd) ) env = _parse_env(env) for bad_env_key in (x for x, y in six.iteritems(env) if y is None): log.error('Environment variable \'%s\' passed without a value. ' 'Setting value to an empty string', bad_env_key) env[bad_env_key] = '' def _get_stripped(cmd): # Return stripped command string copies to improve logging. if isinstance(cmd, list): return [x.strip() if isinstance(x, six.string_types) else x for x in cmd] elif isinstance(cmd, six.string_types): return cmd.strip() else: return cmd if output_loglevel is not None: # Always log the shell commands at INFO unless quiet logging is # requested. The command output is what will be controlled by the # 'loglevel' parameter. msg = ( 'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format( '\'' if not isinstance(cmd, list) else '', _get_stripped(cmd), 'as user \'{0}\' '.format(runas) if runas else '', 'in group \'{0}\' '.format(group) if group else '', cwd, '. Executing command in the background, no output will be ' 'logged.' if bg else '' ) ) log.info(log_callback(msg)) if runas and salt.utils.platform.is_windows(): if not HAS_WIN_RUNAS: msg = 'missing salt/utils/win_runas.py' raise CommandExecutionError(msg) if isinstance(cmd, (list, tuple)): cmd = ' '.join(cmd) return win_runas(cmd, runas, password, cwd) if runas and salt.utils.platform.is_darwin(): # we need to insert the user simulation into the command itself and not # just run it from the environment on macOS as that # method doesn't work properly when run as root for certain commands. if isinstance(cmd, (list, tuple)): cmd = ' '.join(map(_cmd_quote, cmd)) cmd = 'su -l {0} -c "{1}"'.format(runas, cmd) # set runas to None, because if you try to run `su -l` as well as # simulate the environment macOS will prompt for the password of the # user and will cause salt to hang. runas = None if runas: # Save the original command before munging it try: pwd.getpwnam(runas) except KeyError: raise CommandExecutionError( 'User \'{0}\' is not available'.format(runas) ) if group: if salt.utils.platform.is_windows(): msg = 'group is not currently available on Windows' raise SaltInvocationError(msg) if not which_bin(['sudo']): msg = 'group argument requires sudo but not found' raise CommandExecutionError(msg) try: grp.getgrnam(group) except KeyError: raise CommandExecutionError( 'Group \'{0}\' is not available'.format(runas) ) else: use_sudo = True if runas or group: try: # Getting the environment for the runas user # Use markers to thwart any stdout noise # There must be a better way to do this. import uuid marker = '<<<' + str(uuid.uuid4()) + '>>>' marker_b = marker.encode(__salt_system_encoding__) py_code = ( 'import sys, os, itertools; ' 'sys.stdout.write(\"' + marker + '\"); ' 'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); ' 'sys.stdout.write(\"' + marker + '\");' ) if use_sudo or __grains__['os'] in ['MacOS', 'Darwin']: env_cmd = ['sudo'] # runas is optional if use_sudo is set. if runas: env_cmd.extend(['-u', runas]) if group: env_cmd.extend(['-g', group]) if shell != DEFAULT_SHELL: env_cmd.extend(['-s', '--', shell, '-c']) else: env_cmd.extend(['-i', '--']) env_cmd.extend([sys.executable]) elif __grains__['os'] in ['FreeBSD']: env_cmd = ('su', '-', runas, '-c', "{0} -c {1}".format(shell, sys.executable)) elif __grains__['os_family'] in ['Solaris']: env_cmd = ('su', '-', runas, '-c', sys.executable) elif __grains__['os_family'] in ['AIX']: env_cmd = ('su', '-', runas, '-c', sys.executable) else: env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable) msg = 'env command: {0}'.format(env_cmd) log.debug(log_callback(msg)) env_bytes, env_encoded_err = subprocess.Popen( env_cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE ).communicate(salt.utils.stringutils.to_bytes(py_code)) marker_count = env_bytes.count(marker_b) if marker_count == 0: # Possibly PAM prevented the login log.error( 'Environment could not be retrieved for user \'%s\': ' 'stderr=%r stdout=%r', runas, env_encoded_err, env_bytes ) # Ensure that we get an empty env_runas dict below since we # were not able to get the environment. env_bytes = b'' elif marker_count != 2: raise CommandExecutionError( 'Environment could not be retrieved for user \'{0}\'', info={'stderr': repr(env_encoded_err), 'stdout': repr(env_bytes)} ) else: # Strip the marker env_bytes = env_bytes.split(marker_b)[1] if six.PY2: import itertools env_runas = dict(itertools.izip(*[iter(env_bytes.split(b'\0'))]*2)) elif six.PY3: env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2))) env_runas = dict( (salt.utils.stringutils.to_str(k), salt.utils.stringutils.to_str(v)) for k, v in six.iteritems(env_runas) ) env_runas.update(env) # Fix platforms like Solaris that don't set a USER env var in the # user's default environment as obtained above. if env_runas.get('USER') != runas: env_runas['USER'] = runas # Fix some corner cases where shelling out to get the user's # environment returns the wrong home directory. runas_home = os.path.expanduser('~{0}'.format(runas)) if env_runas.get('HOME') != runas_home: env_runas['HOME'] = runas_home env = env_runas except ValueError as exc: log.exception('Error raised retrieving environment for user %s', runas) raise CommandExecutionError( 'Environment could not be retrieved for user \'{0}\': {1}'.format( runas, exc ) ) if reset_system_locale is True: if not salt.utils.platform.is_windows(): # Default to C! # Salt only knows how to parse English words # Don't override if the user has passed LC_ALL env.setdefault('LC_CTYPE', 'C') env.setdefault('LC_NUMERIC', 'C') env.setdefault('LC_TIME', 'C') env.setdefault('LC_COLLATE', 'C') env.setdefault('LC_MONETARY', 'C') env.setdefault('LC_MESSAGES', 'C') env.setdefault('LC_PAPER', 'C') env.setdefault('LC_NAME', 'C') env.setdefault('LC_ADDRESS', 'C') env.setdefault('LC_TELEPHONE', 'C') env.setdefault('LC_MEASUREMENT', 'C') env.setdefault('LC_IDENTIFICATION', 'C') env.setdefault('LANGUAGE', 'C') else: # On Windows set the codepage to US English. if python_shell: cmd = 'chcp 437 > nul & ' + cmd if clean_env: run_env = env else: run_env = os.environ.copy() run_env.update(env) if prepend_path: run_env['PATH'] = ':'.join((prepend_path, run_env['PATH'])) if python_shell is None: python_shell = False new_kwargs = {'cwd': cwd, 'shell': python_shell, 'env': run_env if six.PY3 else salt.utils.data.encode(run_env), 'stdin': six.text_type(stdin) if stdin is not None else stdin, 'stdout': stdout, 'stderr': stderr, 'with_communicate': with_communicate, 'timeout': timeout, 'bg': bg, } if 'stdin_raw_newlines' in kwargs: new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines'] if umask is not None: _umask = six.text_type(umask).lstrip('0') if _umask == '': msg = 'Zero umask is not allowed.' raise CommandExecutionError(msg) try: _umask = int(_umask, 8) except ValueError: raise CommandExecutionError("Invalid umask: '{0}'".format(umask)) else: _umask = None if runas or group or umask: new_kwargs['preexec_fn'] = functools.partial( salt.utils.user.chugid_and_umask, runas, _umask, group) if not salt.utils.platform.is_windows(): # close_fds is not supported on Windows platforms if you redirect # stdin/stdout/stderr if new_kwargs['shell'] is True: new_kwargs['executable'] = shell new_kwargs['close_fds'] = True if not os.path.isabs(cwd) or not os.path.isdir(cwd): raise CommandExecutionError( 'Specified cwd \'{0}\' either not absolute or does not exist' .format(cwd) ) if python_shell is not True \ and not salt.utils.platform.is_windows() \ and not isinstance(cmd, list): cmd = salt.utils.args.shlex_split(cmd) if success_retcodes is None: success_retcodes = [0] else: try: success_retcodes = [int(i) for i in salt.utils.args.split_input( success_retcodes )] except ValueError: raise SaltInvocationError( 'success_retcodes must be a list of integers' ) if not use_vt: # This is where the magic happens try: proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs) except (OSError, IOError) as exc: msg = ( 'Unable to run command \'{0}\' with the context \'{1}\', ' 'reason: '.format( cmd if output_loglevel is not None else 'REDACTED', new_kwargs ) ) try: if exc.filename is None: msg += 'command not found' else: msg += '{0}: {1}'.format(exc, exc.filename) except AttributeError: # Both IOError and OSError have the filename attribute, so this # is a precaution in case the exception classes in the previous # try/except are changed. msg += 'unknown' raise CommandExecutionError(msg) try: proc.run() except TimedProcTimeoutError as exc: ret['stdout'] = six.text_type(exc) ret['stderr'] = '' ret['retcode'] = None ret['pid'] = proc.process.pid # ok return code for timeouts? ret['retcode'] = 1 return ret if output_loglevel != 'quiet' and output_encoding is not None: log.debug('Decoding output from command %s using %s encoding', cmd, output_encoding) try: out = salt.utils.stringutils.to_unicode( proc.stdout, encoding=output_encoding) except TypeError: # stdout is None out = '' except UnicodeDecodeError: out = salt.utils.stringutils.to_unicode( proc.stdout, encoding=output_encoding, errors='replace') if output_loglevel != 'quiet': log.error( 'Failed to decode stdout from command %s, non-decodable ' 'characters have been replaced', cmd ) try: err = salt.utils.stringutils.to_unicode( proc.stderr, encoding=output_encoding) except TypeError: # stderr is None err = '' except UnicodeDecodeError: err = salt.utils.stringutils.to_unicode( proc.stderr, encoding=output_encoding, errors='replace') if output_loglevel != 'quiet': log.error( 'Failed to decode stderr from command %s, non-decodable ' 'characters have been replaced', cmd ) if rstrip: if out is not None: out = out.rstrip() if err is not None: err = err.rstrip() ret['pid'] = proc.process.pid ret['retcode'] = proc.process.returncode if ret['retcode'] in success_retcodes: ret['retcode'] = 0 ret['stdout'] = out ret['stderr'] = err else: formatted_timeout = '' if timeout: formatted_timeout = ' (timeout: {0}s)'.format(timeout) if output_loglevel is not None: msg = 'Running {0} in VT{1}'.format(cmd, formatted_timeout) log.debug(log_callback(msg)) stdout, stderr = '', '' now = time.time() if timeout: will_timeout = now + timeout else: will_timeout = -1 try: proc = salt.utils.vt.Terminal( cmd, shell=True, log_stdout=True, log_stderr=True, cwd=cwd, preexec_fn=new_kwargs.get('preexec_fn', None), env=run_env, log_stdin_level=output_loglevel, log_stdout_level=output_loglevel, log_stderr_level=output_loglevel, stream_stdout=True, stream_stderr=True ) ret['pid'] = proc.pid while proc.has_unread_data: try: try: time.sleep(0.5) try: cstdout, cstderr = proc.recv() except IOError: cstdout, cstderr = '', '' if cstdout: stdout += cstdout else: cstdout = '' if cstderr: stderr += cstderr else: cstderr = '' if timeout and (time.time() > will_timeout): ret['stderr'] = ( 'SALT: Timeout after {0}s\n{1}').format( timeout, stderr) ret['retcode'] = None break except KeyboardInterrupt: ret['stderr'] = 'SALT: User break\n{0}'.format(stderr) ret['retcode'] = 1 break except salt.utils.vt.TerminalException as exc: log.error('VT: %s', exc, exc_info_on_loglevel=logging.DEBUG) ret = {'retcode': 1, 'pid': '2'} break # only set stdout on success as we already mangled in other # cases ret['stdout'] = stdout if not proc.isalive(): # Process terminated, i.e., not canceled by the user or by # the timeout ret['stderr'] = stderr ret['retcode'] = proc.exitstatus if ret['retcode'] in success_retcodes: ret['retcode'] = 0 ret['pid'] = proc.pid finally: proc.close(terminate=True, kill=True) try: if ignore_retcode: __context__['retcode'] = 0 else: __context__['retcode'] = ret['retcode'] except NameError: # Ignore the context error during grain generation pass # Log the output if output_loglevel is not None: if not ignore_retcode and ret['retcode'] != 0: if output_loglevel < LOG_LEVELS['error']: output_loglevel = LOG_LEVELS['error'] msg = ( 'Command \'{0}\' failed with return code: {1}'.format( cmd, ret['retcode'] ) ) log.error(log_callback(msg)) if ret['stdout']: log.log(output_loglevel, 'stdout: {0}'.format(log_callback(ret['stdout']))) if ret['stderr']: log.log(output_loglevel, 'stderr: {0}'.format(log_callback(ret['stderr']))) if ret['retcode']: log.log(output_loglevel, 'retcode: {0}'.format(ret['retcode'])) return ret def _run_quiet(cmd, cwd=None, stdin=None, output_encoding=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, template=None, umask=None, timeout=None, reset_system_locale=True, saltenv='base', pillarenv=None, pillar_override=None, success_retcodes=None): ''' Helper for running commands quietly for minion startup ''' return _run(cmd, runas=runas, cwd=cwd, stdin=stdin, stderr=subprocess.STDOUT, output_encoding=output_encoding, output_loglevel='quiet', log_callback=None, shell=shell, python_shell=python_shell, env=env, template=template, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, pillarenv=pillarenv, pillar_override=pillar_override, success_retcodes=success_retcodes)['stdout'] def _run_all_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, template=None, umask=None, timeout=None, reset_system_locale=True, saltenv='base', pillarenv=None, pillar_override=None, output_encoding=None, success_retcodes=None): ''' Helper for running commands quietly for minion startup. Returns a dict of return data. output_loglevel argument is ignored. This is here for when we alias cmd.run_all directly to _run_all_quiet in certain chicken-and-egg situations where modules need to work both before and after the __salt__ dictionary is populated (cf dracr.py) ''' return _run(cmd, runas=runas, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, output_encoding=output_encoding, output_loglevel='quiet', log_callback=None, template=template, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, pillarenv=pillarenv, pillar_override=pillar_override, success_retcodes=success_retcodes) def run(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, bg=False, password=None, encoded_cmd=False, raise_err=False, prepend_path=None, success_retcodes=None, **kwargs): r''' Execute the passed command and return the output as a string :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. :param str group: Group to run command as. Not currently supported on Windows. :param str password: Windows only. Only required when the minion proccess is running under a non-privileged account. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If ``False``, let python handle the positional arguments. Set to ``True`` to use shell features, such as pipes or redirection. :param bool bg: If ``True``, run command in background and do not await or deliver it's results .. versionadded:: 2016.3.0 :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.run 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary) to $PATH .. versionadded:: 2018.3.0 :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: A timeout in seconds for the executed process to return. :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. :param bool encoded_cmd: Specify if the supplied command is encoded. Only applies to shell 'powershell'. :param bool raise_err: If ``True`` and the command has a nonzero exit code, a CommandExecutionError exception will be raised. .. warning:: This function does not process commands through a shell unless the python_shell flag is set to True. This means that any shell-specific functionality such as 'echo' or the use of pipes, redirection or &&, should either be migrated to cmd.shell or have the python_shell=True flag set here. The use of python_shell=True means that the shell will accept _any_ input including potentially malicious commands such as 'good_command;rm -rf /'. Be absolutely certain that you have sanitized your input prior to using python_shell=True :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine CLI Example: .. code-block:: bash salt '*' cmd.run "ls -l | awk '/foo/{print \\$2}'" The template arg can be set to 'jinja' or another supported template engine to render the command arguments before execution. For example: .. code-block:: bash salt '*' cmd.run template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'" Specify an alternate shell with the shell parameter: .. code-block:: bash salt '*' cmd.run "Get-ChildItem C:\\ " shell='powershell' A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.run "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' cmd.run cmd='sed -e s/=/:/g' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, shell=shell, python_shell=python_shell, cwd=cwd, stdin=stdin, stderr=subprocess.STDOUT, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, bg=bg, password=password, encoded_cmd=encoded_cmd, success_retcodes=success_retcodes, **kwargs) log_callback = _check_cb(log_callback) lvl = _check_loglevel(output_loglevel) if lvl is not None: if not ignore_retcode and ret['retcode'] != 0: if lvl < LOG_LEVELS['error']: lvl = LOG_LEVELS['error'] msg = ( 'Command \'{0}\' failed with return code: {1}'.format( cmd, ret['retcode'] ) ) log.error(log_callback(msg)) if raise_err: raise CommandExecutionError( log_callback(ret['stdout'] if not hide_output else '') ) log.log(lvl, 'output: %s', log_callback(ret['stdout'])) return ret['stdout'] if not hide_output else '' def shell(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, bg=False, password=None, prepend_path=None, success_retcodes=None, **kwargs): ''' Execute the passed command and return the output as a string. .. versionadded:: 2015.5.0 :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str group: Group to run command as. Not currently supported on Windows. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param int shell: Shell to execute under. Defaults to the system default shell. :param bool bg: If True, run command in background and do not await or deliver its results :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.shell 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary) to $PATH .. versionadded:: 2018.3.0 :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: A timeout in seconds for the executed process to return. :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. .. warning:: This passes the cmd argument directly to the shell without any further processing! Be absolutely sure that you have properly sanitized the command passed to this function and do not use untrusted inputs. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine CLI Example: .. code-block:: bash salt '*' cmd.shell "ls -l | awk '/foo/{print \\$2}'" The template arg can be set to 'jinja' or another supported template engine to render the command arguments before execution. For example: .. code-block:: bash salt '*' cmd.shell template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'" Specify an alternate shell with the shell parameter: .. code-block:: bash salt '*' cmd.shell "Get-ChildItem C:\\ " shell='powershell' A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.shell "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' cmd.shell cmd='sed -e s/=/:/g' ''' if 'python_shell' in kwargs: python_shell = kwargs.pop('python_shell') else: python_shell = True return run(cmd, cwd=cwd, stdin=stdin, runas=runas, group=group, shell=shell, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, hide_output=hide_output, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, python_shell=python_shell, bg=bg, password=password, success_retcodes=success_retcodes, **kwargs) def run_stdout(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, prepend_path=None, success_retcodes=None, **kwargs): ''' Execute a command, and only return the standard out :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str group: Group to run command as. Not currently supported on Windows. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.run_stdout 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary) to $PATH .. versionadded:: 2018.3.0 :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: A timeout in seconds for the executed process to return. :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine CLI Example: .. code-block:: bash salt '*' cmd.run_stdout "ls -l | awk '/foo/{print \\$2}'" The template arg can be set to 'jinja' or another supported template engine to render the command arguments before execution. For example: .. code-block:: bash salt '*' cmd.run_stdout template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'" A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.run_stdout "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, success_retcodes=success_retcodes, **kwargs) return ret['stdout'] if not hide_output else '' def run_stderr(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, prepend_path=None, success_retcodes=None, **kwargs): ''' Execute a command and only return the standard error :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str group: Group to run command as. Not currently supported on Windows. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.run_stderr 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary) to $PATH .. versionadded:: 2018.3.0 :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: A timeout in seconds for the executed process to return. :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine CLI Example: .. code-block:: bash salt '*' cmd.run_stderr "ls -l | awk '/foo/{print \\$2}'" The template arg can be set to 'jinja' or another supported template engine to render the command arguments before execution. For example: .. code-block:: bash salt '*' cmd.run_stderr template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'" A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.run_stderr "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, use_vt=use_vt, saltenv=saltenv, password=password, success_retcodes=success_retcodes, **kwargs) return ret['stderr'] if not hide_output else '' def run_all(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, redirect_stderr=False, password=None, encoded_cmd=False, prepend_path=None, success_retcodes=None, **kwargs): ''' Execute the passed command and return a dict of return data :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str group: Group to run command as. Not currently supported on Windows. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.run_all 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary) to $PATH .. versionadded:: 2018.3.0 :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: A timeout in seconds for the executed process to return. :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. :param bool encoded_cmd: Specify if the supplied command is encoded. Only applies to shell 'powershell'. .. versionadded:: 2018.3.0 :param bool redirect_stderr: If set to ``True``, then stderr will be redirected to stdout. This is helpful for cases where obtaining both the retcode and output is desired, but it is not desired to have the output separated into both stdout and stderr. .. versionadded:: 2015.8.2 :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param bool bg: If ``True``, run command in background and do not await or deliver its results .. versionadded:: 2016.3.6 :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine CLI Example: .. code-block:: bash salt '*' cmd.run_all "ls -l | awk '/foo/{print \\$2}'" The template arg can be set to 'jinja' or another supported template engine to render the command arguments before execution. For example: .. code-block:: bash salt '*' cmd.run_all template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'" A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.run_all "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, stderr=stderr, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, encoded_cmd=encoded_cmd, success_retcodes=success_retcodes, **kwargs) if hide_output: ret['stdout'] = ret['stderr'] = '' return ret def retcode(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, success_retcodes=None, **kwargs): ''' Execute a shell command and return the command's return code. :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str group: Group to run command as. Not currently supported on Windows. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.retcode 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param int timeout: A timeout in seconds for the executed process to return. :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. :rtype: int :rtype: None :returns: Return Code as an int or None if there was an exception. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine CLI Example: .. code-block:: bash salt '*' cmd.retcode "file /bin/bash" The template arg can be set to 'jinja' or another supported template engine to render the command arguments before execution. For example: .. code-block:: bash salt '*' cmd.retcode template=jinja "file {{grains.pythonpath[0]}}/python" A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.retcode "grep f" stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, stderr=subprocess.STDOUT, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, success_retcodes=success_retcodes, **kwargs) return ret['retcode'] def _retcode_quiet(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, template=None, umask=None, output_encoding=None, log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, success_retcodes=None, **kwargs): ''' Helper for running commands quietly for minion startup. Returns same as the retcode() function. ''' return retcode(cmd, cwd=cwd, stdin=stdin, runas=runas, group=group, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, umask=umask, output_encoding=output_encoding, output_loglevel='quiet', log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, success_retcodes=success_retcodes, **kwargs) def script(source, args=None, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, template=None, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, saltenv='base', use_vt=False, bg=False, password=None, success_retcodes=None, **kwargs): ''' Download a script from a remote location and execute the script locally. The script can be located on the salt master file server or on an HTTP/FTP server. The script will be executed directly, so it can be written in any available programming language. :param str source: The location of the script to download. If the file is located on the master in the directory named spam, and is called eggs, the source string is salt://spam/eggs :param str args: String of command line args to pass to the script. Only used if no args are specified as part of the `name` argument. To pass a string containing spaces in YAML, you will need to doubly-quote it: .. code-block:: bash salt myminion cmd.script salt://foo.sh "arg1 'arg two' arg3" :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str group: Group to run script as. Not currently supported on Windows. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param bool bg: If True, run script in background and do not await or deliver it's results :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.script 'some command' env='{"FOO": "bar"}' :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: If the command has not terminated after timeout seconds, send the subprocess sigterm, and if sigterm is ignored, follow up with sigkill :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine CLI Example: .. code-block:: bash salt '*' cmd.script salt://scripts/runme.sh salt '*' cmd.script salt://scripts/runme.sh 'arg1 arg2 "arg 3"' salt '*' cmd.script salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell' .. code-block:: bash salt '*' cmd.script salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) def _cleanup_tempfile(path): try: __salt__['file.remove'](path) except (SaltInvocationError, CommandExecutionError) as exc: log.error( 'cmd.script: Unable to clean tempfile \'%s\': %s', path, exc, exc_info_on_loglevel=logging.DEBUG ) if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') win_cwd = False if salt.utils.platform.is_windows() and runas and cwd is None: # Create a temp working directory cwd = tempfile.mkdtemp(dir=__opts__['cachedir']) win_cwd = True salt.utils.win_dacl.set_permissions(obj_name=cwd, principal=runas, permissions='full_control') path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1]) if template: if 'pillarenv' in kwargs or 'pillar' in kwargs: pillarenv = kwargs.get('pillarenv', __opts__.get('pillarenv')) kwargs['pillar'] = _gather_pillar(pillarenv, kwargs.get('pillar')) fn_ = __salt__['cp.get_template'](source, path, template, saltenv, **kwargs) if not fn_: _cleanup_tempfile(path) # If a temp working directory was created (Windows), let's remove that if win_cwd: _cleanup_tempfile(cwd) return {'pid': 0, 'retcode': 1, 'stdout': '', 'stderr': '', 'cache_error': True} else: fn_ = __salt__['cp.cache_file'](source, saltenv) if not fn_: _cleanup_tempfile(path) # If a temp working directory was created (Windows), let's remove that if win_cwd: _cleanup_tempfile(cwd) return {'pid': 0, 'retcode': 1, 'stdout': '', 'stderr': '', 'cache_error': True} shutil.copyfile(fn_, path) if not salt.utils.platform.is_windows(): os.chmod(path, 320) os.chown(path, __salt__['file.user_to_uid'](runas), -1) path = _cmd_quote(path) ret = _run(path + ' ' + six.text_type(args) if args else path, cwd=cwd, stdin=stdin, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, runas=runas, group=group, shell=shell, python_shell=python_shell, env=env, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, use_vt=use_vt, bg=bg, password=password, success_retcodes=success_retcodes, **kwargs) _cleanup_tempfile(path) # If a temp working directory was created (Windows), let's remove that if win_cwd: _cleanup_tempfile(cwd) if hide_output: ret['stdout'] = ret['stderr'] = '' return ret def script_retcode(source, args=None, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, template='jinja', umask=None, timeout=None, reset_system_locale=True, saltenv='base', output_encoding=None, output_loglevel='debug', log_callback=None, use_vt=False, password=None, success_retcodes=None, **kwargs): ''' Download a script from a remote location and execute the script locally. The script can be located on the salt master file server or on an HTTP/FTP server. The script will be executed directly, so it can be written in any available programming language. The script can also be formatted as a template, the default is jinja. Only evaluate the script return code and do not block for terminal output :param str source: The location of the script to download. If the file is located on the master in the directory named spam, and is called eggs, the source string is salt://spam/eggs :param str args: String of command line args to pass to the script. Only used if no args are specified as part of the `name` argument. To pass a string containing spaces in YAML, you will need to doubly-quote it: "arg1 'arg two' arg3" :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str group: Group to run script as. Not currently supported on Windows. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.script_retcode 'some command' env='{"FOO": "bar"}' :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param int timeout: If the command has not terminated after timeout seconds, send the subprocess sigterm, and if sigterm is ignored, follow up with sigkill :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine CLI Example: .. code-block:: bash salt '*' cmd.script_retcode salt://scripts/runme.sh salt '*' cmd.script_retcode salt://scripts/runme.sh 'arg1 arg2 "arg 3"' salt '*' cmd.script_retcode salt://scripts/windows_task.ps1 args=' -Input c:\\tmp\\infile.txt' shell='powershell' A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. .. code-block:: bash salt '*' cmd.script_retcode salt://scripts/runme.sh stdin='one\\ntwo\\nthree\\nfour\\nfive\\n' ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') return script(source=source, args=args, cwd=cwd, stdin=stdin, runas=runas, group=group, shell=shell, python_shell=python_shell, env=env, template=template, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, use_vt=use_vt, password=password, success_retcodes=success_retcodes, **kwargs)['retcode'] def which(cmd): ''' Returns the path of an executable available on the minion, None otherwise CLI Example: .. code-block:: bash salt '*' cmd.which cat ''' return salt.utils.path.which(cmd) def which_bin(cmds): ''' Returns the first command found in a list of commands CLI Example: .. code-block:: bash salt '*' cmd.which_bin '[pip2, pip, pip-python]' ''' return salt.utils.path.which_bin(cmds) def has_exec(cmd): ''' Returns true if the executable is available on the minion, false otherwise CLI Example: .. code-block:: bash salt '*' cmd.has_exec cat ''' return which(cmd) is not None def exec_code(lang, code, cwd=None, args=None, **kwargs): ''' Pass in two strings, the first naming the executable language, aka - python2, python3, ruby, perl, lua, etc. the second string containing the code you wish to execute. The stdout will be returned. All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used. CLI Example: .. code-block:: bash salt '*' cmd.exec_code ruby 'puts "cheese"' salt '*' cmd.exec_code ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}' ''' return exec_code_all(lang, code, cwd, args, **kwargs)['stdout'] def exec_code_all(lang, code, cwd=None, args=None, **kwargs): ''' Pass in two strings, the first naming the executable language, aka - python2, python3, ruby, perl, lua, etc. the second string containing the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid) will be returned. All parameters from :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` except python_shell can be used. CLI Example: .. code-block:: bash salt '*' cmd.exec_code_all ruby 'puts "cheese"' salt '*' cmd.exec_code_all ruby 'puts "cheese"' args='["arg1", "arg2"]' env='{"FOO": "bar"}' ''' powershell = lang.lower().startswith("powershell") if powershell: codefile = salt.utils.files.mkstemp(suffix=".ps1") else: codefile = salt.utils.files.mkstemp() with salt.utils.files.fopen(codefile, 'w+t', binary=False) as fp_: fp_.write(salt.utils.stringutils.to_str(code)) if powershell: cmd = [lang, "-File", codefile] else: cmd = [lang, codefile] if isinstance(args, six.string_types): cmd.append(args) elif isinstance(args, list): cmd += args ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs) os.remove(codefile) return ret def tty(device, echo=''): ''' Echo a string to a specific tty CLI Example: .. code-block:: bash salt '*' cmd.tty tty0 'This is a test' salt '*' cmd.tty pts3 'This is a test' ''' if device.startswith('tty'): teletype = '/dev/{0}'.format(device) elif device.startswith('pts'): teletype = '/dev/{0}'.format(device.replace('pts', 'pts/')) else: return {'Error': 'The specified device is not a valid TTY'} try: with salt.utils.files.fopen(teletype, 'wb') as tty_device: tty_device.write(salt.utils.stringutils.to_bytes(echo)) return { 'Success': 'Message was successfully echoed to {0}'.format(teletype) } except IOError: return { 'Error': 'Echoing to {0} returned error'.format(teletype) } def run_chroot(root, cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=True, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='quiet', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, bg=False, success_retcodes=None, **kwargs): ''' .. versionadded:: 2014.7.0 This function runs :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` wrapped within a chroot, with dev and proc mounted in the chroot :param str root: Path to the root of the jail to use. stdin A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input.: runas User to run script as. group Group to run script as. shell Shell to execute under. Defaults to the system default shell. :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :parar str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.run_chroot 'some command' env='{"FOO": "bar"}' :param dict clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: A timeout in seconds for the executed process to return. :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine CLI Example: .. code-block:: bash salt '*' cmd.run_chroot /var/lib/lxc/container_name/rootfs 'sh /tmp/bootstrap.sh' ''' __salt__['mount.mount']( os.path.join(root, 'dev'), 'udev', fstype='devtmpfs') __salt__['mount.mount']( os.path.join(root, 'proc'), 'proc', fstype='proc') # Execute chroot routine sh_ = '/bin/sh' if os.path.isfile(os.path.join(root, 'bin/bash')): sh_ = '/bin/bash' if isinstance(cmd, (list, tuple)): cmd = ' '.join([six.text_type(i) for i in cmd]) cmd = 'chroot {0} {1} -c {2}'.format(root, sh_, _cmd_quote(cmd)) run_func = __context__.pop('cmd.run_chroot.func', run_all) ret = run_func(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, pillarenv=kwargs.get('pillarenv'), pillar=kwargs.get('pillar'), use_vt=use_vt, success_retcodes=success_retcodes, bg=bg) # Kill processes running in the chroot for i in range(6): pids = _chroot_pids(root) if not pids: break for pid in pids: # use sig 15 (TERM) for first 3 attempts, then 9 (KILL) sig = 15 if i < 3 else 9 os.kill(pid, sig) if _chroot_pids(root): log.error('Processes running in chroot could not be killed, ' 'filesystem will remain mounted') __salt__['mount.umount'](os.path.join(root, 'proc')) __salt__['mount.umount'](os.path.join(root, 'dev')) if hide_output: ret['stdout'] = ret['stderr'] = '' return ret def _is_valid_shell(shell): ''' Attempts to search for valid shells on a system and see if a given shell is in the list ''' if salt.utils.platform.is_windows(): return True # Don't even try this for Windows shells = '/etc/shells' available_shells = [] if os.path.exists(shells): try: with salt.utils.files.fopen(shells, 'r') as shell_fp: lines = [salt.utils.stringutils.to_unicode(x) for x in shell_fp.read().splitlines()] for line in lines: if line.startswith('#'): continue else: available_shells.append(line) except OSError: return True else: # No known method of determining available shells return None if shell in available_shells: return True else: return False def shells(): ''' Lists the valid shells on this system via the /etc/shells file .. versionadded:: 2015.5.0 CLI Example:: salt '*' cmd.shells ''' shells_fn = '/etc/shells' ret = [] if os.path.exists(shells_fn): try: with salt.utils.files.fopen(shells_fn, 'r') as shell_fp: lines = [salt.utils.stringutils.to_unicode(x) for x in shell_fp.read().splitlines()] for line in lines: line = line.strip() if line.startswith('#'): continue elif not line: continue else: ret.append(line) except OSError: log.error("File '%s' was not found", shells_fn) return ret def shell_info(shell, list_modules=False): ''' .. versionadded:: 2016.11.0 Provides information about a shell or script languages which often use ``#!``. The values returned are dependent on the shell or scripting languages all return the ``installed``, ``path``, ``version``, ``version_raw`` Args: shell (str): Name of the shell. Support shells/script languages include bash, cmd, perl, php, powershell, python, ruby and zsh list_modules (bool): True to list modules available to the shell. Currently only lists powershell modules. Returns: dict: A dictionary of information about the shell .. code-block:: python {'version': '<2 or 3 numeric components dot-separated>', 'version_raw': '<full version string>', 'path': '<full path to binary>', 'installed': <True, False or None>, '<attribute>': '<attribute value>'} .. note:: - ``installed`` is always returned, if ``None`` or ``False`` also returns error and may also return ``stdout`` for diagnostics. - ``version`` is for use in determine if a shell/script language has a particular feature set, not for package management. - The shell must be within the executable search path. CLI Example: .. code-block:: bash salt '*' cmd.shell_info bash salt '*' cmd.shell_info powershell :codeauthor: Damon Atkins <https://github.com/damon-atkins> ''' regex_shells = { 'bash': [r'version (\d\S*)', 'bash', '--version'], 'bash-test-error': [r'versioZ ([-\w.]+)', 'bash', '--version'], # used to test an error result 'bash-test-env': [r'(HOME=.*)', 'bash', '-c', 'declare'], # used to test an error result 'zsh': [r'^zsh (\d\S*)', 'zsh', '--version'], 'tcsh': [r'^tcsh (\d\S*)', 'tcsh', '--version'], 'cmd': [r'Version ([\d.]+)', 'cmd.exe', '/C', 'ver'], 'powershell': [r'PSVersion\s+(\d\S*)', 'powershell', '-NonInteractive', '$PSVersionTable'], 'perl': [r'^(\d\S*)', 'perl', '-e', 'printf "%vd\n", $^V;'], 'python': [r'^Python (\d\S*)', 'python', '-V'], 'ruby': [r'^ruby (\d\S*)', 'ruby', '-v'], 'php': [r'^PHP (\d\S*)', 'php', '-v'] } # Ensure ret['installed'] always as a value of True, False or None (not sure) ret = {'installed': False} if salt.utils.platform.is_windows() and shell == 'powershell': pw_keys = salt.utils.win_reg.list_keys( hive='HKEY_LOCAL_MACHINE', key='Software\\Microsoft\\PowerShell') pw_keys.sort(key=int) if len(pw_keys) == 0: return { 'error': 'Unable to locate \'powershell\' Reason: Cannot be ' 'found in registry.', 'installed': False, } for reg_ver in pw_keys: install_data = salt.utils.win_reg.read_value( hive='HKEY_LOCAL_MACHINE', key='Software\\Microsoft\\PowerShell\\{0}'.format(reg_ver), vname='Install') if install_data.get('vtype') == 'REG_DWORD' and \ install_data.get('vdata') == 1: details = salt.utils.win_reg.list_values( hive='HKEY_LOCAL_MACHINE', key='Software\\Microsoft\\PowerShell\\{0}\\' 'PowerShellEngine'.format(reg_ver)) # reset data, want the newest version details only as powershell # is backwards compatible ret = {} # if all goes well this will become True ret['installed'] = None ret['path'] = which('powershell.exe') for attribute in details: if attribute['vname'].lower() == '(default)': continue elif attribute['vname'].lower() == 'powershellversion': ret['psversion'] = attribute['vdata'] ret['version_raw'] = attribute['vdata'] elif attribute['vname'].lower() == 'runtimeversion': ret['crlversion'] = attribute['vdata'] if ret['crlversion'][0].lower() == 'v': ret['crlversion'] = ret['crlversion'][1::] elif attribute['vname'].lower() == 'pscompatibleversion': # reg attribute does not end in s, the powershell # attribute does ret['pscompatibleversions'] = \ attribute['vdata'].replace(' ', '').split(',') else: # keys are lower case as python is case sensitive the # registry is not ret[attribute['vname'].lower()] = attribute['vdata'] else: if shell not in regex_shells: return { 'error': 'Salt does not know how to get the version number for ' '{0}'.format(shell), 'installed': None } shell_data = regex_shells[shell] pattern = shell_data.pop(0) # We need to make sure HOME set, so shells work correctly # salt-call will general have home set, the salt-minion service may not # We need to assume ports of unix shells to windows will look after # themselves in setting HOME as they do it in many different ways newenv = os.environ if ('HOME' not in newenv) and (not salt.utils.platform.is_windows()): newenv['HOME'] = os.path.expanduser('~') log.debug('HOME environment set to %s', newenv['HOME']) try: proc = salt.utils.timed_subprocess.TimedProc( shell_data, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=10, env=newenv ) except (OSError, IOError) as exc: return { 'error': 'Unable to run command \'{0}\' Reason: {1}'.format(' '.join(shell_data), exc), 'installed': False, } try: proc.run() except TimedProcTimeoutError as exc: return { 'error': 'Unable to run command \'{0}\' Reason: Timed out.'.format(' '.join(shell_data)), 'installed': False, } ret['path'] = which(shell_data[0]) pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE) # only set version if we find it, so code later on can deal with it if pattern_result: ret['version_raw'] = pattern_result.group(1) if 'version_raw' in ret: version_results = re.match(r'(\d[\d.]*)', ret['version_raw']) if version_results: ret['installed'] = True ver_list = version_results.group(1).split('.')[:3] if len(ver_list) == 1: ver_list.append('0') ret['version'] = '.'.join(ver_list[:3]) else: ret['installed'] = None # Have an unexpected result # Get a list of the PowerShell modules which are potentially available # to be imported if shell == 'powershell' and ret['installed'] and list_modules: ret['modules'] = salt.utils.powershell.get_modules() if 'version' not in ret: ret['error'] = 'The version regex pattern for shell {0}, could not ' \ 'find the version string'.format(shell) ret['stdout'] = proc.stdout # include stdout so they can see the issue log.error(ret['error']) return ret def powershell(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, depth=None, encode_cmd=False, success_retcodes=None, **kwargs): ''' Execute the passed PowerShell command and return the output as a dictionary. Other ``cmd.*`` functions (besides ``cmd.powershell_all``) return the raw text output of the command. This function appends ``| ConvertTo-JSON`` to the command and then parses the JSON into a Python dictionary. If you want the raw textual result of your PowerShell command you should use ``cmd.run`` with the ``shell=powershell`` option. For example: .. code-block:: bash salt '*' cmd.run '$PSVersionTable.CLRVersion' shell=powershell salt '*' cmd.run 'Get-NetTCPConnection' shell=powershell .. versionadded:: 2016.3.0 .. warning:: This passes the cmd argument directly to PowerShell without any further processing! Be absolutely sure that you have properly sanitized the command passed to this function and do not use untrusted inputs. In addition to the normal ``cmd.run`` parameters, this command offers the ``depth`` parameter to change the Windows default depth for the ``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need more depth, set that here. .. note:: For some commands, setting the depth to a value greater than 4 greatly increases the time it takes for the command to return and in many cases returns useless data. :param str cmd: The powershell command to run. :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.powershell 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param bool hide_output: If ``True``, suppress stdout and stderr in the return data. .. note:: This is separate from ``output_loglevel``, which only handles how Salt logs to the minion log. .. versionadded:: 2018.3.0 :param int timeout: A timeout in seconds for the executed process to return. :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. :param bool reset_system_locale: Resets the system locale :param str saltenv: The salt environment to use. Default is 'base' :param int depth: The number of levels of contained objects to be included. Default is 2. Values greater than 4 seem to greatly increase the time it takes for the command to complete for some commands. eg: ``dir`` .. versionadded:: 2016.3.4 :param bool encode_cmd: Encode the command before executing. Use in cases where characters may be dropped or incorrectly converted when executed. Default is False. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine :returns: :dict: A dictionary of data returned by the powershell command. CLI Example: .. code-block:: powershell salt '*' cmd.powershell "$PSVersionTable.CLRVersion" ''' if 'python_shell' in kwargs: python_shell = kwargs.pop('python_shell') else: python_shell = True # Append PowerShell Object formatting # ConvertTo-JSON is only available on PowerShell 3.0 and later psversion = shell_info('powershell')['psversion'] if salt.utils.versions.version_cmp(psversion, '2.0') == 1: cmd += ' | ConvertTo-JSON' if depth is not None: cmd += ' -Depth {0}'.format(depth) if encode_cmd: # Convert the cmd to UTF-16LE without a BOM and base64 encode. # Just base64 encoding UTF-8 or including a BOM is not valid. log.debug('Encoding PowerShell command \'%s\'', cmd) cmd_utf16 = cmd.decode('utf-8').encode('utf-16le') cmd = base64.standard_b64encode(cmd_utf16) encoded_cmd = True else: encoded_cmd = False # Put the whole command inside a try / catch block # Some errors in PowerShell are not "Terminating Errors" and will not be # caught in a try/catch block. For example, the `Get-WmiObject` command will # often return a "Non Terminating Error". To fix this, make sure # `-ErrorAction Stop` is set in the powershell command cmd = 'try {' + cmd + '} catch { "{}" }' # Retrieve the response, while overriding shell with 'powershell' response = run(cmd, cwd=cwd, stdin=stdin, runas=runas, shell='powershell', env=env, clean_env=clean_env, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, hide_output=hide_output, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, python_shell=python_shell, password=password, encoded_cmd=encoded_cmd, success_retcodes=success_retcodes, **kwargs) try: return salt.utils.json.loads(response) except Exception: log.error("Error converting PowerShell JSON return", exc_info=True) return {} def powershell_all(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', quiet=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, depth=None, encode_cmd=False, force_list=False, success_retcodes=None, **kwargs): ''' Execute the passed PowerShell command and return a dictionary with a result field representing the output of the command, as well as other fields showing us what the PowerShell invocation wrote to ``stderr``, the process id, and the exit code of the invocation. This function appends ``| ConvertTo-JSON`` to the command before actually invoking powershell. An unquoted empty string is not valid JSON, but it's very normal for the Powershell output to be exactly that. Therefore, we do not attempt to parse empty Powershell output (which would result in an exception). Instead we treat this as a special case and one of two things will happen: - If the value of the ``force_list`` parameter is ``True``, then the ``result`` field of the return dictionary will be an empty list. - If the value of the ``force_list`` parameter is ``False``, then the return dictionary **will not have a result key added to it**. We aren't setting ``result`` to ``None`` in this case, because ``None`` is the Python representation of "null" in JSON. (We likewise can't use ``False`` for the equivalent reason.) If Powershell's output is not an empty string and Python cannot parse its content, then a ``CommandExecutionError`` exception will be raised. If Powershell's output is not an empty string, Python is able to parse its content, and the type of the resulting Python object is other than ``list`` then one of two things will happen: - If the value of the ``force_list`` parameter is ``True``, then the ``result`` field will be a singleton list with the Python object as its sole member. - If the value of the ``force_list`` parameter is ``False``, then the value of ``result`` will be the unmodified Python object. If Powershell's output is not an empty string, Python is able to parse its content, and the type of the resulting Python object is ``list``, then the value of ``result`` will be the unmodified Python object. The ``force_list`` parameter has no effect in this case. .. note:: An example of why the ``force_list`` parameter is useful is as follows: The Powershell command ``dir x | Convert-ToJson`` results in - no output when x is an empty directory. - a dictionary object when x contains just one item. - a list of dictionary objects when x contains multiple items. By setting ``force_list`` to ``True`` we will always end up with a list of dictionary items, representing files, no matter how many files x contains. Conversely, if ``force_list`` is ``False``, we will end up with no ``result`` key in our return dictionary when x is an empty directory, and a dictionary object when x contains just one file. If you want a similar function but with a raw textual result instead of a Python dictionary, you should use ``cmd.run_all`` in combination with ``shell=powershell``. The remaining fields in the return dictionary are described in more detail in the ``Returns`` section. Example: .. code-block:: bash salt '*' cmd.run_all '$PSVersionTable.CLRVersion' shell=powershell salt '*' cmd.run_all 'Get-NetTCPConnection' shell=powershell .. versionadded:: 2018.3.0 .. warning:: This passes the cmd argument directly to PowerShell without any further processing! Be absolutely sure that you have properly sanitized the command passed to this function and do not use untrusted inputs. In addition to the normal ``cmd.run`` parameters, this command offers the ``depth`` parameter to change the Windows default depth for the ``ConvertTo-JSON`` powershell command. The Windows default is 2. If you need more depth, set that here. .. note:: For some commands, setting the depth to a value greater than 4 greatly increases the time it takes for the command to return and in many cases returns useless data. :param str cmd: The powershell command to run. :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str stdin: A string of standard input can be specified for the command to be run using the ``stdin`` parameter. This can be useful in cases where sensitive information must be read from standard input. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.powershell_all 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param bool rstrip: Strip all whitespace off the end of output before it is returned. :param str umask: The umask (in octal) to use when running the command. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param int timeout: A timeout in seconds for the executed process to return. :param bool use_vt: Use VT utils (saltstack) to stream the command output more interactively to the console and the logs. This is experimental. :param bool reset_system_locale: Resets the system locale :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param str saltenv: The salt environment to use. Default is 'base' :param int depth: The number of levels of contained objects to be included. Default is 2. Values greater than 4 seem to greatly increase the time it takes for the command to complete for some commands. eg: ``dir`` :param bool encode_cmd: Encode the command before executing. Use in cases where characters may be dropped or incorrectly converted when executed. Default is False. :param bool force_list: The purpose of this parameter is described in the preamble of this function's documentation. Default value is False. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine :return: A dictionary with the following entries: result For a complete description of this field, please refer to this function's preamble. **This key will not be added to the dictionary when force_list is False and Powershell's output is the empty string.** stderr What the PowerShell invocation wrote to ``stderr``. pid The process id of the PowerShell invocation retcode This is the exit code of the invocation of PowerShell. If the final execution status (in PowerShell) of our command (with ``| ConvertTo-JSON`` appended) is ``False`` this should be non-0. Likewise if PowerShell exited with ``$LASTEXITCODE`` set to some non-0 value, then ``retcode`` will end up with this value. :rtype: dict CLI Example: .. code-block:: bash salt '*' cmd.powershell_all "$PSVersionTable.CLRVersion" CLI Example: .. code-block:: bash salt '*' cmd.powershell_all "dir mydirectory" force_list=True ''' if 'python_shell' in kwargs: python_shell = kwargs.pop('python_shell') else: python_shell = True # Append PowerShell Object formatting cmd += ' | ConvertTo-JSON' if depth is not None: cmd += ' -Depth {0}'.format(depth) if encode_cmd: # Convert the cmd to UTF-16LE without a BOM and base64 encode. # Just base64 encoding UTF-8 or including a BOM is not valid. log.debug('Encoding PowerShell command \'%s\'', cmd) cmd_utf16 = cmd.decode('utf-8').encode('utf-16le') cmd = base64.standard_b64encode(cmd_utf16) encoded_cmd = True else: encoded_cmd = False # Retrieve the response, while overriding shell with 'powershell' response = run_all(cmd, cwd=cwd, stdin=stdin, runas=runas, shell='powershell', env=env, clean_env=clean_env, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, quiet=quiet, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, python_shell=python_shell, password=password, encoded_cmd=encoded_cmd, success_retcodes=success_retcodes, **kwargs) stdoutput = response['stdout'] # if stdoutput is the empty string and force_list is True we return an empty list # Otherwise we return response with no result key if not stdoutput: response.pop('stdout') if force_list: response['result'] = [] return response # If we fail to parse stdoutput we will raise an exception try: result = salt.utils.json.loads(stdoutput) except Exception: err_msg = "cmd.powershell_all " + \ "cannot parse the Powershell output." response["cmd"] = cmd raise CommandExecutionError( message=err_msg, info=response ) response.pop("stdout") if type(result) is not list: if force_list: response['result'] = [result] else: response['result'] = result else: # result type is list so the force_list param has no effect response['result'] = result return response def run_bg(cmd, cwd=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, umask=None, timeout=None, output_encoding=None, output_loglevel='debug', log_callback=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', password=None, prepend_path=None, success_retcodes=None, **kwargs): r''' .. versionadded: 2016.3.0 Execute the passed command in the background and return it's PID .. note:: If the init system is systemd and the backgrounded task should run even if the salt-minion process is restarted, prepend ``systemd-run --scope`` to the command. This will reparent the process in its own scope separate from salt-minion, and will not be affected by restarting the minion service. :param str cmd: The command to run. ex: ``ls -lart /home`` :param str cwd: The directory from which to execute the command. Defaults to the home directory of the user specified by ``runas`` (or the user under which Salt is running if ``runas`` is not specified). :param str group: Group to run command as. Not currently supported on Windows. :param str shell: Shell to execute under. Defaults to the system default shell. :param str output_encoding: Control the encoding used to decode the command's output. .. note:: This should not need to be used in most cases. By default, Salt will try to use the encoding detected from the system locale, and will fall back to UTF-8 if this fails. This should only need to be used in cases where the output of the command is encoded in something other than the system locale or UTF-8. To see the encoding Salt has detected from the system locale, check the `locale` line in the output of :py:func:`test.versions_report <salt.modules.test.versions_report>`. .. versionadded:: 2018.3.0 :param str output_loglevel: Control the loglevel at which the output from the command is logged to the minion log. .. note:: The command being run will still be logged at the ``debug`` loglevel regardless, unless ``quiet`` is used for this value. :param bool ignore_retcode: If the exit code of the command is nonzero, this is treated as an error condition, and the output from the command will be logged to the minion log. However, there are some cases where programs use the return code for signaling and a nonzero exit code doesn't necessarily mean failure. Pass this argument as ``True`` to skip logging the output if the command has a nonzero exit code. :param str runas: Specify an alternate user to run the command. The default behavior is to run as the user under which Salt is running. If running on a Windows minion you must also use the ``password`` argument, and the target user account must be in the Administrators group. :param str password: Windows only. Required when specifying ``runas``. This parameter will be ignored on non-Windows platforms. .. versionadded:: 2016.3.0 :param str shell: Specify an alternate shell. Defaults to the system's default shell. :param bool python_shell: If False, let python handle the positional arguments. Set to True to use shell features, such as pipes or redirection. :param dict env: Environment variables to be set prior to execution. .. note:: When passing environment variables on the CLI, they should be passed as the string representation of a dictionary. .. code-block:: bash salt myminion cmd.run_bg 'some command' env='{"FOO": "bar"}' :param bool clean_env: Attempt to clean out all other shell environment variables and set only those provided in the 'env' argument to this function. :param str prepend_path: $PATH segment to prepend (trailing ':' not necessary) to $PATH .. versionadded:: 2018.3.0 :param str template: If this setting is applied then the named templating engine will be used to render the downloaded file. Currently jinja, mako, and wempy are supported. :param str umask: The umask (in octal) to use when running the command. :param int timeout: A timeout in seconds for the executed process to return. .. warning:: This function does not process commands through a shell unless the ``python_shell`` argument is set to ``True``. This means that any shell-specific functionality such as 'echo' or the use of pipes, redirection or &&, should either be migrated to cmd.shell or have the python_shell=True flag set here. The use of ``python_shell=True`` means that the shell will accept _any_ input including potentially malicious commands such as 'good_command;rm -rf /'. Be absolutely certain that you have sanitized your input prior to using ``python_shell=True``. :param list success_retcodes: This parameter will be allow a list of non-zero return codes that should be considered a success. If the return code returned from the run matches any in the provided list, the return code will be overridden with zero. .. versionadded:: Fluorine :param bool stdin_raw_newlines: False If ``True``, Salt will not automatically convert the characters ``\\n`` present in the ``stdin`` value to newlines. .. versionadded:: Fluorine CLI Example: .. code-block:: bash salt '*' cmd.run_bg "fstrim-all" The template arg can be set to 'jinja' or another supported template engine to render the command arguments before execution. For example: .. code-block:: bash salt '*' cmd.run_bg template=jinja "ls -l /tmp/{{grains.id}} | awk '/foo/{print \\$2}'" Specify an alternate shell with the shell parameter: .. code-block:: bash salt '*' cmd.run_bg "Get-ChildItem C:\\ " shell='powershell' If an equal sign (``=``) appears in an argument to a Salt command it is interpreted as a keyword argument in the format ``key=val``. That processing can be bypassed in order to pass an equal sign through to the remote shell command by manually specifying the kwarg: .. code-block:: bash salt '*' cmd.run_bg cmd='ls -lR / | sed -e s/=/:/g > /tmp/dontwait' ''' python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) res = _run(cmd, stdin=None, stderr=None, stdout=None, output_encoding=output_encoding, output_loglevel=output_loglevel, use_vt=None, bg=True, with_communicate=False, rstrip=False, runas=runas, group=group, shell=shell, python_shell=python_shell, cwd=cwd, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, umask=umask, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, password=password, success_retcodes=success_retcodes, **kwargs ) return { 'pid': res['pid'] }
37.389381
121
0.598685
from __future__ import absolute_import, print_function, unicode_literals import functools import glob import logging import os import shutil import subprocess import sys import time import traceback import fnmatch import base64 import re import tempfile import salt.utils.args import salt.utils.data import salt.utils.files import salt.utils.json import salt.utils.path import salt.utils.platform import salt.utils.powershell import salt.utils.stringutils import salt.utils.templates import salt.utils.timed_subprocess import salt.utils.user import salt.utils.versions import salt.utils.vt import salt.utils.win_dacl import salt.utils.win_reg import salt.grains.extra from salt.ext import six from salt.exceptions import CommandExecutionError, TimedProcTimeoutError, \ SaltInvocationError from salt.log import LOG_LEVELS from salt.ext.six.moves import range, zip, map try: import pwd import grp except ImportError: pass if salt.utils.platform.is_windows(): from salt.utils.win_runas import runas as win_runas from salt.utils.win_functions import escape_argument as _cmd_quote HAS_WIN_RUNAS = True else: from salt.ext.six.moves import shlex_quote as _cmd_quote HAS_WIN_RUNAS = False __proxyenabled__ = ['*'] __virtualname__ = 'cmd' # Set up logging log = logging.getLogger(__name__) DEFAULT_SHELL = salt.grains.extra.shell()['shell'] # Overwriting the cmd python module makes debugging modules with pdb a bit # harder so lets do it this way instead. def __virtual__(): return __virtualname__ def _check_cb(cb_): if cb_ is not None: if hasattr(cb_, '__call__'): return cb_ else: log.error('log_callback is not callable, ignoring') return lambda x: x def _python_shell_default(python_shell, __pub_jid): try: # Default to python_shell=True when run directly from remote execution # system. Cross-module calls won't have a jid. if __pub_jid and python_shell is None: return True elif __opts__.get('cmd_safe', True) is False and python_shell is None: return True except NameError: pass return python_shell def _chroot_pids(chroot): pids = [] for root in glob.glob('/proc/[0-9]*/root'): try: link = os.path.realpath(root) if link.startswith(chroot): pids.append(int(os.path.basename( os.path.dirname(root) ))) except OSError: pass return pids def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None): if not template: return (cmd, cwd) if template not in salt.utils.templates.TEMPLATE_REGISTRY: raise CommandExecutionError( 'Attempted to render file paths with unavailable engine ' '{0}'.format(template) ) kwargs = {} kwargs['salt'] = __salt__ if pillarenv is not None or pillar_override is not None: pillarenv = pillarenv or __opts__['pillarenv'] kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override) else: kwargs['pillar'] = __pillar__ kwargs['grains'] = __grains__ kwargs['opts'] = __opts__ kwargs['saltenv'] = saltenv def _render(contents): tmp_path_fn = salt.utils.files.mkstemp() with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_: fp_.write(salt.utils.stringutils.to_str(contents)) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( tmp_path_fn, to_str=True, **kwargs ) salt.utils.files.safe_rm(tmp_path_fn) if not data['result']: raise CommandExecutionError( 'Failed to execute cmd with error: {0}'.format( data['data'] ) ) else: return data['data'] cmd = _render(cmd) cwd = _render(cwd) return (cmd, cwd) def _check_loglevel(level='info'): try: level = level.lower() if level == 'quiet': return None else: return LOG_LEVELS[level] except (AttributeError, KeyError): log.error( 'Invalid output_loglevel \'%s\'. Valid levels are: %s. Falling ' 'back to \'info\'.', level, ', '.join(sorted(LOG_LEVELS, reverse=True)) ) return LOG_LEVELS['info'] def _parse_env(env): if not env: env = {} if isinstance(env, list): env = salt.utils.data.repack_dictlist(env) if not isinstance(env, dict): env = {} return env def _gather_pillar(pillarenv, pillar_override): pillar = salt.pillar.get_pillar( __opts__, __grains__, __opts__['id'], __opts__['saltenv'], pillar_override=pillar_override, pillarenv=pillarenv ) ret = pillar.compile_pillar() if pillar_override and isinstance(pillar_override, dict): ret.update(pillar_override) return ret def _check_avail(cmd): if isinstance(cmd, list): cmd = ' '.join([six.text_type(x) if not isinstance(x, six.string_types) else x for x in cmd]) bret = True wret = False if __salt__['config.get']('cmd_blacklist_glob'): blist = __salt__['config.get']('cmd_blacklist_glob', []) for comp in blist: if fnmatch.fnmatch(cmd, comp): bret = False if __salt__['config.get']('cmd_whitelist_glob', []): blist = __salt__['config.get']('cmd_whitelist_glob', []) for comp in blist: if fnmatch.fnmatch(cmd, comp): wret = True break else: wret = True return bret and wret def _run(cmd, cwd=None, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, output_encoding=None, output_loglevel='debug', log_callback=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, prepend_path=None, rstrip=True, template=None, umask=None, timeout=None, with_communicate=True, reset_system_locale=True, ignore_retcode=False, saltenv='base', pillarenv=None, pillar_override=None, use_vt=False, password=None, bg=False, encoded_cmd=False, success_retcodes=None, **kwargs): if 'pillar' in kwargs and not pillar_override: pillar_override = kwargs['pillar'] if _is_valid_shell(shell) is False: log.warning( 'Attempt to run a shell command with what may be an invalid shell! ' 'Check to ensure that the shell <%s> is valid for this user.', shell ) output_loglevel = _check_loglevel(output_loglevel) log_callback = _check_cb(log_callback) use_sudo = False if runas is None and '__context__' in globals(): runas = __context__.get('runas') if password is None and '__context__' in globals(): password = __context__.get('runas_password') if not cwd: cwd = os.path.expanduser('~{0}'.format('' if not runas else runas)) if not os.access(cwd, os.R_OK): cwd = '/' if salt.utils.platform.is_windows(): cwd = os.path.abspath(os.sep) else: cwd = six.text_type(cwd) if bg: ignore_retcode = True use_vt = False if not salt.utils.platform.is_windows(): if not os.path.isfile(shell) or not os.access(shell, os.X_OK): msg = 'The shell {0} is not available'.format(shell) raise CommandExecutionError(msg) if salt.utils.platform.is_windows() and use_vt: raise CommandExecutionError('VT not available on windows') if shell.lower().strip() == 'powershell': if isinstance(cmd, six.string_types): cmd = cmd.strip() stack = traceback.extract_stack(limit=2) if stack[-2][2] == 'script': cmd = 'Powershell -NonInteractive -NoProfile -ExecutionPolicy Bypass -File ' + cmd elif encoded_cmd: cmd = 'Powershell -NonInteractive -EncodedCommand {0}'.format(cmd) else: cmd = 'Powershell -NonInteractive -NoProfile "{0}"'.format(cmd.replace('"', '\\"')) (cmd, cwd) = _render_cmd(cmd, cwd, template, saltenv, pillarenv, pillar_override) ret = {} if '__pub_jid' in kwargs: if not _check_avail(cmd): raise CommandExecutionError( 'The shell command "{0}" is not permitted'.format(cmd) ) env = _parse_env(env) for bad_env_key in (x for x, y in six.iteritems(env) if y is None): log.error('Environment variable \'%s\' passed without a value. ' 'Setting value to an empty string', bad_env_key) env[bad_env_key] = '' def _get_stripped(cmd): if isinstance(cmd, list): return [x.strip() if isinstance(x, six.string_types) else x for x in cmd] elif isinstance(cmd, six.string_types): return cmd.strip() else: return cmd if output_loglevel is not None: msg = ( 'Executing command {0}{1}{0} {2}{3}in directory \'{4}\'{5}'.format( '\'' if not isinstance(cmd, list) else '', _get_stripped(cmd), 'as user \'{0}\' '.format(runas) if runas else '', 'in group \'{0}\' '.format(group) if group else '', cwd, '. Executing command in the background, no output will be ' 'logged.' if bg else '' ) ) log.info(log_callback(msg)) if runas and salt.utils.platform.is_windows(): if not HAS_WIN_RUNAS: msg = 'missing salt/utils/win_runas.py' raise CommandExecutionError(msg) if isinstance(cmd, (list, tuple)): cmd = ' '.join(cmd) return win_runas(cmd, runas, password, cwd) if runas and salt.utils.platform.is_darwin(): # we need to insert the user simulation into the command itself and not # just run it from the environment on macOS as that # method doesn't work properly when run as root for certain commands. if isinstance(cmd, (list, tuple)): cmd = ' '.join(map(_cmd_quote, cmd)) cmd = 'su -l {0} -c "{1}"'.format(runas, cmd) runas = None if runas: try: pwd.getpwnam(runas) except KeyError: raise CommandExecutionError( 'User \'{0}\' is not available'.format(runas) ) if group: if salt.utils.platform.is_windows(): msg = 'group is not currently available on Windows' raise SaltInvocationError(msg) if not which_bin(['sudo']): msg = 'group argument requires sudo but not found' raise CommandExecutionError(msg) try: grp.getgrnam(group) except KeyError: raise CommandExecutionError( 'Group \'{0}\' is not available'.format(runas) ) else: use_sudo = True if runas or group: try: import uuid marker = '<<<' + str(uuid.uuid4()) + '>>>' marker_b = marker.encode(__salt_system_encoding__) py_code = ( 'import sys, os, itertools; ' 'sys.stdout.write(\"' + marker + '\"); ' 'sys.stdout.write(\"\\0\".join(itertools.chain(*os.environ.items()))); ' 'sys.stdout.write(\"' + marker + '\");' ) if use_sudo or __grains__['os'] in ['MacOS', 'Darwin']: env_cmd = ['sudo'] if runas: env_cmd.extend(['-u', runas]) if group: env_cmd.extend(['-g', group]) if shell != DEFAULT_SHELL: env_cmd.extend(['-s', '--', shell, '-c']) else: env_cmd.extend(['-i', '--']) env_cmd.extend([sys.executable]) elif __grains__['os'] in ['FreeBSD']: env_cmd = ('su', '-', runas, '-c', "{0} -c {1}".format(shell, sys.executable)) elif __grains__['os_family'] in ['Solaris']: env_cmd = ('su', '-', runas, '-c', sys.executable) elif __grains__['os_family'] in ['AIX']: env_cmd = ('su', '-', runas, '-c', sys.executable) else: env_cmd = ('su', '-s', shell, '-', runas, '-c', sys.executable) msg = 'env command: {0}'.format(env_cmd) log.debug(log_callback(msg)) env_bytes, env_encoded_err = subprocess.Popen( env_cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE ).communicate(salt.utils.stringutils.to_bytes(py_code)) marker_count = env_bytes.count(marker_b) if marker_count == 0: log.error( 'Environment could not be retrieved for user \'%s\': ' 'stderr=%r stdout=%r', runas, env_encoded_err, env_bytes ) env_bytes = b'' elif marker_count != 2: raise CommandExecutionError( 'Environment could not be retrieved for user \'{0}\'', info={'stderr': repr(env_encoded_err), 'stdout': repr(env_bytes)} ) else: env_bytes = env_bytes.split(marker_b)[1] if six.PY2: import itertools env_runas = dict(itertools.izip(*[iter(env_bytes.split(b'\0'))]*2)) elif six.PY3: env_runas = dict(list(zip(*[iter(env_bytes.split(b'\0'))]*2))) env_runas = dict( (salt.utils.stringutils.to_str(k), salt.utils.stringutils.to_str(v)) for k, v in six.iteritems(env_runas) ) env_runas.update(env) # user's default environment as obtained above. if env_runas.get('USER') != runas: env_runas['USER'] = runas # environment returns the wrong home directory. runas_home = os.path.expanduser('~{0}'.format(runas)) if env_runas.get('HOME') != runas_home: env_runas['HOME'] = runas_home env = env_runas except ValueError as exc: log.exception('Error raised retrieving environment for user %s', runas) raise CommandExecutionError( 'Environment could not be retrieved for user \'{0}\': {1}'.format( runas, exc ) ) if reset_system_locale is True: if not salt.utils.platform.is_windows(): # Default to C! # Salt only knows how to parse English words # Don't override if the user has passed LC_ALL env.setdefault('LC_CTYPE', 'C') env.setdefault('LC_NUMERIC', 'C') env.setdefault('LC_TIME', 'C') env.setdefault('LC_COLLATE', 'C') env.setdefault('LC_MONETARY', 'C') env.setdefault('LC_MESSAGES', 'C') env.setdefault('LC_PAPER', 'C') env.setdefault('LC_NAME', 'C') env.setdefault('LC_ADDRESS', 'C') env.setdefault('LC_TELEPHONE', 'C') env.setdefault('LC_MEASUREMENT', 'C') env.setdefault('LC_IDENTIFICATION', 'C') env.setdefault('LANGUAGE', 'C') else: if python_shell: cmd = 'chcp 437 > nul & ' + cmd if clean_env: run_env = env else: run_env = os.environ.copy() run_env.update(env) if prepend_path: run_env['PATH'] = ':'.join((prepend_path, run_env['PATH'])) if python_shell is None: python_shell = False new_kwargs = {'cwd': cwd, 'shell': python_shell, 'env': run_env if six.PY3 else salt.utils.data.encode(run_env), 'stdin': six.text_type(stdin) if stdin is not None else stdin, 'stdout': stdout, 'stderr': stderr, 'with_communicate': with_communicate, 'timeout': timeout, 'bg': bg, } if 'stdin_raw_newlines' in kwargs: new_kwargs['stdin_raw_newlines'] = kwargs['stdin_raw_newlines'] if umask is not None: _umask = six.text_type(umask).lstrip('0') if _umask == '': msg = 'Zero umask is not allowed.' raise CommandExecutionError(msg) try: _umask = int(_umask, 8) except ValueError: raise CommandExecutionError("Invalid umask: '{0}'".format(umask)) else: _umask = None if runas or group or umask: new_kwargs['preexec_fn'] = functools.partial( salt.utils.user.chugid_and_umask, runas, _umask, group) if not salt.utils.platform.is_windows(): if new_kwargs['shell'] is True: new_kwargs['executable'] = shell new_kwargs['close_fds'] = True if not os.path.isabs(cwd) or not os.path.isdir(cwd): raise CommandExecutionError( 'Specified cwd \'{0}\' either not absolute or does not exist' .format(cwd) ) if python_shell is not True \ and not salt.utils.platform.is_windows() \ and not isinstance(cmd, list): cmd = salt.utils.args.shlex_split(cmd) if success_retcodes is None: success_retcodes = [0] else: try: success_retcodes = [int(i) for i in salt.utils.args.split_input( success_retcodes )] except ValueError: raise SaltInvocationError( 'success_retcodes must be a list of integers' ) if not use_vt: try: proc = salt.utils.timed_subprocess.TimedProc(cmd, **new_kwargs) except (OSError, IOError) as exc: msg = ( 'Unable to run command \'{0}\' with the context \'{1}\', ' 'reason: '.format( cmd if output_loglevel is not None else 'REDACTED', new_kwargs ) ) try: if exc.filename is None: msg += 'command not found' else: msg += '{0}: {1}'.format(exc, exc.filename) except AttributeError: msg += 'unknown' raise CommandExecutionError(msg) try: proc.run() except TimedProcTimeoutError as exc: ret['stdout'] = six.text_type(exc) ret['stderr'] = '' ret['retcode'] = None ret['pid'] = proc.process.pid ret['retcode'] = 1 return ret if output_loglevel != 'quiet' and output_encoding is not None: log.debug('Decoding output from command %s using %s encoding', cmd, output_encoding) try: out = salt.utils.stringutils.to_unicode( proc.stdout, encoding=output_encoding) except TypeError: out = '' except UnicodeDecodeError: out = salt.utils.stringutils.to_unicode( proc.stdout, encoding=output_encoding, errors='replace') if output_loglevel != 'quiet': log.error( 'Failed to decode stdout from command %s, non-decodable ' 'characters have been replaced', cmd ) try: err = salt.utils.stringutils.to_unicode( proc.stderr, encoding=output_encoding) except TypeError: err = '' except UnicodeDecodeError: err = salt.utils.stringutils.to_unicode( proc.stderr, encoding=output_encoding, errors='replace') if output_loglevel != 'quiet': log.error( 'Failed to decode stderr from command %s, non-decodable ' 'characters have been replaced', cmd ) if rstrip: if out is not None: out = out.rstrip() if err is not None: err = err.rstrip() ret['pid'] = proc.process.pid ret['retcode'] = proc.process.returncode if ret['retcode'] in success_retcodes: ret['retcode'] = 0 ret['stdout'] = out ret['stderr'] = err else: formatted_timeout = '' if timeout: formatted_timeout = ' (timeout: {0}s)'.format(timeout) if output_loglevel is not None: msg = 'Running {0} in VT{1}'.format(cmd, formatted_timeout) log.debug(log_callback(msg)) stdout, stderr = '', '' now = time.time() if timeout: will_timeout = now + timeout else: will_timeout = -1 try: proc = salt.utils.vt.Terminal( cmd, shell=True, log_stdout=True, log_stderr=True, cwd=cwd, preexec_fn=new_kwargs.get('preexec_fn', None), env=run_env, log_stdin_level=output_loglevel, log_stdout_level=output_loglevel, log_stderr_level=output_loglevel, stream_stdout=True, stream_stderr=True ) ret['pid'] = proc.pid while proc.has_unread_data: try: try: time.sleep(0.5) try: cstdout, cstderr = proc.recv() except IOError: cstdout, cstderr = '', '' if cstdout: stdout += cstdout else: cstdout = '' if cstderr: stderr += cstderr else: cstderr = '' if timeout and (time.time() > will_timeout): ret['stderr'] = ( 'SALT: Timeout after {0}s\n{1}').format( timeout, stderr) ret['retcode'] = None break except KeyboardInterrupt: ret['stderr'] = 'SALT: User break\n{0}'.format(stderr) ret['retcode'] = 1 break except salt.utils.vt.TerminalException as exc: log.error('VT: %s', exc, exc_info_on_loglevel=logging.DEBUG) ret = {'retcode': 1, 'pid': '2'} break ret['stdout'] = stdout if not proc.isalive(): ret['stderr'] = stderr ret['retcode'] = proc.exitstatus if ret['retcode'] in success_retcodes: ret['retcode'] = 0 ret['pid'] = proc.pid finally: proc.close(terminate=True, kill=True) try: if ignore_retcode: __context__['retcode'] = 0 else: __context__['retcode'] = ret['retcode'] except NameError: pass if output_loglevel is not None: if not ignore_retcode and ret['retcode'] != 0: if output_loglevel < LOG_LEVELS['error']: output_loglevel = LOG_LEVELS['error'] msg = ( 'Command \'{0}\' failed with return code: {1}'.format( cmd, ret['retcode'] ) ) log.error(log_callback(msg)) if ret['stdout']: log.log(output_loglevel, 'stdout: {0}'.format(log_callback(ret['stdout']))) if ret['stderr']: log.log(output_loglevel, 'stderr: {0}'.format(log_callback(ret['stderr']))) if ret['retcode']: log.log(output_loglevel, 'retcode: {0}'.format(ret['retcode'])) return ret def _run_quiet(cmd, cwd=None, stdin=None, output_encoding=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, template=None, umask=None, timeout=None, reset_system_locale=True, saltenv='base', pillarenv=None, pillar_override=None, success_retcodes=None): return _run(cmd, runas=runas, cwd=cwd, stdin=stdin, stderr=subprocess.STDOUT, output_encoding=output_encoding, output_loglevel='quiet', log_callback=None, shell=shell, python_shell=python_shell, env=env, template=template, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, pillarenv=pillarenv, pillar_override=pillar_override, success_retcodes=success_retcodes)['stdout'] def _run_all_quiet(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=False, env=None, template=None, umask=None, timeout=None, reset_system_locale=True, saltenv='base', pillarenv=None, pillar_override=None, output_encoding=None, success_retcodes=None): return _run(cmd, runas=runas, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, output_encoding=output_encoding, output_loglevel='quiet', log_callback=None, template=template, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, pillarenv=pillarenv, pillar_override=pillar_override, success_retcodes=success_retcodes) def run(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, bg=False, password=None, encoded_cmd=False, raise_err=False, prepend_path=None, success_retcodes=None, **kwargs): python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, shell=shell, python_shell=python_shell, cwd=cwd, stdin=stdin, stderr=subprocess.STDOUT, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, bg=bg, password=password, encoded_cmd=encoded_cmd, success_retcodes=success_retcodes, **kwargs) log_callback = _check_cb(log_callback) lvl = _check_loglevel(output_loglevel) if lvl is not None: if not ignore_retcode and ret['retcode'] != 0: if lvl < LOG_LEVELS['error']: lvl = LOG_LEVELS['error'] msg = ( 'Command \'{0}\' failed with return code: {1}'.format( cmd, ret['retcode'] ) ) log.error(log_callback(msg)) if raise_err: raise CommandExecutionError( log_callback(ret['stdout'] if not hide_output else '') ) log.log(lvl, 'output: %s', log_callback(ret['stdout'])) return ret['stdout'] if not hide_output else '' def shell(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, bg=False, password=None, prepend_path=None, success_retcodes=None, **kwargs): if 'python_shell' in kwargs: python_shell = kwargs.pop('python_shell') else: python_shell = True return run(cmd, cwd=cwd, stdin=stdin, runas=runas, group=group, shell=shell, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, hide_output=hide_output, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, python_shell=python_shell, bg=bg, password=password, success_retcodes=success_retcodes, **kwargs) def run_stdout(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, prepend_path=None, success_retcodes=None, **kwargs): python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, success_retcodes=success_retcodes, **kwargs) return ret['stdout'] if not hide_output else '' def run_stderr(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, prepend_path=None, success_retcodes=None, **kwargs): python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, use_vt=use_vt, saltenv=saltenv, password=password, success_retcodes=success_retcodes, **kwargs) return ret['stderr'] if not hide_output else '' def run_all(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, redirect_stderr=False, password=None, encoded_cmd=False, prepend_path=None, success_retcodes=None, **kwargs): python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) stderr = subprocess.STDOUT if redirect_stderr else subprocess.PIPE ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, stderr=stderr, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, encoded_cmd=encoded_cmd, success_retcodes=success_retcodes, **kwargs) if hide_output: ret['stdout'] = ret['stderr'] = '' return ret def retcode(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, success_retcodes=None, **kwargs): python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) ret = _run(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, stderr=subprocess.STDOUT, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, success_retcodes=success_retcodes, **kwargs) return ret['retcode'] def _retcode_quiet(cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=False, env=None, clean_env=False, template=None, umask=None, output_encoding=None, log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, success_retcodes=None, **kwargs): return retcode(cmd, cwd=cwd, stdin=stdin, runas=runas, group=group, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, umask=umask, output_encoding=output_encoding, output_loglevel='quiet', log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, password=password, success_retcodes=success_retcodes, **kwargs) def script(source, args=None, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, template=None, umask=None, output_encoding=None, output_loglevel='debug', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, saltenv='base', use_vt=False, bg=False, password=None, success_retcodes=None, **kwargs): python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) def _cleanup_tempfile(path): try: __salt__['file.remove'](path) except (SaltInvocationError, CommandExecutionError) as exc: log.error( 'cmd.script: Unable to clean tempfile \'%s\': %s', path, exc, exc_info_on_loglevel=logging.DEBUG ) if '__env__' in kwargs: kwargs.pop('__env__') win_cwd = False if salt.utils.platform.is_windows() and runas and cwd is None: cwd = tempfile.mkdtemp(dir=__opts__['cachedir']) win_cwd = True salt.utils.win_dacl.set_permissions(obj_name=cwd, principal=runas, permissions='full_control') path = salt.utils.files.mkstemp(dir=cwd, suffix=os.path.splitext(source)[1]) if template: if 'pillarenv' in kwargs or 'pillar' in kwargs: pillarenv = kwargs.get('pillarenv', __opts__.get('pillarenv')) kwargs['pillar'] = _gather_pillar(pillarenv, kwargs.get('pillar')) fn_ = __salt__['cp.get_template'](source, path, template, saltenv, **kwargs) if not fn_: _cleanup_tempfile(path) if win_cwd: _cleanup_tempfile(cwd) return {'pid': 0, 'retcode': 1, 'stdout': '', 'stderr': '', 'cache_error': True} else: fn_ = __salt__['cp.cache_file'](source, saltenv) if not fn_: _cleanup_tempfile(path) # If a temp working directory was created (Windows), let's remove that if win_cwd: _cleanup_tempfile(cwd) return {'pid': 0, 'retcode': 1, 'stdout': '', 'stderr': '', 'cache_error': True} shutil.copyfile(fn_, path) if not salt.utils.platform.is_windows(): os.chmod(path, 320) os.chown(path, __salt__['file.user_to_uid'](runas), -1) path = _cmd_quote(path) ret = _run(path + ' ' + six.text_type(args) if args else path, cwd=cwd, stdin=stdin, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, runas=runas, group=group, shell=shell, python_shell=python_shell, env=env, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, use_vt=use_vt, bg=bg, password=password, success_retcodes=success_retcodes, **kwargs) _cleanup_tempfile(path) if win_cwd: _cleanup_tempfile(cwd) if hide_output: ret['stdout'] = ret['stderr'] = '' return ret def script_retcode(source, args=None, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, template='jinja', umask=None, timeout=None, reset_system_locale=True, saltenv='base', output_encoding=None, output_loglevel='debug', log_callback=None, use_vt=False, password=None, success_retcodes=None, **kwargs): if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') return script(source=source, args=args, cwd=cwd, stdin=stdin, runas=runas, group=group, shell=shell, python_shell=python_shell, env=env, template=template, umask=umask, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, use_vt=use_vt, password=password, success_retcodes=success_retcodes, **kwargs)['retcode'] def which(cmd): return salt.utils.path.which(cmd) def which_bin(cmds): return salt.utils.path.which_bin(cmds) def has_exec(cmd): return which(cmd) is not None def exec_code(lang, code, cwd=None, args=None, **kwargs): return exec_code_all(lang, code, cwd, args, **kwargs)['stdout'] def exec_code_all(lang, code, cwd=None, args=None, **kwargs): powershell = lang.lower().startswith("powershell") if powershell: codefile = salt.utils.files.mkstemp(suffix=".ps1") else: codefile = salt.utils.files.mkstemp() with salt.utils.files.fopen(codefile, 'w+t', binary=False) as fp_: fp_.write(salt.utils.stringutils.to_str(code)) if powershell: cmd = [lang, "-File", codefile] else: cmd = [lang, codefile] if isinstance(args, six.string_types): cmd.append(args) elif isinstance(args, list): cmd += args ret = run_all(cmd, cwd=cwd, python_shell=False, **kwargs) os.remove(codefile) return ret def tty(device, echo=''): if device.startswith('tty'): teletype = '/dev/{0}'.format(device) elif device.startswith('pts'): teletype = '/dev/{0}'.format(device.replace('pts', 'pts/')) else: return {'Error': 'The specified device is not a valid TTY'} try: with salt.utils.files.fopen(teletype, 'wb') as tty_device: tty_device.write(salt.utils.stringutils.to_bytes(echo)) return { 'Success': 'Message was successfully echoed to {0}'.format(teletype) } except IOError: return { 'Error': 'Echoing to {0} returned error'.format(teletype) } def run_chroot(root, cmd, cwd=None, stdin=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=True, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='quiet', log_callback=None, hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, bg=False, success_retcodes=None, **kwargs): __salt__['mount.mount']( os.path.join(root, 'dev'), 'udev', fstype='devtmpfs') __salt__['mount.mount']( os.path.join(root, 'proc'), 'proc', fstype='proc') # Execute chroot routine sh_ = '/bin/sh' if os.path.isfile(os.path.join(root, 'bin/bash')): sh_ = '/bin/bash' if isinstance(cmd, (list, tuple)): cmd = ' '.join([six.text_type(i) for i in cmd]) cmd = 'chroot {0} {1} -c {2}'.format(root, sh_, _cmd_quote(cmd)) run_func = __context__.pop('cmd.run_chroot.func', run_all) ret = run_func(cmd, runas=runas, group=group, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, pillarenv=kwargs.get('pillarenv'), pillar=kwargs.get('pillar'), use_vt=use_vt, success_retcodes=success_retcodes, bg=bg) # Kill processes running in the chroot for i in range(6): pids = _chroot_pids(root) if not pids: break for pid in pids: # use sig 15 (TERM) for first 3 attempts, then 9 (KILL) sig = 15 if i < 3 else 9 os.kill(pid, sig) if _chroot_pids(root): log.error('Processes running in chroot could not be killed, ' 'filesystem will remain mounted') __salt__['mount.umount'](os.path.join(root, 'proc')) __salt__['mount.umount'](os.path.join(root, 'dev')) if hide_output: ret['stdout'] = ret['stderr'] = '' return ret def _is_valid_shell(shell): if salt.utils.platform.is_windows(): return True # Don't even try this for Windows shells = '/etc/shells' available_shells = [] if os.path.exists(shells): try: with salt.utils.files.fopen(shells, 'r') as shell_fp: lines = [salt.utils.stringutils.to_unicode(x) for x in shell_fp.read().splitlines()] for line in lines: if line.startswith('#'): continue else: available_shells.append(line) except OSError: return True else: return None if shell in available_shells: return True else: return False def shells(): shells_fn = '/etc/shells' ret = [] if os.path.exists(shells_fn): try: with salt.utils.files.fopen(shells_fn, 'r') as shell_fp: lines = [salt.utils.stringutils.to_unicode(x) for x in shell_fp.read().splitlines()] for line in lines: line = line.strip() if line.startswith('#'): continue elif not line: continue else: ret.append(line) except OSError: log.error("File '%s' was not found", shells_fn) return ret def shell_info(shell, list_modules=False): regex_shells = { 'bash': [r'version (\d\S*)', 'bash', '--version'], 'bash-test-error': [r'versioZ ([-\w.]+)', 'bash', '--version'], 'bash-test-env': [r'(HOME=.*)', 'bash', '-c', 'declare'], 'zsh': [r'^zsh (\d\S*)', 'zsh', '--version'], 'tcsh': [r'^tcsh (\d\S*)', 'tcsh', '--version'], 'cmd': [r'Version ([\d.]+)', 'cmd.exe', '/C', 'ver'], 'powershell': [r'PSVersion\s+(\d\S*)', 'powershell', '-NonInteractive', '$PSVersionTable'], 'perl': [r'^(\d\S*)', 'perl', '-e', 'printf "%vd\n", $^V;'], 'python': [r'^Python (\d\S*)', 'python', '-V'], 'ruby': [r'^ruby (\d\S*)', 'ruby', '-v'], 'php': [r'^PHP (\d\S*)', 'php', '-v'] } ret = {'installed': False} if salt.utils.platform.is_windows() and shell == 'powershell': pw_keys = salt.utils.win_reg.list_keys( hive='HKEY_LOCAL_MACHINE', key='Software\\Microsoft\\PowerShell') pw_keys.sort(key=int) if len(pw_keys) == 0: return { 'error': 'Unable to locate \'powershell\' Reason: Cannot be ' 'found in registry.', 'installed': False, } for reg_ver in pw_keys: install_data = salt.utils.win_reg.read_value( hive='HKEY_LOCAL_MACHINE', key='Software\\Microsoft\\PowerShell\\{0}'.format(reg_ver), vname='Install') if install_data.get('vtype') == 'REG_DWORD' and \ install_data.get('vdata') == 1: details = salt.utils.win_reg.list_values( hive='HKEY_LOCAL_MACHINE', key='Software\\Microsoft\\PowerShell\\{0}\\' 'PowerShellEngine'.format(reg_ver)) ret = {} ret['installed'] = None ret['path'] = which('powershell.exe') for attribute in details: if attribute['vname'].lower() == '(default)': continue elif attribute['vname'].lower() == 'powershellversion': ret['psversion'] = attribute['vdata'] ret['version_raw'] = attribute['vdata'] elif attribute['vname'].lower() == 'runtimeversion': ret['crlversion'] = attribute['vdata'] if ret['crlversion'][0].lower() == 'v': ret['crlversion'] = ret['crlversion'][1::] elif attribute['vname'].lower() == 'pscompatibleversion': ret['pscompatibleversions'] = \ attribute['vdata'].replace(' ', '').split(',') else: ret[attribute['vname'].lower()] = attribute['vdata'] else: if shell not in regex_shells: return { 'error': 'Salt does not know how to get the version number for ' '{0}'.format(shell), 'installed': None } shell_data = regex_shells[shell] pattern = shell_data.pop(0) newenv = os.environ if ('HOME' not in newenv) and (not salt.utils.platform.is_windows()): newenv['HOME'] = os.path.expanduser('~') log.debug('HOME environment set to %s', newenv['HOME']) try: proc = salt.utils.timed_subprocess.TimedProc( shell_data, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=10, env=newenv ) except (OSError, IOError) as exc: return { 'error': 'Unable to run command \'{0}\' Reason: {1}'.format(' '.join(shell_data), exc), 'installed': False, } try: proc.run() except TimedProcTimeoutError as exc: return { 'error': 'Unable to run command \'{0}\' Reason: Timed out.'.format(' '.join(shell_data)), 'installed': False, } ret['path'] = which(shell_data[0]) pattern_result = re.search(pattern, proc.stdout, flags=re.IGNORECASE) if pattern_result: ret['version_raw'] = pattern_result.group(1) if 'version_raw' in ret: version_results = re.match(r'(\d[\d.]*)', ret['version_raw']) if version_results: ret['installed'] = True ver_list = version_results.group(1).split('.')[:3] if len(ver_list) == 1: ver_list.append('0') ret['version'] = '.'.join(ver_list[:3]) else: ret['installed'] = None if shell == 'powershell' and ret['installed'] and list_modules: ret['modules'] = salt.utils.powershell.get_modules() if 'version' not in ret: ret['error'] = 'The version regex pattern for shell {0}, could not ' \ 'find the version string'.format(shell) ret['stdout'] = proc.stdout log.error(ret['error']) return ret def powershell(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', hide_output=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, depth=None, encode_cmd=False, success_retcodes=None, **kwargs): if 'python_shell' in kwargs: python_shell = kwargs.pop('python_shell') else: python_shell = True psversion = shell_info('powershell')['psversion'] if salt.utils.versions.version_cmp(psversion, '2.0') == 1: cmd += ' | ConvertTo-JSON' if depth is not None: cmd += ' -Depth {0}'.format(depth) if encode_cmd: log.debug('Encoding PowerShell command \'%s\'', cmd) cmd_utf16 = cmd.decode('utf-8').encode('utf-16le') cmd = base64.standard_b64encode(cmd_utf16) encoded_cmd = True else: encoded_cmd = False cmd = 'try {' + cmd + '} catch { "{}" }' response = run(cmd, cwd=cwd, stdin=stdin, runas=runas, shell='powershell', env=env, clean_env=clean_env, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, hide_output=hide_output, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, python_shell=python_shell, password=password, encoded_cmd=encoded_cmd, success_retcodes=success_retcodes, **kwargs) try: return salt.utils.json.loads(response) except Exception: log.error("Error converting PowerShell JSON return", exc_info=True) return {} def powershell_all(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_encoding=None, output_loglevel='debug', quiet=False, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, depth=None, encode_cmd=False, force_list=False, success_retcodes=None, **kwargs): if 'python_shell' in kwargs: python_shell = kwargs.pop('python_shell') else: python_shell = True cmd += ' | ConvertTo-JSON' if depth is not None: cmd += ' -Depth {0}'.format(depth) if encode_cmd: log.debug('Encoding PowerShell command \'%s\'', cmd) cmd_utf16 = cmd.decode('utf-8').encode('utf-16le') cmd = base64.standard_b64encode(cmd_utf16) encoded_cmd = True else: encoded_cmd = False response = run_all(cmd, cwd=cwd, stdin=stdin, runas=runas, shell='powershell', env=env, clean_env=clean_env, template=template, rstrip=rstrip, umask=umask, output_encoding=output_encoding, output_loglevel=output_loglevel, quiet=quiet, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, saltenv=saltenv, use_vt=use_vt, python_shell=python_shell, password=password, encoded_cmd=encoded_cmd, success_retcodes=success_retcodes, **kwargs) stdoutput = response['stdout'] if not stdoutput: response.pop('stdout') if force_list: response['result'] = [] return response try: result = salt.utils.json.loads(stdoutput) except Exception: err_msg = "cmd.powershell_all " + \ "cannot parse the Powershell output." response["cmd"] = cmd raise CommandExecutionError( message=err_msg, info=response ) response.pop("stdout") if type(result) is not list: if force_list: response['result'] = [result] else: response['result'] = result else: response['result'] = result return response def run_bg(cmd, cwd=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, umask=None, timeout=None, output_encoding=None, output_loglevel='debug', log_callback=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', password=None, prepend_path=None, success_retcodes=None, **kwargs): python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', '')) res = _run(cmd, stdin=None, stderr=None, stdout=None, output_encoding=output_encoding, output_loglevel=output_loglevel, use_vt=None, bg=True, with_communicate=False, rstrip=False, runas=runas, group=group, shell=shell, python_shell=python_shell, cwd=cwd, env=env, clean_env=clean_env, prepend_path=prepend_path, template=template, umask=umask, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, saltenv=saltenv, password=password, success_retcodes=success_retcodes, **kwargs ) return { 'pid': res['pid'] }
true
true
f714a941e1710abfe811a893f00e369a5965accf
37,199
py
Python
src/windows10_system_logger.py
mikefeneley/stig_windows10
1f2a27e89d27a25768f2edc5d9f25ec6d11d4cb0
[ "MIT" ]
1
2019-11-19T00:14:03.000Z
2019-11-19T00:14:03.000Z
src/windows10_system_logger.py
mikefeneley/stig_windows10
1f2a27e89d27a25768f2edc5d9f25ec6d11d4cb0
[ "MIT" ]
null
null
null
src/windows10_system_logger.py
mikefeneley/stig_windows10
1f2a27e89d27a25768f2edc5d9f25ec6d11d4cb0
[ "MIT" ]
1
2017-10-03T03:21:27.000Z
2017-10-03T03:21:27.000Z
DEFAULT_CONFIG = "Windows10SystemLog.txt" class Windows10SystemLogger: """ Windows10SystemLogger writes error messages to the Windows10 System log file for every rule in the Windows10 STIG that is violated. """ def __init__(self, filename=DEFAULT_CONFIG): self.filename = filename self.log = open(filename, 'w') self.log.write("#########################\n\n") self.log.write("Windows10 System Audit Findings\n\n") def __del__(self): print("Write out") self.log.write("#########################\n\n") self.log.close() def get_filename(self): return self.filename def lan_manager_hash_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78287r1_rule: ") self.log.write( "The system must be configured to prevent the storage of the LAN Manager hash of passwords.\n\n") def remote_assistance_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78141r1_rule: ") self.log.write( "Solicited Remote Assistance must not be allowed.\n\n") def windows_installer_elevated_prviliges_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77815r1_rule: ") self.log.write( "The Windows Installer Always install with elevated privileges must be disabled.\n\n") def non_volume_autoplay_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78157r1_rule: ") self.log.write( "Autoplay must be turned off for non-volume devices.\n\n") def annonymous_pipe_access_restricted_errmsg(self, success): if not success: self.log.write("Check SV-78249r1_rule: ") self.log.write( "Anonymous access to Named Pipes and Shares must be restricted.\n\n") def drive_autorun_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78163r1_rule: ") self.log.write("Autoplay must be disabled for all drives.\n\n") def autorun_commands_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78163r1_rule: ") self.log.write( "The default autorun behavior must be configured to prevent autorun commands.\n\n") def sam_anonymous_enumeration_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78235r1_rule: ") self.log.write( "Anonymous enumeration of SAM accounts must not be allowed.\n\n") def sehop_disabled_errmsg(self, success): if not success: self.log.write("Check SV-83445r1_rule: ") self.log.write( "Structured Exception Handling Overwrite Protection (SEHOP) must be turned on.\n\n") def recovery_console_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78299r1_rule: ") self.log.write( "The Recovery Console option must be set to prevent automatic logon to the system.\n\n") def lanman_auth_level_set_errmsg(self, success): if not success: self.log.write("Check SV-78291r1_rule: ") self.log.write( "The LanMan authentication level must be set to send NTLMv2 response only, and to refuse LM and NTLM.\n\n") def winrm_service_basic_auth_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78287r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) service must not use Basic authentication.\n\n") def annonymous_share_enumeration_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78287r1_rule: ") self.log.write( "Anonymous enumeration of shares must be restricted..\n\n") def winrm_client_basic_auth_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77825r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) client must not use Basic authentication.\n\n") def emet_sehop_optout_set_errmsg(self, success): if not success: self.log.write("Check SV-77901r2_rule: ") self.log.write( "The Enhanced Mitigation Experience Toolkit (EMET) system-wide Structured Exception Handler Overwrite Protection (SEHOP) must be configured to Application Opt Out.\n\n") def emet_deephooks_set_errmsg(self, success): if not success: self.log.write("Check SV-77901r2_rule: ") self.log.write( "The Enhanced Mitigation Experience Toolkit (EMET) Default Actions and Mitigations Settings must enable Deep Hooks.\n\n") def unencrypted_passwd_smb_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78201r1_rule: ") self.log.write( "Unencrypted passwords must not be sent to third-party SMB Servers.\n\n") def smartscreen_filter_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78203r1_rule: ") self.log.write( "The SmartScreen filter for Microsoft Edge must be enabled.\n\n") def hardware_device_pfw_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78207r2_rule: ") self.log.write( "The use of a hardware security device with Microsoft Passport for Work must be enabled.\n\n") def smb_packet_signing_set_errmsg(self, success): if not success: self.log.write("Check SV-78209r1_rule: ") self.log.write( "The Windows SMB server must be configured to always perform SMB packet signing.\n\n") def client_rpc_authentication_set_errmsg(self, success): if not success: self.log.write("Check SV-78145r1_rule: ") self.log.write( " Client computers must be required to authenticate for RPC communication.\n\n") def unauthenticated_rpc_elient_restricted_errmsg(self, success): if not success: self.log.write("Check SV-78147r1_rule: ") self.log.write( "Unauthenticated RPC clients must be restricted from connecting to the RPC server.\n\n") def application_event_log_size_set_errmsg(self, success): if not success: self.log.write("Check SV-78009r1_rule: ") self.log.write( "The Application event log size must be configured to 32768 KB or greater.\n\n") def user_installation_option_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77811r1_rule: ") self.log.write( "Users must be prevented from changing installation options.\n\n") def powershell_script_block_logging_enabled_errmsg(self, success): if not success: self.log.write("Check SV-83411r1_rule: ") self.log.write( "PowerShell script block logging must be enabled.\n\n") def tcp_port_set_errmsg(self, success): if not success: self.log.write("Check SV-78019r1_rule: ") self.log.write( "The system must be configured to send error reports on TCP port 1232.\n\n") def strong_session_key_required_errmsg(self, success): if not success: self.log.write("Check SV-78155r1_rule: ") self.log.write( "The system must be configured to require a strong session key.\n\n") def tcp_port_set_errmsg(self, success): if not success: self.log.write("Check SV-78019r1_rule: ") self.log.write( "The system must be configured to send error reports on TCP port 1232.\n\n") def screen_saver_set_errmsg(self, success): if not success: self.log.write("Check SV-78159r1_rule: ") self.log.write( "The machine inactivity limit must be set to 15 minutes, locking the system with the screensaver.\n\n") def error_reports_generated_errmsg(self, success): if not success: self.log.write("Check SV-77949r1_rule: ") self.log.write( "The system must be configured to generate error reports.\n\n") def smb_packet_signing_errmsg(self, success): if not success: self.log.write("Check SV-78197r1_rule: ") self.log.write( "The Windows SMB client must be enabled to perform SMB packet signing when possible.\n\n") def inprivate_browsing_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78195r1_rule: ") self.log.write( "InPrivate browsing in Microsoft Edge must be disabled.\n\n") def smb_packet_signing_required_errmsg(self, success): if not success: self.log.write("Check SV-78193r1_rule: ") self.log.write( "The Windows SMB client must be configured to always perform SMB packet signing.\n\n") def app_override_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78191r1_rule: ") self.log.write( "Users must not be allowed to ignore SmartScreen filter warnings for unverified files in Microsoft Edge.\n\n") def automatic_logon_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78041r2_rule: ") self.log.write("Automatic logons must be disabled.\n\n") def ipv6_routing_protection_configured_errmsg(self, success): if not success: self.log.write("Check SV-78045r1_rule: ") self.log.write( "IPv6 source routing must be configured to highest protection.\n\n") def screen_saver_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78325r1_rule: ") self.log.write("A screen saver must be enabled on the system.\n\n") def ip_source_routing_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78049r1_rule: ") self.log.write( "The system must be configured to prevent IP source routing.\n\n") def multiple_error_reports_set_errmsg(self, success): if not success: self.log.write("Check SV-77987r1_rule: ") self.log.write( "The system must be configured to collect multiple error reports of the same event type.\n\n") def enhanced_antispoofing_set_errmsg(self, success): if not success: self.log.write("Check SV-78167r1_rule: ") self.log.write( "Enhanced anti-spoofing when available must be enabled for facial recognition.\n\n") def winrm_runas_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77865r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) service must not store RunAs credentials.\n\n") def zone_info_saved_errmsg(self, success): if not success: self.log.write("Check SV-78287r1_rule: ") self.log.write( "Zone information must be preserved when saving attachments.\n\n") def num_error_reports_configured_errmsg(self, success): if not success: self.log.write("Check SV-78033r1_rule: ") self.log.write( "The maximum number of error reports to archive on a system must be configured to 100 or greater.\n\n") def lock_screen_camera_access_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78035r1_rule: ") self.log.write( " Camera access from the lock screen must be disabled.\n\n") def queue_error_reports_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78037r1_rule: ") self.log.write( "The system must be configured to queue error reports until a local or DOD-wide collector is available.\n\n") def lock_screen_slide_shows_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78039r1_rule: ") self.log.write( "The display of slide shows on the lock screen must be disabled.\n\n") def winrm_unencrypted_traffic_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77859r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) service must not allow unencrypted traffic.\n\n") def smartscreen_admin_aproval_required_errmsg(self, success): if not success: self.log.write("Check SV-78175r1_rule: ") self.log.write( "The Windows SmartScreen must be configured to require approval from an administrator before running downloaded unknown software.\n\n") def windows_telemetry_data_set_errmsg(self, success): if not success: self.log.write("Check SV-78173r1_rule: ") self.log.write( "Windows Telemetry must be configured to the lowest level of data sent to Microsoft.\n\n") def classic_security_model_set_errmsg(self, success): if not success: self.log.write("Check SV-78251r1_rule: ") self.log.write( "The system must be configured to use the Classic security model.\n\n") def computer_identity_negotiation_set_errmsg(self, success): if not success: self.log.write("Check SV-78253r1_rule: ") self.log.write( "Services using Local System that use Negotiate when reverting to NTLM authentication must use the computer identity vs. authenticating anonymously.\n\n") def ntml_null_session_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78253r1_rule: ") self.log.write( "NTLM must be prevented from falling back to a Null session.\n\n") def group_policy_objects_reprocess_set_errmsg(self, success): if not success: self.log.write("Check SV-78099r1_rule: ") self.log.write( "Group Policy objects must be reprocessed even if they have not changed.\n\n") def pku2u_authentication_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78099r1_rule: ") self.log.write( "PKU2U authentication using online identities must be prevented.\n\n") def powershell_script_block_invocation_logging_errmsg(self, success): if not success: self.log.write("Check SV-83413r1_rule: ") self.log.write( "PowerShell script block invocation logging must be enabled.\n\n") def all_error_ports_added_to_queue_errmsg(self, success): if not success: self.log.write("Check SV-78047r1_rule: ") self.log.write( "The system must be configured to add all error reports to the queue.\n\n") def consent_override_behavior_set_errmsg(self, success): if not success: self.log.write("Check SV-78065r1_rule: ") self.log.write( "The system must be configured to permit the default consent levels of Windows Error Reporting to override any other consent policy setting.\n\n") def data_transmission_consent_set_errmsg(self, success): if not success: self.log.write("Check SV-78061r1_rule: ") self.log.write( "The system must be configured to automatically consent to send all data requested by a local or DOD-wide error collection site.\n\n") def pin_length_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78211r1_rule: ") self.log.write( "The minimum pin length for Microsoft Passport for Work must be 6 characters or greater.\n\n") def encrypted_indexing_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78241r1_rule: ") self.log.write( "Indexing of encrypted files must be turned off.\n\n") def password_storage_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78243r1_rule: ") self.log.write( "The system must be configured to prevent the storage of passwords and credentials.\n\n") def elevated_network_domain_privlidge_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78087r1_rule: ") self.log.write( "Local administrator accounts must have their privileged token filtered to prevent elevated privileges from being used over the network on domain systems.\n\n") def http_printer_driver_dl_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78105r1_rule: ") self.log.write( "Downloading print driver packages over HTTP must be prevented.\n\n") def blank_passwd_accounts_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78107r1_rule: ") self.log.write( "Local accounts with blank passwords must be restricted to prevent access from the network.\n\n") def wifi_sense_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78081r1_rule: ") self.log.write("Wi-Fi Sense must be disabled.\n\n") def emet_antidetours_set_errmsg(self, success): if not success: self.log.write("Check SV-77915r2_rule: ") self.log.write( "The Enhanced Mitigation Experience Toolkit (EMET) Default Actions and Mitigations Settings must enable Anti Detours.\n\n") def uac_admin_mode_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78319r1_rule: ") self.log.write( "User Account Control must run all administrators in Admin Approval Mode, enabling UAC.\n\n") def sys_event_log_size_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78017r1_rule: ") self.log.write( "The System event log size must be configured to 32768 KB or greater.\n\n") def uac_elevate_restricted_errmsg(self, success): if not success: self.log.write( "User Account Control must only elevate UIAccess applications that are installed in secure locations.\n\n") def uac_installer_detection_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78315r1_rule: ") self.log.write( "User Account Control must be configured to detect application installations and prompt for elevation.\n\n") def kerberos_encrypt_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78315r1_rule: ") self.log.write( "Kerberos encryption types must be configured to prevent the use of DES and RC4 encryption suites.\n\n") def smb_packet_signing_required_errmsg(self, success): if not success: self.log.write("Check SV-78213r1_rule: ") self.log.write( "The Windows SMB server must perform SMB packet signing when possible.\n\n") def error_report_ssl_required_errmsg(self, success): if not success: self.log.write("Check SV-78015r1_rule: ") self.log.write( "The system must be configured to use SSL to forward error reports.\n\n") def domain_joined_computers_unenumerated_errmsg(self, success): if not success: self.log.write("Check SV-78015r1_rule: ") self.log.write( "Connected users on domain-joined computers must not be enumerated.\n\n") def max_error_queue_reports_set_errmsg(self, success): if not success: self.log.write("Check SV-78051r1_rule: ") self.log.write( "The maximum number of error reports to queue on a system must be configured to 50 or greater.\n\n") def security_event_log_size_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78051r1_rule: ") self.log.write( "The Security event log size must be configured to 196608 KB or greater.\n\n") def rss_feed_attachements_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78233r1_rule: ") self.log.write( "Attachments must be prevented from being downloaded from RSS feeds.\n\n") def admin_account_elevation_enumeration_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78169r1_rule: ") self.log.write( "Administrator accounts must not be enumerated during elevation.\n\n") def user_errmsg_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77995r1_rule: ") self.log.write( "The system must be configured to prevent the display of error messages to the user.\n\n") def ignore_edge_warnings_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78189r1_rule: ") self.log.write( "Users must not be allowed to ignore SmartScreen filter warnings for malicious websites in Microsoft Edge.\n\n") def wizard_provider_dl_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78189r1_rule: ") self.log.write( "Web publishing and online ordering wizards must be prevented from downloading a list of providers.\n\n") def nondomain_domain_network_blocked_errmsg(self, success): if not success: self.log.write("Check SV-78075r1_rule: ") self.log.write( "Connections to non-domain networks when connected to a domain authenticated network must be blocked.\n\n") def nui_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78119r1_rule: ") self.log.write( "The network selection user interface (UI) must not be displayed on the logon screen.\n\n") def rds_encryption_level_set_errmsg(self, success): if not success: self.log.write("Check SV-78231r1_rule: ") self.log.write( "Remote Desktop Services must be configured with the client connection encryption set to the required level.\n\n") def screen_saver_passwd_required_errmsg(self, success): if not success: self.log.write("Check SV-78231r1_rule: ") self.log.write("The screen saver must be password protected.\n\n") def uac_virtalilzation_set_errmsg(self, success): if not success: self.log.write("Check SV-78321r1_rule: ") self.log.write( "User Account Control must virtualize file and registry write failures to per-user locations.\n\n") def daily_error_reports_required_errmsg(self, success): if not success: self.log.write("Check SV-78055r1_rule: ") self.log.write( "The system must be configured to attempt to forward queued error reports once a day.\n\n") def annonymous_users_excluded_errmsg(self, success): if not success: self.log.write("Check SV-78245r1_rule: ") self.log.write( "The system must be configured to prevent anonymous users from having the same rights as the Everyone group.\n\n") def error_report_archive_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78029r1_rule: ") self.log.write( "The system must be configured to store all data in the error report archive.\n\n") def uac_elevation_requests_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78311r1_rule: ") self.log.write( "User Account Control must automatically deny elevation requests for standard users.\n\n") def smb_insecure_login_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78059r1_rule: ") self.log.write( "Insecure logons to an SMB server must be disabled.\n\n") def error_reports_archived_errmsg(self, success): if not success: self.log.write("Check SV-78025r1_rule: ") self.log.write( "The system must be configured to archive error reports.\n\n") def remote_desktop_host_secure_rpc_required_errmsg(self, success): if not success: self.log.write("Check SV-78227r1_rule: ") self.log.write( "The Remote Desktop Session Host must require secure RPC communications.\n\n") def spn_client_accept_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78225r1_rule: ") self.log.write( " The service principal name (SPN) target name validation level must be configured to Accept if provided by client.\n\n") def rsd_passwd_prompt_required_errmsg(self, success): if not success: self.log.write("Check SV-78223r1_rule: ") self.log.write( "Remote Desktop Services must always prompt a client for passwords upon connection.\n\n") def remote_desktop_session_hosts_local_drive_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78221r1_rule: ") self.log.write( "Local drives must be prevented from sharing with Remote Desktop Session Hosts.\n\n") def outgoing_traffic_secured_errmsg(self, success): if not success: self.log.write("Check SV-78129r1_rule: ") self.log.write( "Outgoing secure channel traffic must be encrypted or signed.\n\n") def pin_signin_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78127r1_rule: ") self.log.write("Signing in using a PIN must be turned off.\n\n") def local_user_enumeration_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78123r1_rule: ") self.log.write( "Local users on domain-joined computers must not be enumerated.\n\n") def emet_banned_functions_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77923r2_rule: ") self.log.write( "The Enhanced Mitigation Experience Toolkit (EMET) Default Actions and Mitigations Settings must enable Banned Functions.\n\n") def onedrive_storage_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78215r1_rule: ") self.log.write( "The use of OneDrive for storage must be disabled.\n\n") def audit_policy_subcategories_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78125r1_rule: ") self.log.write( "Audit policy using subcategories must be enabled.\n\n") def ldap_client_signing_level_set_errmsg(self, success): if not success: self.log.write("Check SV-78293r1_rule: ") self.log.write( "The system must be configured to the required LDAP client signing level.\n\n") def ntlm_ssp_client_session_security_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78295r1_rule: ") self.log.write( "The system must be configured to meet the minimum session security requirement for NTLM SSP based clients.\n\n") def ntlm_ssp_server_session_security_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78297r1_rule: ") self.log.write( "The system must be configured to meet the minimum session security requirement for NTLM SSP based servers.\n\n") def winrm_digest_authentication_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77831r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) client must not use Digest authentication.\n\n") def command_line_creation_event_logged_errmsg(self, success): if not success: self.log.write("Check SV-83409r1_rule: ") self.log.write( "Command line data must be included in process creation events.\n\n") def uac_approval_mode_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78307r1_rule: ") self.log.write( "User Account Control approval mode for the built-in Administrator must be enabled.\n\n") def ac_sleep_wakeup_password_required_errmsg(self, success): if not success: self.log.write("Check SV-78139r1_rule: ") self.log.write( "The user must be prompted for a password on resume from sleep (plugged in)\n\n") def case_insensitivity_required_errmsg(self, success): if not success: self.log.write("Check SV-78303r1_rule: ") self.log.write( "The system must be configured to require case insensitivity for non-Windows subsystems.\n\n") def fips_compliant_algorithims_set_errmsg(self, success): if not success: self.log.write("Check SV-78301r1_rule: ") self.log.write( "The system must be configured to use FIPS-compliant algorithms for encryption, hashing, and signing.\n\n") def untrusted_fonts_blocked_errmsg(self, success): if not success: self.log.write("Check SV-78131r1_rule: ") self.log.write( "The system must be configured to block untrusted fonts from loading.\n\n") def outgoing_traffic_signed_errmsg(self, success): if not success: self.log.write("Check SV-78137r1_rule: ") self.log.write( "Outgoing secure channel traffic must be signed when possible.\n\n") def remote_desktop_client_password_unsaved_errmsg(self, success): if not success: self.log.write("Check SV-78219r1_rule: ") self.log.write( "Passwords must not be saved in the Remote Desktop Client.\n\n") def dc_sleep_wakeup_password_required_errmsg(self, success): if not success: self.log.write("Check SV-78135r1_rule: ") self.log.write( "Users must be prompted for a password on resume from sleep (on battery).\n\n") def admin_consent_prompt_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78309r1_rule: ") self.log.write( "The system must be configured to audit Account Logon - Credential Validation failures.\n\n") def machine_lockout_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78447r1_rule: ") self.log.write( "The machine account lockout threshold must be set to 10 on systems with BitLocker enabled.\n\n") def http_printing_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78113r1_rule: ") self.log.write("Printing over HTTP must be prevented.\n\n") def restart_automatic_signin_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77823r1_rule: ") self.log.write( "Automatically signing in the last interactive user after a system-initiated restart must be disabled.\n\n") def winrm_client_unencrypted_traffic_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77829r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) client must not allow unencrypted traffic.\n\n") def optional_accounts_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78149r1_rule: ") self.log.write( "he setting to allow Microsoft accounts to be optional for modern style apps must be enabled.\n\n") def session_suspension_time_set_errmsg(self, success): if not success: self.log.write("Check SV-78205r1_rule: ") self.log.write( "The amount of idle time required before suspending a session must be configured to 15 minutes or less.\n\n") def password_reset_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78143r1_rule: ") self.log.write( "The computer account password must not be prevented from being reset.\n\n") def password_age_configured_errmsg(self, success): if not success: self.log.write("Check SV-78151r1_rule: ") self.log.write( "The maximum age for machine account passwords must be configured to 30 days or less.\n\n") def apci_data_collection_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78153r1_rule: ") self.log.write( "The Application Compatibility Program Inventory must be prevented from collecting data and sending the information to Microsoft.\n\n") def login_cache_limited_errmsg(self, success): if not success: self.log.write("Check SV-78177r1_rule: ") self.log.write("Caching of logon credentials must be limited.\n\n") def forced_logoff_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78217r1_rule: ") self.log.write( "Users must be forcibly disconnected when their logon hours expire.\n\n") def heap_termination_turnoff_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78217r1_rule: ") self.log.write( "Turning off File Explorer heap termination on corruption must be disabled.\n\n") def domain_controller_authentication_not_required_errmsg(self, success): if not success: self.log.write("Check SV-78183r1_rule: ") self.log.write( "Domain Controller authentication must not be required to unlock the workstation.\n\n") def imcp_redirect_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78053r1_rule: ") self.log.write( "The system must be configured to prevent Internet Control Message Protocol (ICMP) redirects from overriding Open Shortest Path First (OSPF) generated routes.\n\n") def netbios_name_ignored_errmsg(self, success): if not success: self.log.write("Check SV-78057r1_rule: ") self.log.write( "The system must be configured to ignore NetBIOS name release requests except from WINS servers.\n\n") def toast_notification_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78329r1_rule: ") self.log.write( "Toast notifications to the lock screen must be turned off.\n\n") def global_system_objets_permissions_disabled_errmsg(self, success): if not success: self.log.write("Check SV-80171r1_rule: ") self.log.write( "Windows Update must not obtain updates from other PCs on the Internet.\n\n")
45.642945
186
0.625581
DEFAULT_CONFIG = "Windows10SystemLog.txt" class Windows10SystemLogger: def __init__(self, filename=DEFAULT_CONFIG): self.filename = filename self.log = open(filename, 'w') self.log.write("#########################\n\n") self.log.write("Windows10 System Audit Findings\n\n") def __del__(self): print("Write out") self.log.write("#########################\n\n") self.log.close() def get_filename(self): return self.filename def lan_manager_hash_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78287r1_rule: ") self.log.write( "The system must be configured to prevent the storage of the LAN Manager hash of passwords.\n\n") def remote_assistance_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78141r1_rule: ") self.log.write( "Solicited Remote Assistance must not be allowed.\n\n") def windows_installer_elevated_prviliges_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77815r1_rule: ") self.log.write( "The Windows Installer Always install with elevated privileges must be disabled.\n\n") def non_volume_autoplay_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78157r1_rule: ") self.log.write( "Autoplay must be turned off for non-volume devices.\n\n") def annonymous_pipe_access_restricted_errmsg(self, success): if not success: self.log.write("Check SV-78249r1_rule: ") self.log.write( "Anonymous access to Named Pipes and Shares must be restricted.\n\n") def drive_autorun_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78163r1_rule: ") self.log.write("Autoplay must be disabled for all drives.\n\n") def autorun_commands_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78163r1_rule: ") self.log.write( "The default autorun behavior must be configured to prevent autorun commands.\n\n") def sam_anonymous_enumeration_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78235r1_rule: ") self.log.write( "Anonymous enumeration of SAM accounts must not be allowed.\n\n") def sehop_disabled_errmsg(self, success): if not success: self.log.write("Check SV-83445r1_rule: ") self.log.write( "Structured Exception Handling Overwrite Protection (SEHOP) must be turned on.\n\n") def recovery_console_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78299r1_rule: ") self.log.write( "The Recovery Console option must be set to prevent automatic logon to the system.\n\n") def lanman_auth_level_set_errmsg(self, success): if not success: self.log.write("Check SV-78291r1_rule: ") self.log.write( "The LanMan authentication level must be set to send NTLMv2 response only, and to refuse LM and NTLM.\n\n") def winrm_service_basic_auth_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78287r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) service must not use Basic authentication.\n\n") def annonymous_share_enumeration_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78287r1_rule: ") self.log.write( "Anonymous enumeration of shares must be restricted..\n\n") def winrm_client_basic_auth_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77825r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) client must not use Basic authentication.\n\n") def emet_sehop_optout_set_errmsg(self, success): if not success: self.log.write("Check SV-77901r2_rule: ") self.log.write( "The Enhanced Mitigation Experience Toolkit (EMET) system-wide Structured Exception Handler Overwrite Protection (SEHOP) must be configured to Application Opt Out.\n\n") def emet_deephooks_set_errmsg(self, success): if not success: self.log.write("Check SV-77901r2_rule: ") self.log.write( "The Enhanced Mitigation Experience Toolkit (EMET) Default Actions and Mitigations Settings must enable Deep Hooks.\n\n") def unencrypted_passwd_smb_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78201r1_rule: ") self.log.write( "Unencrypted passwords must not be sent to third-party SMB Servers.\n\n") def smartscreen_filter_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78203r1_rule: ") self.log.write( "The SmartScreen filter for Microsoft Edge must be enabled.\n\n") def hardware_device_pfw_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78207r2_rule: ") self.log.write( "The use of a hardware security device with Microsoft Passport for Work must be enabled.\n\n") def smb_packet_signing_set_errmsg(self, success): if not success: self.log.write("Check SV-78209r1_rule: ") self.log.write( "The Windows SMB server must be configured to always perform SMB packet signing.\n\n") def client_rpc_authentication_set_errmsg(self, success): if not success: self.log.write("Check SV-78145r1_rule: ") self.log.write( " Client computers must be required to authenticate for RPC communication.\n\n") def unauthenticated_rpc_elient_restricted_errmsg(self, success): if not success: self.log.write("Check SV-78147r1_rule: ") self.log.write( "Unauthenticated RPC clients must be restricted from connecting to the RPC server.\n\n") def application_event_log_size_set_errmsg(self, success): if not success: self.log.write("Check SV-78009r1_rule: ") self.log.write( "The Application event log size must be configured to 32768 KB or greater.\n\n") def user_installation_option_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77811r1_rule: ") self.log.write( "Users must be prevented from changing installation options.\n\n") def powershell_script_block_logging_enabled_errmsg(self, success): if not success: self.log.write("Check SV-83411r1_rule: ") self.log.write( "PowerShell script block logging must be enabled.\n\n") def tcp_port_set_errmsg(self, success): if not success: self.log.write("Check SV-78019r1_rule: ") self.log.write( "The system must be configured to send error reports on TCP port 1232.\n\n") def strong_session_key_required_errmsg(self, success): if not success: self.log.write("Check SV-78155r1_rule: ") self.log.write( "The system must be configured to require a strong session key.\n\n") def tcp_port_set_errmsg(self, success): if not success: self.log.write("Check SV-78019r1_rule: ") self.log.write( "The system must be configured to send error reports on TCP port 1232.\n\n") def screen_saver_set_errmsg(self, success): if not success: self.log.write("Check SV-78159r1_rule: ") self.log.write( "The machine inactivity limit must be set to 15 minutes, locking the system with the screensaver.\n\n") def error_reports_generated_errmsg(self, success): if not success: self.log.write("Check SV-77949r1_rule: ") self.log.write( "The system must be configured to generate error reports.\n\n") def smb_packet_signing_errmsg(self, success): if not success: self.log.write("Check SV-78197r1_rule: ") self.log.write( "The Windows SMB client must be enabled to perform SMB packet signing when possible.\n\n") def inprivate_browsing_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78195r1_rule: ") self.log.write( "InPrivate browsing in Microsoft Edge must be disabled.\n\n") def smb_packet_signing_required_errmsg(self, success): if not success: self.log.write("Check SV-78193r1_rule: ") self.log.write( "The Windows SMB client must be configured to always perform SMB packet signing.\n\n") def app_override_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78191r1_rule: ") self.log.write( "Users must not be allowed to ignore SmartScreen filter warnings for unverified files in Microsoft Edge.\n\n") def automatic_logon_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78041r2_rule: ") self.log.write("Automatic logons must be disabled.\n\n") def ipv6_routing_protection_configured_errmsg(self, success): if not success: self.log.write("Check SV-78045r1_rule: ") self.log.write( "IPv6 source routing must be configured to highest protection.\n\n") def screen_saver_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78325r1_rule: ") self.log.write("A screen saver must be enabled on the system.\n\n") def ip_source_routing_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78049r1_rule: ") self.log.write( "The system must be configured to prevent IP source routing.\n\n") def multiple_error_reports_set_errmsg(self, success): if not success: self.log.write("Check SV-77987r1_rule: ") self.log.write( "The system must be configured to collect multiple error reports of the same event type.\n\n") def enhanced_antispoofing_set_errmsg(self, success): if not success: self.log.write("Check SV-78167r1_rule: ") self.log.write( "Enhanced anti-spoofing when available must be enabled for facial recognition.\n\n") def winrm_runas_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77865r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) service must not store RunAs credentials.\n\n") def zone_info_saved_errmsg(self, success): if not success: self.log.write("Check SV-78287r1_rule: ") self.log.write( "Zone information must be preserved when saving attachments.\n\n") def num_error_reports_configured_errmsg(self, success): if not success: self.log.write("Check SV-78033r1_rule: ") self.log.write( "The maximum number of error reports to archive on a system must be configured to 100 or greater.\n\n") def lock_screen_camera_access_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78035r1_rule: ") self.log.write( " Camera access from the lock screen must be disabled.\n\n") def queue_error_reports_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78037r1_rule: ") self.log.write( "The system must be configured to queue error reports until a local or DOD-wide collector is available.\n\n") def lock_screen_slide_shows_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78039r1_rule: ") self.log.write( "The display of slide shows on the lock screen must be disabled.\n\n") def winrm_unencrypted_traffic_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77859r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) service must not allow unencrypted traffic.\n\n") def smartscreen_admin_aproval_required_errmsg(self, success): if not success: self.log.write("Check SV-78175r1_rule: ") self.log.write( "The Windows SmartScreen must be configured to require approval from an administrator before running downloaded unknown software.\n\n") def windows_telemetry_data_set_errmsg(self, success): if not success: self.log.write("Check SV-78173r1_rule: ") self.log.write( "Windows Telemetry must be configured to the lowest level of data sent to Microsoft.\n\n") def classic_security_model_set_errmsg(self, success): if not success: self.log.write("Check SV-78251r1_rule: ") self.log.write( "The system must be configured to use the Classic security model.\n\n") def computer_identity_negotiation_set_errmsg(self, success): if not success: self.log.write("Check SV-78253r1_rule: ") self.log.write( "Services using Local System that use Negotiate when reverting to NTLM authentication must use the computer identity vs. authenticating anonymously.\n\n") def ntml_null_session_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78253r1_rule: ") self.log.write( "NTLM must be prevented from falling back to a Null session.\n\n") def group_policy_objects_reprocess_set_errmsg(self, success): if not success: self.log.write("Check SV-78099r1_rule: ") self.log.write( "Group Policy objects must be reprocessed even if they have not changed.\n\n") def pku2u_authentication_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78099r1_rule: ") self.log.write( "PKU2U authentication using online identities must be prevented.\n\n") def powershell_script_block_invocation_logging_errmsg(self, success): if not success: self.log.write("Check SV-83413r1_rule: ") self.log.write( "PowerShell script block invocation logging must be enabled.\n\n") def all_error_ports_added_to_queue_errmsg(self, success): if not success: self.log.write("Check SV-78047r1_rule: ") self.log.write( "The system must be configured to add all error reports to the queue.\n\n") def consent_override_behavior_set_errmsg(self, success): if not success: self.log.write("Check SV-78065r1_rule: ") self.log.write( "The system must be configured to permit the default consent levels of Windows Error Reporting to override any other consent policy setting.\n\n") def data_transmission_consent_set_errmsg(self, success): if not success: self.log.write("Check SV-78061r1_rule: ") self.log.write( "The system must be configured to automatically consent to send all data requested by a local or DOD-wide error collection site.\n\n") def pin_length_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78211r1_rule: ") self.log.write( "The minimum pin length for Microsoft Passport for Work must be 6 characters or greater.\n\n") def encrypted_indexing_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78241r1_rule: ") self.log.write( "Indexing of encrypted files must be turned off.\n\n") def password_storage_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78243r1_rule: ") self.log.write( "The system must be configured to prevent the storage of passwords and credentials.\n\n") def elevated_network_domain_privlidge_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78087r1_rule: ") self.log.write( "Local administrator accounts must have their privileged token filtered to prevent elevated privileges from being used over the network on domain systems.\n\n") def http_printer_driver_dl_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78105r1_rule: ") self.log.write( "Downloading print driver packages over HTTP must be prevented.\n\n") def blank_passwd_accounts_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78107r1_rule: ") self.log.write( "Local accounts with blank passwords must be restricted to prevent access from the network.\n\n") def wifi_sense_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78081r1_rule: ") self.log.write("Wi-Fi Sense must be disabled.\n\n") def emet_antidetours_set_errmsg(self, success): if not success: self.log.write("Check SV-77915r2_rule: ") self.log.write( "The Enhanced Mitigation Experience Toolkit (EMET) Default Actions and Mitigations Settings must enable Anti Detours.\n\n") def uac_admin_mode_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78319r1_rule: ") self.log.write( "User Account Control must run all administrators in Admin Approval Mode, enabling UAC.\n\n") def sys_event_log_size_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78017r1_rule: ") self.log.write( "The System event log size must be configured to 32768 KB or greater.\n\n") def uac_elevate_restricted_errmsg(self, success): if not success: self.log.write( "User Account Control must only elevate UIAccess applications that are installed in secure locations.\n\n") def uac_installer_detection_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78315r1_rule: ") self.log.write( "User Account Control must be configured to detect application installations and prompt for elevation.\n\n") def kerberos_encrypt_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78315r1_rule: ") self.log.write( "Kerberos encryption types must be configured to prevent the use of DES and RC4 encryption suites.\n\n") def smb_packet_signing_required_errmsg(self, success): if not success: self.log.write("Check SV-78213r1_rule: ") self.log.write( "The Windows SMB server must perform SMB packet signing when possible.\n\n") def error_report_ssl_required_errmsg(self, success): if not success: self.log.write("Check SV-78015r1_rule: ") self.log.write( "The system must be configured to use SSL to forward error reports.\n\n") def domain_joined_computers_unenumerated_errmsg(self, success): if not success: self.log.write("Check SV-78015r1_rule: ") self.log.write( "Connected users on domain-joined computers must not be enumerated.\n\n") def max_error_queue_reports_set_errmsg(self, success): if not success: self.log.write("Check SV-78051r1_rule: ") self.log.write( "The maximum number of error reports to queue on a system must be configured to 50 or greater.\n\n") def security_event_log_size_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78051r1_rule: ") self.log.write( "The Security event log size must be configured to 196608 KB or greater.\n\n") def rss_feed_attachements_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78233r1_rule: ") self.log.write( "Attachments must be prevented from being downloaded from RSS feeds.\n\n") def admin_account_elevation_enumeration_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78169r1_rule: ") self.log.write( "Administrator accounts must not be enumerated during elevation.\n\n") def user_errmsg_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77995r1_rule: ") self.log.write( "The system must be configured to prevent the display of error messages to the user.\n\n") def ignore_edge_warnings_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78189r1_rule: ") self.log.write( "Users must not be allowed to ignore SmartScreen filter warnings for malicious websites in Microsoft Edge.\n\n") def wizard_provider_dl_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78189r1_rule: ") self.log.write( "Web publishing and online ordering wizards must be prevented from downloading a list of providers.\n\n") def nondomain_domain_network_blocked_errmsg(self, success): if not success: self.log.write("Check SV-78075r1_rule: ") self.log.write( "Connections to non-domain networks when connected to a domain authenticated network must be blocked.\n\n") def nui_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78119r1_rule: ") self.log.write( "The network selection user interface (UI) must not be displayed on the logon screen.\n\n") def rds_encryption_level_set_errmsg(self, success): if not success: self.log.write("Check SV-78231r1_rule: ") self.log.write( "Remote Desktop Services must be configured with the client connection encryption set to the required level.\n\n") def screen_saver_passwd_required_errmsg(self, success): if not success: self.log.write("Check SV-78231r1_rule: ") self.log.write("The screen saver must be password protected.\n\n") def uac_virtalilzation_set_errmsg(self, success): if not success: self.log.write("Check SV-78321r1_rule: ") self.log.write( "User Account Control must virtualize file and registry write failures to per-user locations.\n\n") def daily_error_reports_required_errmsg(self, success): if not success: self.log.write("Check SV-78055r1_rule: ") self.log.write( "The system must be configured to attempt to forward queued error reports once a day.\n\n") def annonymous_users_excluded_errmsg(self, success): if not success: self.log.write("Check SV-78245r1_rule: ") self.log.write( "The system must be configured to prevent anonymous users from having the same rights as the Everyone group.\n\n") def error_report_archive_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78029r1_rule: ") self.log.write( "The system must be configured to store all data in the error report archive.\n\n") def uac_elevation_requests_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78311r1_rule: ") self.log.write( "User Account Control must automatically deny elevation requests for standard users.\n\n") def smb_insecure_login_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78059r1_rule: ") self.log.write( "Insecure logons to an SMB server must be disabled.\n\n") def error_reports_archived_errmsg(self, success): if not success: self.log.write("Check SV-78025r1_rule: ") self.log.write( "The system must be configured to archive error reports.\n\n") def remote_desktop_host_secure_rpc_required_errmsg(self, success): if not success: self.log.write("Check SV-78227r1_rule: ") self.log.write( "The Remote Desktop Session Host must require secure RPC communications.\n\n") def spn_client_accept_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78225r1_rule: ") self.log.write( " The service principal name (SPN) target name validation level must be configured to Accept if provided by client.\n\n") def rsd_passwd_prompt_required_errmsg(self, success): if not success: self.log.write("Check SV-78223r1_rule: ") self.log.write( "Remote Desktop Services must always prompt a client for passwords upon connection.\n\n") def remote_desktop_session_hosts_local_drive_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78221r1_rule: ") self.log.write( "Local drives must be prevented from sharing with Remote Desktop Session Hosts.\n\n") def outgoing_traffic_secured_errmsg(self, success): if not success: self.log.write("Check SV-78129r1_rule: ") self.log.write( "Outgoing secure channel traffic must be encrypted or signed.\n\n") def pin_signin_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78127r1_rule: ") self.log.write("Signing in using a PIN must be turned off.\n\n") def local_user_enumeration_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78123r1_rule: ") self.log.write( "Local users on domain-joined computers must not be enumerated.\n\n") def emet_banned_functions_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77923r2_rule: ") self.log.write( "The Enhanced Mitigation Experience Toolkit (EMET) Default Actions and Mitigations Settings must enable Banned Functions.\n\n") def onedrive_storage_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78215r1_rule: ") self.log.write( "The use of OneDrive for storage must be disabled.\n\n") def audit_policy_subcategories_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78125r1_rule: ") self.log.write( "Audit policy using subcategories must be enabled.\n\n") def ldap_client_signing_level_set_errmsg(self, success): if not success: self.log.write("Check SV-78293r1_rule: ") self.log.write( "The system must be configured to the required LDAP client signing level.\n\n") def ntlm_ssp_client_session_security_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78295r1_rule: ") self.log.write( "The system must be configured to meet the minimum session security requirement for NTLM SSP based clients.\n\n") def ntlm_ssp_server_session_security_configuered_errmsg(self, success): if not success: self.log.write("Check SV-78297r1_rule: ") self.log.write( "The system must be configured to meet the minimum session security requirement for NTLM SSP based servers.\n\n") def winrm_digest_authentication_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77831r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) client must not use Digest authentication.\n\n") def command_line_creation_event_logged_errmsg(self, success): if not success: self.log.write("Check SV-83409r1_rule: ") self.log.write( "Command line data must be included in process creation events.\n\n") def uac_approval_mode_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78307r1_rule: ") self.log.write( "User Account Control approval mode for the built-in Administrator must be enabled.\n\n") def ac_sleep_wakeup_password_required_errmsg(self, success): if not success: self.log.write("Check SV-78139r1_rule: ") self.log.write( "The user must be prompted for a password on resume from sleep (plugged in)\n\n") def case_insensitivity_required_errmsg(self, success): if not success: self.log.write("Check SV-78303r1_rule: ") self.log.write( "The system must be configured to require case insensitivity for non-Windows subsystems.\n\n") def fips_compliant_algorithims_set_errmsg(self, success): if not success: self.log.write("Check SV-78301r1_rule: ") self.log.write( "The system must be configured to use FIPS-compliant algorithms for encryption, hashing, and signing.\n\n") def untrusted_fonts_blocked_errmsg(self, success): if not success: self.log.write("Check SV-78131r1_rule: ") self.log.write( "The system must be configured to block untrusted fonts from loading.\n\n") def outgoing_traffic_signed_errmsg(self, success): if not success: self.log.write("Check SV-78137r1_rule: ") self.log.write( "Outgoing secure channel traffic must be signed when possible.\n\n") def remote_desktop_client_password_unsaved_errmsg(self, success): if not success: self.log.write("Check SV-78219r1_rule: ") self.log.write( "Passwords must not be saved in the Remote Desktop Client.\n\n") def dc_sleep_wakeup_password_required_errmsg(self, success): if not success: self.log.write("Check SV-78135r1_rule: ") self.log.write( "Users must be prompted for a password on resume from sleep (on battery).\n\n") def admin_consent_prompt_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78309r1_rule: ") self.log.write( "The system must be configured to audit Account Logon - Credential Validation failures.\n\n") def machine_lockout_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78447r1_rule: ") self.log.write( "The machine account lockout threshold must be set to 10 on systems with BitLocker enabled.\n\n") def http_printing_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78113r1_rule: ") self.log.write("Printing over HTTP must be prevented.\n\n") def restart_automatic_signin_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77823r1_rule: ") self.log.write( "Automatically signing in the last interactive user after a system-initiated restart must be disabled.\n\n") def winrm_client_unencrypted_traffic_disabled_errmsg(self, success): if not success: self.log.write("Check SV-77829r1_rule: ") self.log.write( "The Windows Remote Management (WinRM) client must not allow unencrypted traffic.\n\n") def optional_accounts_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78149r1_rule: ") self.log.write( "he setting to allow Microsoft accounts to be optional for modern style apps must be enabled.\n\n") def session_suspension_time_set_errmsg(self, success): if not success: self.log.write("Check SV-78205r1_rule: ") self.log.write( "The amount of idle time required before suspending a session must be configured to 15 minutes or less.\n\n") def password_reset_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78143r1_rule: ") self.log.write( "The computer account password must not be prevented from being reset.\n\n") def password_age_configured_errmsg(self, success): if not success: self.log.write("Check SV-78151r1_rule: ") self.log.write( "The maximum age for machine account passwords must be configured to 30 days or less.\n\n") def apci_data_collection_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78153r1_rule: ") self.log.write( "The Application Compatibility Program Inventory must be prevented from collecting data and sending the information to Microsoft.\n\n") def login_cache_limited_errmsg(self, success): if not success: self.log.write("Check SV-78177r1_rule: ") self.log.write("Caching of logon credentials must be limited.\n\n") def forced_logoff_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78217r1_rule: ") self.log.write( "Users must be forcibly disconnected when their logon hours expire.\n\n") def heap_termination_turnoff_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78217r1_rule: ") self.log.write( "Turning off File Explorer heap termination on corruption must be disabled.\n\n") def domain_controller_authentication_not_required_errmsg(self, success): if not success: self.log.write("Check SV-78183r1_rule: ") self.log.write( "Domain Controller authentication must not be required to unlock the workstation.\n\n") def imcp_redirect_enabled_errmsg(self, success): if not success: self.log.write("Check SV-78053r1_rule: ") self.log.write( "The system must be configured to prevent Internet Control Message Protocol (ICMP) redirects from overriding Open Shortest Path First (OSPF) generated routes.\n\n") def netbios_name_ignored_errmsg(self, success): if not success: self.log.write("Check SV-78057r1_rule: ") self.log.write( "The system must be configured to ignore NetBIOS name release requests except from WINS servers.\n\n") def toast_notification_disabled_errmsg(self, success): if not success: self.log.write("Check SV-78329r1_rule: ") self.log.write( "Toast notifications to the lock screen must be turned off.\n\n") def global_system_objets_permissions_disabled_errmsg(self, success): if not success: self.log.write("Check SV-80171r1_rule: ") self.log.write( "Windows Update must not obtain updates from other PCs on the Internet.\n\n")
true
true
f714a9a3b54319c86838c7546260c190131c7098
1,978
py
Python
test/TestExpressionParser.py
imrushabh/cronjob-expression-parser
8e577245e7956fa85222bbc5f37beb13aba7819b
[ "MIT" ]
null
null
null
test/TestExpressionParser.py
imrushabh/cronjob-expression-parser
8e577245e7956fa85222bbc5f37beb13aba7819b
[ "MIT" ]
null
null
null
test/TestExpressionParser.py
imrushabh/cronjob-expression-parser
8e577245e7956fa85222bbc5f37beb13aba7819b
[ "MIT" ]
null
null
null
import TestConstants from generator.ExpressionParser import ExpressionParser import unittest class TestExpressionParser(unittest.TestCase): # Test to verify the minute functionality & */multiple expression check. def test_valid_minute_parsing(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertListEqual(expressionParser._parse_minutes(TestConstants.Minutes),[0,20,40]) # Test to verify the invalid minute functionality & */multiple expression check. def test_invalid_minute_parsing(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertNotEqual(expressionParser._parse_minutes(TestConstants.Minutes),[1,20,40]) # Test to verify the hour functionality & [a-b] (hyphen) expression check. def test_valid_hour_parsing(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertListEqual(expressionParser._parse_hours(TestConstants.Hours),[2,3,4]) # Test to verify the month_parsing functionality & comma seperated expression check. def test_valid_day_in_month_parsing(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertListEqual(expressionParser._parse_month(TestConstants.Days_in_month),[6,8,9]) # Test to verify the week functionality & * expression check. def test_valid_day_in_week_parsing(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertListEqual(expressionParser._parse_day_of_week(TestConstants.Days_in_week),[1,2,3,4,5,6,7]) # Test to verify the command functionality check. def test_valid_command(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertListEqual(expressionParser._parse_command(TestConstants.Command),['/usr/bin/find']) if __name__ == '__main__': unittest.main()
52.052632
109
0.776036
import TestConstants from generator.ExpressionParser import ExpressionParser import unittest class TestExpressionParser(unittest.TestCase): def test_valid_minute_parsing(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertListEqual(expressionParser._parse_minutes(TestConstants.Minutes),[0,20,40]) def test_invalid_minute_parsing(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertNotEqual(expressionParser._parse_minutes(TestConstants.Minutes),[1,20,40]) def test_valid_hour_parsing(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertListEqual(expressionParser._parse_hours(TestConstants.Hours),[2,3,4]) def test_valid_day_in_month_parsing(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertListEqual(expressionParser._parse_month(TestConstants.Days_in_month),[6,8,9]) def test_valid_day_in_week_parsing(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertListEqual(expressionParser._parse_day_of_week(TestConstants.Days_in_week),[1,2,3,4,5,6,7]) def test_valid_command(self): expressionParser = ExpressionParser(TestConstants.Valid_cron_expression) self.assertListEqual(expressionParser._parse_command(TestConstants.Command),['/usr/bin/find']) if __name__ == '__main__': unittest.main()
true
true
f714aa4914f7a4f30b2904dd1876178860dd2364
44,061
py
Python
zerver/tests/test_slack_importer.py
DD2480-group7-2020/zulip
9a1e18bcf383c38c35da168563a7345768c6d784
[ "Apache-2.0" ]
1
2020-03-17T14:58:50.000Z
2020-03-17T14:58:50.000Z
zerver/tests/test_slack_importer.py
DD2480-group7-2020/zulip
9a1e18bcf383c38c35da168563a7345768c6d784
[ "Apache-2.0" ]
null
null
null
zerver/tests/test_slack_importer.py
DD2480-group7-2020/zulip
9a1e18bcf383c38c35da168563a7345768c6d784
[ "Apache-2.0" ]
1
2020-07-16T06:00:10.000Z
2020-07-16T06:00:10.000Z
# -*- coding: utf-8 -*- from django.conf import settings from django.utils.timezone import now as timezone_now from zerver.data_import.slack import ( get_slack_api_data, get_admin, get_guest, get_user_timezone, fetch_shared_channel_users, users_to_zerver_userprofile, get_subscription, channels_to_zerver_stream, slack_workspace_to_realm, get_message_sending_user, channel_message_to_zerver_message, convert_slack_workspace_messages, do_convert_data, process_message_files, AddedChannelsT, AddedMPIMsT, DMMembersT, ZerverFieldsT, ) from zerver.data_import.import_util import ( build_zerver_realm, build_subscription, build_recipient, build_usermessages, build_defaultstream, ) from zerver.data_import.sequencer import ( NEXT_ID, ) from zerver.lib.import_realm import ( do_import_realm, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.test_helpers import ( get_test_image_file ) from zerver.lib.topic import ( EXPORT_TOPIC_NAME, ) from zerver.models import ( Realm, get_realm, RealmAuditLog, Recipient, UserProfile, ) import ujson import logging import shutil import os import mock from mock import ANY, call from typing import Any, Dict, List, Set, Tuple, Iterator def remove_folder(path: str) -> None: if os.path.exists(path): shutil.rmtree(path) # This method will be used by the mock to replace requests.get def mocked_requests_get(*args: List[str], **kwargs: List[str]) -> mock.Mock: class MockResponse: def __init__(self, json_data: Dict[str, Any], status_code: int) -> None: self.json_data = json_data self.status_code = status_code def json(self) -> Dict[str, Any]: return self.json_data if args[0] == 'https://slack.com/api/users.list?token=xoxp-valid-token': return MockResponse({"ok": True, "members": "user_data"}, 200) elif args[0] == 'https://slack.com/api/users.list?token=xoxp-invalid-token': return MockResponse({"ok": False, "error": "invalid_auth"}, 200) else: return MockResponse(None, 404) class SlackImporter(ZulipTestCase): logger = logging.getLogger() # set logger to a higher level to suppress 'logger.INFO' outputs logger.setLevel(logging.WARNING) @mock.patch('requests.get', side_effect=mocked_requests_get) def test_get_slack_api_data(self, mock_get: mock.Mock) -> None: token = 'xoxp-valid-token' slack_user_list_url = "https://slack.com/api/users.list" self.assertEqual(get_slack_api_data(slack_user_list_url, "members", token=token), "user_data") token = 'xoxp-invalid-token' with self.assertRaises(Exception) as invalid: get_slack_api_data(slack_user_list_url, "members", token=token) self.assertEqual(invalid.exception.args, ('Error accessing Slack API: invalid_auth',),) token = 'xoxe-invalid-token' with self.assertRaises(Exception) as invalid: get_slack_api_data(slack_user_list_url, "members", token=token) self.assertTrue(invalid.exception.args[0].startswith("Invalid Slack legacy token.\n")) with self.assertRaises(Exception) as invalid: get_slack_api_data(slack_user_list_url, "members") self.assertEqual(invalid.exception.args, ('Slack token missing in kwargs',),) token = 'xoxp-status404' wrong_url = "https://slack.com/api/wrong" with self.assertRaises(Exception) as invalid: get_slack_api_data(wrong_url, "members", token=token) self.assertEqual(invalid.exception.args, ('HTTP error accessing the Slack API.',),) def test_build_zerver_realm(self) -> None: realm_id = 2 realm_subdomain = "test-realm" time = float(timezone_now().timestamp()) test_realm = build_zerver_realm(realm_id, realm_subdomain, time, 'Slack') # type: List[Dict[str, Any]] test_zerver_realm_dict = test_realm[0] self.assertEqual(test_zerver_realm_dict['id'], realm_id) self.assertEqual(test_zerver_realm_dict['string_id'], realm_subdomain) self.assertEqual(test_zerver_realm_dict['name'], realm_subdomain) self.assertEqual(test_zerver_realm_dict['date_created'], time) def test_get_admin(self) -> None: user_data = [{'is_admin': True, 'is_owner': False, 'is_primary_owner': False}, {'is_admin': True, 'is_owner': True, 'is_primary_owner': False}, {'is_admin': True, 'is_owner': True, 'is_primary_owner': True}, {'is_admin': False, 'is_owner': False, 'is_primary_owner': False}] self.assertEqual(get_admin(user_data[0]), True) self.assertEqual(get_admin(user_data[1]), True) self.assertEqual(get_admin(user_data[2]), True) self.assertEqual(get_admin(user_data[3]), False) def test_get_guest(self) -> None: user_data = [{'is_restricted': False, 'is_ultra_restricted': False}, {'is_restricted': True, 'is_ultra_restricted': False}, {'is_restricted': False, 'is_ultra_restricted': True}, {'is_restricted': True, 'is_ultra_restricted': True}] self.assertEqual(get_guest(user_data[0]), False) self.assertEqual(get_guest(user_data[1]), True) self.assertEqual(get_guest(user_data[2]), True) self.assertEqual(get_guest(user_data[3]), True) def test_get_timezone(self) -> None: user_chicago_timezone = {"tz": "America/Chicago"} user_timezone_none = {"tz": None} user_no_timezone = {} # type: Dict[str, Any] self.assertEqual(get_user_timezone(user_chicago_timezone), "America/Chicago") self.assertEqual(get_user_timezone(user_timezone_none), "America/New_York") self.assertEqual(get_user_timezone(user_no_timezone), "America/New_York") @mock.patch("zerver.data_import.slack.get_data_file") @mock.patch("zerver.data_import.slack.get_slack_api_data") @mock.patch("zerver.data_import.slack.get_messages_iterator") def test_fetch_shared_channel_users(self, messages_mock: mock.Mock, api_mock: mock.Mock, data_file_mock: mock.Mock) -> None: users = [{"id": "U061A1R2R"}, {"id": "U061A5N1G"}, {"id": "U064KUGRJ"}] data_file_mock.side_effect = [ [ {"name": "general", "members": ["U061A1R2R", "U061A5N1G"]}, {"name": "sharedchannel", "members": ["U061A1R2R", "U061A3E0G"]} ], [] ] api_mock.side_effect = [ {"id": "U061A3E0G", "team_id": "T6LARQE2Z"}, {"domain": "foreignteam1"}, {"id": "U061A8H1G", "team_id": "T7KJRQE8Y"}, {"domain": "foreignteam2"}, ] messages_mock.return_value = [ {"user": "U061A1R2R"}, {"user": "U061A5N1G"}, {"user": "U061A8H1G"}, ] slack_data_dir = self.fixture_file_name('', type='slack_fixtures') fetch_shared_channel_users(users, slack_data_dir, "token") # Normal users self.assertEqual(len(users), 5) self.assertEqual(users[0]["id"], "U061A1R2R") self.assertEqual(users[0]["is_mirror_dummy"], False) self.assertFalse("team_domain" in users[0]) self.assertEqual(users[1]["id"], "U061A5N1G") self.assertEqual(users[2]["id"], "U064KUGRJ") # Shared channel users self.assertEqual(users[3]["id"], "U061A3E0G") self.assertEqual(users[3]["team_domain"], "foreignteam1") self.assertEqual(users[3]["is_mirror_dummy"], True) self.assertEqual(users[4]["id"], "U061A8H1G") self.assertEqual(users[4]["team_domain"], "foreignteam2") self.assertEqual(users[4]["is_mirror_dummy"], True) api_calls = [ call("https://slack.com/api/users.info", "user", token="token", user="U061A3E0G"), call("https://slack.com/api/team.info", "team", token="token", team="T6LARQE2Z"), call("https://slack.com/api/users.info", "user", token="token", user="U061A8H1G"), call("https://slack.com/api/team.info", "team", token="token", team="T7KJRQE8Y") ] api_mock.assert_has_calls(api_calls, any_order=True) @mock.patch("zerver.data_import.slack.get_data_file") def test_users_to_zerver_userprofile(self, mock_get_data_file: mock.Mock) -> None: custom_profile_field_user1 = {"Xf06054BBB": {"value": "random1"}, "Xf023DSCdd": {"value": "employee"}} custom_profile_field_user2 = {"Xf06054BBB": {"value": "random2"}, "Xf023DSCdd": {"value": "employer"}} user_data = [{"id": "U08RGD1RD", "team_id": "T5YFFM2QY", "name": "john", "deleted": False, "is_mirror_dummy": False, "real_name": "John Doe", "profile": {"image_32": "", "email": "jon@gmail.com", "avatar_hash": "hash", "phone": "+1-123-456-77-868", "fields": custom_profile_field_user1}}, {"id": "U0CBK5KAT", "team_id": "T5YFFM2QY", "is_admin": True, "is_bot": False, "is_owner": True, "is_primary_owner": True, 'name': 'Jane', "real_name": "Jane Doe", "deleted": False, "is_mirror_dummy": False, "profile": {"image_32": "https://secure.gravatar.com/avatar/random.png", "fields": custom_profile_field_user2, "email": "jane@foo.com", "avatar_hash": "hash"}}, {"id": "U09TYF5Sk", "team_id": "T5YFFM2QY", "name": "Bot", "real_name": "Bot", "is_bot": True, "deleted": False, "is_mirror_dummy": False, "profile": {"image_32": "https://secure.gravatar.com/avatar/random1.png", "skype": "test_skype_name", "email": "bot1@zulipchat.com", "avatar_hash": "hash"}}, {"id": "UHSG7OPQN", "team_id": "T6LARQE2Z", 'name': 'matt.perry', "color": '9d8eee', "is_bot": False, "is_app_user": False, "is_mirror_dummy": True, "team_domain": "foreignteam", "profile": {"image_32": "https://secure.gravatar.com/avatar/random6.png", "avatar_hash": "hash", "first_name": "Matt", "last_name": "Perry", "real_name": "Matt Perry", "display_name": "matt.perry", "team": "T6LARQE2Z"}}, {"id": "U8VAHEVUY", "team_id": "T5YFFM2QY", "name": "steviejacob34", "real_name": "Steve Jacob", "is_admin": False, "is_owner": False, "is_primary_owner": False, "is_restricted": True, "is_ultra_restricted": False, "is_bot": False, "is_mirror_dummy": False, "profile": {"email": "steviejacob34@yahoo.com", "avatar_hash": "hash", "image_32": "https://secure.gravatar.com/avatar/random6.png"}}, {"id": "U8X25EBAB", "team_id": "T5YFFM2QY", "name": "pratikweb_0", "real_name": "Pratik", "is_admin": False, "is_owner": False, "is_primary_owner": False, "is_restricted": True, "is_ultra_restricted": True, "is_bot": False, "is_mirror_dummy": False, "profile": {"email": "pratik@mit.edu", "avatar_hash": "hash", "image_32": "https://secure.gravatar.com/avatar/random.png"}}] mock_get_data_file.return_value = user_data # As user with slack_id 'U0CBK5KAT' is the primary owner, that user should be imported first # and hence has zulip_id = 1 test_slack_user_id_to_zulip_user_id = {'U08RGD1RD': 1, 'U0CBK5KAT': 0, 'U09TYF5Sk': 2, 'UHSG7OPQN': 3, 'U8VAHEVUY': 4, 'U8X25EBAB': 5} slack_data_dir = './random_path' timestamp = int(timezone_now().timestamp()) mock_get_data_file.return_value = user_data zerver_userprofile, avatar_list, slack_user_id_to_zulip_user_id, customprofilefield, \ customprofilefield_value = users_to_zerver_userprofile(slack_data_dir, user_data, 1, timestamp, 'test_domain') # Test custom profile fields self.assertEqual(customprofilefield[0]['field_type'], 1) self.assertEqual(customprofilefield[3]['name'], 'skype') cpf_name = {cpf['name'] for cpf in customprofilefield} self.assertIn('phone', cpf_name) self.assertIn('skype', cpf_name) cpf_name.remove('phone') cpf_name.remove('skype') for name in cpf_name: self.assertTrue(name.startswith('slack custom field ')) self.assertEqual(len(customprofilefield_value), 6) self.assertEqual(customprofilefield_value[0]['field'], 0) self.assertEqual(customprofilefield_value[0]['user_profile'], 1) self.assertEqual(customprofilefield_value[3]['user_profile'], 0) self.assertEqual(customprofilefield_value[5]['value'], 'test_skype_name') # test that the primary owner should always be imported first self.assertDictEqual(slack_user_id_to_zulip_user_id, test_slack_user_id_to_zulip_user_id) self.assertEqual(len(avatar_list), 6) self.assertEqual(len(zerver_userprofile), 6) self.assertEqual(zerver_userprofile[0]['is_staff'], False) self.assertEqual(zerver_userprofile[0]['is_bot'], False) self.assertEqual(zerver_userprofile[0]['is_active'], True) self.assertEqual(zerver_userprofile[0]['is_mirror_dummy'], False) self.assertEqual(zerver_userprofile[0]['role'], UserProfile.ROLE_MEMBER) self.assertEqual(zerver_userprofile[0]['enable_desktop_notifications'], True) self.assertEqual(zerver_userprofile[0]['email'], 'jon@gmail.com') self.assertEqual(zerver_userprofile[0]['full_name'], 'John Doe') self.assertEqual(zerver_userprofile[1]['id'], test_slack_user_id_to_zulip_user_id['U0CBK5KAT']) self.assertEqual(zerver_userprofile[1]['role'], UserProfile.ROLE_REALM_ADMINISTRATOR) self.assertEqual(zerver_userprofile[1]['is_staff'], False) self.assertEqual(zerver_userprofile[1]['is_active'], True) self.assertEqual(zerver_userprofile[0]['is_mirror_dummy'], False) self.assertEqual(zerver_userprofile[2]['id'], test_slack_user_id_to_zulip_user_id['U09TYF5Sk']) self.assertEqual(zerver_userprofile[2]['is_bot'], True) self.assertEqual(zerver_userprofile[2]['is_active'], True) self.assertEqual(zerver_userprofile[2]['is_mirror_dummy'], False) self.assertEqual(zerver_userprofile[2]['email'], 'bot1@zulipchat.com') self.assertEqual(zerver_userprofile[2]['bot_type'], 1) self.assertEqual(zerver_userprofile[2]['avatar_source'], 'U') self.assertEqual(zerver_userprofile[3]['id'], test_slack_user_id_to_zulip_user_id['UHSG7OPQN']) self.assertEqual(zerver_userprofile[3]['role'], UserProfile.ROLE_MEMBER) self.assertEqual(zerver_userprofile[3]['is_staff'], False) self.assertEqual(zerver_userprofile[3]['is_active'], False) self.assertEqual(zerver_userprofile[3]['email'], 'matt.perry@foreignteam.slack.com') self.assertEqual(zerver_userprofile[3]['realm'], 1) self.assertEqual(zerver_userprofile[3]['full_name'], 'Matt Perry') self.assertEqual(zerver_userprofile[3]['short_name'], 'matt.perry') self.assertEqual(zerver_userprofile[3]['is_mirror_dummy'], True) self.assertEqual(zerver_userprofile[3]['is_api_super_user'], False) self.assertEqual(zerver_userprofile[4]['id'], test_slack_user_id_to_zulip_user_id['U8VAHEVUY']) self.assertEqual(zerver_userprofile[4]['role'], UserProfile.ROLE_GUEST) self.assertEqual(zerver_userprofile[4]['is_staff'], False) self.assertEqual(zerver_userprofile[4]['is_active'], True) self.assertEqual(zerver_userprofile[4]['is_mirror_dummy'], False) self.assertEqual(zerver_userprofile[5]['id'], test_slack_user_id_to_zulip_user_id['U8X25EBAB']) self.assertEqual(zerver_userprofile[5]['role'], UserProfile.ROLE_GUEST) self.assertEqual(zerver_userprofile[5]['is_staff'], False) self.assertEqual(zerver_userprofile[5]['is_active'], True) self.assertEqual(zerver_userprofile[5]['is_mirror_dummy'], False) def test_build_defaultstream(self) -> None: realm_id = 1 stream_id = 1 default_channel_general = build_defaultstream(realm_id, stream_id, 1) test_default_channel = {'stream': 1, 'realm': 1, 'id': 1} self.assertDictEqual(test_default_channel, default_channel_general) default_channel_general = build_defaultstream(realm_id, stream_id, 1) test_default_channel = {'stream': 1, 'realm': 1, 'id': 1} self.assertDictEqual(test_default_channel, default_channel_general) def test_build_pm_recipient_sub_from_user(self) -> None: zulip_user_id = 3 recipient_id = 5 subscription_id = 7 sub = build_subscription(recipient_id, zulip_user_id, subscription_id) recipient = build_recipient(zulip_user_id, recipient_id, Recipient.PERSONAL) self.assertEqual(recipient['id'], sub['recipient']) self.assertEqual(recipient['type_id'], sub['user_profile']) self.assertEqual(recipient['type'], Recipient.PERSONAL) self.assertEqual(recipient['type_id'], 3) self.assertEqual(sub['recipient'], 5) self.assertEqual(sub['id'], 7) self.assertEqual(sub['active'], True) def test_build_subscription(self) -> None: channel_members = ["U061A1R2R", "U061A3E0G", "U061A5N1G", "U064KUGRJ"] slack_user_id_to_zulip_user_id = {"U061A1R2R": 1, "U061A3E0G": 8, "U061A5N1G": 7, "U064KUGRJ": 5} subscription_id_count = 0 recipient_id = 12 zerver_subscription = [] # type: List[Dict[str, Any]] final_subscription_id = get_subscription(channel_members, zerver_subscription, recipient_id, slack_user_id_to_zulip_user_id, subscription_id_count) # sanity checks self.assertEqual(final_subscription_id, 4) self.assertEqual(zerver_subscription[0]['recipient'], 12) self.assertEqual(zerver_subscription[0]['id'], 0) self.assertEqual(zerver_subscription[0]['user_profile'], slack_user_id_to_zulip_user_id[channel_members[0]]) self.assertEqual(zerver_subscription[2]['user_profile'], slack_user_id_to_zulip_user_id[channel_members[2]]) self.assertEqual(zerver_subscription[3]['id'], 3) self.assertEqual(zerver_subscription[1]['recipient'], zerver_subscription[3]['recipient']) self.assertEqual(zerver_subscription[1]['pin_to_top'], False) def test_channels_to_zerver_stream(self) -> None: slack_user_id_to_zulip_user_id = {"U061A1R2R": 1, "U061A3E0G": 8, "U061A5N1G": 7, "U064KUGRJ": 5} zerver_userprofile = [{'id': 1}, {'id': 8}, {'id': 7}, {'id': 5}] realm_id = 3 realm, added_channels, added_mpims, dm_members, slack_recipient_name_to_zulip_recipient_id = \ channels_to_zerver_stream(self.fixture_file_name("", "slack_fixtures"), realm_id, {"zerver_userpresence": []}, slack_user_id_to_zulip_user_id, zerver_userprofile) test_added_channels = {'sharedchannel': ("C061A0HJG", 3), 'general': ("C061A0YJG", 1), 'general1': ("C061A0YJP", 2), 'random': ("C061A0WJG", 0)} test_added_mpims = {'mpdm-user9--user2--user10-1': ('G9HBG2A5D', 0), 'mpdm-user6--user7--user4-1': ('G6H1Z0ZPS', 1), 'mpdm-user4--user1--user5-1': ('G6N944JPL', 2)} test_dm_members = {'DJ47BL849': ('U061A1R2R', 'U061A5N1G'), 'DHX1UP7EG': ('U061A5N1G', 'U064KUGRJ'), 'DK8HSJDHS': ('U061A1R2R', 'U064KUGRJ'), 'DRS3PSLDK': ('U064KUGRJ', 'U064KUGRJ')} slack_recipient_names = set(slack_user_id_to_zulip_user_id.keys()) | set(test_added_channels.keys()) \ | set(test_added_mpims.keys()) self.assertDictEqual(test_added_channels, added_channels) # zerver defaultstream already tested in helper functions self.assertEqual(realm["zerver_defaultstream"], [{'id': 0, 'realm': 3, 'stream': 0}, {'id': 1, 'realm': 3, 'stream': 1}]) self.assertDictEqual(test_added_mpims, added_mpims) self.assertDictEqual(test_dm_members, dm_members) # We can't do an assertDictEqual since during the construction of Personal # recipients, slack_user_id_to_zulip_user_id are iterated in diffrent order in Python 3.5 and 3.6. self.assertEqual(set(slack_recipient_name_to_zulip_recipient_id.keys()), slack_recipient_names) self.assertEqual(set(slack_recipient_name_to_zulip_recipient_id.values()), set(i for i in range(11))) # functioning of zerver subscriptions are already tested in the helper functions # This is to check the concatenation of the output lists from the helper functions # subscriptions for stream zerver_subscription = realm["zerver_subscription"] zerver_recipient = realm["zerver_recipient"] zerver_stream = realm["zerver_stream"] self.assertEqual(self.get_set(zerver_subscription, "recipient"), {i for i in range(11)}) self.assertEqual(self.get_set(zerver_subscription, "user_profile"), {1, 5, 7, 8}) self.assertEqual(self.get_set(zerver_recipient, "id"), self.get_set(zerver_subscription, "recipient")) self.assertEqual(self.get_set(zerver_recipient, "type_id"), {0, 1, 2, 3, 5, 7, 8}) self.assertEqual(self.get_set(zerver_recipient, "type"), {1, 2, 3}) # stream mapping self.assertEqual(zerver_stream[0]['name'], "random") self.assertEqual(zerver_stream[0]['deactivated'], True) self.assertEqual(zerver_stream[0]['description'], 'no purpose') self.assertEqual(zerver_stream[0]['invite_only'], False) self.assertEqual(zerver_stream[0]['realm'], realm_id) self.assertEqual(zerver_stream[2]['id'], test_added_channels[zerver_stream[2]['name']][1]) self.assertEqual(self.get_set(realm["zerver_huddle"], "id"), {0, 1, 2}) self.assertEqual(realm["zerver_userpresence"], []) @mock.patch("zerver.data_import.slack.users_to_zerver_userprofile", return_value=[[], [], {}, [], []]) @mock.patch("zerver.data_import.slack.channels_to_zerver_stream", return_value=[{"zerver_stream": []}, {}, {}, {}, {}]) def test_slack_workspace_to_realm(self, mock_channels_to_zerver_stream: mock.Mock, mock_users_to_zerver_userprofile: mock.Mock) -> None: realm_id = 1 user_list = [] # type: List[Dict[str, Any]] realm, slack_user_id_to_zulip_user_id, slack_recipient_name_to_zulip_recipient_id, \ added_channels, added_mpims, dm_members, \ avatar_list, em = slack_workspace_to_realm('testdomain', realm_id, user_list, 'test-realm', './random_path', {}) test_zerver_realmdomain = [{'realm': realm_id, 'allow_subdomains': False, 'domain': 'testdomain', 'id': realm_id}] # Functioning already tests in helper functions self.assertEqual(slack_user_id_to_zulip_user_id, {}) self.assertEqual(added_channels, {}) self.assertEqual(added_mpims, {}) self.assertEqual(slack_recipient_name_to_zulip_recipient_id, {}) self.assertEqual(avatar_list, []) mock_channels_to_zerver_stream.assert_called_once_with("./random_path", 1, ANY, {}, []) passed_realm = mock_channels_to_zerver_stream.call_args_list[0][0][2] zerver_realmdomain = passed_realm['zerver_realmdomain'] self.assertListEqual(zerver_realmdomain, test_zerver_realmdomain) self.assertEqual(passed_realm['zerver_realm'][0]['description'], 'Organization imported from Slack!') self.assertEqual(passed_realm['zerver_userpresence'], []) self.assertEqual(len(passed_realm.keys()), 14) self.assertEqual(realm['zerver_stream'], []) self.assertEqual(realm['zerver_userprofile'], []) self.assertEqual(realm['zerver_realmemoji'], []) self.assertEqual(realm['zerver_customprofilefield'], []) self.assertEqual(realm['zerver_customprofilefieldvalue'], []) self.assertEqual(len(realm.keys()), 5) def test_get_message_sending_user(self) -> None: message_with_file = {'subtype': 'file', 'type': 'message', 'file': {'user': 'U064KUGRJ'}} message_without_file = {'subtype': 'file', 'type': 'messge', 'user': 'U064KUGRJ'} user_file = get_message_sending_user(message_with_file) self.assertEqual(user_file, 'U064KUGRJ') user_without_file = get_message_sending_user(message_without_file) self.assertEqual(user_without_file, 'U064KUGRJ') def test_build_zerver_message(self) -> None: zerver_usermessage = [] # type: List[Dict[str, Any]] # recipient_id -> set of user_ids subscriber_map = { 2: {3, 7, 15, 16}, # these we care about 4: {12}, 6: {19, 21}, } recipient_id = 2 mentioned_user_ids = [7] message_id = 9 um_id = NEXT_ID('user_message') build_usermessages( zerver_usermessage=zerver_usermessage, subscriber_map=subscriber_map, recipient_id=recipient_id, mentioned_user_ids=mentioned_user_ids, message_id=message_id, is_private=False, ) self.assertEqual(zerver_usermessage[0]['id'], um_id + 1) self.assertEqual(zerver_usermessage[0]['message'], message_id) self.assertEqual(zerver_usermessage[0]['flags_mask'], 1) self.assertEqual(zerver_usermessage[1]['id'], um_id + 2) self.assertEqual(zerver_usermessage[1]['message'], message_id) self.assertEqual(zerver_usermessage[1]['user_profile'], 7) self.assertEqual(zerver_usermessage[1]['flags_mask'], 9) # mentioned self.assertEqual(zerver_usermessage[2]['id'], um_id + 3) self.assertEqual(zerver_usermessage[2]['message'], message_id) self.assertEqual(zerver_usermessage[3]['id'], um_id + 4) self.assertEqual(zerver_usermessage[3]['message'], message_id) @mock.patch("zerver.data_import.slack.build_usermessages", return_value = (2, 4)) def test_channel_message_to_zerver_message(self, mock_build_usermessage: mock.Mock) -> None: user_data = [{"id": "U066MTL5U", "name": "john doe", "deleted": False, "real_name": "John"}, {"id": "U061A5N1G", "name": "jane doe", "deleted": False, "real_name": "Jane"}, {"id": "U061A1R2R", "name": "jon", "deleted": False, "real_name": "Jon"}] slack_user_id_to_zulip_user_id = {"U066MTL5U": 5, "U061A5N1G": 24, "U061A1R2R": 43} reactions = [{"name": "grinning", "users": ["U061A5N1G"], "count": 1}] all_messages = [{"text": "<@U066MTL5U> has joined the channel", "subtype": "channel_join", "user": "U066MTL5U", "ts": "1434139102.000002", "channel_name": "random"}, {"text": "<@U061A5N1G>: hey!", "user": "U061A1R2R", "ts": "1437868294.000006", "has_image": True, "channel_name": "random"}, {"text": "random", "user": "U061A5N1G", "reactions": reactions, "ts": "1439868294.000006", "channel_name": "random"}, {"text": "without a user", "user": None, # this message will be ignored as it has no user "ts": "1239868294.000006", "channel_name": "general"}, {"text": "<http://journals.plos.org/plosone/article>", "user": "U061A1R2R", "ts": "1463868370.000008", "channel_name": "general"}, {"text": "added bot", "user": "U061A5N1G", "subtype": "bot_add", "ts": "1433868549.000010", "channel_name": "general"}, # This message will be ignored since it has no user and file is None. # See #9217 for the situation; likely file uploads on archived channels {'upload': False, 'file': None, 'text': 'A file was shared', 'channel_name': 'general', 'type': 'message', 'ts': '1433868549.000011', 'subtype': 'file_share'}, {"text": "random test", "user": "U061A1R2R", "ts": "1433868669.000012", "channel_name": "general"}, {"text": "Hello everyone", "user": "U061A1R2R", "type": "message", "ts": "1433868669.000015", "mpim_name": "mpdm-user9--user2--user10-1"}, {"text": "Who is watching the World Cup", "user": "U061A5N1G", "type": "message", "ts": "1433868949.000015", "mpim_name": "mpdm-user6--user7--user4-1"}, {'client_msg_id': '998d9229-35aa-424f-8d87-99e00df27dc9', 'type': 'message', 'text': 'Who is coming for camping this weekend?', 'user': 'U061A1R2R', 'ts': '1553607595.000700', 'pm_name': 'DHX1UP7EG'}, {"client_msg_id": "998d9229-35aa-424f-8d87-99e00df27dc9", "type": "message", "text": "<@U061A5N1G>: Are you in Kochi?", "user": "U066MTL5U", "ts": "1553607595.000700", "pm_name": "DJ47BL849"}] # type: List[Dict[str, Any]] slack_recipient_name_to_zulip_recipient_id = {'random': 2, 'general': 1, 'mpdm-user9--user2--user10-1': 5, 'mpdm-user6--user7--user4-1': 6, 'U066MTL5U': 7, 'U061A5N1G': 8, 'U061A1R2R': 8} dm_members = {'DJ47BL849': ('U066MTL5U', 'U061A5N1G'), 'DHX1UP7EG': ('U061A5N1G', 'U061A1R2R')} zerver_usermessage = [] # type: List[Dict[str, Any]] subscriber_map = dict() # type: Dict[int, Set[int]] added_channels = {'random': ('c5', 1), 'general': ('c6', 2)} # type: Dict[str, Tuple[str, int]] zerver_message, zerver_usermessage, attachment, uploads, reaction = \ channel_message_to_zerver_message( 1, user_data, slack_user_id_to_zulip_user_id, slack_recipient_name_to_zulip_recipient_id, all_messages, [], subscriber_map, added_channels, dm_members, 'domain', set()) # functioning already tested in helper function self.assertEqual(zerver_usermessage, []) # subtype: channel_join is filtered self.assertEqual(len(zerver_message), 9) self.assertEqual(uploads, []) self.assertEqual(attachment, []) # Test reactions self.assertEqual(reaction[0]['user_profile'], 24) self.assertEqual(reaction[0]['emoji_name'], reactions[0]['name']) # Message conversion already tested in tests.test_slack_message_conversion self.assertEqual(zerver_message[0]['content'], '@**Jane**: hey!') self.assertEqual(zerver_message[0]['has_link'], False) self.assertEqual(zerver_message[2]['content'], 'http://journals.plos.org/plosone/article') self.assertEqual(zerver_message[2]['has_link'], True) self.assertEqual(zerver_message[5]['has_link'], False) self.assertEqual(zerver_message[7]['has_link'], False) self.assertEqual(zerver_message[3][EXPORT_TOPIC_NAME], 'imported from slack') self.assertEqual(zerver_message[3]['content'], '/me added bot') self.assertEqual(zerver_message[4]['recipient'], slack_recipient_name_to_zulip_recipient_id['general']) self.assertEqual(zerver_message[2][EXPORT_TOPIC_NAME], 'imported from slack') self.assertEqual(zerver_message[1]['recipient'], slack_recipient_name_to_zulip_recipient_id['random']) self.assertEqual(zerver_message[5]['recipient'], slack_recipient_name_to_zulip_recipient_id['mpdm-user9--user2--user10-1']) self.assertEqual(zerver_message[6]['recipient'], slack_recipient_name_to_zulip_recipient_id['mpdm-user6--user7--user4-1']) self.assertEqual(zerver_message[7]['recipient'], slack_recipient_name_to_zulip_recipient_id['U061A5N1G']) self.assertEqual(zerver_message[7]['recipient'], slack_recipient_name_to_zulip_recipient_id['U061A5N1G']) self.assertEqual(zerver_message[3]['id'], zerver_message[0]['id'] + 3) self.assertEqual(zerver_message[4]['id'], zerver_message[0]['id'] + 4) self.assertEqual(zerver_message[5]['id'], zerver_message[0]['id'] + 5) self.assertEqual(zerver_message[7]['id'], zerver_message[0]['id'] + 7) self.assertIsNone(zerver_message[3]['rendered_content']) self.assertEqual(zerver_message[0]['has_image'], False) self.assertEqual(zerver_message[0]['date_sent'], float(all_messages[1]['ts'])) self.assertEqual(zerver_message[2]['rendered_content_version'], 1) self.assertEqual(zerver_message[0]['sender'], 43) self.assertEqual(zerver_message[3]['sender'], 24) self.assertEqual(zerver_message[5]['sender'], 43) self.assertEqual(zerver_message[6]['sender'], 24) self.assertEqual(zerver_message[7]['sender'], 43) self.assertEqual(zerver_message[8]['sender'], 5) @mock.patch("zerver.data_import.slack.channel_message_to_zerver_message") @mock.patch("zerver.data_import.slack.get_messages_iterator") def test_convert_slack_workspace_messages(self, mock_get_messages_iterator: mock.Mock, mock_message: mock.Mock) -> None: output_dir = os.path.join(settings.TEST_WORKER_DIR, 'test-slack-import') os.makedirs(output_dir, exist_ok=True) added_channels = {'random': ('c5', 1), 'general': ('c6', 2)} # type: Dict[str, Tuple[str, int]] time = float(timezone_now().timestamp()) zerver_message = [{'id': 1, 'ts': time}, {'id': 5, 'ts': time}] def fake_get_messages_iter(slack_data_dir: str, added_channels: AddedChannelsT, added_mpims: AddedMPIMsT, dm_members: DMMembersT) -> Iterator[ZerverFieldsT]: import copy return iter(copy.deepcopy(zerver_message)) realm = {'zerver_subscription': []} # type: Dict[str, Any] user_list = [] # type: List[Dict[str, Any]] reactions = [{"name": "grinning", "users": ["U061A5N1G"], "count": 1}] attachments = uploads = [] # type: List[Dict[str, Any]] zerver_usermessage = [{'id': 3}, {'id': 5}, {'id': 6}, {'id': 9}] mock_get_messages_iterator.side_effect = fake_get_messages_iter mock_message.side_effect = [[zerver_message[:1], zerver_usermessage[:2], attachments, uploads, reactions[:1]], [zerver_message[1:2], zerver_usermessage[2:5], attachments, uploads, reactions[1:1]]] # Hacky: We should include a zerver_userprofile, not the empty [] test_reactions, uploads, zerver_attachment = convert_slack_workspace_messages( './random_path', user_list, 2, {}, {}, added_channels, {}, {}, realm, [], [], 'domain', output_dir=output_dir, chunk_size=1) messages_file_1 = os.path.join(output_dir, 'messages-000001.json') self.assertTrue(os.path.exists(messages_file_1)) messages_file_2 = os.path.join(output_dir, 'messages-000002.json') self.assertTrue(os.path.exists(messages_file_2)) with open(messages_file_1) as f: message_json = ujson.load(f) self.assertEqual(message_json['zerver_message'], zerver_message[:1]) self.assertEqual(message_json['zerver_usermessage'], zerver_usermessage[:2]) with open(messages_file_2) as f: message_json = ujson.load(f) self.assertEqual(message_json['zerver_message'], zerver_message[1:2]) self.assertEqual(message_json['zerver_usermessage'], zerver_usermessage[2:5]) self.assertEqual(test_reactions, reactions) @mock.patch("zerver.data_import.slack.requests.get") @mock.patch("zerver.data_import.slack.process_uploads", return_value = []) @mock.patch("zerver.data_import.slack.build_attachment", return_value = []) @mock.patch("zerver.data_import.slack.build_avatar_url") @mock.patch("zerver.data_import.slack.build_avatar") @mock.patch("zerver.data_import.slack.get_slack_api_data") def test_slack_import_to_existing_database(self, mock_get_slack_api_data: mock.Mock, mock_build_avatar_url: mock.Mock, mock_build_avatar: mock.Mock, mock_process_uploads: mock.Mock, mock_attachment: mock.Mock, mock_requests_get: mock.Mock) -> None: test_slack_dir = os.path.join(settings.DEPLOY_ROOT, "zerver", "tests", "fixtures", "slack_fixtures") test_slack_zip_file = os.path.join(test_slack_dir, "test_slack_importer.zip") test_slack_unzipped_file = os.path.join(test_slack_dir, "test_slack_importer") test_realm_subdomain = 'test-slack-import' output_dir = os.path.join(settings.DEPLOY_ROOT, "var", "test-slack-importer-data") token = 'valid-token' # If the test fails, the 'output_dir' would not be deleted and hence it would give an # error when we run the tests next time, as 'do_convert_data' expects an empty 'output_dir' # hence we remove it before running 'do_convert_data' self.rm_tree(output_dir) # Also the unzipped data file should be removed if the test fails at 'do_convert_data' self.rm_tree(test_slack_unzipped_file) user_data_fixture = ujson.loads(self.fixture_data('user_data.json', type='slack_fixtures')) team_info_fixture = ujson.loads(self.fixture_data('team_info.json', type='slack_fixtures')) mock_get_slack_api_data.side_effect = [user_data_fixture['members'], {}, team_info_fixture["team"]] mock_requests_get.return_value.raw = get_test_image_file("img.png") do_convert_data(test_slack_zip_file, output_dir, token) self.assertTrue(os.path.exists(output_dir)) self.assertTrue(os.path.exists(output_dir + '/realm.json')) realm_icons_path = os.path.join(output_dir, 'realm_icons') realm_icon_records_path = os.path.join(realm_icons_path, 'records.json') self.assertTrue(os.path.exists(realm_icon_records_path)) with open(realm_icon_records_path) as f: records = ujson.load(f) self.assertEqual(len(records), 2) self.assertEqual(records[0]["path"], "0/icon.original") self.assertTrue(os.path.exists(os.path.join(realm_icons_path, records[0]["path"]))) self.assertEqual(records[1]["path"], "0/icon.png") self.assertTrue(os.path.exists(os.path.join(realm_icons_path, records[1]["path"]))) # test import of the converted slack data into an existing database with self.settings(BILLING_ENABLED=False): do_import_realm(output_dir, test_realm_subdomain) realm = get_realm(test_realm_subdomain) self.assertTrue(realm.name, test_realm_subdomain) self.assertEqual(realm.icon_source, Realm.ICON_UPLOADED) # test RealmAuditLog realmauditlog = RealmAuditLog.objects.filter(realm=realm) realmauditlog_event_type = {log.event_type for log in realmauditlog} self.assertEqual(realmauditlog_event_type, {RealmAuditLog.SUBSCRIPTION_CREATED, RealmAuditLog.REALM_PLAN_TYPE_CHANGED}) Realm.objects.filter(name=test_realm_subdomain).delete() remove_folder(output_dir) # remove tar file created in 'do_convert_data' function os.remove(output_dir + '.tar.gz') self.assertFalse(os.path.exists(output_dir)) def test_message_files(self) -> None: alice_id = 7 alice = dict( id=alice_id, profile=dict( email='alice@example.com', ), ) files = [ dict( url_private='files.slack.com/apple.png', title='Apple', name='apple.png', mimetype='image/png', timestamp=9999, created=8888, size=3000000, ), dict( url_private='example.com/banana.zip', title='banana', ), ] message = dict( user=alice_id, files=files, ) domain_name = 'example.com' realm_id = 5 message_id = 99 slack_user_id = 'alice' users = [alice] slack_user_id_to_zulip_user_id = { 'alice': alice_id, } zerver_attachment = [] # type: List[Dict[str, Any]] uploads_list = [] # type: List[Dict[str, Any]] info = process_message_files( message=message, domain_name=domain_name, realm_id=realm_id, message_id=message_id, slack_user_id=slack_user_id, users=users, slack_user_id_to_zulip_user_id=slack_user_id_to_zulip_user_id, zerver_attachment=zerver_attachment, uploads_list=uploads_list, ) self.assertEqual(len(zerver_attachment), 1) self.assertEqual(len(uploads_list), 1) image_path = zerver_attachment[0]['path_id'] self.assertIn('/SlackImportAttachment/', image_path) expected_content = '[Apple](/user_uploads/{image_path})\n[banana](example.com/banana.zip)'.format(image_path=image_path) self.assertEqual(info['content'], expected_content) self.assertTrue(info['has_link']) self.assertTrue(info['has_image']) self.assertEqual(uploads_list[0]['s3_path'], image_path) self.assertEqual(uploads_list[0]['realm_id'], realm_id) self.assertEqual(uploads_list[0]['user_profile_email'], 'alice@example.com')
52.204976
142
0.615737
from django.conf import settings from django.utils.timezone import now as timezone_now from zerver.data_import.slack import ( get_slack_api_data, get_admin, get_guest, get_user_timezone, fetch_shared_channel_users, users_to_zerver_userprofile, get_subscription, channels_to_zerver_stream, slack_workspace_to_realm, get_message_sending_user, channel_message_to_zerver_message, convert_slack_workspace_messages, do_convert_data, process_message_files, AddedChannelsT, AddedMPIMsT, DMMembersT, ZerverFieldsT, ) from zerver.data_import.import_util import ( build_zerver_realm, build_subscription, build_recipient, build_usermessages, build_defaultstream, ) from zerver.data_import.sequencer import ( NEXT_ID, ) from zerver.lib.import_realm import ( do_import_realm, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.lib.test_helpers import ( get_test_image_file ) from zerver.lib.topic import ( EXPORT_TOPIC_NAME, ) from zerver.models import ( Realm, get_realm, RealmAuditLog, Recipient, UserProfile, ) import ujson import logging import shutil import os import mock from mock import ANY, call from typing import Any, Dict, List, Set, Tuple, Iterator def remove_folder(path: str) -> None: if os.path.exists(path): shutil.rmtree(path) def mocked_requests_get(*args: List[str], **kwargs: List[str]) -> mock.Mock: class MockResponse: def __init__(self, json_data: Dict[str, Any], status_code: int) -> None: self.json_data = json_data self.status_code = status_code def json(self) -> Dict[str, Any]: return self.json_data if args[0] == 'https://slack.com/api/users.list?token=xoxp-valid-token': return MockResponse({"ok": True, "members": "user_data"}, 200) elif args[0] == 'https://slack.com/api/users.list?token=xoxp-invalid-token': return MockResponse({"ok": False, "error": "invalid_auth"}, 200) else: return MockResponse(None, 404) class SlackImporter(ZulipTestCase): logger = logging.getLogger() logger.setLevel(logging.WARNING) @mock.patch('requests.get', side_effect=mocked_requests_get) def test_get_slack_api_data(self, mock_get: mock.Mock) -> None: token = 'xoxp-valid-token' slack_user_list_url = "https://slack.com/api/users.list" self.assertEqual(get_slack_api_data(slack_user_list_url, "members", token=token), "user_data") token = 'xoxp-invalid-token' with self.assertRaises(Exception) as invalid: get_slack_api_data(slack_user_list_url, "members", token=token) self.assertEqual(invalid.exception.args, ('Error accessing Slack API: invalid_auth',),) token = 'xoxe-invalid-token' with self.assertRaises(Exception) as invalid: get_slack_api_data(slack_user_list_url, "members", token=token) self.assertTrue(invalid.exception.args[0].startswith("Invalid Slack legacy token.\n")) with self.assertRaises(Exception) as invalid: get_slack_api_data(slack_user_list_url, "members") self.assertEqual(invalid.exception.args, ('Slack token missing in kwargs',),) token = 'xoxp-status404' wrong_url = "https://slack.com/api/wrong" with self.assertRaises(Exception) as invalid: get_slack_api_data(wrong_url, "members", token=token) self.assertEqual(invalid.exception.args, ('HTTP error accessing the Slack API.',),) def test_build_zerver_realm(self) -> None: realm_id = 2 realm_subdomain = "test-realm" time = float(timezone_now().timestamp()) test_realm = build_zerver_realm(realm_id, realm_subdomain, time, 'Slack') test_zerver_realm_dict = test_realm[0] self.assertEqual(test_zerver_realm_dict['id'], realm_id) self.assertEqual(test_zerver_realm_dict['string_id'], realm_subdomain) self.assertEqual(test_zerver_realm_dict['name'], realm_subdomain) self.assertEqual(test_zerver_realm_dict['date_created'], time) def test_get_admin(self) -> None: user_data = [{'is_admin': True, 'is_owner': False, 'is_primary_owner': False}, {'is_admin': True, 'is_owner': True, 'is_primary_owner': False}, {'is_admin': True, 'is_owner': True, 'is_primary_owner': True}, {'is_admin': False, 'is_owner': False, 'is_primary_owner': False}] self.assertEqual(get_admin(user_data[0]), True) self.assertEqual(get_admin(user_data[1]), True) self.assertEqual(get_admin(user_data[2]), True) self.assertEqual(get_admin(user_data[3]), False) def test_get_guest(self) -> None: user_data = [{'is_restricted': False, 'is_ultra_restricted': False}, {'is_restricted': True, 'is_ultra_restricted': False}, {'is_restricted': False, 'is_ultra_restricted': True}, {'is_restricted': True, 'is_ultra_restricted': True}] self.assertEqual(get_guest(user_data[0]), False) self.assertEqual(get_guest(user_data[1]), True) self.assertEqual(get_guest(user_data[2]), True) self.assertEqual(get_guest(user_data[3]), True) def test_get_timezone(self) -> None: user_chicago_timezone = {"tz": "America/Chicago"} user_timezone_none = {"tz": None} user_no_timezone = {} self.assertEqual(get_user_timezone(user_chicago_timezone), "America/Chicago") self.assertEqual(get_user_timezone(user_timezone_none), "America/New_York") self.assertEqual(get_user_timezone(user_no_timezone), "America/New_York") @mock.patch("zerver.data_import.slack.get_data_file") @mock.patch("zerver.data_import.slack.get_slack_api_data") @mock.patch("zerver.data_import.slack.get_messages_iterator") def test_fetch_shared_channel_users(self, messages_mock: mock.Mock, api_mock: mock.Mock, data_file_mock: mock.Mock) -> None: users = [{"id": "U061A1R2R"}, {"id": "U061A5N1G"}, {"id": "U064KUGRJ"}] data_file_mock.side_effect = [ [ {"name": "general", "members": ["U061A1R2R", "U061A5N1G"]}, {"name": "sharedchannel", "members": ["U061A1R2R", "U061A3E0G"]} ], [] ] api_mock.side_effect = [ {"id": "U061A3E0G", "team_id": "T6LARQE2Z"}, {"domain": "foreignteam1"}, {"id": "U061A8H1G", "team_id": "T7KJRQE8Y"}, {"domain": "foreignteam2"}, ] messages_mock.return_value = [ {"user": "U061A1R2R"}, {"user": "U061A5N1G"}, {"user": "U061A8H1G"}, ] slack_data_dir = self.fixture_file_name('', type='slack_fixtures') fetch_shared_channel_users(users, slack_data_dir, "token") self.assertEqual(len(users), 5) self.assertEqual(users[0]["id"], "U061A1R2R") self.assertEqual(users[0]["is_mirror_dummy"], False) self.assertFalse("team_domain" in users[0]) self.assertEqual(users[1]["id"], "U061A5N1G") self.assertEqual(users[2]["id"], "U064KUGRJ") self.assertEqual(users[3]["id"], "U061A3E0G") self.assertEqual(users[3]["team_domain"], "foreignteam1") self.assertEqual(users[3]["is_mirror_dummy"], True) self.assertEqual(users[4]["id"], "U061A8H1G") self.assertEqual(users[4]["team_domain"], "foreignteam2") self.assertEqual(users[4]["is_mirror_dummy"], True) api_calls = [ call("https://slack.com/api/users.info", "user", token="token", user="U061A3E0G"), call("https://slack.com/api/team.info", "team", token="token", team="T6LARQE2Z"), call("https://slack.com/api/users.info", "user", token="token", user="U061A8H1G"), call("https://slack.com/api/team.info", "team", token="token", team="T7KJRQE8Y") ] api_mock.assert_has_calls(api_calls, any_order=True) @mock.patch("zerver.data_import.slack.get_data_file") def test_users_to_zerver_userprofile(self, mock_get_data_file: mock.Mock) -> None: custom_profile_field_user1 = {"Xf06054BBB": {"value": "random1"}, "Xf023DSCdd": {"value": "employee"}} custom_profile_field_user2 = {"Xf06054BBB": {"value": "random2"}, "Xf023DSCdd": {"value": "employer"}} user_data = [{"id": "U08RGD1RD", "team_id": "T5YFFM2QY", "name": "john", "deleted": False, "is_mirror_dummy": False, "real_name": "John Doe", "profile": {"image_32": "", "email": "jon@gmail.com", "avatar_hash": "hash", "phone": "+1-123-456-77-868", "fields": custom_profile_field_user1}}, {"id": "U0CBK5KAT", "team_id": "T5YFFM2QY", "is_admin": True, "is_bot": False, "is_owner": True, "is_primary_owner": True, 'name': 'Jane', "real_name": "Jane Doe", "deleted": False, "is_mirror_dummy": False, "profile": {"image_32": "https://secure.gravatar.com/avatar/random.png", "fields": custom_profile_field_user2, "email": "jane@foo.com", "avatar_hash": "hash"}}, {"id": "U09TYF5Sk", "team_id": "T5YFFM2QY", "name": "Bot", "real_name": "Bot", "is_bot": True, "deleted": False, "is_mirror_dummy": False, "profile": {"image_32": "https://secure.gravatar.com/avatar/random1.png", "skype": "test_skype_name", "email": "bot1@zulipchat.com", "avatar_hash": "hash"}}, {"id": "UHSG7OPQN", "team_id": "T6LARQE2Z", 'name': 'matt.perry', "color": '9d8eee', "is_bot": False, "is_app_user": False, "is_mirror_dummy": True, "team_domain": "foreignteam", "profile": {"image_32": "https://secure.gravatar.com/avatar/random6.png", "avatar_hash": "hash", "first_name": "Matt", "last_name": "Perry", "real_name": "Matt Perry", "display_name": "matt.perry", "team": "T6LARQE2Z"}}, {"id": "U8VAHEVUY", "team_id": "T5YFFM2QY", "name": "steviejacob34", "real_name": "Steve Jacob", "is_admin": False, "is_owner": False, "is_primary_owner": False, "is_restricted": True, "is_ultra_restricted": False, "is_bot": False, "is_mirror_dummy": False, "profile": {"email": "steviejacob34@yahoo.com", "avatar_hash": "hash", "image_32": "https://secure.gravatar.com/avatar/random6.png"}}, {"id": "U8X25EBAB", "team_id": "T5YFFM2QY", "name": "pratikweb_0", "real_name": "Pratik", "is_admin": False, "is_owner": False, "is_primary_owner": False, "is_restricted": True, "is_ultra_restricted": True, "is_bot": False, "is_mirror_dummy": False, "profile": {"email": "pratik@mit.edu", "avatar_hash": "hash", "image_32": "https://secure.gravatar.com/avatar/random.png"}}] mock_get_data_file.return_value = user_data test_slack_user_id_to_zulip_user_id = {'U08RGD1RD': 1, 'U0CBK5KAT': 0, 'U09TYF5Sk': 2, 'UHSG7OPQN': 3, 'U8VAHEVUY': 4, 'U8X25EBAB': 5} slack_data_dir = './random_path' timestamp = int(timezone_now().timestamp()) mock_get_data_file.return_value = user_data zerver_userprofile, avatar_list, slack_user_id_to_zulip_user_id, customprofilefield, \ customprofilefield_value = users_to_zerver_userprofile(slack_data_dir, user_data, 1, timestamp, 'test_domain') self.assertEqual(customprofilefield[0]['field_type'], 1) self.assertEqual(customprofilefield[3]['name'], 'skype') cpf_name = {cpf['name'] for cpf in customprofilefield} self.assertIn('phone', cpf_name) self.assertIn('skype', cpf_name) cpf_name.remove('phone') cpf_name.remove('skype') for name in cpf_name: self.assertTrue(name.startswith('slack custom field ')) self.assertEqual(len(customprofilefield_value), 6) self.assertEqual(customprofilefield_value[0]['field'], 0) self.assertEqual(customprofilefield_value[0]['user_profile'], 1) self.assertEqual(customprofilefield_value[3]['user_profile'], 0) self.assertEqual(customprofilefield_value[5]['value'], 'test_skype_name') self.assertDictEqual(slack_user_id_to_zulip_user_id, test_slack_user_id_to_zulip_user_id) self.assertEqual(len(avatar_list), 6) self.assertEqual(len(zerver_userprofile), 6) self.assertEqual(zerver_userprofile[0]['is_staff'], False) self.assertEqual(zerver_userprofile[0]['is_bot'], False) self.assertEqual(zerver_userprofile[0]['is_active'], True) self.assertEqual(zerver_userprofile[0]['is_mirror_dummy'], False) self.assertEqual(zerver_userprofile[0]['role'], UserProfile.ROLE_MEMBER) self.assertEqual(zerver_userprofile[0]['enable_desktop_notifications'], True) self.assertEqual(zerver_userprofile[0]['email'], 'jon@gmail.com') self.assertEqual(zerver_userprofile[0]['full_name'], 'John Doe') self.assertEqual(zerver_userprofile[1]['id'], test_slack_user_id_to_zulip_user_id['U0CBK5KAT']) self.assertEqual(zerver_userprofile[1]['role'], UserProfile.ROLE_REALM_ADMINISTRATOR) self.assertEqual(zerver_userprofile[1]['is_staff'], False) self.assertEqual(zerver_userprofile[1]['is_active'], True) self.assertEqual(zerver_userprofile[0]['is_mirror_dummy'], False) self.assertEqual(zerver_userprofile[2]['id'], test_slack_user_id_to_zulip_user_id['U09TYF5Sk']) self.assertEqual(zerver_userprofile[2]['is_bot'], True) self.assertEqual(zerver_userprofile[2]['is_active'], True) self.assertEqual(zerver_userprofile[2]['is_mirror_dummy'], False) self.assertEqual(zerver_userprofile[2]['email'], 'bot1@zulipchat.com') self.assertEqual(zerver_userprofile[2]['bot_type'], 1) self.assertEqual(zerver_userprofile[2]['avatar_source'], 'U') self.assertEqual(zerver_userprofile[3]['id'], test_slack_user_id_to_zulip_user_id['UHSG7OPQN']) self.assertEqual(zerver_userprofile[3]['role'], UserProfile.ROLE_MEMBER) self.assertEqual(zerver_userprofile[3]['is_staff'], False) self.assertEqual(zerver_userprofile[3]['is_active'], False) self.assertEqual(zerver_userprofile[3]['email'], 'matt.perry@foreignteam.slack.com') self.assertEqual(zerver_userprofile[3]['realm'], 1) self.assertEqual(zerver_userprofile[3]['full_name'], 'Matt Perry') self.assertEqual(zerver_userprofile[3]['short_name'], 'matt.perry') self.assertEqual(zerver_userprofile[3]['is_mirror_dummy'], True) self.assertEqual(zerver_userprofile[3]['is_api_super_user'], False) self.assertEqual(zerver_userprofile[4]['id'], test_slack_user_id_to_zulip_user_id['U8VAHEVUY']) self.assertEqual(zerver_userprofile[4]['role'], UserProfile.ROLE_GUEST) self.assertEqual(zerver_userprofile[4]['is_staff'], False) self.assertEqual(zerver_userprofile[4]['is_active'], True) self.assertEqual(zerver_userprofile[4]['is_mirror_dummy'], False) self.assertEqual(zerver_userprofile[5]['id'], test_slack_user_id_to_zulip_user_id['U8X25EBAB']) self.assertEqual(zerver_userprofile[5]['role'], UserProfile.ROLE_GUEST) self.assertEqual(zerver_userprofile[5]['is_staff'], False) self.assertEqual(zerver_userprofile[5]['is_active'], True) self.assertEqual(zerver_userprofile[5]['is_mirror_dummy'], False) def test_build_defaultstream(self) -> None: realm_id = 1 stream_id = 1 default_channel_general = build_defaultstream(realm_id, stream_id, 1) test_default_channel = {'stream': 1, 'realm': 1, 'id': 1} self.assertDictEqual(test_default_channel, default_channel_general) default_channel_general = build_defaultstream(realm_id, stream_id, 1) test_default_channel = {'stream': 1, 'realm': 1, 'id': 1} self.assertDictEqual(test_default_channel, default_channel_general) def test_build_pm_recipient_sub_from_user(self) -> None: zulip_user_id = 3 recipient_id = 5 subscription_id = 7 sub = build_subscription(recipient_id, zulip_user_id, subscription_id) recipient = build_recipient(zulip_user_id, recipient_id, Recipient.PERSONAL) self.assertEqual(recipient['id'], sub['recipient']) self.assertEqual(recipient['type_id'], sub['user_profile']) self.assertEqual(recipient['type'], Recipient.PERSONAL) self.assertEqual(recipient['type_id'], 3) self.assertEqual(sub['recipient'], 5) self.assertEqual(sub['id'], 7) self.assertEqual(sub['active'], True) def test_build_subscription(self) -> None: channel_members = ["U061A1R2R", "U061A3E0G", "U061A5N1G", "U064KUGRJ"] slack_user_id_to_zulip_user_id = {"U061A1R2R": 1, "U061A3E0G": 8, "U061A5N1G": 7, "U064KUGRJ": 5} subscription_id_count = 0 recipient_id = 12 zerver_subscription = [] final_subscription_id = get_subscription(channel_members, zerver_subscription, recipient_id, slack_user_id_to_zulip_user_id, subscription_id_count) self.assertEqual(final_subscription_id, 4) self.assertEqual(zerver_subscription[0]['recipient'], 12) self.assertEqual(zerver_subscription[0]['id'], 0) self.assertEqual(zerver_subscription[0]['user_profile'], slack_user_id_to_zulip_user_id[channel_members[0]]) self.assertEqual(zerver_subscription[2]['user_profile'], slack_user_id_to_zulip_user_id[channel_members[2]]) self.assertEqual(zerver_subscription[3]['id'], 3) self.assertEqual(zerver_subscription[1]['recipient'], zerver_subscription[3]['recipient']) self.assertEqual(zerver_subscription[1]['pin_to_top'], False) def test_channels_to_zerver_stream(self) -> None: slack_user_id_to_zulip_user_id = {"U061A1R2R": 1, "U061A3E0G": 8, "U061A5N1G": 7, "U064KUGRJ": 5} zerver_userprofile = [{'id': 1}, {'id': 8}, {'id': 7}, {'id': 5}] realm_id = 3 realm, added_channels, added_mpims, dm_members, slack_recipient_name_to_zulip_recipient_id = \ channels_to_zerver_stream(self.fixture_file_name("", "slack_fixtures"), realm_id, {"zerver_userpresence": []}, slack_user_id_to_zulip_user_id, zerver_userprofile) test_added_channels = {'sharedchannel': ("C061A0HJG", 3), 'general': ("C061A0YJG", 1), 'general1': ("C061A0YJP", 2), 'random': ("C061A0WJG", 0)} test_added_mpims = {'mpdm-user9--user2--user10-1': ('G9HBG2A5D', 0), 'mpdm-user6--user7--user4-1': ('G6H1Z0ZPS', 1), 'mpdm-user4--user1--user5-1': ('G6N944JPL', 2)} test_dm_members = {'DJ47BL849': ('U061A1R2R', 'U061A5N1G'), 'DHX1UP7EG': ('U061A5N1G', 'U064KUGRJ'), 'DK8HSJDHS': ('U061A1R2R', 'U064KUGRJ'), 'DRS3PSLDK': ('U064KUGRJ', 'U064KUGRJ')} slack_recipient_names = set(slack_user_id_to_zulip_user_id.keys()) | set(test_added_channels.keys()) \ | set(test_added_mpims.keys()) self.assertDictEqual(test_added_channels, added_channels) self.assertEqual(realm["zerver_defaultstream"], [{'id': 0, 'realm': 3, 'stream': 0}, {'id': 1, 'realm': 3, 'stream': 1}]) self.assertDictEqual(test_added_mpims, added_mpims) self.assertDictEqual(test_dm_members, dm_members) # recipients, slack_user_id_to_zulip_user_id are iterated in diffrent order in Python 3.5 and 3.6. self.assertEqual(set(slack_recipient_name_to_zulip_recipient_id.keys()), slack_recipient_names) self.assertEqual(set(slack_recipient_name_to_zulip_recipient_id.values()), set(i for i in range(11))) # functioning of zerver subscriptions are already tested in the helper functions # This is to check the concatenation of the output lists from the helper functions # subscriptions for stream zerver_subscription = realm["zerver_subscription"] zerver_recipient = realm["zerver_recipient"] zerver_stream = realm["zerver_stream"] self.assertEqual(self.get_set(zerver_subscription, "recipient"), {i for i in range(11)}) self.assertEqual(self.get_set(zerver_subscription, "user_profile"), {1, 5, 7, 8}) self.assertEqual(self.get_set(zerver_recipient, "id"), self.get_set(zerver_subscription, "recipient")) self.assertEqual(self.get_set(zerver_recipient, "type_id"), {0, 1, 2, 3, 5, 7, 8}) self.assertEqual(self.get_set(zerver_recipient, "type"), {1, 2, 3}) # stream mapping self.assertEqual(zerver_stream[0]['name'], "random") self.assertEqual(zerver_stream[0]['deactivated'], True) self.assertEqual(zerver_stream[0]['description'], 'no purpose') self.assertEqual(zerver_stream[0]['invite_only'], False) self.assertEqual(zerver_stream[0]['realm'], realm_id) self.assertEqual(zerver_stream[2]['id'], test_added_channels[zerver_stream[2]['name']][1]) self.assertEqual(self.get_set(realm["zerver_huddle"], "id"), {0, 1, 2}) self.assertEqual(realm["zerver_userpresence"], []) @mock.patch("zerver.data_import.slack.users_to_zerver_userprofile", return_value=[[], [], {}, [], []]) @mock.patch("zerver.data_import.slack.channels_to_zerver_stream", return_value=[{"zerver_stream": []}, {}, {}, {}, {}]) def test_slack_workspace_to_realm(self, mock_channels_to_zerver_stream: mock.Mock, mock_users_to_zerver_userprofile: mock.Mock) -> None: realm_id = 1 user_list = [] # type: List[Dict[str, Any]] realm, slack_user_id_to_zulip_user_id, slack_recipient_name_to_zulip_recipient_id, \ added_channels, added_mpims, dm_members, \ avatar_list, em = slack_workspace_to_realm('testdomain', realm_id, user_list, 'test-realm', './random_path', {}) test_zerver_realmdomain = [{'realm': realm_id, 'allow_subdomains': False, 'domain': 'testdomain', 'id': realm_id}] # Functioning already tests in helper functions self.assertEqual(slack_user_id_to_zulip_user_id, {}) self.assertEqual(added_channels, {}) self.assertEqual(added_mpims, {}) self.assertEqual(slack_recipient_name_to_zulip_recipient_id, {}) self.assertEqual(avatar_list, []) mock_channels_to_zerver_stream.assert_called_once_with("./random_path", 1, ANY, {}, []) passed_realm = mock_channels_to_zerver_stream.call_args_list[0][0][2] zerver_realmdomain = passed_realm['zerver_realmdomain'] self.assertListEqual(zerver_realmdomain, test_zerver_realmdomain) self.assertEqual(passed_realm['zerver_realm'][0]['description'], 'Organization imported from Slack!') self.assertEqual(passed_realm['zerver_userpresence'], []) self.assertEqual(len(passed_realm.keys()), 14) self.assertEqual(realm['zerver_stream'], []) self.assertEqual(realm['zerver_userprofile'], []) self.assertEqual(realm['zerver_realmemoji'], []) self.assertEqual(realm['zerver_customprofilefield'], []) self.assertEqual(realm['zerver_customprofilefieldvalue'], []) self.assertEqual(len(realm.keys()), 5) def test_get_message_sending_user(self) -> None: message_with_file = {'subtype': 'file', 'type': 'message', 'file': {'user': 'U064KUGRJ'}} message_without_file = {'subtype': 'file', 'type': 'messge', 'user': 'U064KUGRJ'} user_file = get_message_sending_user(message_with_file) self.assertEqual(user_file, 'U064KUGRJ') user_without_file = get_message_sending_user(message_without_file) self.assertEqual(user_without_file, 'U064KUGRJ') def test_build_zerver_message(self) -> None: zerver_usermessage = [] # type: List[Dict[str, Any]] # recipient_id -> set of user_ids subscriber_map = { 2: {3, 7, 15, 16}, # these we care about 4: {12}, 6: {19, 21}, } recipient_id = 2 mentioned_user_ids = [7] message_id = 9 um_id = NEXT_ID('user_message') build_usermessages( zerver_usermessage=zerver_usermessage, subscriber_map=subscriber_map, recipient_id=recipient_id, mentioned_user_ids=mentioned_user_ids, message_id=message_id, is_private=False, ) self.assertEqual(zerver_usermessage[0]['id'], um_id + 1) self.assertEqual(zerver_usermessage[0]['message'], message_id) self.assertEqual(zerver_usermessage[0]['flags_mask'], 1) self.assertEqual(zerver_usermessage[1]['id'], um_id + 2) self.assertEqual(zerver_usermessage[1]['message'], message_id) self.assertEqual(zerver_usermessage[1]['user_profile'], 7) self.assertEqual(zerver_usermessage[1]['flags_mask'], 9) # mentioned self.assertEqual(zerver_usermessage[2]['id'], um_id + 3) self.assertEqual(zerver_usermessage[2]['message'], message_id) self.assertEqual(zerver_usermessage[3]['id'], um_id + 4) self.assertEqual(zerver_usermessage[3]['message'], message_id) @mock.patch("zerver.data_import.slack.build_usermessages", return_value = (2, 4)) def test_channel_message_to_zerver_message(self, mock_build_usermessage: mock.Mock) -> None: user_data = [{"id": "U066MTL5U", "name": "john doe", "deleted": False, "real_name": "John"}, {"id": "U061A5N1G", "name": "jane doe", "deleted": False, "real_name": "Jane"}, {"id": "U061A1R2R", "name": "jon", "deleted": False, "real_name": "Jon"}] slack_user_id_to_zulip_user_id = {"U066MTL5U": 5, "U061A5N1G": 24, "U061A1R2R": 43} reactions = [{"name": "grinning", "users": ["U061A5N1G"], "count": 1}] all_messages = [{"text": "<@U066MTL5U> has joined the channel", "subtype": "channel_join", "user": "U066MTL5U", "ts": "1434139102.000002", "channel_name": "random"}, {"text": "<@U061A5N1G>: hey!", "user": "U061A1R2R", "ts": "1437868294.000006", "has_image": True, "channel_name": "random"}, {"text": "random", "user": "U061A5N1G", "reactions": reactions, "ts": "1439868294.000006", "channel_name": "random"}, {"text": "without a user", "user": None, # this message will be ignored as it has no user "ts": "1239868294.000006", "channel_name": "general"}, {"text": "<http://journals.plos.org/plosone/article>", "user": "U061A1R2R", "ts": "1463868370.000008", "channel_name": "general"}, {"text": "added bot", "user": "U061A5N1G", "subtype": "bot_add", "ts": "1433868549.000010", "channel_name": "general"}, # This message will be ignored since it has no user and file is None. # See #9217 for the situation; likely file uploads on archived channels {'upload': False, 'file': None, 'text': 'A file was shared', 'channel_name': 'general', 'type': 'message', 'ts': '1433868549.000011', 'subtype': 'file_share'}, {"text": "random test", "user": "U061A1R2R", "ts": "1433868669.000012", "channel_name": "general"}, {"text": "Hello everyone", "user": "U061A1R2R", "type": "message", "ts": "1433868669.000015", "mpim_name": "mpdm-user9--user2--user10-1"}, {"text": "Who is watching the World Cup", "user": "U061A5N1G", "type": "message", "ts": "1433868949.000015", "mpim_name": "mpdm-user6--user7--user4-1"}, {'client_msg_id': '998d9229-35aa-424f-8d87-99e00df27dc9', 'type': 'message', 'text': 'Who is coming for camping this weekend?', 'user': 'U061A1R2R', 'ts': '1553607595.000700', 'pm_name': 'DHX1UP7EG'}, {"client_msg_id": "998d9229-35aa-424f-8d87-99e00df27dc9", "type": "message", "text": "<@U061A5N1G>: Are you in Kochi?", "user": "U066MTL5U", "ts": "1553607595.000700", "pm_name": "DJ47BL849"}] # type: List[Dict[str, Any]] slack_recipient_name_to_zulip_recipient_id = {'random': 2, 'general': 1, 'mpdm-user9--user2--user10-1': 5, 'mpdm-user6--user7--user4-1': 6, 'U066MTL5U': 7, 'U061A5N1G': 8, 'U061A1R2R': 8} dm_members = {'DJ47BL849': ('U066MTL5U', 'U061A5N1G'), 'DHX1UP7EG': ('U061A5N1G', 'U061A1R2R')} zerver_usermessage = [] # type: List[Dict[str, Any]] subscriber_map = dict() # type: Dict[int, Set[int]] added_channels = {'random': ('c5', 1), 'general': ('c6', 2)} # type: Dict[str, Tuple[str, int]] zerver_message, zerver_usermessage, attachment, uploads, reaction = \ channel_message_to_zerver_message( 1, user_data, slack_user_id_to_zulip_user_id, slack_recipient_name_to_zulip_recipient_id, all_messages, [], subscriber_map, added_channels, dm_members, 'domain', set()) # functioning already tested in helper function self.assertEqual(zerver_usermessage, []) # subtype: channel_join is filtered self.assertEqual(len(zerver_message), 9) self.assertEqual(uploads, []) self.assertEqual(attachment, []) # Test reactions self.assertEqual(reaction[0]['user_profile'], 24) self.assertEqual(reaction[0]['emoji_name'], reactions[0]['name']) # Message conversion already tested in tests.test_slack_message_conversion self.assertEqual(zerver_message[0]['content'], '@**Jane**: hey!') self.assertEqual(zerver_message[0]['has_link'], False) self.assertEqual(zerver_message[2]['content'], 'http://journals.plos.org/plosone/article') self.assertEqual(zerver_message[2]['has_link'], True) self.assertEqual(zerver_message[5]['has_link'], False) self.assertEqual(zerver_message[7]['has_link'], False) self.assertEqual(zerver_message[3][EXPORT_TOPIC_NAME], 'imported from slack') self.assertEqual(zerver_message[3]['content'], '/me added bot') self.assertEqual(zerver_message[4]['recipient'], slack_recipient_name_to_zulip_recipient_id['general']) self.assertEqual(zerver_message[2][EXPORT_TOPIC_NAME], 'imported from slack') self.assertEqual(zerver_message[1]['recipient'], slack_recipient_name_to_zulip_recipient_id['random']) self.assertEqual(zerver_message[5]['recipient'], slack_recipient_name_to_zulip_recipient_id['mpdm-user9--user2--user10-1']) self.assertEqual(zerver_message[6]['recipient'], slack_recipient_name_to_zulip_recipient_id['mpdm-user6--user7--user4-1']) self.assertEqual(zerver_message[7]['recipient'], slack_recipient_name_to_zulip_recipient_id['U061A5N1G']) self.assertEqual(zerver_message[7]['recipient'], slack_recipient_name_to_zulip_recipient_id['U061A5N1G']) self.assertEqual(zerver_message[3]['id'], zerver_message[0]['id'] + 3) self.assertEqual(zerver_message[4]['id'], zerver_message[0]['id'] + 4) self.assertEqual(zerver_message[5]['id'], zerver_message[0]['id'] + 5) self.assertEqual(zerver_message[7]['id'], zerver_message[0]['id'] + 7) self.assertIsNone(zerver_message[3]['rendered_content']) self.assertEqual(zerver_message[0]['has_image'], False) self.assertEqual(zerver_message[0]['date_sent'], float(all_messages[1]['ts'])) self.assertEqual(zerver_message[2]['rendered_content_version'], 1) self.assertEqual(zerver_message[0]['sender'], 43) self.assertEqual(zerver_message[3]['sender'], 24) self.assertEqual(zerver_message[5]['sender'], 43) self.assertEqual(zerver_message[6]['sender'], 24) self.assertEqual(zerver_message[7]['sender'], 43) self.assertEqual(zerver_message[8]['sender'], 5) @mock.patch("zerver.data_import.slack.channel_message_to_zerver_message") @mock.patch("zerver.data_import.slack.get_messages_iterator") def test_convert_slack_workspace_messages(self, mock_get_messages_iterator: mock.Mock, mock_message: mock.Mock) -> None: output_dir = os.path.join(settings.TEST_WORKER_DIR, 'test-slack-import') os.makedirs(output_dir, exist_ok=True) added_channels = {'random': ('c5', 1), 'general': ('c6', 2)} # type: Dict[str, Tuple[str, int]] time = float(timezone_now().timestamp()) zerver_message = [{'id': 1, 'ts': time}, {'id': 5, 'ts': time}] def fake_get_messages_iter(slack_data_dir: str, added_channels: AddedChannelsT, added_mpims: AddedMPIMsT, dm_members: DMMembersT) -> Iterator[ZerverFieldsT]: import copy return iter(copy.deepcopy(zerver_message)) realm = {'zerver_subscription': []} # type: Dict[str, Any] user_list = [] # type: List[Dict[str, Any]] reactions = [{"name": "grinning", "users": ["U061A5N1G"], "count": 1}] attachments = uploads = [] # type: List[Dict[str, Any]] zerver_usermessage = [{'id': 3}, {'id': 5}, {'id': 6}, {'id': 9}] mock_get_messages_iterator.side_effect = fake_get_messages_iter mock_message.side_effect = [[zerver_message[:1], zerver_usermessage[:2], attachments, uploads, reactions[:1]], [zerver_message[1:2], zerver_usermessage[2:5], attachments, uploads, reactions[1:1]]] # Hacky: We should include a zerver_userprofile, not the empty [] test_reactions, uploads, zerver_attachment = convert_slack_workspace_messages( './random_path', user_list, 2, {}, {}, added_channels, {}, {}, realm, [], [], 'domain', output_dir=output_dir, chunk_size=1) messages_file_1 = os.path.join(output_dir, 'messages-000001.json') self.assertTrue(os.path.exists(messages_file_1)) messages_file_2 = os.path.join(output_dir, 'messages-000002.json') self.assertTrue(os.path.exists(messages_file_2)) with open(messages_file_1) as f: message_json = ujson.load(f) self.assertEqual(message_json['zerver_message'], zerver_message[:1]) self.assertEqual(message_json['zerver_usermessage'], zerver_usermessage[:2]) with open(messages_file_2) as f: message_json = ujson.load(f) self.assertEqual(message_json['zerver_message'], zerver_message[1:2]) self.assertEqual(message_json['zerver_usermessage'], zerver_usermessage[2:5]) self.assertEqual(test_reactions, reactions) @mock.patch("zerver.data_import.slack.requests.get") @mock.patch("zerver.data_import.slack.process_uploads", return_value = []) @mock.patch("zerver.data_import.slack.build_attachment", return_value = []) @mock.patch("zerver.data_import.slack.build_avatar_url") @mock.patch("zerver.data_import.slack.build_avatar") @mock.patch("zerver.data_import.slack.get_slack_api_data") def test_slack_import_to_existing_database(self, mock_get_slack_api_data: mock.Mock, mock_build_avatar_url: mock.Mock, mock_build_avatar: mock.Mock, mock_process_uploads: mock.Mock, mock_attachment: mock.Mock, mock_requests_get: mock.Mock) -> None: test_slack_dir = os.path.join(settings.DEPLOY_ROOT, "zerver", "tests", "fixtures", "slack_fixtures") test_slack_zip_file = os.path.join(test_slack_dir, "test_slack_importer.zip") test_slack_unzipped_file = os.path.join(test_slack_dir, "test_slack_importer") test_realm_subdomain = 'test-slack-import' output_dir = os.path.join(settings.DEPLOY_ROOT, "var", "test-slack-importer-data") token = 'valid-token' # If the test fails, the 'output_dir' would not be deleted and hence it would give an # error when we run the tests next time, as 'do_convert_data' expects an empty 'output_dir' # hence we remove it before running 'do_convert_data' self.rm_tree(output_dir) # Also the unzipped data file should be removed if the test fails at 'do_convert_data' self.rm_tree(test_slack_unzipped_file) user_data_fixture = ujson.loads(self.fixture_data('user_data.json', type='slack_fixtures')) team_info_fixture = ujson.loads(self.fixture_data('team_info.json', type='slack_fixtures')) mock_get_slack_api_data.side_effect = [user_data_fixture['members'], {}, team_info_fixture["team"]] mock_requests_get.return_value.raw = get_test_image_file("img.png") do_convert_data(test_slack_zip_file, output_dir, token) self.assertTrue(os.path.exists(output_dir)) self.assertTrue(os.path.exists(output_dir + '/realm.json')) realm_icons_path = os.path.join(output_dir, 'realm_icons') realm_icon_records_path = os.path.join(realm_icons_path, 'records.json') self.assertTrue(os.path.exists(realm_icon_records_path)) with open(realm_icon_records_path) as f: records = ujson.load(f) self.assertEqual(len(records), 2) self.assertEqual(records[0]["path"], "0/icon.original") self.assertTrue(os.path.exists(os.path.join(realm_icons_path, records[0]["path"]))) self.assertEqual(records[1]["path"], "0/icon.png") self.assertTrue(os.path.exists(os.path.join(realm_icons_path, records[1]["path"]))) # test import of the converted slack data into an existing database with self.settings(BILLING_ENABLED=False): do_import_realm(output_dir, test_realm_subdomain) realm = get_realm(test_realm_subdomain) self.assertTrue(realm.name, test_realm_subdomain) self.assertEqual(realm.icon_source, Realm.ICON_UPLOADED) # test RealmAuditLog realmauditlog = RealmAuditLog.objects.filter(realm=realm) realmauditlog_event_type = {log.event_type for log in realmauditlog} self.assertEqual(realmauditlog_event_type, {RealmAuditLog.SUBSCRIPTION_CREATED, RealmAuditLog.REALM_PLAN_TYPE_CHANGED}) Realm.objects.filter(name=test_realm_subdomain).delete() remove_folder(output_dir) # remove tar file created in 'do_convert_data' function os.remove(output_dir + '.tar.gz') self.assertFalse(os.path.exists(output_dir)) def test_message_files(self) -> None: alice_id = 7 alice = dict( id=alice_id, profile=dict( email='alice@example.com', ), ) files = [ dict( url_private='files.slack.com/apple.png', title='Apple', name='apple.png', mimetype='image/png', timestamp=9999, created=8888, size=3000000, ), dict( url_private='example.com/banana.zip', title='banana', ), ] message = dict( user=alice_id, files=files, ) domain_name = 'example.com' realm_id = 5 message_id = 99 slack_user_id = 'alice' users = [alice] slack_user_id_to_zulip_user_id = { 'alice': alice_id, } zerver_attachment = [] # type: List[Dict[str, Any]] uploads_list = [] # type: List[Dict[str, Any]] info = process_message_files( message=message, domain_name=domain_name, realm_id=realm_id, message_id=message_id, slack_user_id=slack_user_id, users=users, slack_user_id_to_zulip_user_id=slack_user_id_to_zulip_user_id, zerver_attachment=zerver_attachment, uploads_list=uploads_list, ) self.assertEqual(len(zerver_attachment), 1) self.assertEqual(len(uploads_list), 1) image_path = zerver_attachment[0]['path_id'] self.assertIn('/SlackImportAttachment/', image_path) expected_content = '[Apple](/user_uploads/{image_path})\n[banana](example.com/banana.zip)'.format(image_path=image_path) self.assertEqual(info['content'], expected_content) self.assertTrue(info['has_link']) self.assertTrue(info['has_image']) self.assertEqual(uploads_list[0]['s3_path'], image_path) self.assertEqual(uploads_list[0]['realm_id'], realm_id) self.assertEqual(uploads_list[0]['user_profile_email'], 'alice@example.com')
true
true
f714ab74caa7e9e880df60f9b2934a8d8fa7d891
682
py
Python
mfr_rst/tests/test_rst.py
erinspace/modular-file-renderer
acbc1ea188173832dd9d0e037b55653557a04704
[ "Apache-2.0" ]
null
null
null
mfr_rst/tests/test_rst.py
erinspace/modular-file-renderer
acbc1ea188173832dd9d0e037b55653557a04704
[ "Apache-2.0" ]
null
null
null
mfr_rst/tests/test_rst.py
erinspace/modular-file-renderer
acbc1ea188173832dd9d0e037b55653557a04704
[ "Apache-2.0" ]
null
null
null
import pytest import mfr import mfr_rst def test_detect(fakefile): # set filename to have .rst extension fakefile.name = 'mydoc.rst' handler = mfr_rst.Handler() assert handler.detect(fakefile) is True @pytest.mark.parametrize('filename', [ 'other.rs', 'otherrst', 'other', 'other.', ]) def test_does_not_detect_other_extensions(fakefile, filename): fakefile.name = filename handler = mfr_rst.Handler() assert handler.detect(fakefile) is False def test_render_rst_returns_render_result(): with open('mfr_rst/tests/test.rst') as fp: result = mfr_rst.render.render_rst(fp) assert type(result) == mfr.core.RenderResult
22.733333
62
0.705279
import pytest import mfr import mfr_rst def test_detect(fakefile): fakefile.name = 'mydoc.rst' handler = mfr_rst.Handler() assert handler.detect(fakefile) is True @pytest.mark.parametrize('filename', [ 'other.rs', 'otherrst', 'other', 'other.', ]) def test_does_not_detect_other_extensions(fakefile, filename): fakefile.name = filename handler = mfr_rst.Handler() assert handler.detect(fakefile) is False def test_render_rst_returns_render_result(): with open('mfr_rst/tests/test.rst') as fp: result = mfr_rst.render.render_rst(fp) assert type(result) == mfr.core.RenderResult
true
true
f714aba34194863f081881943a6ccb4ee1151632
1,252
py
Python
pyfronius/tests/web_raw/v0/web_state.py
mgrela/pyfronius
0ed5b0d4032870292576336b66922360a1fcd4a2
[ "MIT" ]
null
null
null
pyfronius/tests/web_raw/v0/web_state.py
mgrela/pyfronius
0ed5b0d4032870292576336b66922360a1fcd4a2
[ "MIT" ]
null
null
null
pyfronius/tests/web_raw/v0/web_state.py
mgrela/pyfronius
0ed5b0d4032870292576336b66922360a1fcd4a2
[ "MIT" ]
null
null
null
GET_INVERTER_REALTIME_DATA_SCOPE_DEVICE = { "timestamp": {"value": "2020-09-18T14:14:24-07:00"}, "status": {"Code": 0, "Reason": "", "UserMessage": ""}, "energy_day": {"value": 6000, "unit": "Wh"}, "energy_total": {"value": 35611000, "unit": "Wh"}, "energy_year": {"value": 3310000, "unit": "Wh"}, "frequency_ac": {"value": 60, "unit": "Hz"}, "current_ac": {"value": 7.31, "unit": "A"}, "current_dc": {"value": 6.54, "unit": "A"}, "power_ac": {"value": 1762, "unit": "W"}, "voltage_ac": {"value": 241, "unit": "V"}, "voltage_dc": {"value": 286, "unit": "V"}, } GET_INVERTER_REALTIME_DATA_SYSTEM = { "timestamp": {"value": "2020-09-18T14:13:49-07:00"}, "status": {"Code": 0, "Reason": "", "UserMessage": ""}, "energy_day": {"value": 6000, "unit": "Wh"}, "energy_total": {"value": 35611000, "unit": "Wh"}, "energy_year": {"value": 3310000, "unit": "Wh"}, "power_ac": {"value": 1764, "unit": "W"}, "inverters": { "1": { "energy_day": {"value": 6000, "unit": "Wh"}, "energy_total": {"value": 35611000, "unit": "Wh"}, "energy_year": {"value": 3310000, "unit": "Wh"}, "power_ac": {"value": 1764, "unit": "W"}, } }, }
40.387097
62
0.51278
GET_INVERTER_REALTIME_DATA_SCOPE_DEVICE = { "timestamp": {"value": "2020-09-18T14:14:24-07:00"}, "status": {"Code": 0, "Reason": "", "UserMessage": ""}, "energy_day": {"value": 6000, "unit": "Wh"}, "energy_total": {"value": 35611000, "unit": "Wh"}, "energy_year": {"value": 3310000, "unit": "Wh"}, "frequency_ac": {"value": 60, "unit": "Hz"}, "current_ac": {"value": 7.31, "unit": "A"}, "current_dc": {"value": 6.54, "unit": "A"}, "power_ac": {"value": 1762, "unit": "W"}, "voltage_ac": {"value": 241, "unit": "V"}, "voltage_dc": {"value": 286, "unit": "V"}, } GET_INVERTER_REALTIME_DATA_SYSTEM = { "timestamp": {"value": "2020-09-18T14:13:49-07:00"}, "status": {"Code": 0, "Reason": "", "UserMessage": ""}, "energy_day": {"value": 6000, "unit": "Wh"}, "energy_total": {"value": 35611000, "unit": "Wh"}, "energy_year": {"value": 3310000, "unit": "Wh"}, "power_ac": {"value": 1764, "unit": "W"}, "inverters": { "1": { "energy_day": {"value": 6000, "unit": "Wh"}, "energy_total": {"value": 35611000, "unit": "Wh"}, "energy_year": {"value": 3310000, "unit": "Wh"}, "power_ac": {"value": 1764, "unit": "W"}, } }, }
true
true
f714ad0d90636742e89950dcb0be23eb7b1ca571
9,508
py
Python
axi/planner.py
ejkaplan/axi
cb17cc3ec8093b1f029674dce88711a9c8a293db
[ "MIT" ]
null
null
null
axi/planner.py
ejkaplan/axi
cb17cc3ec8093b1f029674dce88711a9c8a293db
[ "MIT" ]
null
null
null
axi/planner.py
ejkaplan/axi
cb17cc3ec8093b1f029674dce88711a9c8a293db
[ "MIT" ]
null
null
null
from __future__ import division from bisect import bisect from collections import namedtuple from math import sqrt, hypot # a planner computes a motion profile for a list of (x, y) points class Planner(object): def __init__(self, acceleration, max_velocity, corner_factor): self.acceleration = acceleration self.max_velocity = max_velocity self.corner_factor = corner_factor def plan(self, points): return constant_acceleration_plan( points, self.acceleration, self.max_velocity, self.corner_factor ) def plan_all(self, paths): return [self.plan(path) for path in paths] # a plan is a motion profile generated by the planner class Plan(object): def __init__(self, blocks): self.blocks = blocks self.ts = [] # start time of each block self.ss = [] # start distance of each block t = 0 s = 0 for b in blocks: self.ts.append(t) self.ss.append(s) t += b.t s += b.s self.t = t # total time self.s = s # total duration def instant(self, t): t = max(0, min(self.t, t)) # clamp t i = bisect(self.ts, t) - 1 # find block for t return self.blocks[i].instant(t - self.ts[i], self.ts[i], self.ss[i]) # a block is a constant acceleration for a duration of time class Block(object): def __init__(self, a, t, vi, p1, p2): self.a = a self.t = t self.vi = vi self.p1 = p1 self.p2 = p2 self.s = p1.distance(p2) def instant(self, t, dt=0, ds=0): t = max(0, min(self.t, t)) # clamp t a = self.a v = self.vi + self.a * t s = self.vi * t + self.a * t * t / 2 s = max(0, min(self.s, s)) # clamp s p = self.p1.lerps(self.p2, s) return Instant(t + dt, p, s + ds, v, a) # an instant gives position, velocity, etc. at a single point in time Instant = namedtuple("Instant", ["t", "p", "s", "v", "a"]) # a = acceleration # v = velocity # s = distance # t = time # i = initial # f = final # vf = vi + a * t # s = (vf + vi) / 2 * t # s = vi * t + a * t * t / 2 # vf * vf = vi * vi + 2 * a * s EPS = 1e-9 _Point = namedtuple("Point", ["x", "y"]) class Point(_Point): def length(self): return hypot(self.x, self.y) def normalize(self): d = self.length() if d == 0: return Point(0, 0) return Point(self.x / d, self.y / d) def distance(self, other): return hypot(self.x - other.x, self.y - other.y) def distance_squared(self, other): return (self.x - other.x) ** 2 + (self.y - other.y) ** 2 def add(self, other): return Point(self.x + other.x, self.y + other.y) def sub(self, other): return Point(self.x - other.x, self.y - other.y) def mul(self, factor): return Point(self.x * factor, self.y * factor) def dot(self, other): return self.x * other.x + self.y * other.y def lerps(self, other, s): v = other.sub(self).normalize() return self.add(v.mul(s)) def segment_distance(self, v, w): p = self l2 = v.distance_squared(w) if l2 == 0: return p.distance(v) t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2 t = max(0, min(1, t)) x = v.x + t * (w.x - v.x) y = v.y + t * (w.y - v.y) q = Point(x, y) return p.distance(q) Triangle = namedtuple("Triangle", ["s1", "s2", "t1", "t2", "vmax", "p1", "p2", "p3"]) def triangle(s, vi, vf, a, p1, p3): # compute a triangular profile: accelerating, decelerating s1 = (2 * a * s + vf * vf - vi * vi) / (4 * a) s2 = s - s1 vmax = (vi * vi + 2 * a * s1) ** 0.5 t1 = (vmax - vi) / a t2 = (vf - vmax) / -a p2 = p1.lerps(p3, s1) return Triangle(s1, s2, t1, t2, vmax, p1, p2, p3) Trapezoid = namedtuple( "Trapezoid", ["s1", "s2", "s3", "t1", "t2", "t3", "p1", "p2", "p3", "p4"] ) def trapezoid(s, vi, vmax, vf, a, p1, p4): # compute a trapezoidal profile: accelerating, cruising, decelerating t1 = (vmax - vi) / a s1 = (vmax + vi) / 2 * t1 t3 = (vf - vmax) / -a s3 = (vf + vmax) / 2 * t3 s2 = s - s1 - s3 t2 = s2 / vmax p2 = p1.lerps(p4, s1) p3 = p1.lerps(p4, s - s3) return Trapezoid(s1, s2, s3, t1, t2, t3, p1, p2, p3, p4) def corner_velocity(s1, s2, vmax, a, delta): # compute a maximum velocity at the corner of two segments # https://onehossshay.wordpress.com/2011/09/24/improving_grbl_cornering_algorithm/ cosine = -s1.vector.dot(s2.vector) if abs(cosine - 1) < EPS: return 0 sine = sqrt((1 - cosine) / 2) if abs(sine - 1) < EPS: return vmax v = sqrt((a * delta * sine) / (1 - sine)) return min(v, vmax) class Segment(object): # a segment is a line segment between two points, which will be broken # up into blocks by the planner def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 self.length = p1.distance(p2) self.vector = p2.sub(p1).normalize() self.max_entry_velocity = 0 self.entry_velocity = 0 self.blocks = [] class Throttler(object): def __init__(self, points, vmax, dt, threshold): self.points = points self.vmax = vmax self.dt = dt self.threshold = threshold self.distances = [] prev = points[0] d = 0 for point in points: d += prev.distance(point) self.distances.append(d) prev = point def lookup(self, d): return bisect(self.distances, d) - 1 def is_feasible(self, i0, v): d = v * self.dt x0 = self.distances[i0] x1 = x0 + d i1 = self.lookup(x1) if i0 == i1: return True p0 = self.points[i0] p10 = self.points[i1] try: p11 = self.points[i1 + 1] except IndexError: p11 = p10 s = x1 - self.distances[i1] p1 = p10.lerps(p11, s) i = i0 + 1 while i <= i1: p = self.points[i] if p.segment_distance(p0, p1) > self.threshold: return False i += 1 return True def compute_max_velocity(self, index): if self.is_feasible(index, self.vmax): return self.vmax lo = 0 hi = self.vmax for _ in range(16): v = (lo + hi) / 2 if self.is_feasible(index, v): lo = v else: hi = v v = lo return v def compute_max_velocities(self): return [self.compute_max_velocity(i) for i in range(len(self.points))] def constant_acceleration_plan(points, a, vmax, cf): # make sure points are Point objects points = [Point(x, y) for x, y in points] # the throttler reduces speeds based on the discrete timeslicing nature of # the device # TODO: expose parameters throttler = Throttler(points, vmax, 0.02, 0.001) max_velocities = throttler.compute_max_velocities() # create segments for each consecutive pair of points segments = [Segment(p1, p2) for p1, p2 in zip(points, points[1:])] # compute a max_entry_velocity for each segment # based on the angle formed by the two segments at the vertex for v, s1, s2 in zip(max_velocities, segments, segments[1:]): s1.max_entry_velocity = min(s1.max_entry_velocity, v) s2.max_entry_velocity = corner_velocity(s1, s2, vmax, a, cf) # add a dummy segment at the end to force a final velocity of zero segments.append(Segment(points[-1], points[-1])) # loop over segments i = 0 while i < len(segments) - 1: # pull out some variables segment = segments[i] next_segment = segments[i + 1] s = segment.length vi = segment.entry_velocity vexit = next_segment.max_entry_velocity p1 = segment.p1 p2 = segment.p2 # determine which profile to use for this segment m = triangle(s, vi, vexit, a, p1, p2) if m.s1 < -EPS: # too fast! update max_entry_velocity and backtrack segment.max_entry_velocity = sqrt(vexit * vexit + 2 * a * s) i -= 1 elif m.s2 < 0: # accelerate vf = sqrt(vi * vi + 2 * a * s) t = (vf - vi) / a segment.blocks = [ Block(a, t, vi, p1, p2), ] next_segment.entry_velocity = vf i += 1 elif m.vmax > vmax: # accelerate, cruise, decelerate z = trapezoid(s, vi, vmax, vexit, a, p1, p2) segment.blocks = [ Block(a, z.t1, vi, z.p1, z.p2), Block(0, z.t2, vmax, z.p2, z.p3), Block(-a, z.t3, vmax, z.p3, z.p4), ] next_segment.entry_velocity = vexit i += 1 else: # accelerate, decelerate segment.blocks = [ Block(a, m.t1, vi, m.p1, m.p2), Block(-a, m.t2, m.vmax, m.p2, m.p3), ] next_segment.entry_velocity = vexit i += 1 # concatenate all of the blocks blocks = [] for segment in segments: blocks.extend(segment.blocks) # filter out zero-duration blocks and return blocks = [b for b in blocks if b.t > EPS] return Plan(blocks)
29.436533
86
0.538915
from __future__ import division from bisect import bisect from collections import namedtuple from math import sqrt, hypot class Planner(object): def __init__(self, acceleration, max_velocity, corner_factor): self.acceleration = acceleration self.max_velocity = max_velocity self.corner_factor = corner_factor def plan(self, points): return constant_acceleration_plan( points, self.acceleration, self.max_velocity, self.corner_factor ) def plan_all(self, paths): return [self.plan(path) for path in paths] class Plan(object): def __init__(self, blocks): self.blocks = blocks self.ts = [] self.ss = [] t = 0 s = 0 for b in blocks: self.ts.append(t) self.ss.append(s) t += b.t s += b.s self.t = t self.s = s def instant(self, t): t = max(0, min(self.t, t)) i = bisect(self.ts, t) - 1 return self.blocks[i].instant(t - self.ts[i], self.ts[i], self.ss[i]) class Block(object): def __init__(self, a, t, vi, p1, p2): self.a = a self.t = t self.vi = vi self.p1 = p1 self.p2 = p2 self.s = p1.distance(p2) def instant(self, t, dt=0, ds=0): t = max(0, min(self.t, t)) a = self.a v = self.vi + self.a * t s = self.vi * t + self.a * t * t / 2 s = max(0, min(self.s, s)) p = self.p1.lerps(self.p2, s) return Instant(t + dt, p, s + ds, v, a) Instant = namedtuple("Instant", ["t", "p", "s", "v", "a"]) EPS = 1e-9 _Point = namedtuple("Point", ["x", "y"]) class Point(_Point): def length(self): return hypot(self.x, self.y) def normalize(self): d = self.length() if d == 0: return Point(0, 0) return Point(self.x / d, self.y / d) def distance(self, other): return hypot(self.x - other.x, self.y - other.y) def distance_squared(self, other): return (self.x - other.x) ** 2 + (self.y - other.y) ** 2 def add(self, other): return Point(self.x + other.x, self.y + other.y) def sub(self, other): return Point(self.x - other.x, self.y - other.y) def mul(self, factor): return Point(self.x * factor, self.y * factor) def dot(self, other): return self.x * other.x + self.y * other.y def lerps(self, other, s): v = other.sub(self).normalize() return self.add(v.mul(s)) def segment_distance(self, v, w): p = self l2 = v.distance_squared(w) if l2 == 0: return p.distance(v) t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2 t = max(0, min(1, t)) x = v.x + t * (w.x - v.x) y = v.y + t * (w.y - v.y) q = Point(x, y) return p.distance(q) Triangle = namedtuple("Triangle", ["s1", "s2", "t1", "t2", "vmax", "p1", "p2", "p3"]) def triangle(s, vi, vf, a, p1, p3): s1 = (2 * a * s + vf * vf - vi * vi) / (4 * a) s2 = s - s1 vmax = (vi * vi + 2 * a * s1) ** 0.5 t1 = (vmax - vi) / a t2 = (vf - vmax) / -a p2 = p1.lerps(p3, s1) return Triangle(s1, s2, t1, t2, vmax, p1, p2, p3) Trapezoid = namedtuple( "Trapezoid", ["s1", "s2", "s3", "t1", "t2", "t3", "p1", "p2", "p3", "p4"] ) def trapezoid(s, vi, vmax, vf, a, p1, p4): t1 = (vmax - vi) / a s1 = (vmax + vi) / 2 * t1 t3 = (vf - vmax) / -a s3 = (vf + vmax) / 2 * t3 s2 = s - s1 - s3 t2 = s2 / vmax p2 = p1.lerps(p4, s1) p3 = p1.lerps(p4, s - s3) return Trapezoid(s1, s2, s3, t1, t2, t3, p1, p2, p3, p4) def corner_velocity(s1, s2, vmax, a, delta): cosine = -s1.vector.dot(s2.vector) if abs(cosine - 1) < EPS: return 0 sine = sqrt((1 - cosine) / 2) if abs(sine - 1) < EPS: return vmax v = sqrt((a * delta * sine) / (1 - sine)) return min(v, vmax) class Segment(object): def __init__(self, p1, p2): self.p1 = p1 self.p2 = p2 self.length = p1.distance(p2) self.vector = p2.sub(p1).normalize() self.max_entry_velocity = 0 self.entry_velocity = 0 self.blocks = [] class Throttler(object): def __init__(self, points, vmax, dt, threshold): self.points = points self.vmax = vmax self.dt = dt self.threshold = threshold self.distances = [] prev = points[0] d = 0 for point in points: d += prev.distance(point) self.distances.append(d) prev = point def lookup(self, d): return bisect(self.distances, d) - 1 def is_feasible(self, i0, v): d = v * self.dt x0 = self.distances[i0] x1 = x0 + d i1 = self.lookup(x1) if i0 == i1: return True p0 = self.points[i0] p10 = self.points[i1] try: p11 = self.points[i1 + 1] except IndexError: p11 = p10 s = x1 - self.distances[i1] p1 = p10.lerps(p11, s) i = i0 + 1 while i <= i1: p = self.points[i] if p.segment_distance(p0, p1) > self.threshold: return False i += 1 return True def compute_max_velocity(self, index): if self.is_feasible(index, self.vmax): return self.vmax lo = 0 hi = self.vmax for _ in range(16): v = (lo + hi) / 2 if self.is_feasible(index, v): lo = v else: hi = v v = lo return v def compute_max_velocities(self): return [self.compute_max_velocity(i) for i in range(len(self.points))] def constant_acceleration_plan(points, a, vmax, cf): points = [Point(x, y) for x, y in points] throttler = Throttler(points, vmax, 0.02, 0.001) max_velocities = throttler.compute_max_velocities() segments = [Segment(p1, p2) for p1, p2 in zip(points, points[1:])] for v, s1, s2 in zip(max_velocities, segments, segments[1:]): s1.max_entry_velocity = min(s1.max_entry_velocity, v) s2.max_entry_velocity = corner_velocity(s1, s2, vmax, a, cf) segments.append(Segment(points[-1], points[-1])) i = 0 while i < len(segments) - 1: segment = segments[i] next_segment = segments[i + 1] s = segment.length vi = segment.entry_velocity vexit = next_segment.max_entry_velocity p1 = segment.p1 p2 = segment.p2 m = triangle(s, vi, vexit, a, p1, p2) if m.s1 < -EPS: segment.max_entry_velocity = sqrt(vexit * vexit + 2 * a * s) i -= 1 elif m.s2 < 0: vf = sqrt(vi * vi + 2 * a * s) t = (vf - vi) / a segment.blocks = [ Block(a, t, vi, p1, p2), ] next_segment.entry_velocity = vf i += 1 elif m.vmax > vmax: z = trapezoid(s, vi, vmax, vexit, a, p1, p2) segment.blocks = [ Block(a, z.t1, vi, z.p1, z.p2), Block(0, z.t2, vmax, z.p2, z.p3), Block(-a, z.t3, vmax, z.p3, z.p4), ] next_segment.entry_velocity = vexit i += 1 else: segment.blocks = [ Block(a, m.t1, vi, m.p1, m.p2), Block(-a, m.t2, m.vmax, m.p2, m.p3), ] next_segment.entry_velocity = vexit i += 1 blocks = [] for segment in segments: blocks.extend(segment.blocks) blocks = [b for b in blocks if b.t > EPS] return Plan(blocks)
true
true
f714ad9713e72b5a8334c0e62b82795f8e43fffe
20,736
py
Python
mpf/devices/logic_blocks.py
Wolfmarsh/mpf
ad71f381ce8a0e65f28958e51cf8a8b38a6154fb
[ "MIT" ]
null
null
null
mpf/devices/logic_blocks.py
Wolfmarsh/mpf
ad71f381ce8a0e65f28958e51cf8a8b38a6154fb
[ "MIT" ]
null
null
null
mpf/devices/logic_blocks.py
Wolfmarsh/mpf
ad71f381ce8a0e65f28958e51cf8a8b38a6154fb
[ "MIT" ]
null
null
null
"""Logic Blocks devices.""" from typing import Any, List from mpf.core.delays import DelayManager from mpf.core.device_monitor import DeviceMonitor from mpf.core.events import event_handler from mpf.core.machine import MachineController from mpf.core.mode import Mode from mpf.core.mode_device import ModeDevice from mpf.core.player import Player from mpf.core.system_wide_device import SystemWideDevice from mpf.core.utility_functions import Util class LogicBlockState: """Represents the state of a logic_block.""" __slots__ = ["enabled", "completed", "value"] def __init__(self, start_value): """Initialise state.""" self.enabled = False self.completed = False self.value = start_value @DeviceMonitor("value", "enabled", "completed") class LogicBlock(SystemWideDevice, ModeDevice): """Parent class for each of the logic block classes.""" __slots__ = ["_state", "_start_enabled", "player_state_variable"] def __init__(self, machine: MachineController, name: str) -> None: """Initialize logic block.""" super().__init__(machine, name) self._state = None # type: LogicBlockState self._start_enabled = None # type: bool self.player_state_variable = "{}_state".format(self.name) '''player_var: (logic_block)_state desc: A dictionary that stores the internal state of the logic block with the name (logic_block). (In other words, a logic block called *mode1_hit_counter* will store its state in a player variable called ``mode1_hit_counter_state``). The state that's stored in this variable include whether the logic block is enabled and whether it's complete. ''' async def _initialize(self): await super()._initialize() if self.config['start_enabled'] is not None: self._start_enabled = self.config['start_enabled'] else: self._start_enabled = not self.config['enable_events'] def add_control_events_in_mode(self, mode: Mode) -> None: """Do not auto enable this device in modes.""" def validate_and_parse_config(self, config: dict, is_mode_config: bool, debug_prefix: str = None) -> dict: """Validate logic block config.""" del is_mode_config del debug_prefix if 'events_when_complete' not in config: config['events_when_complete'] = ['logicblock_' + self.name + '_complete'] if 'events_when_hit' not in config: config['events_when_hit'] = ['logicblock_' + self.name + '_hit'] self.machine.config_validator.validate_config( self.config_section, config, self.name, ("device", "logic_blocks_common")) self._configure_device_logging(config) return config def can_exist_outside_of_game(self) -> bool: """Return true if persist_state is not set.""" return not bool(self.config['persist_state']) def get_start_value(self) -> Any: """Return the start value for this block.""" raise NotImplementedError("implement") async def device_added_system_wide(self): """Initialise internal state.""" self._state = LogicBlockState(self.get_start_value()) await super().device_added_system_wide() if not self.config['enable_events']: self.enable() if self.config['persist_state']: self.raise_config_error("Cannot set persist_state for system-wide logic_blocks", 1) self.post_update_event() def device_loaded_in_mode(self, mode: Mode, player: Player): """Restore internal state from player if persist_state is set or create new state.""" super().device_loaded_in_mode(mode, player) if self.config['persist_state']: if not player.is_player_var(self.player_state_variable): player[self.player_state_variable] = LogicBlockState(self.get_start_value()) # enable device ONLY when we create a new entry in the player if self._start_enabled: mode.add_mode_event_handler("mode_{}_starting".format(mode.name), self.event_enable, priority=mode.priority + 1) self._state = player[self.player_state_variable] else: self._state = LogicBlockState(self.get_start_value()) if self._start_enabled: mode.add_mode_event_handler("mode_{}_starting".format(mode.name), self.event_enable, priority=mode.priority + 1) mode.add_mode_event_handler("mode_{}_starting".format(mode.name), self.post_update_event) def device_removed_from_mode(self, mode: Mode): """Unset internal state to prevent leakage.""" super().device_removed_from_mode(mode) self._state = None @property def value(self): """Return value or None if that is currently not possible.""" if self._state: return self._state.value return None @property def enabled(self): """Return if enabled.""" return self._state and self._state.enabled @enabled.setter def enabled(self, value): """Set enable.""" self._state.enabled = value @property def completed(self): """Return if completed.""" return self._state and self._state.completed @completed.setter def completed(self, value): """Set if completed.""" self._state.completed = value def post_update_event(self, **kwargs): """Post an event to notify about changes.""" del kwargs value = self._state.value enabled = self._state.enabled self.machine.events.post("logicblock_{}_updated".format(self.name), value=value, enabled=enabled) '''event: logicblock_(name)_updated desc: The logic block called "name" has changed. This might happen when the block advanced, it was resetted or restored. args: value: The current value of this block. enabled: Whatever this block is enabled or not. ''' def enable(self): """Enable this logic block. Automatically called when one of the enable_event events is posted. Can also manually be called. """ super().enable() self.debug_log("Enabling") self.enabled = True self.post_update_event() def _post_hit_events(self, **kwargs): self.post_update_event() for event in self.config['events_when_hit']: self.machine.events.post(event, **kwargs) '''event: logicblock_(name)_hit desc: The logic block "name" was just hit. Note that this is the default hit event for logic blocks, but this can be changed in a logic block's "events_when_hit:" setting, so this might not be the actual event that's posted for all logic blocks in your machine. args: depend on the type ''' @event_handler(0) def event_disable(self, **kwargs): """Event handler for disable event.""" del kwargs self.disable() def disable(self): """Disable this logic block. Automatically called when one of the disable_event events is posted. Can also manually be called. """ self.debug_log("Disabling") self.enabled = False self.post_update_event() @event_handler(4) def event_reset(self, **kwargs): """Event handler for reset event.""" del kwargs self.reset() def reset(self): """Reset the progress towards completion of this logic block. Automatically called when one of the reset_event events is called. Can also be manually called. """ self.completed = False self._state.value = self.get_start_value() self.debug_log("Resetting") self.post_update_event() @event_handler(5) def event_restart(self, **kwargs): """Event handler for restart event.""" del kwargs self.restart() def restart(self): """Restart this logic block by calling reset() and enable(). Automatically called when one of the restart_event events is called. Can also be manually called. """ self.debug_log("Restarting (resetting then enabling)") self.reset() self.enable() def complete(self): """Mark this logic block as complete. Posts the 'events_when_complete' events and optionally restarts this logic block or disables it, depending on this block's configuration settings. """ # if already completed do not complete again if self.completed: return # otherwise mark as completed self.completed = True self.debug_log("Complete") if self.config['events_when_complete']: for event in self.config['events_when_complete']: self.machine.events.post(event) '''event: logicblock_(name)_complete desc: The logic block called "name" has just been completed. Note that this is the default completion event for logic blocks, but this can be changed in a logic block's "events_when_complete:" setting, so this might not be the actual event that's posted for all logic blocks in your machine. ''' # call reset to reset completion if self.config['reset_on_complete']: self.reset() # disable block if self.config['disable_on_complete']: self.disable() class Counter(LogicBlock): """A type of LogicBlock that tracks multiple hits of a single event. This counter can be configured to track hits towards a specific end-goal (like number of tilt hits to tilt), or it can be an open-ended count (like total number of ramp shots). It can also be configured to count up or to count down, and can have a configurable counting interval. """ config_section = 'counters' collection = 'counters' class_label = 'counter' __slots__ = ["delay", "ignore_hits", "hit_value"] def __init__(self, machine: MachineController, name: str) -> None: """Initialise counter.""" super().__init__(machine, name) self.debug_log("Creating Counter LogicBlock") self.delay = DelayManager(self.machine) self.ignore_hits = False self.hit_value = -1 async def _initialize(self): await super()._initialize() self.hit_value = self.config['count_interval'] if self.config['direction'] == 'down' and self.hit_value > 0: self.hit_value *= -1 elif self.config['direction'] == 'up' and self.hit_value < 0: self.hit_value *= -1 # Add control events if included in the config if self.config['control_events']: self._setup_control_events(self.config['control_events']) def add_control_events_in_mode(self, mode: Mode) -> None: """Do not auto enable this device in modes.""" def _setup_control_events(self, event_list): self.debug_log("Setting up control events") kwargs = {} for entry in event_list: if entry['action'] in ('add', 'subtract', 'jump'): handler = getattr(self, "event_{}".format(entry['action'])) kwargs = {'value': entry['value']} else: raise AssertionError("Invalid control_event action {} in mode". format(entry['action']), self.name) self.machine.events.add_handler(entry['event'], handler, **kwargs) def check_complete(self, count_complete_value=None): """Check if counter is completed. Return true if the counter has reached or surpassed its specified completion value, return False if no completion criteria or is not complete. """ # If count_complete_value was not passed, obtain it if count_complete_value is None and self.config.get("count_complete_value"): count_complete_value = self.config["count_complete_value"].evaluate([]) if count_complete_value is not None: if self.config['direction'] == 'up': return self._state.value >= count_complete_value if self.config['direction'] == 'down': return self._state.value <= count_complete_value return False def event_add(self, value, **kwargs): """Add to the value of this counter. Args: value: Value to add to the counter. kwargs: Additional arguments. """ evaluated_value = value.evaluate_or_none(kwargs) if evaluated_value is None: self.log.warning("Placeholder %s for counter add did not evaluate with args %s", value, kwargs) return # Add to the counter the specified value self._state.value += evaluated_value # Check if count is complete given the updated value if self.check_complete(): self.complete() def event_subtract(self, value, **kwargs): """Subtract from the value of this counter. Args: value: Value to subtract from the counter. kwargs: Additional arguments. """ evaluated_value = value.evaluate_or_none(kwargs) if evaluated_value is None: self.log.warning("Placeholder %s for counter substract did not evaluate with args %s", value, kwargs) return # Subtract from the counter the specified value self._state.value -= evaluated_value # Check if count is complete given the updated value if self.check_complete(): self.complete() def event_jump(self, value, **kwargs): """Set the internal value of the counter. Args: value: Value to add to jump to. kwargs: Additional arguments. """ evaluated_value = value.evaluate_or_none(kwargs) if evaluated_value is None: self.log.warning("Placeholder %s for counter jump did not evaluate with args %s", value, kwargs) return # Set the internal value of the counter to the specified value self._state.value = evaluated_value # Check if count is complete given the updated value if self.check_complete(): self.complete() def get_start_value(self) -> int: """Return start count.""" return self.config['starting_count'].evaluate([]) def validate_and_parse_config(self, config: dict, is_mode_config: bool, debug_prefix: str = None) -> dict: """Validate logic block config.""" if 'events_when_hit' not in config: # for compatibility post the same default as previously for # counters. This one is deprecated. config['events_when_hit'] = ['counter_' + self.name + '_hit'] # this is the one moving forward config['events_when_hit'].append('logicblock_' + self.name + '_hit') return super().validate_and_parse_config(config, is_mode_config, debug_prefix) @event_handler(0) def event_count(self, **kwargs): """Event handler for count events.""" del kwargs self.count() def count(self): """Increase the hit progress towards completion. This method is also automatically called when one of the ``count_events`` is posted. """ if not self.enabled: return count_complete_value = self.config['count_complete_value'].evaluate([]) if self.config['count_complete_value']\ is not None else None if not self.ignore_hits: self._state.value += self.hit_value self.debug_log("Processing Count change. Total: %s", self._state.value) args = { "count": self._state.value } if count_complete_value is not None: args['remaining'] = count_complete_value - self._state.value self._post_hit_events(**args) if self.check_complete(count_complete_value): self.complete() if self.config['multiple_hit_window']: self.debug_log("Beginning Ignore Hits") self.ignore_hits = True self.delay.add(name='ignore_hits_within_window', ms=self.config['multiple_hit_window'], callback=self.stop_ignoring_hits) def stop_ignoring_hits(self, **kwargs): """Cause the Counter to stop ignoring subsequent hits that occur within the 'multiple_hit_window'. Automatically called when the window time expires. Can safely be manually called. """ del kwargs self.debug_log("Ending Ignore hits") self.ignore_hits = False class Accrual(LogicBlock): """A type of LogicBlock which tracks many different events (steps) towards a goal. The steps are able to happen in any order. """ config_section = 'accruals' collection = 'accruals' class_label = 'accrual' __slots__ = [] @property def config_section_name(self): """Return config section.""" return "accrual" def __init__(self, machine, name): """Initialise Accrual.""" super().__init__(machine, name) self.debug_log("Creating Accrual LogicBlock") async def _initialize(self): await super()._initialize() self.setup_event_handlers() def get_start_value(self) -> List[bool]: """Return start states.""" return [False] * len(self.config['events']) def setup_event_handlers(self): """Add event handlers.""" for step, events in enumerate(self.config['events']): for event in Util.string_to_list(events): self.machine.events.add_handler(event, self.hit, step=step) def hit(self, step: int, **kwargs): """Increase the hit progress towards completion. Automatically called when one of the `count_events` is posted. Can also manually be called. Args: step: Integer of the step number (0 indexed) that was just hit. """ del kwargs if not self.enabled: return self.debug_log("Processing hit for step: %s", step) if not self._state.value[step]: self._state.value[step] = True self.debug_log("Status: %s", self._state.value) self._post_hit_events(step=step) if self._state.value.count(True) == len(self._state.value): self.complete() class Sequence(LogicBlock): """A type of LogicBlock which tracks many different events (steps) towards a goal. The steps have to happen in order. """ config_section = 'sequences' collection = 'sequences' class_label = 'sequence' __slots__ = [] @property def config_section_name(self): """Return config section.""" return "sequence" def __init__(self, machine: MachineController, name: str) -> None: """Initialise sequence.""" super().__init__(machine, name) self.debug_log("Creating Sequence LogicBlock") async def _initialize(self): """Initialise sequence.""" await super()._initialize() self.setup_event_handlers() def get_start_value(self) -> int: """Return start step.""" return 0 def setup_event_handlers(self): """Add the handlers for the current step.""" for step, events in enumerate(self.config['events']): for event in Util.string_to_list(events): # increase priority with steps to prevent advancing multiple steps at once self.machine.events.add_handler(event, self.hit, step=step, priority=step) def hit(self, step: int = None, **kwargs): """Increase the hit progress towards completion. Automatically called when one of the `count_events` is posted. Can also manually be called. """ del kwargs if not self.enabled: return if step is not None and step != self._state.value: # got this for another state return self.debug_log("Processing Hit") self._state.value += 1 self._post_hit_events(step=self._state.value) if self._state.value >= len(self.config['events']): self.complete()
34.733668
119
0.624904
from typing import Any, List from mpf.core.delays import DelayManager from mpf.core.device_monitor import DeviceMonitor from mpf.core.events import event_handler from mpf.core.machine import MachineController from mpf.core.mode import Mode from mpf.core.mode_device import ModeDevice from mpf.core.player import Player from mpf.core.system_wide_device import SystemWideDevice from mpf.core.utility_functions import Util class LogicBlockState: __slots__ = ["enabled", "completed", "value"] def __init__(self, start_value): self.enabled = False self.completed = False self.value = start_value @DeviceMonitor("value", "enabled", "completed") class LogicBlock(SystemWideDevice, ModeDevice): __slots__ = ["_state", "_start_enabled", "player_state_variable"] def __init__(self, machine: MachineController, name: str) -> None: super().__init__(machine, name) self._state = None self._start_enabled = None self.player_state_variable = "{}_state".format(self.name) async def _initialize(self): await super()._initialize() if self.config['start_enabled'] is not None: self._start_enabled = self.config['start_enabled'] else: self._start_enabled = not self.config['enable_events'] def add_control_events_in_mode(self, mode: Mode) -> None: def validate_and_parse_config(self, config: dict, is_mode_config: bool, debug_prefix: str = None) -> dict: del is_mode_config del debug_prefix if 'events_when_complete' not in config: config['events_when_complete'] = ['logicblock_' + self.name + '_complete'] if 'events_when_hit' not in config: config['events_when_hit'] = ['logicblock_' + self.name + '_hit'] self.machine.config_validator.validate_config( self.config_section, config, self.name, ("device", "logic_blocks_common")) self._configure_device_logging(config) return config def can_exist_outside_of_game(self) -> bool: return not bool(self.config['persist_state']) def get_start_value(self) -> Any: raise NotImplementedError("implement") async def device_added_system_wide(self): self._state = LogicBlockState(self.get_start_value()) await super().device_added_system_wide() if not self.config['enable_events']: self.enable() if self.config['persist_state']: self.raise_config_error("Cannot set persist_state for system-wide logic_blocks", 1) self.post_update_event() def device_loaded_in_mode(self, mode: Mode, player: Player): super().device_loaded_in_mode(mode, player) if self.config['persist_state']: if not player.is_player_var(self.player_state_variable): player[self.player_state_variable] = LogicBlockState(self.get_start_value()) if self._start_enabled: mode.add_mode_event_handler("mode_{}_starting".format(mode.name), self.event_enable, priority=mode.priority + 1) self._state = player[self.player_state_variable] else: self._state = LogicBlockState(self.get_start_value()) if self._start_enabled: mode.add_mode_event_handler("mode_{}_starting".format(mode.name), self.event_enable, priority=mode.priority + 1) mode.add_mode_event_handler("mode_{}_starting".format(mode.name), self.post_update_event) def device_removed_from_mode(self, mode: Mode): super().device_removed_from_mode(mode) self._state = None @property def value(self): if self._state: return self._state.value return None @property def enabled(self): return self._state and self._state.enabled @enabled.setter def enabled(self, value): self._state.enabled = value @property def completed(self): return self._state and self._state.completed @completed.setter def completed(self, value): self._state.completed = value def post_update_event(self, **kwargs): del kwargs value = self._state.value enabled = self._state.enabled self.machine.events.post("logicblock_{}_updated".format(self.name), value=value, enabled=enabled) def enable(self): super().enable() self.debug_log("Enabling") self.enabled = True self.post_update_event() def _post_hit_events(self, **kwargs): self.post_update_event() for event in self.config['events_when_hit']: self.machine.events.post(event, **kwargs) @event_handler(0) def event_disable(self, **kwargs): del kwargs self.disable() def disable(self): self.debug_log("Disabling") self.enabled = False self.post_update_event() @event_handler(4) def event_reset(self, **kwargs): del kwargs self.reset() def reset(self): self.completed = False self._state.value = self.get_start_value() self.debug_log("Resetting") self.post_update_event() @event_handler(5) def event_restart(self, **kwargs): del kwargs self.restart() def restart(self): self.debug_log("Restarting (resetting then enabling)") self.reset() self.enable() def complete(self): if self.completed: return self.completed = True self.debug_log("Complete") if self.config['events_when_complete']: for event in self.config['events_when_complete']: self.machine.events.post(event) if self.config['reset_on_complete']: self.reset() if self.config['disable_on_complete']: self.disable() class Counter(LogicBlock): config_section = 'counters' collection = 'counters' class_label = 'counter' __slots__ = ["delay", "ignore_hits", "hit_value"] def __init__(self, machine: MachineController, name: str) -> None: super().__init__(machine, name) self.debug_log("Creating Counter LogicBlock") self.delay = DelayManager(self.machine) self.ignore_hits = False self.hit_value = -1 async def _initialize(self): await super()._initialize() self.hit_value = self.config['count_interval'] if self.config['direction'] == 'down' and self.hit_value > 0: self.hit_value *= -1 elif self.config['direction'] == 'up' and self.hit_value < 0: self.hit_value *= -1 if self.config['control_events']: self._setup_control_events(self.config['control_events']) def add_control_events_in_mode(self, mode: Mode) -> None: def _setup_control_events(self, event_list): self.debug_log("Setting up control events") kwargs = {} for entry in event_list: if entry['action'] in ('add', 'subtract', 'jump'): handler = getattr(self, "event_{}".format(entry['action'])) kwargs = {'value': entry['value']} else: raise AssertionError("Invalid control_event action {} in mode". format(entry['action']), self.name) self.machine.events.add_handler(entry['event'], handler, **kwargs) def check_complete(self, count_complete_value=None): if count_complete_value is None and self.config.get("count_complete_value"): count_complete_value = self.config["count_complete_value"].evaluate([]) if count_complete_value is not None: if self.config['direction'] == 'up': return self._state.value >= count_complete_value if self.config['direction'] == 'down': return self._state.value <= count_complete_value return False def event_add(self, value, **kwargs): evaluated_value = value.evaluate_or_none(kwargs) if evaluated_value is None: self.log.warning("Placeholder %s for counter add did not evaluate with args %s", value, kwargs) return self._state.value += evaluated_value if self.check_complete(): self.complete() def event_subtract(self, value, **kwargs): evaluated_value = value.evaluate_or_none(kwargs) if evaluated_value is None: self.log.warning("Placeholder %s for counter substract did not evaluate with args %s", value, kwargs) return self._state.value -= evaluated_value if self.check_complete(): self.complete() def event_jump(self, value, **kwargs): evaluated_value = value.evaluate_or_none(kwargs) if evaluated_value is None: self.log.warning("Placeholder %s for counter jump did not evaluate with args %s", value, kwargs) return self._state.value = evaluated_value if self.check_complete(): self.complete() def get_start_value(self) -> int: return self.config['starting_count'].evaluate([]) def validate_and_parse_config(self, config: dict, is_mode_config: bool, debug_prefix: str = None) -> dict: if 'events_when_hit' not in config: config['events_when_hit'] = ['counter_' + self.name + '_hit'] config['events_when_hit'].append('logicblock_' + self.name + '_hit') return super().validate_and_parse_config(config, is_mode_config, debug_prefix) @event_handler(0) def event_count(self, **kwargs): del kwargs self.count() def count(self): if not self.enabled: return count_complete_value = self.config['count_complete_value'].evaluate([]) if self.config['count_complete_value']\ is not None else None if not self.ignore_hits: self._state.value += self.hit_value self.debug_log("Processing Count change. Total: %s", self._state.value) args = { "count": self._state.value } if count_complete_value is not None: args['remaining'] = count_complete_value - self._state.value self._post_hit_events(**args) if self.check_complete(count_complete_value): self.complete() if self.config['multiple_hit_window']: self.debug_log("Beginning Ignore Hits") self.ignore_hits = True self.delay.add(name='ignore_hits_within_window', ms=self.config['multiple_hit_window'], callback=self.stop_ignoring_hits) def stop_ignoring_hits(self, **kwargs): del kwargs self.debug_log("Ending Ignore hits") self.ignore_hits = False class Accrual(LogicBlock): config_section = 'accruals' collection = 'accruals' class_label = 'accrual' __slots__ = [] @property def config_section_name(self): return "accrual" def __init__(self, machine, name): super().__init__(machine, name) self.debug_log("Creating Accrual LogicBlock") async def _initialize(self): await super()._initialize() self.setup_event_handlers() def get_start_value(self) -> List[bool]: return [False] * len(self.config['events']) def setup_event_handlers(self): for step, events in enumerate(self.config['events']): for event in Util.string_to_list(events): self.machine.events.add_handler(event, self.hit, step=step) def hit(self, step: int, **kwargs): del kwargs if not self.enabled: return self.debug_log("Processing hit for step: %s", step) if not self._state.value[step]: self._state.value[step] = True self.debug_log("Status: %s", self._state.value) self._post_hit_events(step=step) if self._state.value.count(True) == len(self._state.value): self.complete() class Sequence(LogicBlock): config_section = 'sequences' collection = 'sequences' class_label = 'sequence' __slots__ = [] @property def config_section_name(self): return "sequence" def __init__(self, machine: MachineController, name: str) -> None: super().__init__(machine, name) self.debug_log("Creating Sequence LogicBlock") async def _initialize(self): await super()._initialize() self.setup_event_handlers() def get_start_value(self) -> int: return 0 def setup_event_handlers(self): for step, events in enumerate(self.config['events']): for event in Util.string_to_list(events): self.machine.events.add_handler(event, self.hit, step=step, priority=step) def hit(self, step: int = None, **kwargs): del kwargs if not self.enabled: return if step is not None and step != self._state.value: return self.debug_log("Processing Hit") self._state.value += 1 self._post_hit_events(step=self._state.value) if self._state.value >= len(self.config['events']): self.complete()
true
true
f714ad9a06849425b9f24c8d797c655c90f7b75e
4,463
py
Python
newapi/ooniapi/prio.py
cyBerta/api
af8e15a800ffc272799a269f4801cbdd174d0c43
[ "BSD-3-Clause" ]
null
null
null
newapi/ooniapi/prio.py
cyBerta/api
af8e15a800ffc272799a269f4801cbdd174d0c43
[ "BSD-3-Clause" ]
null
null
null
newapi/ooniapi/prio.py
cyBerta/api
af8e15a800ffc272799a269f4801cbdd174d0c43
[ "BSD-3-Clause" ]
null
null
null
""" OONI Probe Services API - URL prioritization """ from typing import List import random import time from flask import Blueprint, current_app, request from flask.json import jsonify prio_bp = Blueprint("prio", "probe_services_prio") # TODO add unit tests test_items = {} last_update_time = 0 def update_url_prioritization(): log = current_app.logger log.info("Started update_url_prioritization") # conn = connect_db(conf) # cur = conn.cursor(cursor_factory=RealDictCursor) log.info("Regenerating URL prioritization file") sql = """SELECT priority, domain, url, cc, category_code FROM citizenlab""" q = current_app.db_session.execute(sql) entries = list(q.fetchall()) # Create dict: cc -> category_code -> [entry, ... ] entries_by_country = {} for e in entries: country = e["cc"].upper() if country not in entries_by_country: entries_by_country[country] = {} ccode = e["category_code"] entries_by_country[country].setdefault(ccode, []).append(e) # Merge ZZ into each country, so that "global" urls are given out to probes # from every country. Also keep ZZ as valid cc in case a probe requests it zz = entries_by_country["ZZ"] for ccode, country_dict in entries_by_country.items(): for category_code, prio_test_items in zz.items(): country_dict.setdefault(category_code, []).extend(prio_test_items) log.info("Update done: %d" % len(entries_by_country)) return entries_by_country def algo_chao(s: List, k: int) -> List: """Chao weighted random sampling """ n = len(s) assert len(s) >= k wsum = 0 r = s[:k] assert len(r) == k for i in range(0, n): wsum = wsum + s[i]["priority"] if i < k: continue p = s[i]["priority"] / wsum # probability for this item j = random.random() if j <= p: pos = random.randint(0, k - 1) r[pos] = s[i] return r def generate_test_list(country_code: str, category_codes: str, limit: int): global test_items, last_update_time log = current_app.logger if last_update_time < time.time() - 100: # conf.refresh_interval: last_update_time = time.time() try: test_items = update_url_prioritization() except Exception as e: log.error(e, exc_info=1) candidates_d = test_items[country_code] # category_code -> [test_item, ... ] if category_codes: category_codes = [c.strip().upper() for c in category_codes.split(",")] else: category_codes = candidates_d.keys() candidates = [] for ccode in category_codes: s = candidates_d.get(ccode, []) candidates.extend(s) log.info("%d candidates", len(candidates)) if limit == -1: limit = 100 limit = min(limit, len(candidates)) selected = algo_chao(candidates, limit) out = [] for entry in selected: cc = "XX" if entry["cc"] == "ZZ" else entry["cc"].upper() out.append( { "category_code": entry["category_code"], "url": entry["url"], "country_code": cc, } ) return out @prio_bp.route("/api/v1/test-list/urls") def list_test_urls(): """Generate test URL list with prioritization https://orchestrate.ooni.io/api/v1/test-list/urls?country_code=IT --- parameters: - name: country_code in: query type: string description: Two letter, uppercase country code - name: category_code in: query type: string description: Comma separated list of URL categories, all uppercase responses: '200': description: URL test list """ log = current_app.logger param = request.args.get try: country_code = (param("country_code") or "ZZ").upper() category_codes = param("category_code") limit = int(param("limit") or -1) test_items = generate_test_list(country_code, category_codes, limit) out = { "metadata": { "count": len(test_items), "current_page": -1, "limit": -1, "next_url": "", "pages": 1, }, "results": test_items, } return jsonify(out) except Exception as e: log.error(e, exc_info=1) return jsonify({})
28.980519
81
0.599149
from typing import List import random import time from flask import Blueprint, current_app, request from flask.json import jsonify prio_bp = Blueprint("prio", "probe_services_prio") test_items = {} last_update_time = 0 def update_url_prioritization(): log = current_app.logger log.info("Started update_url_prioritization") log.info("Regenerating URL prioritization file") sql = """SELECT priority, domain, url, cc, category_code FROM citizenlab""" q = current_app.db_session.execute(sql) entries = list(q.fetchall()) entries_by_country = {} for e in entries: country = e["cc"].upper() if country not in entries_by_country: entries_by_country[country] = {} ccode = e["category_code"] entries_by_country[country].setdefault(ccode, []).append(e) zz = entries_by_country["ZZ"] for ccode, country_dict in entries_by_country.items(): for category_code, prio_test_items in zz.items(): country_dict.setdefault(category_code, []).extend(prio_test_items) log.info("Update done: %d" % len(entries_by_country)) return entries_by_country def algo_chao(s: List, k: int) -> List: n = len(s) assert len(s) >= k wsum = 0 r = s[:k] assert len(r) == k for i in range(0, n): wsum = wsum + s[i]["priority"] if i < k: continue p = s[i]["priority"] / wsum j = random.random() if j <= p: pos = random.randint(0, k - 1) r[pos] = s[i] return r def generate_test_list(country_code: str, category_codes: str, limit: int): global test_items, last_update_time log = current_app.logger if last_update_time < time.time() - 100: last_update_time = time.time() try: test_items = update_url_prioritization() except Exception as e: log.error(e, exc_info=1) candidates_d = test_items[country_code] if category_codes: category_codes = [c.strip().upper() for c in category_codes.split(",")] else: category_codes = candidates_d.keys() candidates = [] for ccode in category_codes: s = candidates_d.get(ccode, []) candidates.extend(s) log.info("%d candidates", len(candidates)) if limit == -1: limit = 100 limit = min(limit, len(candidates)) selected = algo_chao(candidates, limit) out = [] for entry in selected: cc = "XX" if entry["cc"] == "ZZ" else entry["cc"].upper() out.append( { "category_code": entry["category_code"], "url": entry["url"], "country_code": cc, } ) return out @prio_bp.route("/api/v1/test-list/urls") def list_test_urls(): log = current_app.logger param = request.args.get try: country_code = (param("country_code") or "ZZ").upper() category_codes = param("category_code") limit = int(param("limit") or -1) test_items = generate_test_list(country_code, category_codes, limit) out = { "metadata": { "count": len(test_items), "current_page": -1, "limit": -1, "next_url": "", "pages": 1, }, "results": test_items, } return jsonify(out) except Exception as e: log.error(e, exc_info=1) return jsonify({})
true
true
f714af1996211444cf3b111bbef2e05f72c01ea6
7,708
py
Python
ibmsecurity/isam/base/extensions.py
zone-zero/ibmsecurity
7d3e38104b67e1b267e18a44845cb756a5302c3d
[ "Apache-2.0" ]
46
2017-03-21T21:08:59.000Z
2022-02-20T22:03:46.000Z
ibmsecurity/isam/base/extensions.py
zone-zero/ibmsecurity
7d3e38104b67e1b267e18a44845cb756a5302c3d
[ "Apache-2.0" ]
201
2017-03-21T21:25:52.000Z
2022-03-30T21:38:20.000Z
ibmsecurity/isam/base/extensions.py
zone-zero/ibmsecurity
7d3e38104b67e1b267e18a44845cb756a5302c3d
[ "Apache-2.0" ]
91
2017-03-22T16:25:36.000Z
2022-02-04T04:36:29.000Z
import json import logging import ibmsecurity.utilities.tools from ibmsecurity.utilities import tools from io import open logger = logging.getLogger(__name__) uri = "/extensions" requires_modules = None requires_version = "9.0.5.0" try: basestring except NameError: basestring = (str, bytes) def get_all(isamAppliance, check_mode=False, force=False): """ Retrieve installed extensions list """ return isamAppliance.invoke_get("Retrieve installed extensions list", "{0}/".format(uri), requires_modules=requires_modules, requires_version=requires_version) def add(isamAppliance, extension, config_data=None, third_party_package=None, check_mode=False, force=False): """ Installing an Extension :param isamAppliance: :param extension: path/filename to .ext file :param config_data: all the config data in a single string. For example, "agentName:ISAM_Monitoring,ipAddress:10.10.10.10,port:9998" :param third_party_package: an array of the supporting files required. :param check_mode: :param force: :return: """ try: id = inspect(isamAppliance, extension) except Exception as e: warning_str = "Exception occurred: {0}".format(e) return isamAppliance.create_return_object(warnings=[warning_str]) if config_data: config_str = '{extId:' + id + ',' + config_data + '}' else: config_str = '{extId:' + id + '}' files = {} files['extension_support_package'] = (tools.path_leaf(extension), open(extension, 'rb')) files['config_data'] = (None, config_str) if third_party_package: if isinstance(third_party_package, basestring): files['third_party_package'] = (tools.path_leaf(third_party_package), open(third_party_package, 'rb')) elif len(third_party_package) == 1: files['third_party_package'] = (tools.path_leaf(third_party_package[0]), open(third_party_package[0], 'rb')) else: counter = 0 for file in third_party_package: third_party = 'third_party_package{0}'.format(counter) files[third_party] = (tools.path_leaf(file), open(file, 'rb')) counter = counter + 1 if check_mode: return isamAppliance.create_return_object(changed=True) return isamAppliance.invoke_post_files( "Installing an Extension", "{0}/activate".format(uri), [], files, requires_modules=requires_modules, requires_version=requires_version, json_response=False, data_as_files=True) def update(isamAppliance, extId, config_data=None, third_party_package=None, check_mode=False, force=False): """ Update an existing installed extension :param isamAppliance: :param extId: extension id :param config_data: all the config data in a single string. For example, "agentName:ISAM_Monitoring,ipAddress:10.10.10.10,port:9998" :param third_party_package: list of third_party files :param check_mode: :param force: :return: """ if force is True or search(isamAppliance, extId=extId): if check_mode: return isamAppliance.create_return_object(changed=True) else: if config_data: config_str = '{extId:' + extId + ',' + config_data + '}' else: config_str = '{extId:' + extId + '}' files = {} files['config_data'] = (None, config_str) if third_party_package: if isinstance(third_party_package, basestring): files['third_party_package'] = ( tools.path_leaf(third_party_package), open(third_party_package, 'rb')) elif len(third_party_package) == 1: files['third_party_package'] = ( tools.path_leaf(third_party_package[0]), open(third_party_package[0], 'rb')) else: counter = 0 for file in third_party_package: third_party = 'third_party_package{0}'.format(counter) files[third_party] = (tools.path_leaf(file), open(file, 'rb')) counter = counter + 1 return isamAppliance.invoke_post_files( "Update an Extension", "{0}/{1}".format(uri, extId), [], files, requires_modules=requires_modules, requires_version=requires_version, json_response=False, data_as_files=True) return isamAppliance.create_return_object() def set(isamAppliance, extension=None, extId=None, config_data=None, third_party_package=None, check_mode=False, force=False): if extId: if search(isamAppliance, extId): return update(isamAppliance=isamAppliance, extId=extId, config_data=config_data, third_party_package=third_party_package, check_mode=check_mode, force=True) else: return add(isamAppliance=isamAppliance, extension=extension, config_data=config_data, third_party_package=third_party_package, check_mode=check_mode, force=force) return isamAppliance.create_return_object() def delete(isamAppliance, extId, check_mode=False, force=False): """ Delete an installed extension """ if force is True or search(isamAppliance, extId=extId): if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isamAppliance.invoke_delete( "Delete an installed extension", "{0}/{1}".format(uri, extId)) return isamAppliance.create_return_object(changed=False) def inspect(isamAppliance, extension, check_mode=False, force=False): """ Inspect the extension file to find the id for the extension. :param isamAppliance: :param extension: :param check_mode: :param force: :return: """ obj = isamAppliance.invoke_post_files("Inspect extension", "{0}/inspect".format(uri), [{ 'file_formfield': 'extension_support_package', 'filename': extension, 'mimetype': 'application/octet-stream' }], { }, json_response=False, requires_modules=requires_modules, requires_version=requires_version) m_obj = obj['data'] m_obj = m_obj.replace('<textarea>', '') m_obj = m_obj.replace('</textarea>', '') json_obj = json.loads(m_obj) return json_obj['id'] def search(isamAppliance, extId, check_mode=False, force=False): """ Search for the extension """ ret_obj = get_all(isamAppliance) for obj in ret_obj['data']: if obj['id'] == extId: return True return False def compare(isamAppliance1, isamAppliance2): """ Compare extensions between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) if ret_obj1['data']: del ret_obj1['data'][0]['date'] if ret_obj2['data']: del ret_obj2['data'][0]['date'] return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2, deleted_keys=['date'])
34.565022
137
0.601583
import json import logging import ibmsecurity.utilities.tools from ibmsecurity.utilities import tools from io import open logger = logging.getLogger(__name__) uri = "/extensions" requires_modules = None requires_version = "9.0.5.0" try: basestring except NameError: basestring = (str, bytes) def get_all(isamAppliance, check_mode=False, force=False): return isamAppliance.invoke_get("Retrieve installed extensions list", "{0}/".format(uri), requires_modules=requires_modules, requires_version=requires_version) def add(isamAppliance, extension, config_data=None, third_party_package=None, check_mode=False, force=False): try: id = inspect(isamAppliance, extension) except Exception as e: warning_str = "Exception occurred: {0}".format(e) return isamAppliance.create_return_object(warnings=[warning_str]) if config_data: config_str = '{extId:' + id + ',' + config_data + '}' else: config_str = '{extId:' + id + '}' files = {} files['extension_support_package'] = (tools.path_leaf(extension), open(extension, 'rb')) files['config_data'] = (None, config_str) if third_party_package: if isinstance(third_party_package, basestring): files['third_party_package'] = (tools.path_leaf(third_party_package), open(third_party_package, 'rb')) elif len(third_party_package) == 1: files['third_party_package'] = (tools.path_leaf(third_party_package[0]), open(third_party_package[0], 'rb')) else: counter = 0 for file in third_party_package: third_party = 'third_party_package{0}'.format(counter) files[third_party] = (tools.path_leaf(file), open(file, 'rb')) counter = counter + 1 if check_mode: return isamAppliance.create_return_object(changed=True) return isamAppliance.invoke_post_files( "Installing an Extension", "{0}/activate".format(uri), [], files, requires_modules=requires_modules, requires_version=requires_version, json_response=False, data_as_files=True) def update(isamAppliance, extId, config_data=None, third_party_package=None, check_mode=False, force=False): if force is True or search(isamAppliance, extId=extId): if check_mode: return isamAppliance.create_return_object(changed=True) else: if config_data: config_str = '{extId:' + extId + ',' + config_data + '}' else: config_str = '{extId:' + extId + '}' files = {} files['config_data'] = (None, config_str) if third_party_package: if isinstance(third_party_package, basestring): files['third_party_package'] = ( tools.path_leaf(third_party_package), open(third_party_package, 'rb')) elif len(third_party_package) == 1: files['third_party_package'] = ( tools.path_leaf(third_party_package[0]), open(third_party_package[0], 'rb')) else: counter = 0 for file in third_party_package: third_party = 'third_party_package{0}'.format(counter) files[third_party] = (tools.path_leaf(file), open(file, 'rb')) counter = counter + 1 return isamAppliance.invoke_post_files( "Update an Extension", "{0}/{1}".format(uri, extId), [], files, requires_modules=requires_modules, requires_version=requires_version, json_response=False, data_as_files=True) return isamAppliance.create_return_object() def set(isamAppliance, extension=None, extId=None, config_data=None, third_party_package=None, check_mode=False, force=False): if extId: if search(isamAppliance, extId): return update(isamAppliance=isamAppliance, extId=extId, config_data=config_data, third_party_package=third_party_package, check_mode=check_mode, force=True) else: return add(isamAppliance=isamAppliance, extension=extension, config_data=config_data, third_party_package=third_party_package, check_mode=check_mode, force=force) return isamAppliance.create_return_object() def delete(isamAppliance, extId, check_mode=False, force=False): if force is True or search(isamAppliance, extId=extId): if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isamAppliance.invoke_delete( "Delete an installed extension", "{0}/{1}".format(uri, extId)) return isamAppliance.create_return_object(changed=False) def inspect(isamAppliance, extension, check_mode=False, force=False): obj = isamAppliance.invoke_post_files("Inspect extension", "{0}/inspect".format(uri), [{ 'file_formfield': 'extension_support_package', 'filename': extension, 'mimetype': 'application/octet-stream' }], { }, json_response=False, requires_modules=requires_modules, requires_version=requires_version) m_obj = obj['data'] m_obj = m_obj.replace('<textarea>', '') m_obj = m_obj.replace('</textarea>', '') json_obj = json.loads(m_obj) return json_obj['id'] def search(isamAppliance, extId, check_mode=False, force=False): ret_obj = get_all(isamAppliance) for obj in ret_obj['data']: if obj['id'] == extId: return True return False def compare(isamAppliance1, isamAppliance2): ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) if ret_obj1['data']: del ret_obj1['data'][0]['date'] if ret_obj2['data']: del ret_obj2['data'][0]['date'] return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2, deleted_keys=['date'])
true
true
f714b043ee7c349b87647ed2e5e6463196b1863f
946
py
Python
ccobra/benchmark/__init__.py
CognitiveComputationLab/orca
432753acff6072c158047000111a66f822aa51f3
[ "MIT" ]
9
2019-03-19T08:51:55.000Z
2021-08-19T13:29:54.000Z
ccobra/benchmark/__init__.py
CognitiveComputationLab/orca
432753acff6072c158047000111a66f822aa51f3
[ "MIT" ]
16
2018-11-27T13:30:34.000Z
2020-06-02T14:15:12.000Z
ccobra/benchmark/__init__.py
CognitiveComputationLab/orca
432753acff6072c158047000111a66f822aa51f3
[ "MIT" ]
6
2018-10-15T13:27:44.000Z
2021-08-19T13:29:56.000Z
""" CCOBRA benchmark functionality. .. rubric:: Submodules .. autosummary:: :toctree: _autosummary ccobra.benchmark.comparators .. rubric:: Functions .. autofunction:: dir_context .. autofunction:: entry_point .. autofunction:: fix_model_path .. autofunction:: fix_rel_path .. autofunction:: main .. autofunction:: parse_arguments .. autofunction:: silence_stdout .. rubric:: Classes .. autoclass:: Benchmark :members: .. autoclass:: ModelInfo :members: .. autoclass:: Evaluator :members: .. autoclass:: ModelImporter :members: .. autoclass:: EvaluationHandler :members: """ from . import comparators from .benchmark import Benchmark, ModelInfo, fix_rel_path, fix_model_path from .contextmanager import dir_context from .evaluator import Evaluator from .modelimporter import ModelImporter from .runner import entry_point, parse_arguments, main, silence_stdout from .evaluation_handler import EvaluationHandler
22
73
0.758985
from . import comparators from .benchmark import Benchmark, ModelInfo, fix_rel_path, fix_model_path from .contextmanager import dir_context from .evaluator import Evaluator from .modelimporter import ModelImporter from .runner import entry_point, parse_arguments, main, silence_stdout from .evaluation_handler import EvaluationHandler
true
true
f714b118c400442b20844c9947d561af1f2c1a2b
1,990
py
Python
kochira/services/web/google.py
gnowxilef/kochira
817b82ad0f0893a58e8d44f8db79ddd6fc0eae77
[ "MS-PL" ]
null
null
null
kochira/services/web/google.py
gnowxilef/kochira
817b82ad0f0893a58e8d44f8db79ddd6fc0eae77
[ "MS-PL" ]
null
null
null
kochira/services/web/google.py
gnowxilef/kochira
817b82ad0f0893a58e8d44f8db79ddd6fc0eae77
[ "MS-PL" ]
null
null
null
""" Google web search. Run queries on Google and return results. """ import requests from kochira import config from kochira.service import Service, background, Config, coroutine from kochira.userdata import UserData service = Service(__name__, __doc__) @service.config class Config(Config): api_key = config.Field(doc="Google API key.") cx = config.Field(doc="Custom search engine ID.") @service.command(r"!g (?P<term>.+?)$") @service.command(r"(?:search for|google) (?P<term>.+?)\??$", mention=True) @background def search(ctx, term): """ Google. Search for the given terms on Google. """ r = requests.get( "https://www.googleapis.com/customsearch/v1", params={ "key": ctx.config.api_key, "cx": ctx.config.cx, "q": term } ).json() results = r.get("items", []) if not results: ctx.respond(ctx._("Couldn't find anything matching \"{term}\".").format(term=term)) return total = len(results) ctx.respond(ctx._("({num} of {total}) {title}: {url}").format( title=results[0]["title"], url=results[0]["link"], num=1, total=total )) @service.command(r"!image (?P<term>.+?)$") @service.command(r"image(?: for)? (?P<term>.+?)\??$", mention=True) @background def image(ctx, term): """ Image search. Search for the given terms on Google. """ r = requests.get( "https://www.googleapis.com/customsearch/v1", params={ "key": ctx.config.api_key, "cx": ctx.config.cx, "searchType": "image", "q": term } ).json() results = r.get("items", []) if not results: ctx.respond(ctx._("Couldn't find anything matching \"{term}\".").format(term=term)) return total = len(results) ctx.respond(ctx._("({num} of {total}) {url}").format( url=results[0]["link"], num=1, total=total ))
22.359551
91
0.566834
import requests from kochira import config from kochira.service import Service, background, Config, coroutine from kochira.userdata import UserData service = Service(__name__, __doc__) @service.config class Config(Config): api_key = config.Field(doc="Google API key.") cx = config.Field(doc="Custom search engine ID.") @service.command(r"!g (?P<term>.+?)$") @service.command(r"(?:search for|google) (?P<term>.+?)\??$", mention=True) @background def search(ctx, term): r = requests.get( "https://www.googleapis.com/customsearch/v1", params={ "key": ctx.config.api_key, "cx": ctx.config.cx, "q": term } ).json() results = r.get("items", []) if not results: ctx.respond(ctx._("Couldn't find anything matching \"{term}\".").format(term=term)) return total = len(results) ctx.respond(ctx._("({num} of {total}) {title}: {url}").format( title=results[0]["title"], url=results[0]["link"], num=1, total=total )) @service.command(r"!image (?P<term>.+?)$") @service.command(r"image(?: for)? (?P<term>.+?)\??$", mention=True) @background def image(ctx, term): r = requests.get( "https://www.googleapis.com/customsearch/v1", params={ "key": ctx.config.api_key, "cx": ctx.config.cx, "searchType": "image", "q": term } ).json() results = r.get("items", []) if not results: ctx.respond(ctx._("Couldn't find anything matching \"{term}\".").format(term=term)) return total = len(results) ctx.respond(ctx._("({num} of {total}) {url}").format( url=results[0]["link"], num=1, total=total ))
true
true
f714b283ab9ae54ec531e9b15a6b3c7e23e726ab
1,561
py
Python
Datacamp Assignments/Data Engineer Track/8. Introduction to AWS Boto in Python/19_sns_create_multiple_topics.py
Ali-Parandeh/Data_Science_Playground
c529e9b3692381572de259e7c93938d6611d83da
[ "MIT" ]
null
null
null
Datacamp Assignments/Data Engineer Track/8. Introduction to AWS Boto in Python/19_sns_create_multiple_topics.py
Ali-Parandeh/Data_Science_Playground
c529e9b3692381572de259e7c93938d6611d83da
[ "MIT" ]
null
null
null
Datacamp Assignments/Data Engineer Track/8. Introduction to AWS Boto in Python/19_sns_create_multiple_topics.py
Ali-Parandeh/Data_Science_Playground
c529e9b3692381572de259e7c93938d6611d83da
[ "MIT" ]
1
2021-03-10T09:40:05.000Z
2021-03-10T09:40:05.000Z
# Creating multiple topics # Sam suddenly became a black sheep because she is responsible for # an onslaught of text messages and notifications to department directors. # No one will go to lunch with her anymore! # To fix this, she decided to create a general topic per # department for routine notifications, and a critical topic for urgent notifications. # Managers will subscribe only to critical notifications, # while supervisors can monitor general notifications. # For example, the streets department would have # 'streets_general' and 'streets_critical' as topics. # She has initialized the SNS client and # stored it in the sns variable. # Help Sam create a tiered topic structure... and have friends again! # Create list of departments departments = ['trash', 'streets', 'water'] for dept in departments: # For every department, create a general topic sns.create_topic(Name="{}_general".format(dept)) # For every department, create a critical topic sns.create_topic(Name="{}_critical".format(dept)) # Print all the topics in SNS response = sns.list_topics() print(response['Topics']) # <script.py> output: # [{'TopicArn': 'arn:aws:sns:us-east-1:123456789012:trash_general'}, {'TopicArn': 'arn:aws:sns:us-east-1:123456789012:trash_critical'}, {'TopicArn': 'arn:aws:sns:us-east-1:123456789012:streets_general'}, {'TopicArn': 'arn:aws:sns:us-east-1:123456789012:streets_critical'}, {'TopicArn': 'arn:aws:sns:us-east-1:123456789012:water_general'}, {'TopicArn': 'arn:aws:sns:us-east-1:123456789012:water_critical'}]
42.189189
409
0.748238
departments = ['trash', 'streets', 'water'] for dept in departments: sns.create_topic(Name="{}_general".format(dept)) sns.create_topic(Name="{}_critical".format(dept)) response = sns.list_topics() print(response['Topics'])
true
true
f714b3e8a0b13082e466e7c61be4a203a48afe3f
889
py
Python
server/utils/view_utils.py
Jordonkopp/Flask-Vue
db842f1a31f2ca4cf51ce1b2a927d6d2ad860c00
[ "MIT" ]
2
2019-02-27T16:55:01.000Z
2019-02-27T20:23:29.000Z
server/utils/view_utils.py
Jordonkopp/Flask-Vue
db842f1a31f2ca4cf51ce1b2a927d6d2ad860c00
[ "MIT" ]
5
2020-04-30T00:01:01.000Z
2021-10-05T19:42:15.000Z
server/utils/view_utils.py
Jordonkopp/Flask-Vue
db842f1a31f2ca4cf51ce1b2a927d6d2ad860c00
[ "MIT" ]
null
null
null
from typing import Tuple, List from flask import jsonify from flask.wrappers import Response def wrapped_response(data: dict = None, status: int = 200, message: str = "") -> Tuple[Response, int]: """ Create a wrapped response to have uniform json response objects """ if type(data) is not dict and data is not None: raise TypeError("Expected data to be type Dictionary") response = { "success": 200 <= status < 300, "code": status, "message": message, "result": data, } return jsonify(response), status def serialize_list(items: List) -> List: """Serializes a list of SQLAlchemy Objects, exposing their attributes. :param items - List of Objects that inherit from Mixin :returns List of dictionaries """ if not items or items is None: return [] return [x.to_dict() for x in items]
26.939394
102
0.649044
from typing import Tuple, List from flask import jsonify from flask.wrappers import Response def wrapped_response(data: dict = None, status: int = 200, message: str = "") -> Tuple[Response, int]: if type(data) is not dict and data is not None: raise TypeError("Expected data to be type Dictionary") response = { "success": 200 <= status < 300, "code": status, "message": message, "result": data, } return jsonify(response), status def serialize_list(items: List) -> List: if not items or items is None: return [] return [x.to_dict() for x in items]
true
true
f714b4d3fcbc5ab3998518dc08e155b098493405
10,591
py
Python
aws/AWSError.py
alexbredo/honeypot-s3
f90c21e34b2c3079656a027cab9dc0cf7b2945c9
[ "BSD-2-Clause" ]
null
null
null
aws/AWSError.py
alexbredo/honeypot-s3
f90c21e34b2c3079656a027cab9dc0cf7b2945c9
[ "BSD-2-Clause" ]
null
null
null
aws/AWSError.py
alexbredo/honeypot-s3
f90c21e34b2c3079656a027cab9dc0cf7b2945c9
[ "BSD-2-Clause" ]
null
null
null
# Copyright (c) 2014 Alexander Bredo # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the # following conditions are met: # # 1. Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # -*- coding: utf-8 -*- defAWSerrors = dict() defAWSerrors["AccessDenied"] = ("Access Denied",403) defAWSerrors["AccountProblem"] = ("There is a problem with your AWS account that prevents the operation from completing successfully. Please use Contact Us.",403) defAWSerrors["AmbiguousGrantByEmailAddress"] = ("The e-mail address you provided is associated with more than one account.",400) defAWSerrors["BadDigest"] = ("The Content-MD5 you specified did not match what we received.",400) defAWSerrors["BucketAlreadyExists"] = ("The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.",409) defAWSerrors["BucketAlreadyOwnedByYou"] = ("Your previous request to create the named bucket succeeded and you already own it.",409) defAWSerrors["BucketNotEmpty"] = ("The bucket you tried to delete is not empty.",409) defAWSerrors["CredentialsNotSupported"] = ("This request does not support credentials.",400) defAWSerrors["CrossLocationLoggingProhibited"] = ("Cross location logging not allowed. Buckets in one geographic location cannot log information to a bucket in another location.",403) defAWSerrors["EntityTooSmall"] = ("Your proposed upload is smaller than the minimum allowed object size.",400) defAWSerrors["EntityTooLarge"] = ("Your proposed upload exceeds the maximum allowed object size.",400) defAWSerrors["ExpiredToken"] = ("The provided token has expired.",400) defAWSerrors["IllegalVersioningConfigurationException"] = ("Indicates that the Versioning configuration specified in the request is invalid.",400) defAWSerrors["IncompleteBody"] = ("You did not provide the number of bytes specified by the Content-Length HTTP header",400) defAWSerrors["IncorrectNumberOfFilesInPostRequest"] = ("POST requires exactly one file upload per request.",400) defAWSerrors["InlineDataTooLarge"] = ("Inline data exceeds the maximum allowed size.",400) defAWSerrors["InternalError"] = ("We encountered an internal error. Please try again.","500 Internal Server Error") defAWSerrors["InvalidAccessKeyId"] = ("The AWS Access Key Id you provided does not exist in our records.",403) defAWSerrors["InvalidAddressingHeader"] = ("You must specify the Anonymous role.",400) defAWSerrors["InvalidArgument"] = ("Invalid Argument",400) defAWSerrors["InvalidBucketName"] = ("The specified bucket is not valid.",400) defAWSerrors["InvalidBucketState"] = ("The request is not valid with the current state of the bucket.",409) defAWSerrors["InvalidDigest"] = ("The Content-MD5 you specified was an invalid.",400) defAWSerrors["InvalidLocationConstraint"] = ("The specified location constraint is not valid. For more information about Regions, see How to Select a Region for Your Buckets.",400) defAWSerrors["InvalidObjectState"] = ("The operation is not valid for the current state of the object.",403) defAWSerrors["InvalidPart"] = ("One or more of the specified parts could not be found. The part might not have been uploaded, or the specified entity tag might not have matched the part's entity tag.",400) defAWSerrors["InvalidPartOrder"] = ("The list of parts was not in ascending order.Parts list must specified in order by part number.",400) defAWSerrors["InvalidPayer"] = ("All access to this object has been disabled.",403) defAWSerrors["InvalidPolicyDocument"] = ("The content of the form does not meet the conditions specified in the policy document.",400) defAWSerrors["InvalidRange"] = ("The requested range cannot be satisfied.",416) defAWSerrors["InvalidRequest"] = ("SOAP requests must be made over an HTTPS connection.",400) defAWSerrors["InvalidSecurity"] = ("The provided security credentials are not valid.",403) defAWSerrors["InvalidSOAPRequest"] = ("The SOAP request body is invalid.",400) defAWSerrors["InvalidStorageClass"] = ("The storage class you specified is not valid.",400) defAWSerrors["InvalidTargetBucketForLogging"] = ("The target bucket for logging does not exist, is not owned by you, or does not have the appropriate grants for the log-delivery group.",400) defAWSerrors["InvalidToken"] = ("The provided token is malformed or otherwise invalid.",400) defAWSerrors["InvalidURI"] = ("Couldn't parse the specified URI.",400) defAWSerrors["KeyTooLong"] = ("Your key is too long.",400) defAWSerrors["MalformedACLError"] = ("The XML you provided was not well-formed or did not validate against our published schema.",400) defAWSerrors["MalformedPOSTRequest"] = ("The body of your POST request is not well-formed multipart/form-data.",400) defAWSerrors["MalformedXML"] = ("This happens when the user sends a malformed xml (xml that doesn't conform to the published xsd) for the configuration. The error message is: The XML you provided was not well-formed or did not validate against our published schema.",400) defAWSerrors["MaxMessageLengthExceeded"] = ("Your request was too big.",400) defAWSerrors["MaxPostPreDataLengthExceededError"] = ("Your POST request fields preceding the upload file were too large.",400) defAWSerrors["MetadataTooLarge"] = ("Your metadata headers exceed the maximum allowed metadata size.",400) defAWSerrors["MethodNotAllowed"] = ("The specified method is not allowed against this resource.",405) defAWSerrors["MissingAttachment"] = ("A SOAP attachment was expected, but none were found.",400) defAWSerrors["MissingContentLength"] = ("You must provide the Content-Length HTTP header.",411) defAWSerrors["MissingRequestBodyError"] = ("This happens when the user sends an empty xml document as a request. The error message is: Request body is empty.",400) defAWSerrors["MissingSecurityElement"] = ("The SOAP 1.1 request is missing a security element.",400) defAWSerrors["MissingSecurityHeader"] = ("Your request was missing a required header.",400) defAWSerrors["NoLoggingStatusForKey"] = ("There is no such thing as a logging status sub-resource for a key.",400) defAWSerrors["NoSuchBucket"] = ("The specified bucket does not exist.",404) defAWSerrors["NoSuchKey"] = ("The specified key does not exist.",404) defAWSerrors["NoSuchLifecycleConfiguration"] = ("The lifecycle configuration does not exist.",404) defAWSerrors["NoSuchUpload"] = ("The specified multipart upload does not exist. The upload ID might be invalid, or the multipart upload might have been aborted or completed.",404) defAWSerrors["NoSuchVersion"] = ("Indicates that the version ID specified in the request does not match an existing version.",404) defAWSerrors["NotImplemented"] = ("A header you provided implies functionality that is not implemented.",501) defAWSerrors["NotSignedUp"] = ("Your account is not signed up for the S3 service. You must sign up before you can use S3.",403) defAWSerrors["NotSuchBucketPolicy"] = ("The specified bucket does not have a bucket policy.",404) defAWSerrors["OperationAborted"] = ("A conflicting conditional operation is currently in progress against this resource. Please try again.",409) defAWSerrors["PermanentRedirect"] = ("The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.",301) defAWSerrors["PreconditionFailed"] = ("At least one of the preconditions you specified did not hold.",412) defAWSerrors["Redirect"] = ("Temporary redirect.",307) defAWSerrors["RestoreAlreadyInProgress"] = ("Object restore is already in progress.",409) defAWSerrors["RequestIsNotMultiPartContent"] = ("Bucket POST must be of the enclosure-type multipart/form-data.",400) defAWSerrors["RequestTimeout"] = ("Your socket connection to the server was not read from or written to within the timeout period.",400) defAWSerrors["RequestTimeTooSkewed"] = ("The difference between the request time and the server's time is too large.",403) defAWSerrors["RequestTorrentOfBucketError"] = ("Requesting the torrent file of a bucket is not permitted.",400) defAWSerrors["SignatureDoesNotMatch"] = ("The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. For more information, see REST Authentication and SOAP Authentication for details.",403) defAWSerrors["ServiceUnavailable"] = ("Please reduce your request rate.",503) defAWSerrors["SlowDown"] = ("Please reduce your request rate.",503) defAWSerrors["TemporaryRedirect"] = ("You are being redirected to the bucket while DNS updates.",307) defAWSerrors["TokenRefreshRequired"] = ("The provided token must be refreshed.",400) defAWSerrors["TooManyBuckets"] = ("You have attempted to create more buckets than allowed.",400) defAWSerrors["UnexpectedContent"] = ("This request does not support content.",400) defAWSerrors["UnresolvableGrantByEmailAddress"] = ("The e-mail address you provided does not match any account on record.",400) defAWSerrors["UserKeyMustBeSpecified"] = ("The bucket POST must contain the specified field name. If it is specified, please check the order of the fields.",400) class AWSError(): def __init__(self, key): if key in defAWSerrors.keys(): self.key = key else: self.key = 'AccountProblem' def getKey(self): return self.key def getMessage(self): return defAWSerrors[self.key][0] def getCode(self): return defAWSerrors[self.key][1]
82.742188
271
0.775942
defAWSerrors = dict() defAWSerrors["AccessDenied"] = ("Access Denied",403) defAWSerrors["AccountProblem"] = ("There is a problem with your AWS account that prevents the operation from completing successfully. Please use Contact Us.",403) defAWSerrors["AmbiguousGrantByEmailAddress"] = ("The e-mail address you provided is associated with more than one account.",400) defAWSerrors["BadDigest"] = ("The Content-MD5 you specified did not match what we received.",400) defAWSerrors["BucketAlreadyExists"] = ("The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.",409) defAWSerrors["BucketAlreadyOwnedByYou"] = ("Your previous request to create the named bucket succeeded and you already own it.",409) defAWSerrors["BucketNotEmpty"] = ("The bucket you tried to delete is not empty.",409) defAWSerrors["CredentialsNotSupported"] = ("This request does not support credentials.",400) defAWSerrors["CrossLocationLoggingProhibited"] = ("Cross location logging not allowed. Buckets in one geographic location cannot log information to a bucket in another location.",403) defAWSerrors["EntityTooSmall"] = ("Your proposed upload is smaller than the minimum allowed object size.",400) defAWSerrors["EntityTooLarge"] = ("Your proposed upload exceeds the maximum allowed object size.",400) defAWSerrors["ExpiredToken"] = ("The provided token has expired.",400) defAWSerrors["IllegalVersioningConfigurationException"] = ("Indicates that the Versioning configuration specified in the request is invalid.",400) defAWSerrors["IncompleteBody"] = ("You did not provide the number of bytes specified by the Content-Length HTTP header",400) defAWSerrors["IncorrectNumberOfFilesInPostRequest"] = ("POST requires exactly one file upload per request.",400) defAWSerrors["InlineDataTooLarge"] = ("Inline data exceeds the maximum allowed size.",400) defAWSerrors["InternalError"] = ("We encountered an internal error. Please try again.","500 Internal Server Error") defAWSerrors["InvalidAccessKeyId"] = ("The AWS Access Key Id you provided does not exist in our records.",403) defAWSerrors["InvalidAddressingHeader"] = ("You must specify the Anonymous role.",400) defAWSerrors["InvalidArgument"] = ("Invalid Argument",400) defAWSerrors["InvalidBucketName"] = ("The specified bucket is not valid.",400) defAWSerrors["InvalidBucketState"] = ("The request is not valid with the current state of the bucket.",409) defAWSerrors["InvalidDigest"] = ("The Content-MD5 you specified was an invalid.",400) defAWSerrors["InvalidLocationConstraint"] = ("The specified location constraint is not valid. For more information about Regions, see How to Select a Region for Your Buckets.",400) defAWSerrors["InvalidObjectState"] = ("The operation is not valid for the current state of the object.",403) defAWSerrors["InvalidPart"] = ("One or more of the specified parts could not be found. The part might not have been uploaded, or the specified entity tag might not have matched the part's entity tag.",400) defAWSerrors["InvalidPartOrder"] = ("The list of parts was not in ascending order.Parts list must specified in order by part number.",400) defAWSerrors["InvalidPayer"] = ("All access to this object has been disabled.",403) defAWSerrors["InvalidPolicyDocument"] = ("The content of the form does not meet the conditions specified in the policy document.",400) defAWSerrors["InvalidRange"] = ("The requested range cannot be satisfied.",416) defAWSerrors["InvalidRequest"] = ("SOAP requests must be made over an HTTPS connection.",400) defAWSerrors["InvalidSecurity"] = ("The provided security credentials are not valid.",403) defAWSerrors["InvalidSOAPRequest"] = ("The SOAP request body is invalid.",400) defAWSerrors["InvalidStorageClass"] = ("The storage class you specified is not valid.",400) defAWSerrors["InvalidTargetBucketForLogging"] = ("The target bucket for logging does not exist, is not owned by you, or does not have the appropriate grants for the log-delivery group.",400) defAWSerrors["InvalidToken"] = ("The provided token is malformed or otherwise invalid.",400) defAWSerrors["InvalidURI"] = ("Couldn't parse the specified URI.",400) defAWSerrors["KeyTooLong"] = ("Your key is too long.",400) defAWSerrors["MalformedACLError"] = ("The XML you provided was not well-formed or did not validate against our published schema.",400) defAWSerrors["MalformedPOSTRequest"] = ("The body of your POST request is not well-formed multipart/form-data.",400) defAWSerrors["MalformedXML"] = ("This happens when the user sends a malformed xml (xml that doesn't conform to the published xsd) for the configuration. The error message is: The XML you provided was not well-formed or did not validate against our published schema.",400) defAWSerrors["MaxMessageLengthExceeded"] = ("Your request was too big.",400) defAWSerrors["MaxPostPreDataLengthExceededError"] = ("Your POST request fields preceding the upload file were too large.",400) defAWSerrors["MetadataTooLarge"] = ("Your metadata headers exceed the maximum allowed metadata size.",400) defAWSerrors["MethodNotAllowed"] = ("The specified method is not allowed against this resource.",405) defAWSerrors["MissingAttachment"] = ("A SOAP attachment was expected, but none were found.",400) defAWSerrors["MissingContentLength"] = ("You must provide the Content-Length HTTP header.",411) defAWSerrors["MissingRequestBodyError"] = ("This happens when the user sends an empty xml document as a request. The error message is: Request body is empty.",400) defAWSerrors["MissingSecurityElement"] = ("The SOAP 1.1 request is missing a security element.",400) defAWSerrors["MissingSecurityHeader"] = ("Your request was missing a required header.",400) defAWSerrors["NoLoggingStatusForKey"] = ("There is no such thing as a logging status sub-resource for a key.",400) defAWSerrors["NoSuchBucket"] = ("The specified bucket does not exist.",404) defAWSerrors["NoSuchKey"] = ("The specified key does not exist.",404) defAWSerrors["NoSuchLifecycleConfiguration"] = ("The lifecycle configuration does not exist.",404) defAWSerrors["NoSuchUpload"] = ("The specified multipart upload does not exist. The upload ID might be invalid, or the multipart upload might have been aborted or completed.",404) defAWSerrors["NoSuchVersion"] = ("Indicates that the version ID specified in the request does not match an existing version.",404) defAWSerrors["NotImplemented"] = ("A header you provided implies functionality that is not implemented.",501) defAWSerrors["NotSignedUp"] = ("Your account is not signed up for the S3 service. You must sign up before you can use S3.",403) defAWSerrors["NotSuchBucketPolicy"] = ("The specified bucket does not have a bucket policy.",404) defAWSerrors["OperationAborted"] = ("A conflicting conditional operation is currently in progress against this resource. Please try again.",409) defAWSerrors["PermanentRedirect"] = ("The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.",301) defAWSerrors["PreconditionFailed"] = ("At least one of the preconditions you specified did not hold.",412) defAWSerrors["Redirect"] = ("Temporary redirect.",307) defAWSerrors["RestoreAlreadyInProgress"] = ("Object restore is already in progress.",409) defAWSerrors["RequestIsNotMultiPartContent"] = ("Bucket POST must be of the enclosure-type multipart/form-data.",400) defAWSerrors["RequestTimeout"] = ("Your socket connection to the server was not read from or written to within the timeout period.",400) defAWSerrors["RequestTimeTooSkewed"] = ("The difference between the request time and the server's time is too large.",403) defAWSerrors["RequestTorrentOfBucketError"] = ("Requesting the torrent file of a bucket is not permitted.",400) defAWSerrors["SignatureDoesNotMatch"] = ("The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. For more information, see REST Authentication and SOAP Authentication for details.",403) defAWSerrors["ServiceUnavailable"] = ("Please reduce your request rate.",503) defAWSerrors["SlowDown"] = ("Please reduce your request rate.",503) defAWSerrors["TemporaryRedirect"] = ("You are being redirected to the bucket while DNS updates.",307) defAWSerrors["TokenRefreshRequired"] = ("The provided token must be refreshed.",400) defAWSerrors["TooManyBuckets"] = ("You have attempted to create more buckets than allowed.",400) defAWSerrors["UnexpectedContent"] = ("This request does not support content.",400) defAWSerrors["UnresolvableGrantByEmailAddress"] = ("The e-mail address you provided does not match any account on record.",400) defAWSerrors["UserKeyMustBeSpecified"] = ("The bucket POST must contain the specified field name. If it is specified, please check the order of the fields.",400) class AWSError(): def __init__(self, key): if key in defAWSerrors.keys(): self.key = key else: self.key = 'AccountProblem' def getKey(self): return self.key def getMessage(self): return defAWSerrors[self.key][0] def getCode(self): return defAWSerrors[self.key][1]
true
true
f714b5c9364ae37e0f28ed2af63d9c13870280d8
4,361
py
Python
third_party/mosquitto/test/broker/06-bridge-per-listener-settings.py
HowJMay/simple-tangle-accelerator
d79bfda23a0fcf67d5a7f9e66f02efa3e73ba381
[ "MIT" ]
null
null
null
third_party/mosquitto/test/broker/06-bridge-per-listener-settings.py
HowJMay/simple-tangle-accelerator
d79bfda23a0fcf67d5a7f9e66f02efa3e73ba381
[ "MIT" ]
null
null
null
third_party/mosquitto/test/broker/06-bridge-per-listener-settings.py
HowJMay/simple-tangle-accelerator
d79bfda23a0fcf67d5a7f9e66f02efa3e73ba381
[ "MIT" ]
1
2021-05-04T16:09:27.000Z
2021-05-04T16:09:27.000Z
#!/usr/bin/env python3 # Test remapping of topic name for incoming message from mosq_test_helper import * def write_config(filename, port1, port2, port3): with open(filename, 'w') as f: f.write("per_listener_settings true\n") f.write("port %d\n" % (port2)) f.write("listener %d 127.0.0.1\n" % (port3)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("bridge_attempt_unsubscribe false\n") f.write("topic # in 0 local/topic/ remote/topic/\n") f.write("topic prefix/# in 0 local2/topic/ remote2/topic/\n") f.write("topic +/value in 0 local3/topic/ remote3/topic/\n") f.write("topic ic/+ in 0 local4/top remote4/tip\n") f.write("topic clients/total in 0 test/mosquitto/org $SYS/broker/\n") f.write("notifications false\n") f.write("restart_timeout 5\n") (port1, port2, port3) = mosq_test.get_port(3) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, port3) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) client_connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive) client_connack_packet = mosq_test.gen_connack(rc=0) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(4) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) def test(bridge, sock): if not mosq_test.expect_packet(bridge, "connect", connect_packet): return 1 bridge.send(connack_packet) mid = 0 patterns = [ "remote/topic/#", "remote2/topic/prefix/#", "remote3/topic/+/value", "remote4/tipic/+", "$SYS/broker/clients/total", ] for pattern in ("remote/topic/#", "remote2/topic/prefix/#", "remote3/topic/+/value"): mid += 1 subscribe_packet = mosq_test.gen_subscribe(mid, pattern, 0) suback_packet = mosq_test.gen_suback(mid, 0) if not mosq_test.expect_packet(bridge, "subscribe", subscribe_packet): return 1 bridge.send(suback_packet) mid += 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0) suback_packet = mosq_test.gen_suback(mid, 0) sock.send(subscribe_packet) if not mosq_test.expect_packet(sock, "suback", suback_packet): return 1 cases = [ ('local/topic/something', 'remote/topic/something'), ('local/topic/some/t/h/i/n/g', 'remote/topic/some/t/h/i/n/g'), ('local/topic/value', 'remote/topic/value'), # Don't work, #40 must be fixed before # ('local/topic', 'remote/topic'), ('local2/topic/prefix/something', 'remote2/topic/prefix/something'), ('local3/topic/something/value', 'remote3/topic/something/value'), ('local4/topic/something', 'remote4/tipic/something'), ('test/mosquitto/orgclients/total', '$SYS/broker/clients/total'), ] for (local_topic, remote_topic) in cases: mid += 1 remote_publish_packet = mosq_test.gen_publish( remote_topic, qos=0, mid=mid, payload='' ) local_publish_packet = mosq_test.gen_publish( local_topic, qos=0, mid=mid, payload='' ) bridge.send(remote_publish_packet) match = mosq_test.expect_packet(sock, "publish", local_publish_packet) if not match: print("Fail on cases local_topic=%r, remote_topic=%r" % ( local_topic, remote_topic, )) return 1 return 0 try: (bridge, address) = ssock.accept() bridge.settimeout(2) sock = mosq_test.do_client_connect( client_connect_packet, client_connack_packet, port=port2, ) rc = test(bridge, sock) sock.close() bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc)
33.037879
108
0.64343
from mosq_test_helper import * def write_config(filename, port1, port2, port3): with open(filename, 'w') as f: f.write("per_listener_settings true\n") f.write("port %d\n" % (port2)) f.write("listener %d 127.0.0.1\n" % (port3)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (port1)) f.write("bridge_attempt_unsubscribe false\n") f.write("topic # in 0 local/topic/ remote/topic/\n") f.write("topic prefix/# in 0 local2/topic/ remote2/topic/\n") f.write("topic +/value in 0 local3/topic/ remote3/topic/\n") f.write("topic ic/+ in 0 local4/top remote4/tip\n") f.write("topic clients/total in 0 test/mosquitto/org $SYS/broker/\n") f.write("notifications false\n") f.write("restart_timeout 5\n") (port1, port2, port3) = mosq_test.get_port(3) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, port3) rc = 1 keepalive = 60 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=128+4) connack_packet = mosq_test.gen_connack(rc=0) client_connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive) client_connack_packet = mosq_test.gen_connack(rc=0) ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssock.settimeout(4) ssock.bind(('', port1)) ssock.listen(5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) def test(bridge, sock): if not mosq_test.expect_packet(bridge, "connect", connect_packet): return 1 bridge.send(connack_packet) mid = 0 patterns = [ "remote/topic/#", "remote2/topic/prefix/#", "remote3/topic/+/value", "remote4/tipic/+", "$SYS/broker/clients/total", ] for pattern in ("remote/topic/#", "remote2/topic/prefix/#", "remote3/topic/+/value"): mid += 1 subscribe_packet = mosq_test.gen_subscribe(mid, pattern, 0) suback_packet = mosq_test.gen_suback(mid, 0) if not mosq_test.expect_packet(bridge, "subscribe", subscribe_packet): return 1 bridge.send(suback_packet) mid += 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0) suback_packet = mosq_test.gen_suback(mid, 0) sock.send(subscribe_packet) if not mosq_test.expect_packet(sock, "suback", suback_packet): return 1 cases = [ ('local/topic/something', 'remote/topic/something'), ('local/topic/some/t/h/i/n/g', 'remote/topic/some/t/h/i/n/g'), ('local/topic/value', 'remote/topic/value'), # ('local/topic', 'remote/topic'), ('local2/topic/prefix/something', 'remote2/topic/prefix/something'), ('local3/topic/something/value', 'remote3/topic/something/value'), ('local4/topic/something', 'remote4/tipic/something'), ('test/mosquitto/orgclients/total', '$SYS/broker/clients/total'), ] for (local_topic, remote_topic) in cases: mid += 1 remote_publish_packet = mosq_test.gen_publish( remote_topic, qos=0, mid=mid, payload='' ) local_publish_packet = mosq_test.gen_publish( local_topic, qos=0, mid=mid, payload='' ) bridge.send(remote_publish_packet) match = mosq_test.expect_packet(sock, "publish", local_publish_packet) if not match: print("Fail on cases local_topic=%r, remote_topic=%r" % ( local_topic, remote_topic, )) return 1 return 0 try: (bridge, address) = ssock.accept() bridge.settimeout(2) sock = mosq_test.do_client_connect( client_connect_packet, client_connack_packet, port=port2, ) rc = test(bridge, sock) sock.close() bridge.close() finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ssock.close() exit(rc)
true
true
f714b611b630264ab6b3b01d609da0098746a3ab
5,508
py
Python
data/p3BR/R1/benchmark/startQiskit_QC456.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/p3BR/R1/benchmark/startQiskit_QC456.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
data/p3BR/R1/benchmark/startQiskit_QC456.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
# qubit number=3 # total number=84 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() # oracle.draw('mpl', filename=(kernel + '-oracle.png')) return oracle def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit: # implement the Bernstein-Vazirani circuit zero = np.binary_repr(0, n) b = f(zero) # initial n + 1 bits input_qubit = QuantumRegister(n+1, "qc") classicals = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classicals) # inverse last one (can be omitted if using O_f^\pm) prog.x(input_qubit[n]) # circuit begin prog.h(input_qubit[1]) # number=1 prog.h(input_qubit[1]) # number=70 prog.rx(-0.09738937226128368,input_qubit[2]) # number=2 prog.h(input_qubit[1]) # number=33 prog.y(input_qubit[2]) # number=56 prog.cz(input_qubit[2],input_qubit[1]) # number=34 prog.h(input_qubit[1]) # number=35 prog.h(input_qubit[1]) # number=3 # apply H to get superposition for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[n]) prog.barrier() # apply oracle O_f oracle = build_oracle(n, f) prog.append( oracle.to_gate(), [input_qubit[i] for i in range(n)] + [input_qubit[n]]) # apply H back (QFT on Z_2^n) for i in range(n): prog.h(input_qubit[i]) prog.barrier() # measure return prog def get_statevector(prog: QuantumCircuit) -> Any: state_backend = Aer.get_backend('statevector_simulator') statevec = execute(prog, state_backend).result() quantum_state = statevec.get_statevector() qubits = round(log2(len(quantum_state))) quantum_state = { "|" + np.binary_repr(i, qubits) + ">": quantum_state[i] for i in range(2 ** qubits) } return quantum_state def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any: # Q: which backend should we use? # get state vector quantum_state = get_statevector(prog) # get simulate results # provider = IBMQ.load_account() # backend = provider.get_backend(backend_str) # qobj = compile(prog, backend, shots) # job = backend.run(qobj) # job.result() backend = Aer.get_backend(backend_str) # transpile/schedule -> assemble -> backend.run results = execute(prog, backend, shots=shots).result() counts = results.get_counts() a = Counter(counts).most_common(1)[0][0][::-1] return { "measurements": counts, # "state": statevec, "quantum_state": quantum_state, "a": a, "b": b } def bernstein_test_1(rep: str): """011 . x + 1""" a = "011" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_2(rep: str): """000 . x + 0""" a = "000" b = "0" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_3(rep: str): """111 . x + 1""" a = "111" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) if __name__ == "__main__": n = 2 a = "11" b = "1" f = lambda rep: \ bitwise_xor(bitwise_dot(a, rep), b) prog = build_circuit(n, f) sample_shot =4000 writefile = open("../data/startQiskit_QC456.csv", "w") # prog.draw('mpl', filename=(kernel + '.png')) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = provider.get_backend("ibmq_belem") circuit1 = transpile(prog, FakeYorktown()) circuit1.h(qubit=2) circuit1.x(qubit=3) circuit1.measure_all() info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
29.142857
140
0.629448
import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from qiskit.test.mock import FakeVigo, FakeYorktown kernel = 'circuit/bernstein' def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit: controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) return oracle def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit: zero = np.binary_repr(0, n) b = f(zero) input_qubit = QuantumRegister(n+1, "qc") classicals = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classicals) prog.x(input_qubit[n]) prog.h(input_qubit[1]) prog.h(input_qubit[1]) prog.rx(-0.09738937226128368,input_qubit[2]) prog.h(input_qubit[1]) prog.y(input_qubit[2]) prog.cz(input_qubit[2],input_qubit[1]) prog.h(input_qubit[1]) prog.h(input_qubit[1]) for i in range(n): prog.h(input_qubit[i]) prog.h(input_qubit[n]) prog.barrier() oracle = build_oracle(n, f) prog.append( oracle.to_gate(), [input_qubit[i] for i in range(n)] + [input_qubit[n]]) for i in range(n): prog.h(input_qubit[i]) prog.barrier() return prog def get_statevector(prog: QuantumCircuit) -> Any: state_backend = Aer.get_backend('statevector_simulator') statevec = execute(prog, state_backend).result() quantum_state = statevec.get_statevector() qubits = round(log2(len(quantum_state))) quantum_state = { "|" + np.binary_repr(i, qubits) + ">": quantum_state[i] for i in range(2 ** qubits) } return quantum_state def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any: quantum_state = get_statevector(prog) backend = Aer.get_backend(backend_str) results = execute(prog, backend, shots=shots).result() counts = results.get_counts() a = Counter(counts).most_common(1)[0][0][::-1] return { "measurements": counts, "quantum_state": quantum_state, "a": a, "b": b } def bernstein_test_1(rep: str): a = "011" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_2(rep: str): a = "000" b = "0" return bitwise_xor(bitwise_dot(a, rep), b) def bernstein_test_3(rep: str): a = "111" b = "1" return bitwise_xor(bitwise_dot(a, rep), b) if __name__ == "__main__": n = 2 a = "11" b = "1" f = lambda rep: \ bitwise_xor(bitwise_dot(a, rep), b) prog = build_circuit(n, f) sample_shot =4000 writefile = open("../data/startQiskit_QC456.csv", "w") IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = provider.get_backend("ibmq_belem") circuit1 = transpile(prog, FakeYorktown()) circuit1.h(qubit=2) circuit1.x(qubit=3) circuit1.measure_all() info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts() print(info, file=writefile) print("results end", file=writefile) print(circuit1.depth(), file=writefile) print(circuit1, file=writefile) writefile.close()
true
true
f714b62fb7954e13787a00829289da3e8338b36b
466
py
Python
Condicional/autonomia_aviao.py
Viniciusmgm/aula_processamento_info
6b334122896e34af51d3a8469f151bca52191585
[ "MIT" ]
null
null
null
Condicional/autonomia_aviao.py
Viniciusmgm/aula_processamento_info
6b334122896e34af51d3a8469f151bca52191585
[ "MIT" ]
null
null
null
Condicional/autonomia_aviao.py
Viniciusmgm/aula_processamento_info
6b334122896e34af51d3a8469f151bca52191585
[ "MIT" ]
null
null
null
def autonomia(carga): if(carga <= 50000): return 18000, 19800 elif(carga <= 200000): return 9000, 9900 else: return 3000, 3300 carga = int(input()) auto = autonomia(carga) ax = float(input()) ay = float(input()) bx = float(input()) by = float(input()) dist = (((bx - ax) ** 2) + ((by - ay) ** 2)) ** 0.5 print(round(dist,2)) if(auto[0] >= dist): print("SIM") elif(auto[1] >= dist): print("TALVEZ") else: print("NAO")
20.26087
51
0.551502
def autonomia(carga): if(carga <= 50000): return 18000, 19800 elif(carga <= 200000): return 9000, 9900 else: return 3000, 3300 carga = int(input()) auto = autonomia(carga) ax = float(input()) ay = float(input()) bx = float(input()) by = float(input()) dist = (((bx - ax) ** 2) + ((by - ay) ** 2)) ** 0.5 print(round(dist,2)) if(auto[0] >= dist): print("SIM") elif(auto[1] >= dist): print("TALVEZ") else: print("NAO")
true
true
f714b6d7c1ff765f98b7b868c578681f6cd0ca1a
3,763
py
Python
hail/python/hail/experimental/export_entries_by_col.py
MaxGreil/hail
4e0605b6bfd24a885a8194e8c0984b20994d3407
[ "MIT" ]
789
2016-09-05T04:14:25.000Z
2022-03-30T09:51:54.000Z
hail/python/hail/experimental/export_entries_by_col.py
MaxGreil/hail
4e0605b6bfd24a885a8194e8c0984b20994d3407
[ "MIT" ]
5,724
2016-08-29T18:58:40.000Z
2022-03-31T23:49:42.000Z
hail/python/hail/experimental/export_entries_by_col.py
MaxGreil/hail
4e0605b6bfd24a885a8194e8c0984b20994d3407
[ "MIT" ]
233
2016-08-31T20:42:38.000Z
2022-02-17T16:42:39.000Z
import hail as hl from hail.typecheck import typecheck @typecheck(mt=hl.MatrixTable, path=str, batch_size=int, bgzip=bool, header_json_in_file=bool, use_string_key_as_file_name=bool) def export_entries_by_col(mt: hl.MatrixTable, path: str, batch_size: int = 256, bgzip: bool = True, header_json_in_file: bool = True, use_string_key_as_file_name: bool = False): """Export entries of the `mt` by column as separate text files. Examples -------- >>> range_mt = hl.utils.range_matrix_table(10, 10) >>> range_mt = range_mt.annotate_entries(x = hl.rand_unif(0, 1)) >>> hl.experimental.export_entries_by_col(range_mt, 'output/cols_files') Notes ----- This function writes a directory with one file per column in `mt`. The files contain one tab-separated field (with header) for each row field and entry field in `mt`. The column fields of `mt` are written as JSON in the first line of each file, prefixed with a ``#``. The above will produce a directory at ``output/cols_files`` with the following files: .. code-block:: text $ ls -l output/cols_files total 80 -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 index.tsv -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 part-00.tsv.bgz -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 part-01.tsv.bgz -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 part-02.tsv.bgz -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 part-03.tsv.bgz -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 part-04.tsv.bgz -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 part-05.tsv.bgz -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 part-06.tsv.bgz -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 part-07.tsv.bgz -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 part-08.tsv.bgz -rw-r--r-- 1 hail-dev wheel 712 Jan 25 17:19 part-09.tsv.bgz $ zcat output/cols_files/part-00.tsv.bgz #{"col_idx":0} row_idx x 0 6.2501e-02 1 7.0083e-01 2 3.6452e-01 3 4.4170e-01 4 7.9177e-02 5 6.2392e-01 6 5.9920e-01 7 9.7540e-01 8 8.4848e-01 9 3.7423e-01 Due to overhead and file system limits related to having large numbers of open files, this function will iteratively export groups of columns. The `batch_size` parameter can control the size of these groups. Parameters ---------- mt : :class:`.MatrixTable` path : :obj:`int` Path (directory to write to. batch_size : :obj:`int` Number of columns to write per iteration. bgzip : :obj:`bool` BGZip output files. header_json_in_file : :obj:`bool` Include JSON header in each component file (if False, only written to index.tsv) """ if use_string_key_as_file_name and not (len(mt.col_key) == 1 and mt.col_key[0].dtype == hl.tstr): raise ValueError(f'parameter "use_string_key_as_file_name" requires a single string column key, found {list(mt.col_key.dtype.values())}') hl.utils.java.Env.backend().execute( hl.ir.MatrixToValueApply(mt._mir, {'name': 'MatrixExportEntriesByCol', 'parallelism': batch_size, 'path': path, 'bgzip': bgzip, 'headerJsonInFile': header_json_in_file, 'useStringKeyAsFileName': use_string_key_as_file_name}) )
43.252874
145
0.577731
import hail as hl from hail.typecheck import typecheck @typecheck(mt=hl.MatrixTable, path=str, batch_size=int, bgzip=bool, header_json_in_file=bool, use_string_key_as_file_name=bool) def export_entries_by_col(mt: hl.MatrixTable, path: str, batch_size: int = 256, bgzip: bool = True, header_json_in_file: bool = True, use_string_key_as_file_name: bool = False): if use_string_key_as_file_name and not (len(mt.col_key) == 1 and mt.col_key[0].dtype == hl.tstr): raise ValueError(f'parameter "use_string_key_as_file_name" requires a single string column key, found {list(mt.col_key.dtype.values())}') hl.utils.java.Env.backend().execute( hl.ir.MatrixToValueApply(mt._mir, {'name': 'MatrixExportEntriesByCol', 'parallelism': batch_size, 'path': path, 'bgzip': bgzip, 'headerJsonInFile': header_json_in_file, 'useStringKeyAsFileName': use_string_key_as_file_name}) )
true
true
f714b6dd34948ac4f7a89b22be5b154664dff0b8
59
py
Python
yfm/YahooFetcher/__init__.py
DanielGzgzz/yfMongo
1ac76c74e7309519d00f0c5205a3581cc6bbfffc
[ "Apache-2.0" ]
20
2017-08-29T22:54:58.000Z
2022-01-19T03:50:50.000Z
yfm/YahooFetcher/__init__.py
DanielGzgzz/yfMongo
1ac76c74e7309519d00f0c5205a3581cc6bbfffc
[ "Apache-2.0" ]
2
2020-05-19T14:12:59.000Z
2022-03-16T05:32:21.000Z
yfm/YahooFetcher/__init__.py
DanielGzgzz/yfMongo
1ac76c74e7309519d00f0c5205a3581cc6bbfffc
[ "Apache-2.0" ]
16
2017-10-31T09:10:28.000Z
2022-03-10T19:02:09.000Z
__all__ = ["YahooFetcher", "QueryBuilder"] from . import *
19.666667
42
0.694915
__all__ = ["YahooFetcher", "QueryBuilder"] from . import *
true
true
f714b70efde4cdb122c6eb564b9db6f1e30ed059
1,062
py
Python
examples/GB-Halide/ila_spec_a/all.py
pramodsu/ILA-Tools
e76bd90cf356ada8dd6f848fb377f57c83322c71
[ "MIT" ]
1
2021-11-29T03:51:27.000Z
2021-11-29T03:51:27.000Z
examples/GB-Halide/ila_spec_a/all.py
pramodsu/ILA-Tools
e76bd90cf356ada8dd6f848fb377f57c83322c71
[ "MIT" ]
1
2018-06-25T08:49:22.000Z
2018-06-25T08:49:22.000Z
examples/GB-Halide/ila_spec_a/all.py
pramodsu/ILA-Tools
e76bd90cf356ada8dd6f848fb377f57c83322c71
[ "MIT" ]
3
2018-06-26T11:31:40.000Z
2021-12-01T20:16:21.000Z
import ila from gb_arch import GBArch from gb_nxt_wri import WRI from gb_nxt_wr0 import WRU0 from gb_nxt_wr0b import WRU0b from gb_nxt_wr1 import WRU1 from gb_rdi import defNext as rdDefNext def defUSts (gb): m = gb.abst gb.pre_pix = m.reg ('pre_pix', gb.DATA_SIZE) gb.pre_pix_nxt = gb.pre_pix gb.st_ready = m.reg ('st_ready', 1) gb.st_ready_nxt = gb.st_ready gb.proc_in = m.reg ('proc_in', gb.slice_size * gb.stencil_size) gb.proc_in_nxt = gb.proc_in # Define next state function for each instruction/child-instruction def defNext (gb): WRI (gb) WRU0 (gb) WRU1 (gb) # Connect next state function to the abstraction def setNext (gb): gb.setNext () m = gb.abst m.set_next ('proc_in', gb.proc_in_nxt) m.set_next ('pre_pix', gb.pre_pix_nxt) m.set_next ('st_ready', gb.st_ready_nxt) if __name__ == '__main__': gb = GBArch () defUSts (gb) defNext (gb) rdDefNext (gb) setNext (gb) verilogFile = 'gb_verilog_all.v' gb.exportVerilog (verilogFile)
22.595745
72
0.667608
import ila from gb_arch import GBArch from gb_nxt_wri import WRI from gb_nxt_wr0 import WRU0 from gb_nxt_wr0b import WRU0b from gb_nxt_wr1 import WRU1 from gb_rdi import defNext as rdDefNext def defUSts (gb): m = gb.abst gb.pre_pix = m.reg ('pre_pix', gb.DATA_SIZE) gb.pre_pix_nxt = gb.pre_pix gb.st_ready = m.reg ('st_ready', 1) gb.st_ready_nxt = gb.st_ready gb.proc_in = m.reg ('proc_in', gb.slice_size * gb.stencil_size) gb.proc_in_nxt = gb.proc_in def defNext (gb): WRI (gb) WRU0 (gb) WRU1 (gb) def setNext (gb): gb.setNext () m = gb.abst m.set_next ('proc_in', gb.proc_in_nxt) m.set_next ('pre_pix', gb.pre_pix_nxt) m.set_next ('st_ready', gb.st_ready_nxt) if __name__ == '__main__': gb = GBArch () defUSts (gb) defNext (gb) rdDefNext (gb) setNext (gb) verilogFile = 'gb_verilog_all.v' gb.exportVerilog (verilogFile)
true
true
f714b773eeecc306dbf5f5429fa3eeef17fbdaba
58,507
py
Python
Lib/test/test_xmlrpc.py
cyyever/nogil
2607880dd93de52cf34045f1b7e850639a06c137
[ "0BSD" ]
953
2021-10-08T17:12:34.000Z
2022-03-31T18:31:50.000Z
Lib/test/test_xmlrpc.py
cyyever/nogil
2607880dd93de52cf34045f1b7e850639a06c137
[ "0BSD" ]
27
2021-10-13T20:54:09.000Z
2022-03-27T14:41:13.000Z
Lib/test/test_xmlrpc.py
cyyever/nogil
2607880dd93de52cf34045f1b7e850639a06c137
[ "0BSD" ]
42
2021-10-08T16:05:57.000Z
2022-03-18T13:06:12.000Z
import base64 import datetime import decimal import sys import time import unittest from unittest import mock import xmlrpc.client as xmlrpclib import xmlrpc.server import http.client import http, http.server import socket import threading import re import io import contextlib from test import support from test.support import socket_helper from test.support import ALWAYS_EQ, LARGEST, SMALLEST try: import gzip except ImportError: gzip = None alist = [{'astring': 'foo@bar.baz.spam', 'afloat': 7283.43, 'anint': 2**20, 'ashortlong': 2, 'anotherlist': ['.zyx.41'], 'abase64': xmlrpclib.Binary(b"my dog has fleas"), 'b64bytes': b"my dog has fleas", 'b64bytearray': bytearray(b"my dog has fleas"), 'boolean': False, 'unicode': '\u4000\u6000\u8000', 'ukey\u4000': 'regular value', 'datetime1': xmlrpclib.DateTime('20050210T11:41:23'), 'datetime2': xmlrpclib.DateTime( (2005, 2, 10, 11, 41, 23, 0, 1, -1)), 'datetime3': xmlrpclib.DateTime( datetime.datetime(2005, 2, 10, 11, 41, 23)), }] class XMLRPCTestCase(unittest.TestCase): def test_dump_load(self): dump = xmlrpclib.dumps((alist,)) load = xmlrpclib.loads(dump) self.assertEqual(alist, load[0][0]) def test_dump_bare_datetime(self): # This checks that an unwrapped datetime.date object can be handled # by the marshalling code. This can't be done via test_dump_load() # since with use_builtin_types set to 1 the unmarshaller would create # datetime objects for the 'datetime[123]' keys as well dt = datetime.datetime(2005, 2, 10, 11, 41, 23) self.assertEqual(dt, xmlrpclib.DateTime('20050210T11:41:23')) s = xmlrpclib.dumps((dt,)) result, m = xmlrpclib.loads(s, use_builtin_types=True) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), datetime.datetime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_builtin_types=False) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), xmlrpclib.DateTime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_datetime=True) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), datetime.datetime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_datetime=False) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), xmlrpclib.DateTime) self.assertIsNone(m) def test_datetime_before_1900(self): # same as before but with a date before 1900 dt = datetime.datetime(1, 2, 10, 11, 41, 23) self.assertEqual(dt, xmlrpclib.DateTime('00010210T11:41:23')) s = xmlrpclib.dumps((dt,)) result, m = xmlrpclib.loads(s, use_builtin_types=True) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), datetime.datetime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_builtin_types=False) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), xmlrpclib.DateTime) self.assertIsNone(m) def test_bug_1164912 (self): d = xmlrpclib.DateTime() ((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,), methodresponse=True)) self.assertIsInstance(new_d.value, str) # Check that the output of dumps() is still an 8-bit string s = xmlrpclib.dumps((new_d,), methodresponse=True) self.assertIsInstance(s, str) def test_newstyle_class(self): class T(object): pass t = T() t.x = 100 t.y = "Hello" ((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,))) self.assertEqual(t2, t.__dict__) def test_dump_big_long(self): self.assertRaises(OverflowError, xmlrpclib.dumps, (2**99,)) def test_dump_bad_dict(self): self.assertRaises(TypeError, xmlrpclib.dumps, ({(1,2,3): 1},)) def test_dump_recursive_seq(self): l = [1,2,3] t = [3,4,5,l] l.append(t) self.assertRaises(TypeError, xmlrpclib.dumps, (l,)) def test_dump_recursive_dict(self): d = {'1':1, '2':1} t = {'3':3, 'd':d} d['t'] = t self.assertRaises(TypeError, xmlrpclib.dumps, (d,)) def test_dump_big_int(self): if sys.maxsize > 2**31-1: self.assertRaises(OverflowError, xmlrpclib.dumps, (int(2**34),)) xmlrpclib.dumps((xmlrpclib.MAXINT, xmlrpclib.MININT)) self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MAXINT+1,)) self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MININT-1,)) def dummy_write(s): pass m = xmlrpclib.Marshaller() m.dump_int(xmlrpclib.MAXINT, dummy_write) m.dump_int(xmlrpclib.MININT, dummy_write) self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MAXINT+1, dummy_write) self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MININT-1, dummy_write) def test_dump_double(self): xmlrpclib.dumps((float(2 ** 34),)) xmlrpclib.dumps((float(xmlrpclib.MAXINT), float(xmlrpclib.MININT))) xmlrpclib.dumps((float(xmlrpclib.MAXINT + 42), float(xmlrpclib.MININT - 42))) def dummy_write(s): pass m = xmlrpclib.Marshaller() m.dump_double(xmlrpclib.MAXINT, dummy_write) m.dump_double(xmlrpclib.MININT, dummy_write) m.dump_double(xmlrpclib.MAXINT + 42, dummy_write) m.dump_double(xmlrpclib.MININT - 42, dummy_write) def test_dump_none(self): value = alist + [None] arg1 = (alist + [None],) strg = xmlrpclib.dumps(arg1, allow_none=True) self.assertEqual(value, xmlrpclib.loads(strg)[0][0]) self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,)) def test_dump_encoding(self): value = {'key\u20ac\xa4': 'value\u20ac\xa4'} strg = xmlrpclib.dumps((value,), encoding='iso-8859-15') strg = "<?xml version='1.0' encoding='iso-8859-15'?>" + strg self.assertEqual(xmlrpclib.loads(strg)[0][0], value) strg = strg.encode('iso-8859-15', 'xmlcharrefreplace') self.assertEqual(xmlrpclib.loads(strg)[0][0], value) strg = xmlrpclib.dumps((value,), encoding='iso-8859-15', methodresponse=True) self.assertEqual(xmlrpclib.loads(strg)[0][0], value) strg = strg.encode('iso-8859-15', 'xmlcharrefreplace') self.assertEqual(xmlrpclib.loads(strg)[0][0], value) methodname = 'method\u20ac\xa4' strg = xmlrpclib.dumps((value,), encoding='iso-8859-15', methodname=methodname) self.assertEqual(xmlrpclib.loads(strg)[0][0], value) self.assertEqual(xmlrpclib.loads(strg)[1], methodname) def test_dump_bytes(self): sample = b"my dog has fleas" self.assertEqual(sample, xmlrpclib.Binary(sample)) for type_ in bytes, bytearray, xmlrpclib.Binary: value = type_(sample) s = xmlrpclib.dumps((value,)) result, m = xmlrpclib.loads(s, use_builtin_types=True) (newvalue,) = result self.assertEqual(newvalue, sample) self.assertIs(type(newvalue), bytes) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_builtin_types=False) (newvalue,) = result self.assertEqual(newvalue, sample) self.assertIs(type(newvalue), xmlrpclib.Binary) self.assertIsNone(m) def test_loads_unsupported(self): ResponseError = xmlrpclib.ResponseError data = '<params><param><value><spam/></value></param></params>' self.assertRaises(ResponseError, xmlrpclib.loads, data) data = ('<params><param><value><array>' '<value><spam/></value>' '</array></value></param></params>') self.assertRaises(ResponseError, xmlrpclib.loads, data) data = ('<params><param><value><struct>' '<member><name>a</name><value><spam/></value></member>' '<member><name>b</name><value><spam/></value></member>' '</struct></value></param></params>') self.assertRaises(ResponseError, xmlrpclib.loads, data) def check_loads(self, s, value, **kwargs): dump = '<params><param><value>%s</value></param></params>' % s result, m = xmlrpclib.loads(dump, **kwargs) (newvalue,) = result self.assertEqual(newvalue, value) self.assertIs(type(newvalue), type(value)) self.assertIsNone(m) def test_load_standard_types(self): check = self.check_loads check('string', 'string') check('<string>string</string>', 'string') check('<string>𝔘𝔫𝔦𝔠𝔬𝔡𝔢 string</string>', '𝔘𝔫𝔦𝔠𝔬𝔡𝔢 string') check('<int>2056183947</int>', 2056183947) check('<int>-2056183947</int>', -2056183947) check('<i4>2056183947</i4>', 2056183947) check('<double>46093.78125</double>', 46093.78125) check('<boolean>0</boolean>', False) check('<base64>AGJ5dGUgc3RyaW5n/w==</base64>', xmlrpclib.Binary(b'\x00byte string\xff')) check('<base64>AGJ5dGUgc3RyaW5n/w==</base64>', b'\x00byte string\xff', use_builtin_types=True) check('<dateTime.iso8601>20050210T11:41:23</dateTime.iso8601>', xmlrpclib.DateTime('20050210T11:41:23')) check('<dateTime.iso8601>20050210T11:41:23</dateTime.iso8601>', datetime.datetime(2005, 2, 10, 11, 41, 23), use_builtin_types=True) check('<array><data>' '<value><int>1</int></value><value><int>2</int></value>' '</data></array>', [1, 2]) check('<struct>' '<member><name>b</name><value><int>2</int></value></member>' '<member><name>a</name><value><int>1</int></value></member>' '</struct>', {'a': 1, 'b': 2}) def test_load_extension_types(self): check = self.check_loads check('<nil/>', None) check('<ex:nil/>', None) check('<i1>205</i1>', 205) check('<i2>20561</i2>', 20561) check('<i8>9876543210</i8>', 9876543210) check('<biginteger>98765432100123456789</biginteger>', 98765432100123456789) check('<float>93.78125</float>', 93.78125) check('<bigdecimal>9876543210.0123456789</bigdecimal>', decimal.Decimal('9876543210.0123456789')) def test_get_host_info(self): # see bug #3613, this raised a TypeError transp = xmlrpc.client.Transport() self.assertEqual(transp.get_host_info("user@host.tld"), ('host.tld', [('Authorization', 'Basic dXNlcg==')], {})) def test_ssl_presence(self): try: import ssl except ImportError: has_ssl = False else: has_ssl = True try: xmlrpc.client.ServerProxy('https://localhost:9999').bad_function() except NotImplementedError: self.assertFalse(has_ssl, "xmlrpc client's error with SSL support") except OSError: self.assertTrue(has_ssl) def test_keepalive_disconnect(self): class RequestHandler(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" handled = False def do_POST(self): length = int(self.headers.get("Content-Length")) self.rfile.read(length) if self.handled: self.close_connection = True return response = xmlrpclib.dumps((5,), methodresponse=True) response = response.encode() self.send_response(http.HTTPStatus.OK) self.send_header("Content-Length", len(response)) self.end_headers() self.wfile.write(response) self.handled = True self.close_connection = False def log_message(self, format, *args): # don't clobber sys.stderr pass def run_server(): server.socket.settimeout(float(1)) # Don't hang if client fails server.handle_request() # First request and attempt at second server.handle_request() # Retried second request server = http.server.HTTPServer((socket_helper.HOST, 0), RequestHandler) self.addCleanup(server.server_close) thread = threading.Thread(target=run_server) thread.start() self.addCleanup(thread.join) url = "http://{}:{}/".format(*server.server_address) with xmlrpclib.ServerProxy(url) as p: self.assertEqual(p.method(), 5) self.assertEqual(p.method(), 5) class SimpleXMLRPCDispatcherTestCase(unittest.TestCase): class DispatchExc(Exception): """Raised inside the dispatched functions when checking for chained exceptions""" def test_call_registered_func(self): """Calls explicitly registered function""" # Makes sure any exception raised inside the function has no other # exception chained to it exp_params = 1, 2, 3 def dispatched_func(*params): raise self.DispatchExc(params) dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_function(dispatched_func) with self.assertRaises(self.DispatchExc) as exc_ctx: dispatcher._dispatch('dispatched_func', exp_params) self.assertEqual(exc_ctx.exception.args, (exp_params,)) self.assertIsNone(exc_ctx.exception.__cause__) self.assertIsNone(exc_ctx.exception.__context__) def test_call_instance_func(self): """Calls a registered instance attribute as a function""" # Makes sure any exception raised inside the function has no other # exception chained to it exp_params = 1, 2, 3 class DispatchedClass: def dispatched_func(self, *params): raise SimpleXMLRPCDispatcherTestCase.DispatchExc(params) dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_instance(DispatchedClass()) with self.assertRaises(self.DispatchExc) as exc_ctx: dispatcher._dispatch('dispatched_func', exp_params) self.assertEqual(exc_ctx.exception.args, (exp_params,)) self.assertIsNone(exc_ctx.exception.__cause__) self.assertIsNone(exc_ctx.exception.__context__) def test_call_dispatch_func(self): """Calls the registered instance's `_dispatch` function""" # Makes sure any exception raised inside the function has no other # exception chained to it exp_method = 'method' exp_params = 1, 2, 3 class TestInstance: def _dispatch(self, method, params): raise SimpleXMLRPCDispatcherTestCase.DispatchExc( method, params) dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_instance(TestInstance()) with self.assertRaises(self.DispatchExc) as exc_ctx: dispatcher._dispatch(exp_method, exp_params) self.assertEqual(exc_ctx.exception.args, (exp_method, exp_params)) self.assertIsNone(exc_ctx.exception.__cause__) self.assertIsNone(exc_ctx.exception.__context__) def test_registered_func_is_none(self): """Calls explicitly registered function which is None""" dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_function(None, name='method') with self.assertRaisesRegex(Exception, 'method'): dispatcher._dispatch('method', ('param',)) def test_instance_has_no_func(self): """Attempts to call nonexistent function on a registered instance""" dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_instance(object()) with self.assertRaisesRegex(Exception, 'method'): dispatcher._dispatch('method', ('param',)) def test_cannot_locate_func(self): """Calls a function that the dispatcher cannot locate""" dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() with self.assertRaisesRegex(Exception, 'method'): dispatcher._dispatch('method', ('param',)) class HelperTestCase(unittest.TestCase): def test_escape(self): self.assertEqual(xmlrpclib.escape("a&b"), "a&amp;b") self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b") self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b") class FaultTestCase(unittest.TestCase): def test_repr(self): f = xmlrpclib.Fault(42, 'Test Fault') self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>") self.assertEqual(repr(f), str(f)) def test_dump_fault(self): f = xmlrpclib.Fault(42, 'Test Fault') s = xmlrpclib.dumps((f,)) (newf,), m = xmlrpclib.loads(s) self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'}) self.assertEqual(m, None) s = xmlrpclib.Marshaller().dumps(f) self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s) def test_dotted_attribute(self): # this will raise AttributeError because code don't want us to use # private methods self.assertRaises(AttributeError, xmlrpc.server.resolve_dotted_attribute, str, '__add') self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title')) class DateTimeTestCase(unittest.TestCase): def test_default(self): with mock.patch('time.localtime') as localtime_mock: time_struct = time.struct_time( [2013, 7, 15, 0, 24, 49, 0, 196, 0]) localtime_mock.return_value = time_struct localtime = time.localtime() t = xmlrpclib.DateTime() self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", localtime)) def test_time(self): d = 1181399930.036952 t = xmlrpclib.DateTime(d) self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d))) def test_time_tuple(self): d = (2007,6,9,10,38,50,5,160,0) t = xmlrpclib.DateTime(d) self.assertEqual(str(t), '20070609T10:38:50') def test_time_struct(self): d = time.localtime(1181399930.036952) t = xmlrpclib.DateTime(d) self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", d)) def test_datetime_datetime(self): d = datetime.datetime(2007,1,2,3,4,5) t = xmlrpclib.DateTime(d) self.assertEqual(str(t), '20070102T03:04:05') def test_repr(self): d = datetime.datetime(2007,1,2,3,4,5) t = xmlrpclib.DateTime(d) val ="<DateTime '20070102T03:04:05' at %#x>" % id(t) self.assertEqual(repr(t), val) def test_decode(self): d = ' 20070908T07:11:13 ' t1 = xmlrpclib.DateTime() t1.decode(d) tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13)) self.assertEqual(t1, tref) t2 = xmlrpclib._datetime(d) self.assertEqual(t2, tref) def test_comparison(self): now = datetime.datetime.now() dtime = xmlrpclib.DateTime(now.timetuple()) # datetime vs. DateTime self.assertTrue(dtime == now) self.assertTrue(now == dtime) then = now + datetime.timedelta(seconds=4) self.assertTrue(then >= dtime) self.assertTrue(dtime < then) # str vs. DateTime dstr = now.strftime("%Y%m%dT%H:%M:%S") self.assertTrue(dtime == dstr) self.assertTrue(dstr == dtime) dtime_then = xmlrpclib.DateTime(then.timetuple()) self.assertTrue(dtime_then >= dstr) self.assertTrue(dstr < dtime_then) # some other types dbytes = dstr.encode('ascii') dtuple = now.timetuple() self.assertFalse(dtime == 1970) self.assertTrue(dtime != dbytes) self.assertFalse(dtime == bytearray(dbytes)) self.assertTrue(dtime != dtuple) with self.assertRaises(TypeError): dtime < float(1970) with self.assertRaises(TypeError): dtime > dbytes with self.assertRaises(TypeError): dtime <= bytearray(dbytes) with self.assertRaises(TypeError): dtime >= dtuple self.assertTrue(dtime == ALWAYS_EQ) self.assertFalse(dtime != ALWAYS_EQ) self.assertTrue(dtime < LARGEST) self.assertFalse(dtime > LARGEST) self.assertTrue(dtime <= LARGEST) self.assertFalse(dtime >= LARGEST) self.assertFalse(dtime < SMALLEST) self.assertTrue(dtime > SMALLEST) self.assertFalse(dtime <= SMALLEST) self.assertTrue(dtime >= SMALLEST) class BinaryTestCase(unittest.TestCase): # XXX What should str(Binary(b"\xff")) return? I'm choosing "\xff" # for now (i.e. interpreting the binary data as Latin-1-encoded # text). But this feels very unsatisfactory. Perhaps we should # only define repr(), and return r"Binary(b'\xff')" instead? def test_default(self): t = xmlrpclib.Binary() self.assertEqual(str(t), '') def test_string(self): d = b'\x01\x02\x03abc123\xff\xfe' t = xmlrpclib.Binary(d) self.assertEqual(str(t), str(d, "latin-1")) def test_decode(self): d = b'\x01\x02\x03abc123\xff\xfe' de = base64.encodebytes(d) t1 = xmlrpclib.Binary() t1.decode(de) self.assertEqual(str(t1), str(d, "latin-1")) t2 = xmlrpclib._binary(de) self.assertEqual(str(t2), str(d, "latin-1")) ADDR = PORT = URL = None # The evt is set twice. First when the server is ready to serve. # Second when the server has been shutdown. The user must clear # the event after it has been set the first time to catch the second set. def http_server(evt, numrequests, requestHandler=None, encoding=None): class TestInstanceClass: def div(self, x, y): return x // y def _methodHelp(self, name): if name == 'div': return 'This is the div function' class Fixture: @staticmethod def getData(): return '42' class MyXMLRPCServer(xmlrpc.server.SimpleXMLRPCServer): def get_request(self): # Ensure the socket is always non-blocking. On Linux, socket # attributes are not inherited like they are on *BSD and Windows. s, port = self.socket.accept() s.setblocking(True) return s, port if not requestHandler: requestHandler = xmlrpc.server.SimpleXMLRPCRequestHandler serv = MyXMLRPCServer(("localhost", 0), requestHandler, encoding=encoding, logRequests=False, bind_and_activate=False) try: serv.server_bind() global ADDR, PORT, URL ADDR, PORT = serv.socket.getsockname() #connect to IP address directly. This avoids socket.create_connection() #trying to connect to "localhost" using all address families, which #causes slowdown e.g. on vista which supports AF_INET6. The server listens #on AF_INET only. URL = "http://%s:%d"%(ADDR, PORT) serv.server_activate() serv.register_introspection_functions() serv.register_multicall_functions() serv.register_function(pow) serv.register_function(lambda x: x, 'têšt') @serv.register_function def my_function(): '''This is my function''' return True @serv.register_function(name='add') def _(x, y): return x + y testInstance = TestInstanceClass() serv.register_instance(testInstance, allow_dotted_names=True) evt.set() # handle up to 'numrequests' requests while numrequests > 0: serv.handle_request() numrequests -= 1 except socket.timeout: pass finally: serv.socket.close() PORT = None evt.set() def http_multi_server(evt, numrequests, requestHandler=None): class TestInstanceClass: def div(self, x, y): return x // y def _methodHelp(self, name): if name == 'div': return 'This is the div function' def my_function(): '''This is my function''' return True class MyXMLRPCServer(xmlrpc.server.MultiPathXMLRPCServer): def get_request(self): # Ensure the socket is always non-blocking. On Linux, socket # attributes are not inherited like they are on *BSD and Windows. s, port = self.socket.accept() s.setblocking(True) return s, port if not requestHandler: requestHandler = xmlrpc.server.SimpleXMLRPCRequestHandler class MyRequestHandler(requestHandler): rpc_paths = [] class BrokenDispatcher: def _marshaled_dispatch(self, data, dispatch_method=None, path=None): raise RuntimeError("broken dispatcher") serv = MyXMLRPCServer(("localhost", 0), MyRequestHandler, logRequests=False, bind_and_activate=False) serv.socket.settimeout(3) serv.server_bind() try: global ADDR, PORT, URL ADDR, PORT = serv.socket.getsockname() #connect to IP address directly. This avoids socket.create_connection() #trying to connect to "localhost" using all address families, which #causes slowdown e.g. on vista which supports AF_INET6. The server listens #on AF_INET only. URL = "http://%s:%d"%(ADDR, PORT) serv.server_activate() paths = [ "/foo", "/foo/bar", "/foo?k=v", "/foo#frag", "/foo?k=v#frag", "", "/", "/RPC2", "?k=v", "#frag", ] for path in paths: d = serv.add_dispatcher(path, xmlrpc.server.SimpleXMLRPCDispatcher()) d.register_introspection_functions() d.register_multicall_functions() d.register_function(lambda p=path: p, 'test') serv.get_dispatcher(paths[0]).register_function(pow) serv.get_dispatcher(paths[1]).register_function(lambda x,y: x+y, 'add') serv.add_dispatcher("/is/broken", BrokenDispatcher()) evt.set() # handle up to 'numrequests' requests while numrequests > 0: serv.handle_request() numrequests -= 1 except socket.timeout: pass finally: serv.socket.close() PORT = None evt.set() # This function prevents errors like: # <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error> def is_unavailable_exception(e): '''Returns True if the given ProtocolError is the product of a server-side exception caused by the 'temporarily unavailable' response sometimes given by operations on non-blocking sockets.''' # sometimes we get a -1 error code and/or empty headers try: if e.errcode == -1 or e.headers is None: return True exc_mess = e.headers.get('X-exception') except AttributeError: # Ignore OSErrors here. exc_mess = str(e) if exc_mess and 'temporarily unavailable' in exc_mess.lower(): return True def make_request_and_skipIf(condition, reason): # If we skip the test, we have to make a request because # the server created in setUp blocks expecting one to come in. if not condition: return lambda func: func def decorator(func): def make_request_and_skip(self): try: xmlrpclib.ServerProxy(URL).my_function() except (xmlrpclib.ProtocolError, OSError) as e: if not is_unavailable_exception(e): raise raise unittest.SkipTest(reason) return make_request_and_skip return decorator class BaseServerTestCase(unittest.TestCase): requestHandler = None request_count = 1 threadFunc = staticmethod(http_server) def setUp(self): # enable traceback reporting xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True self.evt = threading.Event() # start server thread to handle requests serv_args = (self.evt, self.request_count, self.requestHandler) thread = threading.Thread(target=self.threadFunc, args=serv_args) thread.start() self.addCleanup(thread.join) # wait for the server to be ready self.evt.wait() self.evt.clear() def tearDown(self): # wait on the server thread to terminate self.evt.wait() # disable traceback reporting xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False class SimpleServerTestCase(BaseServerTestCase): def test_simple1(self): try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.pow(6,8), 6**8) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_nonascii(self): start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t' end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n' try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.add(start_string, end_string), start_string + end_string) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_client_encoding(self): start_string = '\u20ac' end_string = '\xa4' try: p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15') self.assertEqual(p.add(start_string, end_string), start_string + end_string) except (xmlrpclib.ProtocolError, socket.error) as e: # ignore failures due to non-blocking socket unavailable errors. if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_nonascii_methodname(self): try: p = xmlrpclib.ServerProxy(URL, encoding='ascii') self.assertEqual(p.têšt(42), 42) except (xmlrpclib.ProtocolError, socket.error) as e: # ignore failures due to non-blocking socket unavailable errors. if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_404(self): # send POST with http.client, it should return 404 header and # 'Not Found' message. with contextlib.closing(http.client.HTTPConnection(ADDR, PORT)) as conn: conn.request('POST', '/this-is-not-valid') response = conn.getresponse() self.assertEqual(response.status, 404) self.assertEqual(response.reason, 'Not Found') def test_introspection1(self): expected_methods = set(['pow', 'div', 'my_function', 'add', 'têšt', 'system.listMethods', 'system.methodHelp', 'system.methodSignature', 'system.multicall', 'Fixture']) try: p = xmlrpclib.ServerProxy(URL) meth = p.system.listMethods() self.assertEqual(set(meth), expected_methods) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_introspection2(self): try: # test _methodHelp() p = xmlrpclib.ServerProxy(URL) divhelp = p.system.methodHelp('div') self.assertEqual(divhelp, 'This is the div function') except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) @make_request_and_skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_introspection3(self): try: # test native doc p = xmlrpclib.ServerProxy(URL) myfunction = p.system.methodHelp('my_function') self.assertEqual(myfunction, 'This is my function') except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_introspection4(self): # the SimpleXMLRPCServer doesn't support signatures, but # at least check that we can try making the call try: p = xmlrpclib.ServerProxy(URL) divsig = p.system.methodSignature('div') self.assertEqual(divsig, 'signatures not supported') except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_multicall(self): try: p = xmlrpclib.ServerProxy(URL) multicall = xmlrpclib.MultiCall(p) multicall.add(2,3) multicall.pow(6,8) multicall.div(127,42) add_result, pow_result, div_result = multicall() self.assertEqual(add_result, 2+3) self.assertEqual(pow_result, 6**8) self.assertEqual(div_result, 127//42) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_non_existing_multicall(self): try: p = xmlrpclib.ServerProxy(URL) multicall = xmlrpclib.MultiCall(p) multicall.this_is_not_exists() result = multicall() # result.results contains; # [{'faultCode': 1, 'faultString': '<class \'exceptions.Exception\'>:' # 'method "this_is_not_exists" is not supported'>}] self.assertEqual(result.results[0]['faultCode'], 1) self.assertEqual(result.results[0]['faultString'], '<class \'Exception\'>:method "this_is_not_exists" ' 'is not supported') except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_dotted_attribute(self): # Raises an AttributeError because private methods are not allowed. self.assertRaises(AttributeError, xmlrpc.server.resolve_dotted_attribute, str, '__add') self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title')) # Get the test to run faster by sending a request with test_simple1. # This avoids waiting for the socket timeout. self.test_simple1() def test_allow_dotted_names_true(self): # XXX also need allow_dotted_names_false test. server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) data = server.Fixture.getData() self.assertEqual(data, '42') def test_unicode_host(self): server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) self.assertEqual(server.add("a", "\xe9"), "a\xe9") def test_partial_post(self): # Check that a partial POST doesn't make the server loop: issue #14001. with contextlib.closing(socket.create_connection((ADDR, PORT))) as conn: conn.send('POST /RPC2 HTTP/1.0\r\n' 'Content-Length: 100\r\n\r\n' 'bye HTTP/1.1\r\n' f'Host: {ADDR}:{PORT}\r\n' 'Accept-Encoding: identity\r\n' 'Content-Length: 0\r\n\r\n'.encode('ascii')) def test_context_manager(self): with xmlrpclib.ServerProxy(URL) as server: server.add(2, 3) self.assertNotEqual(server('transport')._connection, (None, None)) self.assertEqual(server('transport')._connection, (None, None)) def test_context_manager_method_error(self): try: with xmlrpclib.ServerProxy(URL) as server: server.add(2, "a") except xmlrpclib.Fault: pass self.assertEqual(server('transport')._connection, (None, None)) class SimpleServerEncodingTestCase(BaseServerTestCase): @staticmethod def threadFunc(evt, numrequests, requestHandler=None, encoding=None): http_server(evt, numrequests, requestHandler, 'iso-8859-15') def test_server_encoding(self): start_string = '\u20ac' end_string = '\xa4' try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.add(start_string, end_string), start_string + end_string) except (xmlrpclib.ProtocolError, socket.error) as e: # ignore failures due to non-blocking socket unavailable errors. if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) class MultiPathServerTestCase(BaseServerTestCase): threadFunc = staticmethod(http_multi_server) request_count = 2 def test_path1(self): p = xmlrpclib.ServerProxy(URL+"/foo") self.assertEqual(p.pow(6,8), 6**8) self.assertRaises(xmlrpclib.Fault, p.add, 6, 8) def test_path2(self): p = xmlrpclib.ServerProxy(URL+"/foo/bar") self.assertEqual(p.add(6,8), 6+8) self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8) def test_path3(self): p = xmlrpclib.ServerProxy(URL+"/is/broken") self.assertRaises(xmlrpclib.Fault, p.add, 6, 8) def test_invalid_path(self): p = xmlrpclib.ServerProxy(URL+"/invalid") self.assertRaises(xmlrpclib.Fault, p.add, 6, 8) def test_path_query_fragment(self): p = xmlrpclib.ServerProxy(URL+"/foo?k=v#frag") self.assertEqual(p.test(), "/foo?k=v#frag") def test_path_fragment(self): p = xmlrpclib.ServerProxy(URL+"/foo#frag") self.assertEqual(p.test(), "/foo#frag") def test_path_query(self): p = xmlrpclib.ServerProxy(URL+"/foo?k=v") self.assertEqual(p.test(), "/foo?k=v") def test_empty_path(self): p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.test(), "/RPC2") def test_root_path(self): p = xmlrpclib.ServerProxy(URL + "/") self.assertEqual(p.test(), "/") def test_empty_path_query(self): p = xmlrpclib.ServerProxy(URL + "?k=v") self.assertEqual(p.test(), "?k=v") def test_empty_path_fragment(self): p = xmlrpclib.ServerProxy(URL + "#frag") self.assertEqual(p.test(), "#frag") #A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism #does indeed serve subsequent requests on the same connection class BaseKeepaliveServerTestCase(BaseServerTestCase): #a request handler that supports keep-alive and logs requests into a #class variable class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler): parentClass = xmlrpc.server.SimpleXMLRPCRequestHandler protocol_version = 'HTTP/1.1' myRequests = [] def handle(self): self.myRequests.append([]) self.reqidx = len(self.myRequests)-1 return self.parentClass.handle(self) def handle_one_request(self): result = self.parentClass.handle_one_request(self) self.myRequests[self.reqidx].append(self.raw_requestline) return result requestHandler = RequestHandler def setUp(self): #clear request log self.RequestHandler.myRequests = [] return BaseServerTestCase.setUp(self) #A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism #does indeed serve subsequent requests on the same connection class KeepaliveServerTestCase1(BaseKeepaliveServerTestCase): def test_two(self): p = xmlrpclib.ServerProxy(URL) #do three requests. self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) p("close")() #they should have all been handled by a single request handler self.assertEqual(len(self.RequestHandler.myRequests), 1) #check that we did at least two (the third may be pending append #due to thread scheduling) self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2) #test special attribute access on the serverproxy, through the __call__ #function. class KeepaliveServerTestCase2(BaseKeepaliveServerTestCase): #ask for two keepalive requests to be handled. request_count=2 def test_close(self): p = xmlrpclib.ServerProxy(URL) #do some requests with close. self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) p("close")() #this should trigger a new keep-alive request self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) p("close")() #they should have all been two request handlers, each having logged at least #two complete requests self.assertEqual(len(self.RequestHandler.myRequests), 2) self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2) self.assertGreaterEqual(len(self.RequestHandler.myRequests[-2]), 2) def test_transport(self): p = xmlrpclib.ServerProxy(URL) #do some requests with close. self.assertEqual(p.pow(6,8), 6**8) p("transport").close() #same as above, really. self.assertEqual(p.pow(6,8), 6**8) p("close")() self.assertEqual(len(self.RequestHandler.myRequests), 2) #A test case that verifies that gzip encoding works in both directions #(for a request and the response) @unittest.skipIf(gzip is None, 'requires gzip') class GzipServerTestCase(BaseServerTestCase): #a request handler that supports keep-alive and logs requests into a #class variable class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler): parentClass = xmlrpc.server.SimpleXMLRPCRequestHandler protocol_version = 'HTTP/1.1' def do_POST(self): #store content of last request in class self.__class__.content_length = int(self.headers["content-length"]) return self.parentClass.do_POST(self) requestHandler = RequestHandler class Transport(xmlrpclib.Transport): #custom transport, stores the response length for our perusal fake_gzip = False def parse_response(self, response): self.response_length=int(response.getheader("content-length", 0)) return xmlrpclib.Transport.parse_response(self, response) def send_content(self, connection, body): if self.fake_gzip: #add a lone gzip header to induce decode error remotely connection.putheader("Content-Encoding", "gzip") return xmlrpclib.Transport.send_content(self, connection, body) def setUp(self): BaseServerTestCase.setUp(self) def test_gzip_request(self): t = self.Transport() t.encode_threshold = None p = xmlrpclib.ServerProxy(URL, transport=t) self.assertEqual(p.pow(6,8), 6**8) a = self.RequestHandler.content_length t.encode_threshold = 0 #turn on request encoding self.assertEqual(p.pow(6,8), 6**8) b = self.RequestHandler.content_length self.assertTrue(a>b) p("close")() def test_bad_gzip_request(self): t = self.Transport() t.encode_threshold = None t.fake_gzip = True p = xmlrpclib.ServerProxy(URL, transport=t) cm = self.assertRaisesRegex(xmlrpclib.ProtocolError, re.compile(r"\b400\b")) with cm: p.pow(6, 8) p("close")() def test_gzip_response(self): t = self.Transport() p = xmlrpclib.ServerProxy(URL, transport=t) old = self.requestHandler.encode_threshold self.requestHandler.encode_threshold = None #no encoding self.assertEqual(p.pow(6,8), 6**8) a = t.response_length self.requestHandler.encode_threshold = 0 #always encode self.assertEqual(p.pow(6,8), 6**8) p("close")() b = t.response_length self.requestHandler.encode_threshold = old self.assertTrue(a>b) @unittest.skipIf(gzip is None, 'requires gzip') class GzipUtilTestCase(unittest.TestCase): def test_gzip_decode_limit(self): max_gzip_decode = 20 * 1024 * 1024 data = b'\0' * max_gzip_decode encoded = xmlrpclib.gzip_encode(data) decoded = xmlrpclib.gzip_decode(encoded) self.assertEqual(len(decoded), max_gzip_decode) data = b'\0' * (max_gzip_decode + 1) encoded = xmlrpclib.gzip_encode(data) with self.assertRaisesRegex(ValueError, "max gzipped payload length exceeded"): xmlrpclib.gzip_decode(encoded) xmlrpclib.gzip_decode(encoded, max_decode=-1) class HeadersServerTestCase(BaseServerTestCase): class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler): test_headers = None def do_POST(self): self.__class__.test_headers = self.headers return super().do_POST() requestHandler = RequestHandler standard_headers = [ 'Host', 'Accept-Encoding', 'Content-Type', 'User-Agent', 'Content-Length'] def setUp(self): self.RequestHandler.test_headers = None return super().setUp() def assertContainsAdditionalHeaders(self, headers, additional): expected_keys = sorted(self.standard_headers + list(additional.keys())) self.assertListEqual(sorted(headers.keys()), expected_keys) for key, value in additional.items(): self.assertEqual(headers.get(key), value) def test_header(self): p = xmlrpclib.ServerProxy(URL, headers=[('X-Test', 'foo')]) self.assertEqual(p.pow(6, 8), 6**8) headers = self.RequestHandler.test_headers self.assertContainsAdditionalHeaders(headers, {'X-Test': 'foo'}) def test_header_many(self): p = xmlrpclib.ServerProxy( URL, headers=[('X-Test', 'foo'), ('X-Test-Second', 'bar')]) self.assertEqual(p.pow(6, 8), 6**8) headers = self.RequestHandler.test_headers self.assertContainsAdditionalHeaders( headers, {'X-Test': 'foo', 'X-Test-Second': 'bar'}) def test_header_empty(self): p = xmlrpclib.ServerProxy(URL, headers=[]) self.assertEqual(p.pow(6, 8), 6**8) headers = self.RequestHandler.test_headers self.assertContainsAdditionalHeaders(headers, {}) def test_header_tuple(self): p = xmlrpclib.ServerProxy(URL, headers=(('X-Test', 'foo'),)) self.assertEqual(p.pow(6, 8), 6**8) headers = self.RequestHandler.test_headers self.assertContainsAdditionalHeaders(headers, {'X-Test': 'foo'}) def test_header_items(self): p = xmlrpclib.ServerProxy(URL, headers={'X-Test': 'foo'}.items()) self.assertEqual(p.pow(6, 8), 6**8) headers = self.RequestHandler.test_headers self.assertContainsAdditionalHeaders(headers, {'X-Test': 'foo'}) #Test special attributes of the ServerProxy object class ServerProxyTestCase(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) # Actual value of the URL doesn't matter if it is a string in # the correct format. self.url = 'http://fake.localhost' def test_close(self): p = xmlrpclib.ServerProxy(self.url) self.assertEqual(p('close')(), None) def test_transport(self): t = xmlrpclib.Transport() p = xmlrpclib.ServerProxy(self.url, transport=t) self.assertEqual(p('transport'), t) # This is a contrived way to make a failure occur on the server side # in order to test the _send_traceback_header flag on the server class FailingMessageClass(http.client.HTTPMessage): def get(self, key, failobj=None): key = key.lower() if key == 'content-length': return 'I am broken' return super().get(key, failobj) class FailingServerTestCase(unittest.TestCase): def setUp(self): self.evt = threading.Event() # start server thread to handle requests serv_args = (self.evt, 1) thread = threading.Thread(target=http_server, args=serv_args) thread.start() self.addCleanup(thread.join) # wait for the server to be ready self.evt.wait() self.evt.clear() def tearDown(self): # wait on the server thread to terminate self.evt.wait() # reset flag xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False # reset message class default_class = http.client.HTTPMessage xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = default_class def test_basic(self): # check that flag is false by default flagval = xmlrpc.server.SimpleXMLRPCServer._send_traceback_header self.assertEqual(flagval, False) # enable traceback reporting xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True # test a call that shouldn't fail just as a smoke test try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.pow(6,8), 6**8) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_fail_no_info(self): # use the broken message class xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass try: p = xmlrpclib.ServerProxy(URL) p.pow(6,8) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e) and hasattr(e, "headers"): # The two server-side error headers shouldn't be sent back in this case self.assertTrue(e.headers.get("X-exception") is None) self.assertTrue(e.headers.get("X-traceback") is None) else: self.fail('ProtocolError not raised') def test_fail_with_info(self): # use the broken message class xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass # Check that errors in the server send back exception/traceback # info when flag is set xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True try: p = xmlrpclib.ServerProxy(URL) p.pow(6,8) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e) and hasattr(e, "headers"): # We should get error info in the response expected_err = "invalid literal for int() with base 10: 'I am broken'" self.assertEqual(e.headers.get("X-exception"), expected_err) self.assertTrue(e.headers.get("X-traceback") is not None) else: self.fail('ProtocolError not raised') @contextlib.contextmanager def captured_stdout(encoding='utf-8'): """A variation on support.captured_stdout() which gives a text stream having a `buffer` attribute. """ orig_stdout = sys.stdout sys.stdout = io.TextIOWrapper(io.BytesIO(), encoding=encoding) try: yield sys.stdout finally: sys.stdout = orig_stdout class CGIHandlerTestCase(unittest.TestCase): def setUp(self): self.cgi = xmlrpc.server.CGIXMLRPCRequestHandler() def tearDown(self): self.cgi = None def test_cgi_get(self): with support.EnvironmentVarGuard() as env: env['REQUEST_METHOD'] = 'GET' # if the method is GET and no request_text is given, it runs handle_get # get sysout output with captured_stdout(encoding=self.cgi.encoding) as data_out: self.cgi.handle_request() # parse Status header data_out.seek(0) handle = data_out.read() status = handle.split()[1] message = ' '.join(handle.split()[2:4]) self.assertEqual(status, '400') self.assertEqual(message, 'Bad Request') def test_cgi_xmlrpc_response(self): data = """<?xml version='1.0'?> <methodCall> <methodName>test_method</methodName> <params> <param> <value><string>foo</string></value> </param> <param> <value><string>bar</string></value> </param> </params> </methodCall> """ with support.EnvironmentVarGuard() as env, \ captured_stdout(encoding=self.cgi.encoding) as data_out, \ support.captured_stdin() as data_in: data_in.write(data) data_in.seek(0) env['CONTENT_LENGTH'] = str(len(data)) self.cgi.handle_request() data_out.seek(0) # will respond exception, if so, our goal is achieved ;) handle = data_out.read() # start with 44th char so as not to get http header, we just # need only xml self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:]) # Also test the content-length returned by handle_request # Using the same test method inorder to avoid all the datapassing # boilerplate code. # Test for bug: http://bugs.python.org/issue5040 content = handle[handle.find("<?xml"):] self.assertEqual( int(re.search(r'Content-Length: (\d+)', handle).group(1)), len(content)) class UseBuiltinTypesTestCase(unittest.TestCase): def test_use_builtin_types(self): # SimpleXMLRPCDispatcher.__init__ accepts use_builtin_types, which # makes all dispatch of binary data as bytes instances, and all # dispatch of datetime argument as datetime.datetime instances. self.log = [] expected_bytes = b"my dog has fleas" expected_date = datetime.datetime(2008, 5, 26, 18, 25, 12) marshaled = xmlrpclib.dumps((expected_bytes, expected_date), 'foobar') def foobar(*args): self.log.extend(args) handler = xmlrpc.server.SimpleXMLRPCDispatcher( allow_none=True, encoding=None, use_builtin_types=True) handler.register_function(foobar) handler._marshaled_dispatch(marshaled) self.assertEqual(len(self.log), 2) mybytes, mydate = self.log self.assertEqual(self.log, [expected_bytes, expected_date]) self.assertIs(type(mydate), datetime.datetime) self.assertIs(type(mybytes), bytes) def test_cgihandler_has_use_builtin_types_flag(self): handler = xmlrpc.server.CGIXMLRPCRequestHandler(use_builtin_types=True) self.assertTrue(handler.use_builtin_types) def test_xmlrpcserver_has_use_builtin_types_flag(self): server = xmlrpc.server.SimpleXMLRPCServer(("localhost", 0), use_builtin_types=True) server.server_close() self.assertTrue(server.use_builtin_types) def setUpModule(): thread_info = support.threading_setup() unittest.addModuleCleanup(support.threading_cleanup, *thread_info) if __name__ == "__main__": unittest.main()
38.695106
87
0.617584
import base64 import datetime import decimal import sys import time import unittest from unittest import mock import xmlrpc.client as xmlrpclib import xmlrpc.server import http.client import http, http.server import socket import threading import re import io import contextlib from test import support from test.support import socket_helper from test.support import ALWAYS_EQ, LARGEST, SMALLEST try: import gzip except ImportError: gzip = None alist = [{'astring': 'foo@bar.baz.spam', 'afloat': 7283.43, 'anint': 2**20, 'ashortlong': 2, 'anotherlist': ['.zyx.41'], 'abase64': xmlrpclib.Binary(b"my dog has fleas"), 'b64bytes': b"my dog has fleas", 'b64bytearray': bytearray(b"my dog has fleas"), 'boolean': False, 'unicode': '\u4000\u6000\u8000', 'ukey\u4000': 'regular value', 'datetime1': xmlrpclib.DateTime('20050210T11:41:23'), 'datetime2': xmlrpclib.DateTime( (2005, 2, 10, 11, 41, 23, 0, 1, -1)), 'datetime3': xmlrpclib.DateTime( datetime.datetime(2005, 2, 10, 11, 41, 23)), }] class XMLRPCTestCase(unittest.TestCase): def test_dump_load(self): dump = xmlrpclib.dumps((alist,)) load = xmlrpclib.loads(dump) self.assertEqual(alist, load[0][0]) def test_dump_bare_datetime(self): # since with use_builtin_types set to 1 the unmarshaller would create # datetime objects for the 'datetime[123]' keys as well dt = datetime.datetime(2005, 2, 10, 11, 41, 23) self.assertEqual(dt, xmlrpclib.DateTime('20050210T11:41:23')) s = xmlrpclib.dumps((dt,)) result, m = xmlrpclib.loads(s, use_builtin_types=True) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), datetime.datetime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_builtin_types=False) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), xmlrpclib.DateTime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_datetime=True) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), datetime.datetime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_datetime=False) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), xmlrpclib.DateTime) self.assertIsNone(m) def test_datetime_before_1900(self): # same as before but with a date before 1900 dt = datetime.datetime(1, 2, 10, 11, 41, 23) self.assertEqual(dt, xmlrpclib.DateTime('00010210T11:41:23')) s = xmlrpclib.dumps((dt,)) result, m = xmlrpclib.loads(s, use_builtin_types=True) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), datetime.datetime) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_builtin_types=False) (newdt,) = result self.assertEqual(newdt, dt) self.assertIs(type(newdt), xmlrpclib.DateTime) self.assertIsNone(m) def test_bug_1164912 (self): d = xmlrpclib.DateTime() ((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,), methodresponse=True)) self.assertIsInstance(new_d.value, str) # Check that the output of dumps() is still an 8-bit string s = xmlrpclib.dumps((new_d,), methodresponse=True) self.assertIsInstance(s, str) def test_newstyle_class(self): class T(object): pass t = T() t.x = 100 t.y = "Hello" ((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,))) self.assertEqual(t2, t.__dict__) def test_dump_big_long(self): self.assertRaises(OverflowError, xmlrpclib.dumps, (2**99,)) def test_dump_bad_dict(self): self.assertRaises(TypeError, xmlrpclib.dumps, ({(1,2,3): 1},)) def test_dump_recursive_seq(self): l = [1,2,3] t = [3,4,5,l] l.append(t) self.assertRaises(TypeError, xmlrpclib.dumps, (l,)) def test_dump_recursive_dict(self): d = {'1':1, '2':1} t = {'3':3, 'd':d} d['t'] = t self.assertRaises(TypeError, xmlrpclib.dumps, (d,)) def test_dump_big_int(self): if sys.maxsize > 2**31-1: self.assertRaises(OverflowError, xmlrpclib.dumps, (int(2**34),)) xmlrpclib.dumps((xmlrpclib.MAXINT, xmlrpclib.MININT)) self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MAXINT+1,)) self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MININT-1,)) def dummy_write(s): pass m = xmlrpclib.Marshaller() m.dump_int(xmlrpclib.MAXINT, dummy_write) m.dump_int(xmlrpclib.MININT, dummy_write) self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MAXINT+1, dummy_write) self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MININT-1, dummy_write) def test_dump_double(self): xmlrpclib.dumps((float(2 ** 34),)) xmlrpclib.dumps((float(xmlrpclib.MAXINT), float(xmlrpclib.MININT))) xmlrpclib.dumps((float(xmlrpclib.MAXINT + 42), float(xmlrpclib.MININT - 42))) def dummy_write(s): pass m = xmlrpclib.Marshaller() m.dump_double(xmlrpclib.MAXINT, dummy_write) m.dump_double(xmlrpclib.MININT, dummy_write) m.dump_double(xmlrpclib.MAXINT + 42, dummy_write) m.dump_double(xmlrpclib.MININT - 42, dummy_write) def test_dump_none(self): value = alist + [None] arg1 = (alist + [None],) strg = xmlrpclib.dumps(arg1, allow_none=True) self.assertEqual(value, xmlrpclib.loads(strg)[0][0]) self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,)) def test_dump_encoding(self): value = {'key\u20ac\xa4': 'value\u20ac\xa4'} strg = xmlrpclib.dumps((value,), encoding='iso-8859-15') strg = "<?xml version='1.0' encoding='iso-8859-15'?>" + strg self.assertEqual(xmlrpclib.loads(strg)[0][0], value) strg = strg.encode('iso-8859-15', 'xmlcharrefreplace') self.assertEqual(xmlrpclib.loads(strg)[0][0], value) strg = xmlrpclib.dumps((value,), encoding='iso-8859-15', methodresponse=True) self.assertEqual(xmlrpclib.loads(strg)[0][0], value) strg = strg.encode('iso-8859-15', 'xmlcharrefreplace') self.assertEqual(xmlrpclib.loads(strg)[0][0], value) methodname = 'method\u20ac\xa4' strg = xmlrpclib.dumps((value,), encoding='iso-8859-15', methodname=methodname) self.assertEqual(xmlrpclib.loads(strg)[0][0], value) self.assertEqual(xmlrpclib.loads(strg)[1], methodname) def test_dump_bytes(self): sample = b"my dog has fleas" self.assertEqual(sample, xmlrpclib.Binary(sample)) for type_ in bytes, bytearray, xmlrpclib.Binary: value = type_(sample) s = xmlrpclib.dumps((value,)) result, m = xmlrpclib.loads(s, use_builtin_types=True) (newvalue,) = result self.assertEqual(newvalue, sample) self.assertIs(type(newvalue), bytes) self.assertIsNone(m) result, m = xmlrpclib.loads(s, use_builtin_types=False) (newvalue,) = result self.assertEqual(newvalue, sample) self.assertIs(type(newvalue), xmlrpclib.Binary) self.assertIsNone(m) def test_loads_unsupported(self): ResponseError = xmlrpclib.ResponseError data = '<params><param><value><spam/></value></param></params>' self.assertRaises(ResponseError, xmlrpclib.loads, data) data = ('<params><param><value><array>' '<value><spam/></value>' '</array></value></param></params>') self.assertRaises(ResponseError, xmlrpclib.loads, data) data = ('<params><param><value><struct>' '<member><name>a</name><value><spam/></value></member>' '<member><name>b</name><value><spam/></value></member>' '</struct></value></param></params>') self.assertRaises(ResponseError, xmlrpclib.loads, data) def check_loads(self, s, value, **kwargs): dump = '<params><param><value>%s</value></param></params>' % s result, m = xmlrpclib.loads(dump, **kwargs) (newvalue,) = result self.assertEqual(newvalue, value) self.assertIs(type(newvalue), type(value)) self.assertIsNone(m) def test_load_standard_types(self): check = self.check_loads check('string', 'string') check('<string>string</string>', 'string') check('<string>𝔘𝔫𝔦𝔠𝔬𝔡𝔢 string</string>', '𝔘𝔫𝔦𝔠𝔬𝔡𝔢 string') check('<int>2056183947</int>', 2056183947) check('<int>-2056183947</int>', -2056183947) check('<i4>2056183947</i4>', 2056183947) check('<double>46093.78125</double>', 46093.78125) check('<boolean>0</boolean>', False) check('<base64>AGJ5dGUgc3RyaW5n/w==</base64>', xmlrpclib.Binary(b'\x00byte string\xff')) check('<base64>AGJ5dGUgc3RyaW5n/w==</base64>', b'\x00byte string\xff', use_builtin_types=True) check('<dateTime.iso8601>20050210T11:41:23</dateTime.iso8601>', xmlrpclib.DateTime('20050210T11:41:23')) check('<dateTime.iso8601>20050210T11:41:23</dateTime.iso8601>', datetime.datetime(2005, 2, 10, 11, 41, 23), use_builtin_types=True) check('<array><data>' '<value><int>1</int></value><value><int>2</int></value>' '</data></array>', [1, 2]) check('<struct>' '<member><name>b</name><value><int>2</int></value></member>' '<member><name>a</name><value><int>1</int></value></member>' '</struct>', {'a': 1, 'b': 2}) def test_load_extension_types(self): check = self.check_loads check('<nil/>', None) check('<ex:nil/>', None) check('<i1>205</i1>', 205) check('<i2>20561</i2>', 20561) check('<i8>9876543210</i8>', 9876543210) check('<biginteger>98765432100123456789</biginteger>', 98765432100123456789) check('<float>93.78125</float>', 93.78125) check('<bigdecimal>9876543210.0123456789</bigdecimal>', decimal.Decimal('9876543210.0123456789')) def test_get_host_info(self): # see bug #3613, this raised a TypeError transp = xmlrpc.client.Transport() self.assertEqual(transp.get_host_info("user@host.tld"), ('host.tld', [('Authorization', 'Basic dXNlcg==')], {})) def test_ssl_presence(self): try: import ssl except ImportError: has_ssl = False else: has_ssl = True try: xmlrpc.client.ServerProxy('https://localhost:9999').bad_function() except NotImplementedError: self.assertFalse(has_ssl, "xmlrpc client's error with SSL support") except OSError: self.assertTrue(has_ssl) def test_keepalive_disconnect(self): class RequestHandler(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" handled = False def do_POST(self): length = int(self.headers.get("Content-Length")) self.rfile.read(length) if self.handled: self.close_connection = True return response = xmlrpclib.dumps((5,), methodresponse=True) response = response.encode() self.send_response(http.HTTPStatus.OK) self.send_header("Content-Length", len(response)) self.end_headers() self.wfile.write(response) self.handled = True self.close_connection = False def log_message(self, format, *args): pass def run_server(): server.socket.settimeout(float(1)) # Don't hang if client fails server.handle_request() server.handle_request() server = http.server.HTTPServer((socket_helper.HOST, 0), RequestHandler) self.addCleanup(server.server_close) thread = threading.Thread(target=run_server) thread.start() self.addCleanup(thread.join) url = "http://{}:{}/".format(*server.server_address) with xmlrpclib.ServerProxy(url) as p: self.assertEqual(p.method(), 5) self.assertEqual(p.method(), 5) class SimpleXMLRPCDispatcherTestCase(unittest.TestCase): class DispatchExc(Exception): def test_call_registered_func(self): exp_params = 1, 2, 3 def dispatched_func(*params): raise self.DispatchExc(params) dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_function(dispatched_func) with self.assertRaises(self.DispatchExc) as exc_ctx: dispatcher._dispatch('dispatched_func', exp_params) self.assertEqual(exc_ctx.exception.args, (exp_params,)) self.assertIsNone(exc_ctx.exception.__cause__) self.assertIsNone(exc_ctx.exception.__context__) def test_call_instance_func(self): exp_params = 1, 2, 3 class DispatchedClass: def dispatched_func(self, *params): raise SimpleXMLRPCDispatcherTestCase.DispatchExc(params) dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_instance(DispatchedClass()) with self.assertRaises(self.DispatchExc) as exc_ctx: dispatcher._dispatch('dispatched_func', exp_params) self.assertEqual(exc_ctx.exception.args, (exp_params,)) self.assertIsNone(exc_ctx.exception.__cause__) self.assertIsNone(exc_ctx.exception.__context__) def test_call_dispatch_func(self): exp_method = 'method' exp_params = 1, 2, 3 class TestInstance: def _dispatch(self, method, params): raise SimpleXMLRPCDispatcherTestCase.DispatchExc( method, params) dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_instance(TestInstance()) with self.assertRaises(self.DispatchExc) as exc_ctx: dispatcher._dispatch(exp_method, exp_params) self.assertEqual(exc_ctx.exception.args, (exp_method, exp_params)) self.assertIsNone(exc_ctx.exception.__cause__) self.assertIsNone(exc_ctx.exception.__context__) def test_registered_func_is_none(self): dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_function(None, name='method') with self.assertRaisesRegex(Exception, 'method'): dispatcher._dispatch('method', ('param',)) def test_instance_has_no_func(self): dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() dispatcher.register_instance(object()) with self.assertRaisesRegex(Exception, 'method'): dispatcher._dispatch('method', ('param',)) def test_cannot_locate_func(self): dispatcher = xmlrpc.server.SimpleXMLRPCDispatcher() with self.assertRaisesRegex(Exception, 'method'): dispatcher._dispatch('method', ('param',)) class HelperTestCase(unittest.TestCase): def test_escape(self): self.assertEqual(xmlrpclib.escape("a&b"), "a&amp;b") self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b") self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b") class FaultTestCase(unittest.TestCase): def test_repr(self): f = xmlrpclib.Fault(42, 'Test Fault') self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>") self.assertEqual(repr(f), str(f)) def test_dump_fault(self): f = xmlrpclib.Fault(42, 'Test Fault') s = xmlrpclib.dumps((f,)) (newf,), m = xmlrpclib.loads(s) self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'}) self.assertEqual(m, None) s = xmlrpclib.Marshaller().dumps(f) self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s) def test_dotted_attribute(self): # private methods self.assertRaises(AttributeError, xmlrpc.server.resolve_dotted_attribute, str, '__add') self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title')) class DateTimeTestCase(unittest.TestCase): def test_default(self): with mock.patch('time.localtime') as localtime_mock: time_struct = time.struct_time( [2013, 7, 15, 0, 24, 49, 0, 196, 0]) localtime_mock.return_value = time_struct localtime = time.localtime() t = xmlrpclib.DateTime() self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", localtime)) def test_time(self): d = 1181399930.036952 t = xmlrpclib.DateTime(d) self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d))) def test_time_tuple(self): d = (2007,6,9,10,38,50,5,160,0) t = xmlrpclib.DateTime(d) self.assertEqual(str(t), '20070609T10:38:50') def test_time_struct(self): d = time.localtime(1181399930.036952) t = xmlrpclib.DateTime(d) self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", d)) def test_datetime_datetime(self): d = datetime.datetime(2007,1,2,3,4,5) t = xmlrpclib.DateTime(d) self.assertEqual(str(t), '20070102T03:04:05') def test_repr(self): d = datetime.datetime(2007,1,2,3,4,5) t = xmlrpclib.DateTime(d) val ="<DateTime '20070102T03:04:05' at %#x>" % id(t) self.assertEqual(repr(t), val) def test_decode(self): d = ' 20070908T07:11:13 ' t1 = xmlrpclib.DateTime() t1.decode(d) tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13)) self.assertEqual(t1, tref) t2 = xmlrpclib._datetime(d) self.assertEqual(t2, tref) def test_comparison(self): now = datetime.datetime.now() dtime = xmlrpclib.DateTime(now.timetuple()) # datetime vs. DateTime self.assertTrue(dtime == now) self.assertTrue(now == dtime) then = now + datetime.timedelta(seconds=4) self.assertTrue(then >= dtime) self.assertTrue(dtime < then) # str vs. DateTime dstr = now.strftime("%Y%m%dT%H:%M:%S") self.assertTrue(dtime == dstr) self.assertTrue(dstr == dtime) dtime_then = xmlrpclib.DateTime(then.timetuple()) self.assertTrue(dtime_then >= dstr) self.assertTrue(dstr < dtime_then) # some other types dbytes = dstr.encode('ascii') dtuple = now.timetuple() self.assertFalse(dtime == 1970) self.assertTrue(dtime != dbytes) self.assertFalse(dtime == bytearray(dbytes)) self.assertTrue(dtime != dtuple) with self.assertRaises(TypeError): dtime < float(1970) with self.assertRaises(TypeError): dtime > dbytes with self.assertRaises(TypeError): dtime <= bytearray(dbytes) with self.assertRaises(TypeError): dtime >= dtuple self.assertTrue(dtime == ALWAYS_EQ) self.assertFalse(dtime != ALWAYS_EQ) self.assertTrue(dtime < LARGEST) self.assertFalse(dtime > LARGEST) self.assertTrue(dtime <= LARGEST) self.assertFalse(dtime >= LARGEST) self.assertFalse(dtime < SMALLEST) self.assertTrue(dtime > SMALLEST) self.assertFalse(dtime <= SMALLEST) self.assertTrue(dtime >= SMALLEST) class BinaryTestCase(unittest.TestCase): # XXX What should str(Binary(b"\xff")) return? I'm choosing "\xff" def test_default(self): t = xmlrpclib.Binary() self.assertEqual(str(t), '') def test_string(self): d = b'\x01\x02\x03abc123\xff\xfe' t = xmlrpclib.Binary(d) self.assertEqual(str(t), str(d, "latin-1")) def test_decode(self): d = b'\x01\x02\x03abc123\xff\xfe' de = base64.encodebytes(d) t1 = xmlrpclib.Binary() t1.decode(de) self.assertEqual(str(t1), str(d, "latin-1")) t2 = xmlrpclib._binary(de) self.assertEqual(str(t2), str(d, "latin-1")) ADDR = PORT = URL = None def http_server(evt, numrequests, requestHandler=None, encoding=None): class TestInstanceClass: def div(self, x, y): return x // y def _methodHelp(self, name): if name == 'div': return 'This is the div function' class Fixture: @staticmethod def getData(): return '42' class MyXMLRPCServer(xmlrpc.server.SimpleXMLRPCServer): def get_request(self): s, port = self.socket.accept() s.setblocking(True) return s, port if not requestHandler: requestHandler = xmlrpc.server.SimpleXMLRPCRequestHandler serv = MyXMLRPCServer(("localhost", 0), requestHandler, encoding=encoding, logRequests=False, bind_and_activate=False) try: serv.server_bind() global ADDR, PORT, URL ADDR, PORT = serv.socket.getsockname() URL = "http://%s:%d"%(ADDR, PORT) serv.server_activate() serv.register_introspection_functions() serv.register_multicall_functions() serv.register_function(pow) serv.register_function(lambda x: x, 'têšt') @serv.register_function def my_function(): return True @serv.register_function(name='add') def _(x, y): return x + y testInstance = TestInstanceClass() serv.register_instance(testInstance, allow_dotted_names=True) evt.set() while numrequests > 0: serv.handle_request() numrequests -= 1 except socket.timeout: pass finally: serv.socket.close() PORT = None evt.set() def http_multi_server(evt, numrequests, requestHandler=None): class TestInstanceClass: def div(self, x, y): return x // y def _methodHelp(self, name): if name == 'div': return 'This is the div function' def my_function(): return True class MyXMLRPCServer(xmlrpc.server.MultiPathXMLRPCServer): def get_request(self): s, port = self.socket.accept() s.setblocking(True) return s, port if not requestHandler: requestHandler = xmlrpc.server.SimpleXMLRPCRequestHandler class MyRequestHandler(requestHandler): rpc_paths = [] class BrokenDispatcher: def _marshaled_dispatch(self, data, dispatch_method=None, path=None): raise RuntimeError("broken dispatcher") serv = MyXMLRPCServer(("localhost", 0), MyRequestHandler, logRequests=False, bind_and_activate=False) serv.socket.settimeout(3) serv.server_bind() try: global ADDR, PORT, URL ADDR, PORT = serv.socket.getsockname() URL = "http://%s:%d"%(ADDR, PORT) serv.server_activate() paths = [ "/foo", "/foo/bar", "/foo?k=v", "/foo#frag", "/foo?k=v#frag", "", "/", "/RPC2", "?k=v", "#frag", ] for path in paths: d = serv.add_dispatcher(path, xmlrpc.server.SimpleXMLRPCDispatcher()) d.register_introspection_functions() d.register_multicall_functions() d.register_function(lambda p=path: p, 'test') serv.get_dispatcher(paths[0]).register_function(pow) serv.get_dispatcher(paths[1]).register_function(lambda x,y: x+y, 'add') serv.add_dispatcher("/is/broken", BrokenDispatcher()) evt.set() while numrequests > 0: serv.handle_request() numrequests -= 1 except socket.timeout: pass finally: serv.socket.close() PORT = None evt.set() def is_unavailable_exception(e): try: if e.errcode == -1 or e.headers is None: return True exc_mess = e.headers.get('X-exception') except AttributeError: exc_mess = str(e) if exc_mess and 'temporarily unavailable' in exc_mess.lower(): return True def make_request_and_skipIf(condition, reason): if not condition: return lambda func: func def decorator(func): def make_request_and_skip(self): try: xmlrpclib.ServerProxy(URL).my_function() except (xmlrpclib.ProtocolError, OSError) as e: if not is_unavailable_exception(e): raise raise unittest.SkipTest(reason) return make_request_and_skip return decorator class BaseServerTestCase(unittest.TestCase): requestHandler = None request_count = 1 threadFunc = staticmethod(http_server) def setUp(self): xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True self.evt = threading.Event() serv_args = (self.evt, self.request_count, self.requestHandler) thread = threading.Thread(target=self.threadFunc, args=serv_args) thread.start() self.addCleanup(thread.join) self.evt.wait() self.evt.clear() def tearDown(self): self.evt.wait() xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False class SimpleServerTestCase(BaseServerTestCase): def test_simple1(self): try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.pow(6,8), 6**8) except (xmlrpclib.ProtocolError, OSError) as e: if not is_unavailable_exception(e): self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_nonascii(self): start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t' end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n' try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.add(start_string, end_string), start_string + end_string) except (xmlrpclib.ProtocolError, OSError) as e: if not is_unavailable_exception(e): self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_client_encoding(self): start_string = '\u20ac' end_string = '\xa4' try: p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15') self.assertEqual(p.add(start_string, end_string), start_string + end_string) except (xmlrpclib.ProtocolError, socket.error) as e: if not is_unavailable_exception(e): self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_nonascii_methodname(self): try: p = xmlrpclib.ServerProxy(URL, encoding='ascii') self.assertEqual(p.têšt(42), 42) except (xmlrpclib.ProtocolError, socket.error) as e: if not is_unavailable_exception(e): self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_404(self): with contextlib.closing(http.client.HTTPConnection(ADDR, PORT)) as conn: conn.request('POST', '/this-is-not-valid') response = conn.getresponse() self.assertEqual(response.status, 404) self.assertEqual(response.reason, 'Not Found') def test_introspection1(self): expected_methods = set(['pow', 'div', 'my_function', 'add', 'têšt', 'system.listMethods', 'system.methodHelp', 'system.methodSignature', 'system.multicall', 'Fixture']) try: p = xmlrpclib.ServerProxy(URL) meth = p.system.listMethods() self.assertEqual(set(meth), expected_methods) except (xmlrpclib.ProtocolError, OSError) as e: if not is_unavailable_exception(e): self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_introspection2(self): try: p = xmlrpclib.ServerProxy(URL) divhelp = p.system.methodHelp('div') self.assertEqual(divhelp, 'This is the div function') except (xmlrpclib.ProtocolError, OSError) as e: if not is_unavailable_exception(e): self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) @make_request_and_skipIf(sys.flags.optimize >= 2, "Docstrings are omitted with -O2 and above") def test_introspection3(self): try: p = xmlrpclib.ServerProxy(URL) myfunction = p.system.methodHelp('my_function') self.assertEqual(myfunction, 'This is my function') except (xmlrpclib.ProtocolError, OSError) as e: if not is_unavailable_exception(e): self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_introspection4(self): # at least check that we can try making the call try: p = xmlrpclib.ServerProxy(URL) divsig = p.system.methodSignature('div') self.assertEqual(divsig, 'signatures not supported') except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_multicall(self): try: p = xmlrpclib.ServerProxy(URL) multicall = xmlrpclib.MultiCall(p) multicall.add(2,3) multicall.pow(6,8) multicall.div(127,42) add_result, pow_result, div_result = multicall() self.assertEqual(add_result, 2+3) self.assertEqual(pow_result, 6**8) self.assertEqual(div_result, 127//42) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_non_existing_multicall(self): try: p = xmlrpclib.ServerProxy(URL) multicall = xmlrpclib.MultiCall(p) multicall.this_is_not_exists() result = multicall() # result.results contains; # [{'faultCode': 1, 'faultString': '<class \'exceptions.Exception\'>:' # 'method "this_is_not_exists" is not supported'>}] self.assertEqual(result.results[0]['faultCode'], 1) self.assertEqual(result.results[0]['faultString'], '<class \'Exception\'>:method "this_is_not_exists" ' 'is not supported') except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e): # protocol error; provide additional information in test output self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_dotted_attribute(self): # Raises an AttributeError because private methods are not allowed. self.assertRaises(AttributeError, xmlrpc.server.resolve_dotted_attribute, str, '__add') self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title')) # Get the test to run faster by sending a request with test_simple1. # This avoids waiting for the socket timeout. self.test_simple1() def test_allow_dotted_names_true(self): # XXX also need allow_dotted_names_false test. server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) data = server.Fixture.getData() self.assertEqual(data, '42') def test_unicode_host(self): server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) self.assertEqual(server.add("a", "\xe9"), "a\xe9") def test_partial_post(self): # Check that a partial POST doesn't make the server loop: issue with contextlib.closing(socket.create_connection((ADDR, PORT))) as conn: conn.send('POST /RPC2 HTTP/1.0\r\n' 'Content-Length: 100\r\n\r\n' 'bye HTTP/1.1\r\n' f'Host: {ADDR}:{PORT}\r\n' 'Accept-Encoding: identity\r\n' 'Content-Length: 0\r\n\r\n'.encode('ascii')) def test_context_manager(self): with xmlrpclib.ServerProxy(URL) as server: server.add(2, 3) self.assertNotEqual(server('transport')._connection, (None, None)) self.assertEqual(server('transport')._connection, (None, None)) def test_context_manager_method_error(self): try: with xmlrpclib.ServerProxy(URL) as server: server.add(2, "a") except xmlrpclib.Fault: pass self.assertEqual(server('transport')._connection, (None, None)) class SimpleServerEncodingTestCase(BaseServerTestCase): @staticmethod def threadFunc(evt, numrequests, requestHandler=None, encoding=None): http_server(evt, numrequests, requestHandler, 'iso-8859-15') def test_server_encoding(self): start_string = '\u20ac' end_string = '\xa4' try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.add(start_string, end_string), start_string + end_string) except (xmlrpclib.ProtocolError, socket.error) as e: if not is_unavailable_exception(e): self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) class MultiPathServerTestCase(BaseServerTestCase): threadFunc = staticmethod(http_multi_server) request_count = 2 def test_path1(self): p = xmlrpclib.ServerProxy(URL+"/foo") self.assertEqual(p.pow(6,8), 6**8) self.assertRaises(xmlrpclib.Fault, p.add, 6, 8) def test_path2(self): p = xmlrpclib.ServerProxy(URL+"/foo/bar") self.assertEqual(p.add(6,8), 6+8) self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8) def test_path3(self): p = xmlrpclib.ServerProxy(URL+"/is/broken") self.assertRaises(xmlrpclib.Fault, p.add, 6, 8) def test_invalid_path(self): p = xmlrpclib.ServerProxy(URL+"/invalid") self.assertRaises(xmlrpclib.Fault, p.add, 6, 8) def test_path_query_fragment(self): p = xmlrpclib.ServerProxy(URL+"/foo?k=v#frag") self.assertEqual(p.test(), "/foo?k=v#frag") def test_path_fragment(self): p = xmlrpclib.ServerProxy(URL+"/foo#frag") self.assertEqual(p.test(), "/foo#frag") def test_path_query(self): p = xmlrpclib.ServerProxy(URL+"/foo?k=v") self.assertEqual(p.test(), "/foo?k=v") def test_empty_path(self): p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.test(), "/RPC2") def test_root_path(self): p = xmlrpclib.ServerProxy(URL + "/") self.assertEqual(p.test(), "/") def test_empty_path_query(self): p = xmlrpclib.ServerProxy(URL + "?k=v") self.assertEqual(p.test(), "?k=v") def test_empty_path_fragment(self): p = xmlrpclib.ServerProxy(URL + "#frag") self.assertEqual(p.test(), "#frag") class BaseKeepaliveServerTestCase(BaseServerTestCase): class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler): parentClass = xmlrpc.server.SimpleXMLRPCRequestHandler protocol_version = 'HTTP/1.1' myRequests = [] def handle(self): self.myRequests.append([]) self.reqidx = len(self.myRequests)-1 return self.parentClass.handle(self) def handle_one_request(self): result = self.parentClass.handle_one_request(self) self.myRequests[self.reqidx].append(self.raw_requestline) return result requestHandler = RequestHandler def setUp(self): self.RequestHandler.myRequests = [] return BaseServerTestCase.setUp(self) class KeepaliveServerTestCase1(BaseKeepaliveServerTestCase): def test_two(self): p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) p("close")() self.assertEqual(len(self.RequestHandler.myRequests), 1) self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2) class KeepaliveServerTestCase2(BaseKeepaliveServerTestCase): request_count=2 def test_close(self): p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) p("close")() self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) self.assertEqual(p.pow(6,8), 6**8) p("close")() self.assertEqual(len(self.RequestHandler.myRequests), 2) self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2) self.assertGreaterEqual(len(self.RequestHandler.myRequests[-2]), 2) def test_transport(self): p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.pow(6,8), 6**8) p("transport").close() self.assertEqual(p.pow(6,8), 6**8) p("close")() self.assertEqual(len(self.RequestHandler.myRequests), 2) @unittest.skipIf(gzip is None, 'requires gzip') class GzipServerTestCase(BaseServerTestCase): class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler): parentClass = xmlrpc.server.SimpleXMLRPCRequestHandler protocol_version = 'HTTP/1.1' def do_POST(self): self.__class__.content_length = int(self.headers["content-length"]) return self.parentClass.do_POST(self) requestHandler = RequestHandler class Transport(xmlrpclib.Transport): fake_gzip = False def parse_response(self, response): self.response_length=int(response.getheader("content-length", 0)) return xmlrpclib.Transport.parse_response(self, response) def send_content(self, connection, body): if self.fake_gzip: connection.putheader("Content-Encoding", "gzip") return xmlrpclib.Transport.send_content(self, connection, body) def setUp(self): BaseServerTestCase.setUp(self) def test_gzip_request(self): t = self.Transport() t.encode_threshold = None p = xmlrpclib.ServerProxy(URL, transport=t) self.assertEqual(p.pow(6,8), 6**8) a = self.RequestHandler.content_length t.encode_threshold = 0 self.assertEqual(p.pow(6,8), 6**8) b = self.RequestHandler.content_length self.assertTrue(a>b) p("close")() def test_bad_gzip_request(self): t = self.Transport() t.encode_threshold = None t.fake_gzip = True p = xmlrpclib.ServerProxy(URL, transport=t) cm = self.assertRaisesRegex(xmlrpclib.ProtocolError, re.compile(r"\b400\b")) with cm: p.pow(6, 8) p("close")() def test_gzip_response(self): t = self.Transport() p = xmlrpclib.ServerProxy(URL, transport=t) old = self.requestHandler.encode_threshold self.requestHandler.encode_threshold = None self.assertEqual(p.pow(6,8), 6**8) a = t.response_length self.requestHandler.encode_threshold = 0 self.assertEqual(p.pow(6,8), 6**8) p("close")() b = t.response_length self.requestHandler.encode_threshold = old self.assertTrue(a>b) @unittest.skipIf(gzip is None, 'requires gzip') class GzipUtilTestCase(unittest.TestCase): def test_gzip_decode_limit(self): max_gzip_decode = 20 * 1024 * 1024 data = b'\0' * max_gzip_decode encoded = xmlrpclib.gzip_encode(data) decoded = xmlrpclib.gzip_decode(encoded) self.assertEqual(len(decoded), max_gzip_decode) data = b'\0' * (max_gzip_decode + 1) encoded = xmlrpclib.gzip_encode(data) with self.assertRaisesRegex(ValueError, "max gzipped payload length exceeded"): xmlrpclib.gzip_decode(encoded) xmlrpclib.gzip_decode(encoded, max_decode=-1) class HeadersServerTestCase(BaseServerTestCase): class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler): test_headers = None def do_POST(self): self.__class__.test_headers = self.headers return super().do_POST() requestHandler = RequestHandler standard_headers = [ 'Host', 'Accept-Encoding', 'Content-Type', 'User-Agent', 'Content-Length'] def setUp(self): self.RequestHandler.test_headers = None return super().setUp() def assertContainsAdditionalHeaders(self, headers, additional): expected_keys = sorted(self.standard_headers + list(additional.keys())) self.assertListEqual(sorted(headers.keys()), expected_keys) for key, value in additional.items(): self.assertEqual(headers.get(key), value) def test_header(self): p = xmlrpclib.ServerProxy(URL, headers=[('X-Test', 'foo')]) self.assertEqual(p.pow(6, 8), 6**8) headers = self.RequestHandler.test_headers self.assertContainsAdditionalHeaders(headers, {'X-Test': 'foo'}) def test_header_many(self): p = xmlrpclib.ServerProxy( URL, headers=[('X-Test', 'foo'), ('X-Test-Second', 'bar')]) self.assertEqual(p.pow(6, 8), 6**8) headers = self.RequestHandler.test_headers self.assertContainsAdditionalHeaders( headers, {'X-Test': 'foo', 'X-Test-Second': 'bar'}) def test_header_empty(self): p = xmlrpclib.ServerProxy(URL, headers=[]) self.assertEqual(p.pow(6, 8), 6**8) headers = self.RequestHandler.test_headers self.assertContainsAdditionalHeaders(headers, {}) def test_header_tuple(self): p = xmlrpclib.ServerProxy(URL, headers=(('X-Test', 'foo'),)) self.assertEqual(p.pow(6, 8), 6**8) headers = self.RequestHandler.test_headers self.assertContainsAdditionalHeaders(headers, {'X-Test': 'foo'}) def test_header_items(self): p = xmlrpclib.ServerProxy(URL, headers={'X-Test': 'foo'}.items()) self.assertEqual(p.pow(6, 8), 6**8) headers = self.RequestHandler.test_headers self.assertContainsAdditionalHeaders(headers, {'X-Test': 'foo'}) class ServerProxyTestCase(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) # the correct format. self.url = 'http://fake.localhost' def test_close(self): p = xmlrpclib.ServerProxy(self.url) self.assertEqual(p('close')(), None) def test_transport(self): t = xmlrpclib.Transport() p = xmlrpclib.ServerProxy(self.url, transport=t) self.assertEqual(p('transport'), t) # This is a contrived way to make a failure occur on the server side # in order to test the _send_traceback_header flag on the server class FailingMessageClass(http.client.HTTPMessage): def get(self, key, failobj=None): key = key.lower() if key == 'content-length': return 'I am broken' return super().get(key, failobj) class FailingServerTestCase(unittest.TestCase): def setUp(self): self.evt = threading.Event() # start server thread to handle requests serv_args = (self.evt, 1) thread = threading.Thread(target=http_server, args=serv_args) thread.start() self.addCleanup(thread.join) # wait for the server to be ready self.evt.wait() self.evt.clear() def tearDown(self): # wait on the server thread to terminate self.evt.wait() # reset flag xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False # reset message class default_class = http.client.HTTPMessage xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = default_class def test_basic(self): # check that flag is false by default flagval = xmlrpc.server.SimpleXMLRPCServer._send_traceback_header self.assertEqual(flagval, False) # enable traceback reporting xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True # test a call that shouldn't fail just as a smoke test try: p = xmlrpclib.ServerProxy(URL) self.assertEqual(p.pow(6,8), 6**8) except (xmlrpclib.ProtocolError, OSError) as e: if not is_unavailable_exception(e): self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) def test_fail_no_info(self): xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass try: p = xmlrpclib.ServerProxy(URL) p.pow(6,8) except (xmlrpclib.ProtocolError, OSError) as e: if not is_unavailable_exception(e) and hasattr(e, "headers"): self.assertTrue(e.headers.get("X-exception") is None) self.assertTrue(e.headers.get("X-traceback") is None) else: self.fail('ProtocolError not raised') def test_fail_with_info(self): # use the broken message class xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass # Check that errors in the server send back exception/traceback # info when flag is set xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True try: p = xmlrpclib.ServerProxy(URL) p.pow(6,8) except (xmlrpclib.ProtocolError, OSError) as e: # ignore failures due to non-blocking socket 'unavailable' errors if not is_unavailable_exception(e) and hasattr(e, "headers"): # We should get error info in the response expected_err = "invalid literal for int() with base 10: 'I am broken'" self.assertEqual(e.headers.get("X-exception"), expected_err) self.assertTrue(e.headers.get("X-traceback") is not None) else: self.fail('ProtocolError not raised') @contextlib.contextmanager def captured_stdout(encoding='utf-8'): orig_stdout = sys.stdout sys.stdout = io.TextIOWrapper(io.BytesIO(), encoding=encoding) try: yield sys.stdout finally: sys.stdout = orig_stdout class CGIHandlerTestCase(unittest.TestCase): def setUp(self): self.cgi = xmlrpc.server.CGIXMLRPCRequestHandler() def tearDown(self): self.cgi = None def test_cgi_get(self): with support.EnvironmentVarGuard() as env: env['REQUEST_METHOD'] = 'GET' # if the method is GET and no request_text is given, it runs handle_get # get sysout output with captured_stdout(encoding=self.cgi.encoding) as data_out: self.cgi.handle_request() # parse Status header data_out.seek(0) handle = data_out.read() status = handle.split()[1] message = ' '.join(handle.split()[2:4]) self.assertEqual(status, '400') self.assertEqual(message, 'Bad Request') def test_cgi_xmlrpc_response(self): data = """<?xml version='1.0'?> <methodCall> <methodName>test_method</methodName> <params> <param> <value><string>foo</string></value> </param> <param> <value><string>bar</string></value> </param> </params> </methodCall> """ with support.EnvironmentVarGuard() as env, \ captured_stdout(encoding=self.cgi.encoding) as data_out, \ support.captured_stdin() as data_in: data_in.write(data) data_in.seek(0) env['CONTENT_LENGTH'] = str(len(data)) self.cgi.handle_request() data_out.seek(0) # will respond exception, if so, our goal is achieved ;) handle = data_out.read() # start with 44th char so as not to get http header, we just # need only xml self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:]) # Also test the content-length returned by handle_request # Using the same test method inorder to avoid all the datapassing # boilerplate code. # Test for bug: http://bugs.python.org/issue5040 content = handle[handle.find("<?xml"):] self.assertEqual( int(re.search(r'Content-Length: (\d+)', handle).group(1)), len(content)) class UseBuiltinTypesTestCase(unittest.TestCase): def test_use_builtin_types(self): # SimpleXMLRPCDispatcher.__init__ accepts use_builtin_types, which # makes all dispatch of binary data as bytes instances, and all # dispatch of datetime argument as datetime.datetime instances. self.log = [] expected_bytes = b"my dog has fleas" expected_date = datetime.datetime(2008, 5, 26, 18, 25, 12) marshaled = xmlrpclib.dumps((expected_bytes, expected_date), 'foobar') def foobar(*args): self.log.extend(args) handler = xmlrpc.server.SimpleXMLRPCDispatcher( allow_none=True, encoding=None, use_builtin_types=True) handler.register_function(foobar) handler._marshaled_dispatch(marshaled) self.assertEqual(len(self.log), 2) mybytes, mydate = self.log self.assertEqual(self.log, [expected_bytes, expected_date]) self.assertIs(type(mydate), datetime.datetime) self.assertIs(type(mybytes), bytes) def test_cgihandler_has_use_builtin_types_flag(self): handler = xmlrpc.server.CGIXMLRPCRequestHandler(use_builtin_types=True) self.assertTrue(handler.use_builtin_types) def test_xmlrpcserver_has_use_builtin_types_flag(self): server = xmlrpc.server.SimpleXMLRPCServer(("localhost", 0), use_builtin_types=True) server.server_close() self.assertTrue(server.use_builtin_types) def setUpModule(): thread_info = support.threading_setup() unittest.addModuleCleanup(support.threading_cleanup, *thread_info) if __name__ == "__main__": unittest.main()
true
true
f714b9348ad752e793cdd77f438e5175c7c11a35
1,235
py
Python
conf/script/src/build_system/cmd/setup/_priv/setup_steps/step_setup_targets.py
benoit-dubreuil/template-repo-cpp-full-ecosystem
f506dd5e2a61cdd311b6a6a4be4abc59567b4b20
[ "MIT" ]
null
null
null
conf/script/src/build_system/cmd/setup/_priv/setup_steps/step_setup_targets.py
benoit-dubreuil/template-repo-cpp-full-ecosystem
f506dd5e2a61cdd311b6a6a4be4abc59567b4b20
[ "MIT" ]
113
2021-02-15T19:22:36.000Z
2021-05-07T15:17:42.000Z
conf/script/src/build_system/cmd/setup/_priv/setup_steps/step_setup_targets.py
benoit-dubreuil/template-repo-cpp-full-ecosystem
f506dd5e2a61cdd311b6a6a4be4abc59567b4b20
[ "MIT" ]
null
null
null
__all__ = ['setup_targets'] from pathlib import Path from typing import Final from build_system.build_target import * from build_system.compiler import * from ..meson import * def setup_targets(root_dir: Path, targets: list[CompilerInstanceTargets], cli_mode: bool) -> None: for compiler_instance_targets in targets: _setup_compiler_instance_targets(root_dir=root_dir, compiler_instance_targets=compiler_instance_targets, cli_mode=cli_mode) if cli_mode: print() def _setup_compiler_instance_targets(root_dir: Path, compiler_instance_targets: CompilerInstanceTargets, cli_mode: bool) -> None: compiler_instance: Final[CompilerInstance] = compiler_instance_targets.compiler_instance with compiler_instance.create_env_context_manager() as compiler_env_manager: for target in compiler_instance_targets.build_targets: setup_target(root_dir=root_dir, compiler_instance=compiler_instance, compiler_env_manager=compiler_env_manager, build_target=target, cli_mode=cli_mode)
37.424242
131
0.672065
__all__ = ['setup_targets'] from pathlib import Path from typing import Final from build_system.build_target import * from build_system.compiler import * from ..meson import * def setup_targets(root_dir: Path, targets: list[CompilerInstanceTargets], cli_mode: bool) -> None: for compiler_instance_targets in targets: _setup_compiler_instance_targets(root_dir=root_dir, compiler_instance_targets=compiler_instance_targets, cli_mode=cli_mode) if cli_mode: print() def _setup_compiler_instance_targets(root_dir: Path, compiler_instance_targets: CompilerInstanceTargets, cli_mode: bool) -> None: compiler_instance: Final[CompilerInstance] = compiler_instance_targets.compiler_instance with compiler_instance.create_env_context_manager() as compiler_env_manager: for target in compiler_instance_targets.build_targets: setup_target(root_dir=root_dir, compiler_instance=compiler_instance, compiler_env_manager=compiler_env_manager, build_target=target, cli_mode=cli_mode)
true
true
f714b949926c5c2ca7e179aeb0fa07f4a42d5c12
1,552
py
Python
src/pacsanini/cli/commands.py
Therapixel/pacsanini
8d8e61601a9df39eaa7aa4b8e9a7e1ccd1ee253d
[ "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause-Clear", "BSD-3-Clause" ]
10
2021-07-05T16:59:03.000Z
2022-02-09T11:13:03.000Z
src/pacsanini/cli/commands.py
Therapixel/pacsanini
8d8e61601a9df39eaa7aa4b8e9a7e1ccd1ee253d
[ "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause-Clear", "BSD-3-Clause" ]
51
2021-07-05T08:29:35.000Z
2021-11-30T08:30:10.000Z
src/pacsanini/cli/commands.py
Therapixel/pacsanini
8d8e61601a9df39eaa7aa4b8e9a7e1ccd1ee253d
[ "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause-Clear", "BSD-3-Clause" ]
2
2021-07-06T06:35:37.000Z
2021-07-09T10:26:38.000Z
# Copyright (C) 2019-2020, Therapixel SA. # All rights reserved. # This file is subject to the terms and conditions described in the # LICENSE file distributed in this package. """The commands module exposes the different command lines methods that can be used with pacsanini. """ from click import echo, group, option from pacsanini.__version__ import __version__ from pacsanini.cli.config import config_cli from pacsanini.cli.dashboard import dashboard_cli from pacsanini.cli.db import db_cli_group from pacsanini.cli.net import echo_cli, find_cli, move_cli, send_cli, server_cli from pacsanini.cli.parse import gen_parser, parse from pacsanini.cli.pipeline import orchestrate_cli def print_version(ctx, param, value): # pylint: disable=unused-argument """Print the program's version.""" if not value or ctx.resilient_parsing: return echo(f"Version {__version__}") ctx.exit() @group(name="pacsanini") @option( "--version", is_flag=True, callback=print_version, expose_value=False, is_eager=True ) def entry_point(**kwargs): """Parse or configure your DICOM tag parsing capabilities from the command line. """ entry_point.add_command(config_cli) entry_point.add_command(dashboard_cli) entry_point.add_command(db_cli_group) entry_point.add_command(echo_cli) entry_point.add_command(find_cli) entry_point.add_command(move_cli) entry_point.add_command(send_cli) entry_point.add_command(server_cli) entry_point.add_command(parse) entry_point.add_command(gen_parser) entry_point.add_command(orchestrate_cli)
32.333333
88
0.794459
from click import echo, group, option from pacsanini.__version__ import __version__ from pacsanini.cli.config import config_cli from pacsanini.cli.dashboard import dashboard_cli from pacsanini.cli.db import db_cli_group from pacsanini.cli.net import echo_cli, find_cli, move_cli, send_cli, server_cli from pacsanini.cli.parse import gen_parser, parse from pacsanini.cli.pipeline import orchestrate_cli def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return echo(f"Version {__version__}") ctx.exit() @group(name="pacsanini") @option( "--version", is_flag=True, callback=print_version, expose_value=False, is_eager=True ) def entry_point(**kwargs): entry_point.add_command(config_cli) entry_point.add_command(dashboard_cli) entry_point.add_command(db_cli_group) entry_point.add_command(echo_cli) entry_point.add_command(find_cli) entry_point.add_command(move_cli) entry_point.add_command(send_cli) entry_point.add_command(server_cli) entry_point.add_command(parse) entry_point.add_command(gen_parser) entry_point.add_command(orchestrate_cli)
true
true
f714b953e0c9a6d6462cb48d28e32167397104dc
9,005
py
Python
CUB-experiments/nearest_embed.py
ashleylqx/AIB
77e418cac52f0ca5f2a7c54927468a7bd75a8fc9
[ "MIT" ]
5
2021-05-23T13:05:45.000Z
2022-02-13T21:40:59.000Z
CUB-experiments/nearest_embed.py
ashleylqx/AIB
77e418cac52f0ca5f2a7c54927468a7bd75a8fc9
[ "MIT" ]
null
null
null
CUB-experiments/nearest_embed.py
ashleylqx/AIB
77e418cac52f0ca5f2a7c54927468a7bd75a8fc9
[ "MIT" ]
3
2021-08-11T03:23:31.000Z
2021-11-17T01:48:52.000Z
# adapted from https://github.com/nadavbh12/VQ-VAE import numpy as np import torch from torch import nn from torch.autograd import Function, Variable import torch.nn.functional as F from config import * import pdb class NearestEmbedFunc(Function): """ Input: ------ x - (batch_size, emb_dim, *) Last dimensions may be arbitrary emb - (emb_dim, num_emb) """ @staticmethod def forward(ctx, input, emb): # if input.size(1) != emb.size(0): # raise RuntimeError('invalid argument: input.size(1) ({}) must be equal to emb.size(0) ({})'. # format(input.size(1), emb.size(0))) # emb = emb.expand(input.size(1), emb.size(1)) emb_ex = emb.expand(input.size(1), emb.size(1)) # new2 # save sizes for backward ctx.batch_size = input.size(0) ctx.num_latents = int(np.prod(np.array(input.size()[2:]))) # ctx.emb_dim = emb.size(0) # ctx.num_emb = emb.size(1) ctx.emb_dim = emb_ex.size(0) ctx.num_emb = emb_ex.size(1) # new2 ctx.input_type = type(input) ctx.dims = list(range(len(input.size()))) # expand to be broadcast-able x_expanded = input.unsqueeze(-1) num_arbitrary_dims = len(ctx.dims) - 2 if num_arbitrary_dims: # emb_expanded = emb.view(emb.shape[0], *([1] * num_arbitrary_dims), emb.shape[1]) emb_expanded = emb_ex.view(emb_ex.shape[0], *([1] * num_arbitrary_dims), emb_ex.shape[1]) # new2 else: # emb_expanded = emb emb_expanded = emb_ex # new2 # find nearest neighbors # dist = torch.norm(x_expanded - emb_expanded, 2, 1) dist = torch.pow(x_expanded - emb_expanded, 2) # (batch_size, emb_dim, *, num_emb) # new2 _, argmin = dist.min(-1) shifted_shape = [input.shape[0], *list(input.shape[2:]) ,input.shape[1]] # pdb.set_trace() result = emb.t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, ctx.dims[-1], *ctx.dims[1:-1]) # new2 ctx.save_for_backward(argmin) return result.contiguous(), argmin @staticmethod def backward(ctx, grad_output, argmin=None): # pdb.set_trace() grad_input = grad_emb = None if ctx.needs_input_grad[0]: grad_input = grad_output if ctx.needs_input_grad[1]: argmin, = ctx.saved_variables latent_indices = torch.arange(ctx.num_emb).type_as(argmin) idx_choices = (argmin.view(-1, 1) == latent_indices.view(1, -1)).type_as(grad_output.data) n_idx_choice = idx_choices.sum(0) n_idx_choice[n_idx_choice == 0] = 1 idx_avg_choices = idx_choices / n_idx_choice grad_output = grad_output.permute(0, *ctx.dims[2:], 1).contiguous() grad_output = grad_output.view(ctx.batch_size * ctx.num_latents, ctx.emb_dim) # pdb.set_trace() # grad_emb = torch.sum(grad_output.data.view(-1, ctx.emb_dim, 1) * # idx_avg_choices.view(-1, 1, ctx.num_emb), 0) grad_emb = torch.sum(grad_output.data.view(-1, 1) * idx_avg_choices.view(-1, ctx.num_emb), 0, keepdim=True) # new2 return grad_input, grad_emb, None, None def nearest_embed(x, emb): return NearestEmbedFunc().apply(x, emb) class NearestEmbed(nn.Module): def __init__(self, num_embeddings, embeddings_dim, rd_init=True): super(NearestEmbed, self).__init__() if rd_init: self.weight = nn.Parameter(torch.rand(embeddings_dim, num_embeddings)) else: # self.weight = nn.Parameter(torch.linspace(0.0, 1.0, num_embeddings).unsqueeze(0).expand(embeddings_dim, num_embeddings)) self.weight = nn.Parameter(torch.linspace(lin_min, lin_max, num_embeddings).unsqueeze(0).expand(embeddings_dim, num_embeddings)) print('Init emb weight:', self.weight.data) def forward(self, x, weight_sg=False): """Input: --------- x - (batch_size, emb_size, *) """ return nearest_embed(x, self.weight.detach() if weight_sg else self.weight) # adapted from https://github.com/rosinality/vq-vae-2-pytorch/blob/master/vqvae.py#L25 # that adapted from https://github.com/deepmind/sonnet class NearestEmbedEMA(nn.Module): def __init__(self, n_emb, emb_dim, decay=0.99, eps=1e-5, rd_init=True): super(NearestEmbedEMA, self).__init__() self.decay = decay self.eps = eps self.embeddings_dim = emb_dim self.n_emb = n_emb self.emb_dim = emb_dim if rd_init: embed = torch.rand(emb_dim, n_emb) else: # embed = torch.linspace(0.0, 1.0, n_emb).unsqueeze(0).expand(emb_dim, n_emb) embed = torch.linspace(lin_min, lin_max, n_emb).unsqueeze(0).expand(emb_dim, n_emb) self.register_buffer('weight', embed) self.register_buffer('cluster_size', torch.zeros(n_emb)) self.register_buffer('embed_avg', embed.clone()) print('Init emb weight ema:', self.weight.data) def forward(self, x, weight_sg=None): """Input: --------- x - (batch_size, emb_size, *) """ emb_ex = self.weight.expand(x.size(1), self.weight.size(1)) # new2 #emb_avg_ex = self.embed_avg.expand(x.size(1), self.weight.size(1)) # new2 dims = list(range(len(x.size()))) x_expanded = x.unsqueeze(-1) num_arbitrary_dims = len(dims) - 2 # if num_arbitrary_dims: # emb_expanded = self.weight.view(self.emb_dim, *([1] * num_arbitrary_dims), self.n_emb) # else: # emb_expanded = self.weight emb_size = x.size(1) if num_arbitrary_dims: #emb_expanded = self.weight.expand(emb_size, self.n_emb).view(self.emb_dim, *([1] * num_arbitrary_dims), self.n_emb) emb_expanded = emb_ex.expand(emb_size, self.n_emb).view(self.emb_dim, *([1] * num_arbitrary_dims), self.n_emb) else: #emb_expanded = self.weight.expand(emb_size, self.n_emb) emb_expanded = emb_ex.expand(emb_size, self.n_emb) # find nearest neighbors # dist = torch.norm(x_expanded - emb_expanded, 2, 1) dist = torch.pow(x_expanded - emb_expanded, 2) # (batch_size, emb_dim, *, num_emb) # new2 _, argmin = dist.min(-1) shifted_shape = [x.shape[0], *list(x.shape[2:]), x.shape[1]] # result = emb_ex.t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, dims[-1], *dims[1:-1]) # (batch_size, emb_dim, *, num_emb) # new2 result = self.weight.t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, dims[-1], *dims[1:-1]) # (batch_size, emb_dim, *, num_emb) # new2 # result = self.weight.expand(emb_size, self.n_emb).t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, dims[-1], *dims[1:-1]) if self.training: latent_indices = torch.arange(self.n_emb).type_as(argmin) emb_onehot = (argmin.view(-1, 1) == latent_indices.view(1, -1)).type_as(x.data) n_idx_choice = emb_onehot.sum(0) n_idx_choice[n_idx_choice == 0] = 1 # pdb.set_trace() # flatten = x.permute(1, 0, *dims[-2:]).contiguous().view(x.shape[1], -1) num_arbitrary_dims = len(dims) - 2 if num_arbitrary_dims: # flatten = x.permute(1, 0, *dims[-2:]).contiguous().view(x.shape[1], -1) # flatten = x.permute(1, 0, *dims[-2:]).contiguous().view(1, -1) flatten = x.view(1, -1) else: # flatten = x.permute(1, 0).contiguous() # flatten = x.permute(1, 0).contiguous().view(1, -1) flatten = x.view(1, -1) self.cluster_size.data.mul_(self.decay).add_( 1 - self.decay, n_idx_choice ) # pdb.set_trace() embed_sum = flatten @ emb_onehot # -----dc0.99 # embed_sum = torch.pow(flatten.t() - emb_onehot, 2).mean(0) # ----dc0.99_s #pdb.set_trace() self.embed_avg.data.mul_(self.decay).add_(1 - self.decay, embed_sum) #emb_avg_ex.data.mul_(self.decay).add_(1 - self.decay, embed_sum) #pdb.set_trace() n = self.cluster_size.sum() cluster_size = ( (self.cluster_size + self.eps) / (n + self.n_emb * self.eps) * n ) embed_normalized = self.embed_avg / cluster_size.unsqueeze(0) self.weight.data.copy_(embed_normalized) # ---dc0.99 # self.weight.data.copy_(self.embed_avg) # -------dc0.99_s #embed_normalized = emb_avg_ex / cluster_size.unsqueeze(0) #self.weight.data.copy_(embed_normalized.mean(0, keepdim=True)) #self.embed_avg.data.copy_(emb_avg_ex.mean(0, keepdim=True)) return result, argmin
43.713592
162
0.595447
import numpy as np import torch from torch import nn from torch.autograd import Function, Variable import torch.nn.functional as F from config import * import pdb class NearestEmbedFunc(Function): @staticmethod def forward(ctx, input, emb): emb_ex = emb.expand(input.size(1), emb.size(1)) ctx.batch_size = input.size(0) ctx.num_latents = int(np.prod(np.array(input.size()[2:]))) ctx.emb_dim = emb_ex.size(0) ctx.num_emb = emb_ex.size(1) ctx.input_type = type(input) ctx.dims = list(range(len(input.size()))) x_expanded = input.unsqueeze(-1) num_arbitrary_dims = len(ctx.dims) - 2 if num_arbitrary_dims: emb_expanded = emb_ex.view(emb_ex.shape[0], *([1] * num_arbitrary_dims), emb_ex.shape[1]) else: emb_expanded = emb_ex dist = torch.pow(x_expanded - emb_expanded, 2) _, argmin = dist.min(-1) shifted_shape = [input.shape[0], *list(input.shape[2:]) ,input.shape[1]] result = emb.t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, ctx.dims[-1], *ctx.dims[1:-1]) ctx.save_for_backward(argmin) return result.contiguous(), argmin @staticmethod def backward(ctx, grad_output, argmin=None): grad_input = grad_emb = None if ctx.needs_input_grad[0]: grad_input = grad_output if ctx.needs_input_grad[1]: argmin, = ctx.saved_variables latent_indices = torch.arange(ctx.num_emb).type_as(argmin) idx_choices = (argmin.view(-1, 1) == latent_indices.view(1, -1)).type_as(grad_output.data) n_idx_choice = idx_choices.sum(0) n_idx_choice[n_idx_choice == 0] = 1 idx_avg_choices = idx_choices / n_idx_choice grad_output = grad_output.permute(0, *ctx.dims[2:], 1).contiguous() grad_output = grad_output.view(ctx.batch_size * ctx.num_latents, ctx.emb_dim) grad_emb = torch.sum(grad_output.data.view(-1, 1) * idx_avg_choices.view(-1, ctx.num_emb), 0, keepdim=True) return grad_input, grad_emb, None, None def nearest_embed(x, emb): return NearestEmbedFunc().apply(x, emb) class NearestEmbed(nn.Module): def __init__(self, num_embeddings, embeddings_dim, rd_init=True): super(NearestEmbed, self).__init__() if rd_init: self.weight = nn.Parameter(torch.rand(embeddings_dim, num_embeddings)) else: self.weight = nn.Parameter(torch.linspace(lin_min, lin_max, num_embeddings).unsqueeze(0).expand(embeddings_dim, num_embeddings)) print('Init emb weight:', self.weight.data) def forward(self, x, weight_sg=False): return nearest_embed(x, self.weight.detach() if weight_sg else self.weight) class NearestEmbedEMA(nn.Module): def __init__(self, n_emb, emb_dim, decay=0.99, eps=1e-5, rd_init=True): super(NearestEmbedEMA, self).__init__() self.decay = decay self.eps = eps self.embeddings_dim = emb_dim self.n_emb = n_emb self.emb_dim = emb_dim if rd_init: embed = torch.rand(emb_dim, n_emb) else: embed = torch.linspace(lin_min, lin_max, n_emb).unsqueeze(0).expand(emb_dim, n_emb) self.register_buffer('weight', embed) self.register_buffer('cluster_size', torch.zeros(n_emb)) self.register_buffer('embed_avg', embed.clone()) print('Init emb weight ema:', self.weight.data) def forward(self, x, weight_sg=None): emb_ex = self.weight.expand(x.size(1), self.weight.size(1)) dims = list(range(len(x.size()))) x_expanded = x.unsqueeze(-1) num_arbitrary_dims = len(dims) - 2 emb_size = x.size(1) if num_arbitrary_dims: emb_expanded = emb_ex.expand(emb_size, self.n_emb).view(self.emb_dim, *([1] * num_arbitrary_dims), self.n_emb) else: emb_expanded = emb_ex.expand(emb_size, self.n_emb) dist = torch.pow(x_expanded - emb_expanded, 2) _, argmin = dist.min(-1) shifted_shape = [x.shape[0], *list(x.shape[2:]), x.shape[1]] , argmin.view(-1)).view(shifted_shape).permute(0, dims[-1], *dims[1:-1]) if self.training: latent_indices = torch.arange(self.n_emb).type_as(argmin) emb_onehot = (argmin.view(-1, 1) == latent_indices.view(1, -1)).type_as(x.data) n_idx_choice = emb_onehot.sum(0) n_idx_choice[n_idx_choice == 0] = 1 num_arbitrary_dims = len(dims) - 2 if num_arbitrary_dims: flatten = x.view(1, -1) else: flatten = x.view(1, -1) self.cluster_size.data.mul_(self.decay).add_( 1 - self.decay, n_idx_choice ) embed_sum = flatten @ emb_onehot self.embed_avg.data.mul_(self.decay).add_(1 - self.decay, embed_sum) n = self.cluster_size.sum() cluster_size = ( (self.cluster_size + self.eps) / (n + self.n_emb * self.eps) * n ) embed_normalized = self.embed_avg / cluster_size.unsqueeze(0) self.weight.data.copy_(embed_normalized) return result, argmin
true
true
f714ba426a5248f82458ccc103e4f061235d9e45
436
py
Python
venv/Scripts/easy_install-3.6-script.py
ololostapenko/bankera
5c9093785fa02ef4aa002249ac2ae04a364de44d
[ "Apache-2.0" ]
null
null
null
venv/Scripts/easy_install-3.6-script.py
ololostapenko/bankera
5c9093785fa02ef4aa002249ac2ae04a364de44d
[ "Apache-2.0" ]
null
null
null
venv/Scripts/easy_install-3.6-script.py
ololostapenko/bankera
5c9093785fa02ef4aa002249ac2ae04a364de44d
[ "Apache-2.0" ]
null
null
null
#!C:\Devel\Bankera\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==28.8.0','console_scripts','easy_install-3.6' __requires__ = 'setuptools==28.8.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('setuptools==28.8.0', 'console_scripts', 'easy_install-3.6')() )
33.538462
87
0.683486
__requires__ = 'setuptools==28.8.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('setuptools==28.8.0', 'console_scripts', 'easy_install-3.6')() )
true
true
f714bd81cb12dc993d3ec9237a0c0ed41807641a
222
py
Python
docs/source/working/include/snippets/processes/functions/calcfunction_multiple_outputs.py
pranavmodx/aiida-core
0edbbf82dfb97ab130914d1674a6f2217eba5971
[ "BSD-2-Clause", "MIT" ]
1
2019-07-31T04:08:13.000Z
2019-07-31T04:08:13.000Z
docs/source/working/include/snippets/processes/functions/calcfunction_multiple_outputs.py
odarbelaeze/aiida_core
934b4ccdc73a993f2a6656caf516500470e3da08
[ "BSD-2-Clause" ]
null
null
null
docs/source/working/include/snippets/processes/functions/calcfunction_multiple_outputs.py
odarbelaeze/aiida_core
934b4ccdc73a993f2a6656caf516500470e3da08
[ "BSD-2-Clause" ]
null
null
null
from aiida.engine import calcfunction from aiida.orm import Int @calcfunction def sum_and_difference(alpha, beta): return {'sum': alpha + beta, 'difference': alpha - beta} result = sum_and_difference(Int(1), Int(2))
24.666667
60
0.743243
from aiida.engine import calcfunction from aiida.orm import Int @calcfunction def sum_and_difference(alpha, beta): return {'sum': alpha + beta, 'difference': alpha - beta} result = sum_and_difference(Int(1), Int(2))
true
true
f714bdafd960a7b2117b4f5520697b701e88a097
10,522
py
Python
tensorflow_federated/python/research/optimization/stackoverflow/dataset.py
hartmanwilliam/federated
55e5fcbfde13ac4788f084e4c3c4714130cd19ec
[ "Apache-2.0" ]
1
2020-10-30T10:38:46.000Z
2020-10-30T10:38:46.000Z
tensorflow_federated/python/research/optimization/stackoverflow/dataset.py
hartmanwilliam/federated
55e5fcbfde13ac4788f084e4c3c4714130cd19ec
[ "Apache-2.0" ]
8
2019-08-06T06:12:07.000Z
2019-12-19T02:06:17.000Z
tensorflow_federated/python/research/optimization/stackoverflow/dataset.py
Junyangz/federated
ecf51cdf8b86cbd000f6edc5715dc904bce07540
[ "Apache-2.0" ]
null
null
null
# Lint as: python3 # Copyright 2019, The TensorFlow Federated 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. """Data loader for Stackoverflow.""" from typing import List import numpy as np import tensorflow as tf import tensorflow_federated as tff EVAL_BATCH_SIZE = 100 def create_vocab(vocab_size): """Creates vocab from `vocab_size` most common words in Stackoverflow.""" vocab_dict = tff.simulation.datasets.stackoverflow.load_word_counts() return list(vocab_dict.keys())[:vocab_size] def split_input_target(chunk): """Generate input and target data. The task of language model is to predict the next word. Args: chunk: A Tensor of text data. Returns: A namedtuple of input and target data. """ input_text = tf.map_fn(lambda x: x[:-1], chunk) target_text = tf.map_fn(lambda x: x[1:], chunk) return (input_text, target_text) def build_to_ids_fn(vocab, max_seq_len): """Constructs function mapping examples to sequences of token indices.""" _, _, bos, eos = get_special_tokens(len(vocab)) table_values = np.arange(len(vocab), dtype=np.int64) table = tf.lookup.StaticVocabularyTable( tf.lookup.KeyValueTensorInitializer(vocab, table_values), num_oov_buckets=1) def to_ids(example): sentence = tf.reshape(example['tokens'], shape=[1]) words = tf.strings.split(sentence, sep=' ').values truncated_words = words[:max_seq_len] tokens = table.lookup(truncated_words) + 1 tokens = tf.cond( tf.less(tf.size(tokens), max_seq_len), lambda: tf.concat([tokens, [eos]], 0), lambda: tokens) return tf.concat([[bos], tokens], 0) return to_ids def batch_and_split(dataset, max_seq_len, batch_size): return dataset.padded_batch( batch_size, padded_shapes=[max_seq_len + 1]).map( split_input_target, num_parallel_calls=tf.data.experimental.AUTOTUNE) def get_special_tokens(vocab_size): """Gets tokens dataset preprocessing code will add to Stackoverflow.""" pad = 0 oov = vocab_size + 1 bos = vocab_size + 2 eos = vocab_size + 3 return pad, oov, bos, eos def create_train_dataset_preprocess_fn(vocab: List[str], client_batch_size: int, client_epochs_per_round: int, max_seq_len: int, max_training_elements_per_user: int, max_shuffle_buffer_size=10000): """Creates preprocessing functions for stackoverflow data. This function returns a function which takes a dataset and returns a dataset, generally for mapping over a set of unprocessed client datasets during training. Args: vocab: Vocabulary which defines the embedding. client_batch_size: Integer representing batch size to use on the clients. client_epochs_per_round: Number of epochs for which to repeat train client dataset. max_seq_len: Integer determining shape of padded batches. Sequences will be padded up to this length, and sentences longer than `max_seq_len` will be truncated to this length. max_training_elements_per_user: Integer controlling the maximum number of elements to take per user. If -1, takes all elements for each user. max_shuffle_buffer_size: Maximum shuffle buffer size. Returns: Two functions, the first `preprocess_train` and the second `preprocess_val_and_test`, as described above. """ if client_batch_size <= 0: raise ValueError('client_batch_size must be a positive integer; you have ' 'passed {}'.format(client_batch_size)) elif client_epochs_per_round <= 0: raise ValueError('client_epochs_per_round must be a positive integer; you ' 'have passed {}'.format(client_epochs_per_round)) elif max_seq_len <= 0: raise ValueError('max_seq_len must be a positive integer; you have ' 'passed {}'.format(max_seq_len)) elif max_training_elements_per_user < -1: raise ValueError( 'max_training_elements_per_user must be an integer at ' 'least -1; you have passed {}'.format(max_training_elements_per_user)) if (max_training_elements_per_user == -1 or max_training_elements_per_user > max_shuffle_buffer_size): shuffle_buffer_size = max_shuffle_buffer_size else: shuffle_buffer_size = max_training_elements_per_user # TODO(b/155408842): need further investigation on why `tff.tf_compuation` # decorator causes b/153363900 for `to_ids`, and large memory consumption. def preprocess_train(dataset): to_ids = build_to_ids_fn(vocab, max_seq_len) dataset = dataset.take(max_training_elements_per_user) dataset = dataset.shuffle(shuffle_buffer_size) dataset = dataset.repeat(client_epochs_per_round) dataset = dataset.map( to_ids, num_parallel_calls=tf.data.experimental.AUTOTUNE) return batch_and_split(dataset, max_seq_len, client_batch_size) return preprocess_train def create_test_dataset_preprocess_fn(vocab: List[str], max_seq_len: int): """Creates preprocessing functions for stackoverflow data. This function returns a function which represents preprocessing logic for use on centralized validation and test datasets outside of TFF. Args: vocab: Vocabulary which defines the embedding. max_seq_len: Integer determining shape of padded batches. Sequences will be padded up to this length, and sentences longer than `max_seq_len` will be truncated to this length. Returns: `preprocess_val_and_test`, as described above. """ if max_seq_len <= 0: raise ValueError('max_seq_len must be a positive integer; you have ' 'passed {}'.format(max_seq_len)) def preprocess_val_and_test(dataset): to_ids = build_to_ids_fn(vocab, max_seq_len) id_dataset = dataset.map( to_ids, num_parallel_calls=tf.data.experimental.AUTOTUNE) return batch_and_split(id_dataset, max_seq_len, EVAL_BATCH_SIZE) return preprocess_val_and_test def construct_word_level_datasets(vocab_size: int, client_batch_size: int, client_epochs_per_round: int, max_seq_len: int, max_training_elements_per_user: int, num_validation_examples: int, max_shuffle_buffer_size=10000): """Preprocessing for Stackoverflow data. Notice that this preprocessing function *ignores* the heldout Stackoverflow dataset for consistency with the other datasets in the proposed optimization paper, and returns a validation/test split of the Stackoverflow "test" data, containing more examples from users in the Stackoverflow train dataset. Args: vocab_size: Integer representing size of the vocab to use. Vocabulary will then be the `vocab_size` most frequent words in the Stackoverflow dataset. client_batch_size: Integer representing batch size to use on the clients. client_epochs_per_round: Number of epochs for which to repeat train client dataset. max_seq_len: Integer determining shape of padded batches. Sequences will be padded up to this length, and sentences longer than `max_seq_len` will be truncated to this length. max_training_elements_per_user: Integer controlling the maximum number of elements to take per user. If -1, takes all elements for each user. num_validation_examples: Number of examples from Stackoverflow test set to use for validation on each round. max_shuffle_buffer_size: Maximum shuffle buffer size. Returns: stackoverflow_train: An instance of `tff.simulation.ClientData` representing Stackoverflow data for training. stackoverflow_validation: A split of the Stackoverflow Test data as outlined in `tff.simulation.datasets.stackoverflow`, containing at most `num_validation_examples` examples. stackoverflow_test: A split of the same Stackoverflow Test data containing the examples not used in `stackoverflow_validation`. """ if num_validation_examples < 1: raise ValueError( 'num_validation_examples must be an integer at ' 'least 1; you have passed {}'.format(num_validation_examples)) elif vocab_size <= 0: raise ValueError('vocab_size must be a positive integer; you have ' 'passed {}'.format(vocab_size)) (stackoverflow_train, _, stackoverflow_test) = tff.simulation.datasets.stackoverflow.load_data() vocab = create_vocab(vocab_size) raw_test_dataset = stackoverflow_test.create_tf_dataset_from_all_clients() preprocess_train = create_train_dataset_preprocess_fn( vocab, client_batch_size, client_epochs_per_round, max_seq_len, max_training_elements_per_user, max_shuffle_buffer_size) preprocess_val_and_test = create_test_dataset_preprocess_fn( vocab, max_seq_len) stackoverflow_train = stackoverflow_train.preprocess(preprocess_train) stackoverflow_val = preprocess_val_and_test( raw_test_dataset.take(num_validation_examples)) stackoverflow_test = preprocess_val_and_test( raw_test_dataset.skip(num_validation_examples)) return stackoverflow_train, stackoverflow_val, stackoverflow_test def get_centralized_train_dataset(vocab_size: int, batch_size: int, max_seq_len: int, shuffle_buffer_size: int = 10000): """Creates centralized approximately shuffled train dataset.""" vocab = create_vocab(vocab_size) to_ids = build_to_ids_fn(vocab, max_seq_len) train, _, _ = tff.simulation.datasets.stackoverflow.load_data() train = train.create_tf_dataset_from_all_clients() train = train.shuffle(buffer_size=shuffle_buffer_size) return batch_and_split( train.map(to_ids, num_parallel_calls=tf.data.experimental.AUTOTUNE), max_seq_len, batch_size)
40.625483
80
0.720776
from typing import List import numpy as np import tensorflow as tf import tensorflow_federated as tff EVAL_BATCH_SIZE = 100 def create_vocab(vocab_size): vocab_dict = tff.simulation.datasets.stackoverflow.load_word_counts() return list(vocab_dict.keys())[:vocab_size] def split_input_target(chunk): input_text = tf.map_fn(lambda x: x[:-1], chunk) target_text = tf.map_fn(lambda x: x[1:], chunk) return (input_text, target_text) def build_to_ids_fn(vocab, max_seq_len): _, _, bos, eos = get_special_tokens(len(vocab)) table_values = np.arange(len(vocab), dtype=np.int64) table = tf.lookup.StaticVocabularyTable( tf.lookup.KeyValueTensorInitializer(vocab, table_values), num_oov_buckets=1) def to_ids(example): sentence = tf.reshape(example['tokens'], shape=[1]) words = tf.strings.split(sentence, sep=' ').values truncated_words = words[:max_seq_len] tokens = table.lookup(truncated_words) + 1 tokens = tf.cond( tf.less(tf.size(tokens), max_seq_len), lambda: tf.concat([tokens, [eos]], 0), lambda: tokens) return tf.concat([[bos], tokens], 0) return to_ids def batch_and_split(dataset, max_seq_len, batch_size): return dataset.padded_batch( batch_size, padded_shapes=[max_seq_len + 1]).map( split_input_target, num_parallel_calls=tf.data.experimental.AUTOTUNE) def get_special_tokens(vocab_size): pad = 0 oov = vocab_size + 1 bos = vocab_size + 2 eos = vocab_size + 3 return pad, oov, bos, eos def create_train_dataset_preprocess_fn(vocab: List[str], client_batch_size: int, client_epochs_per_round: int, max_seq_len: int, max_training_elements_per_user: int, max_shuffle_buffer_size=10000): if client_batch_size <= 0: raise ValueError('client_batch_size must be a positive integer; you have ' 'passed {}'.format(client_batch_size)) elif client_epochs_per_round <= 0: raise ValueError('client_epochs_per_round must be a positive integer; you ' 'have passed {}'.format(client_epochs_per_round)) elif max_seq_len <= 0: raise ValueError('max_seq_len must be a positive integer; you have ' 'passed {}'.format(max_seq_len)) elif max_training_elements_per_user < -1: raise ValueError( 'max_training_elements_per_user must be an integer at ' 'least -1; you have passed {}'.format(max_training_elements_per_user)) if (max_training_elements_per_user == -1 or max_training_elements_per_user > max_shuffle_buffer_size): shuffle_buffer_size = max_shuffle_buffer_size else: shuffle_buffer_size = max_training_elements_per_user def preprocess_train(dataset): to_ids = build_to_ids_fn(vocab, max_seq_len) dataset = dataset.take(max_training_elements_per_user) dataset = dataset.shuffle(shuffle_buffer_size) dataset = dataset.repeat(client_epochs_per_round) dataset = dataset.map( to_ids, num_parallel_calls=tf.data.experimental.AUTOTUNE) return batch_and_split(dataset, max_seq_len, client_batch_size) return preprocess_train def create_test_dataset_preprocess_fn(vocab: List[str], max_seq_len: int): if max_seq_len <= 0: raise ValueError('max_seq_len must be a positive integer; you have ' 'passed {}'.format(max_seq_len)) def preprocess_val_and_test(dataset): to_ids = build_to_ids_fn(vocab, max_seq_len) id_dataset = dataset.map( to_ids, num_parallel_calls=tf.data.experimental.AUTOTUNE) return batch_and_split(id_dataset, max_seq_len, EVAL_BATCH_SIZE) return preprocess_val_and_test def construct_word_level_datasets(vocab_size: int, client_batch_size: int, client_epochs_per_round: int, max_seq_len: int, max_training_elements_per_user: int, num_validation_examples: int, max_shuffle_buffer_size=10000): if num_validation_examples < 1: raise ValueError( 'num_validation_examples must be an integer at ' 'least 1; you have passed {}'.format(num_validation_examples)) elif vocab_size <= 0: raise ValueError('vocab_size must be a positive integer; you have ' 'passed {}'.format(vocab_size)) (stackoverflow_train, _, stackoverflow_test) = tff.simulation.datasets.stackoverflow.load_data() vocab = create_vocab(vocab_size) raw_test_dataset = stackoverflow_test.create_tf_dataset_from_all_clients() preprocess_train = create_train_dataset_preprocess_fn( vocab, client_batch_size, client_epochs_per_round, max_seq_len, max_training_elements_per_user, max_shuffle_buffer_size) preprocess_val_and_test = create_test_dataset_preprocess_fn( vocab, max_seq_len) stackoverflow_train = stackoverflow_train.preprocess(preprocess_train) stackoverflow_val = preprocess_val_and_test( raw_test_dataset.take(num_validation_examples)) stackoverflow_test = preprocess_val_and_test( raw_test_dataset.skip(num_validation_examples)) return stackoverflow_train, stackoverflow_val, stackoverflow_test def get_centralized_train_dataset(vocab_size: int, batch_size: int, max_seq_len: int, shuffle_buffer_size: int = 10000): vocab = create_vocab(vocab_size) to_ids = build_to_ids_fn(vocab, max_seq_len) train, _, _ = tff.simulation.datasets.stackoverflow.load_data() train = train.create_tf_dataset_from_all_clients() train = train.shuffle(buffer_size=shuffle_buffer_size) return batch_and_split( train.map(to_ids, num_parallel_calls=tf.data.experimental.AUTOTUNE), max_seq_len, batch_size)
true
true
f714bdbc502cd21e6811596121f81b0a678e8f1c
478
py
Python
setup.py
danielsiwiec/jetbot
3b0e57dd1eb3a5d274e7e5bbf0623924e42258b6
[ "MIT" ]
5
2019-12-09T20:49:59.000Z
2022-03-10T18:13:23.000Z
setup.py
SnowMasaya/jetbot
534b7d9b88988b96a228676e2a9f8e92119d86dd
[ "MIT" ]
4
2019-09-23T17:50:31.000Z
2019-09-23T17:52:35.000Z
setup.py
SnowMasaya/jetbot
534b7d9b88988b96a228676e2a9f8e92119d86dd
[ "MIT" ]
8
2019-06-09T12:44:10.000Z
2020-08-31T10:32:14.000Z
import glob import subprocess from setuptools import setup, find_packages, Extension def build_libs(): subprocess.call(['cmake', '.']) subprocess.call(['make']) build_libs() setup( name='jetbot', version='0.3.0', description='An open-source robot based on NVIDIA Jetson Nano', packages=find_packages(), install_requires=[ 'Adafruit_MotorHat', 'Adafruit-SSD1306', ], package_data={'jetbot': ['ssd_tensorrt/*.so']}, )
19.12
67
0.648536
import glob import subprocess from setuptools import setup, find_packages, Extension def build_libs(): subprocess.call(['cmake', '.']) subprocess.call(['make']) build_libs() setup( name='jetbot', version='0.3.0', description='An open-source robot based on NVIDIA Jetson Nano', packages=find_packages(), install_requires=[ 'Adafruit_MotorHat', 'Adafruit-SSD1306', ], package_data={'jetbot': ['ssd_tensorrt/*.so']}, )
true
true
f714be8826c14195468efb9f011bb9edd0b15aca
1,877
py
Python
viz/scenes/base.py
entzian/spats
cb0d9f1f3c0fbcb3c333096d657ef96f7179de46
[ "BSL-1.0" ]
4
2016-11-27T04:44:41.000Z
2019-10-08T18:32:51.000Z
viz/scenes/base.py
entzian/spats
cb0d9f1f3c0fbcb3c333096d657ef96f7179de46
[ "BSL-1.0" ]
1
2017-12-18T22:02:28.000Z
2017-12-18T22:02:28.000Z
viz/scenes/base.py
entzian/spats
cb0d9f1f3c0fbcb3c333096d657ef96f7179de46
[ "BSL-1.0" ]
3
2016-06-10T11:36:00.000Z
2021-08-30T18:25:18.000Z
import cjb.uif from cjb.uif.views import Label from viz.layout import buttonSize class BaseScene(cjb.uif.Scene): def __init__(self, ui, key = None): self.ui = ui self.scroller = None cjb.uif.Scene.__init__(self, ui.manager, key or self.__class__.__name__) self.container.properties['sendKeys'] = 1 def build(self): # common UI if self.key != 'Home': self.targetButtons([self.ui.home, self.back]) def layout(self, view): # common layout home = self.buttonWithKey('home') if home: home.frame = view.frame.bottomRightSubrect(size = buttonSize, margin = 10) back = self.buttonWithKey('back') if back: back.frame = view.frame.topRightSubrect(size = buttonSize, margin = 10) return view def back(self, message = None): self.ui.popScene() def addLabel(self, txt, bg = None): return self.addView(Label(txt, fontSize = 11, bg = bg)) def addModelView(self, obj): return self.addView(cjb.uif.views.Button(obj = obj)) def addModelViews(self, objs): map(self.addModelView, objs) def handleViewMessage(self, scene, obj, message): if obj: if isinstance(obj, Relationship): self.showRelationship(obj) #... else: print("App got message to " + str(obj) + ": " + str(message)) elif message.get('event') == 'key': self.handleKeyEvent(message["arg"]) else: print("App got general message: " + str(message)) def handleKeyEvent(self, keyInfo): if keyInfo["t"] == "h" and 1 == len(keyInfo): self.ui.home() elif keyInfo["t"] == "b" and 1 == len(keyInfo): self.back() else: print("Unhandled key: " + str(keyInfo))
30.274194
86
0.571124
import cjb.uif from cjb.uif.views import Label from viz.layout import buttonSize class BaseScene(cjb.uif.Scene): def __init__(self, ui, key = None): self.ui = ui self.scroller = None cjb.uif.Scene.__init__(self, ui.manager, key or self.__class__.__name__) self.container.properties['sendKeys'] = 1 def build(self): if self.key != 'Home': self.targetButtons([self.ui.home, self.back]) def layout(self, view): home = self.buttonWithKey('home') if home: home.frame = view.frame.bottomRightSubrect(size = buttonSize, margin = 10) back = self.buttonWithKey('back') if back: back.frame = view.frame.topRightSubrect(size = buttonSize, margin = 10) return view def back(self, message = None): self.ui.popScene() def addLabel(self, txt, bg = None): return self.addView(Label(txt, fontSize = 11, bg = bg)) def addModelView(self, obj): return self.addView(cjb.uif.views.Button(obj = obj)) def addModelViews(self, objs): map(self.addModelView, objs) def handleViewMessage(self, scene, obj, message): if obj: if isinstance(obj, Relationship): self.showRelationship(obj) else: print("App got message to " + str(obj) + ": " + str(message)) elif message.get('event') == 'key': self.handleKeyEvent(message["arg"]) else: print("App got general message: " + str(message)) def handleKeyEvent(self, keyInfo): if keyInfo["t"] == "h" and 1 == len(keyInfo): self.ui.home() elif keyInfo["t"] == "b" and 1 == len(keyInfo): self.back() else: print("Unhandled key: " + str(keyInfo))
true
true