code
stringlengths
22
1.05M
apis
listlengths
1
3.31k
extract_api
stringlengths
75
3.25M
''' ExperimentClass.py: Contains the Experiment Class for reproducing RL Experiments. Purpose: - Stores all relevant parameters in experiment directory for easy reproducibility. - Auto generates plot using chart_utils. - Can document learning activity. ''' # Python imports. from __future__ import print_function import os from collections import defaultdict # Other imports. from simple_rl.utils import chart_utils from simple_rl.experiments.ExperimentParametersClass import ExperimentParameters class Experiment(object): FULL_EXP_FILE_NAME = "full_experiment_data.json" EXP_PARAM_FILE_NAME = "readable_experiment_data.txt" ''' Experiment Class for RL Experiments ''' # Dumps the results in a directory called "results" in the current working dir. RESULTS_DIR = os.path.join(os.getcwd(), "results", "") def __init__(self, agents, mdp, agent_colors=[], params=None, is_episodic=False, is_markov_game=False, is_lifelong=False, track_disc_reward=False, clear_old_results=True, count_r_per_n_timestep=1, cumulative_plot=True, exp_function="run_agents_on_mdp", dir_for_plot="", experiment_name_prefix="", track_success=False, success_reward=None): ''' Args: agents (list) mdp (MDP) agent_colors (list) params (dict) is_episodic (bool) is_markov_game (bool) is_lifelong (bool) clear_old_results (bool) count_r_per_n_timestep (int) cumulative_plot (bool) exp_function (lambda): tracks with run_experiments.py function was called. dir_for_plot (str) experiment_name_prefix (str) track_success (bool) success_reward (int) ''' # Store all relevant bools. self.agents = agents self.agent_colors = range(len(self.agents)) if agent_colors == [] else agent_colors params["track_disc_reward"] = track_disc_reward self.parameters = ExperimentParameters(params) self.mdp = mdp self.track_disc_reward = track_disc_reward self.count_r_per_n_timestep = count_r_per_n_timestep self.steps_since_added_r = 1 self.rew_since_count = 0 self.cumulative_plot = cumulative_plot self.name = str(self.mdp) self.rewards = defaultdict(list) self.times = defaultdict(list) if dir_for_plot == "": self.exp_directory = os.path.join(Experiment.RESULTS_DIR, self.name) else: self.exp_directory = os.path.join(os.getcwd(), dir_for_plot, self.name) self.experiment_name_prefix = experiment_name_prefix self.is_episodic = is_episodic self.is_markov_game = is_markov_game self.track_success = track_success self.success_reward = success_reward self._setup_files(clear_old_results) # Write experiment reproduction file. self._make_and_write_agent_and_mdp_params(agents, mdp, self.parameters.params, exp_function) def _make_and_write_agent_and_mdp_params(self, agents, mdp, parameters, exp_function): ''' Args: agents mdp parameters Summary: Writes enough detail about @agents, @mdp, and @parameters to the file results/<exp_name>/params.txt so that the function simple_rl.run_experiments.reproduce_from_exp_file can rerun the experiment. ''' import json out_file = open(os.path.join(self.exp_directory, Experiment.FULL_EXP_FILE_NAME), "w") if not self._is_valid_mdp_type(mdp): print("Warning (simple_rl): Cannot track and reproduce experiments for MDPs of type `" + str(type(mdp)) + "'.") return # Dict to hold all experiment info to write to json. all_exp_info_dict = {} # MDP. mdp_class = str(type(mdp)) mdp_params = mdp.get_parameters() all_exp_info_dict["MDP"] = {"name":mdp_class, "params":mdp_params} # Get agents and their parameters. all_exp_info_dict["AGENTS"] = defaultdict(lambda: defaultdict(str)) for i, agent in enumerate(agents): agent_params = agent.get_parameters() agent_class = str(type(agent)) all_exp_info_dict["AGENTS"][agent_class]["params"] = agent_params all_exp_info_dict["AGENTS"][agent_class]["index"] = i # Misc. Params. all_exp_info_dict["MISC"] = parameters # Function called. all_exp_info_dict["FUNC"] = exp_function # Encode and store. from simple_rl.utils.additional_datastructures import TupleEncoder encoder = TupleEncoder() data_to_store = encoder.encode(all_exp_info_dict) load_enc = json.loads(data_to_store) json.dump(load_enc, out_file, indent=4) out_file.close() return def _is_valid_mdp_type(self, mdp): from simple_rl.mdp import OOMDP, MDPDistribution from simple_rl.pomdp.POMDPClass import POMDP from simple_rl.mdp.markov_game.MarkovGameMDPClass import MarkovGameMDP from simple_rl.tasks import BanditMDP if isinstance(mdp, OOMDP) \ or isinstance(mdp, POMDP) \ or isinstance(mdp, MarkovGameMDP) \ or isinstance(mdp, MDPDistribution) \ or isinstance(mdp, BanditMDP): return False return True def _setup_files(self, clear_old_results=True): ''' Summary: Creates and removes relevant directories/files. ''' if not os.path.exists(os.path.join(self.exp_directory, "")): os.makedirs(self.exp_directory) elif clear_old_results: for agent in self.agents: if os.path.exists(os.path.join(self.exp_directory, str(agent)) + ".csv"): os.remove(os.path.join(self.exp_directory, str(agent)) + ".csv") if os.path.exists(os.path.join(self.exp_directory, "times", str(agent)) + ".csv"): os.remove(os.path.join(self.exp_directory, "times", str(agent)) + ".csv") if os.path.exists(os.path.join(self.exp_directory, "success", str(agent)) + ".csv"): os.remove(os.path.join(self.exp_directory, "success", str(agent)) + ".csv") self.write_exp_info_to_file() def make_plots(self, open_plot=True): ''' Summary: Makes plots for the current experiment. ''' if self.is_markov_game: agent_name_ls = [agent_name for agent_name in self.agents.keys()] else: agent_name_ls = [a.get_name() for a in self.agents] if self.experiment_name_prefix != "": plot_file_name = self.experiment_name_prefix + str(self.mdp) else: plot_file_name = "" chart_utils.make_plots(self.exp_directory, agent_name_ls, episodic=self.is_episodic, plot_file_name=plot_file_name, cumulative=self.cumulative_plot, track_disc_reward=self.track_disc_reward, open_plot=open_plot) if self.track_success: print(os.path.join("success", self.exp_directory)) chart_utils.make_plots(os.path.join(self.exp_directory, "success"), agent_name_ls, episodic=True, plot_file_name="success_rate", cumulative=False, track_disc_reward=False, open_plot=open_plot, new_title="Success Rate", new_x_label="Episode Number", new_y_label="Avg. Success %") def _write_extra_datum_to_file(self, mdp_name, agent, datum, datum_name): out_file = open(os.path.join(self.exp_directory, str(agent)) + "-" + datum_name + ".csv", "a+") out_file.write(str(datum) + ",") out_file.close() def get_agent_avg_cumulative_rew(self, agent): result_file = open(os.path.join(self.exp_directory, str(agent)) + ".csv", "r") total = 0 num_lines = 0 for line in result_file.readlines(): total += sum([float(datum) for datum in line.strip().split(",")[:-1]]) num_lines += 1 result_file.close() return total / num_lines def add_experience(self, agent, state, action, reward, next_state, time_taken=0): ''' Args: agent (agent OR dict): if self.is_markov_game, contains a dict of agents Summary: Record any relevant information about this experience. ''' # Markov Game. if self.is_markov_game: for a in agent: self.rewards[a] += [reward[a]] return # Regular MDP. if self.steps_since_added_r % self.count_r_per_n_timestep == 0: if self.is_markov_game and self.count_r_per_n_timestep > 1: raise ValueError("(simple_rl) Experiment Error: can't track markov games per step. (set rew_step_count to 1).") else: self.rewards[agent] += [self.rew_since_count + reward] self.times[agent] += [time_taken] self.rew_since_count = 0 self.steps_since_added_r = 1 else: self.rew_since_count += reward self.steps_since_added_r += 1 def end_of_episode(self, agent, num_times_to_write=1): ''' Args: agent (str) Summary: Writes reward data from this episode to file and resets the reward. ''' if self.is_episodic: for x in range(num_times_to_write): self.write_datum_to_file(agent, sum(self.rewards[agent])) self.write_datum_to_file(agent, sum(self.times[agent]), extra_dir="times/") if self.track_success: self.write_datum_to_file(agent, int(self.rewards[agent][-1] >= self.success_reward), extra_dir="success/") else: for x in range(num_times_to_write): for step_reward in self.rewards[agent]: self.write_datum_to_file(agent, step_reward) self.rewards[agent] = [] def end_of_instance(self, agent): ''' Summary: Adds a new line to indicate we're onto a new instance. ''' # out_file = open(os.path.join(self.exp_directory, str(agent)) + ".csv", "a+") out_file.write("\n") out_file.close() if self.track_success: out_file = open(os.path.join(self.exp_directory, "success", str(agent)) + ".csv", "a+") out_file.write("\n") out_file.close() if os.path.isdir(os.path.join(self.exp_directory, "times", "")): out_file = open(os.path.join(self.exp_directory, "times", str(agent)) + ".csv", "a+") out_file.write("\n") out_file.close() def write_datum_to_file(self, agent, datum, extra_dir=""): ''' Summary: Writes datum to file. ''' if extra_dir != "" and not os.path.isdir(self.exp_directory + "/" + extra_dir): os.makedirs(os.path.join(self.exp_directory, extra_dir)) out_file = open(os.path.join(self.exp_directory, extra_dir, str(agent)) + ".csv", "a+") out_file.write(str(datum) + ",") out_file.close() def write_exp_info_to_file(self): ''' Summary: Writes relevant experiment information to a file for reproducibility. ''' out_file = open(os.path.join(self.exp_directory, Experiment.EXP_PARAM_FILE_NAME), "w+") to_write_to_file = self._get_exp_file_string() out_file.write(to_write_to_file) out_file.close() def _get_exp_file_string(self): ''' Returns: (str): contains the AGENT-names, the MDP-names, and PARAMETER-information. ''' mdp_text = "(Markov Game MDP)" if self.is_markov_game else "(MDP)" mdp_string = mdp_text + "\n\t" + self.name + "\n" agent_string = "(Agents)\n" for i, agent in enumerate(self.agents): agent_string += "\t" + str(agent) + "," + str(self.agent_colors[i]) + "\n" param_string = "(Params)" + str(self.parameters) + "\n" return mdp_string + agent_string + param_string def __str__(self): return self._get_exp_file_string()
[ "json.loads", "os.makedirs", "simple_rl.utils.additional_datastructures.TupleEncoder", "os.path.join", "simple_rl.utils.chart_utils.make_plots", "os.getcwd", "os.path.isdir", "collections.defaultdict", "simple_rl.experiments.ExperimentParametersClass.ExperimentParameters", "json.dump" ]
[((815, 826), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (824, 826), False, 'import os\n'), ((2325, 2353), 'simple_rl.experiments.ExperimentParametersClass.ExperimentParameters', 'ExperimentParameters', (['params'], {}), '(params)\n', (2345, 2353), False, 'from simple_rl.experiments.ExperimentParametersClass import ExperimentParameters\n'), ((2663, 2680), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2674, 2680), False, 'from collections import defaultdict\n'), ((2702, 2719), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (2713, 2719), False, 'from collections import defaultdict\n'), ((5021, 5035), 'simple_rl.utils.additional_datastructures.TupleEncoder', 'TupleEncoder', ([], {}), '()\n', (5033, 5035), False, 'from simple_rl.utils.additional_datastructures import TupleEncoder\n'), ((5113, 5138), 'json.loads', 'json.loads', (['data_to_store'], {}), '(data_to_store)\n', (5123, 5138), False, 'import json\n'), ((5147, 5186), 'json.dump', 'json.dump', (['load_enc', 'out_file'], {'indent': '(4)'}), '(load_enc, out_file, indent=4)\n', (5156, 5186), False, 'import json\n'), ((7217, 7443), 'simple_rl.utils.chart_utils.make_plots', 'chart_utils.make_plots', (['self.exp_directory', 'agent_name_ls'], {'episodic': 'self.is_episodic', 'plot_file_name': 'plot_file_name', 'cumulative': 'self.cumulative_plot', 'track_disc_reward': 'self.track_disc_reward', 'open_plot': 'open_plot'}), '(self.exp_directory, agent_name_ls, episodic=self.\n is_episodic, plot_file_name=plot_file_name, cumulative=self.\n cumulative_plot, track_disc_reward=self.track_disc_reward, open_plot=\n open_plot)\n', (7239, 7443), False, 'from simple_rl.utils import chart_utils\n'), ((2784, 2831), 'os.path.join', 'os.path.join', (['Experiment.RESULTS_DIR', 'self.name'], {}), '(Experiment.RESULTS_DIR, self.name)\n', (2796, 2831), False, 'import os\n'), ((3830, 3893), 'os.path.join', 'os.path.join', (['self.exp_directory', 'Experiment.FULL_EXP_FILE_NAME'], {}), '(self.exp_directory, Experiment.FULL_EXP_FILE_NAME)\n', (3842, 3893), False, 'import os\n'), ((6001, 6032), 'os.makedirs', 'os.makedirs', (['self.exp_directory'], {}), '(self.exp_directory)\n', (6012, 6032), False, 'import os\n'), ((11308, 11353), 'os.path.join', 'os.path.join', (['self.exp_directory', '"""times"""', '""""""'], {}), "(self.exp_directory, 'times', '')\n", (11320, 11353), False, 'import os\n'), ((12160, 12224), 'os.path.join', 'os.path.join', (['self.exp_directory', 'Experiment.EXP_PARAM_FILE_NAME'], {}), '(self.exp_directory, Experiment.EXP_PARAM_FILE_NAME)\n', (12172, 12224), False, 'import os\n'), ((2892, 2903), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2901, 2903), False, 'import os\n'), ((4452, 4468), 'collections.defaultdict', 'defaultdict', (['str'], {}), '(str)\n', (4463, 4468), False, 'from collections import defaultdict\n'), ((5950, 5986), 'os.path.join', 'os.path.join', (['self.exp_directory', '""""""'], {}), "(self.exp_directory, '')\n", (5962, 5986), False, 'import os\n'), ((7639, 7682), 'os.path.join', 'os.path.join', (['"""success"""', 'self.exp_directory'], {}), "('success', self.exp_directory)\n", (7651, 7682), False, 'import os\n'), ((7719, 7762), 'os.path.join', 'os.path.join', (['self.exp_directory', '"""success"""'], {}), "(self.exp_directory, 'success')\n", (7731, 7762), False, 'import os\n'), ((11690, 11741), 'os.path.isdir', 'os.path.isdir', (["(self.exp_directory + '/' + extra_dir)"], {}), "(self.exp_directory + '/' + extra_dir)\n", (11703, 11741), False, 'import os\n'), ((11767, 11810), 'os.path.join', 'os.path.join', (['self.exp_directory', 'extra_dir'], {}), '(self.exp_directory, extra_dir)\n', (11779, 11810), False, 'import os\n')]
# -*- coding: utf-8 -*- import datetime import hashlib import json import os import socket import subprocess import tempfile import urllib2 import shutil from copy import deepcopy from decimal import Decimal from functools import wraps from tempfile import NamedTemporaryFile from zipfile import BadZipfile from django.conf import settings from django.core.cache import cache from django.core.files.storage import default_storage as storage from django.core.management import call_command from django.core.validators import ValidationError from django.db import transaction from django.template import loader from django.utils.translation import ugettext import celery import waffle from celery.result import AsyncResult from django_statsd.clients import statsd import olympia.core.logger from olympia import amo from olympia.addons.models import Addon, Persona, Preview from olympia.amo.celery import task from olympia.amo.decorators import atomic, set_modified_on, use_primary_db from olympia.amo.urlresolvers import reverse from olympia.amo.utils import ( image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch) from olympia.api.models import SYMMETRIC_JWT_TYPE, APIKey from olympia.applications.management.commands import dump_apps from olympia.files.models import File, FileUpload, FileValidation from olympia.files.utils import parse_addon, SafeZip from olympia.lib.akismet.models import AkismetReport from olympia.versions.compare import version_int from olympia.versions.models import Version log = olympia.core.logger.getLogger('z.devhub.task') def validate(file_, listed=None, subtask=None, synchronous=False, pretask=None): """Run the validator on the given File or FileUpload object. If a task has already begun for this file, instead return an AsyncResult object for that task. file_ can be either a File or FileUpload; if File then listed must be None; if FileUpload listed must be specified.""" # Import loop. from .utils import Validator validator = Validator(file_, listed=listed) task_id = cache.get(validator.cache_key) if not synchronous and task_id: return AsyncResult(task_id) else: # celery.group() | validator.task returns a celery.chord - which works # great in tests (meaning we don't have to rewrite existing tests) but # in non-eager mode celery does nothing and just hangs the validation. # # Thankfully devhub.views.handle_upload now always passes along a value # for pretask but if this is changed it WILL break on dev/stage/prod. # # We HAVE to have a task at the start of the chain that returns a # result (ignore_result=False) as the result from pretask is passed # down to the next task in the chain, validation.task, which is wrapped # in validation_task. If there no task then validation_task fails with # mismatched arguments (same with something like an empty celery.group) # # In a ideal world this would all be rewritten with chords and # parallel tasks in groups and magic. chain = celery.group() if pretask is None else pretask chain |= validator.task if subtask is not None: chain |= subtask if synchronous: result = chain.apply() else: result = chain.delay() cache.set(validator.cache_key, result.task_id, 5 * 60) return result def validate_and_submit(addon, file_, channel, pretask=None): return validate( file_, listed=(channel == amo.RELEASE_CHANNEL_LISTED), subtask=submit_file.si(addon.pk, file_.pk, channel), pretask=pretask) @task @use_primary_db def submit_file(addon_pk, upload_pk, channel): addon = Addon.unfiltered.get(pk=addon_pk) upload = FileUpload.objects.get(pk=upload_pk) if upload.passed_all_validations: create_version_for_upload(addon, upload, channel) else: log.info('Skipping version creation for {upload_uuid} that failed ' 'validation'.format(upload_uuid=upload.uuid)) @atomic def create_version_for_upload(addon, upload, channel): """Note this function is only used for API uploads.""" fileupload_exists = addon.fileupload_set.filter( created__gt=upload.created, version=upload.version).exists() version_exists = Version.unfiltered.filter( addon=addon, version=upload.version).exists() if (fileupload_exists or version_exists): log.info('Skipping Version creation for {upload_uuid} that would ' ' cause duplicate version'.format(upload_uuid=upload.uuid)) else: # Import loop. from olympia.devhub.utils import add_dynamic_theme_tag from olympia.devhub.views import auto_sign_version log.info('Creating version for {upload_uuid} that passed ' 'validation'.format(upload_uuid=upload.uuid)) # Note: if we somehow managed to get here with an invalid add-on, # parse_addon() will raise ValidationError and the task will fail # loudly in sentry. parsed_data = parse_addon(upload, addon, user=upload.user) version = Version.from_upload( upload, addon, [x[0] for x in amo.APPS_CHOICES], channel, parsed_data=parsed_data) # The add-on's status will be STATUS_NULL when its first version is # created because the version has no files when it gets added and it # gets flagged as invalid. We need to manually set the status. if (addon.status == amo.STATUS_NULL and channel == amo.RELEASE_CHANNEL_LISTED): addon.update(status=amo.STATUS_NOMINATED) auto_sign_version(version) add_dynamic_theme_tag(version) def validation_task(fn): """Wrap a validation task so that it runs with the correct flags, then parse and annotate the results before returning. akismet_results is the return from the previous task.""" @task(bind=True, ignore_result=False, # Required for groups/chains. soft_time_limit=settings.VALIDATOR_TIMEOUT) @wraps(fn) def wrapper(task, akismet_results, id_, hash_, *args, **kw): # This is necessary to prevent timeout exceptions from being set # as our result, and replacing the partial validation results we'd # prefer to return. task.ignore_result = True try: data = fn(id_, hash_, *args, **kw) result = json.loads(data) if akismet_results: annotate_akismet_spam_check(result, akismet_results) return result except Exception as e: log.exception('Unhandled error during validation: %r' % e) is_webextension = kw.get('is_webextension', False) if is_webextension: return deepcopy(amo.VALIDATOR_SKELETON_EXCEPTION_WEBEXT) return deepcopy(amo.VALIDATOR_SKELETON_EXCEPTION) finally: # But we do want to return a result after that exception has # been handled. task.ignore_result = False return wrapper @validation_task def validate_file_path(path, hash_, listed=True, is_webextension=False, **kw): """Run the validator against a file at the given path, and return the results. Should only be called directly by Validator.""" if is_webextension: return run_addons_linter(path, listed=listed) return run_validator(path, listed=listed) @validation_task def validate_file(file_id, hash_, is_webextension=False, **kw): """Validate a File instance. If cached validation results exist, return those, otherwise run the validator. Should only be called directly by Validator.""" file_ = File.objects.get(pk=file_id) try: return file_.validation.validation except FileValidation.DoesNotExist: listed = file_.version.channel == amo.RELEASE_CHANNEL_LISTED if is_webextension: return run_addons_linter( file_.current_file_path, listed=listed) return run_validator(file_.current_file_path, listed=listed) @task @use_primary_db def handle_upload_validation_result( results, upload_pk, channel, is_mozilla_signed): """Annotate a set of validation results and save them to the given FileUpload instance.""" upload = FileUpload.objects.get(pk=upload_pk) # Restrictions applying to new legacy submissions apply if: # - It's the very first upload (there is no addon id yet) # - It's the first upload in that channel is_new_upload = ( not upload.addon_id or not upload.addon.find_latest_version(channel=channel, exclude=())) # Annotate results with potential legacy add-ons restrictions. if not is_mozilla_signed: results = annotate_legacy_addon_restrictions( results=results, is_new_upload=is_new_upload) annotate_legacy_langpack_restriction(results=results) # Check for API keys in submissions. # Make sure it is extension-like, e.g. no LWT or search plugin try: results = check_for_api_keys_in_file(results=results, upload=upload) except (ValidationError, BadZipfile, IOError): pass # Annotate results with potential webext warnings on new versions. if upload.addon_id and upload.version: results = annotate_webext_incompatibilities( results=results, file_=None, addon=upload.addon, version_string=upload.version, channel=channel) upload.validation = json.dumps(results) upload.save() # We want to hit the custom save(). # Track the time it took from first upload through validation # until the results were processed and saved. upload_start = utc_millesecs_from_epoch(upload.created) now = datetime.datetime.now() now_ts = utc_millesecs_from_epoch(now) delta = now_ts - upload_start statsd.timing('devhub.validation_results_processed', delta) if not storage.exists(upload.path): # TODO: actually fix this so we can get stats. It seems that # the file maybe gets moved but it needs more investigation. log.warning('Scaled upload stats were not tracked. File is ' 'missing: {}'.format(upload.path)) return size = Decimal(storage.size(upload.path)) megabyte = Decimal(1024 * 1024) # Stash separate metrics for small / large files. quantifier = 'over' if size > megabyte else 'under' statsd.timing( 'devhub.validation_results_processed_{}_1mb'.format(quantifier), delta) # Scale the upload / processing time by package size (in MB) # so we can normalize large XPIs which naturally take longer to validate. scaled_delta = None size_in_mb = size / megabyte if size > 0: # If the package is smaller than 1MB, don't scale it. This should # help account for validator setup time. unit = size_in_mb if size > megabyte else Decimal(1) scaled_delta = Decimal(delta) / unit statsd.timing('devhub.validation_results_processed_per_mb', scaled_delta) log.info('Time to process and save upload validation; ' 'upload.pk={upload}; processing_time={delta}; ' 'scaled_per_mb={scaled}; upload_size_in_mb={size_in_mb}; ' 'created={created}; now={now}' .format(delta=delta, upload=upload.pk, created=upload.created, now=now, scaled=scaled_delta, size_in_mb=size_in_mb)) # We need to explicitly not ignore the result, for the sake of `views.py` code # that needs to wait on a result, rather than just trigger the task to save # the result to a FileValidation object. @task(ignore_result=False) @use_primary_db def handle_file_validation_result(results, file_id, *args): """Annotate a set of validation results and save them to the given File instance.""" file_ = File.objects.get(pk=file_id) annotate_webext_incompatibilities( results=results, file_=file_, addon=file_.version.addon, version_string=file_.version.version, channel=file_.version.channel) return FileValidation.from_json(file_, results).pk def insert_validation_message(results, type_='error', message='', msg_id='', compatibility_type=None): messages = results['messages'] messages.insert(0, { 'tier': 1, 'type': type_, 'id': ['validation', 'messages', msg_id], 'message': message, 'description': [], 'compatibility_type': compatibility_type, }) # Need to increment 'errors' or 'warnings' count, so add an extra 's' after # the type_ to increment the right entry. results['{}s'.format(type_)] += 1 def annotate_legacy_addon_restrictions(results, is_new_upload): """ Annotate validation results to restrict uploads of legacy (non-webextension) add-ons if specific conditions are met. """ metadata = results.get('metadata', {}) is_webextension = metadata.get('is_webextension') is True if is_webextension: # If we're dealing with a webextension, return early as the whole # function is supposed to only care about legacy extensions. return results target_apps = metadata.get('applications', {}) max_target_firefox_version = max( version_int(target_apps.get('firefox', {}).get('max', '')), version_int(target_apps.get('android', {}).get('max', '')) ) is_extension_or_complete_theme = ( # Note: annoyingly, `detected_type` is at the root level, not under # `metadata`. results.get('detected_type') in ('theme', 'extension')) is_targeting_firefoxes_only = target_apps and ( set(target_apps.keys()).intersection(('firefox', 'android')) == set(target_apps.keys()) ) is_targeting_thunderbird_or_seamonkey_only = target_apps and ( set(target_apps.keys()).intersection(('thunderbird', 'seamonkey')) == set(target_apps.keys()) ) is_targeting_firefox_lower_than_53_only = ( metadata.get('strict_compatibility') is True and # version_int('') is actually 200100. If strict compatibility is true, # the validator should have complained about the non-existant max # version, but it doesn't hurt to check that the value is sane anyway. max_target_firefox_version > 200100 and max_target_firefox_version < 53000000000000 ) is_targeting_firefox_higher_or_equal_than_57 = ( max_target_firefox_version >= 57000000000000 and max_target_firefox_version < 99000000000000) # Thunderbird/Seamonkey only add-ons are moving to addons.thunderbird.net. if (is_targeting_thunderbird_or_seamonkey_only): msg = ugettext( u'Add-ons for Thunderbird and SeaMonkey are now listed and ' u'maintained on addons.thunderbird.net. You can use the same ' u'account to update your add-ons on the new site.') insert_validation_message( results, message=msg, msg_id='thunderbird_and_seamonkey_migration') # Legacy add-ons are no longer supported on AMO (if waffle is enabled). elif (is_extension_or_complete_theme and waffle.switch_is_active('disallow-legacy-submissions')): msg = ugettext( u'Legacy extensions are no longer supported in Firefox.') insert_validation_message( results, message=msg, msg_id='legacy_addons_unsupported') # New legacy add-ons targeting Firefox only must target Firefox 53 or # lower, strictly. Extensions targeting multiple other apps are exempt from # this. elif (is_new_upload and is_extension_or_complete_theme and is_targeting_firefoxes_only and not is_targeting_firefox_lower_than_53_only): msg = ugettext( u'Starting with Firefox 53, new add-ons on this site can ' u'only be WebExtensions.') insert_validation_message( results, message=msg, msg_id='legacy_addons_restricted') # All legacy add-ons (new or upgrades) targeting Firefox must target # Firefox 56.* or lower, even if they target multiple apps. elif (is_extension_or_complete_theme and is_targeting_firefox_higher_or_equal_than_57): # Note: legacy add-ons targeting '*' (which is the default for sdk # add-ons) are excluded from this error, and instead are silently # rewritten as supporting '56.*' in the manifest parsing code. msg = ugettext( u'Legacy add-ons are not compatible with Firefox 57 or higher. ' u'Use a maxVersion of 56.* or lower.') insert_validation_message( results, message=msg, msg_id='legacy_addons_max_version') return results def annotate_legacy_langpack_restriction(results): """ Annotate validation results to restrict uploads of legacy langpacks. See https://github.com/mozilla/addons-linter/issues/1985 for more details. """ if not waffle.switch_is_active('disallow-legacy-langpacks'): return metadata = results.get('metadata', {}) is_webextension = metadata.get('is_webextension') is True target_apps = metadata.get('applications', {}) is_langpack = results.get('detected_type') == 'langpack' is_targeting_firefoxes_only = ( set(target_apps.keys()).intersection(('firefox', 'android')) == set(target_apps.keys()) ) if not is_webextension and is_langpack and is_targeting_firefoxes_only: link = ( 'https://developer.mozilla.org/Add-ons/WebExtensions/' 'manifest.json') msg = ugettext( u'Legacy language packs for Firefox are no longer supported. ' u'A WebExtensions install manifest is required. See {mdn_link} ' u'for more details.') insert_validation_message( results, message=msg.format(mdn_link=link), msg_id='legacy_langpacks_disallowed') return results def annotate_webext_incompatibilities(results, file_, addon, version_string, channel): """Check for WebExtension upgrades or downgrades. We avoid developers to downgrade their webextension to a XUL add-on at any cost and warn in case of an upgrade from XUL add-on to a WebExtension. Firefox doesn't support a downgrade. See https://github.com/mozilla/addons-server/issues/3061 and https://github.com/mozilla/addons-server/issues/3082 for more details. """ from .utils import find_previous_version previous_version = find_previous_version( addon, file_, version_string, channel) if not previous_version: return results is_webextension = results['metadata'].get('is_webextension', False) was_webextension = previous_version and previous_version.is_webextension if is_webextension and not was_webextension: results['is_upgrade_to_webextension'] = True msg = ugettext( 'We allow and encourage an upgrade but you cannot reverse ' 'this process. Once your users have the WebExtension ' 'installed, they will not be able to install a legacy add-on.') messages = results['messages'] messages.insert(0, { 'tier': 1, 'type': 'warning', 'id': ['validation', 'messages', 'webext_upgrade'], 'message': msg, 'description': [], 'compatibility_type': None}) results['warnings'] += 1 elif was_webextension and not is_webextension: msg = ugettext( 'You cannot update a WebExtensions add-on with a legacy ' 'add-on. Your users would not be able to use your new version ' 'because Firefox does not support this type of update.') messages = results['messages'] messages.insert(0, { 'tier': 1, 'type': ('error' if channel == amo.RELEASE_CHANNEL_LISTED else 'warning'), 'id': ['validation', 'messages', 'webext_downgrade'], 'message': msg, 'description': [], 'compatibility_type': None}) if channel == amo.RELEASE_CHANNEL_LISTED: results['errors'] += 1 else: results['warnings'] += 1 return results def annotate_akismet_spam_check(results, akismet_results): msg = ugettext('The text entered has been flagged as spam.') for report_result in akismet_results: if report_result in ( AkismetReport.MAYBE_SPAM, AkismetReport.DEFINITE_SPAM): insert_validation_message( results, message=msg, msg_id='akismet_is_spam') def check_for_api_keys_in_file(results, upload): if upload.addon: users = upload.addon.authors.all() else: users = [upload.user] if upload.user else [] keys = [] for user in users: try: key = APIKey.get_jwt_key(user_id=user.id) keys.append(key) except APIKey.DoesNotExist: pass if len(keys) > 0: zipfile = SafeZip(source=upload.path) for zipinfo in zipfile.info_list: if zipinfo.file_size >= 64: file_ = zipfile.read(zipinfo) for key in keys: if key.secret in file_.decode(encoding='unicode-escape', errors="ignore"): log.info('Developer API key for user %s found in ' 'submission.' % key.user) if key.user == upload.user: msg = ugettext('Your developer API key was found ' 'in the submitted file. To protect ' 'your account, the key will be ' 'revoked.') else: msg = ugettext('The developer API key of a ' 'coauthor was found in the ' 'submitted file. To protect your ' 'add-on, the key will be revoked.') insert_validation_message( results, type_='error', message=msg, msg_id='api_key_detected', compatibility_type=None) # Revoke after 2 minutes to allow the developer to # fetch the validation results revoke_api_key.apply_async( kwargs={'key_id': key.id}, countdown=120) zipfile.close() return results @task @use_primary_db def revoke_api_key(key_id): try: # Fetch the original key, do not use `get_jwt_key` # so we get access to a user object for logging later. original_key = APIKey.objects.get( type=SYMMETRIC_JWT_TYPE, id=key_id) # Fetch the current key to compare to the original, # throws if the key has been revoked, which also means # `original_key` is not active. current_key = APIKey.get_jwt_key(user_id=original_key.user.id) if current_key.key != original_key.key: log.info('User %s has already regenerated the key, nothing to be ' 'done.' % original_key.user) else: with transaction.atomic(): log.info('Revoking key for user %s.' % current_key.user) current_key.update(is_active=None) send_api_key_revocation_email(emails=[current_key.user.email]) except APIKey.DoesNotExist: log.info('User %s has already revoked the key, nothing to be done.' % original_key.user) pass def run_validator(path, listed=True): """A pre-configured wrapper around the addon validator. *path* Path to addon / extension file to validate. *listed=True* Validate the XPI as listed or unlisted. """ apps = dump_apps.Command.get_json_path() if not os.path.exists(apps): call_command('dump_apps') suffix = '_' + os.path.basename(path) with NamedTemporaryFile(suffix=suffix, dir=settings.TMP_PATH) as temp: if path and not os.path.exists(path) and storage.exists(path): # This file doesn't exist locally. Write it to our # currently-open temp file and switch to that path. shutil.copyfileobj(storage.open(path), temp.file) path = temp.name cmd = [ settings.ADDONS_VALIDATOR_BIN, '--boring', '--output=json', '--approved_applications=' + apps, '--timeout=' + str(settings.VALIDATOR_TIMEOUT), ] if not listed: cmd.append('--selfhosted') cmd.append(path) stdout, stderr = ( tempfile.TemporaryFile(), tempfile.TemporaryFile()) with statsd.timer('devhub.validator'): process = subprocess.Popen( # Have to use a string instead of a list because of how # `shell=True` resolves paths and working dirs ' '.join(cmd), stdout=stdout, stderr=stderr, # We're explicitly using a shell here because amo-validator # uses subprocess itself to shell out calls to spidermonkey # and it somehow needs to be called with shell=True to make # all that work properly. Not too much investigation went into # the "why" but since `shell=True` isn't much of a security # concern here given that all legacy add-ons we're validating # are uploaded / developed by Mozilla employees at this point # we're kinda safe-ish... shell=True ) process.wait() stdout.seek(0) stderr.seek(0) output, error = stdout.read(), stderr.read() # Make sure we close all descriptors, otherwise they'll hang around # and could cause a nasty exception. stdout.close() stderr.close() if error: raise ValueError(error) track_validation_stats(output) return output def run_addons_linter(path, listed=True): from .utils import fix_addons_linter_output args = [ settings.ADDONS_LINTER_BIN, path, '--boring', '--output=json' ] if not listed: args.append('--self-hosted') if not os.path.exists(path): raise ValueError( 'Path "{}" is not a file or directory or does not exist.' .format(path)) stdout, stderr = ( tempfile.TemporaryFile(), tempfile.TemporaryFile()) with statsd.timer('devhub.linter'): process = subprocess.Popen( args, stdout=stdout, stderr=stderr, # default but explicitly set to make sure we don't open a shell. shell=False ) process.wait() stdout.seek(0) stderr.seek(0) output, error = stdout.read(), stderr.read() # Make sure we close all descriptors, otherwise they'll hang around # and could cause a nasty exception. stdout.close() stderr.close() if error: raise ValueError(error) parsed_data = json.loads(output) result = json.dumps(fix_addons_linter_output(parsed_data, listed)) track_validation_stats(result, addons_linter=True) return result def track_validation_stats(json_result, addons_linter=False): """ Given a raw JSON string of validator results, log some stats. """ result = json.loads(json_result) result_kind = 'success' if result['errors'] == 0 else 'failure' runner = 'linter' if addons_linter else 'validator' statsd.incr('devhub.{}.results.all.{}'.format(runner, result_kind)) listed_tag = 'listed' if result['metadata']['listed'] else 'unlisted' # Track listed/unlisted success/fail. statsd.incr('devhub.{}.results.{}.{}' .format(runner, listed_tag, result_kind)) @task @use_primary_db @set_modified_on def pngcrush_existing_icons(addon_id): """ Call pngcrush_image() on the icons of a given add-on. """ log.info('Crushing icons for add-on %s', addon_id) addon = Addon.objects.get(pk=addon_id) if addon.icon_type != 'image/png': log.info('Aborting icon crush for add-on %s, icon type is not a PNG.', addon_id) return icon_dir = addon.get_icon_dir() pngcrush_image(os.path.join(icon_dir, '%s-64.png' % addon_id)) pngcrush_image(os.path.join(icon_dir, '%s-32.png' % addon_id)) # Return an icon hash that set_modified_on decorator will set on the add-on # after a small delay. This is normally done with the true md5 hash of the # original icon, but we don't necessarily have it here. We could read one # of the icons we modified but it does not matter just fake a hash to # indicate it was "manually" crushed. return { 'icon_hash': 'mcrushed' } @task @use_primary_db @set_modified_on def pngcrush_existing_preview(preview_id): """ Call pngcrush_image() on the images of a given add-on Preview object. """ log.info('Crushing images for Preview %s', preview_id) preview = Preview.objects.get(pk=preview_id) pngcrush_image(preview.thumbnail_path) pngcrush_image(preview.image_path) # We don't need a hash, previews are cachebusted with their modified date, # which does not change often. @set_modified_on will do that for us # automatically if the task was called with set_modified_on_obj=[preview]. @task @use_primary_db @set_modified_on def pngcrush_existing_theme(persona_id): """ Call pngcrush_image() on the images of a given Persona object. """ log.info('Crushing images for Persona %s', persona_id) persona = Persona.objects.get(pk=persona_id) # Only do this on "new" Personas with persona_id = 0, the older ones (with # a persona_id) have jpeg and not pngs. if not persona.is_new(): log.info('Aborting images crush for Persona %s (too old).', persona_id) return pngcrush_image(persona.preview_path) # No need to crush thumb_path, it's the same as preview_path for "new" # Personas. pngcrush_image(persona.icon_path) if persona.header: pngcrush_image(persona.header_path) if persona.footer: pngcrush_image(persona.footer_path) @task @set_modified_on def resize_icon(source, dest_folder, target_sizes, **kw): """Resizes addon icons.""" log.info('[1@None] Resizing icon: %s' % dest_folder) try: # Resize in every size we want. dest_file = None for size in target_sizes: dest_file = '%s-%s.png' % (dest_folder, size) resize_image(source, dest_file, (size, size)) # Store the original hash, we'll return it to update the corresponding # add-on. We only care about the first 8 chars of the md5, it's # unlikely a new icon on the same add-on would get the same first 8 # chars, especially with icon changes being so rare in the first place. with open(source) as fd: icon_hash = hashlib.md5(fd.read()).hexdigest()[:8] # Keep a copy of the original image. dest_file = '%s-original.png' % dest_folder os.rename(source, dest_file) return { 'icon_hash': icon_hash } except Exception as e: log.error("Error saving addon icon (%s): %s" % (dest_file, e)) @task @set_modified_on def resize_preview(src, preview_pk, **kw): """Resizes preview images and stores the sizes on the preview.""" preview = Preview.objects.get(pk=preview_pk) thumb_dst, full_dst, orig_dst = ( preview.thumbnail_path, preview.image_path, preview.original_path) sizes = {} log.info('[1@None] Resizing preview and storing size: %s' % thumb_dst) try: (sizes['thumbnail'], sizes['original']) = resize_image( src, thumb_dst, amo.ADDON_PREVIEW_SIZES['thumb']) (sizes['image'], _) = resize_image( src, full_dst, amo.ADDON_PREVIEW_SIZES['full']) if not os.path.exists(os.path.dirname(orig_dst)): os.makedirs(os.path.dirname(orig_dst)) os.rename(src, orig_dst) preview.sizes = sizes preview.save() return True except Exception as e: log.error("Error saving preview: %s" % e) def _recreate_images_for_preview(preview): log.info('Resizing preview: %s' % preview.id) try: preview.sizes = {} if storage.exists(preview.original_path): # We have an original size image, so we can resize that. src = preview.original_path preview.sizes['image'], preview.sizes['original'] = resize_image( src, preview.image_path, amo.ADDON_PREVIEW_SIZES['full']) preview.sizes['thumbnail'], _ = resize_image( src, preview.thumbnail_path, amo.ADDON_PREVIEW_SIZES['thumb']) else: # Otherwise we can't create a new sized full image, but can # use it for a new thumbnail src = preview.image_path preview.sizes['thumbnail'], preview.sizes['image'] = resize_image( src, preview.thumbnail_path, amo.ADDON_PREVIEW_SIZES['thumb']) preview.save() return True except Exception as e: log.exception("Error saving preview: %s" % e) @task @use_primary_db def recreate_previews(addon_ids, **kw): log.info('[%s@%s] Getting preview sizes for addons starting at id: %s...' % (len(addon_ids), recreate_previews.rate_limit, addon_ids[0])) addons = Addon.objects.filter(pk__in=addon_ids).no_transforms() for addon in addons: log.info('Recreating previews for addon: %s' % addon.id) previews = addon.previews.all() for preview in previews: _recreate_images_for_preview(preview) @task @use_primary_db def get_preview_sizes(ids, **kw): log.info('[%s@%s] Getting preview sizes for addons starting at id: %s...' % (len(ids), get_preview_sizes.rate_limit, ids[0])) addons = Addon.objects.filter(pk__in=ids).no_transforms() for addon in addons: previews = addon.previews.all() log.info('Found %s previews for: %s' % (previews.count(), addon.pk)) for preview in previews: try: log.info('Getting size for preview: %s' % preview.pk) sizes = { 'thumbnail': image_size(preview.thumbnail_path), 'image': image_size(preview.image_path), } preview.update(sizes=sizes) except Exception as err: log.error('Failed to find size of preview: %s, error: %s' % (addon.pk, err)) def failed_validation(*messages): """Return a validation object that looks like the add-on validator.""" m = [] for msg in messages: m.append({'type': 'error', 'message': msg, 'tier': 1}) return json.dumps({'errors': 1, 'success': False, 'messages': m}) def _fetch_content(url): try: return urllib2.urlopen(url, timeout=15) except urllib2.HTTPError as e: raise Exception( ugettext('%s responded with %s (%s).') % (url, e.code, e.msg)) except urllib2.URLError as e: # Unpack the URLError to try and find a useful message. if isinstance(e.reason, socket.timeout): raise Exception(ugettext('Connection to "%s" timed out.') % url) elif isinstance(e.reason, socket.gaierror): raise Exception(ugettext('Could not contact host at "%s".') % url) else: raise Exception(str(e.reason)) def check_content_type(response, content_type, no_ct_message, wrong_ct_message): if not response.headers.get('Content-Type', '').startswith(content_type): if 'Content-Type' in response.headers: raise Exception(wrong_ct_message % (content_type, response.headers['Content-Type'])) else: raise Exception(no_ct_message % content_type) def get_content_and_check_size(response, max_size, error_message): # Read one extra byte. Reject if it's too big so we don't have issues # downloading huge files. content = response.read(max_size + 1) if len(content) > max_size: raise Exception(error_message % max_size) return content @task def send_welcome_email(addon_pk, emails, context, **kw): log.info(u'[1@None] Sending welcome email for %s to %s.' % (addon_pk, emails)) subject = ( u'Mozilla Add-ons: %s has been submitted to addons.mozilla.org!' % context.get('addon_name', 'Your add-on')) html_template = 'devhub/email/submission.html' text_template = 'devhub/email/submission.txt' return send_html_mail_jinja(subject, html_template, text_template, context, recipient_list=emails, from_email=settings.ADDONS_EMAIL, use_deny_list=False, perm_setting='individual_contact') def send_api_key_revocation_email(emails): log.info(u'[1@None] Sending API key revocation email to %s.' % emails) subject = ugettext( u'Mozilla Security Notice: Your AMO API credentials have been revoked') template = loader.get_template( 'devhub/email/submission_api_key_revocation.txt') context = { 'api_keys_url': reverse('devhub.api_key') } send_mail(subject, template.render(context), from_email=settings.ADDONS_EMAIL, recipient_list=emails, use_deny_list=False, perm_setting='individual_contact')
[ "olympia.amo.utils.image_size", "django.core.files.storage.default_storage.exists", "olympia.addons.models.Addon.objects.filter", "olympia.amo.celery.task", "olympia.addons.models.Addon.objects.get", "copy.deepcopy", "olympia.versions.models.Version.from_upload", "django.core.files.storage.default_sto...
[((11863, 11888), 'olympia.amo.celery.task', 'task', ([], {'ignore_result': '(False)'}), '(ignore_result=False)\n', (11867, 11888), False, 'from olympia.amo.celery import task\n'), ((2123, 2153), 'django.core.cache.cache.get', 'cache.get', (['validator.cache_key'], {}), '(validator.cache_key)\n', (2132, 2153), False, 'from django.core.cache import cache\n'), ((3832, 3865), 'olympia.addons.models.Addon.unfiltered.get', 'Addon.unfiltered.get', ([], {'pk': 'addon_pk'}), '(pk=addon_pk)\n', (3852, 3865), False, 'from olympia.addons.models import Addon, Persona, Preview\n'), ((3879, 3915), 'olympia.files.models.FileUpload.objects.get', 'FileUpload.objects.get', ([], {'pk': 'upload_pk'}), '(pk=upload_pk)\n', (3901, 3915), False, 'from olympia.files.models import File, FileUpload, FileValidation\n'), ((6072, 6157), 'olympia.amo.celery.task', 'task', ([], {'bind': '(True)', 'ignore_result': '(False)', 'soft_time_limit': 'settings.VALIDATOR_TIMEOUT'}), '(bind=True, ignore_result=False, soft_time_limit=settings.VALIDATOR_TIMEOUT\n )\n', (6076, 6157), False, 'from olympia.amo.celery import task\n'), ((6199, 6208), 'functools.wraps', 'wraps', (['fn'], {}), '(fn)\n', (6204, 6208), False, 'from functools import wraps\n'), ((7845, 7873), 'olympia.files.models.File.objects.get', 'File.objects.get', ([], {'pk': 'file_id'}), '(pk=file_id)\n', (7861, 7873), False, 'from olympia.files.models import File, FileUpload, FileValidation\n'), ((8486, 8522), 'olympia.files.models.FileUpload.objects.get', 'FileUpload.objects.get', ([], {'pk': 'upload_pk'}), '(pk=upload_pk)\n', (8508, 8522), False, 'from olympia.files.models import File, FileUpload, FileValidation\n'), ((9665, 9684), 'json.dumps', 'json.dumps', (['results'], {}), '(results)\n', (9675, 9684), False, 'import json\n'), ((9876, 9916), 'olympia.amo.utils.utc_millesecs_from_epoch', 'utc_millesecs_from_epoch', (['upload.created'], {}), '(upload.created)\n', (9900, 9916), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((9927, 9950), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (9948, 9950), False, 'import datetime\n'), ((9964, 9993), 'olympia.amo.utils.utc_millesecs_from_epoch', 'utc_millesecs_from_epoch', (['now'], {}), '(now)\n', (9988, 9993), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((10032, 10091), 'django_statsd.clients.statsd.timing', 'statsd.timing', (['"""devhub.validation_results_processed"""', 'delta'], {}), "('devhub.validation_results_processed', delta)\n", (10045, 10091), False, 'from django_statsd.clients import statsd\n'), ((10472, 10492), 'decimal.Decimal', 'Decimal', (['(1024 * 1024)'], {}), '(1024 * 1024)\n', (10479, 10492), False, 'from decimal import Decimal\n'), ((12071, 12099), 'olympia.files.models.File.objects.get', 'File.objects.get', ([], {'pk': 'file_id'}), '(pk=file_id)\n', (12087, 12099), False, 'from olympia.files.models import File, FileUpload, FileValidation\n'), ((20636, 20690), 'django.utils.translation.ugettext', 'ugettext', (['"""The text entered has been flagged as spam."""'], {}), "('The text entered has been flagged as spam.')\n", (20644, 20690), False, 'from django.utils.translation import ugettext\n'), ((24357, 24390), 'olympia.applications.management.commands.dump_apps.Command.get_json_path', 'dump_apps.Command.get_json_path', ([], {}), '()\n', (24388, 24390), False, 'from olympia.applications.management.commands import dump_apps\n'), ((27786, 27804), 'json.loads', 'json.loads', (['output'], {}), '(output)\n', (27796, 27804), False, 'import json\n'), ((28110, 28133), 'json.loads', 'json.loads', (['json_result'], {}), '(json_result)\n', (28120, 28133), False, 'import json\n'), ((28769, 28799), 'olympia.addons.models.Addon.objects.get', 'Addon.objects.get', ([], {'pk': 'addon_id'}), '(pk=addon_id)\n', (28786, 28799), False, 'from olympia.addons.models import Addon, Persona, Preview\n'), ((29781, 29815), 'olympia.addons.models.Preview.objects.get', 'Preview.objects.get', ([], {'pk': 'preview_id'}), '(pk=preview_id)\n', (29800, 29815), False, 'from olympia.addons.models import Addon, Persona, Preview\n'), ((29820, 29858), 'olympia.amo.utils.pngcrush_image', 'pngcrush_image', (['preview.thumbnail_path'], {}), '(preview.thumbnail_path)\n', (29834, 29858), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((29863, 29897), 'olympia.amo.utils.pngcrush_image', 'pngcrush_image', (['preview.image_path'], {}), '(preview.image_path)\n', (29877, 29897), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((30366, 30400), 'olympia.addons.models.Persona.objects.get', 'Persona.objects.get', ([], {'pk': 'persona_id'}), '(pk=persona_id)\n', (30385, 30400), False, 'from olympia.addons.models import Addon, Persona, Preview\n'), ((30652, 30688), 'olympia.amo.utils.pngcrush_image', 'pngcrush_image', (['persona.preview_path'], {}), '(persona.preview_path)\n', (30666, 30688), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((30784, 30817), 'olympia.amo.utils.pngcrush_image', 'pngcrush_image', (['persona.icon_path'], {}), '(persona.icon_path)\n', (30798, 30817), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((32199, 32233), 'olympia.addons.models.Preview.objects.get', 'Preview.objects.get', ([], {'pk': 'preview_pk'}), '(pk=preview_pk)\n', (32218, 32233), False, 'from olympia.addons.models import Addon, Persona, Preview\n'), ((35616, 35674), 'json.dumps', 'json.dumps', (["{'errors': 1, 'success': False, 'messages': m}"], {}), "({'errors': 1, 'success': False, 'messages': m})\n", (35626, 35674), False, 'import json\n'), ((37464, 37654), 'olympia.amo.utils.send_html_mail_jinja', 'send_html_mail_jinja', (['subject', 'html_template', 'text_template', 'context'], {'recipient_list': 'emails', 'from_email': 'settings.ADDONS_EMAIL', 'use_deny_list': '(False)', 'perm_setting': '"""individual_contact"""'}), "(subject, html_template, text_template, context,\n recipient_list=emails, from_email=settings.ADDONS_EMAIL, use_deny_list=\n False, perm_setting='individual_contact')\n", (37484, 37654), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((37908, 37993), 'django.utils.translation.ugettext', 'ugettext', (['u"""Mozilla Security Notice: Your AMO API credentials have been revoked"""'], {}), "(u'Mozilla Security Notice: Your AMO API credentials have been revoked'\n )\n", (37916, 37993), False, 'from django.utils.translation import ugettext\n'), ((38013, 38082), 'django.template.loader.get_template', 'loader.get_template', (['"""devhub/email/submission_api_key_revocation.txt"""'], {}), "('devhub/email/submission_api_key_revocation.txt')\n", (38032, 38082), False, 'from django.template import loader\n'), ((2205, 2225), 'celery.result.AsyncResult', 'AsyncResult', (['task_id'], {}), '(task_id)\n', (2216, 2225), False, 'from celery.result import AsyncResult\n'), ((5191, 5235), 'olympia.files.utils.parse_addon', 'parse_addon', (['upload', 'addon'], {'user': 'upload.user'}), '(upload, addon, user=upload.user)\n', (5202, 5235), False, 'from olympia.files.utils import parse_addon, SafeZip\n'), ((5254, 5360), 'olympia.versions.models.Version.from_upload', 'Version.from_upload', (['upload', 'addon', '[x[0] for x in amo.APPS_CHOICES]', 'channel'], {'parsed_data': 'parsed_data'}), '(upload, addon, [x[0] for x in amo.APPS_CHOICES],\n channel, parsed_data=parsed_data)\n', (5273, 5360), False, 'from olympia.versions.models import Version\n'), ((5784, 5810), 'olympia.devhub.views.auto_sign_version', 'auto_sign_version', (['version'], {}), '(version)\n', (5801, 5810), False, 'from olympia.devhub.views import auto_sign_version\n'), ((5819, 5849), 'olympia.devhub.utils.add_dynamic_theme_tag', 'add_dynamic_theme_tag', (['version'], {}), '(version)\n', (5840, 5849), False, 'from olympia.devhub.utils import add_dynamic_theme_tag\n'), ((10104, 10131), 'django.core.files.storage.default_storage.exists', 'storage.exists', (['upload.path'], {}), '(upload.path)\n', (10118, 10131), True, 'from django.core.files.storage import default_storage as storage\n'), ((10430, 10455), 'django.core.files.storage.default_storage.size', 'storage.size', (['upload.path'], {}), '(upload.path)\n', (10442, 10455), True, 'from django.core.files.storage import default_storage as storage\n'), ((11158, 11231), 'django_statsd.clients.statsd.timing', 'statsd.timing', (['"""devhub.validation_results_processed_per_mb"""', 'scaled_delta'], {}), "('devhub.validation_results_processed_per_mb', scaled_delta)\n", (11171, 11231), False, 'from django_statsd.clients import statsd\n'), ((12294, 12334), 'olympia.files.models.FileValidation.from_json', 'FileValidation.from_json', (['file_', 'results'], {}), '(file_, results)\n', (12318, 12334), False, 'from olympia.files.models import File, FileUpload, FileValidation\n'), ((14935, 15121), 'django.utils.translation.ugettext', 'ugettext', (['u"""Add-ons for Thunderbird and SeaMonkey are now listed and maintained on addons.thunderbird.net. You can use the same account to update your add-ons on the new site."""'], {}), "(\n u'Add-ons for Thunderbird and SeaMonkey are now listed and maintained on addons.thunderbird.net. You can use the same account to update your add-ons on the new site.'\n )\n", (14943, 15121), False, 'from django.utils.translation import ugettext\n'), ((17220, 17272), 'waffle.switch_is_active', 'waffle.switch_is_active', (['"""disallow-legacy-langpacks"""'], {}), "('disallow-legacy-langpacks')\n", (17243, 17272), False, 'import waffle\n'), ((17859, 18019), 'django.utils.translation.ugettext', 'ugettext', (['u"""Legacy language packs for Firefox are no longer supported. A WebExtensions install manifest is required. See {mdn_link} for more details."""'], {}), "(\n u'Legacy language packs for Firefox are no longer supported. A WebExtensions install manifest is required. See {mdn_link} for more details.'\n )\n", (17867, 18019), False, 'from django.utils.translation import ugettext\n'), ((19208, 19399), 'django.utils.translation.ugettext', 'ugettext', (['"""We allow and encourage an upgrade but you cannot reverse this process. Once your users have the WebExtension installed, they will not be able to install a legacy add-on."""'], {}), "(\n 'We allow and encourage an upgrade but you cannot reverse this process. Once your users have the WebExtension installed, they will not be able to install a legacy add-on.'\n )\n", (19216, 19399), False, 'from django.utils.translation import ugettext\n'), ((21344, 21371), 'olympia.files.utils.SafeZip', 'SafeZip', ([], {'source': 'upload.path'}), '(source=upload.path)\n', (21351, 21371), False, 'from olympia.files.utils import parse_addon, SafeZip\n'), ((23213, 23267), 'olympia.api.models.APIKey.objects.get', 'APIKey.objects.get', ([], {'type': 'SYMMETRIC_JWT_TYPE', 'id': 'key_id'}), '(type=SYMMETRIC_JWT_TYPE, id=key_id)\n', (23231, 23267), False, 'from olympia.api.models import SYMMETRIC_JWT_TYPE, APIKey\n'), ((23466, 23514), 'olympia.api.models.APIKey.get_jwt_key', 'APIKey.get_jwt_key', ([], {'user_id': 'original_key.user.id'}), '(user_id=original_key.user.id)\n', (23484, 23514), False, 'from olympia.api.models import SYMMETRIC_JWT_TYPE, APIKey\n'), ((24403, 24423), 'os.path.exists', 'os.path.exists', (['apps'], {}), '(apps)\n', (24417, 24423), False, 'import os\n'), ((24433, 24458), 'django.core.management.call_command', 'call_command', (['"""dump_apps"""'], {}), "('dump_apps')\n", (24445, 24458), False, 'from django.core.management import call_command\n'), ((24479, 24501), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (24495, 24501), False, 'import os\n'), ((24512, 24568), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'suffix': 'suffix', 'dir': 'settings.TMP_PATH'}), '(suffix=suffix, dir=settings.TMP_PATH)\n', (24530, 24568), False, 'from tempfile import NamedTemporaryFile\n'), ((26930, 26950), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (26944, 26950), False, 'import os\n'), ((27107, 27131), 'tempfile.TemporaryFile', 'tempfile.TemporaryFile', ([], {}), '()\n', (27129, 27131), False, 'import tempfile\n'), ((27141, 27165), 'tempfile.TemporaryFile', 'tempfile.TemporaryFile', ([], {}), '()\n', (27163, 27165), False, 'import tempfile\n'), ((27177, 27206), 'django_statsd.clients.statsd.timer', 'statsd.timer', (['"""devhub.linter"""'], {}), "('devhub.linter')\n", (27189, 27206), False, 'from django_statsd.clients import statsd\n'), ((27226, 27291), 'subprocess.Popen', 'subprocess.Popen', (['args'], {'stdout': 'stdout', 'stderr': 'stderr', 'shell': '(False)'}), '(args, stdout=stdout, stderr=stderr, shell=False)\n', (27242, 27291), False, 'import subprocess\n'), ((29015, 29061), 'os.path.join', 'os.path.join', (['icon_dir', "('%s-64.png' % addon_id)"], {}), "(icon_dir, '%s-64.png' % addon_id)\n", (29027, 29061), False, 'import os\n'), ((29082, 29128), 'os.path.join', 'os.path.join', (['icon_dir', "('%s-32.png' % addon_id)"], {}), "(icon_dir, '%s-32.png' % addon_id)\n", (29094, 29128), False, 'import os\n'), ((30849, 30884), 'olympia.amo.utils.pngcrush_image', 'pngcrush_image', (['persona.header_path'], {}), '(persona.header_path)\n', (30863, 30884), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((30916, 30951), 'olympia.amo.utils.pngcrush_image', 'pngcrush_image', (['persona.footer_path'], {}), '(persona.footer_path)\n', (30930, 30951), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((31857, 31885), 'os.rename', 'os.rename', (['source', 'dest_file'], {}), '(source, dest_file)\n', (31866, 31885), False, 'import os\n'), ((32496, 32558), 'olympia.amo.utils.resize_image', 'resize_image', (['src', 'thumb_dst', "amo.ADDON_PREVIEW_SIZES['thumb']"], {}), "(src, thumb_dst, amo.ADDON_PREVIEW_SIZES['thumb'])\n", (32508, 32558), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((32602, 32662), 'olympia.amo.utils.resize_image', 'resize_image', (['src', 'full_dst', "amo.ADDON_PREVIEW_SIZES['full']"], {}), "(src, full_dst, amo.ADDON_PREVIEW_SIZES['full'])\n", (32614, 32662), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((32793, 32817), 'os.rename', 'os.rename', (['src', 'orig_dst'], {}), '(src, orig_dst)\n', (32802, 32817), False, 'import os\n'), ((33110, 33147), 'django.core.files.storage.default_storage.exists', 'storage.exists', (['preview.original_path'], {}), '(preview.original_path)\n', (33124, 33147), True, 'from django.core.files.storage import default_storage as storage\n'), ((35726, 35758), 'urllib2.urlopen', 'urllib2.urlopen', (['url'], {'timeout': '(15)'}), '(url, timeout=15)\n', (35741, 35758), False, 'import urllib2\n'), ((38132, 38157), 'olympia.amo.urlresolvers.reverse', 'reverse', (['"""devhub.api_key"""'], {}), "('devhub.api_key')\n", (38139, 38157), False, 'from olympia.amo.urlresolvers import reverse\n'), ((3184, 3198), 'celery.group', 'celery.group', ([], {}), '()\n', (3196, 3198), False, 'import celery\n'), ((3445, 3499), 'django.core.cache.cache.set', 'cache.set', (['validator.cache_key', 'result.task_id', '(5 * 60)'], {}), '(validator.cache_key, result.task_id, 5 * 60)\n', (3454, 3499), False, 'from django.core.cache import cache\n'), ((4428, 4490), 'olympia.versions.models.Version.unfiltered.filter', 'Version.unfiltered.filter', ([], {'addon': 'addon', 'version': 'upload.version'}), '(addon=addon, version=upload.version)\n', (4453, 4490), False, 'from olympia.versions.models import Version\n'), ((6565, 6581), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (6575, 6581), False, 'import json\n'), ((11094, 11104), 'decimal.Decimal', 'Decimal', (['(1)'], {}), '(1)\n', (11101, 11104), False, 'from decimal import Decimal\n'), ((11128, 11142), 'decimal.Decimal', 'Decimal', (['delta'], {}), '(delta)\n', (11135, 11142), False, 'from decimal import Decimal\n'), ((15407, 15461), 'waffle.switch_is_active', 'waffle.switch_is_active', (['"""disallow-legacy-submissions"""'], {}), "('disallow-legacy-submissions')\n", (15430, 15461), False, 'import waffle\n'), ((15478, 15544), 'django.utils.translation.ugettext', 'ugettext', (['u"""Legacy extensions are no longer supported in Firefox."""'], {}), "(u'Legacy extensions are no longer supported in Firefox.')\n", (15486, 15544), False, 'from django.utils.translation import ugettext\n'), ((19818, 20009), 'django.utils.translation.ugettext', 'ugettext', (['"""You cannot update a WebExtensions add-on with a legacy add-on. Your users would not be able to use your new version because Firefox does not support this type of update."""'], {}), "(\n 'You cannot update a WebExtensions add-on with a legacy add-on. Your users would not be able to use your new version because Firefox does not support this type of update.'\n )\n", (19826, 20009), False, 'from django.utils.translation import ugettext\n'), ((21185, 21220), 'olympia.api.models.APIKey.get_jwt_key', 'APIKey.get_jwt_key', ([], {'user_id': 'user.id'}), '(user_id=user.id)\n', (21203, 21220), False, 'from olympia.api.models import SYMMETRIC_JWT_TYPE, APIKey\n'), ((24627, 24647), 'django.core.files.storage.default_storage.exists', 'storage.exists', (['path'], {}), '(path)\n', (24641, 24647), True, 'from django.core.files.storage import default_storage as storage\n'), ((25226, 25250), 'tempfile.TemporaryFile', 'tempfile.TemporaryFile', ([], {}), '()\n', (25248, 25250), False, 'import tempfile\n'), ((25264, 25288), 'tempfile.TemporaryFile', 'tempfile.TemporaryFile', ([], {}), '()\n', (25286, 25288), False, 'import tempfile\n'), ((25304, 25336), 'django_statsd.clients.statsd.timer', 'statsd.timer', (['"""devhub.validator"""'], {}), "('devhub.validator')\n", (25316, 25336), False, 'from django_statsd.clients import statsd\n'), ((31301, 31346), 'olympia.amo.utils.resize_image', 'resize_image', (['source', 'dest_file', '(size, size)'], {}), '(source, dest_file, (size, size))\n', (31313, 31346), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((33322, 33392), 'olympia.amo.utils.resize_image', 'resize_image', (['src', 'preview.image_path', "amo.ADDON_PREVIEW_SIZES['full']"], {}), "(src, preview.image_path, amo.ADDON_PREVIEW_SIZES['full'])\n", (33334, 33392), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((33454, 33529), 'olympia.amo.utils.resize_image', 'resize_image', (['src', 'preview.thumbnail_path', "amo.ADDON_PREVIEW_SIZES['thumb']"], {}), "(src, preview.thumbnail_path, amo.ADDON_PREVIEW_SIZES['thumb'])\n", (33466, 33529), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((33776, 33851), 'olympia.amo.utils.resize_image', 'resize_image', (['src', 'preview.thumbnail_path', "amo.ADDON_PREVIEW_SIZES['thumb']"], {}), "(src, preview.thumbnail_path, amo.ADDON_PREVIEW_SIZES['thumb'])\n", (33788, 33851), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((34225, 34263), 'olympia.addons.models.Addon.objects.filter', 'Addon.objects.filter', ([], {'pk__in': 'addon_ids'}), '(pk__in=addon_ids)\n', (34245, 34263), False, 'from olympia.addons.models import Addon, Persona, Preview\n'), ((34708, 34740), 'olympia.addons.models.Addon.objects.filter', 'Addon.objects.filter', ([], {'pk__in': 'ids'}), '(pk__in=ids)\n', (34728, 34740), False, 'from olympia.addons.models import Addon, Persona, Preview\n'), ((6999, 7041), 'copy.deepcopy', 'deepcopy', (['amo.VALIDATOR_SKELETON_EXCEPTION'], {}), '(amo.VALIDATOR_SKELETON_EXCEPTION)\n', (7007, 7041), False, 'from copy import deepcopy\n'), ((16023, 16123), 'django.utils.translation.ugettext', 'ugettext', (['u"""Starting with Firefox 53, new add-ons on this site can only be WebExtensions."""'], {}), "(\n u'Starting with Firefox 53, new add-ons on this site can only be WebExtensions.'\n )\n", (16031, 16123), False, 'from django.utils.translation import ugettext\n'), ((23723, 23743), 'django.db.transaction.atomic', 'transaction.atomic', ([], {}), '()\n', (23741, 23743), False, 'from django.db import transaction\n'), ((24602, 24622), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (24616, 24622), False, 'import os\n'), ((24807, 24825), 'django.core.files.storage.default_storage.open', 'storage.open', (['path'], {}), '(path)\n', (24819, 24825), True, 'from django.core.files.storage import default_storage as storage\n'), ((32706, 32731), 'os.path.dirname', 'os.path.dirname', (['orig_dst'], {}), '(orig_dst)\n', (32721, 32731), False, 'import os\n'), ((32758, 32783), 'os.path.dirname', 'os.path.dirname', (['orig_dst'], {}), '(orig_dst)\n', (32773, 32783), False, 'import os\n'), ((6930, 6979), 'copy.deepcopy', 'deepcopy', (['amo.VALIDATOR_SKELETON_EXCEPTION_WEBEXT'], {}), '(amo.VALIDATOR_SKELETON_EXCEPTION_WEBEXT)\n', (6938, 6979), False, 'from copy import deepcopy\n'), ((16724, 16842), 'django.utils.translation.ugettext', 'ugettext', (['u"""Legacy add-ons are not compatible with Firefox 57 or higher. Use a maxVersion of 56.* or lower."""'], {}), "(\n u'Legacy add-ons are not compatible with Firefox 57 or higher. Use a maxVersion of 56.* or lower.'\n )\n", (16732, 16842), False, 'from django.utils.translation import ugettext\n'), ((35079, 35113), 'olympia.amo.utils.image_size', 'image_size', (['preview.thumbnail_path'], {}), '(preview.thumbnail_path)\n', (35089, 35113), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((35144, 35174), 'olympia.amo.utils.image_size', 'image_size', (['preview.image_path'], {}), '(preview.image_path)\n', (35154, 35174), False, 'from olympia.amo.utils import image_size, pngcrush_image, resize_image, send_html_mail_jinja, send_mail, utc_millesecs_from_epoch\n'), ((35831, 35869), 'django.utils.translation.ugettext', 'ugettext', (['"""%s responded with %s (%s)."""'], {}), "('%s responded with %s (%s).')\n", (35839, 35869), False, 'from django.utils.translation import ugettext\n'), ((36069, 36110), 'django.utils.translation.ugettext', 'ugettext', (['"""Connection to "%s" timed out."""'], {}), '(\'Connection to "%s" timed out.\')\n', (36077, 36110), False, 'from django.utils.translation import ugettext\n'), ((21898, 22025), 'django.utils.translation.ugettext', 'ugettext', (['"""Your developer API key was found in the submitted file. To protect your account, the key will be revoked."""'], {}), "(\n 'Your developer API key was found in the submitted file. To protect your account, the key will be revoked.'\n )\n", (21906, 22025), False, 'from django.utils.translation import ugettext\n'), ((22218, 22357), 'django.utils.translation.ugettext', 'ugettext', (['"""The developer API key of a coauthor was found in the submitted file. To protect your add-on, the key will be revoked."""'], {}), "(\n 'The developer API key of a coauthor was found in the submitted file. To protect your add-on, the key will be revoked.'\n )\n", (22226, 22357), False, 'from django.utils.translation import ugettext\n'), ((36198, 36241), 'django.utils.translation.ugettext', 'ugettext', (['"""Could not contact host at "%s"."""'], {}), '(\'Could not contact host at "%s".\')\n', (36206, 36241), False, 'from django.utils.translation import ugettext\n')]
# pipeline.py # # An example of setting up a processing pipeline with generators access_log = "ausdhuash test auhsd aushdua ahduasd auhdu uhasd" def grep(pattern,lines): for line in lines: if pattern in line: yield line if __name__ == '__main__': from follow import follow # Set up a processing pipe : tail -f | grep python loglines = follow(access_log) pylines = grep("python",loglines) # Pull results out of the processing pipeline for line in pylines: print(line)
[ "follow.follow" ]
[((377, 395), 'follow.follow', 'follow', (['access_log'], {}), '(access_log)\n', (383, 395), False, 'from follow import follow\n')]
from app import app from flask import request @app.route("/output/endpoint1", methods=["POST"]) def output_endpoint1(): assert request.headers["Content-Type"] == "application/json" s = request.data.decode("utf-8") assert s == '{ "user": "bob" }' return app.response_class( headers={"date": "DATE1"}, response="Response endpoint1\n" ) @app.route("/output/endpoint2") def output_endpoint2(): return app.response_class( headers={"date": "DATE2"}, response="Response endpoint2\n" )
[ "app.app.response_class", "flask.request.data.decode", "app.app.route" ]
[((49, 97), 'app.app.route', 'app.route', (['"""/output/endpoint1"""'], {'methods': "['POST']"}), "('/output/endpoint1', methods=['POST'])\n", (58, 97), False, 'from app import app\n'), ((367, 397), 'app.app.route', 'app.route', (['"""/output/endpoint2"""'], {}), "('/output/endpoint2')\n", (376, 397), False, 'from app import app\n'), ((195, 223), 'flask.request.data.decode', 'request.data.decode', (['"""utf-8"""'], {}), "('utf-8')\n", (214, 223), False, 'from flask import request\n'), ((271, 349), 'app.app.response_class', 'app.response_class', ([], {'headers': "{'date': 'DATE1'}", 'response': '"""Response endpoint1\n"""'}), "(headers={'date': 'DATE1'}, response='Response endpoint1\\n')\n", (289, 349), False, 'from app import app\n'), ((433, 511), 'app.app.response_class', 'app.response_class', ([], {'headers': "{'date': 'DATE2'}", 'response': '"""Response endpoint2\n"""'}), "(headers={'date': 'DATE2'}, response='Response endpoint2\\n')\n", (451, 511), False, 'from app import app\n')]
""" Copyright 2016 <NAME> 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 unittest from xp.pipeline import get_pipeline, USE_FILE_PREFIX import xp.pipeline as pipeline import os, os.path BASE_PATH = os.path.dirname(__file__) def get_complete_filename(fname): return os.path.join(BASE_PATH,'pipelines',fname) class TaskPropertiesTestCase(unittest.TestCase): def test_one_property(self): p = get_pipeline(get_complete_filename('one_property'),default_prefix=USE_FILE_PREFIX) t1 = p.get_task('my_task') props = t1.properties() self.assertEqual(len(props),1) self.assertEqual(props['author'],'<NAME>')
[ "os.path.dirname", "os.path.join" ]
[((689, 714), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (704, 714), False, 'import os, os.path\n'), ((758, 801), 'os.path.join', 'os.path.join', (['BASE_PATH', '"""pipelines"""', 'fname'], {}), "(BASE_PATH, 'pipelines', fname)\n", (770, 801), False, 'import os, os.path\n')]
# Copyright (c) 2012 Midokura Japan K.K. # # 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 mock import six import webob from oslo_policy import policy as oslo_policy from nova.api.openstack.compute import extension_info from nova.api.openstack.compute import servers \ as server_v21 from nova.compute import api as compute_api from nova import db from nova import exception from nova import policy from nova import test from nova.tests.unit.api.openstack import fakes from nova.tests import uuidsentinel as uuids class ServerStartStopTestV21(test.TestCase): start_policy = "os_compute_api:servers:start" stop_policy = "os_compute_api:servers:stop" def setUp(self): super(ServerStartStopTestV21, self).setUp() self._setup_controller() self.req = fakes.HTTPRequest.blank('') self.stub_out('nova.db.instance_get_by_uuid', fakes.fake_instance_get()) def _setup_controller(self): ext_info = extension_info.LoadedExtensionInfo() self.controller = server_v21.ServersController( extension_info=ext_info) @mock.patch.object(compute_api.API, 'start') def test_start(self, start_mock): body = dict(start="") self.controller._start_server(self.req, uuids.instance, body) start_mock.assert_called_once_with(mock.ANY, mock.ANY) def test_start_policy_failed(self): rules = { self.start_policy: "project_id:non_fake" } policy.set_rules(oslo_policy.Rules.from_dict(rules)) body = dict(start="") exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller._start_server, self.req, uuids.instance, body) self.assertIn(self.start_policy, exc.format_message()) @mock.patch.object(compute_api.API, 'start', side_effect=exception.InstanceNotReady( instance_id=uuids.instance)) def test_start_not_ready(self, start_mock): body = dict(start="") self.assertRaises(webob.exc.HTTPConflict, self.controller._start_server, self.req, uuids.instance, body) @mock.patch.object(compute_api.API, 'start', side_effect=exception.InstanceIsLocked( instance_uuid=uuids.instance)) def test_start_locked_server(self, start_mock): body = dict(start="") self.assertRaises(webob.exc.HTTPConflict, self.controller._start_server, self.req, uuids.instance, body) @mock.patch.object(compute_api.API, 'start', side_effect=exception.InstanceIsLocked( instance_uuid=uuids.instance)) def test_start_invalid_state(self, start_mock): body = dict(start="") ex = self.assertRaises(webob.exc.HTTPConflict, self.controller._start_server, self.req, uuids.instance, body) self.assertIn('is locked', six.text_type(ex)) @mock.patch.object(compute_api.API, 'stop') def test_stop(self, stop_mock): body = dict(stop="") self.controller._stop_server(self.req, uuids.instance, body) stop_mock.assert_called_once_with(mock.ANY, mock.ANY) def test_stop_policy_failed(self): rules = { self.stop_policy: "project_id:non_fake" } policy.set_rules(oslo_policy.Rules.from_dict(rules)) body = dict(stop="") exc = self.assertRaises(exception.PolicyNotAuthorized, self.controller._stop_server, self.req, uuids.instance, body) self.assertIn(self.stop_policy, exc.format_message()) @mock.patch.object(compute_api.API, 'stop', side_effect=exception.InstanceNotReady( instance_id=uuids.instance)) def test_stop_not_ready(self, stop_mock): body = dict(stop="") self.assertRaises(webob.exc.HTTPConflict, self.controller._stop_server, self.req, uuids.instance, body) @mock.patch.object(compute_api.API, 'stop', side_effect=exception.InstanceIsLocked( instance_uuid=uuids.instance)) def test_stop_locked_server(self, stop_mock): body = dict(stop="") ex = self.assertRaises(webob.exc.HTTPConflict, self.controller._stop_server, self.req, uuids.instance, body) self.assertIn('is locked', six.text_type(ex)) @mock.patch.object(compute_api.API, 'stop', side_effect=exception.InstanceIsLocked( instance_uuid=uuids.instance)) def test_stop_invalid_state(self, stop_mock): body = dict(start="") self.assertRaises(webob.exc.HTTPConflict, self.controller._stop_server, self.req, uuids.instance, body) @mock.patch.object(db, 'instance_get_by_uuid', side_effect=exception.InstanceNotFound( instance_id=uuids.instance)) def test_start_with_bogus_id(self, get_mock): body = dict(start="") self.assertRaises(webob.exc.HTTPNotFound, self.controller._start_server, self.req, uuids.instance, body) @mock.patch.object(db, 'instance_get_by_uuid', side_effect=exception.InstanceNotFound( instance_id=uuids.instance)) def test_stop_with_bogus_id(self, get_mock): body = dict(stop="") self.assertRaises(webob.exc.HTTPNotFound, self.controller._stop_server, self.req, uuids.instance, body)
[ "nova.api.openstack.compute.servers.ServersController", "nova.tests.unit.api.openstack.fakes.HTTPRequest.blank", "nova.tests.unit.api.openstack.fakes.fake_instance_get", "six.text_type", "nova.exception.InstanceIsLocked", "nova.exception.InstanceNotFound", "mock.patch.object", "nova.api.openstack.comp...
[((1664, 1707), 'mock.patch.object', 'mock.patch.object', (['compute_api.API', '"""start"""'], {}), "(compute_api.API, 'start')\n", (1681, 1707), False, 'import mock\n'), ((3568, 3610), 'mock.patch.object', 'mock.patch.object', (['compute_api.API', '"""stop"""'], {}), "(compute_api.API, 'stop')\n", (3585, 3610), False, 'import mock\n'), ((1326, 1353), 'nova.tests.unit.api.openstack.fakes.HTTPRequest.blank', 'fakes.HTTPRequest.blank', (['""""""'], {}), "('')\n", (1349, 1353), False, 'from nova.tests.unit.api.openstack import fakes\n'), ((1510, 1546), 'nova.api.openstack.compute.extension_info.LoadedExtensionInfo', 'extension_info.LoadedExtensionInfo', ([], {}), '()\n', (1544, 1546), False, 'from nova.api.openstack.compute import extension_info\n'), ((1573, 1626), 'nova.api.openstack.compute.servers.ServersController', 'server_v21.ServersController', ([], {'extension_info': 'ext_info'}), '(extension_info=ext_info)\n', (1601, 1626), True, 'from nova.api.openstack.compute import servers as server_v21\n'), ((1430, 1455), 'nova.tests.unit.api.openstack.fakes.fake_instance_get', 'fakes.fake_instance_get', ([], {}), '()\n', (1453, 1455), False, 'from nova.tests.unit.api.openstack import fakes\n'), ((2056, 2090), 'oslo_policy.policy.Rules.from_dict', 'oslo_policy.Rules.from_dict', (['rules'], {}), '(rules)\n', (2083, 2090), True, 'from oslo_policy import policy as oslo_policy\n'), ((2460, 2514), 'nova.exception.InstanceNotReady', 'exception.InstanceNotReady', ([], {'instance_id': 'uuids.instance'}), '(instance_id=uuids.instance)\n', (2486, 2514), False, 'from nova import exception\n'), ((2832, 2888), 'nova.exception.InstanceIsLocked', 'exception.InstanceIsLocked', ([], {'instance_uuid': 'uuids.instance'}), '(instance_uuid=uuids.instance)\n', (2858, 2888), False, 'from nova import exception\n'), ((3543, 3560), 'six.text_type', 'six.text_type', (['ex'], {}), '(ex)\n', (3556, 3560), False, 'import six\n'), ((3210, 3266), 'nova.exception.InstanceIsLocked', 'exception.InstanceIsLocked', ([], {'instance_uuid': 'uuids.instance'}), '(instance_uuid=uuids.instance)\n', (3236, 3266), False, 'from nova import exception\n'), ((3952, 3986), 'oslo_policy.policy.Rules.from_dict', 'oslo_policy.Rules.from_dict', (['rules'], {}), '(rules)\n', (3979, 3986), True, 'from oslo_policy import policy as oslo_policy\n'), ((4352, 4406), 'nova.exception.InstanceNotReady', 'exception.InstanceNotReady', ([], {'instance_id': 'uuids.instance'}), '(instance_id=uuids.instance)\n', (4378, 4406), False, 'from nova import exception\n'), ((5048, 5065), 'six.text_type', 'six.text_type', (['ex'], {}), '(ex)\n', (5061, 5065), False, 'import six\n'), ((4719, 4775), 'nova.exception.InstanceIsLocked', 'exception.InstanceIsLocked', ([], {'instance_uuid': 'uuids.instance'}), '(instance_uuid=uuids.instance)\n', (4745, 4775), False, 'from nova import exception\n'), ((5151, 5207), 'nova.exception.InstanceIsLocked', 'exception.InstanceIsLocked', ([], {'instance_uuid': 'uuids.instance'}), '(instance_uuid=uuids.instance)\n', (5177, 5207), False, 'from nova import exception\n'), ((5528, 5582), 'nova.exception.InstanceNotFound', 'exception.InstanceNotFound', ([], {'instance_id': 'uuids.instance'}), '(instance_id=uuids.instance)\n', (5554, 5582), False, 'from nova import exception\n'), ((5904, 5958), 'nova.exception.InstanceNotFound', 'exception.InstanceNotFound', ([], {'instance_id': 'uuids.instance'}), '(instance_id=uuids.instance)\n', (5930, 5958), False, 'from nova import exception\n')]
import pandas as pd import numpy as np import os from df_to_sql.write2text import * def drop_cols(df, col2drop = []): if len(col2drop) > 0: cols = df.columns.to_list() ncols = [] for i in range(len(cols)): match = 0 for j in range(len(col2drop)): if cols[i] == col2drop[j]: match = 1 if match == 0: ncols.append(cols[i]) ndf = df[ncols] return ndf else: return df def qrybuilt(tbl, ndf, bycol, oncols = False): dfx = drop_cols(ndf, bycol) ncols = dfx.columns.to_list() lsqry = [] for i in range(len(ndf)): x = '' y = '' for j in range(len(bycol)): x1 = str(bycol[j]) + "='" + str(ndf.loc[i, bycol[j]]) + "'" if x == '': x = x1 else: x = x + " and " + x1 for n in range(len(ncols)): if oncols == False: a1 = str(ncols[n]) a2 = "'" + str(ndf.loc[i, ncols[n]]) + "'" if y == '': y = a1 + '=' + a2 else: y = y + "," + a1 + '=' + a2 else: a1 = str(ncols[n]) mat = 0 for j in range(len(oncols)): if oncols[j] == a1: mat = 1 break if mat == 1: a2 = "'" + str(ndf.loc[i, ncols[n]]) + "'" if y == '': y = a1 + '=' + a2 else: y = y + "," + a1 + '=' + a2 qry = "update " + tbl + ' set ' + y + ' Where ' + x lsqry.append(qry) return lsqry def CheckExist(conn , tbl, colname, values): qry = "select * from " + tbl + " where " + colname + "='" + values + "'" dfx = pd.read_sql(qry, conn) rw = dfx.shape[0] return rw def get_key(my_dict, val): for value, key in my_dict.items(): if value == val: return key def modstr(strval): if isinstance(strval, str): s1 = strval.replace("'","\\'") s2 = s1.replace(":","\\:") return s2 def insert_into_sql(tbl, tbl_property, lscol, lsval): col = '' val = '' dic = tbl_property if isinstance(lscol, list) and isinstance(lsval, list) and len(lscol) == len(lsval): for i in range(len(lscol)): valmod = '' try: if lsval[i] != '' and lsval[i] is not None: dtype = get_key(dic,lscol[i]) if dtype == 'text' or dtype == 'varchar': valmod = modstr(lsval[i]) else: valmod = str(lsval[i]) if val == '': col = lscol[i] val = "'" + valmod + "'" else: col = col + ',' + lscol[i] val = val + ',' + "'" + valmod + "'" else: pass except: pass qry = "insert into " + tbl + " (" + col + ") values (" + val + ")" return qry else: return "" def prep_update(tbl, tbl_property, lscol,lsval): hp = '' stval = '' dic = tbl_property if isinstance(lscol, list) and isinstance(lsval, list): if len(lscol) == len(lsval): for i in range(len(lscol)): try: if lsval[i] is not None and lsval[i] !='': dtype = get_key(dic,lscol[i]) if dtype == 'text' or dtype == 'varchar': stval = modstr(lsval[i]) else: stval = str(lsval[i]) x = lscol[i] + "='" + stval + "'" if hp == '': hp = x else: hp = hp + ',' + x else: pass except: pass else: print('num of col and value are not same') return hp elif isinstance(lscol, str) and isinstance(lsval, str): hp = "" comma = lsval.count(',') invertcomma = lsval.count("'") if invertcomma == (comma+1)*2: x1 = lscol.split(',') x2 = lsval.split(',') print(x1,x2) for i in range(len(x1)): x = x1[i] + "=" + x2[i] if hp == '': hp = x else: hp = hp + ',' + x if invertcomma <= 2: x1 = lscol.split(',') x2 = lsval.split(',') for i in range(len(x1)): x = str(x1[i]) + "='" + str(x2[i]) + "'" if hp == '': hp = x else: hp = hp + ',' + x return hp def UPIN(df, tbl, tblproperty, conn, bycols, oncols = False, operations = "and"): cr = conn.cursor() er = 0 lser = [] if isinstance(bycols, list): xdf = None bydf = df[bycols] ndf = drop_cols(df, bycols) if oncols: xdf = ndf[oncols] else: xdf = ndf fcols = xdf.columns.to_list() fcols_pbycol = xdf.columns.to_list() for n in range(len(bycols)): fcols_pbycol.append(bycols[n]) dfup = df[fcols_pbycol] x = '' #print(fcols, fcols_pbycol, len(fcols), len(fcols_pbycol)) lsqry = [] for i in range(len(df)): x = '' for j in range(len(bycols)): lss = bycols[j] lsv = df.loc[i,lss] st = str(lss) + "='" + str(lsv) + "'" if x == '': x = st else: x = x + " " + operation + " " + st qr = "select * from " + tbl + " where " + x dfx = pd.read_sql(qr, conn) rw = dfx.shape[0] ls = [] if rw != 0: for n in range(len(fcols)): ls.append(df.loc[i, fcols[n]]) qry = "update " + tbl + ' set ' + prep_update(tbl, tblproperty, fcols,ls) + ' where ' + x else: for n in range(len(fcols_pbycol)): ax = df.loc[i, fcols_pbycol[n]] ls.append(ax) qry = insert_into_sql(tbl, tblproperty , fcols_pbycol,ls) try: cr.execute(qry) except: lser.append(qry) er = er + 1 print('error sql: ', qry) if er > 500: wrt2txt(excmd, 'exe_error') print('exiting as error greater than 500 rows') exit() lsqry.append(qry) conn.commit() print('update done for ', len(lsqry), ' rows ') return lsqry elif isinstance(bycols, str): xdf = None byc = df[bycols].values.tolist() ndf = drop_cols(df, [bycols]) if oncols: xdf = ndf[oncols] else: xdf = ndf fcols = xdf.columns.to_list() fcols_pbycol = xdf.columns.to_list() fcols_pbycol.append(bycols) lsqry = [] for i in range(len(byc)): condval = byc[i] rs = CheckExist(conn, tbl, bycols, condval) ls = [] if rs != 0: for c1 in xdf: ls.append(xdf.loc[i,c1]) qry = "update " + tbl + ' set ' + prep_update(tbl, tblproperty, fcols,ls) + ' where ' + bycols + "='" + condval + "'" else: for c1 in ndf: ls.append(ndf.loc[i,c1]) ls.append(condval) qry = insert_into_sql(tbl, tblproperty , fcols_pbycol,ls) print(qry) cr.execute(qry) lsqry.append(qry) conn.commit() print('update done for ', len(lsqry), ' rows ') return lsqry
[ "pandas.read_sql" ]
[((1912, 1934), 'pandas.read_sql', 'pd.read_sql', (['qry', 'conn'], {}), '(qry, conn)\n', (1923, 1934), True, 'import pandas as pd\n'), ((6082, 6103), 'pandas.read_sql', 'pd.read_sql', (['qr', 'conn'], {}), '(qr, conn)\n', (6093, 6103), True, 'import pandas as pd\n')]
import sys, os, glob import argparse import time import random from copy import copy, deepcopy from termcolor import colored, cprint import numpy as np from sklearn.metrics import precision_recall_fscore_support from sklearn.metrics import roc_auc_score from sklearn.metrics import precision_recall_curve import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import torch.utils.data as data from torch.utils.tensorboard import SummaryWriter sys.path.append('../') from msda_src.model_utils import get_model_class, get_critic_class from msda_src.model_utils.domain_critic import ClassificationD, MMD, CoralD, WassersteinD from msda_src.utils.io import AmazonDataset, AmazonDomainDataset from msda_src.utils.io import say from msda_src.utils.op import softmax from dataset import ProcessedCNNInputDataset, OAGDomainDataset from models.cnn import CNNMatchModel from sklearn.metrics import confusion_matrix from sklearn.manifold import TSNE from utils import settings import warnings warnings.filterwarnings("ignore") argparser = argparse.ArgumentParser(description="Learning to Adapt from Multi-Source Domains") argparser.add_argument("--cuda", action="store_true") argparser.add_argument("--train", type=str, default="author,paper,aff", help="multi-source domains for training, separated with (,)") argparser.add_argument("--test", type=str, default="venue", help="target domain for testing") argparser.add_argument("--eval_only", action="store_true") argparser.add_argument("--critic", type=str, default="mmd") argparser.add_argument("--batch_size", type=int, default=32) argparser.add_argument("--batch_size_d", type=int, default=32) argparser.add_argument("--max_epoch", type=int, default=500) argparser.add_argument("--lr", type=float, default=1e-4) argparser.add_argument("--lr_d", type=float, default=1e-4) argparser.add_argument("--lambda_critic", type=float, default=0) argparser.add_argument("--lambda_gp", type=float, default=0) argparser.add_argument("--lambda_moe", type=float, default=1) argparser.add_argument("--lambda_mtl", type=float, default=0.3) argparser.add_argument("--lambda_all", type=float, default=0) argparser.add_argument("--lambda_dst", type=float, default=0) argparser.add_argument("--m_rank", type=int, default=10) argparser.add_argument("--lambda_entropy", type=float, default=0.0) argparser.add_argument("--load_model", type=str) argparser.add_argument("--save_model", type=str) argparser.add_argument("--metric", type=str, default="biaffine", help="mahalanobis: mahalanobis distance; biaffine: biaffine distance") argparser.add_argument('--no-cuda', action='store_true', default=False, help='Disables CUDA training.') argparser.add_argument('--matrix-size1', type=int, default=7, help='Matrix size 1.') argparser.add_argument('--matrix-size2', type=int, default=4, help='Matrix size 2.') argparser.add_argument('--mat1-channel1', type=int, default=8, help='Matrix1 number of channels1.') argparser.add_argument('--mat1-kernel-size1', type=int, default=3, help='Matrix1 kernel size1.') argparser.add_argument('--mat1-channel2', type=int, default=16, help='Matrix1 number of channel2.') argparser.add_argument('--mat1-kernel-size2', type=int, default=2, help='Matrix1 kernel size2.') argparser.add_argument('--mat1-hidden', type=int, default=512, help='Matrix1 hidden dim.') argparser.add_argument('--mat2-channel1', type=int, default=8, help='Matrix2 number of channels1.') argparser.add_argument('--mat2-kernel-size1', type=int, default=2, help='Matrix2 kernel size1.') argparser.add_argument('--mat2-hidden', type=int, default=512, help='Matrix2 hidden dim') argparser.add_argument('--build-index-window', type=int, default=5, help='Matrix2 hidden dim') argparser.add_argument('--seed', type=int, default=42, help='Random seed.') argparser.add_argument('--seed-delta', type=int, default=0, help='Random seed.') argparser.add_argument('--initial-accumulator-value', type=float, default=0.01, help='Initial accumulator value.') argparser.add_argument('--weight-decay', type=float, default=1e-3, help='Weight decay (L2 loss on parameters).') # argparser.add_argument('--dropout', type=float, default=0.2, # help='Dropout rate (1 - keep probability).') argparser.add_argument('--attn-dropout', type=float, default=0., help='Dropout rate (1 - keep probability).') argparser.add_argument('--check-point', type=int, default=2, help="Check point") argparser.add_argument('--shuffle', action='store_true', default=True, help="Shuffle dataset") args, _ = argparser.parse_known_args() writer = SummaryWriter('runs/{}_mix_moe_{}'.format(args.test, args.seed_delta)) class WeightScaler(nn.Module): def __init__(self): super(WeightScaler, self).__init__() self.multp = nn.Parameter(torch.rand(1)) # requires_grad is True by default for Parameter class HLoss(nn.Module): def __init__(self): super(HLoss, self).__init__() def forward(self, x): # b = F.softmax(x, dim=1) * F.log_softmax(x, dim=1) b = x * torch.log(x) b = -1.0 * b.sum() return b class L1Norm(nn.Module): def __init__(self): super(L1Norm, self).__init__() def forward(self, x): return torch.norm(x, 1, 1).sum() def domain_encoding(loaders, args, encoders): ''' Compute the encoding of domains, each domain is represented as its mean vector Note: the covariance inverse matrix is learned ''' statistics = [] for load_i, loader in enumerate(loaders): ind = 0 labels = None S = [] for batch1, batch2, label in loader: if args.cuda: batch1 = Variable(batch1.cuda()) batch2 = Variable(batch2.cuda()) _, s_out = encoders[load_i](batch1, batch2) # print("s_out", s_out) S.append(s_out) if ind == 0: labels = label else: labels = torch.cat((labels, label), dim=0) ind += 1 S = torch.cat(S, 0) # print("S", S) neg_index = ((labels == 0).nonzero()) pos_index = ((labels == 1).nonzero()) neg_index = Variable(neg_index.expand(neg_index.size(0), S.size(1))) pos_index = Variable(pos_index.expand(pos_index.size(0), S.size(1))) if args.cuda: pos_index = pos_index.cuda() neg_index = neg_index.cuda() pos_S = torch.gather(S, 0, pos_index) neg_S = torch.gather(S, 0, neg_index) pos_mu_S = torch.mean(pos_S, dim=0, keepdim=True) neg_mu_S = torch.mean(neg_S, dim=0, keepdim=True) mu_S = torch.mean(S, dim=0, keepdim=True) # print("mu_s", mu_S) # print("pos_mu_s", pos_mu_S) # print("neg_mu_s", neg_mu_S) statistics.append((mu_S, pos_mu_S, neg_mu_S)) return statistics TEMPERATURE = 4 def mahalanobis_metric_fast(p, mu, U, pos_mu, pos_U, neg_mu, neg_U): # covi = (cov + I).inverse() # print("p", type(p), p) # print("p", p.shape, p) # print("mu", mu.shape, mu) # # print("p - mu", p - mu) # print("U", U) mahalanobis_distances = (p - mu).mm(U.mm(U.t())).mm((p - mu).t()) pos_mahalanobis_distance = (p - pos_mu).mm(pos_U.mm(pos_U.t())).mm((p - pos_mu).t()).diag().sqrt().data neg_mahalanobis_distance = (p - neg_mu).mm(neg_U.mm(neg_U.t())).mm((p - neg_mu).t()).diag().sqrt().data mahalanobis_ratio1 = pos_mahalanobis_distance - neg_mahalanobis_distance mahalanobis_ratio2 = neg_mahalanobis_distance - pos_mahalanobis_distance max_ratio = torch.max(mahalanobis_ratio1, mahalanobis_ratio2) return max_ratio # / TEMPERATURE # return mahalanobis_distances.diag().sqrt().data def mahalanobis_metric(p, S, L, U, pos_U, neg_U, args, encoder=None): r''' Compute the mahalanobis distance between the encoding of a sample (p) and a set (S). Args: p: tensor (batch_size, dim), a batch of samples S: tensor (size, dim), a domain which contains a set of samples encoder: a module used for encoding p and S Return: mahalanobis_distances: tensor (batch_size) ''' if encoder is not None: p = encoder(p) # (batch_size, dim) S = encoder(S) # (size, dim) neg_index = ((L == 0).nonzero()) pos_index = ((L == 1).nonzero()) neg_index = neg_index.expand(neg_index.size(0), S.data.size(1)) pos_index = pos_index.expand(pos_index.size(0), S.data.size(1)) neg_S = torch.gather(S, 0, neg_index) pos_S = torch.gather(S, 0, pos_index) neg_mu = torch.mean(neg_S, dim=0, keepdim=True) pos_mu = torch.mean(pos_S, dim=0, keepdim=True) pos_mahalanobis_distance = (p - pos_mu).mm(pos_U.mm(pos_U.t())).mm((p - pos_mu).t()).diag().sqrt() neg_mahalanobis_distance = (p - neg_mu).mm(neg_U.mm(neg_U.t())).mm((p - neg_mu).t()).diag().sqrt() mahalanobis_ratio1 = pos_mahalanobis_distance - neg_mahalanobis_distance mahalanobis_ratio2 = neg_mahalanobis_distance - pos_mahalanobis_distance max_ratio = torch.max(mahalanobis_ratio1, mahalanobis_ratio2) return max_ratio.clamp(0.01, 2) # / TEMPERATURE # .clamp(0.001, 1) # mu_S = torch.mean(S, dim=0, keepdim=True) # (1, dim) # mahalanobis_distances = (p - mu_S).mm(U.mm(U.t())).mm((p - mu_S).t()) # return mahalanobis_distances.diag().sqrt().clamp(0.01, 2) def biaffine_metric_fast(p, mu, U): biaffine_distances = p.mm(U).mm(mu.t()) return biaffine_distances.squeeze(1).data def biaffine_metric(p, S, U, W, V, args, encoder=None): ''' Compute the biaffine distance between the encoding of a sample (p) and a set (S). Args: p: tensor (batch_size, dim), a batch of samples U: matrix (dim, dim) S: tensor (size, dim), a domain which contains a set of samples encoder: a module used for encoding p and S Return: biaffine_distance: tensor (batch_size) ''' if encoder is not None: p = encoder(p) S = encoder(S) mu_S = torch.mean(S, dim=0, keepdim=True) biaffine_distances = p.mm(U).mm(mu_S.t()) + p.mm(W) + mu_S.mm(V) # extra components return biaffine_distances.squeeze(1).clamp(-10, 10) DATA_DIR = "../../msda-data/amazon/chen12" def train_epoch(iter_cnt, encoders, classifiers, critic, mats, data_loaders, args, optim_model, epoch): encoders, encoder_dst = encoders classifiers, classifier_dst, classifier_mix = classifiers map(lambda m: m.train(), encoders + [encoder_dst, classifier_dst, critic, classifier_mix] + classifiers) train_loaders, train_loader_dst, unl_loader, valid_loader = data_loaders dup_train_loaders = deepcopy(train_loaders) # mtl_criterion = nn.CrossEntropyLoss() mtl_criterion = nn.NLLLoss() moe_criterion = nn.NLLLoss() # with log_softmax separated kl_criterion = nn.MSELoss() entropy_criterion = HLoss() if args.metric == "biaffine": metric = biaffine_metric Us, Ws, Vs = mats else: metric = mahalanobis_metric Us, Ps, Ns = mats loss_total = 0 total = 0 for batches, batches_dst, unl_batch in zip(zip(*train_loaders), train_loader_dst, unl_loader): train_batches1, train_batches2, train_labels = zip(*batches) # print("train batches1", train_labels[0].size()) # print("train batches2", train_batches2) # print("train labels", train_labels) unl_critic_batch1, unl_critic_batch2, unl_critic_label = unl_batch # print("unl", unl_critic_batch1) batches1_dst, batches2_dst, labels_dst = batches_dst # print("batches1_dst", batches1_dst) # print("batches2_dst", batches2_dst) total += len(batches1_dst) iter_cnt += 1 if args.cuda: train_batches1 = [batch.cuda() for batch in train_batches1] train_batches2 = [batch.cuda() for batch in train_batches2] train_labels = [label.cuda() for label in train_labels] batches1_dst = batches1_dst.cuda() batches2_dst = batches2_dst.cuda() labels_dst = labels_dst.cuda() unl_critic_batch1 = unl_critic_batch1.cuda() unl_critic_batch2 = unl_critic_batch2.cuda() unl_critic_label = unl_critic_label.cuda() # train_batches1 = [Variable(batch) for batch in train_batches1] # train_batches2 = [Variable(batch) for batch in train_batches2] # train_labels = [Variable(label) for label in train_labels] # unl_critic_batch1 = Variable(unl_critic_batch1) # unl_critic_batch2 = Variable(unl_critic_batch2) # unl_critic_label = Variable(unl_critic_label) optim_model.zero_grad() loss_train_dst = [] loss_mtl = [] loss_moe = [] loss_kl = [] loss_entropy = [] loss_dan = [] loss_all = [] ms_outputs = [] # (n_sources, n_classifiers) hiddens = [] hidden_corresponding_labels = [] # labels = [] _, hidden_dst = encoder_dst(batches1_dst, batches2_dst) cur_output_dst = classifier_dst(hidden_dst) cur_output_dst_mem = torch.softmax(cur_output_dst, dim=1) cur_output_dst = torch.log(cur_output_dst_mem) loss_train_dst.append(mtl_criterion(cur_output_dst, labels_dst)) outputs_dst_transfer = [] for i in range(len(train_batches1)): _, cur_hidden = encoders[i](batches1_dst, batches2_dst) cur_output = classifiers[i](cur_hidden) outputs_dst_transfer.append(cur_output) for i, (batch1, batch2, label) in enumerate(zip(train_batches1, train_batches2, train_labels)): # source i _, hidden = encoders[i](batch1, batch2) outputs = [] # create output matrix: # - (i, j) indicates the output of i'th source batch using j'th classifier # print("hidden", hidden) # raise hiddens.append(hidden) for classifier in classifiers: output = classifier(hidden) output = torch.log_softmax(output, dim=1) # print("output", output) outputs.append(output) ms_outputs.append(outputs) hidden_corresponding_labels.append(label) # multi-task loss # print("ms & label", ms_outputs[i][i], label) loss_mtl.append(mtl_criterion(ms_outputs[i][i], label)) # labels.append(label) if args.lambda_critic > 0: # critic_batch = torch.cat([batch, unl_critic_batch]) critic_label = torch.cat([1 - unl_critic_label, unl_critic_label]) # critic_label = torch.cat([1 - unl_critic_label] * len(train_batches) + [unl_critic_label]) if isinstance(critic, ClassificationD): critic_output = critic(torch.cat(hidden, encoders[i](unl_critic_batch1, unl_critic_batch2))) loss_dan.append(critic.compute_loss(critic_output, critic_label)) else: critic_output = critic(hidden, encoders[i](unl_critic_batch1, unl_critic_batch2)) loss_dan.append(critic_output) # critic_output = critic(torch.cat(hiddens), encoder(unl_critic_batch)) # loss_dan = critic_output else: loss_dan = Variable(torch.FloatTensor([0])) # assert (len(outputs) == len(outputs[0])) source_ids = range(len(train_batches1)) # for i in source_ids: # support_ids = [x for x in source_ids if x != i] # experts support_ids = [x for x in source_ids] # experts # i = 0 # support_alphas = [ metric( # hiddens[i], # hiddens[j].detach(), # hidden_corresponding_labels[j], # Us[j], Ps[j], Ns[j], # args) for j in support_ids ] if args.metric == "biaffine": source_alphas = [metric(hidden_dst, hiddens[j].detach(), Us[0], Ws[0], Vs[0], # for biaffine metric, we use a unified matrix args) for j in source_ids] else: source_alphas = [metric(hidden_dst, # i^th source hiddens[j].detach(), hidden_corresponding_labels[j], Us[j], Ps[j], Ns[j], args) for j in source_ids] support_alphas = [source_alphas[x] for x in support_ids] # print torch.cat([ x.unsqueeze(1) for x in support_alphas ], 1) support_alphas = softmax(support_alphas) # print("support_alphas after softmax", support_alphas) # meta-supervision: KL loss over \alpha and real source source_alphas = softmax(source_alphas) # [ 32, 32, 32 ] source_labels = [torch.FloatTensor([x == len(train_batches1)]) for x in source_ids] # one-hot if args.cuda: source_alphas = [alpha.cuda() for alpha in source_alphas] source_labels = [label.cuda() for label in source_labels] source_labels = Variable(torch.stack(source_labels, dim=0)) # 3*1 # print("source labels", source_labels) source_alphas = torch.stack(source_alphas, dim=0) # print("source_alpha after stack", source_alphas) source_labels = source_labels.expand_as(source_alphas).permute(1, 0) source_alphas = source_alphas.permute(1, 0) loss_kl.append(kl_criterion(source_alphas, source_labels)) # entropy loss over \alpha # entropy_loss = entropy_criterion(torch.stack(support_alphas, dim=0).permute(1, 0)) # print source_alphas loss_entropy.append(entropy_criterion(source_alphas)) output_moe_i = sum([alpha.unsqueeze(1).repeat(1, 2) * F.softmax(outputs_dst_transfer[id], dim=1) \ for alpha, id in zip(support_alphas, support_ids)]) # output_moe_full = sum([ alpha.unsqueeze(1).repeat(1, 2) * F.softmax(ms_outputs[i][id], dim=1) \ # for alpha, id in zip(full_alphas, source_ids) ]) # print("output_moe_i & labels", output_moe_i, train_labels[i]) loss_moe.append(moe_criterion(torch.log(output_moe_i), labels_dst)) # loss_moe.append(moe_criterion(torch.log(output_moe_full), train_labels[i])) # print("labels_dst", labels_dst) # upper_out = classifier_mix(torch.cat((cur_output_dst_mem, output_moe_i), dim=1)) upper_out = cur_output_dst_mem + classifier_mix.multp * output_moe_i loss_all = mtl_criterion(torch.log_softmax(upper_out, dim=1), labels_dst) loss_train_dst = sum(loss_train_dst) loss_mtl = sum(loss_mtl) # print("loss mtl", loss_mtl) # loss_mtl = loss_mtl.mean() loss_mtl /= len(source_ids) loss_moe = sum(loss_moe) # if iter_cnt < 400: # lambda_moe = 0 # lambda_entropy = 0 # else: lambda_moe = args.lambda_moe lambda_entropy = args.lambda_entropy # loss = (1 - lambda_moe) * loss_mtl + lambda_moe * loss_moe loss = args.lambda_mtl * loss_mtl + lambda_moe * loss_moe loss_kl = sum(loss_kl) loss_entropy = sum(loss_entropy) loss += args.lambda_entropy * loss_entropy loss += loss_train_dst * args.lambda_dst loss += loss_all * args.lambda_all loss_total += loss if args.lambda_critic > 0: loss_dan = sum(loss_dan) loss += args.lambda_critic * loss_dan loss.backward() optim_model.step() # print("loss entropy", loss_entropy) # print("mats", [Us, Ps, Ns]) # for paras in task_paras: # print(paras) # for name, param in paras: # if param.requires_grad: # print(name, param.data) # for name, param in encoder.named_parameters(): # if param.requires_grad: # # print(name, param.data) # print(name, param.grad) for cls_i, classifier in enumerate(classifiers): for name, param in classifier.named_parameters(): # print(cls_i, name, param.grad) pass if iter_cnt % 5 == 0: # [(mu_i, covi_i), ...] # domain_encs = domain_encoding(dup_train_loaders, args, encoder) if args.metric == "biaffine": mats = [Us, Ws, Vs] else: mats = [Us, Ps, Ns] # evaluate( # # [encoders, encoder_dst], # # [classifiers, classifier_dst, classifier_mix], # # mats, # # [dup_train_loaders, valid_loader], # # True, # # args # # ) # say("\r" + " " * 50) # TODO: print train acc as well # print("loss dan", loss_dan) say("{} MTL loss: {:.4f}, MOE loss: {:.4f}, DAN loss: {:.4f}, " "loss: {:.4f}\n" # ", dev acc/oracle: {:.4f}/{:.4f}" .format(iter_cnt, loss_mtl.item(), loss_moe.item(), loss_dan.item(), loss.item(), # curr_dev, # oracle_curr_dev )) writer.add_scalar('training_loss', loss_total / total, epoch) say("\n") return iter_cnt def compute_oracle(outputs, label, args): ''' Compute the oracle accuracy given outputs from multiple classifiers ''' # oracle = torch.ByteTensor([0] * label.shape[0]) oracle = torch.BoolTensor([0] * label.shape[0]) if args.cuda: oracle = oracle.cuda() for i, output in enumerate(outputs): pred = output.data.max(dim=1)[1] # print("pred", pred) # print("label", label) oracle |= pred.eq(label.byte()) return oracle def evaluate(epoch, encoders, classifiers, mats, loaders, return_best_thrs, args, thr=None): ''' Evaluate model using MOE ''' encoders, encoder_dst = encoders classifiers, classifier_dst, classifier_mix = classifiers map(lambda m: m.eval(), encoders + classifiers + [encoder_dst, classifier_dst, classifier_mix]) if args.metric == "biaffine": Us, Ws, Vs = mats else: Us, Ps, Ns = mats source_loaders, valid_loader = loaders domain_encs = domain_encoding(source_loaders, args, encoders) oracle_correct = 0 correct = 0 tot_cnt = 0 y_true = [] y_pred = [] y_score = [] loss = 0. source_ids = range(len(domain_encs)) for batch1, batch2, label in valid_loader: if args.cuda: batch1 = batch1.cuda() batch2 = batch2.cuda() label = label.cuda() # print("eval labels", label) batch1 = Variable(batch1) batch2 = Variable(batch2) bs = len(batch1) # print("bs", len(batch1)) _, hidden_dst = encoder_dst(batch1, batch2) cur_output_dst = classifier_dst(hidden_dst) cur_output_dst_mem = torch.softmax(cur_output_dst, dim=1) # print("mem", cur_output_dst_mem) cur_output_dst = torch.log(cur_output_dst_mem) outputs_dst_transfer = [] for src_i in range(len(source_loaders)): _, cur_hidden = encoders[src_i](batch1, batch2) cur_output = classifiers[src_i](cur_hidden) outputs_dst_transfer.append(cur_output) # _, hidden = encoders[0](batch1, batch2) # source_ids = range(len(domain_encs)) if args.metric == "biaffine": alphas = [biaffine_metric_fast(hidden_dst, mu[0], Us[0]) \ for mu in domain_encs] else: alphas = [mahalanobis_metric_fast(hidden_dst, mu[0], U, mu[1], P, mu[2], N) \ for (mu, U, P, N) in zip(domain_encs, Us, Ps, Ns)] # # alphas = [ (1 - x / sum(alphas)) for x in alphas ] alphas = softmax(alphas) if args.cuda: alphas = [alpha.cuda() for alpha in alphas] alphas = [Variable(alpha) for alpha in alphas] # # outputs = [F.softmax(classifier(hidden), dim=1) for classifier in classifiers] output_moe = sum([alpha.unsqueeze(1).repeat(1, 2) * output_i \ for (alpha, output_i) in zip(alphas, outputs_dst_transfer)]) # pred = output.data.max(dim=1)[1] # oracle_eq = compute_oracle(outputs, label, args) # outputs = classifier_mix(torch.cat((cur_output_dst_mem, output_moe), dim=1)) outputs = cur_output_dst_mem + classifier_mix.multp * output_moe # print("weight mix", classifier_mix.multp) outputs_upper_logits = torch.log_softmax(outputs, dim=1) # outputs_upper_logits = torch.log(cur_output_dst_mem) outputs_upper_logits = output_moe # print("outputs_upper_logits", outputs_upper_logits) pred = outputs_upper_logits.data.max(dim=1)[1] # oracle_eq = compute_oracle(outputs_upper_logits, label, args) loss_batch = F.nll_loss(outputs_upper_logits, label) loss += bs * loss_batch.item() # if args.eval_only: # for i in range(batch1.shape[0]): # for j in range(len(alphas)): # say("{:.4f}: [{:.4f}, {:.4f}], ".format( # alphas[j].data[i], outputs[j].data[i][0], outputs[j].data[i][1]) # ) # oracle_TF = "T" if oracle_eq[i] == 1 else colored("F", 'red') # say("gold: {}, pred: {}, oracle: {}\n".format(label[i], pred[i], oracle_TF)) # say("\n") # print torch.cat( # [ # torch.cat([ x.unsqueeze(1) for x in alphas ], 1), # torch.cat([ x for x in outputs ], 1) # ], 1 # ) y_true += label.tolist() y_pred += pred.tolist() # print("output", output[:, 1].data.tolist()) y_score += outputs_upper_logits[:, 1].data.tolist() # print("cur y score", y_score) correct += pred.eq(label).sum() # oracle_correct += oracle_eq.sum() tot_cnt += outputs_upper_logits.size(0) # print("y_true", y_true) # print("y_pred", y_pred) if thr is not None: print("using threshold %.4f" % thr) y_score = np.array(y_score) y_pred = np.zeros_like(y_score) y_pred[y_score > thr] = 1 else: # print("y_score", y_score) pass loss /= tot_cnt prec, rec, f1, _ = precision_recall_fscore_support(y_true, y_pred, average="binary") # print("y_score", y_score) auc = roc_auc_score(y_true, y_score) print("Loss: {:.4f}, AUC: {:.2f}, Prec: {:.2f}, Rec: {:.2f}, F1: {:.2f}".format( loss, auc * 100, prec * 100, rec * 100, f1 * 100)) best_thr = None metric = [auc, prec, rec, f1] if return_best_thrs: precs, recs, thrs = precision_recall_curve(y_true, y_score) f1s = 2 * precs * recs / (precs + recs) f1s = f1s[:-1] thrs = thrs[~np.isnan(f1s)] f1s = f1s[~np.isnan(f1s)] best_thr = thrs[np.argmax(f1s)] print("best threshold={:.4f}, f1={:.4f}".format(best_thr, np.max(f1s))) writer.add_scalar('val_loss', loss, epoch) else: writer.add_scalar('test_f1', f1, epoch) acc = float(correct) / tot_cnt oracle_acc = float(oracle_correct) / tot_cnt # return (acc, oracle_acc), confusion_matrix(y_true, y_pred) return best_thr, metric def evaluate_cross(encoder, classifiers, mats, loaders, return_best_thrs, args, thr=None): ''' Evaluate model using MOE ''' map(lambda m: m.eval(), [encoder] + classifiers) if args.metric == "biaffine": Us, Ws, Vs = mats else: Us, Ps, Ns = mats source_loaders, valid_loaders_src = loaders domain_encs = domain_encoding(source_loaders, args, encoder) source_ids = range(len(valid_loaders_src)) thresholds = [] metrics = [] alphas_weights = np.zeros(shape=(4, 4)) for src_i in range(len(valid_loaders_src)): valid_loader = valid_loaders_src[src_i] oracle_correct = 0 correct = 0 tot_cnt = 0 y_true = [] y_pred = [] y_score = [] # support_ids = [x for x in source_ids if x != src_i] # experts support_ids = [x for x in source_ids] # experts cur_domain_encs = [domain_encs[x] for x in support_ids] cur_Us = [Us[x] for x in support_ids] cur_Ps = [Ps[x] for x in support_ids] cur_Ns = [Ns[x] for x in support_ids] cur_alpha_weights = [[]] * 4 cur_alpha_weights_stack = np.empty(shape=(0, len(support_ids))) for batch1, batch2, label in valid_loader: if args.cuda: batch1 = batch1.cuda() batch2 = batch2.cuda() label = label.cuda() # print("eval labels", label) batch1 = Variable(batch1) batch2 = Variable(batch2) _, hidden = encoder(batch1, batch2) # source_ids = range(len(domain_encs)) if args.metric == "biaffine": alphas = [biaffine_metric_fast(hidden, mu[0], Us[0]) \ for mu in domain_encs] else: alphas = [mahalanobis_metric_fast(hidden, mu[0], U, mu[1], P, mu[2], N) \ for (mu, U, P, N) in zip(cur_domain_encs, cur_Us, cur_Ps, cur_Ns)] # alphas = [ (1 - x / sum(alphas)) for x in alphas ] alphas = softmax(alphas) # print("alphas", alphas[0].mean(), alphas[1].mean(), alphas[2].mean()) # print("alphas", alphas) alphas = [] for al_i in range(len(support_ids)): alphas.append(torch.zeros(size=(batch1.size()[0],))) alphas[src_i] = torch.ones(size=(batch1.size()[0],)) alpha_cat = torch.zeros(size=(alphas[0].shape[0], len(support_ids))) for col, a_list in enumerate(alphas): alpha_cat[:, col] = a_list cur_alpha_weights_stack = np.concatenate((cur_alpha_weights_stack, alpha_cat.detach().numpy())) # for j, supp_id in enumerate(support_ids): # cur_alpha_weights[supp_id] += alphas[j].data.tolist() # cur_alpha_weights[supp_id].append(alphas[j].mean().item()) if args.cuda: alphas = [alpha.cuda() for alpha in alphas] alphas = [Variable(alpha) for alpha in alphas] outputs = [F.softmax(classifiers[j](hidden), dim=1) for j in support_ids] output = sum([alpha.unsqueeze(1).repeat(1, 2) * output_i \ for (alpha, output_i) in zip(alphas, outputs)]) # print("pred output", output) pred = output.data.max(dim=1)[1] oracle_eq = compute_oracle(outputs, label, args) if args.eval_only: for i in range(batch1.shape[0]): for j in range(len(alphas)): say("{:.4f}: [{:.4f}, {:.4f}], ".format( alphas[j].data[i], outputs[j].data[i][0], outputs[j].data[i][1]) ) oracle_TF = "T" if oracle_eq[i] == 1 else colored("F", 'red') say("gold: {}, pred: {}, oracle: {}\n".format(label[i], pred[i], oracle_TF)) say("\n") # print torch.cat( # [ # torch.cat([ x.unsqueeze(1) for x in alphas ], 1), # torch.cat([ x for x in outputs ], 1) # ], 1 # ) y_true += label.tolist() y_pred += pred.tolist() y_score += output[:, 1].data.tolist() correct += pred.eq(label).sum() oracle_correct += oracle_eq.sum() tot_cnt += output.size(0) # print("y_true", y_true) # print("y_pred", y_pred) # for j in support_ids: # print(src_i, j, cur_alpha_weights[j]) # alphas_weights[src_i, j] = np.mean(cur_alpha_weights[j]) # print(alphas_weights) alphas_weights[src_i, support_ids] = np.mean(cur_alpha_weights_stack, axis=0) if thr is not None: print("using threshold %.4f" % thr[src_i]) y_score = np.array(y_score) y_pred = np.zeros_like(y_score) y_pred[y_score > thr[src_i]] = 1 # prec, rec, f1, _ = precision_recall_fscore_support(y_true, y_pred, average="binary") acc = float(correct) / tot_cnt oracle_acc = float(oracle_correct) / tot_cnt # print("source", src_i, "validation results: precision: {:.2f}, recall: {:.2f}, f1: {:.2f}".format( # prec*100, rec*100, f1*100)) # return (acc, oracle_acc), confusion_matrix(y_true, y_pred) prec, rec, f1, _ = precision_recall_fscore_support(y_true, y_pred, average="binary") auc = roc_auc_score(y_true, y_score) print("source {}, AUC: {:.2f}, Prec: {:.2f}, Rec: {:.2f}, F1: {:.2f}".format( src_i, auc * 100, prec * 100, rec * 100, f1 * 100)) metrics.append([auc, prec, rec, f1]) if return_best_thrs: precs, recs, thrs = precision_recall_curve(y_true, y_score) f1s = 2 * precs * recs / (precs + recs) f1s = f1s[:-1] thrs = thrs[~np.isnan(f1s)] f1s = f1s[~np.isnan(f1s)] best_thr = thrs[np.argmax(f1s)] print("best threshold=%4f, f1=%.4f", best_thr, np.max(f1s)) thresholds.append(best_thr) print("source domain weight matrix\n", alphas_weights) metrics = np.array(metrics) return thresholds, metrics, alphas_weights def predict(args): encoder, classifiers, Us, Ps, Ns = torch.load(args.load_model) map(lambda m: m.eval(), [encoder] + classifiers) # args = argparser.parse_args() # say(args) if args.cuda: map(lambda m: m.cuda(), [encoder] + classifiers) Us = [U.cuda() for U in Us] Ps = [P.cuda() for P in Ps] Ns = [N.cuda() for N in Ns] say("\nTransferring from %s to %s\n" % (args.train, args.test)) source_train_sets = args.train.split(',') train_loaders = [] for source in source_train_sets: filepath = os.path.join(DATA_DIR, "%s_train.svmlight" % (source)) train_dataset = AmazonDataset(filepath) train_loader = data.DataLoader( train_dataset, batch_size=args.batch_size, shuffle=False, num_workers=0 ) train_loaders.append(train_loader) test_filepath = os.path.join(DATA_DIR, "%s_test.svmlight" % (args.test)) test_dataset = AmazonDataset(test_filepath) test_loader = data.DataLoader( test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=0 ) say("Corpus loaded.\n") mats = [Us, Ps, Ns] (acc, oracle_acc), confusion_mat = evaluate( encoder, classifiers, mats, [train_loaders, test_loader], args ) say(colored("Test accuracy/oracle {:.4f}/{:.4f}\n".format(acc, oracle_acc), 'red')) def train(args): ''' Training Strategy Input: source = {S1, S2, ..., Sk}, target = {T} Train: Approach 1: fix metric and learn encoder only Approach 2: learn metric and encoder alternatively ''' # test_mahalanobis_metric() and return args.cuda = not args.no_cuda and torch.cuda.is_available() say('cuda is available %s\n' % args.cuda) np.random.seed(args.seed) torch.manual_seed(args.seed + args.seed_delta) if args.cuda: torch.cuda.manual_seed(args.seed + args.seed_delta) source_train_sets = args.train.split(',') print("sources", source_train_sets) encoders = [] for _ in range(len(source_train_sets)): # encoder_class = get_model_class("mlp") encoder_class = CNNMatchModel(input_matrix_size1=args.matrix_size1, input_matrix_size2=args.matrix_size2, mat1_channel1=args.mat1_channel1, mat1_kernel_size1=args.mat1_kernel_size1, mat1_channel2=args.mat1_channel2, mat1_kernel_size2=args.mat1_kernel_size2, mat1_hidden=args.mat1_hidden, mat2_channel1=args.mat2_channel1, mat2_kernel_size1=args.mat2_kernel_size1, mat2_hidden=args.mat2_hidden) # encoder_class.add_config(argparser) encoders.append(encoder_class) encoder_dst = CNNMatchModel(input_matrix_size1=args.matrix_size1, input_matrix_size2=args.matrix_size2, mat1_channel1=args.mat1_channel1, mat1_kernel_size1=args.mat1_kernel_size1, mat1_channel2=args.mat1_channel2, mat1_kernel_size2=args.mat1_kernel_size2, mat1_hidden=args.mat1_hidden, mat2_channel1=args.mat2_channel1, mat2_kernel_size1=args.mat2_kernel_size1, mat2_hidden=args.mat2_hidden) critic_class = get_critic_class(args.critic) critic_class.add_config(argparser) args = argparser.parse_args() say(args) # encoder is shared across domains # encoder = encoder_class(args) # encoder = encoder_class print() print("encoder", encoders[0]) say("Transferring from %s to %s\n" % (args.train, args.test)) train_loaders = [] # valid_loaders_src = [] # test_loaders_src = [] Us = [] Ps = [] Ns = [] Ws = [] Vs = [] # Ms = [] for source in source_train_sets: # filepath = os.path.join(DATA_DIR, "%s_train.svmlight" % (source)) filepath = os.path.join(settings.DOM_ADAPT_DIR, "{}_train.pkl".format(source)) assert (os.path.exists(filepath)) # train_dataset = AmazonDataset(filepath) train_dataset = ProcessedCNNInputDataset(source, "train") train_loader = data.DataLoader( train_dataset, batch_size=args.batch_size, shuffle=False, num_workers=0 ) train_loaders.append(train_loader) # cur_valid_dataset = ProcessedCNNInputDataset(source, "valid") # cur_valid_loader = data.DataLoader( # cur_valid_dataset, # batch_size=args.batch_size, # shuffle=False, # num_workers=0 # ) # valid_loaders_src.append(cur_valid_loader) # # cur_test_dataset = ProcessedCNNInputDataset(source, "test") # cur_test_loader = data.DataLoader( # cur_test_dataset, # batch_size=args.batch_size, # shuffle=False, # num_workers=0 # ) # test_loaders_src.append(cur_test_loader) if args.metric == "biaffine": U = torch.FloatTensor(encoders[0].n_d, encoders[0].n_d) W = torch.FloatTensor(encoders[0].n_d, 1) nn.init.xavier_uniform(W) Ws.append(W) V = torch.FloatTensor(encoders[0].n_d, 1) nn.init.xavier_uniform(V) Vs.append(V) else: U = torch.FloatTensor(encoders[0].n_d, args.m_rank) nn.init.xavier_uniform_(U) Us.append(U) P = torch.FloatTensor(encoders[0].n_d, args.m_rank) nn.init.xavier_uniform_(P) Ps.append(P) N = torch.FloatTensor(encoders[0].n_d, args.m_rank) nn.init.xavier_uniform_(N) Ns.append(N) # Ms.append(U.mm(U.t())) # unl_filepath = os.path.join(DATA_DIR, "%s_train.svmlight" % (args.test)) unl_filepath = os.path.join(settings.DOM_ADAPT_DIR, "{}_train.pkl".format(args.test)) print("****************", unl_filepath) assert (os.path.exists(unl_filepath)) # unl_dataset = AmazonDomainDataset(unl_filepath) # using domain as labels unl_dataset = OAGDomainDataset(args.test, "train") unl_loader = data.DataLoader( unl_dataset, batch_size=args.batch_size, shuffle=True, num_workers=0 ) train_dataset_dst = ProcessedCNNInputDataset(args.test, "train") train_loader_dst = data.DataLoader( train_dataset_dst, batch_size=args.batch_size, shuffle=False, num_workers=0 ) # valid_filepath = os.path.join(DATA_DIR, "%s_test.svmlight" % (args.test)) # No dev files # valid_dataset = AmazonDataset(valid_filepath) valid_dataset = ProcessedCNNInputDataset(args.test, "valid") print("valid y", len(valid_dataset), valid_dataset.y) valid_loader = data.DataLoader( valid_dataset, batch_size=args.batch_size, shuffle=False, num_workers=0 ) # test_filepath = os.path.join(DATA_DIR, "%s_test.svmlight" % (args.test)) # assert (os.path.exists(test_filepath)) # test_dataset = AmazonDataset(test_filepath) test_dataset = ProcessedCNNInputDataset(args.test, "test") test_loader = data.DataLoader( test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=0 ) say("Corpus loaded.\n") classifiers = [] for source in source_train_sets: # only one layer classifier = nn.Linear(encoders[0].n_out, 2) # binary classification # classifier = encoder.fc_out # nn.init.xavier_normal(classifier.weight) # nn.init.constant(classifier.bias, 0.1) classifiers.append(classifier) classifier_dst = nn.Linear(encoder_dst.n_out, 2) # classifier_mix = nn.Linear(2, 2) classifier_mix = WeightScaler() critic = critic_class(encoders[0], args) # if args.save_model: # say(colored("Save model to {}\n".format(args.save_model + ".init"), 'red')) # torch.save([encoder, classifiers, Us, Ps, Ns], args.save_model + ".init") if args.cuda: map(lambda m: m.cuda(), [encoder_dst, critic, classifier_dst, classifier_mix] + encoders + classifiers) Us = [Variable(U.cuda(), requires_grad=True) for U in Us] Ps = [Variable(P.cuda(), requires_grad=True) for P in Ps] Ns = [Variable(N.cuda(), requires_grad=True) for N in Ns] if args.metric == "biaffine": Ws = [Variable(W.cuda(), requires_grad=True) for W in Ws] Vs = [Variable(V.cuda(), requires_grad=True) for V in Vs] # Ms = [ U.mm(U.t()) for U in Us ] # say("\nEncoder: {}\n".format(encoder)) for i, classifier in enumerate(classifiers): say("Classifier-{}: {}\n".format(i, classifier)) say("Critic: {}\n".format(critic)) requires_grad = lambda x: x.requires_grad # task_params = list(encoder.parameters()) task_params = [] for encoder in encoders: task_params += encoder.parameters() task_params += encoder_dst.parameters() for classifier in classifiers: task_params += list(classifier.parameters()) task_params += classifier_dst.parameters() task_params += classifier_mix.parameters() # task_params += [classifier_mix.data] task_params += list(critic.parameters()) task_params += Us task_params += Ps task_params += Ns if args.metric == "biaffine": task_params += Ws task_params += Vs optim_model = optim.Adagrad( # use adagrad instead of adam filter(requires_grad, task_params), lr=args.lr, weight_decay=1e-4 ) say("Training will begin from scratch\n") best_dev = 0 best_test = 0 iter_cnt = 0 # encoder.load_state_dict(torch.load(os.path.join(settings.OUT_VENUE_DIR, "venue-matching-cnn.mdl"))) for epoch in range(args.max_epoch): say("epoch: {}\n".format(epoch)) if args.metric == "biaffine": mats = [Us, Ws, Vs] else: mats = [Us, Ps, Ns] iter_cnt = train_epoch( iter_cnt, [encoders, encoder_dst], [classifiers, classifier_dst, classifier_mix], critic, mats, [train_loaders, train_loader_dst, unl_loader, valid_loader], args, optim_model, epoch ) # thrs, metrics_val, src_weights_val = evaluate_cross( # encoder, classifiers, # mats, # [train_loaders, valid_loaders_src], # return_best_thrs=True, # args=args # ) # # _, metrics_test, src_weights_test = evaluate_cross( # encoder, classifiers, # mats, # [train_loaders, test_loaders_src], # return_best_thrs=False, # args=args, # thr=thrs # ) thr, metrics_val = evaluate( epoch, [encoders, encoder_dst], [classifiers, classifier_dst, classifier_mix], mats, [train_loaders, valid_loader], True, args ) # say("Dev accuracy/oracle: {:.4f}/{:.4f}\n".format(curr_dev, oracle_curr_dev)) _, metrics_test = evaluate( epoch, [encoders, encoder_dst], [classifiers, classifier_dst, classifier_mix], mats, [train_loaders, test_loader], False, args, thr=thr ) # say("Test accuracy/oracle: {:.4f}/{:.4f}\n".format(curr_test, oracle_curr_test)) # if curr_dev >= best_dev: # best_dev = curr_dev # best_test = curr_test # print(confusion_mat) # if args.save_model: # say(colored("Save model to {}\n".format(args.save_model + ".best"), 'red')) # torch.save([encoder, classifiers, Us, Ps, Ns], args.save_model + ".best") say("\n") say(colored("Best test accuracy {:.4f}\n".format(best_test), 'red')) def test_mahalanobis_metric(): p = torch.FloatTensor(1, 5).normal_() S = torch.FloatTensor(4, 5).normal_() p = Variable(p) # .cuda() S = Variable(S) # .cuda() print(p, S) encoder = nn.Sequential(nn.Linear(5, 5), nn.ReLU()) encoder = encoder # .cuda() nn.init.xavier_normal(encoder[0].weight) nn.init.constant(encoder[0].bias, 0.1) print(encoder[0].weight) d = mahalanobis_metric(p, S, args, encoder) print(d) # import argparse if __name__ == '__main__': random.seed(0) torch.manual_seed(0) if args.cuda: torch.cuda.manual_seed(0) print("eval only", args.eval_only) if args.eval_only: predict(args) else: train(args) writer.close()
[ "torch.nn.ReLU", "models.cnn.CNNMatchModel", "msda_src.model_utils.get_critic_class", "dataset.OAGDomainDataset", "torch.log_softmax", "torch.max", "torch.nn.init.xavier_normal", "sklearn.metrics.roc_auc_score", "torch.softmax", "torch.nn.MSELoss", "numpy.array", "msda_src.utils.op.softmax", ...
[((521, 543), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (536, 543), False, 'import sys, os, glob\n'), ((1064, 1097), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1087, 1097), False, 'import warnings\n'), ((1111, 1198), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Learning to Adapt from Multi-Source Domains"""'}), "(description=\n 'Learning to Adapt from Multi-Source Domains')\n", (1134, 1198), False, 'import argparse\n'), ((7751, 7800), 'torch.max', 'torch.max', (['mahalanobis_ratio1', 'mahalanobis_ratio2'], {}), '(mahalanobis_ratio1, mahalanobis_ratio2)\n', (7760, 7800), False, 'import torch\n'), ((8659, 8688), 'torch.gather', 'torch.gather', (['S', '(0)', 'neg_index'], {}), '(S, 0, neg_index)\n', (8671, 8688), False, 'import torch\n'), ((8701, 8730), 'torch.gather', 'torch.gather', (['S', '(0)', 'pos_index'], {}), '(S, 0, pos_index)\n', (8713, 8730), False, 'import torch\n'), ((8744, 8782), 'torch.mean', 'torch.mean', (['neg_S'], {'dim': '(0)', 'keepdim': '(True)'}), '(neg_S, dim=0, keepdim=True)\n', (8754, 8782), False, 'import torch\n'), ((8796, 8834), 'torch.mean', 'torch.mean', (['pos_S'], {'dim': '(0)', 'keepdim': '(True)'}), '(pos_S, dim=0, keepdim=True)\n', (8806, 8834), False, 'import torch\n'), ((9214, 9263), 'torch.max', 'torch.max', (['mahalanobis_ratio1', 'mahalanobis_ratio2'], {}), '(mahalanobis_ratio1, mahalanobis_ratio2)\n', (9223, 9263), False, 'import torch\n'), ((10188, 10222), 'torch.mean', 'torch.mean', (['S'], {'dim': '(0)', 'keepdim': '(True)'}), '(S, dim=0, keepdim=True)\n', (10198, 10222), False, 'import torch\n'), ((10829, 10852), 'copy.deepcopy', 'deepcopy', (['train_loaders'], {}), '(train_loaders)\n', (10837, 10852), False, 'from copy import copy, deepcopy\n'), ((10918, 10930), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {}), '()\n', (10928, 10930), True, 'import torch.nn as nn\n'), ((10951, 10963), 'torch.nn.NLLLoss', 'nn.NLLLoss', ([], {}), '()\n', (10961, 10963), True, 'import torch.nn as nn\n'), ((11013, 11025), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (11023, 11025), True, 'import torch.nn as nn\n'), ((22006, 22015), 'msda_src.utils.io.say', 'say', (['"""\n"""'], {}), "('\\n')\n", (22009, 22015), False, 'from msda_src.utils.io import say\n'), ((22231, 22269), 'torch.BoolTensor', 'torch.BoolTensor', (['([0] * label.shape[0])'], {}), '([0] * label.shape[0])\n', (22247, 22269), False, 'import torch\n'), ((27213, 27278), 'sklearn.metrics.precision_recall_fscore_support', 'precision_recall_fscore_support', (['y_true', 'y_pred'], {'average': '"""binary"""'}), "(y_true, y_pred, average='binary')\n", (27244, 27278), False, 'from sklearn.metrics import precision_recall_fscore_support\n'), ((27321, 27351), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_true', 'y_score'], {}), '(y_true, y_score)\n', (27334, 27351), False, 'from sklearn.metrics import roc_auc_score\n'), ((28803, 28825), 'numpy.zeros', 'np.zeros', ([], {'shape': '(4, 4)'}), '(shape=(4, 4))\n', (28811, 28825), True, 'import numpy as np\n'), ((34533, 34550), 'numpy.array', 'np.array', (['metrics'], {}), '(metrics)\n', (34541, 34550), True, 'import numpy as np\n'), ((34658, 34685), 'torch.load', 'torch.load', (['args.load_model'], {}), '(args.load_model)\n', (34668, 34685), False, 'import torch\n'), ((34980, 35045), 'msda_src.utils.io.say', 'say', (['("""\nTransferring from %s to %s\n""" % (args.train, args.test))'], {}), '("""\nTransferring from %s to %s\n""" % (args.train, args.test))\n', (34983, 35045), False, 'from msda_src.utils.io import say\n'), ((35506, 35560), 'os.path.join', 'os.path.join', (['DATA_DIR', "('%s_test.svmlight' % args.test)"], {}), "(DATA_DIR, '%s_test.svmlight' % args.test)\n", (35518, 35560), False, 'import sys, os, glob\n'), ((35582, 35610), 'msda_src.utils.io.AmazonDataset', 'AmazonDataset', (['test_filepath'], {}), '(test_filepath)\n', (35595, 35610), False, 'from msda_src.utils.io import AmazonDataset, AmazonDomainDataset\n'), ((35629, 35720), 'torch.utils.data.DataLoader', 'data.DataLoader', (['test_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(test_dataset, batch_size=args.batch_size, shuffle=False,\n num_workers=0)\n', (35644, 35720), True, 'import torch.utils.data as data\n'), ((35759, 35782), 'msda_src.utils.io.say', 'say', (['"""Corpus loaded.\n"""'], {}), "('Corpus loaded.\\n')\n", (35762, 35782), False, 'from msda_src.utils.io import say\n'), ((36389, 36430), 'msda_src.utils.io.say', 'say', (["('cuda is available %s\\n' % args.cuda)"], {}), "('cuda is available %s\\n' % args.cuda)\n", (36392, 36430), False, 'from msda_src.utils.io import say\n'), ((36436, 36461), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (36450, 36461), True, 'import numpy as np\n'), ((36466, 36512), 'torch.manual_seed', 'torch.manual_seed', (['(args.seed + args.seed_delta)'], {}), '(args.seed + args.seed_delta)\n', (36483, 36512), False, 'import torch\n'), ((37449, 37850), 'models.cnn.CNNMatchModel', 'CNNMatchModel', ([], {'input_matrix_size1': 'args.matrix_size1', 'input_matrix_size2': 'args.matrix_size2', 'mat1_channel1': 'args.mat1_channel1', 'mat1_kernel_size1': 'args.mat1_kernel_size1', 'mat1_channel2': 'args.mat1_channel2', 'mat1_kernel_size2': 'args.mat1_kernel_size2', 'mat1_hidden': 'args.mat1_hidden', 'mat2_channel1': 'args.mat2_channel1', 'mat2_kernel_size1': 'args.mat2_kernel_size1', 'mat2_hidden': 'args.mat2_hidden'}), '(input_matrix_size1=args.matrix_size1, input_matrix_size2=args\n .matrix_size2, mat1_channel1=args.mat1_channel1, mat1_kernel_size1=args\n .mat1_kernel_size1, mat1_channel2=args.mat1_channel2, mat1_kernel_size2\n =args.mat1_kernel_size2, mat1_hidden=args.mat1_hidden, mat2_channel1=\n args.mat2_channel1, mat2_kernel_size1=args.mat2_kernel_size1,\n mat2_hidden=args.mat2_hidden)\n', (37462, 37850), False, 'from models.cnn import CNNMatchModel\n'), ((37975, 38004), 'msda_src.model_utils.get_critic_class', 'get_critic_class', (['args.critic'], {}), '(args.critic)\n', (37991, 38004), False, 'from msda_src.model_utils import get_model_class, get_critic_class\n'), ((38083, 38092), 'msda_src.utils.io.say', 'say', (['args'], {}), '(args)\n', (38086, 38092), False, 'from msda_src.utils.io import say\n'), ((38251, 38312), 'msda_src.utils.io.say', 'say', (["('Transferring from %s to %s\\n' % (args.train, args.test))"], {}), "('Transferring from %s to %s\\n' % (args.train, args.test))\n", (38254, 38312), False, 'from msda_src.utils.io import say\n'), ((40641, 40669), 'os.path.exists', 'os.path.exists', (['unl_filepath'], {}), '(unl_filepath)\n', (40655, 40669), False, 'import sys, os, glob\n'), ((40769, 40805), 'dataset.OAGDomainDataset', 'OAGDomainDataset', (['args.test', '"""train"""'], {}), "(args.test, 'train')\n", (40785, 40805), False, 'from dataset import ProcessedCNNInputDataset, OAGDomainDataset\n'), ((40823, 40912), 'torch.utils.data.DataLoader', 'data.DataLoader', (['unl_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(True)', 'num_workers': '(0)'}), '(unl_dataset, batch_size=args.batch_size, shuffle=True,\n num_workers=0)\n', (40838, 40912), True, 'import torch.utils.data as data\n'), ((40972, 41016), 'dataset.ProcessedCNNInputDataset', 'ProcessedCNNInputDataset', (['args.test', '"""train"""'], {}), "(args.test, 'train')\n", (40996, 41016), False, 'from dataset import ProcessedCNNInputDataset, OAGDomainDataset\n'), ((41040, 41137), 'torch.utils.data.DataLoader', 'data.DataLoader', (['train_dataset_dst'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(train_dataset_dst, batch_size=args.batch_size, shuffle=\n False, num_workers=0)\n', (41055, 41137), True, 'import torch.utils.data as data\n'), ((41340, 41384), 'dataset.ProcessedCNNInputDataset', 'ProcessedCNNInputDataset', (['args.test', '"""valid"""'], {}), "(args.test, 'valid')\n", (41364, 41384), False, 'from dataset import ProcessedCNNInputDataset, OAGDomainDataset\n'), ((41462, 41554), 'torch.utils.data.DataLoader', 'data.DataLoader', (['valid_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(valid_dataset, batch_size=args.batch_size, shuffle=False,\n num_workers=0)\n', (41477, 41554), True, 'import torch.utils.data as data\n'), ((41783, 41826), 'dataset.ProcessedCNNInputDataset', 'ProcessedCNNInputDataset', (['args.test', '"""test"""'], {}), "(args.test, 'test')\n", (41807, 41826), False, 'from dataset import ProcessedCNNInputDataset, OAGDomainDataset\n'), ((41845, 41936), 'torch.utils.data.DataLoader', 'data.DataLoader', (['test_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(test_dataset, batch_size=args.batch_size, shuffle=False,\n num_workers=0)\n', (41860, 41936), True, 'import torch.utils.data as data\n'), ((41975, 41998), 'msda_src.utils.io.say', 'say', (['"""Corpus loaded.\n"""'], {}), "('Corpus loaded.\\n')\n", (41978, 41998), False, 'from msda_src.utils.io import say\n'), ((42353, 42384), 'torch.nn.Linear', 'nn.Linear', (['encoder_dst.n_out', '(2)'], {}), '(encoder_dst.n_out, 2)\n', (42362, 42384), True, 'import torch.nn as nn\n'), ((44261, 44302), 'msda_src.utils.io.say', 'say', (['"""Training will begin from scratch\n"""'], {}), "('Training will begin from scratch\\n')\n", (44264, 44302), False, 'from msda_src.utils.io import say\n'), ((46794, 46805), 'torch.autograd.Variable', 'Variable', (['p'], {}), '(p)\n', (46802, 46805), False, 'from torch.autograd import Variable\n'), ((46825, 46836), 'torch.autograd.Variable', 'Variable', (['S'], {}), '(S)\n', (46833, 46836), False, 'from torch.autograd import Variable\n'), ((46957, 46997), 'torch.nn.init.xavier_normal', 'nn.init.xavier_normal', (['encoder[0].weight'], {}), '(encoder[0].weight)\n', (46978, 46997), True, 'import torch.nn as nn\n'), ((47002, 47040), 'torch.nn.init.constant', 'nn.init.constant', (['encoder[0].bias', '(0.1)'], {}), '(encoder[0].bias, 0.1)\n', (47018, 47040), True, 'import torch.nn as nn\n'), ((47183, 47197), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (47194, 47197), False, 'import random\n'), ((47202, 47222), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (47219, 47222), False, 'import torch\n'), ((6191, 6206), 'torch.cat', 'torch.cat', (['S', '(0)'], {}), '(S, 0)\n', (6200, 6206), False, 'import torch\n'), ((6600, 6629), 'torch.gather', 'torch.gather', (['S', '(0)', 'pos_index'], {}), '(S, 0, pos_index)\n', (6612, 6629), False, 'import torch\n'), ((6646, 6675), 'torch.gather', 'torch.gather', (['S', '(0)', 'neg_index'], {}), '(S, 0, neg_index)\n', (6658, 6675), False, 'import torch\n'), ((6695, 6733), 'torch.mean', 'torch.mean', (['pos_S'], {'dim': '(0)', 'keepdim': '(True)'}), '(pos_S, dim=0, keepdim=True)\n', (6705, 6733), False, 'import torch\n'), ((6753, 6791), 'torch.mean', 'torch.mean', (['neg_S'], {'dim': '(0)', 'keepdim': '(True)'}), '(neg_S, dim=0, keepdim=True)\n', (6763, 6791), False, 'import torch\n'), ((6807, 6841), 'torch.mean', 'torch.mean', (['S'], {'dim': '(0)', 'keepdim': '(True)'}), '(S, dim=0, keepdim=True)\n', (6817, 6841), False, 'import torch\n'), ((13321, 13357), 'torch.softmax', 'torch.softmax', (['cur_output_dst'], {'dim': '(1)'}), '(cur_output_dst, dim=1)\n', (13334, 13357), False, 'import torch\n'), ((13383, 13412), 'torch.log', 'torch.log', (['cur_output_dst_mem'], {}), '(cur_output_dst_mem)\n', (13392, 13412), False, 'import torch\n'), ((16997, 17020), 'msda_src.utils.op.softmax', 'softmax', (['support_alphas'], {}), '(support_alphas)\n', (17004, 17020), False, 'from msda_src.utils.op import softmax\n'), ((17175, 17197), 'msda_src.utils.op.softmax', 'softmax', (['source_alphas'], {}), '(source_alphas)\n', (17182, 17197), False, 'from msda_src.utils.op import softmax\n'), ((17629, 17662), 'torch.stack', 'torch.stack', (['source_alphas'], {'dim': '(0)'}), '(source_alphas, dim=0)\n', (17640, 17662), False, 'import torch\n'), ((23456, 23472), 'torch.autograd.Variable', 'Variable', (['batch1'], {}), '(batch1)\n', (23464, 23472), False, 'from torch.autograd import Variable\n'), ((23490, 23506), 'torch.autograd.Variable', 'Variable', (['batch2'], {}), '(batch2)\n', (23498, 23506), False, 'from torch.autograd import Variable\n'), ((23701, 23737), 'torch.softmax', 'torch.softmax', (['cur_output_dst'], {'dim': '(1)'}), '(cur_output_dst, dim=1)\n', (23714, 23737), False, 'import torch\n'), ((23806, 23835), 'torch.log', 'torch.log', (['cur_output_dst_mem'], {}), '(cur_output_dst_mem)\n', (23815, 23835), False, 'import torch\n'), ((24597, 24612), 'msda_src.utils.op.softmax', 'softmax', (['alphas'], {}), '(alphas)\n', (24604, 24612), False, 'from msda_src.utils.op import softmax\n'), ((25345, 25378), 'torch.log_softmax', 'torch.log_softmax', (['outputs'], {'dim': '(1)'}), '(outputs, dim=1)\n', (25362, 25378), False, 'import torch\n'), ((25695, 25734), 'torch.nn.functional.nll_loss', 'F.nll_loss', (['outputs_upper_logits', 'label'], {}), '(outputs_upper_logits, label)\n', (25705, 25734), True, 'import torch.nn.functional as F\n'), ((27017, 27034), 'numpy.array', 'np.array', (['y_score'], {}), '(y_score)\n', (27025, 27034), True, 'import numpy as np\n'), ((27052, 27074), 'numpy.zeros_like', 'np.zeros_like', (['y_score'], {}), '(y_score)\n', (27065, 27074), True, 'import numpy as np\n'), ((27605, 27644), 'sklearn.metrics.precision_recall_curve', 'precision_recall_curve', (['y_true', 'y_score'], {}), '(y_true, y_score)\n', (27627, 27644), False, 'from sklearn.metrics import precision_recall_curve\n'), ((33045, 33085), 'numpy.mean', 'np.mean', (['cur_alpha_weights_stack'], {'axis': '(0)'}), '(cur_alpha_weights_stack, axis=0)\n', (33052, 33085), True, 'import numpy as np\n'), ((33736, 33801), 'sklearn.metrics.precision_recall_fscore_support', 'precision_recall_fscore_support', (['y_true', 'y_pred'], {'average': '"""binary"""'}), "(y_true, y_pred, average='binary')\n", (33767, 33801), False, 'from sklearn.metrics import precision_recall_fscore_support\n'), ((33816, 33846), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_true', 'y_score'], {}), '(y_true, y_score)\n', (33829, 33846), False, 'from sklearn.metrics import roc_auc_score\n'), ((35169, 35221), 'os.path.join', 'os.path.join', (['DATA_DIR', "('%s_train.svmlight' % source)"], {}), "(DATA_DIR, '%s_train.svmlight' % source)\n", (35181, 35221), False, 'import sys, os, glob\n'), ((35248, 35271), 'msda_src.utils.io.AmazonDataset', 'AmazonDataset', (['filepath'], {}), '(filepath)\n', (35261, 35271), False, 'from msda_src.utils.io import AmazonDataset, AmazonDomainDataset\n'), ((35295, 35387), 'torch.utils.data.DataLoader', 'data.DataLoader', (['train_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(train_dataset, batch_size=args.batch_size, shuffle=False,\n num_workers=0)\n', (35310, 35387), True, 'import torch.utils.data as data\n'), ((36359, 36384), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (36382, 36384), False, 'import torch\n'), ((36539, 36590), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['(args.seed + args.seed_delta)'], {}), '(args.seed + args.seed_delta)\n', (36561, 36590), False, 'import torch\n'), ((36814, 37215), 'models.cnn.CNNMatchModel', 'CNNMatchModel', ([], {'input_matrix_size1': 'args.matrix_size1', 'input_matrix_size2': 'args.matrix_size2', 'mat1_channel1': 'args.mat1_channel1', 'mat1_kernel_size1': 'args.mat1_kernel_size1', 'mat1_channel2': 'args.mat1_channel2', 'mat1_kernel_size2': 'args.mat1_kernel_size2', 'mat1_hidden': 'args.mat1_hidden', 'mat2_channel1': 'args.mat2_channel1', 'mat2_kernel_size1': 'args.mat2_kernel_size1', 'mat2_hidden': 'args.mat2_hidden'}), '(input_matrix_size1=args.matrix_size1, input_matrix_size2=args\n .matrix_size2, mat1_channel1=args.mat1_channel1, mat1_kernel_size1=args\n .mat1_kernel_size1, mat1_channel2=args.mat1_channel2, mat1_kernel_size2\n =args.mat1_kernel_size2, mat1_hidden=args.mat1_hidden, mat2_channel1=\n args.mat2_channel1, mat2_kernel_size1=args.mat2_kernel_size1,\n mat2_hidden=args.mat2_hidden)\n', (36827, 37215), False, 'from models.cnn import CNNMatchModel\n'), ((38684, 38708), 'os.path.exists', 'os.path.exists', (['filepath'], {}), '(filepath)\n', (38698, 38708), False, 'import sys, os, glob\n'), ((38784, 38825), 'dataset.ProcessedCNNInputDataset', 'ProcessedCNNInputDataset', (['source', '"""train"""'], {}), "(source, 'train')\n", (38808, 38825), False, 'from dataset import ProcessedCNNInputDataset, OAGDomainDataset\n'), ((38849, 38941), 'torch.utils.data.DataLoader', 'data.DataLoader', (['train_dataset'], {'batch_size': 'args.batch_size', 'shuffle': '(False)', 'num_workers': '(0)'}), '(train_dataset, batch_size=args.batch_size, shuffle=False,\n num_workers=0)\n', (38864, 38941), True, 'import torch.utils.data as data\n'), ((40102, 40128), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['U'], {}), '(U)\n', (40125, 40128), True, 'import torch.nn as nn\n'), ((40162, 40209), 'torch.FloatTensor', 'torch.FloatTensor', (['encoders[0].n_d', 'args.m_rank'], {}), '(encoders[0].n_d, args.m_rank)\n', (40179, 40209), False, 'import torch\n'), ((40218, 40244), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['P'], {}), '(P)\n', (40241, 40244), True, 'import torch.nn as nn\n'), ((40278, 40325), 'torch.FloatTensor', 'torch.FloatTensor', (['encoders[0].n_d', 'args.m_rank'], {}), '(encoders[0].n_d, args.m_rank)\n', (40295, 40325), False, 'import torch\n'), ((40334, 40360), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['N'], {}), '(N)\n', (40357, 40360), True, 'import torch.nn as nn\n'), ((42097, 42128), 'torch.nn.Linear', 'nn.Linear', (['encoders[0].n_out', '(2)'], {}), '(encoders[0].n_out, 2)\n', (42106, 42128), True, 'import torch.nn as nn\n'), ((46585, 46594), 'msda_src.utils.io.say', 'say', (['"""\n"""'], {}), "('\\n')\n", (46588, 46594), False, 'from msda_src.utils.io import say\n'), ((46892, 46907), 'torch.nn.Linear', 'nn.Linear', (['(5)', '(5)'], {}), '(5, 5)\n', (46901, 46907), True, 'import torch.nn as nn\n'), ((46909, 46918), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (46916, 46918), True, 'import torch.nn as nn\n'), ((47249, 47274), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['(0)'], {}), '(0)\n', (47271, 47274), False, 'import torch\n'), ((4947, 4960), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (4957, 4960), False, 'import torch\n'), ((5202, 5214), 'torch.log', 'torch.log', (['x'], {}), '(x)\n', (5211, 5214), False, 'import torch\n'), ((17515, 17548), 'torch.stack', 'torch.stack', (['source_labels'], {'dim': '(0)'}), '(source_labels, dim=0)\n', (17526, 17548), False, 'import torch\n'), ((18997, 19032), 'torch.log_softmax', 'torch.log_softmax', (['upper_out'], {'dim': '(1)'}), '(upper_out, dim=1)\n', (19014, 19032), False, 'import torch\n'), ((24709, 24724), 'torch.autograd.Variable', 'Variable', (['alpha'], {}), '(alpha)\n', (24717, 24724), False, 'from torch.autograd import Variable\n'), ((27810, 27824), 'numpy.argmax', 'np.argmax', (['f1s'], {}), '(f1s)\n', (27819, 27824), True, 'import numpy as np\n'), ((29752, 29768), 'torch.autograd.Variable', 'Variable', (['batch1'], {}), '(batch1)\n', (29760, 29768), False, 'from torch.autograd import Variable\n'), ((29790, 29806), 'torch.autograd.Variable', 'Variable', (['batch2'], {}), '(batch2)\n', (29798, 29806), False, 'from torch.autograd import Variable\n'), ((30355, 30370), 'msda_src.utils.op.softmax', 'softmax', (['alphas'], {}), '(alphas)\n', (30362, 30370), False, 'from msda_src.utils.op import softmax\n'), ((33192, 33209), 'numpy.array', 'np.array', (['y_score'], {}), '(y_score)\n', (33200, 33209), True, 'import numpy as np\n'), ((33231, 33253), 'numpy.zeros_like', 'np.zeros_like', (['y_score'], {}), '(y_score)\n', (33244, 33253), True, 'import numpy as np\n'), ((34105, 34144), 'sklearn.metrics.precision_recall_curve', 'precision_recall_curve', (['y_true', 'y_score'], {}), '(y_true, y_score)\n', (34127, 34144), False, 'from sklearn.metrics import precision_recall_curve\n'), ((39729, 39780), 'torch.FloatTensor', 'torch.FloatTensor', (['encoders[0].n_d', 'encoders[0].n_d'], {}), '(encoders[0].n_d, encoders[0].n_d)\n', (39746, 39780), False, 'import torch\n'), ((39797, 39834), 'torch.FloatTensor', 'torch.FloatTensor', (['encoders[0].n_d', '(1)'], {}), '(encoders[0].n_d, 1)\n', (39814, 39834), False, 'import torch\n'), ((39847, 39872), 'torch.nn.init.xavier_uniform', 'nn.init.xavier_uniform', (['W'], {}), '(W)\n', (39869, 39872), True, 'import torch.nn as nn\n'), ((39914, 39951), 'torch.FloatTensor', 'torch.FloatTensor', (['encoders[0].n_d', '(1)'], {}), '(encoders[0].n_d, 1)\n', (39931, 39951), False, 'import torch\n'), ((39964, 39989), 'torch.nn.init.xavier_uniform', 'nn.init.xavier_uniform', (['V'], {}), '(V)\n', (39986, 39989), True, 'import torch.nn as nn\n'), ((40045, 40092), 'torch.FloatTensor', 'torch.FloatTensor', (['encoders[0].n_d', 'args.m_rank'], {}), '(encoders[0].n_d, args.m_rank)\n', (40062, 40092), False, 'import torch\n'), ((46710, 46733), 'torch.FloatTensor', 'torch.FloatTensor', (['(1)', '(5)'], {}), '(1, 5)\n', (46727, 46733), False, 'import torch\n'), ((46752, 46775), 'torch.FloatTensor', 'torch.FloatTensor', (['(4)', '(5)'], {}), '(4, 5)\n', (46769, 46775), False, 'import torch\n'), ((5391, 5410), 'torch.norm', 'torch.norm', (['x', '(1)', '(1)'], {}), '(x, 1, 1)\n', (5401, 5410), False, 'import torch\n'), ((6123, 6156), 'torch.cat', 'torch.cat', (['(labels, label)'], {'dim': '(0)'}), '((labels, label), dim=0)\n', (6132, 6156), False, 'import torch\n'), ((14264, 14296), 'torch.log_softmax', 'torch.log_softmax', (['output'], {'dim': '(1)'}), '(output, dim=1)\n', (14281, 14296), False, 'import torch\n'), ((14804, 14855), 'torch.cat', 'torch.cat', (['[1 - unl_critic_label, unl_critic_label]'], {}), '([1 - unl_critic_label, unl_critic_label])\n', (14813, 14855), False, 'import torch\n'), ((18628, 18651), 'torch.log', 'torch.log', (['output_moe_i'], {}), '(output_moe_i)\n', (18637, 18651), False, 'import torch\n'), ((27737, 27750), 'numpy.isnan', 'np.isnan', (['f1s'], {}), '(f1s)\n', (27745, 27750), True, 'import numpy as np\n'), ((27771, 27784), 'numpy.isnan', 'np.isnan', (['f1s'], {}), '(f1s)\n', (27779, 27784), True, 'import numpy as np\n'), ((27892, 27903), 'numpy.max', 'np.max', (['f1s'], {}), '(f1s)\n', (27898, 27903), True, 'import numpy as np\n'), ((31289, 31304), 'torch.autograd.Variable', 'Variable', (['alpha'], {}), '(alpha)\n', (31297, 31304), False, 'from torch.autograd import Variable\n'), ((32216, 32225), 'msda_src.utils.io.say', 'say', (['"""\n"""'], {}), "('\\n')\n", (32219, 32225), False, 'from msda_src.utils.io import say\n'), ((34330, 34344), 'numpy.argmax', 'np.argmax', (['f1s'], {}), '(f1s)\n', (34339, 34344), True, 'import numpy as np\n'), ((34405, 34416), 'numpy.max', 'np.max', (['f1s'], {}), '(f1s)\n', (34411, 34416), True, 'import numpy as np\n'), ((15590, 15612), 'torch.FloatTensor', 'torch.FloatTensor', (['[0]'], {}), '([0])\n', (15607, 15612), False, 'import torch\n'), ((18203, 18245), 'torch.nn.functional.softmax', 'F.softmax', (['outputs_dst_transfer[id]'], {'dim': '(1)'}), '(outputs_dst_transfer[id], dim=1)\n', (18212, 18245), True, 'import torch.nn.functional as F\n'), ((34249, 34262), 'numpy.isnan', 'np.isnan', (['f1s'], {}), '(f1s)\n', (34257, 34262), True, 'import numpy as np\n'), ((34287, 34300), 'numpy.isnan', 'np.isnan', (['f1s'], {}), '(f1s)\n', (34295, 34300), True, 'import numpy as np\n'), ((32083, 32102), 'termcolor.colored', 'colored', (['"""F"""', '"""red"""'], {}), "('F', 'red')\n", (32090, 32102), False, 'from termcolor import colored, cprint\n')]
"""ILI9341 demo (color palette).""" from time import sleep from ili9341 import Display, color565 from machine import Pin, SPI def hsv_to_rgb(h, s, v): """ Convert HSV to RGB (based on colorsys.py). Args: h (float): Hue 0 to 1. s (float): Saturation 0 to 1. v (float): Value 0 to 1 (Brightness). """ if s == 0.0: return v, v, v i = int(h * 6.0) f = (h * 6.0) - i p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) i = i % 6 v = int(v * 255) t = int(t * 255) p = int(p * 255) q = int(q * 255) if i == 0: return v, t, p if i == 1: return q, v, p if i == 2: return p, v, t if i == 3: return p, q, v if i == 4: return t, p, v if i == 5: return v, p, q def test(): """Test code.""" # Baud rate of 40000000 seems about the max spi = SPI(1, baudrate=40000000, sck=Pin(14), mosi=Pin(13)) display = Display(spi, dc=Pin(4), cs=Pin(16), rst=Pin(17)) c = 0 for x in range(0, 240, 20): for y in range(0, 320, 20): color = color565(*hsv_to_rgb(c / 192, 1, 1)) display.fill_circle(x + 9, y + 9, 9, color) c += 1 sleep(9) display.cleanup() test()
[ "machine.Pin", "time.sleep" ]
[((1275, 1283), 'time.sleep', 'sleep', (['(9)'], {}), '(9)\n', (1280, 1283), False, 'from time import sleep\n'), ((974, 981), 'machine.Pin', 'Pin', (['(14)'], {}), '(14)\n', (977, 981), False, 'from machine import Pin, SPI\n'), ((988, 995), 'machine.Pin', 'Pin', (['(13)'], {}), '(13)\n', (991, 995), False, 'from machine import Pin, SPI\n'), ((1027, 1033), 'machine.Pin', 'Pin', (['(4)'], {}), '(4)\n', (1030, 1033), False, 'from machine import Pin, SPI\n'), ((1038, 1045), 'machine.Pin', 'Pin', (['(16)'], {}), '(16)\n', (1041, 1045), False, 'from machine import Pin, SPI\n'), ((1051, 1058), 'machine.Pin', 'Pin', (['(17)'], {}), '(17)\n', (1054, 1058), False, 'from machine import Pin, SPI\n')]
# Copyright 2018 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. # ============================================================================== """Input-pipeline utilities for Distribution strategies.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.data.ops import readers from tensorflow.python.data.util import nest from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import tf_logging # TODO(priyag): Any other reader datasets to consider here? _READER_DATASET_OPS = [ "TextLineDataset", "TFRecordDataset", "FixedLengthRecordDataset" ] # pylint: disable=protected-access def auto_shard_dataset(dataset, num_shards, index): """Shard the input pipeline by sharding the underlying list of files. Args: dataset: A `tf.data.Dataset` instance, typically the result of a bunch of dataset transformations. num_shards: A `tf.int64` scalar `tf.Tensor`, representing the number of shards operating in parallel. Same usage as in `Dataset.shard`. index: A `tf.int64` scalar `tf.Tensor`, representing the worker index. Same usage as in `Dataset.shard`. Returns: A modified `Dataset` obtained by updating the pipeline sharded by the files. The input dataset will be returned if we cannot automatically determine a good way to shard the input dataset. """ # TODO(priyag): Clone datasets instead of updating in place, similar to the # clone method for TFRecordDataset. def _auto_shard_impl(dataset, found_reader_op): """Recursive implementation of auto sharding.""" if not found_reader_op: # TODO(priyag): Make this check more robust by enforcing some common # property on reader datasets. if (isinstance(dataset, readers.TextLineDataset) or isinstance(dataset, readers.FixedLengthRecordDataset)): filenames_tensor = dataset._filenames num_files = array_ops.size(filenames_tensor) sharded_filenames_tensor = array_ops.gather( filenames_tensor, math_ops.range(index, num_files, num_shards)) dataset._filenames = sharded_filenames_tensor return dataset elif isinstance(dataset, readers.TFRecordDataset): # `TFRecordDataset` needs to be handled separately than other readers # because it converts filenames to a dataset first. Also, we clone it # instead of updating in place because it has special logic in the # constructor. Eventually we will change all cases to clone datasets # instead of updating in-place. return dataset._clone( filenames=dataset._filenames.shard(num_shards, index)) elif hasattr(dataset, "_map_func"): # TODO(priyag): Make this check more robust by enforcing some common # property on all map/flatmap/interleave datasets. map_func_def = dataset._map_func.definition for node in map_func_def.node_def: if node.op in _READER_DATASET_OPS: found_reader_op = True break elif node.op == "FlatMapDataset": # TODO(priyag): Should this check for other map datasets? Should it # be recursive? It is too specific to implementation of # TFRecordDataset right now. nested_func_name = node.attr["f"].func.name nested_func = ops.get_default_graph()._functions[nested_func_name] for nested_node in nested_func.definition.node_def: if nested_node.op in _READER_DATASET_OPS: found_reader_op = True break if found_reader_op: break if found_reader_op: dataset._input_dataset = _auto_shard_impl( dataset._input_dataset, found_reader_op) return dataset # TODO(priyag): Make _input_dataset(s) a common property of all datasets to # make this check more robust. if hasattr(dataset, "_input_dataset"): dataset._input_dataset = _auto_shard_impl( dataset._input_dataset, found_reader_op) if hasattr(dataset, "_dataset_to_concatenate"): # Special case for `ConcatentateDataset`. We want to shard all input # datasets. dataset._dataset_to_concatenate = _auto_shard_impl( dataset._dataset_to_concatenate, found_reader_op) return dataset if hasattr(dataset, "_datasets"): # Special case for `ZipDataset`. dataset._datasets = nest.pack_sequence_as(dataset._datasets, [ _auto_shard_impl(ds, found_reader_op) for ds in nest.flatten(dataset._datasets) ]) return dataset if not found_reader_op: tf_logging.warn( "Could not find a standard reader in the input pipeline" "(one of TextLineDataset, TFRecordDataset, FixedLengthRecordDataset)." "So auto-sharding is not done. Please verify correctness of " "auto-sharding for your input.") # TODO(yuefengz): maybe still shard it? return dataset # TODO(priyag): What do we want to do if the number of filenames is # uneven in the number of shards? By default, this will just return as # many items it can before throwing OutOfRangeError. # TODO(priyag): This will shard the filenames before any shuffling of the # filename dataset. It might be desirable to shard after shuffling # filenames? If so, how do we achieve that? return dataset.shard(num_shards, index) return _auto_shard_impl(dataset=dataset, found_reader_op=False)
[ "tensorflow.python.ops.array_ops.size", "tensorflow.python.platform.tf_logging.warn", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.ops.math_ops.range", "tensorflow.python.data.util.nest.flatten" ]
[((5471, 5710), 'tensorflow.python.platform.tf_logging.warn', 'tf_logging.warn', (['"""Could not find a standard reader in the input pipeline(one of TextLineDataset, TFRecordDataset, FixedLengthRecordDataset).So auto-sharding is not done. Please verify correctness of auto-sharding for your input."""'], {}), "(\n 'Could not find a standard reader in the input pipeline(one of TextLineDataset, TFRecordDataset, FixedLengthRecordDataset).So auto-sharding is not done. Please verify correctness of auto-sharding for your input.'\n )\n", (5486, 5710), False, 'from tensorflow.python.platform import tf_logging\n'), ((2672, 2704), 'tensorflow.python.ops.array_ops.size', 'array_ops.size', (['filenames_tensor'], {}), '(filenames_tensor)\n', (2686, 2704), False, 'from tensorflow.python.ops import array_ops\n'), ((2790, 2834), 'tensorflow.python.ops.math_ops.range', 'math_ops.range', (['index', 'num_files', 'num_shards'], {}), '(index, num_files, num_shards)\n', (2804, 2834), False, 'from tensorflow.python.ops import math_ops\n'), ((5369, 5400), 'tensorflow.python.data.util.nest.flatten', 'nest.flatten', (['dataset._datasets'], {}), '(dataset._datasets)\n', (5381, 5400), False, 'from tensorflow.python.data.util import nest\n'), ((4126, 4149), 'tensorflow.python.framework.ops.get_default_graph', 'ops.get_default_graph', ([], {}), '()\n', (4147, 4149), False, 'from tensorflow.python.framework import ops\n')]
''' # something wrong with the logging/the way to write as a ''' import os import re import time import numpy as np import matplotlib.pyplot as plt import argparse # original settings ... parser = argparse.ArgumentParser() parser.add_argument('--file_name', type = str, default = 0, help = 'The name of txt log file. ' ) parser.add_argument('--train_loss', type = bool, default = True, help = 'Whether draw the training loss plot') parser.add_argument('--test_loss', type = bool, default = True, help = 'Whether draw the test_loss plot') parser.add_argument('--train_acc', type = bool, default = True, help = 'Whether draw the train_acc plot') parser.add_argument('--test_acc', type = bool, default = True, help = 'Whether draw the test_acc plot') args = parser.parse_args() txt_file = os.path.join( os.getcwd(), 'logs', '{}.txt'.format( args.file_name) ) save_path = os.path.join( os.getcwd(), 'plot_figures') def plot(value_lists, value_names, save_path): fig, ax = plt.subplots() ax.set_title('Training_Curve') plt.xlabel('iteration/episode_number') ax.set_ylabel('loss value') plt.axis( [0, 10000, 0, 2.5] ) # order: min(x), max(x), min(y), max(y) ... # the number of max(x) print (value_names) for value_list in value_lists: print ("The length of value_list is {}".format( len(value_list) ) ) if 'inner_train_loss' in value_names: inner_iter_list = range( 0, len(value_lists[0]) ) inner_iter_list = [ i*2 for i in inner_iter_list] inner_loss_id = value_names.index('inner_train_loss') print ("The length of inner_loss is {}; inner_loss_iter_length is {}".format( len(value_lists[inner_loss_id]), len(inner_iter_list) )) value_list = value_lists[inner_loss_id] ax.plot(inner_iter_list, value_list, 'g+', label = 'inner_train_loss') if 'inner_train_acc' in value_names or 'outer_train_acc' in value_names: ax_2 = ax.twinx() ax_2.set_ylabel('acc') if 'inner_train_acc' in value_names: inner_acc_id = value_names.index('inner_train_acc') value_list = value_lists[inner_acc_id] print ("The length of train_acc is {}; train_acc_iter_length is {}".format( len(value_lists[inner_acc_id]), len(inner_iter_list) )) ax_2.plot(inner_iter_list, value_list, 'y+', linewidth=10, alpha=0.7, label = 'inner_train_acc') else: print("There is no train_acc detected ... ") if 'outer_train_acc' in value_names: # if we have test loss then we have test_acc outer_acc_id = value_names.index('outer_train_acc') value_list = value_lists[outer_acc_id] outer_iter_list = range(1, len(value_list)+1 ) outer_iter_list = [ i*16 for i in outer_iter_list] # modification needed here ... print ("The length of outer_acc is {}; outer_acc_iter_length is {}".format( len(value_lists[outer_acc_id]), len(outer_iter_list) )) ax_2.plot(outer_iter_list, value_list, 'r*', linewidth=10, alpha=0.7, label = 'outer_train_acc' ) else: print("There is no test_acc detected ... ") if 'outer_train_loss' in value_names: outer_loss_id = value_names.index('outer_train_loss') value_list = value_lists[outer_loss_id] print ("The length of outer_loss is {}; outer_loss_iter_length is {}".format( len(value_lists[outer_loss_id]), len(outer_iter_list) )) ax.plot( outer_iter_list, value_list, 'b*', label = 'outer_train_loss' ) else: print("There is no test_loss detected ... ") ax.legend(loc='upper left') ax_2.legend(loc='upper right') ax.yaxis.label.set_color('blue') ax_2.spines['left'].set_color('blue') ax_2.yaxis.label.set_color('red') ax_2.spines['right'].set_color('red') plt.show() plt.savefig(save_path + '/' + args.file_name + '.jpg') def get_value_list(txt_file, re_exp): # here, we use re to match all contents from global context ... value_list = re.findall(txt_file, re_exp) return value_list ''' in this case, all the stats are about the ''' def filter_out(value_list, step = 16): length = len(value_list) new_value_list = [ value_list[idx] for idx in range(0,length, step) ] return new_value_list def main(save_path): fig_suffix = args.file_name # use the same name as logging file ... txt_contents = open(txt_file, 'r').read() # wait for further notice ... value_names = [] value_lists = [] if args.train_loss == True: value_names.append('inner_train_loss') re_exp = r'inner_loss: (.*?),' train_loss = get_value_list(re_exp, txt_contents) print (len(train_loss)) train_loss = [ float(i) for i in train_loss ] train_loss = filter_out(train_loss) value_lists.append(train_loss) if args.test_loss == True: re_exp = r'outer_loss: (.*?),' test_loss = get_value_list(re_exp, txt_contents) value_names.append('outer_train_loss') test_loss = [ float(i) for i in test_loss ] test_loss = filter_out(test_loss) value_lists.append(test_loss) if args.train_acc == True: re_exp = r'inner_train_acc: (.*?),' train_acc = get_value_list(re_exp, txt_contents) # print (train_acc) # there are normal training values ... value_names.append('inner_train_acc') train_acc = [ float(i) for i in train_acc ] train_acc = filter_out(train_acc) value_lists.append(train_acc) if args.test_acc == True: # here the re match has some problems ... re_exp = r'outer_acc: (.*?),' test_acc = get_value_list(re_exp, txt_contents) # print (test_acc) value_names.append('outer_train_acc') test_acc = [ float(i) for i in test_acc ] test_acc = filter_out(test_acc) value_lists.append(test_acc) plot(value_lists, value_names , save_path) # draw those training&test stats together ... if __name__ == "__main__": main( save_path )
[ "matplotlib.pyplot.savefig", "argparse.ArgumentParser", "matplotlib.pyplot.xlabel", "os.getcwd", "matplotlib.pyplot.axis", "re.findall", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((203, 228), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (226, 228), False, 'import argparse\n'), ((807, 818), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (816, 818), False, 'import os\n'), ((889, 900), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (898, 900), False, 'import os\n'), ((982, 996), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (994, 996), True, 'import matplotlib.pyplot as plt\n'), ((1036, 1074), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iteration/episode_number"""'], {}), "('iteration/episode_number')\n", (1046, 1074), True, 'import matplotlib.pyplot as plt\n'), ((1112, 1140), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, 10000, 0, 2.5]'], {}), '([0, 10000, 0, 2.5])\n', (1120, 1140), True, 'import matplotlib.pyplot as plt\n'), ((3762, 3772), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3770, 3772), True, 'import matplotlib.pyplot as plt\n'), ((3777, 3831), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(save_path + '/' + args.file_name + '.jpg')"], {}), "(save_path + '/' + args.file_name + '.jpg')\n", (3788, 3831), True, 'import matplotlib.pyplot as plt\n'), ((3959, 3987), 're.findall', 're.findall', (['txt_file', 're_exp'], {}), '(txt_file, re_exp)\n', (3969, 3987), False, 'import re\n')]
import logging from PIL import Image import os import torch from torchvision import transforms from torch.utils.data import DataLoader, RandomSampler, DistributedSampler, SequentialSampler from .dataset import CUB, CarsDataset, NABirds, dogs, INat2017, emptyJudge from .autoaugment import AutoAugImageNetPolicy logger = logging.getLogger(__name__) def get_loader(args): if args.local_rank not in [-1, 0]: torch.distributed.barrier() if args.dataset == 'CUB_200_2011': train_transform=transforms.Compose([transforms.Resize((600, 600), Image.BILINEAR), transforms.RandomCrop((448, 448)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) test_transform=transforms.Compose([transforms.Resize((600, 600), Image.BILINEAR), transforms.CenterCrop((448, 448)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) trainset = CUB(root=args.data_root, is_train=True, transform=train_transform) testset = CUB(root=args.data_root, is_train=False, transform=test_transform) elif args.dataset == 'car': trainset = CarsDataset(os.path.join(args.data_root,'devkit/cars_train_annos.mat'), os.path.join(args.data_root,'cars_train'), os.path.join(args.data_root,'devkit/cars_meta.mat'), # cleaned=os.path.join(data_dir,'cleaned.dat'), transform=transforms.Compose([ transforms.Resize((600, 600), Image.BILINEAR), transforms.RandomCrop((448, 448)), transforms.RandomHorizontalFlip(), AutoAugImageNetPolicy(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) ) testset = CarsDataset(os.path.join(args.data_root,'cars_test_annos_withlabels.mat'), os.path.join(args.data_root,'cars_test'), os.path.join(args.data_root,'devkit/cars_meta.mat'), # cleaned=os.path.join(data_dir,'cleaned_test.dat'), transform=transforms.Compose([ transforms.Resize((600, 600), Image.BILINEAR), transforms.CenterCrop((448, 448)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) ) elif args.dataset == 'dog': train_transform=transforms.Compose([transforms.Resize((600, 600), Image.BILINEAR), transforms.RandomCrop((448, 448)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) test_transform=transforms.Compose([transforms.Resize((600, 600), Image.BILINEAR), transforms.CenterCrop((448, 448)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) trainset = dogs(root=args.data_root, train=True, cropped=False, transform=train_transform, download=False ) testset = dogs(root=args.data_root, train=False, cropped=False, transform=test_transform, download=False ) elif args.dataset == 'nabirds': train_transform=transforms.Compose([transforms.Resize((600, 600), Image.BILINEAR), transforms.RandomCrop((448, 448)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) test_transform=transforms.Compose([transforms.Resize((600, 600), Image.BILINEAR), transforms.CenterCrop((448, 448)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) trainset = NABirds(root=args.data_root, train=True, transform=train_transform) testset = NABirds(root=args.data_root, train=False, transform=test_transform) elif args.dataset == 'INat2017': train_transform=transforms.Compose([transforms.Resize((400, 400), Image.BILINEAR), transforms.RandomCrop((304, 304)), transforms.RandomHorizontalFlip(), AutoAugImageNetPolicy(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) test_transform=transforms.Compose([transforms.Resize((400, 400), Image.BILINEAR), transforms.CenterCrop((304, 304)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) trainset = INat2017(args.data_root, 'train', train_transform) testset = INat2017(args.data_root, 'val', test_transform) elif args.dataset == 'emptyJudge5' or args.dataset == 'emptyJudge4': train_transform = transforms.Compose([transforms.Resize((600, 600), Image.BILINEAR), transforms.RandomCrop((448, 448)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # test_transform = transforms.Compose([transforms.Resize((600, 600), Image.BILINEAR), # transforms.CenterCrop((448, 448)), # transforms.ToTensor(), # transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) test_transform = transforms.Compose([transforms.Resize((448, 448), Image.BILINEAR), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) trainset = emptyJudge(root=args.data_root, is_train=True, transform=train_transform) testset = emptyJudge(root=args.data_root, is_train=False, transform=test_transform) if args.local_rank == 0: torch.distributed.barrier() train_sampler = RandomSampler(trainset) if args.local_rank == -1 else DistributedSampler(trainset) test_sampler = SequentialSampler(testset) if args.local_rank == -1 else DistributedSampler(testset) train_loader = DataLoader(trainset, sampler=train_sampler, batch_size=args.train_batch_size, num_workers=4, drop_last=True, pin_memory=True) test_loader = DataLoader(testset, sampler=test_sampler, batch_size=args.eval_batch_size, num_workers=4, pin_memory=True) if testset is not None else None return train_loader, test_loader
[ "logging.getLogger", "torch.utils.data.DistributedSampler", "torch.distributed.barrier", "torchvision.transforms.CenterCrop", "torch.utils.data.SequentialSampler", "torchvision.transforms.RandomHorizontalFlip", "torch.utils.data.RandomSampler", "os.path.join", "torchvision.transforms.RandomCrop", ...
[((324, 351), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (341, 351), False, 'import logging\n'), ((7767, 7897), 'torch.utils.data.DataLoader', 'DataLoader', (['trainset'], {'sampler': 'train_sampler', 'batch_size': 'args.train_batch_size', 'num_workers': '(4)', 'drop_last': '(True)', 'pin_memory': '(True)'}), '(trainset, sampler=train_sampler, batch_size=args.\n train_batch_size, num_workers=4, drop_last=True, pin_memory=True)\n', (7777, 7897), False, 'from torch.utils.data import DataLoader, RandomSampler, DistributedSampler, SequentialSampler\n'), ((423, 450), 'torch.distributed.barrier', 'torch.distributed.barrier', ([], {}), '()\n', (448, 450), False, 'import torch\n'), ((7512, 7539), 'torch.distributed.barrier', 'torch.distributed.barrier', ([], {}), '()\n', (7537, 7539), False, 'import torch\n'), ((7561, 7584), 'torch.utils.data.RandomSampler', 'RandomSampler', (['trainset'], {}), '(trainset)\n', (7574, 7584), False, 'from torch.utils.data import DataLoader, RandomSampler, DistributedSampler, SequentialSampler\n'), ((7615, 7643), 'torch.utils.data.DistributedSampler', 'DistributedSampler', (['trainset'], {}), '(trainset)\n', (7633, 7643), False, 'from torch.utils.data import DataLoader, RandomSampler, DistributedSampler, SequentialSampler\n'), ((7663, 7689), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['testset'], {}), '(testset)\n', (7680, 7689), False, 'from torch.utils.data import DataLoader, RandomSampler, DistributedSampler, SequentialSampler\n'), ((7720, 7747), 'torch.utils.data.DistributedSampler', 'DistributedSampler', (['testset'], {}), '(testset)\n', (7738, 7747), False, 'from torch.utils.data import DataLoader, RandomSampler, DistributedSampler, SequentialSampler\n'), ((8061, 8171), 'torch.utils.data.DataLoader', 'DataLoader', (['testset'], {'sampler': 'test_sampler', 'batch_size': 'args.eval_batch_size', 'num_workers': '(4)', 'pin_memory': '(True)'}), '(testset, sampler=test_sampler, batch_size=args.eval_batch_size,\n num_workers=4, pin_memory=True)\n', (8071, 8171), False, 'from torch.utils.data import DataLoader, RandomSampler, DistributedSampler, SequentialSampler\n'), ((535, 580), 'torchvision.transforms.Resize', 'transforms.Resize', (['(600, 600)', 'Image.BILINEAR'], {}), '((600, 600), Image.BILINEAR)\n', (552, 580), False, 'from torchvision import transforms\n'), ((618, 651), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['(448, 448)'], {}), '((448, 448))\n', (639, 651), False, 'from torchvision import transforms\n'), ((689, 722), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (720, 722), False, 'from torchvision import transforms\n'), ((760, 781), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (779, 781), False, 'from torchvision import transforms\n'), ((819, 885), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (839, 885), False, 'from torchvision import transforms\n'), ((931, 976), 'torchvision.transforms.Resize', 'transforms.Resize', (['(600, 600)', 'Image.BILINEAR'], {}), '((600, 600), Image.BILINEAR)\n', (948, 976), False, 'from torchvision import transforms\n'), ((1014, 1047), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(448, 448)'], {}), '((448, 448))\n', (1035, 1047), False, 'from torchvision import transforms\n'), ((1085, 1106), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1104, 1106), False, 'from torchvision import transforms\n'), ((1144, 1210), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (1164, 1210), False, 'from torchvision import transforms\n'), ((1447, 1506), 'os.path.join', 'os.path.join', (['args.data_root', '"""devkit/cars_train_annos.mat"""'], {}), "(args.data_root, 'devkit/cars_train_annos.mat')\n", (1459, 1506), False, 'import os\n'), ((1535, 1577), 'os.path.join', 'os.path.join', (['args.data_root', '"""cars_train"""'], {}), "(args.data_root, 'cars_train')\n", (1547, 1577), False, 'import os\n'), ((1606, 1658), 'os.path.join', 'os.path.join', (['args.data_root', '"""devkit/cars_meta.mat"""'], {}), "(args.data_root, 'devkit/cars_meta.mat')\n", (1618, 1658), False, 'import os\n'), ((2304, 2366), 'os.path.join', 'os.path.join', (['args.data_root', '"""cars_test_annos_withlabels.mat"""'], {}), "(args.data_root, 'cars_test_annos_withlabels.mat')\n", (2316, 2366), False, 'import os\n'), ((2395, 2436), 'os.path.join', 'os.path.join', (['args.data_root', '"""cars_test"""'], {}), "(args.data_root, 'cars_test')\n", (2407, 2436), False, 'import os\n'), ((2465, 2517), 'os.path.join', 'os.path.join', (['args.data_root', '"""devkit/cars_meta.mat"""'], {}), "(args.data_root, 'devkit/cars_meta.mat')\n", (2477, 2517), False, 'import os\n'), ((3082, 3127), 'torchvision.transforms.Resize', 'transforms.Resize', (['(600, 600)', 'Image.BILINEAR'], {}), '((600, 600), Image.BILINEAR)\n', (3099, 3127), False, 'from torchvision import transforms\n'), ((3165, 3198), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['(448, 448)'], {}), '((448, 448))\n', (3186, 3198), False, 'from torchvision import transforms\n'), ((3236, 3269), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (3267, 3269), False, 'from torchvision import transforms\n'), ((3307, 3328), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3326, 3328), False, 'from torchvision import transforms\n'), ((3366, 3432), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (3386, 3432), False, 'from torchvision import transforms\n'), ((3478, 3523), 'torchvision.transforms.Resize', 'transforms.Resize', (['(600, 600)', 'Image.BILINEAR'], {}), '((600, 600), Image.BILINEAR)\n', (3495, 3523), False, 'from torchvision import transforms\n'), ((3561, 3594), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(448, 448)'], {}), '((448, 448))\n', (3582, 3594), False, 'from torchvision import transforms\n'), ((3632, 3653), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3651, 3653), False, 'from torchvision import transforms\n'), ((3691, 3757), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (3711, 3757), False, 'from torchvision import transforms\n'), ((1830, 1875), 'torchvision.transforms.Resize', 'transforms.Resize', (['(600, 600)', 'Image.BILINEAR'], {}), '((600, 600), Image.BILINEAR)\n', (1847, 1875), False, 'from torchvision import transforms\n'), ((1913, 1946), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['(448, 448)'], {}), '((448, 448))\n', (1934, 1946), False, 'from torchvision import transforms\n'), ((1984, 2017), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (2015, 2017), False, 'from torchvision import transforms\n'), ((2116, 2137), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2135, 2137), False, 'from torchvision import transforms\n'), ((2175, 2241), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (2195, 2241), False, 'from torchvision import transforms\n'), ((2694, 2739), 'torchvision.transforms.Resize', 'transforms.Resize', (['(600, 600)', 'Image.BILINEAR'], {}), '((600, 600), Image.BILINEAR)\n', (2711, 2739), False, 'from torchvision import transforms\n'), ((2777, 2810), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(448, 448)'], {}), '((448, 448))\n', (2798, 2810), False, 'from torchvision import transforms\n'), ((2848, 2869), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2867, 2869), False, 'from torchvision import transforms\n'), ((2907, 2973), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (2927, 2973), False, 'from torchvision import transforms\n'), ((4391, 4436), 'torchvision.transforms.Resize', 'transforms.Resize', (['(600, 600)', 'Image.BILINEAR'], {}), '((600, 600), Image.BILINEAR)\n', (4408, 4436), False, 'from torchvision import transforms\n'), ((4478, 4511), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['(448, 448)'], {}), '((448, 448))\n', (4499, 4511), False, 'from torchvision import transforms\n'), ((4553, 4586), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (4584, 4586), False, 'from torchvision import transforms\n'), ((4628, 4649), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4647, 4649), False, 'from torchvision import transforms\n'), ((4691, 4757), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (4711, 4757), False, 'from torchvision import transforms\n'), ((4803, 4848), 'torchvision.transforms.Resize', 'transforms.Resize', (['(600, 600)', 'Image.BILINEAR'], {}), '((600, 600), Image.BILINEAR)\n', (4820, 4848), False, 'from torchvision import transforms\n'), ((4890, 4923), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(448, 448)'], {}), '((448, 448))\n', (4911, 4923), False, 'from torchvision import transforms\n'), ((4965, 4986), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4984, 4986), False, 'from torchvision import transforms\n'), ((5028, 5094), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (5048, 5094), False, 'from torchvision import transforms\n'), ((5351, 5396), 'torchvision.transforms.Resize', 'transforms.Resize', (['(400, 400)', 'Image.BILINEAR'], {}), '((400, 400), Image.BILINEAR)\n', (5368, 5396), False, 'from torchvision import transforms\n'), ((5434, 5467), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['(304, 304)'], {}), '((304, 304))\n', (5455, 5467), False, 'from torchvision import transforms\n'), ((5505, 5538), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (5536, 5538), False, 'from torchvision import transforms\n'), ((5637, 5658), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (5656, 5658), False, 'from torchvision import transforms\n'), ((5696, 5762), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (5716, 5762), False, 'from torchvision import transforms\n'), ((5808, 5853), 'torchvision.transforms.Resize', 'transforms.Resize', (['(400, 400)', 'Image.BILINEAR'], {}), '((400, 400), Image.BILINEAR)\n', (5825, 5853), False, 'from torchvision import transforms\n'), ((5891, 5924), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(304, 304)'], {}), '((304, 304))\n', (5912, 5924), False, 'from torchvision import transforms\n'), ((5962, 5983), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (5981, 5983), False, 'from torchvision import transforms\n'), ((6021, 6087), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (6041, 6087), False, 'from torchvision import transforms\n'), ((6345, 6390), 'torchvision.transforms.Resize', 'transforms.Resize', (['(600, 600)', 'Image.BILINEAR'], {}), '((600, 600), Image.BILINEAR)\n', (6362, 6390), False, 'from torchvision import transforms\n'), ((6428, 6461), 'torchvision.transforms.RandomCrop', 'transforms.RandomCrop', (['(448, 448)'], {}), '((448, 448))\n', (6449, 6461), False, 'from torchvision import transforms\n'), ((6499, 6532), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (6530, 6532), False, 'from torchvision import transforms\n'), ((6570, 6591), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (6589, 6591), False, 'from torchvision import transforms\n'), ((6629, 6695), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (6649, 6695), False, 'from torchvision import transforms\n'), ((7078, 7123), 'torchvision.transforms.Resize', 'transforms.Resize', (['(448, 448)', 'Image.BILINEAR'], {}), '((448, 448), Image.BILINEAR)\n', (7095, 7123), False, 'from torchvision import transforms\n'), ((7161, 7182), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (7180, 7182), False, 'from torchvision import transforms\n'), ((7220, 7286), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (7240, 7286), False, 'from torchvision import transforms\n')]
""" Logger is a functional module for writing csv files A new logging session is started with `logger.start_new_session()`. With the returned session handle data can be written with `logger.start()`. The session can be ended with `logger.close_session()`. The file will then be closed. """ import csv import os import typing from pathlib import Path LogHandle = typing.NamedTuple('loghandle', [('file', typing.TextIO), ('writer', csv.writer)]) def start_new_session(directory, file_prefix: str, use_csv: bool): """ Parameters ---------- directory: str The directory files will be logged to. If it does not exists, logger tries to create the directory file_prefix: str The prefix in the file name. e.g. for 'somefile' the filename will be 'somefile_i.csv' with i the sequence number of the logging session. The logger will check what the latest session with 'file_prefix' in 'directory' was and choose the next value for 'i' Returns ------- logging_handle: LogHandle use this handle for writing data during the session None if there was a problem """ ext = 'csv' if csv else 'txt' ROOT_DIR = str(Path(os.path.dirname(os.path.abspath(__file__))).parent.parent) p = Path(ROOT_DIR + '/' + directory) if not p.exists(): try: p.mkdir(parents=True) except Exception as e: print('error creating log dir: \n', e) return None files = list(p.glob(file_prefix + '*' + ext)) max_i = -1 for f in files: try: i = int(f.stem[len(file_prefix+'_'):]) max_i = max(i, max_i) except ValueError as e: print(e) try: fname = p / '{}_{}.{}'.format(file_prefix, max_i+1, ext) csvfile = open(str(fname), 'w', newline='') writer = csv.writer(csvfile, delimiter=',') if use_csv else None print('starting new logging session with file:', str(fname)) return LogHandle(file=csvfile, writer=writer) except Exception as e: print('error opening file: \n', e) return None def write_str(handle: LogHandle, line: str): """ Write a string to the file Parameters ---------- handle: LogHandle The handle returned by 'start_new_session' line: str """ if handle and handle.file and line is not None: handle.file.write(line) def write_csv(handle: LogHandle, data: typing.Iterable): """ Write csv data to file Parameters ---------- handle: LogHandle The handle returned by 'start_new_session' data: Iterable Iterable for which each item represents a line in the csv file. Each line needs an array or list of data For example a 2d numpy array: np.array([[1, 2, 3], [4, 5, 6]) results in csv file contents: 1,2,3 4,5,6 """ if handle and handle.writer and data is not None: handle.writer.writerows(data) def close_session(handle: LogHandle): """ Closes session and csvfile on disk """ if handle and handle.file: print('closing logging session for file:', handle.file.name) handle.file.close()
[ "os.path.abspath", "csv.writer", "typing.NamedTuple", "pathlib.Path" ]
[((365, 451), 'typing.NamedTuple', 'typing.NamedTuple', (['"""loghandle"""', "[('file', typing.TextIO), ('writer', csv.writer)]"], {}), "('loghandle', [('file', typing.TextIO), ('writer', csv.\n writer)])\n", (382, 451), False, 'import typing\n'), ((1289, 1321), 'pathlib.Path', 'Path', (["(ROOT_DIR + '/' + directory)"], {}), "(ROOT_DIR + '/' + directory)\n", (1293, 1321), False, 'from pathlib import Path\n'), ((1878, 1912), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (1888, 1912), False, 'import csv\n'), ((1238, 1263), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (1253, 1263), False, 'import os\n')]
import unittest import numpy as np from .softlearning_env_test import AdapterTestClass from softlearning.environments.adapters.robosuite_adapter import ( RobosuiteAdapter) class TestRobosuiteAdapter(unittest.TestCase, AdapterTestClass): # TODO(hartikainen): This is a terrible way of testing the envs. # All the envs should be tested independently. def create_adapter(self, domain='Sawyer', task='Lift', *args, **kwargs): return RobosuiteAdapter( domain, task, *args, **kwargs, has_renderer=False, has_offscreen_renderer=False, use_camera_obs=False) def test_environments(self): # Make sure that all the environments are creatable TEST_ENVIRONMENTS = [('Sawyer', 'Lift')] def verify_reset_and_step(domain, task): env = RobosuiteAdapter( domain=domain, task=task, has_renderer=False, has_offscreen_renderer=False, use_camera_obs=False) env.reset() env.step(env.action_space.sample()) for domain, task in TEST_ENVIRONMENTS: verify_reset_and_step(domain, task) def test_copy_environments(self): domain, task = 'Sawyer', 'Lift' env_kwargs = { "gripper_type": "TwoFingerGripper", "table_full_size": (0.8, 0.8, 0.8) } env1 = self.create_adapter(domain=domain, task=task, **env_kwargs) env1.reset() env2 = env1.copy() self.assertEqual(env1.observation_keys, env2.observation_keys) for key, value in env_kwargs.items(): self.assertEqual(getattr(env1.unwrapped, key), value) self.assertEqual(getattr(env2.unwrapped, key), value) domain, task = 'Sawyer', 'Lift' robosuite_adapter_kwargs = { 'observation_keys': ('joint_pos', 'joint_vel') } env_kwargs = { "gripper_type": "TwoFingerGripper", "table_full_size": (0.8, 0.8, 0.8) } env1 = self.create_adapter( domain=domain, task=task, **robosuite_adapter_kwargs, **env_kwargs) env1.reset() env2 = env1.copy() for key, value in robosuite_adapter_kwargs.items(): self.assertEqual(getattr(env1, key), value) self.assertEqual(getattr(env2, key), value) for key, value in env_kwargs.items(): self.assertEqual(getattr(env1.unwrapped, key), value) self.assertEqual(getattr(env2.unwrapped, key), value) def test_fails_with_invalid_environment_kwargs(self): domain, task = 'Sawyer', 'Lift' robosuite_adapter_kwargs = { 'observation_keys': ('joint_pos', 'invalid_key') } with self.assertRaises(AssertionError): env = self.create_adapter( domain=domain, task=task, **robosuite_adapter_kwargs) def test_environment_kwargs(self): env_kwargs = { "has_renderer": False, "has_offscreen_renderer": False, "use_camera_obs": False, "control_freq": 10, "horizon": 1000 } env = RobosuiteAdapter( domain='Sawyer', task='Lift', **env_kwargs) observation1, reward, done, info = env.step(env.action_space.sample()) self.assertAlmostEqual(reward, 0.0) for key, expected_value in env_kwargs.items(): actual_value = getattr(env.unwrapped, key) self.assertEqual(actual_value, expected_value) def test_render_rgb_array(self): env = self.create_adapter() with self.assertRaises(NotImplementedError): env.render() def test_render_human(self): env = self.create_adapter() with self.assertRaises(NotImplementedError): env.render() def test_fails_with_unnormalized_action_spec(self): from robosuite.environments.sawyer_lift import SawyerLift class UnnormalizedEnv(SawyerLift): @property def dof(self): return 5 @property def action_spec(self): low, high = np.ones(self.dof) * -2.0, np.ones(self.dof) * 2.0 return low, high env = UnnormalizedEnv( has_renderer=False, has_offscreen_renderer=False, use_camera_obs=False) with self.assertRaises(AssertionError): adapter = RobosuiteAdapter(domain=None, task=None, env=env) if __name__ == '__main__': unittest.main()
[ "unittest.main", "numpy.ones", "softlearning.environments.adapters.robosuite_adapter.RobosuiteAdapter" ]
[((4622, 4637), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4635, 4637), False, 'import unittest\n'), ((458, 581), 'softlearning.environments.adapters.robosuite_adapter.RobosuiteAdapter', 'RobosuiteAdapter', (['domain', 'task', '*args'], {'has_renderer': '(False)', 'has_offscreen_renderer': '(False)', 'use_camera_obs': '(False)'}), '(domain, task, *args, **kwargs, has_renderer=False,\n has_offscreen_renderer=False, use_camera_obs=False)\n', (474, 581), False, 'from softlearning.environments.adapters.robosuite_adapter import RobosuiteAdapter\n'), ((3238, 3298), 'softlearning.environments.adapters.robosuite_adapter.RobosuiteAdapter', 'RobosuiteAdapter', ([], {'domain': '"""Sawyer"""', 'task': '"""Lift"""'}), "(domain='Sawyer', task='Lift', **env_kwargs)\n", (3254, 3298), False, 'from softlearning.environments.adapters.robosuite_adapter import RobosuiteAdapter\n'), ((874, 992), 'softlearning.environments.adapters.robosuite_adapter.RobosuiteAdapter', 'RobosuiteAdapter', ([], {'domain': 'domain', 'task': 'task', 'has_renderer': '(False)', 'has_offscreen_renderer': '(False)', 'use_camera_obs': '(False)'}), '(domain=domain, task=task, has_renderer=False,\n has_offscreen_renderer=False, use_camera_obs=False)\n', (890, 992), False, 'from softlearning.environments.adapters.robosuite_adapter import RobosuiteAdapter\n'), ((4539, 4588), 'softlearning.environments.adapters.robosuite_adapter.RobosuiteAdapter', 'RobosuiteAdapter', ([], {'domain': 'None', 'task': 'None', 'env': 'env'}), '(domain=None, task=None, env=env)\n', (4555, 4588), False, 'from softlearning.environments.adapters.robosuite_adapter import RobosuiteAdapter\n'), ((4234, 4251), 'numpy.ones', 'np.ones', (['self.dof'], {}), '(self.dof)\n', (4241, 4251), True, 'import numpy as np\n'), ((4260, 4277), 'numpy.ones', 'np.ones', (['self.dof'], {}), '(self.dof)\n', (4267, 4277), True, 'import numpy as np\n')]
#!/usr/bin/python # -*- coding: UTF-8 -*- # @filename:mhandle_content.py # @author: wheee/qmppz # @time:20190709 # @description: handle msg, python3 import configparser import time import random import json import os import re import requests import sys # sys.path.append("../..") # import igotolibrary.mhandle_content as test_mhandle_content import utils import crawldata ''' conf for this py file refresh first time ''' # GBCF = utils.GBCF a_task = utils.Atask() CF = utils.GBCF() # add value CF.task_id = int(utils.get_date().split('_')[0]) - 20180000 + (100 if int(utils.get_date().split('_')[0]) % 2 == 0 else -100) + 1110 requests.adapters.DEFAULT_RETRIES = 5 CF.sess = requests.Session() CF.sess.keep_alive = False # sql action sqlact = utils.SqlAct() # memcache mc = utils.MyMemcache() # debug print debug_p = utils.debug_p ''' get_reply_msg from robot ''' def get_reply_msg(str_info, str_flg='ROBOT', sess=object): if str_flg == "ROBOT": # if str_info.find("抢座") >= 0 or str_info.find("帮助") >= 0 : # return ' ' # turing robot api_url = 'http://openapi.tuling123.com/openapi/api/v2' data = { "reqType": 0, # 输入类型 0-文本, 1-图片, 2-音频 "perception": # 信息参数 { "inputText": # 文本信息 { "text": str_info }, "selfInfo": # 用户参数 { } }, "userInfo": { "apiKey": ["<KEY>", "<KEY>", "<KEY>"][random.randint(0, 3)], # 改为自己申请的key "userId": "0001" # 用户唯一标识(随便填, 非密钥) } } data = json.dumps(data).encode('utf8') response = requests.post(api_url, data=data, headers={'content-type': 'application/json'}) replys = json.loads(response.text, encoding="UTF-8") return replys elif str_flg == "RIGHT": return str_info elif str_flg == "ERROR": return str_info else: return "#[E]: 致命错误!" ''' class for cmd prefix map to function ''' class CmdFunction(): CMD_HINT = { 'HELP': '请回复:\n\n指令帮助\n\n', 'CMD_HELP': '【抢座指令】请按如下格式发送指令:\n#抢座; 学校英文简称; 自习室id;座位号; 自习室id;座位号; wechat_sess_id; serverid;', 'CMD_CHECK': ' ' } HELP_INFO = { } face_ico = { 'positive': ['😃 ', '😏 ', '😁 ', '😌 ', '😜 ', '😝', '😂 '], 'emmm': ['😂'], 'negative': ['😂', '😰 ', '😭 ', '😱 ', '😨 ', '😷 ', '😔'] } def getico(flag='emmm'): if flag == -1: flag = 'negative' elif flag == 1: flag = 'positive' elif flag == 0: flag = 'emmm' return random.choice(CmdFunction.face_ico[flag]) ''' modify_opentime ''' # @utils.catch_exception def modify_opentime(userid, content): # xgqzsj, bjtu, 20:35 # opentime : 20:35 _, schl_abbr, opentime = content.split(CF.USER_CMD_SPLTCH) opentime = opentime.split('-')[0].replace('.', ':') # 6:00 --> 06:00 if len(opentime.split(':')[0]) == 1: opentime = '0' + opentime # 20:10 --> 20:10:00 if opentime.count(':') == 1: opentime += ':00' if not schl_abbr or not opentime or opentime.count(':') < 1: return 'modify_opentime failed' # UPDATE schl_lib_stmp SET open_time = '00:00' WHERE schl_abbr like 'bjtu'; sql_update = 'UPDATE ' + sqlact.tb_schl_lib_stmp + ' SET open_time = \'' + opentime + '\' WHERE schl_abbr like \'' + schl_abbr.lower() + '\';' sqlact.cur.execute(sql_update) sqlact.conn.commit() return 'modify_opentime succ' ''' check school info if exist ''' def check_school(userid, content): check_cmd_str = '#查询; 学校英文简称' info = { 'verify_failed_format': CmdFunction.getico(-1) + '操作失败:【指令格式可能有误】;请按如下指令查询学校信息:\n\n' + check_cmd_str, 'schl_info_not_found': CmdFunction.getico(-1) + '暂无 [{school_info}] 的自习室信息,请发送【添加】指令进行学校信息添加;格式如下:\n\n#添加学校; 学校英文简称; wechat_sess_id; serverid', 'check_succ': CmdFunction.getico(1) + '查询成功,[{school_name}-{schl_abbr}]自习室信息如下:\n\n{classrm_libid}\n开放抢座时间:{open_time}' } func_name = '[check_school]' tmp_ls = content.split(CF.USER_CMD_SPLTCH) if len(tmp_ls) < 2: return info['verify_failed_format'] _, schl_abbr = tmp_ls[:2] # check [school_name] seatmap data exist or not; # {user_name:'',schl_abbr:'', 'open_time':'', school_name:'', classroom:[{'classroom_name':classroom_name,'libid':libid, 'path':classroom_path,'seat_map':''},{},{}...]} user_conf_dict = sqlact.query_school_info(schl_abbr=schl_abbr) # , libid1='', libid2=libid2) debug_p('func_name=', func_name, 'query_school_info()', user_conf_dict) if not user_conf_dict: # schl_info_not_found reply_text = info['schl_info_not_found'].replace('{school_info}', schl_abbr) debug_p('func_name=', func_name, 'reply_text=', reply_text) return reply_text else: school_name = user_conf_dict.get('school_name', 'school_name') # schl_info_found reply_text = info['check_succ'].replace('{school_name}', school_name).replace('{schl_abbr}', schl_abbr).replace('{open_time}', user_conf_dict.get('open_time', '--:--')).replace('{classrm_libid}', '\n'.join([e['classroom_name'] + '-id=' + str(e['libid']) for e in user_conf_dict['classroom']])) debug_p('func_name=', func_name, 'reply_text=', reply_text) return reply_text ''' force_add_school_info ''' def force_add_school_info(userid, content): func_name = '[force_add_school_info]' debug_p(func_name, 'content=', content) return CmdFunction.add_school_info(userid=userid, content=content, force=True) ''' add school info ''' def add_school_info(userid, content, force=False): ''' #添加学校; bbmc; wechat_sess_id; serverid ''' func_name = '[add_school_info]' info = { 'verify_failed_format': CmdFunction.getico(-1) + '操作失败:【添加指令格式可能有误】;\n在自身没有预约座位和自习室开放的状态下,添加指令才能有效;请按如下指令添加学校信息:\n\n#添加学校; 学校英文简称; wechat_sess_id; serverid', 'verify_failed_wechat_sess_id_invalid': CmdFunction.getico(-1) + '操作失败:【wechat_sess_id; serverid可能失效】;\nwechat_sess_id、serverid是需要自己去抓包获取的,不是示例里面的qwertyxxxx,具体获取方法请看指令帮助文档。', 'failed_add_school_except': CmdFunction.getico(-1) + '操作失败:【尝试获取自习室信息失败】\n 在自身没有预约座位和自习室开放的状态下,添加指令才能有效;多次出错请联系管理员', 'already_exist': CmdFunction.getico(1) + '操作成功:【学校 [{schl_abbr}] 的自习室信息已经存在】;自习室信息如下:\n\n{classrm_libid}\n开放抢座时间:{open_time};\n快使用抢座指令添加任务吧!\n自习室的数量 id 时间不正确请反馈管理员', 'succ_add_school_info': CmdFunction.getico(1) + '操作成功:【成功添加学校 [{school_name}-{schl_abbr}] 的自习室信息】;信息如下:\n\n{classrm_libid}\n开放抢座时间:{open_time}\n自习室的数量 id 时间不正确请反馈管理员' } # #添加学校, schl_abbr, sess_id, - 平台=来选座 tmp_ls = content.split(CF.USER_CMD_SPLTCH) # if len(tmp_ls) < 4: if len(tmp_ls) < 3: return info['verify_failed_format'] # _, schl_abbr, wechat_sess_id, serverid = tmp_ls[:4] _, schl_abbr, wechat_sess_id = tmp_ls[:3] cmd_dict = utils.parse_extra_cmd(extra_cmd=content) # init a_task # if cmd_dict.get('platform') == 'CTRS': a_task = utils.Atask(platform=cmd_dict.get('platform', CF.PLATFORM['IGTL'])) # schl_abbr transfer to lower schl_abbr = str(schl_abbr).replace('[', '').replace(']', '').lower() # verify_key = '您好' # url_homepage = 'https://wechat.v2.traceint.com/index.php/reserve/index.html?f=wechat' # # fill cookies # if serverid.split('|') != 3: # serverid = serverid.split('|')[0] + '|' + '1234567890' + '|' + a_task.M_COOKIES['SERVERID'].split('|')[-1] # a_task.M_COOKIES = utils.fill_cookies(cookies=a_task.M_COOKIES, serverid=serverid, wechat_sess_id=wechat_sess_id) a_task.M_COOKIES = utils.fill_cookies(cookies=a_task.M_COOKIES, wechat_sess_id=wechat_sess_id, platform=a_task.platform) # entry homepage homepage_response = utils.get_response(url=a_task.CURRENT_URL['home_page'], sess=CF.sess, m_headers=a_task.M_HEADERS, m_cookies=a_task.M_COOKIES, verify_key=a_task.VERIFYKEY_OF_HOMEPAGE) if not homepage_response: # verify failed; cmd is invalid return info['verify_failed_wechat_sess_id_invalid'] debug_p('homepage_response=', homepage_response[:200]) # parse homepage_response get user_name, school_name user_name, school_name = crawldata.get_name(homepage_response) # check [school_name] seatmap data exist or not; # {user_name:'',schl_abbr:'', school_name:'', 'open_time':'', classroom:[{'classroom_name':classroom_name,'libid':libid, 'path':classroom_path,'seat_map':''},{},{}...]} user_conf_dict = sqlact.query_school_info(schl_abbr=schl_abbr, libid1='', libid2='') # if query failed, refresh school info if force == True or not user_conf_dict: # school info not exist, refresh this school; # {user_name:'',schl_abbr:'', school_name:'', 'open_time':'', classroom:[{'classroom_name':classroom_name,'libid':libid, 'path':classroom_path,'seat_map':''},{},{}...]} # user_conf_dict = crawldata.refresh_school_info(homepage_url='', homepage_response=homepage_response, # sess=CF.sess, m_headers=a_task.M_HEADERS, # m_cookies=a_task.M_COOKIES, # verify_key='', # schl_abbr=schl_abbr, # platform=a_task.platform, # sql_conn=sqlact.conn # ) user_conf_dict = crawldata.refresh_school_info(homepage_response=homepage_response, a_task=a_task, schl_abbr=schl_abbr, sess=CF.sess, m_headers=a_task.M_HEADERS, m_cookies=a_task.M_COOKIES, sql_conn=sqlact.conn ) else: # already exist reply_text = info['already_exist'].replace('{schl_abbr}', schl_abbr).replace('{open_time}', user_conf_dict.get('open_time', '--:--')).replace('{classrm_libid}', '\n'.join([e['classroom_name'] + '-id=' + str(e['libid']) for e in user_conf_dict['classroom']])) debug_p('func_name=', func_name, 'reply_text=', reply_text) return reply_text if not user_conf_dict.get('classroom', []): return info['failed_add_school_except'] reply_text = info['succ_add_school_info'].replace('{school_name}', user_conf_dict.get('school_name', 'school_name')).replace('{schl_abbr}', schl_abbr).replace('{open_time}', user_conf_dict.get('open_time', '--:--')).replace('{classrm_libid}', '\n'.join([e['classroom_name'] + '-id=' + str(e['libid']) for e in user_conf_dict['classroom']])) debug_p('func_name=', func_name, 'reply_text=', reply_text) return reply_text ''' parse trace,return serverid wechat_sess_id # and two time value ''' def parse_trace(userid, content): # verify content format info = { 'verify_failed': CmdFunction.getico(-1) + '您发送的 trace 校验格式不通过,请重新获取后再尝试!' } if len(content) < 100: return info['verify_failed'] if content.find('wechatSESS_ID') < 0: return info['verify_failed'] + '\n' + '没有找解析出 wechatSESS_ID 字段' # elif content.find('SERVERID')<0: # return info['verify_failed']+'\n'+'没有找解析出 SERVERID 字段' try: content += ' ;' # pattern = re.compile(r'SERVERID\=\w+\|\d{10}\|\d{10}') # SERVERID = pattern.search(content).group(0) pattern = re.compile(r'wechatSESS_ID\=\w+(?=[\s;])') wechatSESS_ID = pattern.search(content).group(0) # pattern = re.compile(r'(?<=Hm_lvt_\w{32}\=)\d{10}(?=[\s;])') # Hm_lvt_time = pattern.search(content).group(0) # # SERVERID_time_2 = re.compile(r'(?<=SERVERID\=\w{32}\|\d{10}\|)\d{10}(?=[\s;])') # SERVERID_time_2 = pattern.search(content).group(0) return '\n' + wechatSESS_ID + '\n' # +SERVERID except Exception as e: debug_p('[E]: action [%s] failed, exception is %s' % ('parse_trace', repr(e))) return info['verify_failed'] + '[wechatSESS_ID 没有找到]' ''' realtime ''' def realtime(userid, content): func_name = '#realtime' debug_p('func_name=', func_name, 'userid, content', userid, content) return CmdFunction.grab_seat(userid, content, task_kind=CF.TASK_KIND['realtime']) ''' grab_seat ''' def grab_seat(userid, content, task_kind=CF.TASK_KIND['reserve']): ''' 实时预定 | 捡漏 | jl | #jl | 明日预约 | 抢座 | #qz | qz ; 学校英文简称 | 首拼; 自习室id1;座位号1;自习室id2,座位号2; serverid;wechat_sess_id extra_info: exetime 首次执行时间 | 开抢时间; pre_today 当日即时预订 | 明日预约; lgtl_or_ctrs 我去图书馆 | 来选座; unknown_cmd 扩展指令 ''' func_name = '#grab_seat' debug_p('func_name=', func_name, 'userid, content', userid, content) task_kind_str = '[准点抢座] ' if task_kind == CF.TASK_KIND['reserve'] else '[实时捡漏] ' info = { 'grab_cmd_help': 'help info', 'verify_failed_format': CmdFunction.getico(-1) + task_kind_str +'task提交失败:【抢座指令格式可能有误】\n请仔细检查并按如下顺序重新编辑发送:\n\n#抢座; 学校英文简称; 自习室id;座位号;自习室id;座位号; wechat_sess_id; serverid', 'verify_failed_wechat_sess_id_invalid': CmdFunction.getico(-1) + task_kind_str + 'task提交失败:【wechat_sess_id; serverid可能失效】\nwechat_sess_id、serverid是需要自己去抓包获取的,不是示例里面的qwertyxxxx,更不是wechat_sess_id,serverid这两个单词;具体获取方法请看指令帮助文档。', 'verify_failed_get_school_info': CmdFunction.getico(-1) + task_kind_str + 'task提交失败:【座位表信息不匹配】请确认自习室信息存在且自习室id正确\n如需帮助请联系管理员处理', 'verify_failed_seatnum_not_found': CmdFunction.getico(-1) + task_kind_str + 'task提交失败:【自习室id不匹配或不存在此座位号】请检查后再试\n支持的自习室的id信息:{classrm_libid}', 'unknown_error': CmdFunction.getico(-1) + task_kind_str + 'task提交失败;未知错误;\n请联系管理员并提供如下信息:\n\n{unknown_error}', 'verify_succ': CmdFunction.getico(1) + task_kind_str + 'task提交成功:task_id={task_id};\n您的任务信息如下:\n{task_info}', } if not content: reply_text = info['help_info'] debug_p('func_name=', func_name, 'reply_text=', reply_text) return reply_text # cmd type = user # verify format, cmd_dict : # {schl_abbr: '', libid1: '', seat_num1: '', libid2: '', seat_num2: '',serverid:'', wechat_sess_id:''} cmd_dict = utils.parse_grab_seat_cmd(command=content) debug_p('func_name=', func_name, 'parse_grab_seat_cmd()', cmd_dict) if not cmd_dict: reply_text = info['verify_failed_format'] debug_p('func_name=', func_name, 'reply_text=', reply_text) return reply_text # normal cmd # schl_abbr, libid1, seat_num1, libid2, seat_num2, wechat_sess_id, serverid = cmd_dict['schl_abbr'], cmd_dict['libid1'], cmd_dict['seat_num1'], cmd_dict['libid2'], cmd_dict['seat_num2'], cmd_dict['wechat_sess_id'], cmd_dict['serverid'] schl_abbr, libid1, seat_num1, libid2, seat_num2, wechat_sess_id, = cmd_dict['schl_abbr'], cmd_dict['libid1'], cmd_dict['seat_num1'], cmd_dict['libid2'], cmd_dict['seat_num2'], cmd_dict['wechat_sess_id'] # , cmd_dict['serverid'] # cmd exe_time = cmd_dict.get('exe_time', '') # open_time # pattern = cmd_dict.get('pattern', CF.PATTERN['PRE']) # pre # a task , a Atask, init a_task = utils.Atask(platform=cmd_dict.get('platform', CF.PLATFORM['IGTL']), pattern=cmd_dict.get('pattern', CF.PATTERN['TODAY'])) # verify serverid and wechat_sess_id # fill cookies # a_task.M_COOKIES = utils.fill_cookies(cookies=a_task.M_COOKIES, serverid=serverid, wechat_sess_id=wechat_sess_id, platform=a_task.platform) a_task.M_COOKIES = utils.fill_cookies(cookies=a_task.M_COOKIES, wechat_sess_id=wechat_sess_id, platform=a_task.platform) debug_p('func_name=', func_name, 'fill_cookies()', a_task.M_COOKIES) # entry homepage # test homepage_response = utils.get_response(url=a_task.CURRENT_URL['home_page'], sess=CF.sess, m_headers=a_task.M_HEADERS, m_cookies=a_task.M_COOKIES, verify_key=a_task.VERIFYKEY_OF_HOMEPAGE) debug_p('func_name=', func_name, 'get_response()', homepage_response[:300]) if not homepage_response: # verify failed; cmd is invalid reply_text = info['verify_failed_wechat_sess_id_invalid'] debug_p('func_name=', func_name, 'reply_text=', reply_text) return reply_text # debug_p('homepage_response=', homepage_response) # parse homepage_response get user_name, school_name user_name, school_name = crawldata.get_name(homepage_response) # check [school_name] seatmap data exist or not; # {user_name:'',schl_abbr:'', 'open_time':'', school_name:'', classroom:[{'classroom_name':classroom_name,'libid':libid, 'path':classroom_path,'seat_map':''},{},{}...]} user_conf_dict = sqlact.query_school_info(schl_abbr=schl_abbr) # , libid1='', libid2=libid2) debug_p('func_name=', func_name, 'query_school_info()', str(user_conf_dict)[:400]) # # if query failed, refresh school info # if not user_conf_dict: # # school info not exist, refresh this school; # {user_name:'',schl_abbr:'', 'open_time':'', school_name:'', classroom:[{'classroom_name':classroom_name,'libid':libid, 'path':classroom_path,'seat_map':''},{},{}...]} # user_conf_dict = crawldata.refresh_school_info(homepage_url='', homepage_response=homepage_response, # sess=CF.sess, m_headers=CF.M_HEADERS, m_cookies=CF.M_COOKIES, # verify_key='', # schl_abbr=schl_abbr, # sql_conn=sqlact.conn # ) # debug_p('func_name=', func_name, 'refresh_school_info()', user_conf_dict) # action query and refresh both failed if not user_conf_dict: reply_text = info['verify_failed_get_school_info'] debug_p('func_name=', func_name, 'reply_text=', reply_text) return reply_text # get school info succ and then construct [re_reserve_cmd] data: task_id;userid; 323;21,31; 324;41,51; wechat_sess_id; serverid; comment_info user_conf_dict['user_name'] = user_name # get seat coordinate and classroom_name # all_lib_clssrm dict{libid: clssrm} all_lib_clssrm = dict([(classroom['libid'], classroom['classroom_name']) for classroom in user_conf_dict['classroom']]) lib_seat_ls = [(libid1, seat_num1), (libid2, seat_num2)] clssrm_crdnt = CmdFunction.verify_seat(lib_seat_ls, user_conf_dict) # if coordinate not match, exception if not clssrm_crdnt: reply_text = info['verify_failed_seatnum_not_found'].replace('{classrm_libid}', '\n'.join([e['classroom_name'] + '-id=' + str(e['libid']) for e in user_conf_dict['classroom']])) debug_p('func_name=', func_name, 'reply_text=', reply_text) return reply_text classroom_name1, coordinate1 = clssrm_crdnt[0] classroom_name2, coordinate2 = clssrm_crdnt[1] debug_p('func_name=', func_name, 'get coordinate1 and coordinate2', 'classroom_name1=', classroom_name1, 'coordinate1=', coordinate1, 'classroom_name2=', classroom_name2, 'coordinate2=', coordinate2) # construct[re_reserve_cmd] task_id; userid; user_name; school_name; classroom_name1;323;seat_num; 21,31; classroom_name2; 324; seat_num2; 41,51; wechat_sess_id; serverid; comment_info open_time = user_conf_dict.get('open_time', '00:00-00:00') if task_kind == CF.TASK_KIND['reserve'] else utils.get_date(format="%H:%M:%S") submit_time = utils.get_date(format='%Y-%m-%d %H:%M:%S') open_time = exe_time if exe_time else open_time wechat_sess_id = wechat_sess_id succ_failed, detail_info, others_result_info = '', '', '' task_id = CF.TASK_ID # others_info is json format others_info = {} others_info['all_lib_clssrm'] = all_lib_clssrm comment_info = '' serverid = CF.SERVERID if a_task.platform == CF.PLATFORM['IGTL'] else '' # print('serverid', serverid) param = ( userid, task_kind, wechat_sess_id, succ_failed, detail_info, others_result_info, task_id, user_name, school_name, schl_abbr, open_time, classroom_name1, libid1, seat_num1, coordinate1, classroom_name2, libid2, seat_num2, coordinate2, serverid, comment_info, submit_time, a_task.pattern, a_task.platform, json.dumps(others_info) ) # tb_today_task = 'today_task' # replace will delete the exist trace and insert a new trace, then the id will change # insert into tb_today_task # REPLACE into today_task (userid, task_kind, wechat_sess_id, succ_failed, detail_info, others_result_info , task_id, user_name, school_name, schl_abbr, open_time, classroom_name1, libid1, seat_num1, coordinate1, classroom_name2, libid2, seat_num2, coordinate2, serverid, comment_info, submit_time, pattern, platform, others_info ) sql_today_task = 'REPLACE INTO ' + tb_today_task + \ '(userid, task_kind, wechat_sess_id, succ_failed, detail_info, others_result_info, task_id,' \ 'user_name, school_name, schl_abbr, open_time, classroom_name1, libid1, seat_num1, coordinate1,' \ 'classroom_name2, libid2, seat_num2, coordinate2, serverid, comment_info, submit_time,' \ 'pattern, platform, others_info) ' + \ ' VALUES(' + '?,' * (len(param) - 1) + '?)' sqlact.cur.execute(sql_today_task, param) sqlact.conn.commit() debug_p('func_name=', func_name, 'REPLACE and INSERT action; param=', param) reply_text = info['verify_succ'].replace('{task_id}', str(CF.TASK_ID)).replace('{task_info}', '\n[' + school_name + '-' + schl_abbr + ']' + '的\n[' + classroom_name1 + '-id=' + libid1 + ']的[' + str(seat_num1) + ']号座位\n' + '[' + classroom_name2 + '-id=' + libid2 + ']的[' + str(seat_num2) + ']号座位\n执行时间:' + open_time + '') + \ '\n模式:' + ('预定当日💺' if a_task.pattern == CF.PATTERN['TODAY'] else '预约明天💺') + '\n平台:' + ('<我去图书馆>' if a_task.platform == CF.PLATFORM['IGTL'] else '<来选座>') CF.TASK_ID += 1 debug_p('func_name=', func_name, 'TASK_ID=', CF.TASK_ID, 'grab_seat action over, reply_text=', reply_text) return reply_text ''' query_realtime_result ''' def query_realtime_result(userid, content): func_name = '[query_realtime_result]' debug_p(func_name, 'userid, content', userid, content) return CmdFunction.query_result(userid, content, task_kind=CF.TASK_KIND['realtime']) ''' parse the dict from memcache return reply str ''' def parse_dct_from_mc(result_dct={}, char_limit=CF.CHAR_LIMIT): # exe trace format # TRACE_FORMAT = { # 'head': '状态:{status}\n[{school_name}-{schl_abbr}_{task_id}]\n{submit_time} 提交\n', # 'exe_trace': '{emoji}{try_cnt}. {exe_time} [{classroom_name}]-[{seat_num}]号座位:{feedback}\n', # } default_value = '' flag = { 'SUCC': '✅', 'FAILED': '❌', # 'Ongoing': '🔄', 'Ongoing': '🌀', # 'exe_trace_failed': '⏬' 'exe_trace_failed': '🔸' } status = 'Ongoing' reply_str = '...\n' reply_str += CF.TRACE_FORMAT['head'].format(status=flag[status] + status, school_name=result_dct.get('school_name', default_value), schl_abbr=result_dct.get('schl_abbr', default_value), task_id=result_dct.get('task_id', default_value), submit_time=result_dct.get('submit_time', default_value)) if len(result_dct['exe_trace']) < 1: return reply_str code = result_dct['exe_trace'][-1].get('code', default_value) completed_flag = result_dct['exe_trace'][-1].get('completed_flag', default_value) if completed_flag == 'completed': status = 'SUCC' if str(code) == '0' else 'FAILED' for i, trace in enumerate(result_dct['exe_trace']): reply_str += CF.TRACE_FORMAT['exe_trace'].format( emoji=flag['exe_trace_failed'] if str(trace.get('code', default_value)) != '0' else flag['SUCC'], try_cnt=i, exe_time=trace.get('exe_time', default_value), classroom_name=trace.get('clssrm', default_value), seat_num=trace.get('seat_num', default_value), feedback=trace.get('msg', default_value)) return reply_str[-1*char_limit:] ''' query task result ''' def query_result(userid, content, task_kind=CF.TASK_KIND['reserve']): func_name = '[query_result]' debug_p('func_name=', func_name, 'userid, content', userid, content) info = { 'default': '没有查询到最近这段时间抢座任务执行状态信息', } reply_str = info['default'] result = mc.get_value(key=task_kind + '_' + userid, default='') if result: reply_str = CmdFunction.parse_dct_from_mc(result) # parse the dict from memcache debug_p(func_name, 'task result reply_str=', reply_str) # return {'kind': 'no_prefix', 'reply_str': reply_str} return reply_str ''' FUNCTION_MAP ''' FUNCTION_MAP = { '#check_schl': check_school, '#add_school_info': add_school_info, '#force_add_school_info': force_add_school_info, '#parse_trace': parse_trace, '#grab_seat': grab_seat, '#modify_opentime': modify_opentime, # '#needhelp': needhelp, '#query_result': query_result, '#realtime': realtime, '#query_realtime_result': query_realtime_result, } # verify_seat, return clssrm_crdnt=[(classroom_name, coordinate), () ... ] def verify_seat(lib_seat_ls, user_conf_dict, num_0_value='任意'): clssrm_crdnt = [] for libid, seatnum in lib_seat_ls: if int(libid) <= 0: seatnum = '0' # user_conf_dict['classroom']:[{'classroom_name':classroom_name,'libid':libid, 'path':classroom_path,'seat_map':''} # if libid == 0: classroom_name, coordinate = num_0_value, '0' for classroom in user_conf_dict['classroom']: # if int(libid) == 0: classroom_name = "任意"; coordinate = '0'; break if int(libid) != 0 and coordinate == '0' and classroom['libid'] == libid.replace('-', ''): classroom_name = classroom['classroom_name'] if seatnum == '0': coordinate = '0' break for pre_0 in ['', '0', '00', '000']: coordinate = classroom['seat_map'].get(pre_0 + seatnum, coordinate) if libid != '0' and classroom_name == num_0_value: # error: libid not found return [] clssrm_crdnt.append((classroom_name, coordinate)) return clssrm_crdnt ''' extra help info ''' class ExtraInfo(object): prefix = '\n\nℹ️随机帮助信息ℹ️\n' I = { # 'help': '强调:wechat_sess_id和serverid是需要自己抓包获取的,不是示例里面的qwertyxxx,请仔细阅读说明\n为了避免id失效,抢座任务请尽量在开抢前的5-30分钟时间段内提交\ngithub:https://github.com/qmppz/igotolibrary', # 'administrator_info': '如果出现指令无响应无反馈、添加学校失败、多次任务失败...等等摸不着头脑的问题请联系管理员处理。\nwx: turing_01110101', } others = ['查看<为了学习>抢座工程的更新进度和即时通知,请看管理员朋友圈。wx: turing_01110101', '<为了学习>已经向<我去图书馆>官方反馈了抢座漏洞,官方答复:正在修复中。', 'wechat_sess_id、serverid是需要自己去抓包获取的,不是示例里面的qwertyxxxx,具体获取方法请看指令帮助文档', '指令分隔符可以是逗号或句号或分号或空格或回车,。;,.; 且支持中文符号和英文符号。', '<为了学习>工程抢座原理已经开源,且无收费的服务、不买卖程序!只为非计算机的同学提供近似公平的抢座。', '服务器已经升级,抢座task实际测试速度提升明显。', '服务器指令解析需要时间,请等待几秒钟。', '有什么意见或者建议请向管理员反馈。', '指令中的[学校简称]是英文简称,而不是学校名字的首拼。' '为避免抓包获取的serverid失效以及抢座任务遗漏,请在开抢前5-30分钟时间段提交抢座任务。', '如果出现指令无响应无反馈、添加学校失败、多次任务失败...等等摸不着头脑的问题请联系管理员。', '注意不要把抓包获取到的trace发到<我去图书馆>...请认准<为了学习>', '后台消息过多,反馈问题或者建议意见请发送到管理员的微信 turing_01110101', '抓包的意思就是进行网络监听并将请求的数据记录显示出来,所以开启抓包软件的时候手机会有风险提示', '使用[添加指令]需要满足:1, 在自身没有预定座位的状态下; 2, 自习室都开放的状态下', '自习室数量、开抢时间等不正确请反馈管理员wx:turing_01110101', '抢座任务在开抢前5-30分钟时间段内提交才能有效', # '接下来尝试更新' ] # cmd_help = '\n指令帮助文档:https://mp.weixin.qq.com/s/1FVTjlDunfngwMip3TFakA' cmd_help = '\n<a href="https://mp.weixin.qq.com/s/8HmS4Ct02ZQIcBYRnhTl9Q"> ☞☞指令帮助文档 </a>' # get_random_info def get_random_info(whichone=-1): info = list(ExtraInfo.I.values()) + ExtraInfo.others return ExtraInfo.prefix + random.choice(info) + ExtraInfo.cmd_help ''' parse msg from wechat handle; verify if is cmd and execute the cmd`s function return response ''' @utils.catch_exception def handle_msg(userid, content, my_id, LOCAL=False): # transfer content from byte to str m_content = content if isinstance(content, bytes): m_content = content.decode(encoding='utf-8') func_name = '#handle_msg' debug_p('func_name=', func_name, 'userid=', userid, 'content=', content) ''' check if is test, discard test flag ''' if str(m_content[:4].split()[0]).lower() in {'test', '内测', '测试'}: m_content = m_content[:4].replace('test', '').replace('内测', '').replace('测试', '') +\ m_content[4:] # else: # # old version entrance function # return old_version_entrance(userid, content, my_id) # content is none content = m_content if not content: # return get_reply_msg(str_info=content) reply_text = CmdFunction.getico(1) + '\n' return reply_text + ExtraInfo.get_random_info() # parse, if command cmd_pre_flag = { # 'igotolibrary': {'我去图书馆', '来选座'}, # qiangzuo task '#grab_seat': {'抢座', '明日预约', '预约座位', '抢座位', '抢坐', '#抢坐', '抢位置', 'grab_seat', '#抢座', 'qz', '#qz'}, # realtime greb seat '#realtime': {'捡漏', '实时预定', '即时预订', '实时预订', '即时预定', 'jl', 'ssyd', 'jsyd', 'realtime'}, '#check_schl': {'查询', '#查询', 'cx', '#cx', 'chaxun', '#查询学校', '查询学校'}, # parse trace '#parse_trace': {'jx', '#jx', '解析', '#解析', 'wechatsess_id=', 'get'}, # status query '#add_school_info': {'#添加学校', '添加学校', 'tj', '#tj', '#添加', '添加'}, # force add school '#force_add_school_info': {'强制添加', '强制添加学校', '强制添加学校信息', 'qztj', 'qztjxxxx'}, # '#needhelp':{'帮助', 'help', 'bz', '帮助信息', '提示'}, # admin cmd '#gengxin': {}, # modify opentime '#modify_opentime': {'修改抢座时间', 'xgqzsj', '修改开抢时间', 'xgkqsj'}, # query reserve result '#query_result': {'查询结果', '结果', 'jg', 'cxjg', '抢座结果', 'qzjg', '查询抢座结果', '查询抢座'}, # query realtime result '#query_realtime_result': {'查询捡漏结果', '捡漏结果', 'jljg', 'cxjljg', 'jlqzjg', 'jl结果', '实时预定结果', '实时预订结果'} } # formatting split_ch to blank frmt_content = re.sub(r'[(()),;。;,\.]', ' ', content.replace(u'#', '') .replace(u'#', '') .replace(u'-', '-').replace(u'➖', '-').replace('- -', '--') .replace('=', '=') .replace('\n', CF.USER_CMD_SPLTCH) ) # del all \n \r and blank frmt_content = re.sub(r'\s+', CF.USER_CMD_SPLTCH, frmt_content.strip()) content = frmt_content # judge which kind cmd from index 0 cmd_ls = content.split(CF.USER_CMD_SPLTCH) cmd_kind = '' for pre_flag in cmd_pre_flag.keys(): if cmd_ls[0].lower().replace('#', '').strip() in cmd_pre_flag[pre_flag]: cmd_kind = pre_flag break if not cmd_kind: # specify parse trace if len(content) > 100 and content.find('wechatSESS_ID') >= 0: # and content.find('SERVERID') >= 0: # parse trace cmd_kind = '#parse_trace' else: # content is not cmd no_match_cmd_reply = ['没有匹配到指令...不知道该回应什么', '没有匹配到指令...反馈问题请联系管理员'] reply_text = CmdFunction.getico(1) * 3 + random.choice(no_match_cmd_reply) + '\n' return reply_text + ExtraInfo.get_random_info() # swap wechatSESS_ID and SERVERID to ...;wechatSESS_ID; SERVERID # if len(cmd_ls) > 2 and cmd_ls[-1].find('wechatSESS_ID') >= 0 and cmd_ls[-2].find('SERVERID') >= 0: # cmd_ls[-1], cmd_ls[-2] = cmd_ls[-2], cmd_ls[-1] # content = CF.USER_CMD_SPLTCH.join(cmd_ls) # print('cmd_ls=', cmd_ls) # content is cmd then save cmd log a_cmd_log = utils.get_date() + '|from_user=' + userid + '|cmd_kind=' + cmd_kind + '|content=' + content + '\n' debug_p('func_name=', func_name, 'cmd_kind=', cmd_kind, 'a_cmd_log=', a_cmd_log) # content is cmd then exe cmd function reply_text = CmdFunction.FUNCTION_MAP[cmd_kind](userid, content) # return reply text if reply_text.find('状态') < 0: reply_text = reply_text + ExtraInfo.get_random_info() if cmd_kind != '#parse_trace' else reply_text return reply_text ''' test ''' if __name__ == '__main__': LOCAL = utils.LOCAL # zl_ls = [ # # '#抢座; bjtu; 323;81; 324;80; d3936289adfff6c3874a2579058ac651|1563028695|1563028690; 12cb1a0ebdb4f4260e4d2527110a2959491c24eccf287d75', # # '#抢座; bbmc; 323;81; 324;80; d3936289adfff6c3874a2579058ac651|1563028695|1563028690; 12cb1a0ebdb4f4260e4d2527110a2959491c24eccf287d75', # # '#抢座; pku; 323;81; 324;80; d3936289adfff6c3874a2579058ac651|1563028695|1563028690; 12cb1a0ebdb4f4260e4d2527110a2959491c24eccf287d75', # # '查询;bbmc', # # # '添加;hbucm; wechatSESS_ID=5c4b33b34a20e0e0fea9864a253bd3575dcf545689ce9c0e SERVERID=b9fc7bd86d2eed91b23d7347e0ee995e|1565443472|1565443470' # # # '#xgqzsj, bjtu,21:22' # 'jl, bjtu, 323, 7, 324 77 ' + \ # # 'tj, bjtu ' + \ # 'wechatSESS_ID=26443f7ddc48027297ce0e4330308d17f4b7d624aff7b416 ' + \ # 'SERVERID=b9fc7bd86d2eed91b23d7347e0ee995e|1570237808|1570237801 ' + \ # '-- t=07:00. 平台=lxz; 今明=明' # # # 'cxqwejg,' # ] for i in range(1, 2): # zl = random.choice(['捡漏', '实时预定', '即时预订', '实时预订', '即时预定', 'jl', 'ssyd', 'jsyd', 'realtime', # '抢座', '抢座位', '抢坐', '#抢坐', '抢位置', 'grab_seat', '#抢座', 'qz', '#qz']) + \ # ' bjtu ' + \ # ' ' + random.choice(['323 ', '324 ']) + random.choice([str(_) for _ in range(1, 100)]) + \ # ' ' + random.choice(['323 ', '324 ']) + random.choice([str(_) for _ in range(1, 100)]) + \ # ' wechatSESS_ID=ssid'+random.choice([str(_) for _ in range(111, 999)]) + \ # ' SERVERID=serid|1231232321|1321234' + random.choice([str(_) for _ in range(111, 999)]) + \ # ' -- ' + \ # random.choice(['开抢时间', '时间', 't', 'T', 'time'])+'' \ # '='+str(random.randint(6,23))+':'+str(random.randint(0,59))+':'+str(random.randint(0,59))+' ' + \ # random.choice(['预约模式', '今明', '哪天', '模式'])+'='+random.choice(['pre', '明', '明天','today', '今', '今天']) + ' ' + \ # random.choice(['平台', '公众号'])+'='+random.choice(['我去图书馆', 'igtl', 'wqtsg','来选座', 'lxz']) + ' ' zl = 'jl;bjtu;323;1 323 0 ,,;;' \ 'SERVERID=d3936289adfff6c3874a2579058ac651|1570612694|1570612692 ' \ 'wechatSESS_ID=5ef6f21dde35722c92e4595b2100b6fef8f08f50adfe6cb3;' \ ' -- 时间=12:00;模式=明;平台=我去图书馆' zl = '抢座;ycgxy;1234;355;' \ 'wechatSESS_ID=672c5459adb7c20f3a3f64e677dfdfebac2455b49c34e280;SERVERID=b9fc7bd86d2eed91b23d7347e0ee995e|1570632661|1570631371' \ ';—-;时间=6:00;模式=明;平台=我去图书馆' zl = '捡漏, bjtu,0,0 wechatSESS_ID=14a69992ca6af9a2e11b4c3ba270a752a6d28a49fc116272' zl = '#抢座; bjtu; 0; 046; 0; 045; ' \ 'wechatSESS_ID=d251fce0daa72515a1d71eefb5b55debc1cbae9d1a32d721; ' \ 'SERVERID=d3936289adfff6c3874a2579058ac651|1570707938|1570707927 ' \ '-- t=17:20 模式=今' zl = 'test 捡漏, tyut, 323, 0, 324,0, wechatSESS_ID=0db7db1b5250d65e4d1c2af0a707296c0f689afc5f901273 SERVERID=b9fc7bd86d2eed91b23d7347e0ee995e|1570926044|1570924907 -- 时间=08:40, 模式=今天' # # zl = '添加学校;sxau;wechatSESS_ID=65dece8f05041ee8c849e5ec5c622a14 -- pt=lxz' # 'SERVERID=b9fc7bd86d2eed91b23d7347e0ee995e|1570237808|1570237801 ' + \ # ' SERVERID=d3936289adfff6c3874a2579058ac651|1570237808|1570237801 ' + \ # zl = '添加; ycgxy; wechat_sess_id=672c5459adb7c20f3a3f64e677dfdfebac2455b49c34e280;' # zl = '抢座;bjtu;324;10;323;85;SERVERID=b9fc7bd86d2eed91b23d7347e0ee995e|1570448431|1570448430;wechatSESS_ID=65bf8d12c374bf3b1fc466a279bd5ba04f2d9fe375ee717f;' # zl = '#jl; tyut; 311; 100; 313; 91;' + \ # ' wechatSESS_ID=ed024e28d954710784abf2f385eb9ee1d7de4c53bfdfd898; SERVERID=d3936289adfff6c3874a2579058ac651|1570400154|1570400153;' +\ # '-- t=07:00 平台=wqtsg; 今明=j' # zl = 'jljg' # zl = ''' # GET /index.php/url/auth.html?r=%2Findex.php%2Freserve%2Findex.html%3Ff%3Dwechat%26n%3D5d9bd23e7dc9a&code=081elvY90k3kSy1WSDW90ZsgY90elvY6&state=1 HTTP/1.1 Host: wechat.laixuanzuo.com Connection: keep-alive Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Linux; Android 7.0; PRO 7 Plus Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044904 Mobile Safari/537.36 MMWEBID/4071 MicroMessenger/7.0.7.1521(0x27000736) Process/tools NetType/4G Language/zh_CN Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,image/wxpic,image/sharpp,image/apng,image/tpg,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,en-US;q=0.9 Cookie: FROM_TYPE=weixin; Hm_lvt_7838cef374eb966ae9ff502c68d6f098=1570464181; Hm_lpvt_7838cef374eb966ae9ff502c68d6f098=1570489433; wechatSESS_ID=85807fb3863be66e8b868e4dfce18da0 # ''' # zl = 'test 捡漏 sxau; 10281, 0; 0,0; wechatSESS_ID=89040c2998084ed651a8a7991ce11264 -- 时间=21:40 模式=今天 平台=来选座' # zl = 'test tj sxau; wechatSESS_ID=89040c2998084ed651a8a7991ce11264 -- 时间=21:40 模式=今天 平台=来选座' # zl = 'test jl, bjtu 323, 0, 323, 1 wechatSESS_ID=de2e1d47c50c59709ebb5ee102ea6f738092499495a61e5e SERVERID=b9fc7bd86d2eed91b23d7347e0ee995e|1572577791|1572577787 -- 模式=今天' zl = 'test tj, sxau wechatSESS_ID=0d9a58a026826c2f6aebb2d3926eb01d -- 平台=来选座' # zl = 'test cx, wnsfxy' # zl = 'test jl,wnsfxy, 10110, 0, 0 ,0, wechatSESS_ID=35ed243f92be7b748a21d53cce7179b9 -- 平台=来选座 模式=今天' zl = 'test jl;sxau;10238;086;10238;004;wechatSESS_ID=0d9a58a026826c2f6aebb2d3926eb01d -- 平台=来选座' res = handle_msg(userid='userid_test_' + str(i), content=zl, my_id='my_id_' + str(i), LOCAL=LOCAL) mc.client_close() debug_p('complete!\n', res)
[ "crawldata.get_name", "utils.Atask", "requests.post", "json.loads", "requests.Session", "random.choice", "utils.fill_cookies", "utils.MyMemcache", "utils.get_response", "utils.parse_grab_seat_cmd", "crawldata.refresh_school_info", "re.compile", "json.dumps", "utils.SqlAct", "utils.GBCF",...
[((456, 469), 'utils.Atask', 'utils.Atask', ([], {}), '()\n', (467, 469), False, 'import utils\n'), ((476, 488), 'utils.GBCF', 'utils.GBCF', ([], {}), '()\n', (486, 488), False, 'import utils\n'), ((683, 701), 'requests.Session', 'requests.Session', ([], {}), '()\n', (699, 701), False, 'import requests\n'), ((751, 765), 'utils.SqlAct', 'utils.SqlAct', ([], {}), '()\n', (763, 765), False, 'import utils\n'), ((782, 800), 'utils.MyMemcache', 'utils.MyMemcache', ([], {}), '()\n', (798, 800), False, 'import utils\n'), ((1748, 1827), 'requests.post', 'requests.post', (['api_url'], {'data': 'data', 'headers': "{'content-type': 'application/json'}"}), "(api_url, data=data, headers={'content-type': 'application/json'})\n", (1761, 1827), False, 'import requests\n'), ((1846, 1889), 'json.loads', 'json.loads', (['response.text'], {'encoding': '"""UTF-8"""'}), "(response.text, encoding='UTF-8')\n", (1856, 1889), False, 'import json\n'), ((2715, 2756), 'random.choice', 'random.choice', (['CmdFunction.face_ico[flag]'], {}), '(CmdFunction.face_ico[flag])\n', (2728, 2756), False, 'import random\n'), ((7338, 7378), 'utils.parse_extra_cmd', 'utils.parse_extra_cmd', ([], {'extra_cmd': 'content'}), '(extra_cmd=content)\n', (7359, 7378), False, 'import utils\n'), ((8113, 8218), 'utils.fill_cookies', 'utils.fill_cookies', ([], {'cookies': 'a_task.M_COOKIES', 'wechat_sess_id': 'wechat_sess_id', 'platform': 'a_task.platform'}), '(cookies=a_task.M_COOKIES, wechat_sess_id=wechat_sess_id,\n platform=a_task.platform)\n', (8131, 8218), False, 'import utils\n'), ((8268, 8443), 'utils.get_response', 'utils.get_response', ([], {'url': "a_task.CURRENT_URL['home_page']", 'sess': 'CF.sess', 'm_headers': 'a_task.M_HEADERS', 'm_cookies': 'a_task.M_COOKIES', 'verify_key': 'a_task.VERIFYKEY_OF_HOMEPAGE'}), "(url=a_task.CURRENT_URL['home_page'], sess=CF.sess,\n m_headers=a_task.M_HEADERS, m_cookies=a_task.M_COOKIES, verify_key=\n a_task.VERIFYKEY_OF_HOMEPAGE)\n", (8286, 8443), False, 'import utils\n'), ((8922, 8959), 'crawldata.get_name', 'crawldata.get_name', (['homepage_response'], {}), '(homepage_response)\n', (8940, 8959), False, 'import crawldata\n'), ((15545, 15587), 'utils.parse_grab_seat_cmd', 'utils.parse_grab_seat_cmd', ([], {'command': 'content'}), '(command=content)\n', (15570, 15587), False, 'import utils\n'), ((16942, 17047), 'utils.fill_cookies', 'utils.fill_cookies', ([], {'cookies': 'a_task.M_COOKIES', 'wechat_sess_id': 'wechat_sess_id', 'platform': 'a_task.platform'}), '(cookies=a_task.M_COOKIES, wechat_sess_id=wechat_sess_id,\n platform=a_task.platform)\n', (16960, 17047), False, 'import utils\n'), ((17189, 17364), 'utils.get_response', 'utils.get_response', ([], {'url': "a_task.CURRENT_URL['home_page']", 'sess': 'CF.sess', 'm_headers': 'a_task.M_HEADERS', 'm_cookies': 'a_task.M_COOKIES', 'verify_key': 'a_task.VERIFYKEY_OF_HOMEPAGE'}), "(url=a_task.CURRENT_URL['home_page'], sess=CF.sess,\n m_headers=a_task.M_HEADERS, m_cookies=a_task.M_COOKIES, verify_key=\n a_task.VERIFYKEY_OF_HOMEPAGE)\n", (17207, 17364), False, 'import utils\n'), ((18085, 18122), 'crawldata.get_name', 'crawldata.get_name', (['homepage_response'], {}), '(homepage_response)\n', (18103, 18122), False, 'import crawldata\n'), ((21376, 21418), 'utils.get_date', 'utils.get_date', ([], {'format': '"""%Y-%m-%d %H:%M:%S"""'}), "(format='%Y-%m-%d %H:%M:%S')\n", (21390, 21418), False, 'import utils\n'), ((10333, 10536), 'crawldata.refresh_school_info', 'crawldata.refresh_school_info', ([], {'homepage_response': 'homepage_response', 'a_task': 'a_task', 'schl_abbr': 'schl_abbr', 'sess': 'CF.sess', 'm_headers': 'a_task.M_HEADERS', 'm_cookies': 'a_task.M_COOKIES', 'sql_conn': 'sqlact.conn'}), '(homepage_response=homepage_response, a_task=\n a_task, schl_abbr=schl_abbr, sess=CF.sess, m_headers=a_task.M_HEADERS,\n m_cookies=a_task.M_COOKIES, sql_conn=sqlact.conn)\n', (10362, 10536), False, 'import crawldata\n'), ((12615, 12659), 're.compile', 're.compile', (['"""wechatSESS_ID\\\\=\\\\w+(?=[\\\\s;])"""'], {}), "('wechatSESS_ID\\\\=\\\\w+(?=[\\\\s;])')\n", (12625, 12659), False, 'import re\n'), ((21320, 21353), 'utils.get_date', 'utils.get_date', ([], {'format': '"""%H:%M:%S"""'}), "(format='%H:%M:%S')\n", (21334, 21353), False, 'import utils\n'), ((22245, 22268), 'json.dumps', 'json.dumps', (['others_info'], {}), '(others_info)\n', (22255, 22268), False, 'import json\n'), ((1696, 1712), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (1706, 1712), False, 'import json\n'), ((30708, 30727), 'random.choice', 'random.choice', (['info'], {}), '(info)\n', (30721, 30727), False, 'import random\n'), ((1552, 1572), 'random.randint', 'random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (1566, 1572), False, 'import random\n'), ((34194, 34227), 'random.choice', 'random.choice', (['no_match_cmd_reply'], {}), '(no_match_cmd_reply)\n', (34207, 34227), False, 'import random\n'), ((519, 535), 'utils.get_date', 'utils.get_date', ([], {}), '()\n', (533, 535), False, 'import utils\n'), ((34667, 34683), 'utils.get_date', 'utils.get_date', ([], {}), '()\n', (34681, 34683), False, 'import utils\n'), ((576, 592), 'utils.get_date', 'utils.get_date', ([], {}), '()\n', (590, 592), False, 'import utils\n')]
from day5 import parse from intcode import IntCode BLACK = 0 WHITE = 1 N = 1j LEFT, RIGHT = -1j, 1j def loop_run(program, current_color=BLACK): heading = N position = 0 painted_panels = {position: current_color} intcode = IntCode(program) while current_color is not None: input_value = current_color current_color = intcode.run(input_value) direction_value = intcode.run(input_value) if direction_value is None: break painted_panels[position] = current_color if direction_value not in (0, 1): raise RuntimeError("Invalid direction value: {}".format(direction_value)) heading = RIGHT * heading if direction_value else LEFT * heading position = position + heading current_color = painted_panels.get(position, BLACK) # print(f"direction={direction_value} color={current_color}") return painted_panels def print_image(panel, color=WHITE): values = list(panel.keys()) x_values = [c.real for c in values] y_values = [c.imag for c in values] max_width, min_width = max(x_values), min(x_values) max_height, min_height = max(y_values), min(y_values) width, height = int(max_width - min_width) + 1, int(max_height - min_height) print(width, height) # Reverse the axes for y in range(height, -1, -1): for x in range(width, 0, -1): position = x + min_width + 1j * y + (min_height * 1j) c = panel.get(position) e = "##" if c == color else " " end = "\n" if (x + 1) % width == 0 else "" print(e, end=end) if __name__ == "__main__": with open("../inputs/day11.input") as f: program = f.readline().strip() # Part I loop_run(parse(program), BLACK) # 2238 # Part II panel = loop_run(parse(program), WHITE) print_image(panel) # PKFPAZRP
[ "intcode.IntCode", "day5.parse" ]
[((243, 259), 'intcode.IntCode', 'IntCode', (['program'], {}), '(program)\n', (250, 259), False, 'from intcode import IntCode\n'), ((1779, 1793), 'day5.parse', 'parse', (['program'], {}), '(program)\n', (1784, 1793), False, 'from day5 import parse\n'), ((1846, 1860), 'day5.parse', 'parse', (['program'], {}), '(program)\n', (1851, 1860), False, 'from day5 import parse\n')]
import random from typing import Any, Dict, List, Optional, Type from mathy_core.expressions import MathExpression from mathy_core.problems import get_rand_term_templates, mathy_term_string from mathy_core.rule import BaseRule from mathy_core.rules import ( AssociativeSwapRule, CommutativeSwapRule, ConstantsSimplifyRule, DistributiveFactorOutRule, DistributiveMultiplyRule, VariableMultiplyRule, ) from mathy_core.util import TermEx, get_term_ex, get_terms from .. import time_step from ..env import MathyEnvProblem from ..state import MathyEnvState, MathyEnvStateStep, MathyObservation from ..types import EnvRewards, MathyEnvDifficulty, MathyEnvProblemArgs from .poly_simplify import PolySimplify class PolyHaystackLikeTerms(PolySimplify): """Act on any node in the expression that has another term like it somewhere else. For example in the problem: 2x + 8 + 13.2y + z^2 + 5x ^^---------------------^^ Applying any rule to one of those nodes is a win. The idea here is that in order to succeed at this task, the model must build a representation that can identify like terms in a large expression tree. """ def __init__(self, **kwargs: Any): super(PolyHaystackLikeTerms, self).__init__(**kwargs) def get_env_namespace(self) -> str: return "mathy.polynomials.haystack.like.terms" def get_penalizing_actions(self, state: MathyEnvState) -> List[Type[BaseRule]]: return [ CommutativeSwapRule, AssociativeSwapRule, DistributiveFactorOutRule, DistributiveMultiplyRule, ConstantsSimplifyRule, VariableMultiplyRule, ] def max_moves_fn( self, problem: MathyEnvProblem, config: MathyEnvProblemArgs ) -> int: return problem.complexity def transition_fn( self, env_state: MathyEnvState, expression: MathExpression, features: MathyObservation, ) -> Optional[time_step.TimeStep]: """If all like terms are siblings.""" agent = env_state.agent if len(agent.history) == 0: return None # History gets pushed before this fn, so history[-1] is the current state, # and history[-2] is the previous state. Find the previous state node we # acted on, and compare to that. curr_timestep: MathyEnvStateStep = agent.history[-1] last_timestep: MathyEnvStateStep = agent.history[-2] expression = self.parser.parse(last_timestep.raw) action_node = self.get_token_at_index(expression, curr_timestep.action[1]) touched_term = get_term_ex(action_node) term_nodes = get_terms(expression) # We have the token_index of the term that was acted on, now we have to see # if that term has any like siblings (not itself). We do this by ignoring the # term with a matching r_index to the node the agent acted on. # # find_nodes updates the `r_index` value on each node which is the token index BaseRule().find_nodes(expression) like_counts: Dict[str, int] = {} all_indices: Dict[str, List[int]] = {} max_index = 0 for term_node in term_nodes: assert term_node is not None and term_node.r_index is not None max_index = max(max_index, term_node.r_index) ex: Optional[TermEx] = get_term_ex(term_node) if ex is None: continue key = mathy_term_string(variable=ex.variable, exponent=ex.exponent) if key == "": key = "const" if key not in like_counts: like_counts[key] = 1 else: like_counts[key] += 1 if key not in all_indices: all_indices[key] = [term_node.r_index] else: all_indices[key].append(term_node.r_index) like_indices: Optional[List[int]] = None for key in all_indices.keys(): if len(all_indices[key]) > 1: like_indices = all_indices[key] if action_node is not None and touched_term is not None: touched_key = mathy_term_string( variable=touched_term.variable, exponent=touched_term.exponent ) if touched_key in like_counts and like_counts[touched_key] > 1: action_node.all_changed() return time_step.termination(features, self.get_win_signal(env_state)) if env_state.agent.moves_remaining <= 0: distances = [] if like_indices is not None: assert action_node is not None and action_node.r_index is not None for index in like_indices: distances.append(abs(index - action_node.r_index)) loss_magnitude = min(distances) / max_index else: loss_magnitude = 1.0 lose_signal = EnvRewards.LOSE - loss_magnitude return time_step.termination(features, lose_signal) return None def make_problem( self, min_terms: int, max_terms: int, like_terms: int, exponent_probability: float, ) -> str: assert min_terms <= max_terms, "min cannot be greater than max" assert like_terms < min_terms, "must have atleast one term that is not like" out_terms = [] total_terms = random.randint(min_terms, max_terms) num_diff_terms = total_terms - like_terms diff_term_tpls = get_rand_term_templates( num_diff_terms + 1, exponent_probability=exponent_probability ) like_term_tpl = diff_term_tpls[-1] diff_term_tpls = diff_term_tpls[:-1] for i in range(like_terms): out_terms.append(like_term_tpl.make()) for tpl in diff_term_tpls: out_terms.append(tpl.make()) random.shuffle(out_terms) problem = " + ".join(out_terms) return problem def problem_fn(self, params: MathyEnvProblemArgs) -> MathyEnvProblem: if params.difficulty == MathyEnvDifficulty.easy: text = self.make_problem( min_terms=3, max_terms=8, like_terms=2, exponent_probability=0.3 ) elif params.difficulty == MathyEnvDifficulty.normal: text = self.make_problem( min_terms=4, max_terms=7, like_terms=2, exponent_probability=0.5 ) elif params.difficulty == MathyEnvDifficulty.hard: text = self.make_problem( min_terms=5, max_terms=12, like_terms=2, exponent_probability=0.4 ) else: raise ValueError(f"Unknown difficulty: {params.difficulty}") return MathyEnvProblem(text, 2, self.get_env_namespace())
[ "mathy_core.util.get_term_ex", "mathy_core.util.get_terms", "random.shuffle", "mathy_core.problems.mathy_term_string", "mathy_core.rule.BaseRule", "mathy_core.problems.get_rand_term_templates", "random.randint" ]
[((2647, 2671), 'mathy_core.util.get_term_ex', 'get_term_ex', (['action_node'], {}), '(action_node)\n', (2658, 2671), False, 'from mathy_core.util import TermEx, get_term_ex, get_terms\n'), ((2694, 2715), 'mathy_core.util.get_terms', 'get_terms', (['expression'], {}), '(expression)\n', (2703, 2715), False, 'from mathy_core.util import TermEx, get_term_ex, get_terms\n'), ((5450, 5486), 'random.randint', 'random.randint', (['min_terms', 'max_terms'], {}), '(min_terms, max_terms)\n', (5464, 5486), False, 'import random\n'), ((5562, 5653), 'mathy_core.problems.get_rand_term_templates', 'get_rand_term_templates', (['(num_diff_terms + 1)'], {'exponent_probability': 'exponent_probability'}), '(num_diff_terms + 1, exponent_probability=\n exponent_probability)\n', (5585, 5653), False, 'from mathy_core.problems import get_rand_term_templates, mathy_term_string\n'), ((5932, 5957), 'random.shuffle', 'random.shuffle', (['out_terms'], {}), '(out_terms)\n', (5946, 5957), False, 'import random\n'), ((3412, 3434), 'mathy_core.util.get_term_ex', 'get_term_ex', (['term_node'], {}), '(term_node)\n', (3423, 3434), False, 'from mathy_core.util import TermEx, get_term_ex, get_terms\n'), ((3506, 3567), 'mathy_core.problems.mathy_term_string', 'mathy_term_string', ([], {'variable': 'ex.variable', 'exponent': 'ex.exponent'}), '(variable=ex.variable, exponent=ex.exponent)\n', (3523, 3567), False, 'from mathy_core.problems import get_rand_term_templates, mathy_term_string\n'), ((4197, 4283), 'mathy_core.problems.mathy_term_string', 'mathy_term_string', ([], {'variable': 'touched_term.variable', 'exponent': 'touched_term.exponent'}), '(variable=touched_term.variable, exponent=touched_term.\n exponent)\n', (4214, 4283), False, 'from mathy_core.problems import get_rand_term_templates, mathy_term_string\n'), ((3062, 3072), 'mathy_core.rule.BaseRule', 'BaseRule', ([], {}), '()\n', (3070, 3072), False, 'from mathy_core.rule import BaseRule\n')]
# -*- coding: utf-8 -*- """ Created on Wed May 09 11:41:19 2018 @author: Prodipta """ from enum import Enum import time import datetime import pytz import pandas as pd class ClockEvents(Enum): BAR = 0 SESSION_START = 1 SESSION_END = 2 MINUTE_END = 3 BEFORE_TRADING_START_BAR = 4 HEART_BEAT = 5 END_CLOCK = 6 class RealTimeClock: def __init__(self,*args, **kwargs): self.lifetime = kwargs.pop('lifetime', 200) self.heartbeat = kwargs.pop('heartbeat', 5) self.timezone = kwargs.pop('timezone', 'Etc/UTC') self.market_open_time = kwargs.pop('market_open',datetime.time(9,15,0)) self.market_close_time = kwargs.pop('market_open',datetime.time(15,30,0)) self.before_trading_start_minute = kwargs.pop('before_trading_start_minute',datetime.time(8,45,0)) self.is_market_open = kwargs.pop('is_market_open', lambda x:True) self.minute_emission = kwargs.pop('minute_emission', True) self.timestamp = None self.date = None self.time = None self.before_trading_start = True self.current_date = None self.kill = False self.get_time_now() def get_time_now(self): tz = pytz.timezone(self.timezone) dt = datetime.datetime.now(tz) self.timestamp = pd.Timestamp(dt, tz= 'Etc/UTC') self.date = dt.date() self.time = dt.time() def is_active_session(self): return self.is_market_open(self.date) def is_in_session(self): if not self.is_active_session(): return False if self.time >= self.market_open_time and self.time <= self.market_close_time: return True return False def is_session_start(self): if self.current_date is None and self.time >= self.market_open_time: #self.current_date = self.date return True return False def is_session_end(self): if self.time > self.market_close_time and self.current_date is not None: #self.current_date = None return True return False def is_before_trading_start(self): if self.before_trading_start and self.current_date is None and self.time >= self.before_trading_start_minute: return True return False def reset_clock(self): self.before_trading_start = True self.current_date = None self.kill = False def pause_clock(self): self.kill = True def close(self): self.reset_clock() raise GeneratorExit def __iter__(self): try: while not self.kill: self.get_time_now() loop_start_time = time.time() if self.is_before_trading_start(): self.before_trading_start = False yield self.timestamp, ClockEvents.BEFORE_TRADING_START_BAR if self.is_session_start(): self.current_date = self.date yield self.timestamp, ClockEvents.SESSION_START if self.is_session_end(): self.current_date = None self.before_trading_start = True yield self.timestamp, ClockEvents.SESSION_END if self.is_in_session(): yield self.timestamp, ClockEvents.BAR if self.minute_emission: yield self.timestamp, ClockEvents.MINUTE_END else: yield self.timestamp, ClockEvents.HEART_BEAT loop_end_time = time.time() time_left = round(self.heartbeat - (loop_end_time - loop_start_time)) if time_left > 0: time.sleep(time_left) except GeneratorExit: self.reset_clock() return finally: self.reset_clock() return #yield self.timestamp, ClockEvents.END_CLOCK self.reset_clock() return #realtime_clock = RealTimeClock(timezone='Asia/Calcutta') #i = 0 #for t,e in realtime_clock: # print('{}:{}'.format(t,e)) # i = i+1 # if i>6: # print('we are done, exit the clock loop') # #realtime_clock.kill = True # break # #realtime_clock.close()
[ "pytz.timezone", "datetime.time", "time.sleep", "datetime.datetime.now", "pandas.Timestamp", "time.time" ]
[((1257, 1285), 'pytz.timezone', 'pytz.timezone', (['self.timezone'], {}), '(self.timezone)\n', (1270, 1285), False, 'import pytz\n'), ((1299, 1324), 'datetime.datetime.now', 'datetime.datetime.now', (['tz'], {}), '(tz)\n', (1320, 1324), False, 'import datetime\n'), ((1350, 1380), 'pandas.Timestamp', 'pd.Timestamp', (['dt'], {'tz': '"""Etc/UTC"""'}), "(dt, tz='Etc/UTC')\n", (1362, 1380), True, 'import pandas as pd\n'), ((619, 642), 'datetime.time', 'datetime.time', (['(9)', '(15)', '(0)'], {}), '(9, 15, 0)\n', (632, 642), False, 'import datetime\n'), ((700, 724), 'datetime.time', 'datetime.time', (['(15)', '(30)', '(0)'], {}), '(15, 30, 0)\n', (713, 724), False, 'import datetime\n'), ((808, 831), 'datetime.time', 'datetime.time', (['(8)', '(45)', '(0)'], {}), '(8, 45, 0)\n', (821, 831), False, 'import datetime\n'), ((2789, 2800), 'time.time', 'time.time', ([], {}), '()\n', (2798, 2800), False, 'import time\n'), ((3737, 3748), 'time.time', 'time.time', ([], {}), '()\n', (3746, 3748), False, 'import time\n'), ((3890, 3911), 'time.sleep', 'time.sleep', (['time_left'], {}), '(time_left)\n', (3900, 3911), False, 'import time\n')]
#!/usr/bin/python3 # -*- coding: utf-8 -*- # (c) B.Kerler 2018-2021 import argparse import os import sys import logging from enum import Enum from struct import unpack, pack from binascii import hexlify try: from edl.Library.utils import LogBase, structhelper except: from utils import LogBase, structhelper class gpt(metaclass=LogBase): class gpt_header: def __init__(self, data): sh = structhelper(data) self.signature = sh.bytes(8) self.revision = sh.dword() self.header_size = sh.dword() self.crc32 = sh.dword() self.reserved = sh.dword() self.current_lba = sh.qword() self.backup_lba = sh.qword() self.first_usable_lba = sh.qword() self.last_usable_lba = sh.qword() self.disk_guid = sh.bytes(16) self.part_entry_start_lba = sh.qword() self.num_part_entries = sh.dword() self.part_entry_size = sh.dword() class gpt_partition: def __init__(self, data): sh = structhelper(data) self.type = sh.bytes(16) self.unique = sh.bytes(16) self.first_lba = sh.qword() self.last_lba = sh.qword() self.flags = sh.qword() self.name = sh.string(72) class efi_type(Enum): EFI_UNUSED = 0x00000000 EFI_MBR = 0x024DEE41 EFI_SYSTEM = 0xC12A7328 EFI_BIOS_BOOT = 0x21686148 EFI_IFFS = 0xD3BFE2DE EFI_SONY_BOOT = 0xF4019732 EFI_LENOVO_BOOT = 0xBFBFAFE7 EFI_MSR = 0xE3C9E316 EFI_BASIC_DATA = 0xEBD0A0A2 EFI_LDM_META = 0x5808C8AA EFI_LDM = 0xAF9B60A0 EFI_RECOVERY = 0xDE94BBA4 EFI_GPFS = 0x37AFFC90 EFI_STORAGE_SPACES = 0xE75CAF8F EFI_HPUX_DATA = 0x75894C1E EFI_HPUX_SERVICE = 0xE2A1E728 EFI_LINUX_DAYA = 0x0FC63DAF EFI_LINUX_RAID = 0xA19D880F EFI_LINUX_ROOT32 = 0x44479540 EFI_LINUX_ROOT64 = 0x4F68BCE3 EFI_LINUX_ROOT_ARM32 = 0x69DAD710 EFI_LINUX_ROOT_ARM64 = 0xB921B045 EFI_LINUX_SWAP = 0x0657FD6D EFI_LINUX_LVM = 0xE6D6D379 EFI_LINUX_HOME = 0x933AC7E1 EFI_LINUX_SRV = 0x3B8F8425 EFI_LINUX_DM_CRYPT = 0x7FFEC5C9 EFI_LINUX_LUKS = 0xCA7D7CCB EFI_LINUX_RESERVED = 0x8DA63339 EFI_FREEBSD_BOOT = 0x83BD6B9D EFI_FREEBSD_DATA = 0x516E7CB4 EFI_FREEBSD_SWAP = 0x516E7CB5 EFI_FREEBSD_UFS = 0x516E7CB6 EFI_FREEBSD_VINUM = 0x516E7CB8 EFI_FREEBSD_ZFS = 0x516E7CBA EFI_OSX_HFS = 0x48465300 EFI_OSX_UFS = 0x55465300 EFI_OSX_ZFS = 0x6A898CC3 EFI_OSX_RAID = 0x52414944 EFI_OSX_RAID_OFFLINE = 0x52414944 EFI_OSX_RECOVERY = 0x426F6F74 EFI_OSX_LABEL = 0x4C616265 EFI_OSX_TV_RECOVERY = 0x5265636F EFI_OSX_CORE_STORAGE = 0x53746F72 EFI_SOLARIS_BOOT = 0x6A82CB45 EFI_SOLARIS_ROOT = 0x6A85CF4D EFI_SOLARIS_SWAP = 0x6A87C46F EFI_SOLARIS_BACKUP = 0x6A8B642B EFI_SOLARIS_USR = 0x6A898CC3 EFI_SOLARIS_VAR = 0x6A8EF2E9 EFI_SOLARIS_HOME = 0x6A90BA39 EFI_SOLARIS_ALTERNATE = 0x6A9283A5 EFI_SOLARIS_RESERVED1 = 0x6A945A3B EFI_SOLARIS_RESERVED2 = 0x6A9630D1 EFI_SOLARIS_RESERVED3 = 0x6A980767 EFI_SOLARIS_RESERVED4 = 0x6A96237F EFI_SOLARIS_RESERVED5 = 0x6A8D2AC7 EFI_NETBSD_SWAP = 0x49F48D32 EFI_NETBSD_FFS = 0x49F48D5A EFI_NETBSD_LFS = 0x49F48D82 EFI_NETBSD_RAID = 0x49F48DAA EFI_NETBSD_CONCAT = 0x2DB519C4 EFI_NETBSD_ENCRYPT = 0x2DB519EC EFI_CHROMEOS_KERNEL = 0xFE3A2A5D EFI_CHROMEOS_ROOTFS = 0x3CB8E202 EFI_CHROMEOS_FUTURE = 0x2E0A753D EFI_HAIKU = 0x42465331 EFI_MIDNIGHTBSD_BOOT = 0x85D5E45E EFI_MIDNIGHTBSD_DATA = 0x85D5E45A EFI_MIDNIGHTBSD_SWAP = 0x85D5E45B EFI_MIDNIGHTBSD_UFS = 0x0394EF8B EFI_MIDNIGHTBSD_VINUM = 0x85D5E45C EFI_MIDNIGHTBSD_ZFS = 0x85D5E45D EFI_CEPH_JOURNAL = 0x45B0969E EFI_CEPH_ENCRYPT = 0x45B0969E EFI_CEPH_OSD = 0x4FBD7E29 EFI_CEPH_ENCRYPT_OSD = 0x4FBD7E29 EFI_CEPH_CREATE = 0x89C57F98 EFI_CEPH_ENCRYPT_CREATE = 0x89C57F98 EFI_OPENBSD = 0x824CC7A0 EFI_QNX = 0xCEF5A9AD EFI_PLAN9 = 0xC91818F9 EFI_VMWARE_VMKCORE = 0x9D275380 EFI_VMWARE_VMFS = 0xAA31E02A EFI_VMWARE_RESERVED = 0x9198EFFC def __init__(self, num_part_entries=0, part_entry_size=0, part_entry_start_lba=0, loglevel=logging.INFO, *args, **kwargs): self.num_part_entries = num_part_entries self.__logger = self.__logger self.part_entry_size = part_entry_size self.part_entry_start_lba = part_entry_start_lba self.totalsectors = None self.header = None self.sectorsize = None self.partentries = [] self.error = self.__logger.error self.__logger.setLevel(loglevel) if loglevel == logging.DEBUG: logfilename = "log.txt" fh = logging.FileHandler(logfilename) self.__logger.addHandler(fh) def parseheader(self, gptdata, sectorsize=512): return self.gpt_header(gptdata[sectorsize:sectorsize + 0x5C]) def parse(self, gptdata, sectorsize=512): self.header = self.gpt_header(gptdata[sectorsize:sectorsize + 0x5C]) self.sectorsize = sectorsize if self.header.signature != b"EFI PART": return False if self.header.revision != 0x10000: self.error("Unknown GPT revision.") return False if self.part_entry_start_lba != 0: start = self.part_entry_start_lba else: start = self.header.part_entry_start_lba * sectorsize entrysize = self.header.part_entry_size self.partentries = [] class partf: unique = b"" first_lba = 0 last_lba = 0 flags = 0 sector = 0 sectors = 0 type = b"" name = "" num_part_entries = self.header.num_part_entries for idx in range(0, num_part_entries): data = gptdata[start + (idx * entrysize):start + (idx * entrysize) + entrysize] if int(hexlify(data[16:32]), 16) == 0: break partentry = self.gpt_partition(data) pa = partf() guid1 = unpack("<I", partentry.unique[0:0x4])[0] guid2 = unpack("<H", partentry.unique[0x4:0x6])[0] guid3 = unpack("<H", partentry.unique[0x6:0x8])[0] guid4 = unpack("<H", partentry.unique[0x8:0xA])[0] guid5 = hexlify(partentry.unique[0xA:0x10]).decode('utf-8') pa.unique = "{:08x}-{:04x}-{:04x}-{:04x}-{}".format(guid1, guid2, guid3, guid4, guid5) pa.sector = partentry.first_lba pa.sectors = partentry.last_lba - partentry.first_lba + 1 pa.flags = partentry.flags type = int(unpack("<I", partentry.type[0:0x4])[0]) try: pa.type = self.efi_type(type).name except: pa.type = hex(type) pa.name = partentry.name.replace(b"\x00\x00", b"").decode('utf-16') if pa.type == "EFI_UNUSED": continue self.partentries.append(pa) self.totalsectors = self.header.last_usable_lba + 34 return True def print(self): print(self.tostring()) def tostring(self): mstr = "\nGPT Table:\n-------------\n" for partition in self.partentries: mstr += ("{:20} Offset 0x{:016x}, Length 0x{:016x}, Flags 0x{:08x}, UUID {}, Type {}\n".format( partition.name + ":", partition.sector * self.sectorsize, partition.sectors * self.sectorsize, partition.flags, partition.unique, partition.type)) mstr += ("\nTotal disk size:0x{:016x}, sectors:0x{:016x}\n".format(self.totalsectors * self.sectorsize, self.totalsectors)) return mstr def generate_rawprogram(self, lun, sectorsize, directory): fname = "rawprogram" + str(lun) + ".xml" with open(os.path.join(directory, fname), "wb") as wf: mstr = "<?xml version=\"1.0\" ?>\n<data>\n" partofsingleimage = "false" readbackverify = "false" sparse = "false" for partition in self.partentries: filename = partition.name + ".bin" mstr += f"\t<program SECTOR_SIZE_IN_BYTES=\"{sectorsize}\" " + \ f"file_sector_offset=\"0\" " \ f"filename=\"{filename}\" " + \ f"label=\"{partition.name}\" " \ f"num_partition_sectors=\"{partition.sectors}\" " + \ f"partofsingleimage=\"{partofsingleimage}\" " \ f"physical_partition_number=\"{str(lun)}\" " + \ f"readbackverify=\"{readbackverify}\" " \ f"size_in_KB=\"{(partition.sectors * sectorsize / 1024):.1f}\" " \ f"sparse=\"{sparse}\" " + \ f"start_byte_hex=\"{hex(partition.sector * sectorsize)}\" " \ f"start_sector=\"{partition.sector}\"/>\n" partofsingleimage = "true" sectors = self.header.first_usable_lba mstr += f"\t<program SECTOR_SIZE_IN_BYTES=\"{sectorsize}\" " + \ f"file_sector_offset=\"0\" " + \ f"filename=\"gpt_main{str(lun)}.bin\" " + \ f"label=\"PrimaryGPT\" " + \ f"num_partition_sectors=\"{sectors}\" " + \ f"partofsingleimage=\"{partofsingleimage}\" " + \ f"physical_partition_number=\"{str(lun)}\" " + \ f"readbackverify=\"{readbackverify}\" " + \ f"size_in_KB=\"{(sectors * sectorsize / 1024):.1f}\" " + \ f"sparse=\"{sparse}\" " + \ f"start_byte_hex=\"0x0\" " + \ f"start_sector=\"0\"/>\n" sectors = self.header.first_usable_lba - 1 mstr += f"\t<program SECTOR_SIZE_IN_BYTES=\"{sectorsize}\" " + \ f"file_sector_offset=\"0\" " + \ f"filename=\"gpt_backup{str(lun)}.bin\" " + \ f"label=\"BackupGPT\" " + \ f"num_partition_sectors=\"{sectors}\" " + \ f"partofsingleimage=\"{partofsingleimage}\" " + \ f"physical_partition_number=\"{str(lun)}\" " + \ f"readbackverify=\"{readbackverify}\" " + \ f"size_in_KB=\"{(sectors * sectorsize / 1024):.1f}\" " + \ f"sparse=\"{sparse}\" " + \ f"start_byte_hex=\"({sectorsize}*NUM_DISK_SECTORS)-{sectorsize * sectors}.\" " + \ f"start_sector=\"NUM_DISK_SECTORS-{sectors}.\"/>\n" mstr += "</data>" wf.write(bytes(mstr, 'utf-8')) print(f"Wrote partition xml as {fname}") def print_gptfile(self, filename): try: filesize = os.stat(filename).st_size with open(filename, "rb") as rf: size = min(32 * 4096, filesize) data = rf.read(size) for sectorsize in [512, 4096]: result = self.parse(data, sectorsize) if result: break if result: print(self.tostring()) return result except Exception as e: self.error(str(e)) return "" def test_gpt(self): res = self.print_gptfile(os.path.join("TestFiles", "gpt_sm8180x.bin")) assert res, "GPT Partition wasn't decoded properly" if __name__ == "__main__": parser = argparse.ArgumentParser(description="GPT utils") subparsers = parser.add_subparsers(dest="command", help='sub-command help') parser_print = subparsers.add_parser("print", help="Print the gpt table") parser_print.add_argument("image", help="The path of the GPT disk image") parser_test = subparsers.add_parser("test", help="Run self-test") parser_extract = subparsers.add_parser("extract", help="Extract the partitions") parser_extract.add_argument("image", help="The path of the GPT disk image") parser_extract.add_argument("-out", "-o", help="The path to extract the partitions") parser_extract.add_argument("-partition", "-p", help="Extract specific partitions (separated by comma)") args = parser.parse_args() if args.command not in ["print", "extract", "test"]: parser.error("Command is mandatory") gp = gpt() if args.command == "print": if not os.path.exists(args.image): print(f"File {args.image} does not exist. Aborting.") sys.exit(1) gp.print_gptfile(args.image) elif args.command == "test": gp.test_gpt() elif args.command == "extract": if not os.path.exists(args.image): print(f"File {args.image} does not exist. Aborting.") sys.exit(1) filesize = os.stat(args.image).st_size with open(args.image, "rb", buffering=1024 * 1024) as rf: data = rf.read(min(32 * 4096, filesize)) ssize = None for sectorsize in [512, 4096]: result = gp.parse(data, sectorsize) if result: ssize = sectorsize break if ssize is not None: for partition in gp.partentries: if args.partition is not None: if partition != args.partition: continue name = partition.name start = partition.sector * ssize length = partition.sectors * ssize out = args.out if out is None: out = "." if not os.path.exists(out): os.makedirs(out) filename = os.path.join(out, name) rf.seek(start) bytestoread = length with open(filename, "wb", buffering=1024 * 1024) as wf: while bytestoread > 0: size = min(bytestoread, 0x200000) rf.read(size) wf.write(size) bytestoread -= size print(f"Extracting {name} to {filename} at {hex(start)}, length {hex(length)}")
[ "os.path.exists", "argparse.ArgumentParser", "os.makedirs", "binascii.hexlify", "os.path.join", "struct.unpack", "logging.FileHandler", "sys.exit", "os.stat", "utils.structhelper" ]
[((12099, 12147), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""GPT utils"""'}), "(description='GPT utils')\n", (12122, 12147), False, 'import argparse\n'), ((422, 440), 'utils.structhelper', 'structhelper', (['data'], {}), '(data)\n', (434, 440), False, 'from utils import LogBase, structhelper\n'), ((1077, 1095), 'utils.structhelper', 'structhelper', (['data'], {}), '(data)\n', (1089, 1095), False, 'from utils import LogBase, structhelper\n'), ((5165, 5197), 'logging.FileHandler', 'logging.FileHandler', (['logfilename'], {}), '(logfilename)\n', (5184, 5197), False, 'import logging\n'), ((11951, 11995), 'os.path.join', 'os.path.join', (['"""TestFiles"""', '"""gpt_sm8180x.bin"""'], {}), "('TestFiles', 'gpt_sm8180x.bin')\n", (11963, 11995), False, 'import os\n'), ((13017, 13043), 'os.path.exists', 'os.path.exists', (['args.image'], {}), '(args.image)\n', (13031, 13043), False, 'import os\n'), ((13123, 13134), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (13131, 13134), False, 'import sys\n'), ((6538, 6573), 'struct.unpack', 'unpack', (['"""<I"""', 'partentry.unique[0:4]'], {}), "('<I', partentry.unique[0:4])\n", (6544, 6573), False, 'from struct import unpack, pack\n'), ((6599, 6634), 'struct.unpack', 'unpack', (['"""<H"""', 'partentry.unique[4:6]'], {}), "('<H', partentry.unique[4:6])\n", (6605, 6634), False, 'from struct import unpack, pack\n'), ((6662, 6697), 'struct.unpack', 'unpack', (['"""<H"""', 'partentry.unique[6:8]'], {}), "('<H', partentry.unique[6:8])\n", (6668, 6697), False, 'from struct import unpack, pack\n'), ((6725, 6761), 'struct.unpack', 'unpack', (['"""<H"""', 'partentry.unique[8:10]'], {}), "('<H', partentry.unique[8:10])\n", (6731, 6761), False, 'from struct import unpack, pack\n'), ((8358, 8388), 'os.path.join', 'os.path.join', (['directory', 'fname'], {}), '(directory, fname)\n', (8370, 8388), False, 'import os\n'), ((11391, 11408), 'os.stat', 'os.stat', (['filename'], {}), '(filename)\n', (11398, 11408), False, 'import os\n'), ((6390, 6410), 'binascii.hexlify', 'hexlify', (['data[16:32]'], {}), '(data[16:32])\n', (6397, 6410), False, 'from binascii import hexlify\n'), ((6788, 6820), 'binascii.hexlify', 'hexlify', (['partentry.unique[10:16]'], {}), '(partentry.unique[10:16])\n', (6795, 6820), False, 'from binascii import hexlify\n'), ((7115, 7148), 'struct.unpack', 'unpack', (['"""<I"""', 'partentry.type[0:4]'], {}), "('<I', partentry.type[0:4])\n", (7121, 7148), False, 'from struct import unpack, pack\n'), ((13278, 13304), 'os.path.exists', 'os.path.exists', (['args.image'], {}), '(args.image)\n', (13292, 13304), False, 'import os\n'), ((13384, 13395), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (13392, 13395), False, 'import sys\n'), ((13415, 13434), 'os.stat', 'os.stat', (['args.image'], {}), '(args.image)\n', (13422, 13434), False, 'import os\n'), ((14376, 14399), 'os.path.join', 'os.path.join', (['out', 'name'], {}), '(out, name)\n', (14388, 14399), False, 'import os\n'), ((14283, 14302), 'os.path.exists', 'os.path.exists', (['out'], {}), '(out)\n', (14297, 14302), False, 'import os\n'), ((14328, 14344), 'os.makedirs', 'os.makedirs', (['out'], {}), '(out)\n', (14339, 14344), False, 'import os\n')]
# Copyright 21 May 2005 - (c) 2005 <NAME> <<EMAIL>> # Copyright 2005-2007 <NAME> <<EMAIL>> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from __future__ import absolute_import import contextlib import struct import sys import threading from .i18n import _ from . import ( encoding, error, pycompat, util, wireprototypes, wireprotov1server, wireprotov2server, ) from .utils import ( cborutil, interfaceutil, procutil, ) stringio = util.stringio urlerr = util.urlerr urlreq = util.urlreq HTTP_OK = 200 HGTYPE = 'application/mercurial-0.1' HGTYPE2 = 'application/mercurial-0.2' HGERRTYPE = 'application/hg-error' SSHV1 = wireprototypes.SSHV1 SSHV2 = wireprototypes.SSHV2 def decodevaluefromheaders(req, headerprefix): """Decode a long value from multiple HTTP request headers. Returns the value as a bytes, not a str. """ chunks = [] i = 1 while True: v = req.headers.get(b'%s-%d' % (headerprefix, i)) if v is None: break chunks.append(pycompat.bytesurl(v)) i += 1 return ''.join(chunks) @interfaceutil.implementer(wireprototypes.baseprotocolhandler) class httpv1protocolhandler(object): def __init__(self, req, ui, checkperm): self._req = req self._ui = ui self._checkperm = checkperm self._protocaps = None @property def name(self): return 'http-v1' def getargs(self, args): knownargs = self._args() data = {} keys = args.split() for k in keys: if k == '*': star = {} for key in knownargs.keys(): if key != 'cmd' and key not in keys: star[key] = knownargs[key][0] data['*'] = star else: data[k] = knownargs[k][0] return [data[k] for k in keys] def _args(self): args = self._req.qsparams.asdictoflists() postlen = int(self._req.headers.get(b'X-HgArgs-Post', 0)) if postlen: args.update(urlreq.parseqs( self._req.bodyfh.read(postlen), keep_blank_values=True)) return args argvalue = decodevaluefromheaders(self._req, b'X-HgArg') args.update(urlreq.parseqs(argvalue, keep_blank_values=True)) return args def getprotocaps(self): if self._protocaps is None: value = decodevaluefromheaders(self._req, b'X-HgProto') self._protocaps = set(value.split(' ')) return self._protocaps def getpayload(self): # Existing clients *always* send Content-Length. length = int(self._req.headers[b'Content-Length']) # If httppostargs is used, we need to read Content-Length # minus the amount that was consumed by args. length -= int(self._req.headers.get(b'X-HgArgs-Post', 0)) return util.filechunkiter(self._req.bodyfh, limit=length) @contextlib.contextmanager def mayberedirectstdio(self): oldout = self._ui.fout olderr = self._ui.ferr out = util.stringio() try: self._ui.fout = out self._ui.ferr = out yield out finally: self._ui.fout = oldout self._ui.ferr = olderr def client(self): return 'remote:%s:%s:%s' % ( self._req.urlscheme, urlreq.quote(self._req.remotehost or ''), urlreq.quote(self._req.remoteuser or '')) def addcapabilities(self, repo, caps): caps.append(b'batch') caps.append('httpheader=%d' % repo.ui.configint('server', 'maxhttpheaderlen')) if repo.ui.configbool('experimental', 'httppostargs'): caps.append('httppostargs') # FUTURE advertise 0.2rx once support is implemented # FUTURE advertise minrx and mintx after consulting config option caps.append('httpmediatype=0.1rx,0.1tx,0.2tx') compengines = wireprototypes.supportedcompengines(repo.ui, util.SERVERROLE) if compengines: comptypes = ','.join(urlreq.quote(e.wireprotosupport().name) for e in compengines) caps.append('compression=%s' % comptypes) return caps def checkperm(self, perm): return self._checkperm(perm) # This method exists mostly so that extensions like remotefilelog can # disable a kludgey legacy method only over http. As of early 2018, # there are no other known users, so with any luck we can discard this # hook if remotefilelog becomes a first-party extension. def iscmd(cmd): return cmd in wireprotov1server.commands def handlewsgirequest(rctx, req, res, checkperm): """Possibly process a wire protocol request. If the current request is a wire protocol request, the request is processed by this function. ``req`` is a ``parsedrequest`` instance. ``res`` is a ``wsgiresponse`` instance. Returns a bool indicating if the request was serviced. If set, the caller should stop processing the request, as a response has already been issued. """ # Avoid cycle involving hg module. from .hgweb import common as hgwebcommon repo = rctx.repo # HTTP version 1 wire protocol requests are denoted by a "cmd" query # string parameter. If it isn't present, this isn't a wire protocol # request. if 'cmd' not in req.qsparams: return False cmd = req.qsparams['cmd'] # The "cmd" request parameter is used by both the wire protocol and hgweb. # While not all wire protocol commands are available for all transports, # if we see a "cmd" value that resembles a known wire protocol command, we # route it to a protocol handler. This is better than routing possible # wire protocol requests to hgweb because it prevents hgweb from using # known wire protocol commands and it is less confusing for machine # clients. if not iscmd(cmd): return False # The "cmd" query string argument is only valid on the root path of the # repo. e.g. ``/?cmd=foo``, ``/repo?cmd=foo``. URL paths within the repo # like ``/blah?cmd=foo`` are not allowed. So don't recognize the request # in this case. We send an HTTP 404 for backwards compatibility reasons. if req.dispatchpath: res.status = hgwebcommon.statusmessage(404) res.headers['Content-Type'] = HGTYPE # TODO This is not a good response to issue for this request. This # is mostly for BC for now. res.setbodybytes('0\n%s\n' % b'Not Found') return True proto = httpv1protocolhandler(req, repo.ui, lambda perm: checkperm(rctx, req, perm)) # The permissions checker should be the only thing that can raise an # ErrorResponse. It is kind of a layer violation to catch an hgweb # exception here. So consider refactoring into a exception type that # is associated with the wire protocol. try: _callhttp(repo, req, res, proto, cmd) except hgwebcommon.ErrorResponse as e: for k, v in e.headers: res.headers[k] = v res.status = hgwebcommon.statusmessage(e.code, pycompat.bytestr(e)) # TODO This response body assumes the failed command was # "unbundle." That assumption is not always valid. res.setbodybytes('0\n%s\n' % pycompat.bytestr(e)) return True def _availableapis(repo): apis = set() # Registered APIs are made available via config options of the name of # the protocol. for k, v in API_HANDLERS.items(): section, option = v['config'] if repo.ui.configbool(section, option): apis.add(k) return apis def handlewsgiapirequest(rctx, req, res, checkperm): """Handle requests to /api/*.""" assert req.dispatchparts[0] == b'api' repo = rctx.repo # This whole URL space is experimental for now. But we want to # reserve the URL space. So, 404 all URLs if the feature isn't enabled. if not repo.ui.configbool('experimental', 'web.apiserver'): res.status = b'404 Not Found' res.headers[b'Content-Type'] = b'text/plain' res.setbodybytes(_('Experimental API server endpoint not enabled')) return # The URL space is /api/<protocol>/*. The structure of URLs under varies # by <protocol>. availableapis = _availableapis(repo) # Requests to /api/ list available APIs. if req.dispatchparts == [b'api']: res.status = b'200 OK' res.headers[b'Content-Type'] = b'text/plain' lines = [_('APIs can be accessed at /api/<name>, where <name> can be ' 'one of the following:\n')] if availableapis: lines.extend(sorted(availableapis)) else: lines.append(_('(no available APIs)\n')) res.setbodybytes(b'\n'.join(lines)) return proto = req.dispatchparts[1] if proto not in API_HANDLERS: res.status = b'404 Not Found' res.headers[b'Content-Type'] = b'text/plain' res.setbodybytes(_('Unknown API: %s\nKnown APIs: %s') % ( proto, b', '.join(sorted(availableapis)))) return if proto not in availableapis: res.status = b'404 Not Found' res.headers[b'Content-Type'] = b'text/plain' res.setbodybytes(_('API %s not enabled\n') % proto) return API_HANDLERS[proto]['handler'](rctx, req, res, checkperm, req.dispatchparts[2:]) # Maps API name to metadata so custom API can be registered. # Keys are: # # config # Config option that controls whether service is enabled. # handler # Callable receiving (rctx, req, res, checkperm, urlparts) that is called # when a request to this API is received. # apidescriptor # Callable receiving (req, repo) that is called to obtain an API # descriptor for this service. The response must be serializable to CBOR. API_HANDLERS = { wireprotov2server.HTTP_WIREPROTO_V2: { 'config': ('experimental', 'web.api.http-v2'), 'handler': wireprotov2server.handlehttpv2request, 'apidescriptor': wireprotov2server.httpv2apidescriptor, }, } def _httpresponsetype(ui, proto, prefer_uncompressed): """Determine the appropriate response type and compression settings. Returns a tuple of (mediatype, compengine, engineopts). """ # Determine the response media type and compression engine based # on the request parameters. if '0.2' in proto.getprotocaps(): # All clients are expected to support uncompressed data. if prefer_uncompressed: return HGTYPE2, util._noopengine(), {} # Now find an agreed upon compression format. compformats = wireprotov1server.clientcompressionsupport(proto) for engine in wireprototypes.supportedcompengines(ui, util.SERVERROLE): if engine.wireprotosupport().name in compformats: opts = {} level = ui.configint('server', '%slevel' % engine.name()) if level is not None: opts['level'] = level return HGTYPE2, engine, opts # No mutually supported compression format. Fall back to the # legacy protocol. # Don't allow untrusted settings because disabling compression or # setting a very high compression level could lead to flooding # the server's network or CPU. opts = {'level': ui.configint('server', 'zliblevel')} return HGTYPE, util.compengines['zlib'], opts def processcapabilitieshandshake(repo, req, res, proto): """Called during a ?cmd=capabilities request. If the client is advertising support for a newer protocol, we send a CBOR response with information about available services. If no advertised services are available, we don't handle the request. """ # Fall back to old behavior unless the API server is enabled. if not repo.ui.configbool('experimental', 'web.apiserver'): return False clientapis = decodevaluefromheaders(req, b'X-HgUpgrade') protocaps = decodevaluefromheaders(req, b'X-HgProto') if not clientapis or not protocaps: return False # We currently only support CBOR responses. protocaps = set(protocaps.split(' ')) if b'cbor' not in protocaps: return False descriptors = {} for api in sorted(set(clientapis.split()) & _availableapis(repo)): handler = API_HANDLERS[api] descriptorfn = handler.get('apidescriptor') if not descriptorfn: continue descriptors[api] = descriptorfn(req, repo) v1caps = wireprotov1server.dispatch(repo, proto, 'capabilities') assert isinstance(v1caps, wireprototypes.bytesresponse) m = { # TODO allow this to be configurable. 'apibase': 'api/', 'apis': descriptors, 'v1capabilities': v1caps.data, } res.status = b'200 OK' res.headers[b'Content-Type'] = b'application/mercurial-cbor' res.setbodybytes(b''.join(cborutil.streamencode(m))) return True def _callhttp(repo, req, res, proto, cmd): # Avoid cycle involving hg module. from .hgweb import common as hgwebcommon def genversion2(gen, engine, engineopts): # application/mercurial-0.2 always sends a payload header # identifying the compression engine. name = engine.wireprotosupport().name assert 0 < len(name) < 256 yield struct.pack('B', len(name)) yield name for chunk in gen: yield chunk def setresponse(code, contenttype, bodybytes=None, bodygen=None): if code == HTTP_OK: res.status = '200 Script output follows' else: res.status = hgwebcommon.statusmessage(code) res.headers['Content-Type'] = contenttype if bodybytes is not None: res.setbodybytes(bodybytes) if bodygen is not None: res.setbodygen(bodygen) if not wireprotov1server.commands.commandavailable(cmd, proto): setresponse(HTTP_OK, HGERRTYPE, _('requested wire protocol command is not available over ' 'HTTP')) return proto.checkperm(wireprotov1server.commands[cmd].permission) # Possibly handle a modern client wanting to switch protocols. if (cmd == 'capabilities' and processcapabilitieshandshake(repo, req, res, proto)): return rsp = wireprotov1server.dispatch(repo, proto, cmd) if isinstance(rsp, bytes): setresponse(HTTP_OK, HGTYPE, bodybytes=rsp) elif isinstance(rsp, wireprototypes.bytesresponse): setresponse(HTTP_OK, HGTYPE, bodybytes=rsp.data) elif isinstance(rsp, wireprototypes.streamreslegacy): setresponse(HTTP_OK, HGTYPE, bodygen=rsp.gen) elif isinstance(rsp, wireprototypes.streamres): gen = rsp.gen # This code for compression should not be streamres specific. It # is here because we only compress streamres at the moment. mediatype, engine, engineopts = _httpresponsetype( repo.ui, proto, rsp.prefer_uncompressed) gen = engine.compressstream(gen, engineopts) if mediatype == HGTYPE2: gen = genversion2(gen, engine, engineopts) setresponse(HTTP_OK, mediatype, bodygen=gen) elif isinstance(rsp, wireprototypes.pushres): rsp = '%d\n%s' % (rsp.res, rsp.output) setresponse(HTTP_OK, HGTYPE, bodybytes=rsp) elif isinstance(rsp, wireprototypes.pusherr): rsp = '0\n%s\n' % rsp.res res.drain = True setresponse(HTTP_OK, HGTYPE, bodybytes=rsp) elif isinstance(rsp, wireprototypes.ooberror): setresponse(HTTP_OK, HGERRTYPE, bodybytes=rsp.message) else: raise error.ProgrammingError('hgweb.protocol internal failure', rsp) def _sshv1respondbytes(fout, value): """Send a bytes response for protocol version 1.""" fout.write('%d\n' % len(value)) fout.write(value) fout.flush() def _sshv1respondstream(fout, source): write = fout.write for chunk in source.gen: write(chunk) fout.flush() def _sshv1respondooberror(fout, ferr, rsp): ferr.write(b'%s\n-\n' % rsp) ferr.flush() fout.write(b'\n') fout.flush() @interfaceutil.implementer(wireprototypes.baseprotocolhandler) class sshv1protocolhandler(object): """Handler for requests services via version 1 of SSH protocol.""" def __init__(self, ui, fin, fout): self._ui = ui self._fin = fin self._fout = fout self._protocaps = set() @property def name(self): return wireprototypes.SSHV1 def getargs(self, args): data = {} keys = args.split() for n in pycompat.xrange(len(keys)): argline = self._fin.readline()[:-1] arg, l = argline.split() if arg not in keys: raise error.Abort(_("unexpected parameter %r") % arg) if arg == '*': star = {} for k in pycompat.xrange(int(l)): argline = self._fin.readline()[:-1] arg, l = argline.split() val = self._fin.read(int(l)) star[arg] = val data['*'] = star else: val = self._fin.read(int(l)) data[arg] = val return [data[k] for k in keys] def getprotocaps(self): return self._protocaps def getpayload(self): # We initially send an empty response. This tells the client it is # OK to start sending data. If a client sees any other response, it # interprets it as an error. _sshv1respondbytes(self._fout, b'') # The file is in the form: # # <chunk size>\n<chunk> # ... # 0\n count = int(self._fin.readline()) while count: yield self._fin.read(count) count = int(self._fin.readline()) @contextlib.contextmanager def mayberedirectstdio(self): yield None def client(self): client = encoding.environ.get('SSH_CLIENT', '').split(' ', 1)[0] return 'remote:ssh:' + client def addcapabilities(self, repo, caps): if self.name == wireprototypes.SSHV1: caps.append(b'protocaps') caps.append(b'batch') return caps def checkperm(self, perm): pass class sshv2protocolhandler(sshv1protocolhandler): """Protocol handler for version 2 of the SSH protocol.""" @property def name(self): return wireprototypes.SSHV2 def addcapabilities(self, repo, caps): return caps def _runsshserver(ui, repo, fin, fout, ev): # This function operates like a state machine of sorts. The following # states are defined: # # protov1-serving # Server is in protocol version 1 serving mode. Commands arrive on # new lines. These commands are processed in this state, one command # after the other. # # protov2-serving # Server is in protocol version 2 serving mode. # # upgrade-initial # The server is going to process an upgrade request. # # upgrade-v2-filter-legacy-handshake # The protocol is being upgraded to version 2. The server is expecting # the legacy handshake from version 1. # # upgrade-v2-finish # The upgrade to version 2 of the protocol is imminent. # # shutdown # The server is shutting down, possibly in reaction to a client event. # # And here are their transitions: # # protov1-serving -> shutdown # When server receives an empty request or encounters another # error. # # protov1-serving -> upgrade-initial # An upgrade request line was seen. # # upgrade-initial -> upgrade-v2-filter-legacy-handshake # Upgrade to version 2 in progress. Server is expecting to # process a legacy handshake. # # upgrade-v2-filter-legacy-handshake -> shutdown # Client did not fulfill upgrade handshake requirements. # # upgrade-v2-filter-legacy-handshake -> upgrade-v2-finish # Client fulfilled version 2 upgrade requirements. Finishing that # upgrade. # # upgrade-v2-finish -> protov2-serving # Protocol upgrade to version 2 complete. Server can now speak protocol # version 2. # # protov2-serving -> protov1-serving # Ths happens by default since protocol version 2 is the same as # version 1 except for the handshake. state = 'protov1-serving' proto = sshv1protocolhandler(ui, fin, fout) protoswitched = False while not ev.is_set(): if state == 'protov1-serving': # Commands are issued on new lines. request = fin.readline()[:-1] # Empty lines signal to terminate the connection. if not request: state = 'shutdown' continue # It looks like a protocol upgrade request. Transition state to # handle it. if request.startswith(b'upgrade '): if protoswitched: _sshv1respondooberror(fout, ui.ferr, b'cannot upgrade protocols multiple ' b'times') state = 'shutdown' continue state = 'upgrade-initial' continue available = wireprotov1server.commands.commandavailable( request, proto) # This command isn't available. Send an empty response and go # back to waiting for a new command. if not available: _sshv1respondbytes(fout, b'') continue rsp = wireprotov1server.dispatch(repo, proto, request) if isinstance(rsp, bytes): _sshv1respondbytes(fout, rsp) elif isinstance(rsp, wireprototypes.bytesresponse): _sshv1respondbytes(fout, rsp.data) elif isinstance(rsp, wireprototypes.streamres): _sshv1respondstream(fout, rsp) elif isinstance(rsp, wireprototypes.streamreslegacy): _sshv1respondstream(fout, rsp) elif isinstance(rsp, wireprototypes.pushres): _sshv1respondbytes(fout, b'') _sshv1respondbytes(fout, b'%d' % rsp.res) elif isinstance(rsp, wireprototypes.pusherr): _sshv1respondbytes(fout, rsp.res) elif isinstance(rsp, wireprototypes.ooberror): _sshv1respondooberror(fout, ui.ferr, rsp.message) else: raise error.ProgrammingError('unhandled response type from ' 'wire protocol command: %s' % rsp) # For now, protocol version 2 serving just goes back to version 1. elif state == 'protov2-serving': state = 'protov1-serving' continue elif state == 'upgrade-initial': # We should never transition into this state if we've switched # protocols. assert not protoswitched assert proto.name == wireprototypes.SSHV1 # Expected: upgrade <token> <capabilities> # If we get something else, the request is malformed. It could be # from a future client that has altered the upgrade line content. # We treat this as an unknown command. try: token, caps = request.split(b' ')[1:] except ValueError: _sshv1respondbytes(fout, b'') state = 'protov1-serving' continue # Send empty response if we don't support upgrading protocols. if not ui.configbool('experimental', 'sshserver.support-v2'): _sshv1respondbytes(fout, b'') state = 'protov1-serving' continue try: caps = urlreq.parseqs(caps) except ValueError: _sshv1respondbytes(fout, b'') state = 'protov1-serving' continue # We don't see an upgrade request to protocol version 2. Ignore # the upgrade request. wantedprotos = caps.get(b'proto', [b''])[0] if SSHV2 not in wantedprotos: _sshv1respondbytes(fout, b'') state = 'protov1-serving' continue # It looks like we can honor this upgrade request to protocol 2. # Filter the rest of the handshake protocol request lines. state = 'upgrade-v2-filter-legacy-handshake' continue elif state == 'upgrade-v2-filter-legacy-handshake': # Client should have sent legacy handshake after an ``upgrade`` # request. Expected lines: # # hello # between # pairs 81 # 0000...-0000... ok = True for line in (b'hello', b'between', b'pairs 81'): request = fin.readline()[:-1] if request != line: _sshv1respondooberror(fout, ui.ferr, b'malformed handshake protocol: ' b'missing %s' % line) ok = False state = 'shutdown' break if not ok: continue request = fin.read(81) if request != b'%s-%s' % (b'0' * 40, b'0' * 40): _sshv1respondooberror(fout, ui.ferr, b'malformed handshake protocol: ' b'missing between argument value') state = 'shutdown' continue state = 'upgrade-v2-finish' continue elif state == 'upgrade-v2-finish': # Send the upgrade response. fout.write(b'upgraded %s %s\n' % (token, SSHV2)) servercaps = wireprotov1server.capabilities(repo, proto) rsp = b'capabilities: %s' % servercaps.data fout.write(b'%d\n%s\n' % (len(rsp), rsp)) fout.flush() proto = sshv2protocolhandler(ui, fin, fout) protoswitched = True state = 'protov2-serving' continue elif state == 'shutdown': break else: raise error.ProgrammingError('unhandled ssh server state: %s' % state) class sshserver(object): def __init__(self, ui, repo, logfh=None): self._ui = ui self._repo = repo self._fin, self._fout = procutil.protectstdio(ui.fin, ui.fout) # TODO: manage the redirection flag internally by ui ui._finoutredirected = (self._fin, self._fout) != (ui.fin, ui.fout) # Log write I/O to stdout and stderr if configured. if logfh: self._fout = util.makeloggingfileobject( logfh, self._fout, 'o', logdata=True) ui.ferr = util.makeloggingfileobject( logfh, ui.ferr, 'e', logdata=True) def serve_forever(self): self.serveuntil(threading.Event()) procutil.restorestdio(self._ui.fin, self._ui.fout, self._fin, self._fout) sys.exit(0) def serveuntil(self, ev): """Serve until a threading.Event is set.""" _runsshserver(self._ui, self._repo, self._fin, self._fout, ev)
[ "threading.Event", "sys.exit" ]
[((27758, 27769), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (27766, 27769), False, 'import sys\n'), ((27619, 27636), 'threading.Event', 'threading.Event', ([], {}), '()\n', (27634, 27636), False, 'import threading\n')]
#!/usr/bin/env python3 # _*_ coding:utf-8 _*_ import json from . import jdbot, chat_id, logger, LOG_DIR, BOT_SET_JSON_FILE_USER, BOT_SET_JSON_FILE, BOT_SET, BOT_DIR from .utils import load_module import os import random from .bot.update import version, botlog BOT_UP_LOG = f'{LOG_DIR}/bot/up.log' BOT_M_DIR = f'{BOT_DIR}/bot/' BOT_D_DIR = f'{BOT_DIR}/diy/' BOT_U_DIR = f'{BOT_DIR}/user/' logger.info('加载 user 模块') load_module('user', BOT_U_DIR) logger.info('加载 bot 模块') load_module('bot', BOT_M_DIR) logger.info('加载 diy 模块') load_module('diy', BOT_D_DIR) async def new_ver(): info = '[项目地址](https://github.com/chiupam/JD_Diy.git) \t| \t[交流频道](https://t.me/JD_Diy_Channel) \n\t[监控源码](https://github.com/curtinlv/gd.git) \t| \t[交流频道](https://t.me/topstyle996) ' if os.path.exists(BOT_UP_LOG): is_new = False with open(BOT_UP_LOG, 'r', encoding='utf-8') as f: logs = f.read() if version in logs: is_new = True return if not is_new: with open(BOT_UP_LOG, 'a', encoding='utf-8') as f: f.writelines([version, botlog]) await jdbot.send_message(chat_id, f'[机器人上新了](https://github.com/curtinlv/gd.git)\n{botlog}\n运行日志为log/bot/run.log\n\n\t{info}', link_preview=False) else: with open(BOT_UP_LOG, 'w+', encoding='utf-8') as f: f.writelines([version, botlog]) await jdbot.send_message(chat_id, f'[机器人上新了](https://github.com/curtinlv/gd.git)\n{botlog}\n运行日志为log/bot/run.log\n\n\t{info}', link_preview=False) async def bot_set_init(): try: with open(BOT_SET_JSON_FILE, 'r', encoding='utf-8') as f: bot_set = json.load(f) if os.path.exists(BOT_SET_JSON_FILE_USER): with open(BOT_SET_JSON_FILE_USER, 'r', encoding='utf-8') as f: user_set = json.load(f) if user_set['版本'] != bot_set['版本']: for i in user_set: if '版本' not in i and not isinstance(user_set[i], dict): bot_set[i] = user_set[i] elif isinstance(user_set[i], dict): for j in user_set[i]: bot_set[i][j] = user_set[i][j] else: continue with open(BOT_SET_JSON_FILE_USER, 'w+', encoding='utf-8') as f: json.dump(bot_set, f) else: with open(BOT_SET_JSON_FILE_USER, 'w+', encoding='utf-8') as f: json.dump(bot_set, f) except Exception as e: logger.info(str(e)) async def hello(): if BOT_SET.get('启动问候') and BOT_SET['启动问候'].lower() == 'true': info = '[项目地址](https://github.com/chiupam/JD_Diy.git) \t| \t[交流频道](https://t.me/JD_Diy_Channel) \n\t[监控源码](https://github.com/curtinlv/gd.git) \t| \t[交流频道](https://t.me/topstyle996) ' hello_words = BOT_SET["启动问候语"].split("|") hello_word = hello_words[random.randint(0, len(hello_words) - 1)] await jdbot.send_message(chat_id, f'{str(hello_word)}\n\n\t{info}', link_preview=False) if __name__ == "__main__": with jdbot: jdbot.loop.create_task(new_ver()) jdbot.loop.create_task(bot_set_init()) jdbot.loop.create_task(hello()) jdbot.loop.run_forever()
[ "json.load", "os.path.exists", "json.dump" ]
[((775, 801), 'os.path.exists', 'os.path.exists', (['BOT_UP_LOG'], {}), '(BOT_UP_LOG)\n', (789, 801), False, 'import os\n'), ((1837, 1875), 'os.path.exists', 'os.path.exists', (['BOT_SET_JSON_FILE_USER'], {}), '(BOT_SET_JSON_FILE_USER)\n', (1851, 1875), False, 'import os\n'), ((1813, 1825), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1822, 1825), False, 'import json\n'), ((1979, 1991), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1988, 1991), False, 'import json\n'), ((2648, 2669), 'json.dump', 'json.dump', (['bot_set', 'f'], {}), '(bot_set, f)\n', (2657, 2669), False, 'import json\n'), ((2520, 2541), 'json.dump', 'json.dump', (['bot_set', 'f'], {}), '(bot_set, f)\n', (2529, 2541), False, 'import json\n')]
from typing import Set, Dict, List from pathlib import Path from pydantic import BaseModel from py_irt.io import read_jsonlines from sklearn.feature_extraction.text import CountVectorizer class ItemAccuracy(BaseModel): correct: int = 0 total: int = 0 @property def accuracy(self): return self.correct / max(1, self.total) class Dataset(BaseModel): item_ids: Set[str] subject_ids: Set[str] item_id_to_ix: Dict[str, int] ix_to_item_id: Dict[int, str] subject_id_to_ix: Dict[str, int] ix_to_subject_id: Dict[int, str] # observation_subjects and observation_items refers to indices observation_subjects: List[int] observation_items: List # Actual response value, usually an integer observations: List[float] # should this example be included in training? training_example: List[bool] def get_item_accuracies(self) -> Dict[str, ItemAccuracy]: item_accuracies = {} for ix, response in enumerate(self.observations): item_ix = self.observation_items[ix] item_id = self.ix_to_item_id[item_ix] if item_id not in item_accuracies: item_accuracies[item_id] = ItemAccuracy() item_accuracies[item_id].correct += response item_accuracies[item_id].total += 1 return item_accuracies @classmethod def from_jsonlines(cls, data_path: Path, train_items: dict = None, amortized: bool = False): """Parse IRT dataset from jsonlines, formatted in the following way: * The dataset is in jsonlines format, each line representing the responses of a subject * Each row looks like this: {"subject_id": "<subject_id>", "responses": {"<item_id>": <response>}} * Where <subject_id> is a string, <item_id> is a string, and <response> is a number (usually integer) """ item_ids = set() subject_ids = set() item_id_to_ix = {} ix_to_item_id = {} subject_id_to_ix = {} ix_to_subject_id = {} input_data = read_jsonlines(data_path) for line in input_data: subject_id = line["subject_id"] subject_ids.add(subject_id) responses = line["responses"] for item_id in responses.keys(): item_ids.add(item_id) for idx, item_id in enumerate(item_ids): item_id_to_ix[item_id] = idx ix_to_item_id[idx] = item_id for idx, subject_id in enumerate(subject_ids): subject_id_to_ix[subject_id] = idx ix_to_subject_id[idx] = subject_id if amortized: vectorizer = CountVectorizer(max_df=0.5, min_df=20, stop_words='english') vectorizer.fit(item_ids) observation_subjects = [] observation_items = [] observations = [] training_example = [] print(amortized) for idx, line in enumerate(input_data): subject_id = line["subject_id"] for item_id, response in line["responses"].items(): observations.append(response) observation_subjects.append(subject_id_to_ix[subject_id]) if not amortized: observation_items.append(item_id_to_ix[item_id]) else: observation_items.append(vectorizer.transform([item_id]).todense().tolist()[0]) if train_items is not None: training_example.append(train_items[subject_id][item_id]) else: training_example.append(True) return cls( item_ids=item_ids, subject_ids=subject_ids, item_id_to_ix=item_id_to_ix, ix_to_item_id=ix_to_item_id, subject_id_to_ix=subject_id_to_ix, ix_to_subject_id=ix_to_subject_id, observation_subjects=observation_subjects, observation_items=observation_items, observations=observations, training_example=training_example, )
[ "sklearn.feature_extraction.text.CountVectorizer", "py_irt.io.read_jsonlines" ]
[((2066, 2091), 'py_irt.io.read_jsonlines', 'read_jsonlines', (['data_path'], {}), '(data_path)\n', (2080, 2091), False, 'from py_irt.io import read_jsonlines\n'), ((2671, 2731), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {'max_df': '(0.5)', 'min_df': '(20)', 'stop_words': '"""english"""'}), "(max_df=0.5, min_df=20, stop_words='english')\n", (2686, 2731), False, 'from sklearn.feature_extraction.text import CountVectorizer\n')]
import Bio.PDB.Superimposer from Bio.PDB.Atom import Atom as BioPDBAtom import numpy as np import warnings from Bio.PDB.Atom import PDBConstructionWarning from classes.PDB import PDB from classes.Atom import Atom warnings.simplefilter('ignore', PDBConstructionWarning) def biopdb_aligned_chain(pdb_fixed, chain_id_fixed, pdb_moving, chain_id_moving): biopdb_atom_fixed = [] biopdb_atom_moving = [] for atom in pdb_fixed.get_CA_atoms(): if atom.chain == chain_id_fixed: biopdb_atom_fixed.append( BioPDBAtom(atom.type, (atom.x, atom.y, atom.z), atom.temp_fact, atom.occ, atom.alt_location, " %s " % atom.type, atom.number, element=atom.element_symbol)) pdb_moving_coords = [] for atom in pdb_moving.get_all_atoms(): pdb_moving_coords.append([atom.get_x(), atom.get_y(), atom.get_z()]) if atom.is_CA(): if atom.chain == chain_id_moving: biopdb_atom_moving.append( BioPDBAtom(atom.type, (atom.x, atom.y, atom.z), atom.temp_fact, atom.occ, atom.alt_location, " %s " % atom.type, atom.number, element=atom.element_symbol)) sup = Bio.PDB.Superimposer() sup.set_atoms(biopdb_atom_fixed, biopdb_atom_moving) # no need to transpose rotation matrix as Bio.PDB.Superimposer() generates correct matrix to rotate using np.matmul rot, tr = sup.rotran[0], sup.rotran[1] pdb_moving_coords_rot = np.matmul(pdb_moving_coords, rot) pdb_moving_coords_rot_tx = pdb_moving_coords_rot + tr pdb_moving_copy = PDB() pdb_moving_copy.set_chain_id_list(pdb_moving.get_chain_id_list()) pdb_moving_copy_atom_list = [] atom_count = 0 for atom in pdb_moving.get_all_atoms(): x_transformed = pdb_moving_coords_rot_tx[atom_count][0] y_transformed = pdb_moving_coords_rot_tx[atom_count][1] z_transformed = pdb_moving_coords_rot_tx[atom_count][2] atom_transformed = Atom(atom.get_number(), atom.get_type(), atom.get_alt_location(), atom.get_residue_type(), atom.get_chain(), atom.get_residue_number(), atom.get_code_for_insertion(), x_transformed, y_transformed, z_transformed, atom.get_occ(), atom.get_temp_fact(), atom.get_element_symbol(), atom.get_atom_charge()) pdb_moving_copy_atom_list.append(atom_transformed) atom_count += 1 pdb_moving_copy.set_all_atoms(pdb_moving_copy_atom_list) return pdb_moving_copy def biopdb_superimposer(atoms_fixed, atoms_moving): biopdb_atom_fixed = [] for atom in atoms_fixed: biopdb_atom_fixed.append( BioPDBAtom(atom.type, (atom.x, atom.y, atom.z), atom.temp_fact, atom.occ, atom.alt_location, " %s " % atom.type, atom.number, element=atom.element_symbol)) biopdb_atom_moving = [] for atom in atoms_moving: biopdb_atom_moving.append( BioPDBAtom(atom.type, (atom.x, atom.y, atom.z), atom.temp_fact, atom.occ, atom.alt_location, " %s " % atom.type, atom.number, element=atom.element_symbol)) sup = Bio.PDB.Superimposer() sup.set_atoms(biopdb_atom_fixed, biopdb_atom_moving) rmsd = sup.rms rot = np.transpose(sup.rotran[0]).tolist() tx = sup.rotran[1].tolist() return rmsd, rot, tx
[ "Bio.PDB.Atom.Atom", "numpy.matmul", "warnings.simplefilter", "numpy.transpose", "classes.PDB.PDB" ]
[((213, 268), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'PDBConstructionWarning'], {}), "('ignore', PDBConstructionWarning)\n", (234, 268), False, 'import warnings\n'), ((1482, 1515), 'numpy.matmul', 'np.matmul', (['pdb_moving_coords', 'rot'], {}), '(pdb_moving_coords, rot)\n', (1491, 1515), True, 'import numpy as np\n'), ((1597, 1602), 'classes.PDB.PDB', 'PDB', ([], {}), '()\n', (1600, 1602), False, 'from classes.PDB import PDB\n'), ((2813, 2976), 'Bio.PDB.Atom.Atom', 'BioPDBAtom', (['atom.type', '(atom.x, atom.y, atom.z)', 'atom.temp_fact', 'atom.occ', 'atom.alt_location', "(' %s ' % atom.type)", 'atom.number'], {'element': 'atom.element_symbol'}), "(atom.type, (atom.x, atom.y, atom.z), atom.temp_fact, atom.occ,\n atom.alt_location, ' %s ' % atom.type, atom.number, element=atom.\n element_symbol)\n", (2823, 2976), True, 'from Bio.PDB.Atom import Atom as BioPDBAtom\n'), ((3098, 3261), 'Bio.PDB.Atom.Atom', 'BioPDBAtom', (['atom.type', '(atom.x, atom.y, atom.z)', 'atom.temp_fact', 'atom.occ', 'atom.alt_location', "(' %s ' % atom.type)", 'atom.number'], {'element': 'atom.element_symbol'}), "(atom.type, (atom.x, atom.y, atom.z), atom.temp_fact, atom.occ,\n atom.alt_location, ' %s ' % atom.type, atom.number, element=atom.\n element_symbol)\n", (3108, 3261), True, 'from Bio.PDB.Atom import Atom as BioPDBAtom\n'), ((3398, 3425), 'numpy.transpose', 'np.transpose', (['sup.rotran[0]'], {}), '(sup.rotran[0])\n', (3410, 3425), True, 'import numpy as np\n'), ((546, 709), 'Bio.PDB.Atom.Atom', 'BioPDBAtom', (['atom.type', '(atom.x, atom.y, atom.z)', 'atom.temp_fact', 'atom.occ', 'atom.alt_location', "(' %s ' % atom.type)", 'atom.number'], {'element': 'atom.element_symbol'}), "(atom.type, (atom.x, atom.y, atom.z), atom.temp_fact, atom.occ,\n atom.alt_location, ' %s ' % atom.type, atom.number, element=atom.\n element_symbol)\n", (556, 709), True, 'from Bio.PDB.Atom import Atom as BioPDBAtom\n'), ((1012, 1175), 'Bio.PDB.Atom.Atom', 'BioPDBAtom', (['atom.type', '(atom.x, atom.y, atom.z)', 'atom.temp_fact', 'atom.occ', 'atom.alt_location', "(' %s ' % atom.type)", 'atom.number'], {'element': 'atom.element_symbol'}), "(atom.type, (atom.x, atom.y, atom.z), atom.temp_fact, atom.occ,\n atom.alt_location, ' %s ' % atom.type, atom.number, element=atom.\n element_symbol)\n", (1022, 1175), True, 'from Bio.PDB.Atom import Atom as BioPDBAtom\n')]
import base64 from datetime import datetime import json import random import re from tests.tx_generator.k8s_handler import api_call, aws_api_call class WalletAPI: """ WalletAPI communicates with a [random] miner pod for information such as a wallet nonce, balance and submitting transactions """ ADDRESS_SIZE_BYTES = 20 account_api = 'v1/globalstate/account' get_tx_api = 'v1/transaction/transactionsstate' submit_api = 'v1/transaction/submittransaction' def __init__(self, namespace, clients_lst, fixed_node=None): """ :param namespace: string, namespace :param clients_lst: [{"pod_ip": ..., "name": ...}, ...] """ # TODO make fixed node boolean and create a @property to choose index once self.clients_lst = clients_lst self.namespace = namespace self.fixed_node = fixed_node self.tx_ids = [] def submit_tx(self, to, src, gas_price, amount, nonce, tx_bytes): print(f"\n{datetime.now()}: submit transaction\nfrom {src}\nto {to}") pod_ip, pod_name = self.random_node() print(f"nonce: {nonce}, amount: {amount}, gas-price: {gas_price}, total: {amount+gas_price}") tx_str = base64.b64encode(tx_bytes).decode('utf-8') print(f"txbytes in base64: {tx_str}") tx_field = '{"transaction": "' + tx_str + '"}' out = self.send_api_call(pod_ip, tx_field, self.submit_api) print(f"{datetime.now()}: submit result: {out}") if not out: print("cannot parse submission result, result is none") return False res = self.decode_response(out) if res['txstate']['state'] == 'TRANSACTION_STATE_MEMPOOL': print("tx submission successful") self.tx_ids.append(self.extract_tx_id(out)) return True print("tx submission failed, bad status or txstate") return False def get_tx_by_id(self, tx_id): print(f"get transaction with id {tx_id}") tx_id_lst = self.convert_hex_str_to_bytes(tx_id) pod_ip, pod_name = self.random_node() data = f'{{"id": {str(tx_id_lst)}}}' out = self.send_api_call(pod_ip, data, self.get_tx_api) print(f"get tx output={out}") return self.extract_tx_id(out) def get_nonce_value(self, acc): return self._get_nonce(acc) def get_balance_value(self, acc): return self._get_balance(acc) def _get_nonce(self, acc): return self._make_address_api_call(acc, "counter") def _get_balance(self, acc): return self._make_address_api_call(acc, "balance") def _make_address_api_call(self, acc, resource): # get account state to check balance/nonce print(f"\ngetting {resource} of {acc}") pod_ip, pod_name = self.random_node() # API expects binary address in base64 format, must be converted to string to pass into curl address = base64.b64encode(bytes.fromhex(acc)[-self.ADDRESS_SIZE_BYTES:]).decode('utf-8') data = '{"account_id": {"address":"' + address + '"}}' print(f"api input: {data}") out = self.send_api_call(pod_ip, data, self.account_api) print(f"api output: {out}") # Try to decode the response. If we fail that probably just means the data isn't there. try: out = self.decode_response(out)['account_wrapper']['state_projected'] except json.decoder.JSONDecodeError: raise Exception(f"missing or malformed account data for address {acc}") # GRPC doesn't include zero values so use intelligent defaults here if resource == 'balance': return int(out.get('balance', {'value': 0})['value']) elif resource == 'counter': return int(out.get('counter', 0)) def random_node(self): """ gets a random node from nodes list if fixed is set then the node at the nodes[fixed] will be returned, this may be useful in stress tests :return: string string, chosen pod ip and chosen pod name """ rnd = random.randint(0, len(self.clients_lst)-1) if not self.fixed_node else self.fixed_node pod_ip, pod_name = self.clients_lst[rnd]['pod_ip'], self.clients_lst[rnd]['name'] if not self.fixed_node: print("randomly ", end="") print(f"selected pod: ip = {pod_ip}, name = {pod_name}") return pod_ip, pod_name def send_api_call(self, pod_ip, data, api_resource): if self.namespace: out = api_call(pod_ip, data, api_resource, self.namespace) else: out = aws_api_call(pod_ip, data, api_resource) if out.status_code == 200: out = out.text else: print("status code != 200, output =", out.text) out = None return out # ======================= utils ======================= @staticmethod def extract_tx_id(tx_output): if not tx_output: print("cannot extract id from output, input is None") return None id_pat = r"'value': 'ok', 'id': '([0-9a-f]{64})'" group_num = 1 match = re.search(id_pat, tx_output) if match: return match.group(group_num) return None @staticmethod def convert_hex_str_to_bytes(hex_str): """ :param hex_str: string, 64 bytes (32 byte hex rep) :return: list, a list of 32 integers (32 bytes rep) """ return list(bytearray.fromhex(hex_str)) @staticmethod def decode_response(res): p = re.compile('(?<!\\\\)\'') res = p.sub('\"', res) return json.loads(res)
[ "re.search", "json.loads", "re.compile", "tests.tx_generator.k8s_handler.api_call", "base64.b64encode", "datetime.datetime.now", "tests.tx_generator.k8s_handler.aws_api_call" ]
[((5213, 5241), 're.search', 're.search', (['id_pat', 'tx_output'], {}), '(id_pat, tx_output)\n', (5222, 5241), False, 'import re\n'), ((5637, 5661), 're.compile', 're.compile', (['"""(?<!\\\\\\\\)\'"""'], {}), '("(?<!\\\\\\\\)\'")\n', (5647, 5661), False, 'import re\n'), ((5709, 5724), 'json.loads', 'json.loads', (['res'], {}), '(res)\n', (5719, 5724), False, 'import json\n'), ((4560, 4612), 'tests.tx_generator.k8s_handler.api_call', 'api_call', (['pod_ip', 'data', 'api_resource', 'self.namespace'], {}), '(pod_ip, data, api_resource, self.namespace)\n', (4568, 4612), False, 'from tests.tx_generator.k8s_handler import api_call, aws_api_call\n'), ((4645, 4685), 'tests.tx_generator.k8s_handler.aws_api_call', 'aws_api_call', (['pod_ip', 'data', 'api_resource'], {}), '(pod_ip, data, api_resource)\n', (4657, 4685), False, 'from tests.tx_generator.k8s_handler import api_call, aws_api_call\n'), ((1228, 1254), 'base64.b64encode', 'base64.b64encode', (['tx_bytes'], {}), '(tx_bytes)\n', (1244, 1254), False, 'import base64\n'), ((1004, 1018), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1016, 1018), False, 'from datetime import datetime\n'), ((1457, 1471), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1469, 1471), False, 'from datetime import datetime\n')]
import uuid import urllib import os import json from datetime import datetime from functools import wraps, update_wrapper import requests from flask import g, request, abort, make_response, Response from flask_restplus import Resource, fields from werkzeug.datastructures import FileStorage from pyinfraboxutils import get_logger, get_root_url from pyinfraboxutils.ibflask import OK from pyinfraboxutils.ibrestplus import api, response_model from pyinfraboxutils.storage import storage from pyinfraboxutils.token import encode_project_token ns = api.namespace('Projects', path='/api/v1/projects/<project_id>', description='Project related operations') logger = get_logger('api') enable_upload_forward = False if os.environ['INFRABOX_HA_ENABLED'] == 'true': enable_upload_forward = True elif os.environ['INFRABOX_CLUSTER_NAME'] == 'master': enable_upload_forward = True def nocache(view): @wraps(view) def no_cache(*args, **kwargs): response = make_response(view(*args, **kwargs)) response.headers['Surrogate-Control'] = 'no-store' response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, proxy-revalidate' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = '0' response.last_modified = datetime.now() response.add_etag() return response return update_wrapper(no_cache, view) def get_badge(url): resp = requests.get(url) excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection'] headers = [(name, value) for (name, value) in resp.raw.headers.items() if name.lower() not in excluded_headers] response = Response(resp.content, resp.status_code, headers) return response @ns.route('/state.svg') @api.doc(security=[]) class State(Resource): @nocache def get(self, project_id): ''' State badge ''' p = g.db.execute_one_dict(""" SELECT type FROM project WHERE id = %s """, [project_id]) if not p: abort(404) project_type = p['type'] rows = None if request.args.get('branch', None) and project_type in ('github', 'gerrit'): rows = g.db.execute_many_dict(''' SELECT state FROM job j WHERE j.project_id = %s AND j.build_id = ( SELECT b.id FROM build b INNER JOIN "commit" c ON c.id = b.commit_id AND c.project_id = b.project_id WHERE b.project_id = %s AND c.branch = %s ORDER BY build_number DESC, restart_counter DESC LIMIT 1 ) ''', [project_id, project_id, request.args['branch']]) else: rows = g.db.execute_many_dict(''' SELECT state FROM job j WHERE j.project_id = %s AND j.build_id = ( SELECT id FROM build WHERE project_id = %s ORDER BY build_number DESC, restart_counter DESC LIMIT 1 ) ''', [project_id, project_id]) if not rows: abort(404) status = 'finished' color = 'brightgreen' for r in rows: state = r['state'] if state in ('running', 'queued', 'scheduled'): status = 'running' color = 'grey' break if state in ('failure', 'error', 'killed', 'unstable'): status = state color = 'red' url = 'https://img.shields.io/badge/infrabox-%s-%s.svg' % (status, color) return get_badge(url) @ns.route('/tests.svg') @api.doc(security=[]) class Tests(Resource): @nocache def get(self, project_id): ''' Tests badge ''' branch = request.args.get('branch', None) p = g.db.execute_one_dict(''' SELECT type FROM project WHERE id = %s ''', [project_id]) if not p: abort(404) project_type = p['type'] if branch and project_type in ('github', 'gerrit'): r = g.db.execute_one_dict(''' SELECT count(CASE WHEN tr.state = 'ok' THEN 1 END) success, count(CASE WHEN tr.state = 'failure' THEN 1 END) failure, count(CASE WHEN tr.state = 'error' THEN 1 END) error, count(CASE WHEN tr.state = 'skipped' THEN 1 END) skipped FROM test_run tr WHERE tr.project_id = %s AND tr.job_id IN ( SELECT j.id FROM job j WHERE j.project_id = %s AND j.build_id = ( SELECT b.id FROM build b INNER JOIN job j ON b.id = j.build_id AND b.project_id = %s AND j.project_id = %s INNER JOIN "commit" c ON c.id = b.commit_id AND c.project_id = b.project_id AND c.branch = %s ORDER BY j.created_at DESC LIMIT 1 ) ) ''', [project_id, project_id, project_id, project_id, branch]) else: r = g.db.execute_one_dict(''' SELECT count(CASE WHEN tr.state = 'ok' THEN 1 END) success, count(CASE WHEN tr.state = 'failure' THEN 1 END) failure, count(CASE WHEN tr.state = 'error' THEN 1 END) error, count(CASE WHEN tr.state = 'skipped' THEN 1 END) skipped FROM test_run tr WHERE tr.project_id = %s AND tr.job_id IN ( SELECT j.id FROM job j WHERE j.project_id = %s AND j.build_id = ( SELECT b.id FROM build b INNER JOIN job j ON b.id = j.build_id AND b.project_id = %s AND j.project_id = %s ORDER BY j.created_at DESC LIMIT 1 ) ) ''', [project_id, project_id, project_id, project_id]) total = int(r['success']) + int(r['failure']) + int(r['error']) status = '%s / %s' % (r['success'], total) return get_badge('https://img.shields.io/badge/infrabox-%s-%s.svg' % (status, 'brightgreen')) @ns.route('/badge.svg') @api.doc(security=[]) class Badge(Resource): @nocache def get(self, project_id): ''' Badge ''' job_name = request.args.get('job_name', None) subject = request.args.get('subject', None) branch = request.args.get('branch', None) p = g.db.execute_one_dict(''' SELECT type FROM project WHERE id = %s ''', [project_id]) project_type = p['type'] if branch and project_type in ('github', 'gerrit'): badge = g.db.execute_one_dict(''' SELECT status, color FROM job_badge jb JOIN job j ON j.id = jb.job_id AND j.project_id = %s AND j.state = 'finished' AND j.name = %s AND jb.subject = %s JOIN build b ON j.build_id = b.id AND b.project_id = %s INNER JOIN "commit" c ON c.id = b.commit_id AND c.project_id = b.project_id AND c.branch = %s ORDER BY j.end_date desc LIMIT 1 ''', [project_id, job_name, subject, project_id, branch]) else: badge = g.db.execute_one_dict(''' SELECT status, color FROM job_badge jb JOIN job j ON j.id = jb.job_id AND j.project_id = %s AND j.state = 'finished' AND j.name = %s AND jb.subject = %s JOIN build b ON j.build_id = b.id AND b.project_id = %s ORDER BY j.end_date desc LIMIT 1 ''', [project_id, job_name, subject, project_id]) if not badge: abort(404) status = urllib.quote(badge['status']) subject = urllib.quote(subject) return get_badge('https://img.shields.io/badge/%s-%s-%s.svg' % (subject, status, badge['color'])) upload_parser = api.parser() upload_parser.add_argument('project.zip', location='files', type=FileStorage, required=True) @ns.route('/upload/<build_id>/') @api.expect(upload_parser) class UploadRemote(Resource): @api.response(200, 'Success', response_model) def post(self, project_id, build_id): ''' Upload and trigger build ''' project = g.db.execute_one_dict(''' SELECT type FROM project WHERE id = %s ''', [project_id]) if not project: abort(404, 'Project not found') if project['type'] != 'upload': abort(400, 'Project is not of type "upload"') key = '%s.zip' % build_id stream = request.files['project.zip'].stream storage.upload_project(stream, key) return OK('successfully uploaded data') if enable_upload_forward: @ns.route('/upload/', doc=False) @api.expect(upload_parser) class Upload(Resource): @api.response(200, 'Success', response_model) def post(self, project_id): project = g.db.execute_one_dict(''' SELECT type FROM project WHERE id = %s ''', [project_id]) if not project: abort(404, 'Project not found') if project['type'] != 'upload': abort(400, 'Project is not of type "upload"') build_id = str(uuid.uuid4()) key = '%s.zip' % build_id stream = request.files['project.zip'].stream storage.upload_project(stream, key) clusters = g.db.execute_many_dict(''' SELECT root_url FROM cluster WHERE active = true AND enabled = true AND name != %s ''', [os.environ['INFRABOX_CLUSTER_NAME']]) for c in clusters: stream.seek(0) url = '%s/api/v1/projects/%s/upload/%s/' % (c['root_url'], project_id, build_id) files = {'project.zip': stream} token = encode_project_token(g.token['id'], project_id) headers = {'Authorization': 'bearer ' + token} logger.info('Also uploading to %s', url) # TODO(ib-steffen): allow custom ca bundles r = requests.post(url, files=files, headers=headers, timeout=120, verify=False) if r.status_code != 200: abort(500, "Failed to upload data") build_number = g.db.execute_one_dict(''' SELECT count(distinct build_number) + 1 AS build_number FROM build AS b WHERE b.project_id = %s ''', [project_id])['build_number'] source_upload_id = g.db.execute_one(''' INSERT INTO source_upload(filename, project_id, filesize) VALUES (%s, %s, 0) RETURNING ID ''', [key, project_id])[0] g.db.execute(''' INSERT INTO build (commit_id, build_number, project_id, source_upload_id, id) VALUES (null, %s, %s, %s, %s) ''', [build_number, project_id, source_upload_id, build_id]) definition = { 'build_only': False, 'resources': { 'limits': { 'cpu': 0.5, 'memory': 1024 } } } g.db.execute(''' INSERT INTO job (id, state, build_id, type, name, project_id, dockerfile, definition, cluster_name) VALUES (gen_random_uuid(), 'queued', %s, 'create_job_matrix', 'Create Jobs', %s, '', %s, %s); ''', [build_id, project_id, json.dumps(definition), None]) project_name = g.db.execute_one(''' SELECT name FROM project WHERE id = %s ''', [project_id])[0] root_url = get_root_url('global') url = '%s/dashboard/#/project/%s/build/%s/1' % (root_url, project_name, build_number) data = { 'build': { 'id': build_id, 'number': build_number }, 'url': url } g.db.commit() return OK('successfully started build', data=data)
[ "flask.request.args.get", "requests.post", "pyinfraboxutils.ibrestplus.api.expect", "flask.g.db.execute_one_dict", "urllib.quote", "flask.g.db.execute", "pyinfraboxutils.ibflask.OK", "json.dumps", "functools.wraps", "pyinfraboxutils.ibrestplus.api.doc", "flask.abort", "pyinfraboxutils.ibrestpl...
[((553, 663), 'pyinfraboxutils.ibrestplus.api.namespace', 'api.namespace', (['"""Projects"""'], {'path': '"""/api/v1/projects/<project_id>"""', 'description': '"""Project related operations"""'}), "('Projects', path='/api/v1/projects/<project_id>', description\n ='Project related operations')\n", (566, 663), False, 'from pyinfraboxutils.ibrestplus import api, response_model\n'), ((708, 725), 'pyinfraboxutils.get_logger', 'get_logger', (['"""api"""'], {}), "('api')\n", (718, 725), False, 'from pyinfraboxutils import get_logger, get_root_url\n'), ((1836, 1856), 'pyinfraboxutils.ibrestplus.api.doc', 'api.doc', ([], {'security': '[]'}), '(security=[])\n', (1843, 1856), False, 'from pyinfraboxutils.ibrestplus import api, response_model\n'), ((3918, 3938), 'pyinfraboxutils.ibrestplus.api.doc', 'api.doc', ([], {'security': '[]'}), '(security=[])\n', (3925, 3938), False, 'from pyinfraboxutils.ibrestplus import api, response_model\n'), ((7285, 7305), 'pyinfraboxutils.ibrestplus.api.doc', 'api.doc', ([], {'security': '[]'}), '(security=[])\n', (7292, 7305), False, 'from pyinfraboxutils.ibrestplus import api, response_model\n'), ((9546, 9558), 'pyinfraboxutils.ibrestplus.api.parser', 'api.parser', ([], {}), '()\n', (9556, 9558), False, 'from pyinfraboxutils.ibrestplus import api, response_model\n'), ((9715, 9740), 'pyinfraboxutils.ibrestplus.api.expect', 'api.expect', (['upload_parser'], {}), '(upload_parser)\n', (9725, 9740), False, 'from pyinfraboxutils.ibrestplus import api, response_model\n'), ((950, 961), 'functools.wraps', 'wraps', (['view'], {}), '(view)\n', (955, 961), False, 'from functools import wraps, update_wrapper\n'), ((1414, 1444), 'functools.update_wrapper', 'update_wrapper', (['no_cache', 'view'], {}), '(no_cache, view)\n', (1428, 1444), False, 'from functools import wraps, update_wrapper\n'), ((1477, 1494), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (1489, 1494), False, 'import requests\n'), ((1740, 1789), 'flask.Response', 'Response', (['resp.content', 'resp.status_code', 'headers'], {}), '(resp.content, resp.status_code, headers)\n', (1748, 1789), False, 'from flask import g, request, abort, make_response, Response\n'), ((9777, 9821), 'pyinfraboxutils.ibrestplus.api.response', 'api.response', (['(200)', '"""Success"""', 'response_model'], {}), "(200, 'Success', response_model)\n", (9789, 9821), False, 'from pyinfraboxutils.ibrestplus import api, response_model\n'), ((10487, 10512), 'pyinfraboxutils.ibrestplus.api.expect', 'api.expect', (['upload_parser'], {}), '(upload_parser)\n', (10497, 10512), False, 'from pyinfraboxutils.ibrestplus import api, response_model\n'), ((1335, 1349), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1347, 1349), False, 'from datetime import datetime\n'), ((1981, 2094), 'flask.g.db.execute_one_dict', 'g.db.execute_one_dict', (['"""\n SELECT type FROM project WHERE id = %s\n """', '[project_id]'], {}), '(\n """\n SELECT type FROM project WHERE id = %s\n """, [\n project_id])\n', (2002, 2094), False, 'from flask import g, request, abort, make_response, Response\n'), ((4068, 4100), 'flask.request.args.get', 'request.args.get', (['"""branch"""', 'None'], {}), "('branch', None)\n", (4084, 4100), False, 'from flask import g, request, abort, make_response, Response\n'), ((4113, 4226), 'flask.g.db.execute_one_dict', 'g.db.execute_one_dict', (['"""\n SELECT type FROM project WHERE id = %s\n """', '[project_id]'], {}), '(\n """\n SELECT type FROM project WHERE id = %s\n """, [\n project_id])\n', (4134, 4226), False, 'from flask import g, request, abort, make_response, Response\n'), ((7431, 7465), 'flask.request.args.get', 'request.args.get', (['"""job_name"""', 'None'], {}), "('job_name', None)\n", (7447, 7465), False, 'from flask import g, request, abort, make_response, Response\n'), ((7484, 7517), 'flask.request.args.get', 'request.args.get', (['"""subject"""', 'None'], {}), "('subject', None)\n", (7500, 7517), False, 'from flask import g, request, abort, make_response, Response\n'), ((7535, 7567), 'flask.request.args.get', 'request.args.get', (['"""branch"""', 'None'], {}), "('branch', None)\n", (7551, 7567), False, 'from flask import g, request, abort, make_response, Response\n'), ((7580, 7693), 'flask.g.db.execute_one_dict', 'g.db.execute_one_dict', (['"""\n SELECT type FROM project WHERE id = %s\n """', '[project_id]'], {}), '(\n """\n SELECT type FROM project WHERE id = %s\n """, [\n project_id])\n', (7601, 7693), False, 'from flask import g, request, abort, make_response, Response\n'), ((9207, 9236), 'urllib.quote', 'urllib.quote', (["badge['status']"], {}), "(badge['status'])\n", (9219, 9236), False, 'import urllib\n'), ((9255, 9276), 'urllib.quote', 'urllib.quote', (['subject'], {}), '(subject)\n', (9267, 9276), False, 'import urllib\n'), ((9939, 10076), 'flask.g.db.execute_one_dict', 'g.db.execute_one_dict', (['"""\n SELECT type\n FROM project\n WHERE id = %s\n """', '[project_id]'], {}), '(\n """\n SELECT type\n FROM project\n WHERE id = %s\n """\n , [project_id])\n', (9960, 10076), False, 'from flask import g, request, abort, make_response, Response\n'), ((10332, 10367), 'pyinfraboxutils.storage.storage.upload_project', 'storage.upload_project', (['stream', 'key'], {}), '(stream, key)\n', (10354, 10367), False, 'from pyinfraboxutils.storage import storage\n'), ((10384, 10416), 'pyinfraboxutils.ibflask.OK', 'OK', (['"""successfully uploaded data"""'], {}), "('successfully uploaded data')\n", (10386, 10416), False, 'from pyinfraboxutils.ibflask import OK\n'), ((10551, 10595), 'pyinfraboxutils.ibrestplus.api.response', 'api.response', (['(200)', '"""Success"""', 'response_model'], {}), "(200, 'Success', response_model)\n", (10563, 10595), False, 'from pyinfraboxutils.ibrestplus import api, response_model\n'), ((2116, 2126), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (2121, 2126), False, 'from flask import g, request, abort, make_response, Response\n'), ((2193, 2225), 'flask.request.args.get', 'request.args.get', (['"""branch"""', 'None'], {}), "('branch', None)\n", (2209, 2225), False, 'from flask import g, request, abort, make_response, Response\n'), ((2287, 2915), 'flask.g.db.execute_many_dict', 'g.db.execute_many_dict', (['"""\n SELECT state FROM job j\n WHERE j.project_id = %s\n AND j.build_id = (\n SELECT b.id\n FROM build b\n INNER JOIN "commit" c\n ON c.id = b.commit_id\n AND c.project_id = b.project_id\n WHERE b.project_id = %s\n AND c.branch = %s\n ORDER BY build_number DESC, restart_counter DESC\n LIMIT 1\n )\n """', "[project_id, project_id, request.args['branch']]"], {}), '(\n """\n SELECT state FROM job j\n WHERE j.project_id = %s\n AND j.build_id = (\n SELECT b.id\n FROM build b\n INNER JOIN "commit" c\n ON c.id = b.commit_id\n AND c.project_id = b.project_id\n WHERE b.project_id = %s\n AND c.branch = %s\n ORDER BY build_number DESC, restart_counter DESC\n LIMIT 1\n )\n """\n , [project_id, project_id, request.args[\'branch\']])\n', (2309, 2915), False, 'from flask import g, request, abort, make_response, Response\n'), ((2939, 3351), 'flask.g.db.execute_many_dict', 'g.db.execute_many_dict', (['"""\n SELECT state FROM job j\n WHERE j.project_id = %s\n AND j.build_id = (\n SELECT id\n FROM build\n WHERE project_id = %s\n ORDER BY build_number DESC, restart_counter DESC\n LIMIT 1\n )\n """', '[project_id, project_id]'], {}), '(\n """\n SELECT state FROM job j\n WHERE j.project_id = %s\n AND j.build_id = (\n SELECT id\n FROM build\n WHERE project_id = %s\n ORDER BY build_number DESC, restart_counter DESC\n LIMIT 1\n )\n """\n , [project_id, project_id])\n', (2961, 3351), False, 'from flask import g, request, abort, make_response, Response\n'), ((3376, 3386), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (3381, 3386), False, 'from flask import g, request, abort, make_response, Response\n'), ((4248, 4258), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (4253, 4258), False, 'from flask import g, request, abort, make_response, Response\n'), ((4370, 5777), 'flask.g.db.execute_one_dict', 'g.db.execute_one_dict', (['"""\n SELECT\n count(CASE WHEN tr.state = \'ok\' THEN 1 END) success,\n count(CASE WHEN tr.state = \'failure\' THEN 1 END) failure,\n count(CASE WHEN tr.state = \'error\' THEN 1 END) error,\n count(CASE WHEN tr.state = \'skipped\' THEN 1 END) skipped\n FROM test_run tr\n WHERE tr.project_id = %s\n AND tr.job_id IN (\n SELECT j.id\n FROM job j\n WHERE j.project_id = %s\n AND j.build_id = (\n SELECT b.id\n FROM build b\n INNER JOIN job j\n ON b.id = j.build_id\n AND b.project_id = %s\n AND j.project_id = %s\n INNER JOIN "commit" c\n ON c.id = b.commit_id\n AND c.project_id = b.project_id\n AND c.branch = %s\n ORDER BY j.created_at DESC\n LIMIT 1\n )\n )\n """', '[project_id, project_id, project_id, project_id, branch]'], {}), '(\n """\n SELECT\n count(CASE WHEN tr.state = \'ok\' THEN 1 END) success,\n count(CASE WHEN tr.state = \'failure\' THEN 1 END) failure,\n count(CASE WHEN tr.state = \'error\' THEN 1 END) error,\n count(CASE WHEN tr.state = \'skipped\' THEN 1 END) skipped\n FROM test_run tr\n WHERE tr.project_id = %s\n AND tr.job_id IN (\n SELECT j.id\n FROM job j\n WHERE j.project_id = %s\n AND j.build_id = (\n SELECT b.id\n FROM build b\n INNER JOIN job j\n ON b.id = j.build_id\n AND b.project_id = %s\n AND j.project_id = %s\n INNER JOIN "commit" c\n ON c.id = b.commit_id\n AND c.project_id = b.project_id\n AND c.branch = %s\n ORDER BY j.created_at DESC\n LIMIT 1\n )\n )\n """\n , [project_id, project_id, project_id, project_id, branch])\n', (4391, 5777), False, 'from flask import g, request, abort, make_response, Response\n'), ((5798, 6963), 'flask.g.db.execute_one_dict', 'g.db.execute_one_dict', (['"""\n SELECT\n count(CASE WHEN tr.state = \'ok\' THEN 1 END) success,\n count(CASE WHEN tr.state = \'failure\' THEN 1 END) failure,\n count(CASE WHEN tr.state = \'error\' THEN 1 END) error,\n count(CASE WHEN tr.state = \'skipped\' THEN 1 END) skipped\n FROM test_run tr\n WHERE tr.project_id = %s\n AND tr.job_id IN (\n SELECT j.id\n FROM job j\n WHERE j.project_id = %s\n AND j.build_id = (\n SELECT b.id\n FROM build b\n INNER JOIN job j\n ON b.id = j.build_id\n AND b.project_id = %s\n AND j.project_id = %s\n ORDER BY j.created_at DESC\n LIMIT 1\n )\n )\n """', '[project_id, project_id, project_id, project_id]'], {}), '(\n """\n SELECT\n count(CASE WHEN tr.state = \'ok\' THEN 1 END) success,\n count(CASE WHEN tr.state = \'failure\' THEN 1 END) failure,\n count(CASE WHEN tr.state = \'error\' THEN 1 END) error,\n count(CASE WHEN tr.state = \'skipped\' THEN 1 END) skipped\n FROM test_run tr\n WHERE tr.project_id = %s\n AND tr.job_id IN (\n SELECT j.id\n FROM job j\n WHERE j.project_id = %s\n AND j.build_id = (\n SELECT b.id\n FROM build b\n INNER JOIN job j\n ON b.id = j.build_id\n AND b.project_id = %s\n AND j.project_id = %s\n ORDER BY j.created_at DESC\n LIMIT 1\n )\n )\n """\n , [project_id, project_id, project_id, project_id])\n', (5819, 6963), False, 'from flask import g, request, abort, make_response, Response\n'), ((7799, 8552), 'flask.g.db.execute_one_dict', 'g.db.execute_one_dict', (['"""\n SELECT status, color\n FROM job_badge jb\n JOIN job j\n ON j.id = jb.job_id\n AND j.project_id = %s\n AND j.state = \'finished\'\n AND j.name = %s\n AND jb.subject = %s\n JOIN build b\n ON j.build_id = b.id\n AND b.project_id = %s\n INNER JOIN "commit" c\n ON c.id = b.commit_id\n AND c.project_id = b.project_id\n AND c.branch = %s\n ORDER BY j.end_date desc\n LIMIT 1\n """', '[project_id, job_name, subject, project_id, branch]'], {}), '(\n """\n SELECT status, color\n FROM job_badge jb\n JOIN job j\n ON j.id = jb.job_id\n AND j.project_id = %s\n AND j.state = \'finished\'\n AND j.name = %s\n AND jb.subject = %s\n JOIN build b\n ON j.build_id = b.id\n AND b.project_id = %s\n INNER JOIN "commit" c\n ON c.id = b.commit_id\n AND c.project_id = b.project_id\n AND c.branch = %s\n ORDER BY j.end_date desc\n LIMIT 1\n """\n , [project_id, job_name, subject, project_id, branch])\n', (7820, 8552), False, 'from flask import g, request, abort, make_response, Response\n'), ((8577, 9152), 'flask.g.db.execute_one_dict', 'g.db.execute_one_dict', (['"""\n SELECT status, color\n FROM job_badge jb\n JOIN job j\n ON j.id = jb.job_id\n AND j.project_id = %s\n AND j.state = \'finished\'\n AND j.name = %s\n AND jb.subject = %s\n JOIN build b\n ON j.build_id = b.id\n AND b.project_id = %s\n ORDER BY j.end_date desc\n LIMIT 1\n """', '[project_id, job_name, subject, project_id]'], {}), '(\n """\n SELECT status, color\n FROM job_badge jb\n JOIN job j\n ON j.id = jb.job_id\n AND j.project_id = %s\n AND j.state = \'finished\'\n AND j.name = %s\n AND jb.subject = %s\n JOIN build b\n ON j.build_id = b.id\n AND b.project_id = %s\n ORDER BY j.end_date desc\n LIMIT 1\n """\n , [project_id, job_name, subject, project_id])\n', (8598, 9152), False, 'from flask import g, request, abort, make_response, Response\n'), ((9178, 9188), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (9183, 9188), False, 'from flask import g, request, abort, make_response, Response\n'), ((10104, 10135), 'flask.abort', 'abort', (['(404)', '"""Project not found"""'], {}), "(404, 'Project not found')\n", (10109, 10135), False, 'from flask import g, request, abort, make_response, Response\n'), ((10189, 10234), 'flask.abort', 'abort', (['(400)', '"""Project is not of type "upload\\""""'], {}), '(400, \'Project is not of type "upload"\')\n', (10194, 10234), False, 'from flask import g, request, abort, make_response, Response\n'), ((10654, 10807), 'flask.g.db.execute_one_dict', 'g.db.execute_one_dict', (['"""\n SELECT type\n FROM project\n WHERE id = %s\n """', '[project_id]'], {}), '(\n """\n SELECT type\n FROM project\n WHERE id = %s\n """\n , [project_id])\n', (10675, 10807), False, 'from flask import g, request, abort, make_response, Response\n'), ((11132, 11167), 'pyinfraboxutils.storage.storage.upload_project', 'storage.upload_project', (['stream', 'key'], {}), '(stream, key)\n', (11154, 11167), False, 'from pyinfraboxutils.storage import storage\n'), ((11192, 11447), 'flask.g.db.execute_many_dict', 'g.db.execute_many_dict', (['"""\n SELECT root_url\n FROM cluster\n WHERE active = true\n AND enabled = true\n AND name != %s\n """', "[os.environ['INFRABOX_CLUSTER_NAME']]"], {}), '(\n """\n SELECT root_url\n FROM cluster\n WHERE active = true\n AND enabled = true\n AND name != %s\n """\n , [os.environ[\'INFRABOX_CLUSTER_NAME\']])\n', (11214, 11447), False, 'from flask import g, request, abort, make_response, Response\n'), ((12549, 12788), 'flask.g.db.execute', 'g.db.execute', (['"""\n INSERT INTO build (commit_id, build_number, project_id, source_upload_id, id)\n VALUES (null, %s, %s, %s, %s)\n """', '[build_number, project_id, source_upload_id, build_id]'], {}), '(\n """\n INSERT INTO build (commit_id, build_number, project_id, source_upload_id, id)\n VALUES (null, %s, %s, %s, %s)\n """\n , [build_number, project_id, source_upload_id, build_id])\n', (12561, 12788), False, 'from flask import g, request, abort, make_response, Response\n'), ((13582, 13604), 'pyinfraboxutils.get_root_url', 'get_root_url', (['"""global"""'], {}), "('global')\n", (13594, 13604), False, 'from pyinfraboxutils import get_logger, get_root_url\n'), ((14024, 14037), 'flask.g.db.commit', 'g.db.commit', ([], {}), '()\n', (14035, 14037), False, 'from flask import g, request, abort, make_response, Response\n'), ((14058, 14101), 'pyinfraboxutils.ibflask.OK', 'OK', (['"""successfully started build"""'], {'data': 'data'}), "('successfully started build', data=data)\n", (14060, 14101), False, 'from pyinfraboxutils.ibflask import OK\n'), ((10843, 10874), 'flask.abort', 'abort', (['(404)', '"""Project not found"""'], {}), "(404, 'Project not found')\n", (10848, 10874), False, 'from flask import g, request, abort, make_response, Response\n'), ((10936, 10981), 'flask.abort', 'abort', (['(400)', '"""Project is not of type "upload\\""""'], {}), '(400, \'Project is not of type "upload"\')\n', (10941, 10981), False, 'from flask import g, request, abort, make_response, Response\n'), ((11010, 11022), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (11020, 11022), False, 'import uuid\n'), ((11670, 11717), 'pyinfraboxutils.token.encode_project_token', 'encode_project_token', (["g.token['id']", 'project_id'], {}), "(g.token['id'], project_id)\n", (11690, 11717), False, 'from pyinfraboxutils.token import encode_project_token\n'), ((11919, 11994), 'requests.post', 'requests.post', (['url'], {'files': 'files', 'headers': 'headers', 'timeout': '(120)', 'verify': '(False)'}), '(url, files=files, headers=headers, timeout=120, verify=False)\n', (11932, 11994), False, 'import requests\n'), ((12121, 12331), 'flask.g.db.execute_one_dict', 'g.db.execute_one_dict', (['"""\n SELECT count(distinct build_number) + 1 AS build_number\n FROM build AS b\n WHERE b.project_id = %s\n """', '[project_id]'], {}), '(\n """\n SELECT count(distinct build_number) + 1 AS build_number\n FROM build AS b\n WHERE b.project_id = %s\n """\n , [project_id])\n', (12142, 12331), False, 'from flask import g, request, abort, make_response, Response\n'), ((12370, 12542), 'flask.g.db.execute_one', 'g.db.execute_one', (['"""\n INSERT INTO source_upload(filename, project_id, filesize) VALUES (%s, %s, 0) RETURNING ID\n """', '[key, project_id]'], {}), '(\n """\n INSERT INTO source_upload(filename, project_id, filesize) VALUES (%s, %s, 0) RETURNING ID\n """\n , [key, project_id])\n', (12386, 12542), False, 'from flask import g, request, abort, make_response, Response\n'), ((13448, 13563), 'flask.g.db.execute_one', 'g.db.execute_one', (['"""\n SELECT name FROM project WHERE id = %s\n """', '[project_id]'], {}), '(\n """\n SELECT name FROM project WHERE id = %s\n """,\n [project_id])\n', (13464, 13563), False, 'from flask import g, request, abort, make_response, Response\n'), ((12057, 12092), 'flask.abort', 'abort', (['(500)', '"""Failed to upload data"""'], {}), "(500, 'Failed to upload data')\n", (12062, 12092), False, 'from flask import g, request, abort, make_response, Response\n'), ((13389, 13411), 'json.dumps', 'json.dumps', (['definition'], {}), '(definition)\n', (13399, 13411), False, 'import json\n')]
from typing import Any import numpy as np from xgboost import XGBClassifier from bender.model_trainer.interface import ModelTrainer from bender.split_strategy.split_strategy import TrainingDataSet from bender.trained_model.interface import TrainedModel from bender.trained_model.xgboosted_tree import TrainedXGBoostModel class XGBoostTrainer(ModelTrainer): xgboost_parmas: dict[str, Any] def __init__( self, enable_categorical: bool = False, use_label_encoder: bool = False, learning_rate: float = 0.01, max_depth: int = 5, n_estimators: int = 400, verbosity: float = 0, scale_pos_weight: float = 1.0, gamma: float = 0, min_child_weight: float = 1, colsample_bytree: float = 1, reg_lambda: float = 1, alpha: float = 0, ) -> None: self.xgboost_parmas = { 'enable_categorical': enable_categorical, 'use_label_encoder': use_label_encoder, 'learning_rate': learning_rate, 'max_depth': max_depth, 'n_estimators': n_estimators, 'verbosity': verbosity, 'scale_pos_weight': scale_pos_weight, 'gamma': gamma, 'min_child_weight': min_child_weight, 'colsample_bytree': colsample_bytree, 'reg_lambda': reg_lambda, 'alpha': alpha, } async def train(self, data_split: TrainingDataSet) -> TrainedModel: # if data_split.y_train.dtype not in [int, bool, str]: # print(data_split.y_train.dtypes) # raise Exception('Training classification model on continuse values. Maybe you want a regression model?') model = XGBClassifier(**self.xgboost_parmas) if set(data_split.y_train.unique().tolist()) == {1, 0}: pos_data = len(data_split.y_train.loc[data_split.y_train == 1]) neg_data = data_split.y_train.shape[0] - pos_data model.scale_pos_weight = int(np.round(neg_data / pos_data)) model.fit(data_split.x_train, data_split.y_train, eval_set=[(data_split.x_validate, data_split.y_validate)]) return TrainedXGBoostModel(model, data_split.x_features)
[ "bender.trained_model.xgboosted_tree.TrainedXGBoostModel", "numpy.round", "xgboost.XGBClassifier" ]
[((1720, 1756), 'xgboost.XGBClassifier', 'XGBClassifier', ([], {}), '(**self.xgboost_parmas)\n', (1733, 1756), False, 'from xgboost import XGBClassifier\n'), ((2163, 2212), 'bender.trained_model.xgboosted_tree.TrainedXGBoostModel', 'TrainedXGBoostModel', (['model', 'data_split.x_features'], {}), '(model, data_split.x_features)\n', (2182, 2212), False, 'from bender.trained_model.xgboosted_tree import TrainedXGBoostModel\n'), ((2000, 2029), 'numpy.round', 'np.round', (['(neg_data / pos_data)'], {}), '(neg_data / pos_data)\n', (2008, 2029), True, 'import numpy as np\n')]
#------------------------------------------------------------------------------- # Name: DNS_modules # Purpose: # # Author: <EMAIL> # # Created: 05/31/2014 #------------------------------------------------------------------------------- import os import sys import tools import module_locater import dns.resolver import datetime scriptdir = module_locater.module_path() myDate = datetime.datetime.now().strftime("%y-%m-%d") myTime = datetime.datetime.now().strftime("%H%M") myDateTime = datetime.datetime.now().strftime("%y-%m-%d %H%M") resultsdir = scriptdir + '\\Results\\' if not os.path.exists(resultsdir): os.makedirs(resultsdir) def DNS(host, recordtype): answers = dns.resolver.query(host, recordtype) for rdata in answers: print('Host', rdata.exchange, 'has preference', rdata.preference) def main(): pass if __name__ == '__main__': main()
[ "os.path.exists", "datetime.datetime.now", "os.makedirs", "module_locater.module_path" ]
[((358, 386), 'module_locater.module_path', 'module_locater.module_path', ([], {}), '()\n', (384, 386), False, 'import module_locater\n'), ((600, 626), 'os.path.exists', 'os.path.exists', (['resultsdir'], {}), '(resultsdir)\n', (614, 626), False, 'import os\n'), ((632, 655), 'os.makedirs', 'os.makedirs', (['resultsdir'], {}), '(resultsdir)\n', (643, 655), False, 'import os\n'), ((396, 419), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (417, 419), False, 'import datetime\n'), ((450, 473), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (471, 473), False, 'import datetime\n'), ((504, 527), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (525, 527), False, 'import datetime\n')]
# Copyright 2016 Google 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. from concurrent.futures import ThreadPoolExecutor import queue import re import threading import time import traceback class EventDispatcherError(Exception): pass class IllegalStateError(EventDispatcherError): """Raise when user tries to put event_dispatcher into an illegal state. """ class DuplicateError(EventDispatcherError): """Raise when a duplicate is being created and it shouldn't. """ class EventDispatcher: """Class managing events for an sl4a connection. """ DEFAULT_TIMEOUT = 60 def __init__(self, sl4a): self._sl4a = sl4a self.started = False self.executor = None self.poller = None self.event_dict = {} self.handlers = {} self.lock = threading.RLock() def poll_events(self): """Continuously polls all types of events from sl4a. Events are sorted by name and store in separate queues. If there are registered handlers, the handlers will be called with corresponding event immediately upon event discovery, and the event won't be stored. If exceptions occur, stop the dispatcher and return """ while self.started: event_obj = None event_name = None try: event_obj = self._sl4a.eventWait(50000) except: if self.started: print("Exception happened during polling.") print(traceback.format_exc()) raise if not event_obj: continue elif 'name' not in event_obj: print("Received Malformed event {}".format(event_obj)) continue else: event_name = event_obj['name'] # if handler registered, process event if event_name in self.handlers: self.handle_subscribed_event(event_obj, event_name) if event_name == "EventDispatcherShutdown": self._sl4a.closeSl4aSession() break else: self.lock.acquire() if event_name in self.event_dict: # otherwise, cache event self.event_dict[event_name].put(event_obj) else: q = queue.Queue() q.put(event_obj) self.event_dict[event_name] = q self.lock.release() def register_handler(self, handler, event_name, args): """Registers an event handler. One type of event can only have one event handler associated with it. Args: handler: The event handler function to be registered. event_name: Name of the event the handler is for. args: User arguments to be passed to the handler when it's called. Raises: IllegalStateError: Raised if attempts to register a handler after the dispatcher starts running. DuplicateError: Raised if attempts to register more than one handler for one type of event. """ if self.started: raise IllegalStateError(("Can't register service after polling is" " started")) self.lock.acquire() try: if event_name in self.handlers: raise DuplicateError( 'A handler for {} already exists'.format(event_name)) self.handlers[event_name] = (handler, args) finally: self.lock.release() def start(self): """Starts the event dispatcher. Initiates executor and start polling events. Raises: IllegalStateError: Can't start a dispatcher again when it's already running. """ if not self.started: self.started = True self.executor = ThreadPoolExecutor(max_workers=32) self.poller = self.executor.submit(self.poll_events) else: raise IllegalStateError("Dispatcher is already started.") def clean_up(self): """Clean up and release resources after the event dispatcher polling loop has been broken. The following things happen: 1. Clear all events and flags. 2. Close the sl4a client the event_dispatcher object holds. 3. Shut down executor without waiting. """ if not self.started: return self.started = False self.clear_all_events() # At this point, the sl4a apk is destroyed and nothing is listening on # the socket. Avoid sending any sl4a commands; just clean up the socket # and return. self._sl4a.disconnect() self.poller.set_result("Done") # The polling thread is guaranteed to finish after a max of 60 seconds, # so we don't wait here. self.executor.shutdown(wait=False) def pop_event(self, event_name, timeout=DEFAULT_TIMEOUT): """Pop an event from its queue. Return and remove the oldest entry of an event. Block until an event of specified name is available or times out if timeout is set. Args: event_name: Name of the event to be popped. timeout: Number of seconds to wait when event is not present. Never times out if None. Returns: The oldest entry of the specified event. None if timed out. Raises: IllegalStateError: Raised if pop is called before the dispatcher starts polling. """ if not self.started: raise IllegalStateError("Dispatcher needs to be started before popping.") e_queue = self.get_event_q(event_name) if not e_queue: raise TypeError("Failed to get an event queue for {}".format(event_name)) try: # Block for timeout if timeout: return e_queue.get(True, timeout) # Non-blocking poll for event elif timeout == 0: return e_queue.get(False) else: # Block forever on event wait return e_queue.get(True) except queue.Empty: raise queue.Empty('Timeout after {}s waiting for event: {}'.format( timeout, event_name)) def wait_for_event(self, event_name, predicate, timeout=DEFAULT_TIMEOUT, *args, **kwargs): """Wait for an event that satisfies a predicate to appear. Continuously pop events of a particular name and check against the predicate until an event that satisfies the predicate is popped or timed out. Note this will remove all the events of the same name that do not satisfy the predicate in the process. Args: event_name: Name of the event to be popped. predicate: A function that takes an event and returns True if the predicate is satisfied, False otherwise. timeout: Number of seconds to wait. *args: Optional positional args passed to predicate(). **kwargs: Optional keyword args passed to predicate(). Returns: The event that satisfies the predicate. Raises: queue.Empty: Raised if no event that satisfies the predicate was found before time out. """ deadline = time.time() + timeout while True: event = None try: event = self.pop_event(event_name, 1) except queue.Empty: pass if event and predicate(event, *args, **kwargs): return event if time.time() > deadline: raise queue.Empty('Timeout after {}s waiting for event: {}'.format( timeout, event_name)) def pop_events(self, regex_pattern, timeout): """Pop events whose names match a regex pattern. If such event(s) exist, pop one event from each event queue that satisfies the condition. Otherwise, wait for an event that satisfies the condition to occur, with timeout. Results are sorted by timestamp in ascending order. Args: regex_pattern: The regular expression pattern that an event name should match in order to be popped. timeout: Number of seconds to wait for events in case no event matching the condition exits when the function is called. Returns: Events whose names match a regex pattern. Empty if none exist and the wait timed out. Raises: IllegalStateError: Raised if pop is called before the dispatcher starts polling. queue.Empty: Raised if no event was found before time out. """ if not self.started: raise IllegalStateError("Dispatcher needs to be started before popping.") deadline = time.time() + timeout while True: #TODO: fix the sleep loop results = self._match_and_pop(regex_pattern) if len(results) != 0 or time.time() > deadline: break time.sleep(1) if len(results) == 0: raise queue.Empty('Timeout after {}s waiting for event: {}'.format( timeout, regex_pattern)) return sorted(results, key=lambda event: event['time']) def _match_and_pop(self, regex_pattern): """Pop one event from each of the event queues whose names match (in a sense of regular expression) regex_pattern. """ results = [] self.lock.acquire() for name in self.event_dict.keys(): if re.match(regex_pattern, name): q = self.event_dict[name] if q: try: results.append(q.get(False)) except: pass self.lock.release() return results def get_event_q(self, event_name): """Obtain the queue storing events of the specified name. If no event of this name has been polled, wait for one to. Returns: A queue storing all the events of the specified name. None if timed out. Raises: queue.Empty: Raised if the queue does not exist and timeout has passed. """ self.lock.acquire() if event_name not in self.event_dict or self.event_dict[event_name] is None: self.event_dict[event_name] = queue.Queue() self.lock.release() event_queue = self.event_dict[event_name] return event_queue def handle_subscribed_event(self, event_obj, event_name): """Execute the registered handler of an event. Retrieve the handler and its arguments, and execute the handler in a new thread. Args: event_obj: Json object of the event. event_name: Name of the event to call handler for. """ handler, args = self.handlers[event_name] self.executor.submit(handler, event_obj, *args) def _handle(self, event_handler, event_name, user_args, event_timeout, cond, cond_timeout): """Pop an event of specified type and calls its handler on it. If condition is not None, block until condition is met or timeout. """ if cond: cond.wait(cond_timeout) event = self.pop_event(event_name, event_timeout) return event_handler(event, *user_args) def handle_event(self, event_handler, event_name, user_args, event_timeout=None, cond=None, cond_timeout=None): """Handle events that don't have registered handlers In a new thread, poll one event of specified type from its queue and execute its handler. If no such event exists, the thread waits until one appears. Args: event_handler: Handler for the event, which should take at least one argument - the event json object. event_name: Name of the event to be handled. user_args: User arguments for the handler; to be passed in after the event json. event_timeout: Number of seconds to wait for the event to come. cond: A condition to wait on before executing the handler. Should be a threading.Event object. cond_timeout: Number of seconds to wait before the condition times out. Never times out if None. Returns: A concurrent.Future object associated with the handler. If blocking call worker.result() is triggered, the handler needs to return something to unblock. """ worker = self.executor.submit(self._handle, event_handler, event_name, user_args, event_timeout, cond, cond_timeout) return worker def pop_all(self, event_name): """Return and remove all stored events of a specified name. Pops all events from their queue. May miss the latest ones. If no event is available, return immediately. Args: event_name: Name of the events to be popped. Returns: List of the desired events. Raises: IllegalStateError: Raised if pop is called before the dispatcher starts polling. """ if not self.started: raise IllegalStateError(("Dispatcher needs to be started before " "popping.")) results = [] try: self.lock.acquire() while True: e = self.event_dict[event_name].get(block=False) results.append(e) except (queue.Empty, KeyError): return results finally: self.lock.release() def clear_events(self, event_name): """Clear all events of a particular name. Args: event_name: Name of the events to be popped. """ self.lock.acquire() try: q = self.get_event_q(event_name) q.queue.clear() except queue.Empty: return finally: self.lock.release() def clear_all_events(self): """Clear all event queues and their cached events.""" self.lock.acquire() self.event_dict.clear() self.lock.release()
[ "traceback.format_exc", "concurrent.futures.ThreadPoolExecutor", "re.match", "threading.RLock", "time.sleep", "queue.Queue", "time.time" ]
[((1281, 1298), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (1296, 1298), False, 'import threading\n'), ((3990, 4024), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {'max_workers': '(32)'}), '(max_workers=32)\n', (4008, 4024), False, 'from concurrent.futures import ThreadPoolExecutor\n'), ((7257, 7268), 'time.time', 'time.time', ([], {}), '()\n', (7266, 7268), False, 'import time\n'), ((8649, 8660), 'time.time', 'time.time', ([], {}), '()\n', (8658, 8660), False, 'import time\n'), ((8844, 8857), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (8854, 8857), False, 'import time\n'), ((9319, 9348), 're.match', 're.match', (['regex_pattern', 'name'], {}), '(regex_pattern, name)\n', (9327, 9348), False, 'import re\n'), ((10043, 10056), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (10054, 10056), False, 'import queue\n'), ((7497, 7508), 'time.time', 'time.time', ([], {}), '()\n', (7506, 7508), False, 'import time\n'), ((2588, 2601), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (2599, 2601), False, 'import queue\n'), ((8800, 8811), 'time.time', 'time.time', ([], {}), '()\n', (8809, 8811), False, 'import time\n'), ((1906, 1928), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (1926, 1928), False, 'import traceback\n')]
# -*- coding: utf-8 -*- """ Defines unit tests for :mod:`colour.colorimetry.lightness` module. """ import numpy as np import unittest from colour.colorimetry import (lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011) from colour.colorimetry.lightness import lightness from colour.utilities import domain_range_scale, ignore_numpy_errors __author__ = 'Colour Developers' __copyright__ = 'Copyright (C) 2013-2021 - Colour Developers' __license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause' __maintainer__ = 'Colour Developers' __email__ = '<EMAIL>' __status__ = 'Production' __all__ = [ 'TestLightnessGlasser1958', 'TestLightnessWyszecki1963', 'TestIntermediateLightnessFunctionCIE1976', 'TestLightnessCIE1976', 'TestLightnessFairchild2010', 'TestLightnessFairchild2011', 'TestLightness' ] class TestLightnessGlasser1958(unittest.TestCase): """ Defines :func:`colour.colorimetry.lightness.lightness_Glasser1958` definition unit tests methods. """ def test_lightness_Glasser1958(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Glasser1958` definition. """ self.assertAlmostEqual( lightness_Glasser1958(12.19722535), 39.83512646492521, places=7) self.assertAlmostEqual( lightness_Glasser1958(23.04276781), 53.585946877480623, places=7) self.assertAlmostEqual( lightness_Glasser1958(6.15720079), 27.972867038082629, places=7) def test_n_dimensional_lightness_Glasser1958(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Glasser1958` definition n-dimensional arrays support. """ Y = 12.19722535 L = lightness_Glasser1958(Y) Y = np.tile(Y, 6) L = np.tile(L, 6) np.testing.assert_almost_equal(lightness_Glasser1958(Y), L, decimal=7) Y = np.reshape(Y, (2, 3)) L = np.reshape(L, (2, 3)) np.testing.assert_almost_equal(lightness_Glasser1958(Y), L, decimal=7) Y = np.reshape(Y, (2, 3, 1)) L = np.reshape(L, (2, 3, 1)) np.testing.assert_almost_equal(lightness_Glasser1958(Y), L, decimal=7) def test_domain_range_scale_lightness_Glasser1958(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Glasser1958` definition domain and range scale support. """ L = lightness_Glasser1958(12.19722535) d_r = (('reference', 1), (1, 0.01), (100, 1)) for scale, factor in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( lightness_Glasser1958(12.19722535 * factor), L * factor, decimal=7) @ignore_numpy_errors def test_nan_lightness_Glasser1958(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Glasser1958` definition nan support. """ lightness_Glasser1958( np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])) class TestLightnessWyszecki1963(unittest.TestCase): """ Defines :func:`colour.colorimetry.lightness.lightness_Wyszecki1963` definition unit tests methods. """ def test_lightness_Wyszecki1963(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Wyszecki1963` definition. """ self.assertAlmostEqual( lightness_Wyszecki1963(12.19722535), 40.547574599570197, places=7) self.assertAlmostEqual( lightness_Wyszecki1963(23.04276781), 54.140714588256841, places=7) self.assertAlmostEqual( lightness_Wyszecki1963(6.15720079), 28.821339499883976, places=7) def test_n_dimensional_lightness_Wyszecki1963(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Wyszecki1963` definition n-dimensional arrays support. """ Y = 12.19722535 W = lightness_Wyszecki1963(Y) Y = np.tile(Y, 6) W = np.tile(W, 6) np.testing.assert_almost_equal(lightness_Wyszecki1963(Y), W, decimal=7) Y = np.reshape(Y, (2, 3)) W = np.reshape(W, (2, 3)) np.testing.assert_almost_equal(lightness_Wyszecki1963(Y), W, decimal=7) Y = np.reshape(Y, (2, 3, 1)) W = np.reshape(W, (2, 3, 1)) np.testing.assert_almost_equal(lightness_Wyszecki1963(Y), W, decimal=7) def test_domain_range_scale_lightness_Wyszecki1963(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Wyszecki1963` definition domain and range scale support. """ W = lightness_Wyszecki1963(12.19722535) d_r = (('reference', 1), (1, 0.01), (100, 1)) for scale, factor in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( lightness_Wyszecki1963(12.19722535 * factor), W * factor, decimal=7) @ignore_numpy_errors def test_nan_lightness_Wyszecki1963(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Wyszecki1963` definition nan support. """ lightness_Wyszecki1963( np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])) class TestIntermediateLightnessFunctionCIE1976(unittest.TestCase): """ Defines :func:`colour.colorimetry.lightness.\ intermediate_lightness_function_CIE1976` definition unit tests methods. """ def test_intermediate_lightness_function_CIE1976(self): """ Tests :func:`colour.colorimetry.lightness.\ intermediate_lightness_function_CIE1976` definition. """ self.assertAlmostEqual( intermediate_lightness_function_CIE1976(12.19722535), 0.495929964178047, places=7) self.assertAlmostEqual( intermediate_lightness_function_CIE1976(23.04276781), 0.613072093530391, places=7) self.assertAlmostEqual( intermediate_lightness_function_CIE1976(6.15720079), 0.394876333449113, places=7) def test_n_dimensional_intermediate_lightness_function_CIE1976(self): """ Tests :func:`colour.colorimetry.lightness.\ intermediate_lightness_function_CIE1976` definition n-dimensional arrays support. """ Y = 12.19722535 f_Y_Y_n = intermediate_lightness_function_CIE1976(Y) Y = np.tile(Y, 6) f_Y_Y_n = np.tile(f_Y_Y_n, 6) np.testing.assert_almost_equal( intermediate_lightness_function_CIE1976(Y), f_Y_Y_n, decimal=7) Y = np.reshape(Y, (2, 3)) f_Y_Y_n = np.reshape(f_Y_Y_n, (2, 3)) np.testing.assert_almost_equal( intermediate_lightness_function_CIE1976(Y), f_Y_Y_n, decimal=7) Y = np.reshape(Y, (2, 3, 1)) f_Y_Y_n = np.reshape(f_Y_Y_n, (2, 3, 1)) np.testing.assert_almost_equal( intermediate_lightness_function_CIE1976(Y), f_Y_Y_n, decimal=7) def test_domain_range_scale_intermediate_lightness_function_CIE1976(self): """ Tests :func:`colour.colorimetry.lightness.\ intermediate_lightness_function_CIE1976` definition domain and range scale support. """ f_Y_Y_n = intermediate_lightness_function_CIE1976(12.19722535, 100) for scale in ('reference', 1, 100): with domain_range_scale(scale): np.testing.assert_almost_equal( intermediate_lightness_function_CIE1976(12.19722535, 100), f_Y_Y_n, decimal=7) @ignore_numpy_errors def test_nan_intermediate_lightness_function_CIE1976(self): """ Tests :func:`colour.colorimetry.lightness.\ intermediate_lightness_function_CIE1976` definition nan support. """ intermediate_lightness_function_CIE1976( np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])) class TestLightnessCIE1976(unittest.TestCase): """ Defines :func:`colour.colorimetry.lightness.lightness_CIE1976` definition unit tests methods. """ def test_lightness_CIE1976(self): """ Tests :func:`colour.colorimetry.lightness.lightness_CIE1976` definition. """ self.assertAlmostEqual( lightness_CIE1976(12.19722535), 41.527875844653451, places=7) self.assertAlmostEqual( lightness_CIE1976(23.04276781), 55.116362849525402, places=7) self.assertAlmostEqual( lightness_CIE1976(6.15720079), 29.805654680097106, places=7) self.assertAlmostEqual( lightness_CIE1976(12.19722535, 50), 56.480581732417676, places=7) self.assertAlmostEqual( lightness_CIE1976(12.19722535, 75), 47.317620274162735, places=7) self.assertAlmostEqual( lightness_CIE1976(12.19722535, 95), 42.519930728120940, places=7) def test_n_dimensional_lightness_CIE1976(self): """ Tests :func:`colour.colorimetry.lightness.lightness_CIE1976` definition n-dimensional arrays support. """ Y = 12.19722535 L_star = lightness_CIE1976(Y) Y = np.tile(Y, 6) L_star = np.tile(L_star, 6) np.testing.assert_almost_equal(lightness_CIE1976(Y), L_star, decimal=7) Y = np.reshape(Y, (2, 3)) L_star = np.reshape(L_star, (2, 3)) np.testing.assert_almost_equal(lightness_CIE1976(Y), L_star, decimal=7) Y = np.reshape(Y, (2, 3, 1)) L_star = np.reshape(L_star, (2, 3, 1)) np.testing.assert_almost_equal(lightness_CIE1976(Y), L_star, decimal=7) def test_domain_range_scale_lightness_CIE1976(self): """ Tests :func:`colour.colorimetry.lightness.lightness_CIE1976` definition domain and range scale support. """ L_star = lightness_CIE1976(12.19722535, 100) d_r = (('reference', 1), (1, 0.01), (100, 1)) for scale, factor in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( lightness_CIE1976(12.19722535 * factor, 100), L_star * factor, decimal=7) @ignore_numpy_errors def test_nan_lightness_CIE1976(self): """ Tests :func:`colour.colorimetry.lightness.lightness_CIE1976` definition nan support. """ lightness_CIE1976(np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])) class TestLightnessFairchild2010(unittest.TestCase): """ Defines :func:`colour.colorimetry.lightness.lightness_Fairchild2010` definition unit tests methods. """ def test_lightness_Fairchild2010(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Fairchild2010` definition. """ self.assertAlmostEqual( lightness_Fairchild2010(12.19722535 / 100), 31.996390226262736, places=7) self.assertAlmostEqual( lightness_Fairchild2010(23.04276781 / 100), 60.203153682783302, places=7) self.assertAlmostEqual( lightness_Fairchild2010(6.15720079 / 100), 11.836517240976489, places=7) self.assertAlmostEqual( lightness_Fairchild2010(12.19722535 / 100, 2.75), 24.424283249379986, places=7) self.assertAlmostEqual( lightness_Fairchild2010(1008), 100.019986327374240, places=7) self.assertAlmostEqual( lightness_Fairchild2010(100800), 100.019999997090270, places=7) def test_n_dimensional_lightness_Fairchild2010(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Fairchild2010` definition n-dimensional arrays support. """ Y = 12.19722535 / 100 L_hdr = lightness_Fairchild2010(Y) Y = np.tile(Y, 6) L_hdr = np.tile(L_hdr, 6) np.testing.assert_almost_equal( lightness_Fairchild2010(Y), L_hdr, decimal=7) Y = np.reshape(Y, (2, 3)) L_hdr = np.reshape(L_hdr, (2, 3)) np.testing.assert_almost_equal( lightness_Fairchild2010(Y), L_hdr, decimal=7) Y = np.reshape(Y, (2, 3, 1)) L_hdr = np.reshape(L_hdr, (2, 3, 1)) np.testing.assert_almost_equal( lightness_Fairchild2010(Y), L_hdr, decimal=7) def test_domain_range_scale_lightness_Fairchild2010(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Fairchild2010` definition domain and range scale support. """ L_hdr = lightness_Fairchild2010(12.19722535 / 100) d_r = (('reference', 1, 1), (1, 1, 0.01), (100, 100, 1)) for scale, factor_a, factor_b in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( lightness_Fairchild2010(12.19722535 / 100 * factor_a), L_hdr * factor_b, decimal=7) @ignore_numpy_errors def test_nan_lightness_Fairchild2010(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Fairchild2010` definition nan support. """ lightness_Fairchild2010( np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])) class TestLightnessFairchild2011(unittest.TestCase): """ Defines :func:`colour.colorimetry.lightness.lightness_Fairchild2011` definition unit tests methods. """ def test_lightness_Fairchild2011(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Fairchild2011` definition. """ self.assertAlmostEqual( lightness_Fairchild2011(12.19722535 / 100), 51.852958445912506, places=7) self.assertAlmostEqual( lightness_Fairchild2011(23.04276781 / 100), 65.275207956353853, places=7) self.assertAlmostEqual( lightness_Fairchild2011(6.15720079 / 100), 39.818935510715917, places=7) self.assertAlmostEqual( lightness_Fairchild2011(12.19722535 / 100, 2.75), 0.13268968410139345, places=7) self.assertAlmostEqual( lightness_Fairchild2011(1008), 234.72925682, places=7) self.assertAlmostEqual( lightness_Fairchild2011(100800), 245.5705978, places=7) def test_n_dimensional_lightness_Fairchild2011(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Fairchild2011` definition n-dimensional arrays support. """ Y = 12.19722535 / 100 L_hdr = lightness_Fairchild2011(Y) Y = np.tile(Y, 6) L_hdr = np.tile(L_hdr, 6) np.testing.assert_almost_equal( lightness_Fairchild2011(Y), L_hdr, decimal=7) Y = np.reshape(Y, (2, 3)) L_hdr = np.reshape(L_hdr, (2, 3)) np.testing.assert_almost_equal( lightness_Fairchild2011(Y), L_hdr, decimal=7) Y = np.reshape(Y, (2, 3, 1)) L_hdr = np.reshape(L_hdr, (2, 3, 1)) np.testing.assert_almost_equal( lightness_Fairchild2011(Y), L_hdr, decimal=7) def test_domain_range_scale_lightness_Fairchild2011(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Fairchild2011` definition domain and range scale support. """ L_hdr = lightness_Fairchild2011(12.19722535 / 100) d_r = (('reference', 1, 1), (1, 1, 0.01), (100, 100, 1)) for scale, factor_a, factor_b in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( lightness_Fairchild2011(12.19722535 / 100 * factor_a), L_hdr * factor_b, decimal=7) @ignore_numpy_errors def test_nan_lightness_Fairchild2011(self): """ Tests :func:`colour.colorimetry.lightness.lightness_Fairchild2011` definition nan support. """ lightness_Fairchild2011( np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])) class TestLightness(unittest.TestCase): """ Defines :func:`colour.colorimetry.lightness.lightness` definition unit tests methods. """ def test_domain_range_scale_lightness(self): """ Tests :func:`colour.colorimetry.lightness.lightness` definition domain and range scale support. """ m = ('Glasser 1958', 'Wyszecki 1963', 'CIE 1976', 'Fairchild 2010', 'Fairchild 2011') v = [lightness(12.19722535, method, Y_n=100) for method in m] d_r = (('reference', 1), (1, 0.01), (100, 1)) for method, value in zip(m, v): for scale, factor in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( lightness(12.19722535 * factor, method, Y_n=100), value * factor, decimal=7) if __name__ == '__main__': unittest.main()
[ "numpy.tile", "numpy.reshape", "colour.colorimetry.lightness_CIE1976", "colour.colorimetry.lightness_Glasser1958", "colour.utilities.domain_range_scale", "colour.colorimetry.lightness_Fairchild2011", "colour.colorimetry.lightness_Wyszecki1963", "numpy.array", "colour.colorimetry.lightness.lightness"...
[((17391, 17406), 'unittest.main', 'unittest.main', ([], {}), '()\n', (17404, 17406), False, 'import unittest\n'), ((1935, 1959), 'colour.colorimetry.lightness_Glasser1958', 'lightness_Glasser1958', (['Y'], {}), '(Y)\n', (1956, 1959), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((1973, 1986), 'numpy.tile', 'np.tile', (['Y', '(6)'], {}), '(Y, 6)\n', (1980, 1986), True, 'import numpy as np\n'), ((1999, 2012), 'numpy.tile', 'np.tile', (['L', '(6)'], {}), '(L, 6)\n', (2006, 2012), True, 'import numpy as np\n'), ((2105, 2126), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3)'], {}), '(Y, (2, 3))\n', (2115, 2126), True, 'import numpy as np\n'), ((2139, 2160), 'numpy.reshape', 'np.reshape', (['L', '(2, 3)'], {}), '(L, (2, 3))\n', (2149, 2160), True, 'import numpy as np\n'), ((2253, 2277), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3, 1)'], {}), '(Y, (2, 3, 1))\n', (2263, 2277), True, 'import numpy as np\n'), ((2290, 2314), 'numpy.reshape', 'np.reshape', (['L', '(2, 3, 1)'], {}), '(L, (2, 3, 1))\n', (2300, 2314), True, 'import numpy as np\n'), ((2617, 2651), 'colour.colorimetry.lightness_Glasser1958', 'lightness_Glasser1958', (['(12.19722535)'], {}), '(12.19722535)\n', (2638, 2651), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((4175, 4200), 'colour.colorimetry.lightness_Wyszecki1963', 'lightness_Wyszecki1963', (['Y'], {}), '(Y)\n', (4197, 4200), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((4214, 4227), 'numpy.tile', 'np.tile', (['Y', '(6)'], {}), '(Y, 6)\n', (4221, 4227), True, 'import numpy as np\n'), ((4240, 4253), 'numpy.tile', 'np.tile', (['W', '(6)'], {}), '(W, 6)\n', (4247, 4253), True, 'import numpy as np\n'), ((4347, 4368), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3)'], {}), '(Y, (2, 3))\n', (4357, 4368), True, 'import numpy as np\n'), ((4381, 4402), 'numpy.reshape', 'np.reshape', (['W', '(2, 3)'], {}), '(W, (2, 3))\n', (4391, 4402), True, 'import numpy as np\n'), ((4496, 4520), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3, 1)'], {}), '(Y, (2, 3, 1))\n', (4506, 4520), True, 'import numpy as np\n'), ((4533, 4557), 'numpy.reshape', 'np.reshape', (['W', '(2, 3, 1)'], {}), '(W, (2, 3, 1))\n', (4543, 4557), True, 'import numpy as np\n'), ((4863, 4898), 'colour.colorimetry.lightness_Wyszecki1963', 'lightness_Wyszecki1963', (['(12.19722535)'], {}), '(12.19722535)\n', (4885, 4898), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((6646, 6688), 'colour.colorimetry.intermediate_lightness_function_CIE1976', 'intermediate_lightness_function_CIE1976', (['Y'], {}), '(Y)\n', (6685, 6688), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((6702, 6715), 'numpy.tile', 'np.tile', (['Y', '(6)'], {}), '(Y, 6)\n', (6709, 6715), True, 'import numpy as np\n'), ((6734, 6753), 'numpy.tile', 'np.tile', (['f_Y_Y_n', '(6)'], {}), '(f_Y_Y_n, 6)\n', (6741, 6753), True, 'import numpy as np\n'), ((6883, 6904), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3)'], {}), '(Y, (2, 3))\n', (6893, 6904), True, 'import numpy as np\n'), ((6923, 6950), 'numpy.reshape', 'np.reshape', (['f_Y_Y_n', '(2, 3)'], {}), '(f_Y_Y_n, (2, 3))\n', (6933, 6950), True, 'import numpy as np\n'), ((7080, 7104), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3, 1)'], {}), '(Y, (2, 3, 1))\n', (7090, 7104), True, 'import numpy as np\n'), ((7123, 7153), 'numpy.reshape', 'np.reshape', (['f_Y_Y_n', '(2, 3, 1)'], {}), '(f_Y_Y_n, (2, 3, 1))\n', (7133, 7153), True, 'import numpy as np\n'), ((7537, 7594), 'colour.colorimetry.intermediate_lightness_function_CIE1976', 'intermediate_lightness_function_CIE1976', (['(12.19722535)', '(100)'], {}), '(12.19722535, 100)\n', (7576, 7594), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((9426, 9446), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['Y'], {}), '(Y)\n', (9443, 9446), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((9460, 9473), 'numpy.tile', 'np.tile', (['Y', '(6)'], {}), '(Y, 6)\n', (9467, 9473), True, 'import numpy as np\n'), ((9491, 9509), 'numpy.tile', 'np.tile', (['L_star', '(6)'], {}), '(L_star, 6)\n', (9498, 9509), True, 'import numpy as np\n'), ((9603, 9624), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3)'], {}), '(Y, (2, 3))\n', (9613, 9624), True, 'import numpy as np\n'), ((9642, 9668), 'numpy.reshape', 'np.reshape', (['L_star', '(2, 3)'], {}), '(L_star, (2, 3))\n', (9652, 9668), True, 'import numpy as np\n'), ((9762, 9786), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3, 1)'], {}), '(Y, (2, 3, 1))\n', (9772, 9786), True, 'import numpy as np\n'), ((9804, 9833), 'numpy.reshape', 'np.reshape', (['L_star', '(2, 3, 1)'], {}), '(L_star, (2, 3, 1))\n', (9814, 9833), True, 'import numpy as np\n'), ((10134, 10169), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['(12.19722535)', '(100)'], {}), '(12.19722535, 100)\n', (10151, 10169), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((12148, 12174), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['Y'], {}), '(Y)\n', (12171, 12174), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((12188, 12201), 'numpy.tile', 'np.tile', (['Y', '(6)'], {}), '(Y, 6)\n', (12195, 12201), True, 'import numpy as np\n'), ((12218, 12235), 'numpy.tile', 'np.tile', (['L_hdr', '(6)'], {}), '(L_hdr, 6)\n', (12225, 12235), True, 'import numpy as np\n'), ((12347, 12368), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3)'], {}), '(Y, (2, 3))\n', (12357, 12368), True, 'import numpy as np\n'), ((12385, 12410), 'numpy.reshape', 'np.reshape', (['L_hdr', '(2, 3)'], {}), '(L_hdr, (2, 3))\n', (12395, 12410), True, 'import numpy as np\n'), ((12522, 12546), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3, 1)'], {}), '(Y, (2, 3, 1))\n', (12532, 12546), True, 'import numpy as np\n'), ((12563, 12591), 'numpy.reshape', 'np.reshape', (['L_hdr', '(2, 3, 1)'], {}), '(L_hdr, (2, 3, 1))\n', (12573, 12591), True, 'import numpy as np\n'), ((12921, 12963), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['(12.19722535 / 100)'], {}), '(12.19722535 / 100)\n', (12944, 12963), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((14992, 15018), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['Y'], {}), '(Y)\n', (15015, 15018), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((15032, 15045), 'numpy.tile', 'np.tile', (['Y', '(6)'], {}), '(Y, 6)\n', (15039, 15045), True, 'import numpy as np\n'), ((15062, 15079), 'numpy.tile', 'np.tile', (['L_hdr', '(6)'], {}), '(L_hdr, 6)\n', (15069, 15079), True, 'import numpy as np\n'), ((15191, 15212), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3)'], {}), '(Y, (2, 3))\n', (15201, 15212), True, 'import numpy as np\n'), ((15229, 15254), 'numpy.reshape', 'np.reshape', (['L_hdr', '(2, 3)'], {}), '(L_hdr, (2, 3))\n', (15239, 15254), True, 'import numpy as np\n'), ((15366, 15390), 'numpy.reshape', 'np.reshape', (['Y', '(2, 3, 1)'], {}), '(Y, (2, 3, 1))\n', (15376, 15390), True, 'import numpy as np\n'), ((15407, 15435), 'numpy.reshape', 'np.reshape', (['L_hdr', '(2, 3, 1)'], {}), '(L_hdr, (2, 3, 1))\n', (15417, 15435), True, 'import numpy as np\n'), ((15765, 15807), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['(12.19722535 / 100)'], {}), '(12.19722535 / 100)\n', (15788, 15807), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((1409, 1443), 'colour.colorimetry.lightness_Glasser1958', 'lightness_Glasser1958', (['(12.19722535)'], {}), '(12.19722535)\n', (1430, 1443), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((1519, 1553), 'colour.colorimetry.lightness_Glasser1958', 'lightness_Glasser1958', (['(23.04276781)'], {}), '(23.04276781)\n', (1540, 1553), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((1630, 1663), 'colour.colorimetry.lightness_Glasser1958', 'lightness_Glasser1958', (['(6.15720079)'], {}), '(6.15720079)\n', (1651, 1663), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((2052, 2076), 'colour.colorimetry.lightness_Glasser1958', 'lightness_Glasser1958', (['Y'], {}), '(Y)\n', (2073, 2076), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((2200, 2224), 'colour.colorimetry.lightness_Glasser1958', 'lightness_Glasser1958', (['Y'], {}), '(Y)\n', (2221, 2224), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((2354, 2378), 'colour.colorimetry.lightness_Glasser1958', 'lightness_Glasser1958', (['Y'], {}), '(Y)\n', (2375, 2378), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((3206, 3257), 'numpy.array', 'np.array', (['[-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]'], {}), '([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])\n', (3214, 3257), True, 'import numpy as np\n'), ((3643, 3678), 'colour.colorimetry.lightness_Wyszecki1963', 'lightness_Wyszecki1963', (['(12.19722535)'], {}), '(12.19722535)\n', (3665, 3678), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((3755, 3790), 'colour.colorimetry.lightness_Wyszecki1963', 'lightness_Wyszecki1963', (['(23.04276781)'], {}), '(23.04276781)\n', (3777, 3790), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((3867, 3901), 'colour.colorimetry.lightness_Wyszecki1963', 'lightness_Wyszecki1963', (['(6.15720079)'], {}), '(6.15720079)\n', (3889, 3901), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((4293, 4318), 'colour.colorimetry.lightness_Wyszecki1963', 'lightness_Wyszecki1963', (['Y'], {}), '(Y)\n', (4315, 4318), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((4442, 4467), 'colour.colorimetry.lightness_Wyszecki1963', 'lightness_Wyszecki1963', (['Y'], {}), '(Y)\n', (4464, 4467), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((4597, 4622), 'colour.colorimetry.lightness_Wyszecki1963', 'lightness_Wyszecki1963', (['Y'], {}), '(Y)\n', (4619, 4622), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((5457, 5508), 'numpy.array', 'np.array', (['[-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]'], {}), '([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])\n', (5465, 5508), True, 'import numpy as np\n'), ((5952, 6004), 'colour.colorimetry.intermediate_lightness_function_CIE1976', 'intermediate_lightness_function_CIE1976', (['(12.19722535)'], {}), '(12.19722535)\n', (5991, 6004), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((6104, 6156), 'colour.colorimetry.intermediate_lightness_function_CIE1976', 'intermediate_lightness_function_CIE1976', (['(23.04276781)'], {}), '(23.04276781)\n', (6143, 6156), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((6256, 6307), 'colour.colorimetry.intermediate_lightness_function_CIE1976', 'intermediate_lightness_function_CIE1976', (['(6.15720079)'], {}), '(6.15720079)\n', (6295, 6307), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((6806, 6848), 'colour.colorimetry.intermediate_lightness_function_CIE1976', 'intermediate_lightness_function_CIE1976', (['Y'], {}), '(Y)\n', (6845, 6848), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((7003, 7045), 'colour.colorimetry.intermediate_lightness_function_CIE1976', 'intermediate_lightness_function_CIE1976', (['Y'], {}), '(Y)\n', (7042, 7045), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((7206, 7248), 'colour.colorimetry.intermediate_lightness_function_CIE1976', 'intermediate_lightness_function_CIE1976', (['Y'], {}), '(Y)\n', (7245, 7248), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((8164, 8215), 'numpy.array', 'np.array', (['[-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]'], {}), '([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])\n', (8172, 8215), True, 'import numpy as np\n'), ((8581, 8611), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['(12.19722535)'], {}), '(12.19722535)\n', (8598, 8611), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((8688, 8718), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['(23.04276781)'], {}), '(23.04276781)\n', (8705, 8718), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((8795, 8824), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['(6.15720079)'], {}), '(6.15720079)\n', (8812, 8824), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((8901, 8935), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['(12.19722535)', '(50)'], {}), '(12.19722535, 50)\n', (8918, 8935), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((9012, 9046), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['(12.19722535)', '(75)'], {}), '(12.19722535, 75)\n', (9029, 9046), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((9123, 9157), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['(12.19722535)', '(95)'], {}), '(12.19722535, 95)\n', (9140, 9157), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((9549, 9569), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['Y'], {}), '(Y)\n', (9566, 9569), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((9708, 9728), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['Y'], {}), '(Y)\n', (9725, 9728), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((9873, 9893), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['Y'], {}), '(Y)\n', (9890, 9893), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((10705, 10756), 'numpy.array', 'np.array', (['[-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]'], {}), '([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])\n', (10713, 10756), True, 'import numpy as np\n'), ((11146, 11188), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['(12.19722535 / 100)'], {}), '(12.19722535 / 100)\n', (11169, 11188), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((11289, 11331), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['(23.04276781 / 100)'], {}), '(23.04276781 / 100)\n', (11312, 11331), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((11432, 11473), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['(6.15720079 / 100)'], {}), '(6.15720079 / 100)\n', (11455, 11473), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((11574, 11622), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['(12.19722535 / 100)', '(2.75)'], {}), '(12.19722535 / 100, 2.75)\n', (11597, 11622), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((11723, 11752), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['(1008)'], {}), '(1008)\n', (11746, 11752), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((11830, 11861), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['(100800)'], {}), '(100800)\n', (11853, 11861), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((12288, 12314), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['Y'], {}), '(Y)\n', (12311, 12314), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((12463, 12489), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['Y'], {}), '(Y)\n', (12486, 12489), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((12644, 12670), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['Y'], {}), '(Y)\n', (12667, 12670), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((13563, 13614), 'numpy.array', 'np.array', (['[-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]'], {}), '([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])\n', (13571, 13614), True, 'import numpy as np\n'), ((14004, 14046), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['(12.19722535 / 100)'], {}), '(12.19722535 / 100)\n', (14027, 14046), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((14147, 14189), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['(23.04276781 / 100)'], {}), '(23.04276781 / 100)\n', (14170, 14189), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((14290, 14331), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['(6.15720079 / 100)'], {}), '(6.15720079 / 100)\n', (14313, 14331), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((14432, 14480), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['(12.19722535 / 100)', '(2.75)'], {}), '(12.19722535 / 100, 2.75)\n', (14455, 14480), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((14582, 14611), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['(1008)'], {}), '(1008)\n', (14605, 14611), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((14682, 14713), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['(100800)'], {}), '(100800)\n', (14705, 14713), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((15132, 15158), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['Y'], {}), '(Y)\n', (15155, 15158), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((15307, 15333), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['Y'], {}), '(Y)\n', (15330, 15333), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((15488, 15514), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['Y'], {}), '(Y)\n', (15511, 15514), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((16407, 16458), 'numpy.array', 'np.array', (['[-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]'], {}), '([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan])\n', (16415, 16458), True, 'import numpy as np\n'), ((16919, 16958), 'colour.colorimetry.lightness.lightness', 'lightness', (['(12.19722535)', 'method'], {'Y_n': '(100)'}), '(12.19722535, method, Y_n=100)\n', (16928, 16958), False, 'from colour.colorimetry.lightness import lightness\n'), ((2758, 2783), 'colour.utilities.domain_range_scale', 'domain_range_scale', (['scale'], {}), '(scale)\n', (2776, 2783), False, 'from colour.utilities import domain_range_scale, ignore_numpy_errors\n'), ((5005, 5030), 'colour.utilities.domain_range_scale', 'domain_range_scale', (['scale'], {}), '(scale)\n', (5023, 5030), False, 'from colour.utilities import domain_range_scale, ignore_numpy_errors\n'), ((7657, 7682), 'colour.utilities.domain_range_scale', 'domain_range_scale', (['scale'], {}), '(scale)\n', (7675, 7682), False, 'from colour.utilities import domain_range_scale, ignore_numpy_errors\n'), ((10276, 10301), 'colour.utilities.domain_range_scale', 'domain_range_scale', (['scale'], {}), '(scale)\n', (10294, 10301), False, 'from colour.utilities import domain_range_scale, ignore_numpy_errors\n'), ((13093, 13118), 'colour.utilities.domain_range_scale', 'domain_range_scale', (['scale'], {}), '(scale)\n', (13111, 13118), False, 'from colour.utilities import domain_range_scale, ignore_numpy_errors\n'), ((15937, 15962), 'colour.utilities.domain_range_scale', 'domain_range_scale', (['scale'], {}), '(scale)\n', (15955, 15962), False, 'from colour.utilities import domain_range_scale, ignore_numpy_errors\n'), ((2853, 2896), 'colour.colorimetry.lightness_Glasser1958', 'lightness_Glasser1958', (['(12.19722535 * factor)'], {}), '(12.19722535 * factor)\n', (2874, 2896), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((5100, 5144), 'colour.colorimetry.lightness_Wyszecki1963', 'lightness_Wyszecki1963', (['(12.19722535 * factor)'], {}), '(12.19722535 * factor)\n', (5122, 5144), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((7752, 7809), 'colour.colorimetry.intermediate_lightness_function_CIE1976', 'intermediate_lightness_function_CIE1976', (['(12.19722535)', '(100)'], {}), '(12.19722535, 100)\n', (7791, 7809), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((10371, 10415), 'colour.colorimetry.lightness_CIE1976', 'lightness_CIE1976', (['(12.19722535 * factor)', '(100)'], {}), '(12.19722535 * factor, 100)\n', (10388, 10415), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((13188, 13241), 'colour.colorimetry.lightness_Fairchild2010', 'lightness_Fairchild2010', (['(12.19722535 / 100 * factor_a)'], {}), '(12.19722535 / 100 * factor_a)\n', (13211, 13241), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((16032, 16085), 'colour.colorimetry.lightness_Fairchild2011', 'lightness_Fairchild2011', (['(12.19722535 / 100 * factor_a)'], {}), '(12.19722535 / 100 * factor_a)\n', (16055, 16085), False, 'from colour.colorimetry import lightness_Glasser1958, lightness_Wyszecki1963, intermediate_lightness_function_CIE1976, lightness_CIE1976, lightness_Fairchild2010, lightness_Fairchild2011\n'), ((17130, 17155), 'colour.utilities.domain_range_scale', 'domain_range_scale', (['scale'], {}), '(scale)\n', (17148, 17155), False, 'from colour.utilities import domain_range_scale, ignore_numpy_errors\n'), ((17233, 17281), 'colour.colorimetry.lightness.lightness', 'lightness', (['(12.19722535 * factor)', 'method'], {'Y_n': '(100)'}), '(12.19722535 * factor, method, Y_n=100)\n', (17242, 17281), False, 'from colour.colorimetry.lightness import lightness\n')]
""" A :class:`~glue.core.subset_group.SubsetGroup` unites a group of :class:`~glue.core.subset.Subset` instances together with a consistent state, label, and style. While subsets are internally associated with particular datasets, it's confusing for the user to juggle multiple similar or identical subsets, applied to different datasets. Because of this, the GUI manages SubsetGroups, and presents each group to the user as a single entity. The individual subsets are held in-sync by the SubsetGroup. Client code should *only* create Subset Groups via DataCollection.new_subset_group. It should *not* call Data.add_subset or Data.new_subset directly """ from __future__ import absolute_import, division, print_function from warnings import warn from glue.external import six from glue.core.contracts import contract from glue.core.message import (DataCollectionAddMessage, DataCollectionDeleteMessage) from glue.core.visual import VisualAttributes from glue.core.hub import HubListener from glue.utils import Pointer from glue.core.subset import SubsetState from glue.core import Subset from glue.config import settings __all__ = ['GroupedSubset', 'SubsetGroup'] class GroupedSubset(Subset): """ A member of a SubsetGroup, whose internal representation is shared with other group members """ subset_state = Pointer('group.subset_state') label = Pointer('group.label') def __init__(self, data, group): """ :param data: :class:`~glue.core.data.Data` instance to bind to :param group: :class:`~glue.core.subset_group.SubsetGroup` """ # We deliberately don't call Subset.__init__ here because we don't want # to set e.g. the subset state, color, transparency, etc. Instead we # just want to defer to the SubsetGroup for these. self._broadcasting = False # must be first def self.group = group self.data = data self.label = group.label # trigger disambiguation @property def style(self): return self.group.style @property def subset_group(self): return self.group.subset_group @property def verbose_label(self): return "%s (%s)" % (self.label, self.data.label) def __eq__(self, other): return other is self # In Python 3, if __eq__ is defined, then __hash__ has to be re-defined if six.PY3: __hash__ = object.__hash__ def __gluestate__(self, context): return dict(group=context.id(self.group), style=context.do(self.style)) @classmethod def __setgluestate__(cls, rec, context): dummy_grp = SubsetGroup() # __init__ needs group.label self = cls(None, dummy_grp) yield self self.group = context.object(rec['group']) class SubsetGroup(HubListener): def __init__(self, color=settings.SUBSET_COLORS[0], alpha=0.5, label=None, subset_state=None): """ Create a new empty SubsetGroup Note: By convention, SubsetGroups should be created via DataCollection.new_subset. """ self.subsets = [] if subset_state is None: self.subset_state = SubsetState() else: self.subset_state = subset_state self.label = label self.style = VisualAttributes(parent=self) self.style.markersize *= 2.5 self.style.linewidth *= 2.5 self.style.color = color self.style.alpha = alpha @contract(data='isinstance(DataCollection)') def register(self, data): """ Register to a :class:`~glue.core.data_collection.DataCollection` This is called automatically by :meth:`glue.core.data_collection.DataCollection.new_subset_group` """ self.register_to_hub(data.hub) # add to self, then register, so fully populated by first # broadcast for d in data: s = GroupedSubset(d, self) self.subsets.append(s) for d, s in zip(data, self.subsets): d.add_subset(s) def paste(self, other_subset): """paste subset state from other_subset onto self """ state = other_subset.subset_state.copy() self.subset_state = state def _add_data(self, data): # add a new data object to group s = GroupedSubset(data, self) data.add_subset(s) self.subsets.append(s) def _remove_data(self, data): # remove a data object from group for s in list(self.subsets): if s.data is data: self.subsets.remove(s) def register_to_hub(self, hub): hub.subscribe(self, DataCollectionAddMessage, lambda x: self._add_data(x.data)) hub.subscribe(self, DataCollectionDeleteMessage, lambda x: self._remove_data(x.data)) @property def style(self): return self._style @style.setter def style(self, value): self._style = value @contract(item='string') def broadcast(self, item): for s in self.subsets: s.broadcast(item) def __setattr__(self, attr, value): # We terminate early here if the value is not None but hasn't changed # to avoid broadcasting a message after. if value is not None and value == getattr(self, attr, None): return object.__setattr__(self, attr, value) if attr in ['subset_state', 'label', 'style']: self.broadcast(attr) def __gluestate__(self, context): return dict(label=self.label, state=context.id(self.subset_state), style=context.do(self.style), subsets=list(map(context.id, self.subsets))) @classmethod def __setgluestate__(cls, rec, context): result = cls() yield result result.subset_state = context.object(rec['state']) result.label = rec['label'] result.style = context.object(rec['style']) result.style.parent = result result.subsets = list(map(context.object, rec['subsets'])) def __and__(self, other): return self.subset_state & other.subset_state def __or__(self, other): return self.subset_state | other.subset_state def __xor__(self, other): return self.subset_state ^ other.subset_state def __invert__(self): return ~self.subset_state def coerce_subset_groups(collect): """ If necessary, reassign non-grouped subsets in a DataCollection into SubsetGroups. This is used to support DataCollections saved with version 1 of glue.core.state.save_data_collection """ for data in collect: for subset in data.subsets: if not isinstance(subset, GroupedSubset): warn("DataCollection has subsets outside of " "subset groups, which are no longer supported. " "Moving to subset groups") subset.delete() grp = collect.new_subset_group() grp.subset_state = subset.subset_state grp.style = subset.style grp.label = subset.label
[ "glue.core.visual.VisualAttributes", "glue.utils.Pointer", "glue.core.contracts.contract", "warnings.warn", "glue.core.subset.SubsetState" ]
[((1368, 1397), 'glue.utils.Pointer', 'Pointer', (['"""group.subset_state"""'], {}), "('group.subset_state')\n", (1375, 1397), False, 'from glue.utils import Pointer\n'), ((1410, 1432), 'glue.utils.Pointer', 'Pointer', (['"""group.label"""'], {}), "('group.label')\n", (1417, 1432), False, 'from glue.utils import Pointer\n'), ((3516, 3559), 'glue.core.contracts.contract', 'contract', ([], {'data': '"""isinstance(DataCollection)"""'}), "(data='isinstance(DataCollection)')\n", (3524, 3559), False, 'from glue.core.contracts import contract\n'), ((5043, 5066), 'glue.core.contracts.contract', 'contract', ([], {'item': '"""string"""'}), "(item='string')\n", (5051, 5066), False, 'from glue.core.contracts import contract\n'), ((3341, 3370), 'glue.core.visual.VisualAttributes', 'VisualAttributes', ([], {'parent': 'self'}), '(parent=self)\n', (3357, 3370), False, 'from glue.core.visual import VisualAttributes\n'), ((3218, 3231), 'glue.core.subset.SubsetState', 'SubsetState', ([], {}), '()\n', (3229, 3231), False, 'from glue.core.subset import SubsetState\n'), ((6855, 6980), 'warnings.warn', 'warn', (['"""DataCollection has subsets outside of subset groups, which are no longer supported. Moving to subset groups"""'], {}), "(\n 'DataCollection has subsets outside of subset groups, which are no longer supported. Moving to subset groups'\n )\n", (6859, 6980), False, 'from warnings import warn\n')]
import random #Generate a random number to be guessed number = random.randint(0, 100) print("Guess a magic number between 0 and 100") while True: #Prompt the user to guess the number guess = eval(input("Enter your guess: ")) if guess == number: print("Yes, the number is " + str(number)) break elif guess > number: print("Your guess is too high") else: print("Your guess is too low")
[ "random.randint" ]
[((64, 86), 'random.randint', 'random.randint', (['(0)', '(100)'], {}), '(0, 100)\n', (78, 86), False, 'import random\n')]
# XXX depends on internet connectivity, so not run as part of standard tests from __future__ import absolute_import, division, print_function def exercise(): from mmtbx.wwpdb import rcsb_web_services lysozyme = """<KEY>""" homologs = rcsb_web_services.sequence_search(lysozyme, d_max=2.0) assert (len(homologs) > 500) atp_binding = rcsb_web_services.chemical_id_search("ATP", protein_only=True) assert (len(atp_binding) > 650) report = rcsb_web_services.get_high_resolution_for_structures(atp_binding) assert (len(report) == len(atp_binding)) and (len(report[0]) == 2) ligand_info = rcsb_web_services.get_ligand_info_for_structures(['1mru']) assert (len(ligand_info) == 4) print("OK") if (__name__ == "__main__"): exercise()
[ "mmtbx.wwpdb.rcsb_web_services.chemical_id_search", "mmtbx.wwpdb.rcsb_web_services.get_ligand_info_for_structures", "mmtbx.wwpdb.rcsb_web_services.get_high_resolution_for_structures", "mmtbx.wwpdb.rcsb_web_services.sequence_search" ]
[((243, 297), 'mmtbx.wwpdb.rcsb_web_services.sequence_search', 'rcsb_web_services.sequence_search', (['lysozyme'], {'d_max': '(2.0)'}), '(lysozyme, d_max=2.0)\n', (276, 297), False, 'from mmtbx.wwpdb import rcsb_web_services\n'), ((345, 407), 'mmtbx.wwpdb.rcsb_web_services.chemical_id_search', 'rcsb_web_services.chemical_id_search', (['"""ATP"""'], {'protein_only': '(True)'}), "('ATP', protein_only=True)\n", (381, 407), False, 'from mmtbx.wwpdb import rcsb_web_services\n'), ((453, 518), 'mmtbx.wwpdb.rcsb_web_services.get_high_resolution_for_structures', 'rcsb_web_services.get_high_resolution_for_structures', (['atp_binding'], {}), '(atp_binding)\n', (505, 518), False, 'from mmtbx.wwpdb import rcsb_web_services\n'), ((604, 662), 'mmtbx.wwpdb.rcsb_web_services.get_ligand_info_for_structures', 'rcsb_web_services.get_ligand_info_for_structures', (["['1mru']"], {}), "(['1mru'])\n", (652, 662), False, 'from mmtbx.wwpdb import rcsb_web_services\n')]
from insertion_sort import insertion_sort def test_insertion_sort_one(): arr =[4,1,5,6,3] assert insertion_sort(arr) == [1,3,4,5,6,] def test_insertion_sort_two(): arr =[20,11,14,17,19] assert insertion_sort(arr) == [11,14,17,19,20] def test_insertion_sort_empty(): arr =[] assert insertion_sort(arr) == 'List is empty.'
[ "insertion_sort.insertion_sort" ]
[((107, 126), 'insertion_sort.insertion_sort', 'insertion_sort', (['arr'], {}), '(arr)\n', (121, 126), False, 'from insertion_sort import insertion_sort\n'), ((211, 230), 'insertion_sort.insertion_sort', 'insertion_sort', (['arr'], {}), '(arr)\n', (225, 230), False, 'from insertion_sort import insertion_sort\n'), ((307, 326), 'insertion_sort.insertion_sort', 'insertion_sort', (['arr'], {}), '(arr)\n', (321, 326), False, 'from insertion_sort import insertion_sort\n')]
from tests import BaseTestCase from flask import Flask from nose.tools import assert_equals class MongoDBURITestCase(BaseTestCase): "MongoDB URI generation" def setup(self): self.app = Flask(__name__) self.app.config['MONGOALCHEMY_DATABASE'] = 'test' def should_use_localhost_for_server_and_27017_for_port_when_only_the_database_name_was_specified(self): from flaskext.mongoalchemy import _get_mongo_uri assert_equals(_get_mongo_uri(self.app), 'mongodb://localhost:27017') def should_be_able_to_generate_an_uri_using_only_the_username_without_password(self): self.app.config['MONGOALCHEMY_USER'] = 'luke' from flaskext.mongoalchemy import _get_mongo_uri assert_equals(_get_mongo_uri(self.app), 'mongodb://luke@localhost:27017') def should_be_able_to_generate_an_uri_using_an_username_and_a_password(self): self.app.config['MONGOALCHEMY_USER'] = 'luke' self.app.config['MONGOALCHEMY_PASSWORD'] = '<PASSWORD>' from flaskext.mongoalchemy import _get_mongo_uri assert_equals(_get_mongo_uri(self.app), 'mongodb://luke:father@localhost:27017') def should_be_able_to_use_not_only_localhost_for_server_and_27017_for_port(self): self.app.config['MONGOALCHEMY_SERVER'] = 'database.lukehome.com' self.app.config['MONGOALCHEMY_PORT'] = '42' from flaskext.mongoalchemy import _get_mongo_uri assert_equals(_get_mongo_uri(self.app), 'mongodb://database.lukehome.com:42') def should_be_able_to_generate_an_uri_with_options(self): self.app.config['MONGOALCHEMY_SERVER'] = 'database.lukehome.com' self.app.config['MONGOALCHEMY_OPTIONS'] = 'safe=true' from flaskext.mongoalchemy import _get_mongo_uri assert_equals(_get_mongo_uri(self.app), 'mongodb://database.lukehome.com:27017/?safe=true')
[ "flaskext.mongoalchemy._get_mongo_uri", "flask.Flask" ]
[((203, 218), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (208, 218), False, 'from flask import Flask\n'), ((465, 489), 'flaskext.mongoalchemy._get_mongo_uri', '_get_mongo_uri', (['self.app'], {}), '(self.app)\n', (479, 489), False, 'from flaskext.mongoalchemy import _get_mongo_uri\n'), ((744, 768), 'flaskext.mongoalchemy._get_mongo_uri', '_get_mongo_uri', (['self.app'], {}), '(self.app)\n', (758, 768), False, 'from flaskext.mongoalchemy import _get_mongo_uri\n'), ((1084, 1108), 'flaskext.mongoalchemy._get_mongo_uri', '_get_mongo_uri', (['self.app'], {}), '(self.app)\n', (1098, 1108), False, 'from flaskext.mongoalchemy import _get_mongo_uri\n'), ((1442, 1466), 'flaskext.mongoalchemy._get_mongo_uri', '_get_mongo_uri', (['self.app'], {}), '(self.app)\n', (1456, 1466), False, 'from flaskext.mongoalchemy import _get_mongo_uri\n'), ((1783, 1807), 'flaskext.mongoalchemy._get_mongo_uri', '_get_mongo_uri', (['self.app'], {}), '(self.app)\n', (1797, 1807), False, 'from flaskext.mongoalchemy import _get_mongo_uri\n')]
#!/usr/bin/env python3 import sys import os from glob import glob from constants import CHESSBOARDS_DIR, TILES_DIR OUT_FILE = 'images.html' def _save_output_html(tile_dirs): html = '<html lang="en">' html += '<link rel="stylesheet" href="./web/style.css" />' for tile_dir in tile_dirs: img_dir = tile_dir.split('/')[-2] img_filename_prefix = tile_dir.split('/')[-1] chessboard_img_path = os.path.join( CHESSBOARDS_DIR, img_dir, '{}.png'.format(img_filename_prefix) ) html += '<h3>{}</h3>'.format(chessboard_img_path) html += '<img src="{}" class="chessboard"/>'.format(chessboard_img_path) html += '<h3>{}</h3>'.format(tile_dir) square_map = {} for tile_img_path in glob(os.path.join(tile_dir, '*.png')): square_id = tile_img_path[-8:-6] fen_char = tile_img_path[-5] square_map[square_id] = { 'img_src': tile_img_path, 'fen_char': fen_char, } for rank in [8,7,6,5,4,3,2,1]: for file in ['a','b','c','d','e','f','g','h']: square_id = '{}{}'.format(file, rank) square = square_map[square_id] fen_char = square['fen_char'] html += '<img src="{}"/>'.format(square['img_src']) html += '<span class="fen-char {}">{}</span>'.format( 'empty' if fen_char is '1' else '', fen_char ) html += '<br />' html += '<br />' html += '</html>' with open(OUT_FILE, 'w') as f: f.write(html) if __name__ == '__main__': sub_dir = sys.argv[1] if len(sys.argv) > 1 else '*' tiles_base_dir = os.path.join(TILES_DIR, sub_dir, '*') print('Looking for tile images in {}'.format(tiles_base_dir)) print('Found {} tile images'.format( len(glob(os.path.join(tiles_base_dir, '*.png'))) )) _save_output_html(glob(tiles_base_dir)) print('Open {} to view all tile images'.format(OUT_FILE))
[ "os.path.join", "glob.glob" ]
[((1747, 1784), 'os.path.join', 'os.path.join', (['TILES_DIR', 'sub_dir', '"""*"""'], {}), "(TILES_DIR, sub_dir, '*')\n", (1759, 1784), False, 'import os\n'), ((1978, 1998), 'glob.glob', 'glob', (['tiles_base_dir'], {}), '(tiles_base_dir)\n', (1982, 1998), False, 'from glob import glob\n'), ((771, 802), 'os.path.join', 'os.path.join', (['tile_dir', '"""*.png"""'], {}), "(tile_dir, '*.png')\n", (783, 802), False, 'import os\n'), ((1909, 1946), 'os.path.join', 'os.path.join', (['tiles_base_dir', '"""*.png"""'], {}), "(tiles_base_dir, '*.png')\n", (1921, 1946), False, 'import os\n')]
#!/usr/bin/env python """ Demonstrate how to use major and minor tickers. The two relevant userland classes are Locators and Formatters. Locators determine where the ticks are and formatters control the formatting of ticks. Minor ticks are off by default (NullLocator and NullFormatter). You can turn minor ticks on w/o labels by setting the minor locator. You can also turn labeling on for the minor ticker by setting the minor formatter Make a plot with major ticks that are multiples of 20 and minor ticks that are multiples of 5. Label major ticks with %d formatting but don't label minor ticks The MultipleLocator ticker class is used to place ticks on multiples of some base. The FormatStrFormatter uses a string format string (eg '%d' or '%1.2f' or '%1.1f cm' ) to format the tick The pylab interface grid command changes the grid settings of the major ticks of the y and y axis together. If you want to control the grid of the minor ticks for a given axis, use for example ax.xaxis.grid(True, which='minor') Note, you should not use the same locator between different Axis because the locator stores references to the Axis data and view limits """ from pylab import * from matplotlib.ticker import MultipleLocator, FormatStrFormatter majorLocator = MultipleLocator(20) majorFormatter = FormatStrFormatter('%d') minorLocator = MultipleLocator(5) t = arange(0.0, 100.0, 0.1) s = sin(0.1*pi*t)*exp(-t*0.01) ax = subplot(111) plot(t,s) ax.xaxis.set_major_locator(majorLocator) ax.xaxis.set_major_formatter(majorFormatter) #for the minor ticks, use no labels; default NullFormatter ax.xaxis.set_minor_locator(minorLocator) show()
[ "matplotlib.ticker.MultipleLocator", "matplotlib.ticker.FormatStrFormatter" ]
[((1276, 1295), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(20)'], {}), '(20)\n', (1291, 1295), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter\n'), ((1313, 1337), 'matplotlib.ticker.FormatStrFormatter', 'FormatStrFormatter', (['"""%d"""'], {}), "('%d')\n", (1331, 1337), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter\n'), ((1355, 1373), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(5)'], {}), '(5)\n', (1370, 1373), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter\n')]
# -*- coding: utf-8 -*- """Module with form and form field definitions.""" from django import forms from .bibliography.storage import FileType __all__ = ('BibliographyUploadFileForm', 'BibliographyUploadEntryForm') class FileTypeField(forms.TypedChoiceField): """Form field that provides a choice of a :class:`biblary.bibliography.storage.FileType`.""" def __init__(self, *, choices=None, coerce=None, empty_value=None, **kwargs): """Construct a new instance. The ``choices``, ``coerce`` and ``empty_value`` argument of the ``forms.TypedChoiceField`` base class static and automatically determined from the :class:`biblary.bibliography.storage.FileType` enum. The constructor will raise a ``ValueError`` if they are specified. :raises ValueError: if ``choices``, ``coerce`` or ``empty_value`` are defined. """ super().__init__(**kwargs) for arg in [choices, coerce, empty_value]: if arg is not None: raise ValueError(f'`{arg.__name__}` cannot be changed for the `FileTypeField`.') self.choices = [(file_type.value, file_type.value) for file_type in FileType] self.coerce = FileType self.empty_value = () class BibliographyUploadFileForm(forms.Form): """Form to upload a file of a given type for the specified bibligraphic entry. .. note:: The choices of the ``entry_identifier`` have to be specified in the view that presents the form because those should depend on the :class:`biblary.bibliography.Bibliography` that is configured and loaded. The values should correspond to the entries of the :class:`biblary.bibliography.entry.BibliographicEntry`'s. """ entry_identifier = forms.ChoiceField(label='Entry') file_type = FileTypeField(label='Type') content = forms.FileField(label='File') class BibliographyUploadEntryForm(forms.Form): """Form to upload a bibligraphic entry.""" content = forms.CharField(label='', widget=forms.Textarea())
[ "django.forms.ChoiceField", "django.forms.FileField", "django.forms.Textarea" ]
[((1745, 1777), 'django.forms.ChoiceField', 'forms.ChoiceField', ([], {'label': '"""Entry"""'}), "(label='Entry')\n", (1762, 1777), False, 'from django import forms\n'), ((1836, 1865), 'django.forms.FileField', 'forms.FileField', ([], {'label': '"""File"""'}), "(label='File')\n", (1851, 1865), False, 'from django import forms\n'), ((2010, 2026), 'django.forms.Textarea', 'forms.Textarea', ([], {}), '()\n', (2024, 2026), False, 'from django import forms\n')]
# Copyright 2019 by <NAME>. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Tests for SearchIO HhsuiteIO parsers.""" import os import unittest from Bio.SearchIO import parse # test case files are in the Blast directory TEST_DIR = "HHsuite" FMT = "hhsuite2-text" def get_file(filename): """Return the path of a test file.""" return os.path.join(TEST_DIR, filename) class HhsuiteCases(unittest.TestCase): """Test hhsuite2 output.""" def test_2uvo(self): """Parsing 2uvo.""" txt_file = get_file("2uvo_hhblits.hhr") qresults = parse(txt_file, FMT) # test first and only qresult qresult = next(qresults) num_hits = 16 self.assertEqual("HHSUITE", qresult.program) self.assertEqual("2UVO:A|PDBID|CHAIN|SEQUENCE", qresult.id) self.assertEqual(171, qresult.seq_len) self.assertEqual(num_hits, len(qresult)) hit = qresult[0] self.assertEqual("2uvo_A", hit.id) self.assertEqual("Agglutinin isolectin 1; carbohydrate-binding protein, hevein domain, chitin-binding," " GERM agglutinin, chitin-binding protein; HET: NDG NAG GOL; 1.40A {Triticum aestivum}" " PDB: 1wgc_A* 2cwg_A* 2x3t_A* 4aml_A* 7wga_A 9wga_A 2wgc_A 1wgt_A 1k7t_A* 1k7v_A* 1k7u_A" " 2x52_A* 1t0w_A*", hit.description) self.assertTrue(hit.is_included) self.assertEqual(3.7e-34, hit.evalue) self.assertEqual(210.31, hit.score) self.assertEqual(2, len(hit)) hsp = hit.hsps[0] self.assertTrue(hsp.is_included) self.assertEqual(0, hsp.output_index) self.assertEqual(99.95, hsp.prob) self.assertEqual(210.31, hsp.score) self.assertEqual(3.7e-34, hsp.evalue) self.assertEqual(0, hsp.hit_start) self.assertEqual(171, hsp.hit_end) self.assertEqual(0, hsp.query_start) self.assertEqual(171, hsp.query_end) self.assertEqual("ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGATCTNNQCCSQYGYCGFGAEYC" "GAGCQGGPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGGCQSGACSTDKPCGKDAGGRVCTNNYCCS" "KWGSCGIGPGYCGAGCQSGGCDG", str(hsp.hit.seq)) self.assertEqual("ERCGEQGSNMECPNNLCCSQYGYCGMGGDYCGKGCQNGACWTSKRCGSQAGGATCTNNQCCSQYGYCGFGAEYC" "GAGCQGGPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGGCQSGACSTDKPCGKDAGGRVCTNNYCCS" "KWGSCGIGPGYCGAGCQSGGCDG", str(hsp.query.seq)) # Check last hit hit = qresult[num_hits - 1] self.assertEqual("4z8i_A", hit.id) self.assertEqual("BBTPGRP3, peptidoglycan recognition protein 3; chitin-binding domain, " "AM hydrolase; 2.70A {Branchiostoma belcheri tsingtauense}", hit.description) self.assertTrue(hit.is_included) self.assertEqual(0.11, hit.evalue) self.assertEqual(36.29, hit.score) self.assertEqual(2, len(hit)) # Check we can get the original last HSP from the file. num_hsps = 32 self.assertEqual(num_hsps, len(qresult.hsps)) hsp = qresult.hsps[-1] self.assertTrue(hsp.is_included) self.assertEqual(num_hsps - 1, hsp.output_index) self.assertEqual(2.6, hsp.evalue) self.assertEqual(25.90, hsp.score) self.assertEqual(40.43, hsp.prob) self.assertEqual(10, hsp.hit_start) self.assertEqual(116, hsp.hit_end) self.assertEqual(53, hsp.query_start) self.assertEqual(163, hsp.query_end) self.assertEqual("XCXXXXCCXXXXXCXXXXXXCXXXCXXXXCXXXXXCXXX--XXXCXXXXCCXXXXXCXXXXXXCXXXCXXXXCXXXXXCX" "XX--XXXCXXXXCCXXXXXCXXXXXXCXXX", str(hsp.hit.seq)) self.assertEqual("TCTNNQCCSQYGYCGFGAEYCGAGCQGGPCRADIKCGSQAGGKLCPNNLCCSQWGFCGLGSEFCGGGCQSGACSTDKPCG" "KDAGGRVCTNNYCCSKWGSCGIGPGYCGAG", str(hsp.query.seq)) def test_2uvo_onlyheader(self): """Parsing 4uvo with only header present.""" txt_file = get_file("2uvo_hhblits_onlyheader.hhr") qresults = parse(txt_file, FMT) with self.assertRaises(RuntimeError): next(qresults) def test_2uvo_emptytable(self): """Parsing 4uvo with empty results table.""" txt_file = get_file("2uvo_hhblits_emptytable.hhr") qresults = parse(txt_file, FMT) with self.assertRaises(RuntimeError): next(qresults) def test_allx(self): """Parsing allx.hhr file.""" txt_file = get_file("allx.hhr") qresults = parse(txt_file, FMT) # test first and only qresult qresult = next(qresults) num_hits = 10 self.assertEqual("HHSUITE", qresult.program) self.assertEqual("Only X amino acids", qresult.id) self.assertEqual(39, qresult.seq_len) self.assertEqual(num_hits, len(qresult)) hit = qresult[0] self.assertEqual("1klr_A", hit.id) self.assertEqual("Zinc finger Y-chromosomal protein; transcription; NMR {Synthetic} SCOP: g.37.1.1 PDB: " "5znf_A 1kls_A 1xrz_A* 7znf_A", hit.description) self.assertTrue(hit.is_included) self.assertEqual(3.4E+04, hit.evalue) self.assertEqual(-0.01, hit.score) self.assertEqual(1, len(hit)) hsp = hit.hsps[0] self.assertTrue(hsp.is_included) self.assertEqual(0, hsp.output_index) self.assertEqual(3.4E+04, hsp.evalue) self.assertEqual(-0.01, hsp.score) self.assertEqual(0.04, hsp.prob) self.assertEqual(23, hsp.hit_start) self.assertEqual(24, hsp.hit_end) self.assertEqual(38, hsp.query_start) self.assertEqual(39, hsp.query_end) self.assertEqual("T", str(hsp.hit.seq)) self.assertEqual("X", str(hsp.query.seq)) # Check last hit hit = qresult[num_hits - 1] self.assertEqual("1zfd_A", hit.id) self.assertEqual("SWI5; DNA binding motif, zinc finger DNA binding domain; NMR {Saccharomyces cerevisiae}" " SCOP: g.37.1.1", hit.description) self.assertTrue(hit.is_included) self.assertEqual(3.6e+04, hit.evalue) self.assertEqual(0.03, hit.score) self.assertEqual(1, len(hit)) # Check we can get the original last HSP from the file. num_hsps = num_hits self.assertEqual(num_hsps, len(qresult.hsps)) hsp = qresult.hsps[-1] self.assertTrue(hsp.is_included) self.assertEqual(num_hsps - 1, hsp.output_index) self.assertEqual(3.6e+04, hsp.evalue) self.assertEqual(0.03, hsp.score) self.assertEqual(0.03, hsp.prob) self.assertEqual(0, hsp.hit_start) self.assertEqual(1, hsp.hit_end) self.assertEqual(3, hsp.query_start) self.assertEqual(4, hsp.query_end) self.assertEqual("D", str(hsp.hit.seq)) self.assertEqual("X", str(hsp.query.seq)) def test_4y9h_nossm(self): """Parsing 4y9h_hhsearch_server_NOssm.hhr file.""" txt_file = get_file("4y9h_hhsearch_server_NOssm.hhr") qresults = parse(txt_file, FMT) # test first and only qresult qresult = next(qresults) num_hits = 29 self.assertEqual("HHSUITE", qresult.program) self.assertEqual("4Y9H:A|PDBID|CHAIN|SEQUENCE", qresult.id) self.assertEqual(226, qresult.seq_len) self.assertEqual(num_hits, len(qresult)) hit = qresult[0] self.assertEqual("5ZIM_A", hit.id) self.assertEqual("Bacteriorhodopsin; proton pump, membrane protein, PROTON; HET: L2P, RET; 1.25A {Halobacterium" " salinarum}; Related PDB entries: 1R84_A 1KG8_A 1KME_B 1KGB_A 1KG9_A 1KME_A 4X31_A 5ZIL_A 1E0P_A " "4X32_A 5ZIN_A 1S53_B 1S51_B 1S53_A 1S54_A 1F50_A 1S54_B 1S51_A 1F4Z_A 5J7A_A 1S52_B 1S52_A 4Y9H_A " "3T45_A 3T45_C 3T45_B 1C3W_A 1L0M_A", hit.description) self.assertTrue(hit.is_included) self.assertEqual(2.1e-48, hit.evalue) self.assertEqual(320.44, hit.score) self.assertEqual(1, len(hit)) hsp = hit.hsps[0] self.assertTrue(hsp.is_included) self.assertEqual(0, hsp.output_index) self.assertEqual(2.1e-48, hsp.evalue) self.assertEqual(320.44, hsp.score) self.assertEqual(100.00, hsp.prob) self.assertEqual(1, hsp.hit_start) self.assertEqual(227, hsp.hit_end) self.assertEqual(0, hsp.query_start) self.assertEqual(226, hsp.query_end) self.assertEqual("GRPEWIWLALGTALMGLGTLYFLVKGMGVSDPDAKKFYAITTLVPAIAFTMYLSMLLGYGLTMVPFGGEQNPIYWARYAD" "WLFTTPLLLLDLALLVDADQGTILALVGADGIMIGTGLVGALTKVYSYRFVWWAISTAAMLYILYVLFFGFTSKAESMRP" "EVASTFKVLRNVTVVLWSAYPVVWLIGSEGAGIVPLNIETLLFMVLDVSAKVGFGLILLRSRAIFG", str(hsp.hit.seq)) self.assertEqual("GRPEWIWLALGTALMGLGTLYFLVKGMGVSDPDAKKFYAITTLVPAIAFTMYLSMLLGYGLTMVPFGGEQNPIYWARYAD" "WLFTTPLLLLDLALLVDADQGTILALVGADGIMIGTGLVGALTKVYSYRFVWWAISTAAMLYILYVLFFGFTSKAESMRP" "EVASTFKVLRNVTVVLWSAYPVVWLIGSEGAGIVPLNIETLLFMVLDVSAKVGFGLILLRSRAIFG", str(hsp.query.seq)) # Check last hit hit = qresult[num_hits - 1] self.assertEqual("5ABB_Z", hit.id) self.assertEqual("PROTEIN TRANSLOCASE SUBUNIT SECY, PROTEIN; TRANSLATION, RIBOSOME, MEMBRANE PROTEIN, " "TRANSLOCON; 8.0A {ESCHERICHIA COLI}", hit.description) self.assertTrue(hit.is_included) self.assertEqual(3.3e-05, hit.evalue) self.assertEqual(51.24, hit.score) self.assertEqual(1, len(hit)) # Check we can get the original last HSP from the file. num_hsps = num_hits self.assertEqual(num_hsps, len(qresult.hsps)) hsp = qresult.hsps[-1] self.assertTrue(hsp.is_included) self.assertEqual(num_hsps - 1, hsp.output_index) self.assertEqual(3.3e-05, hsp.evalue) self.assertEqual(51.24, hsp.score) self.assertEqual(96.55, hsp.prob) self.assertEqual(14, hsp.hit_start) self.assertEqual(65, hsp.hit_end) self.assertEqual(7, hsp.query_start) self.assertEqual(59, hsp.query_end) self.assertEqual("FWLVTAALLASTVFFFVERDRVS-AKWKTSLTVSGLVTGIAFWHYMYMRGVW", str(hsp.hit.seq)) self.assertEqual("LALGTALMGLGTLYFLVKGMGVSDPDAKKFYAITTLVPAIAFTMYLSMLLGY", str(hsp.query.seq)) def test_q9bsu1(self): """Parsing hhsearch_q9bsu1_uniclust_w_ss_pfamA_30.hhr file.""" txt_file = get_file("hhsearch_q9bsu1_uniclust_w_ss_pfamA_30.hhr") qresults = parse(txt_file, FMT) # test first and only qresult qresult = next(qresults) num_hits = 12 self.assertEqual("HHSUITE", qresult.program) self.assertEqual("sp|Q9BSU1|CP070_HUMAN UPF0183 protein C16orf70 OS=Homo sapiens OX=9606 GN=C16orf70" " PE=1 SV=1", qresult.id) self.assertEqual(422, qresult.seq_len) self.assertEqual(num_hits, len(qresult)) hit = qresult[0] self.assertEqual("PF03676.13", hit.id) self.assertEqual("UPF0183 ; Uncharacterised protein family (UPF0183)", hit.description) self.assertTrue(hit.is_included) self.assertEqual(2e-106, hit.evalue) self.assertEqual(822.75, hit.score) self.assertEqual(1, len(hit)) hsp = hit.hsps[0] self.assertTrue(hsp.is_included) self.assertEqual(0, hsp.output_index) self.assertEqual(2e-106, hsp.evalue) self.assertEqual(822.75, hsp.score) self.assertEqual(100.00, hsp.prob) self.assertEqual(0, hsp.hit_start) self.assertEqual(395, hsp.hit_end) self.assertEqual(10, hsp.query_start) self.assertEqual(407, hsp.query_end) self.assertEqual("SLGNEQWEFTLGMPLAQAVAILQKHCRIIKNVQVLYSEQSPLSHDLILNLTQDGIKLMFDAFNQRLKVIEVCDLTKVKLK" "YCGVHFNSQAIAPTIEQIDQSFGATHPGVYNSAEQLFHLNFRGLSFSFQLDSWTEAPKYEPNFAHGLASLQIPHGATVKR" "MYIYSGNSLQDTKAPMMPLSCFLGNVYAESVDVLRDGTGPAGLRLRLLAAGCGPGLLADAKMRVFERSVYFGDSCQDVLS" "MLGSPHKVFYKSEDKMKIHSPSPHKQVPSKCNDYFFNYFTLGVDILFDANTHKVKKFVLHTNYPGHYNFNIYHRCEFKIP" "LAIKKENADGQTE--TCTTYSKWDNIQELLGHPVEKPVVLHRSSSPNNTNPFGSTFCFGLQRMIFEVMQNNHIASVTLY", str(hsp.query.seq)) self.assertEqual("EQWE----FALGMPLAQAISILQKHCRIIKNVQVLYSEQMPLSHDLILNLTQDGIKLLFDACNQRLKVIEVYDLTKVKLK" "YCGVHFNSQAIAPTIEQIDQSFGATHPGVYNAAEQLFHLNFRGLSFSFQLDSWSEAPKYEPNFAHGLASLQIPHGATVKR" "MYIYSGNNLQETKAPAMPLACFLGNVYAECVEVLRDGAGPLGLKLRLLTAGCGPGVLADTKVRAVERSIYFGDSCQDVLS" "ALGSPHKVFYKSEDKMKIHSPSPHKQVPSKCNDYFFNYYILGVDILFDSTTHLVKKFVLHTNFPGHYNFNIYHRCDFKIP" "LIIKKDGADAHSEDCILTTYSKWDQIQELLGHPMEKPVVLHRSSSANNTNPFGSTFCFGLQRMIFEVMQNNHIASVTLY", str(hsp.hit.seq)) # Check last hit hit = qresult[num_hits - 1] self.assertEqual("PF10049.8", hit.id) self.assertEqual("DUF2283 ; Protein of unknown function (DUF2283)", hit.description) self.assertTrue(hit.is_included) self.assertEqual(78, hit.evalue) self.assertEqual(19.81, hit.score) self.assertEqual(1, len(hit)) # Check we can get the original last HSP from the file. num_hsps = 16 self.assertEqual(num_hsps, len(qresult.hsps)) hsp = qresult.hsps[-1] self.assertTrue(hsp.is_included) self.assertEqual(num_hsps - 1, hsp.output_index) self.assertEqual(78, hsp.evalue) self.assertEqual(19.81, hsp.score) self.assertEqual(20.88, hsp.prob) self.assertEqual(25, hsp.hit_start) self.assertEqual(48, hsp.hit_end) self.assertEqual(61, hsp.query_start) self.assertEqual(85, hsp.query_end) self.assertEqual("APNVIFDYDA-EGRIVGIELLDAR", str(hsp.hit.seq)) self.assertEqual("QDGIKLMFDAFNQRLKVIEVCDLT", str(hsp.query.seq)) def test_4p79(self): """Parsing 4p79_hhsearch_server_NOssm.hhr file.""" txt_file = get_file("4p79_hhsearch_server_NOssm.hhr") qresults = parse(txt_file, FMT) # test first and only qresult qresult = next(qresults) num_hits = 8 self.assertEqual("HHSUITE", qresult.program) self.assertEqual("4P79:A|PDBID|CHAIN|SEQUENCE", qresult.id) self.assertEqual(198, qresult.seq_len) self.assertEqual(num_hits, len(qresult)) hit = qresult[0] self.assertEqual("4P79_A", hit.id) self.assertEqual("cell adhesion protein; cell adhesion, tight junction, membrane; HET: OLC" ", MSE; 2.4A {Mus musculus}", hit.description) self.assertTrue(hit.is_included) self.assertEqual(6.8e-32, hit.evalue) self.assertEqual(194.63, hit.score) self.assertEqual(1, len(hit)) hsp = hit.hsps[0] self.assertTrue(hsp.is_included) self.assertEqual(0, hsp.output_index) self.assertEqual(6.8e-32, hsp.evalue) self.assertEqual(194.63, hsp.score) self.assertEqual(99.94, hsp.prob) self.assertEqual(0, hsp.hit_start) self.assertEqual(198, hsp.hit_end) self.assertEqual(0, hsp.query_start) self.assertEqual(198, hsp.query_end) self.assertEqual("GSEFMSVAVETFGFFMSALGLLMLGLTLSNSYWRVSTVHGNVITTNTIFENLWYSCATDSLGVSNCWDFPSMLALSGYVQ" "GCRALMITAILLGFLGLFLGMVGLRATNVGNMDLSKKAKLLAIAGTLHILAGACGMVAISWYAVNITTDFFNPLYAGTKY" "ELGPALYLGWSASLLSILGGICVFSTAAASSKEEPATR", str(hsp.query.seq)) self.assertEqual("GSEFMSVAVETFGFFMSALGLLMLGLTLSNSYWRVSTVHGNVITTNTIFENLWYSCATDSLGVSNCWDFPSMLALSGYVQ" "GCRALMITAILLGFLGLFLGMVGLRATNVGNMDLSKKAKLLAIAGTLHILAGACGMVAISWYAVNITTDFFNPLYAGTKY" "ELGPALYLGWSASLLSILGGICVFSTAAASSKEEPATR", str(hsp.hit.seq)) # Check last hit hit = qresult[num_hits - 1] self.assertEqual("5YQ7_F", hit.id) self.assertEqual("Beta subunit of light-harvesting 1; Photosynthetic core complex, PHOTOSYNTHESIS; " "HET: MQE, BCL, HEM, KGD, BPH;{Roseiflexus castenholzii}; Related PDB entries: 5YQ7_V" " 5YQ7_3 5YQ7_T 5YQ7_J 5YQ7_9 5YQ7_N 5YQ7_A 5YQ7_P 5YQ7_H 5YQ7_D 5YQ7_5 5YQ7_7 5YQ7_1 " "5YQ7_R", hit.description) self.assertTrue(hit.is_included) self.assertEqual(6.7, hit.evalue) self.assertEqual(20.51, hit.score) self.assertEqual(1, len(hit)) # Check we can get the original last HSP from the file. num_hsps = num_hits self.assertEqual(num_hsps, len(qresult.hsps)) hsp = qresult.hsps[-1] self.assertTrue(hsp.is_included) self.assertEqual(num_hsps - 1, hsp.output_index) self.assertEqual(6.7, hsp.evalue) self.assertEqual(20.51, hsp.score) self.assertEqual(52.07, hsp.prob) self.assertEqual(8, hsp.hit_start) self.assertEqual(42, hsp.hit_end) self.assertEqual(5, hsp.query_start) self.assertEqual(37, hsp.query_end) self.assertEqual("RTSVVVSTLLGLVMALLIHFVVLSSGAFNWLRAP", str(hsp.hit.seq)) self.assertEqual("SVAVETFGFFMSALGLLMLGLTLSNS--YWRVST", str(hsp.query.seq)) def test_9590198(self): """Parsing hhpred_9590198.hhr file.""" txt_file = get_file("hhpred_9590198.hhr") qresults = parse(txt_file, FMT) # test first and only qresult qresult = next(qresults) num_hits = 22 self.assertEqual("HHSUITE", qresult.program) self.assertEqual("sp|Q9BSU1|CP070_HUMAN UPF0183 protein C16orf70 OS=Homo sapiens OX=9606 GN=C16orf70" " PE=1 SV=1", qresult.id) self.assertEqual(422, qresult.seq_len) self.assertEqual(num_hits, len(qresult)) hit = qresult[0] self.assertEqual("PF03676.14", hit.id) self.assertEqual("UPF0183 ; Uncharacterised protein family (UPF0183)", hit.description) self.assertTrue(hit.is_included) self.assertEqual(9.9e-102, hit.evalue) self.assertEqual(792.76, hit.score) self.assertEqual(1, len(hit)) hsp = hit.hsps[0] self.assertTrue(hsp.is_included) self.assertEqual(0, hsp.output_index) self.assertEqual(9.9e-102, hsp.evalue) self.assertEqual(792.76, hsp.score) self.assertEqual(100.00, hsp.prob) self.assertEqual(0, hsp.hit_start) self.assertEqual(394, hsp.hit_end) self.assertEqual(21, hsp.query_start) self.assertEqual(407, hsp.query_end) self.assertEqual("GMHFSQSVAIIQSQVGTIRGVQVLYSDQNPLSVDLVINMPQDGMRLIFDPVAQRLKIIEIYNMKLVKLRYSGMCFNSPEI" "TPSIEQVEHCFGATHPGLYDSQRHLFALNFRGLSFYFPVDS-----KFEPGYAHGLGSLQFPNGGSPVVSRTTIYYGSQH" "QLSSNTSSRVSGVPLPDLPLSCYRQQLHLRRCDVLRNTTSTMGLRLHMFTEGT--SRALEPSQVALVRVVRFGDSCQGVA" "RALGAPARLYYKADDKMRIHRPTARRR-PPPASDYLFNYFTLGLDVLFDARTNQVKKFVLHTNYPGHYNFNMYHRCEFEL" "TVQPD-KSEAHSLVESGGGVAVTAYSKWEVVSRAL-RVCERPVVLNRASSTNTTNPFGSTFCYGYQDIIFEVMSNNYIAS" "ITLY", str(hsp.hit.seq)) self.assertEqual("GMPLAQAVAILQKHCRIIKNVQVLYSEQSPLSHDLILNLTQDGIKLMFDAFNQRLKVIEVCDLTKVKLKYCGVHFNSQAI" "APTIEQIDQSFGATHPGVYNSAEQLFHLNFRGLSFSFQLDSWTEAPKYEPNFAHGLASLQIPHGA--TVKRMYIYSGNSL" "Q---------DTKA-PMMPLSCFLGNVYAESVDVLRDGTGPAGLRLRLLAAGCGPGLLADAKMRVFERSVYFGDSCQDVL" "SMLGSPHKVFYKSEDKMKIHSPSPHKQVPSKCNDYFFNYFTLGVDILFDANTHKVKKFVLHTNYPGHYNFNIYHRCEFKI" "PLAIKKENADG------QTETCTTYSKWDNIQELLGHPVEKPVVLHRSSSPNNTNPFGSTFCFGLQRMIFEVMQNNHIAS" "VTLY", str(hsp.query.seq)) # Check last hit hit = qresult[num_hits - 1] self.assertEqual("4IL7_A", hit.id) self.assertEqual("Putative uncharacterized protein; partial jelly roll fold, hypothetical; 1.4A " "{Sulfolobus turreted icosahedral virus}", hit.description) self.assertTrue(hit.is_included) self.assertEqual(6.8e+02, hit.evalue) self.assertEqual(22.72, hit.score) self.assertEqual(1, len(hit)) # Check we can get the original last HSP from the file. num_hsps = 34 self.assertEqual(num_hsps, len(qresult.hsps)) hsp = qresult.hsps[-1] self.assertTrue(hsp.is_included) self.assertEqual(num_hsps - 1, hsp.output_index) self.assertEqual(3.9e+02, hsp.evalue) self.assertEqual(22.84, hsp.score) self.assertEqual(21.56, hsp.prob) self.assertEqual(7, hsp.hit_start) self.assertEqual(96, hsp.hit_end) self.assertEqual(18, hsp.query_start) self.assertEqual(114, hsp.query_end) self.assertEqual("FTLGMPLAQAVAILQKHCRIIKNVQVLYSEQSPLSHDLILNLTQDGIKLMFDAFNQRLKVIEVCDLTKVKLKYCGVH-FN" "SQAIAPTIEQIDQSFGA", str(hsp.query.seq)) self.assertEqual("IQFGMDRTLVWQLAGADQSCSDQVERIICYNNPDH-------YGPQGHFFFNA-ADKLIHKRQMELFPAPKPTMRLATYN" "KTQTGMTEAQFWAAVPS", str(hsp.hit.seq)) if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) unittest.main(testRunner=runner)
[ "unittest.main", "Bio.SearchIO.parse", "os.path.join", "unittest.TextTestRunner" ]
[((492, 524), 'os.path.join', 'os.path.join', (['TEST_DIR', 'filename'], {}), '(TEST_DIR, filename)\n', (504, 524), False, 'import os\n'), ((21681, 21717), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (21704, 21717), False, 'import unittest\n'), ((21722, 21754), 'unittest.main', 'unittest.main', ([], {'testRunner': 'runner'}), '(testRunner=runner)\n', (21735, 21754), False, 'import unittest\n'), ((719, 739), 'Bio.SearchIO.parse', 'parse', (['txt_file', 'FMT'], {}), '(txt_file, FMT)\n', (724, 739), False, 'from Bio.SearchIO import parse\n'), ((4352, 4372), 'Bio.SearchIO.parse', 'parse', (['txt_file', 'FMT'], {}), '(txt_file, FMT)\n', (4357, 4372), False, 'from Bio.SearchIO import parse\n'), ((4615, 4635), 'Bio.SearchIO.parse', 'parse', (['txt_file', 'FMT'], {}), '(txt_file, FMT)\n', (4620, 4635), False, 'from Bio.SearchIO import parse\n'), ((4832, 4852), 'Bio.SearchIO.parse', 'parse', (['txt_file', 'FMT'], {}), '(txt_file, FMT)\n', (4837, 4852), False, 'from Bio.SearchIO import parse\n'), ((7394, 7414), 'Bio.SearchIO.parse', 'parse', (['txt_file', 'FMT'], {}), '(txt_file, FMT)\n', (7399, 7414), False, 'from Bio.SearchIO import parse\n'), ((10941, 10961), 'Bio.SearchIO.parse', 'parse', (['txt_file', 'FMT'], {}), '(txt_file, FMT)\n', (10946, 10961), False, 'from Bio.SearchIO import parse\n'), ((14542, 14562), 'Bio.SearchIO.parse', 'parse', (['txt_file', 'FMT'], {}), '(txt_file, FMT)\n', (14547, 14562), False, 'from Bio.SearchIO import parse\n'), ((17852, 17872), 'Bio.SearchIO.parse', 'parse', (['txt_file', 'FMT'], {}), '(txt_file, FMT)\n', (17857, 17872), False, 'from Bio.SearchIO import parse\n')]
import sys import os # check SBMolGen_PATH setting if os.getenv('SBMolGen_PATH') == None: print("THe SBMolGen_PATH has not defined, please set it before use it!") exit(0) else: SBMolGen_PATH=os.getenv('SBMolGen_PATH') sys.path.append(SBMolGen_PATH+'/utils') from subprocess import Popen, PIPE from math import * import random import random as pr import numpy as np from copy import deepcopy import itertools import time import math import argparse import subprocess from keras.preprocessing import sequence from rdkit import Chem from rdkit.Chem import Draw from rdkit.Chem import Descriptors from load_model import loaded_model from make_smile import zinc_data_with_bracket_original, zinc_processed_with_bracket from add_node_type_zinc import chem_kn_simulation, make_input_smile,predict_smile,check_node_type,node_to_add,expanded_node import yaml class chemical: def __init__(self): self.position=['&'] self.num_atom=8 #self.vl=['\n', '&', 'C', '(', 'c', '1', 'o', '=', 'O', 'N', 'F', '[C@@H]', #'n', '-', '#', 'S', 'Cl', '[O-]', '[C@H]', '[NH+]', '[C@]', 's', 'Br', '/', '[nH]', '[NH3+]', #'[NH2+]', '[C@@]', '[N+]', '[nH+]', '\\', '[S@]', '[N-]', '[n+]', '[S@@]', '[S-]', #'I', '[n-]', 'P', '[OH+]', '[NH-]', '[P@@H]', '[P@@]', '[PH2]', '[P@]', '[P+]', '[S+]', #'[o+]', '[CH2-]', '[CH-]', '[SH+]', '[O+]', '[s+]', '[PH+]', '[PH]', '[S@@+]'] self.vl = ['\n', '&', 'C', '1', 'N', '[C@@H]', '2', '[C@H]', '(', '=', 'O', ')', 'S', 'c', '[S@]', '[nH]', '[O-]', '[N+]', 'n', 'F', '#', '[C@]', '[C@@]', '[S@@]', 'P', '/', '\\', 'Cl', 's', 'Br', 'o', '[NH3+]', 'I', '[n+]', '[nH+]', '3', '[N-]', '[S-]', 'B', '4', '5', '[NH+]', '[Si]', '[P@]', '[NH2+]', '[P@@]', '[N@+]', '6', '[N@@+]', '[S@@+]', '7', '8', '[P@@H]', '[n-]', '[C-]', '[P+]', '[Cu]', '[Ni]', '[Zn]', '[Au-]', '[OH+]'] def Clone(self): st = chemical() st.position= self.position[:] return st def SelectPosition(self,m): self.position.append(m) def Getatom(self): return [i for i in range(self.num_atom)] class Node: def __init__(self, position = None, parent = None, state = None): self.position = position self.parentNode = parent self.childNodes = [] self.child=None self.wins = 0 self.visits = 0 self.nonvisited_atom=state.Getatom() self.type_node=[] self.depth=0 def Selectnode(self): #s = sorted(self.childNodes, key = lambda c: c.wins/c.visits + 0.8*sqrt(2*log(self.visits)/c.visits))[-1] #s=random.choice(self.childNodes) ucb=[] print('UCB:') for i in range(len(self.childNodes)): ucb_tmp = self.childNodes[i].wins/self.childNodes[i].visits+ c_val*sqrt(2*log(self.visits)/self.childNodes[i].\ visits) ucb.append(ucb_tmp) print(self.childNodes[i].position, ucb_tmp,) m = np.amax(ucb) indices = np.nonzero(ucb == m)[0] ind=pr.choice(indices) s=self.childNodes[ind] print('\n', 'index', ind, self.position, m,) return s def Addnode(self, m, s): n = Node(position = m, parent = self, state = s) self.childNodes.append(n) def simulation(self,state): predicted_smile=predict_smile(model,state) input_smile=make_input_smile(predicted_smile) logp,valid_smile,all_smile=logp_calculation(input_smile) return logp,valid_smile,all_smile def Update(self, result): self.visits += 1 self.wins += result def MCTS(root, verbose = False): """initialization of the chemical trees and grammar trees""" #run_time=time.time()+3600*48 start_time = time.time() run_time = time.time() + 3600*hours # 3600*24 rootnode = Node(state = root) state = root.Clone() """----------------------------------------------------------------------""" """global variables used for save valid compounds and simulated compounds""" valid_compound=[] all_simulated_compound=[] desired_compound=[] max_logp=[] desired_activity=[] depth=[] min_score=1000 score_distribution=[] min_score_distribution=[] generated_dict = {} #dictionary of generated compounds dict_id = 1 ## this id used for save best docking pose. """----------------------------------------------------------------------""" out_f = open(output_dir, 'a') while time.time()<=run_time: node = rootnode # important ! this node is different with state / node is the tree node state = root.Clone() # but this state is the state of the initialization . too important !!! """selection step""" node_pool=[] while node.childNodes!=[]: node = node.Selectnode() state.SelectPosition(node.position) print("state position:,",state.position) if len(state.position)>= 70: re= -1.0 while node != None: node.Update(re) node = node.parentNode continue if node.position == '\n': re = -1.0 while node != None: node.Update(re) node = node.parentNode continue """------------------------------------------------------------------""" """expansion step""" expanded=expanded_node(model,state.position,val,loop_num_nodeExpansion) new_compound = [] nodeadded = [] for n in range(simulation_num): nodeadded_tmp = node_to_add(expanded, val) all_posible=chem_kn_simulation(model,state.position,val,nodeadded_tmp) generate_smile=predict_smile(all_posible,val) new_compound_tmp = make_input_smile(generate_smile) nodeadded.extend(nodeadded_tmp) new_compound.extend(new_compound_tmp) print('nodeadded', nodeadded) print('new compound', new_compound) print('generated_dict', generated_dict) print('dict_id', dict_id) for comp in new_compound: print('lastcomp', comp[-1], ' ... ',comp[-1] == '\n') node_index,rdock_score,valid_smile,generated_dict = check_node_type(new_compound, score_type, generated_dict, sa_threshold = sa_threshold, rule = rule5, radical = radical_check, docking_num = docking_num, target_dir = target_dir, hashimoto_filter = hashimoto_filter, dict_id = dict_id, trial = trial) valid_compound.extend(valid_smile) score_distribution.extend(rdock_score) print('node', node_index, 'rdock_score', rdock_score, 'valid', valid_smile) #out_f = open(output_dir, 'a') #out_f.write(str(valid_smile) + ', '+ str(rdock_score)+', '+str(min_score)+', '+str(len(state.position))) out_f.write(str(valid_smile) + ', '+ str(rdock_score)+', '+str(min_score)+', '+str(len(state.position))+', '+str(time.time()-start_time)) out_f.write('\n') out_f.flush() #out_f.close() dict_id += 1 if len(node_index)==0: re=-1.0 while node != None: node.Update(re) node = node.parentNode else: re_list = [] #atom_list = [nodeadded[m] for m in node_index] atom_checked = [] for i in range(len(node_index)): m=node_index[i] atom = nodeadded[m] if atom not in atom_checked: node.Addnode(atom, state) node_pool.append(node.childNodes[len(atom_checked)]) depth.append(len(state.position)) atom_checked.append(atom) else: node_pool.append(node.childNodes[atom_checked.index(atom)]) #node.Addnode(nodeadded[m],state) #node.Addnode(nodeadded[m],state) #print valid_smile[i], 'node m', m, 'nodeadded[m]', nodeadded[m], 'node.childNodes[i]', node.childNodes[i] for child in node.childNodes: print(child.position) print('\n') #node_pool.append(node.childNodes[i]) #depth.append(len(state.position)) score_index = 0 if score_type == 'SCORE' else 1 print("current minmum score",min_score) if rdock_score[i][score_index]<=min_score: min_score_distribution.append(rdock_score[i][score_index]) min_score=rdock_score[i][score_index] else: min_score_distribution.append(min_score) """simulation""" if atom == '\n': re = -1 else: #re=(- (rdock_score[i][score_index] + 20)*0.1)/(1+abs(rdock_score[i][score_index] + 20)*0.1) re=(- (rdock_score[i][score_index] - base_rdock_score)*0.1)/(1+abs(rdock_score[i][score_index] -base_rdock_score)*0.1) #### pj16 reward fuction: #base_rdock_score = -20 #reward = (np.tanh(0.1*(abs(rdock_score[max_index])+base_rdock_score)) + 1)/2 re_list.append(re) print('atom', atom, 're_list', re_list) #re=(- (rdock_score[i]/100))/(1+abs(rdock_score[i]/100)) """backpropation step""" for i in range(len(node_pool)): node=node_pool[i] while node != None: node.Update(re_list[i]) node = node.parentNode for child in node_pool: print(child.position, child.wins, child.visits) out_f.close() """check if found the desired compound""" #print "all valid compounds:",valid_compound #print "all active compounds:",desired_compound print("rdock_score",score_distribution) print("num valid_compound:",len(valid_compound)) print("valid compounds",valid_compound) print("depth",depth) print("min_score",min_score_distribution) return valid_compound def UCTchemical(): one_search_start_time=time.time() time_out=one_search_start_time+60*10 state = chemical() best = MCTS(root = state,verbose = False) return best if __name__ == "__main__": # set parameter argvs = sys.argv """read yaml file for configuration""" f = open(str(argvs[1]), "r+") conf = yaml.load(f, Loader=yaml.SafeLoader) f.close() trial = conf.get('trial', 1) c_val = conf.get('c_val', 1.0) loop_num_nodeExpansion = conf.get('loop_num_nodeExpansion', 1000) target = conf.get('target', 'CDK2') target_dir = conf.get('target_path', './') hours = conf.get('hours', 1) score_type = conf.get('score_type', 'SCORE.INTER') #<SCORE> or <SCORE.INTER> docking_num = conf.get('docking_num', 10) sa_threshold = conf.get('sa_threshold', 3.5) #if SA > sa_threshold, score = 0. Default sa_threshold = 10 #RO5: if a compound does not satisfy rule of 5, score = 0. rule5 = conf.get('rule5', 1) #0:none, 1: rule of 5, 2: rule of 3 radical_check = conf.get('radical_check', True) simulation_num = conf.get('simulation_num', 3) hashimoto_filter = conf.get('hashimoto_filter', True) # or False, use/not use hashimoto filter base_rdock_score = conf.get('base_rdock_score', -20) model_name = conf.get('model_name', 'model') print('========== display configuration ==========') print('trial num is: ', trial) print('c_val: ', c_val) print('loop_num_nodeExpansion: ', loop_num_nodeExpansion) print('target: ', target) print('target_dir: ',target_dir) print('max run time: ',hours) print('score_type: ', score_type) print('docking_num: ',docking_num) print('sa_threshold: ',sa_threshold) print('model_name: ', model_name) print('base_rdock_score: ', base_rdock_score) print('simulation_num: ',simulation_num) print('hashimoto_filter: ', hashimoto_filter) """----------------------------------------------------------------------""" output_dir = 'result_'+target+'_C'+str(c_val)+'_trial'+str(trial)+'.txt' smile_old=zinc_data_with_bracket_original(SBMolGen_PATH + '/data/250k_rndm_zinc_drugs_clean.smi') val,smile=zinc_processed_with_bracket(smile_old) print('val is ', val) out_f = open(output_dir, 'w') out_f.write('#valid_smile, rdock_score, min_score, depth, used_time') out_f.write('\n') out_f.close() model=loaded_model(SBMolGen_PATH + '/RNN-model/'+ model_name) #WM300 not tested valid_compound=UCTchemical()
[ "add_node_type_zinc.node_to_add", "random.choice", "numpy.amax", "add_node_type_zinc.check_node_type", "os.getenv", "load_model.loaded_model", "add_node_type_zinc.chem_kn_simulation", "add_node_type_zinc.predict_smile", "yaml.load", "make_smile.zinc_data_with_bracket_original", "add_node_type_zi...
[((54, 80), 'os.getenv', 'os.getenv', (['"""SBMolGen_PATH"""'], {}), "('SBMolGen_PATH')\n", (63, 80), False, 'import os\n'), ((203, 229), 'os.getenv', 'os.getenv', (['"""SBMolGen_PATH"""'], {}), "('SBMolGen_PATH')\n", (212, 229), False, 'import os\n'), ((234, 275), 'sys.path.append', 'sys.path.append', (["(SBMolGen_PATH + '/utils')"], {}), "(SBMolGen_PATH + '/utils')\n", (249, 275), False, 'import sys\n'), ((3752, 3763), 'time.time', 'time.time', ([], {}), '()\n', (3761, 3763), False, 'import time\n'), ((10343, 10354), 'time.time', 'time.time', ([], {}), '()\n', (10352, 10354), False, 'import time\n'), ((10641, 10677), 'yaml.load', 'yaml.load', (['f'], {'Loader': 'yaml.SafeLoader'}), '(f, Loader=yaml.SafeLoader)\n', (10650, 10677), False, 'import yaml\n'), ((12390, 12481), 'make_smile.zinc_data_with_bracket_original', 'zinc_data_with_bracket_original', (["(SBMolGen_PATH + '/data/250k_rndm_zinc_drugs_clean.smi')"], {}), "(SBMolGen_PATH +\n '/data/250k_rndm_zinc_drugs_clean.smi')\n", (12421, 12481), False, 'from make_smile import zinc_data_with_bracket_original, zinc_processed_with_bracket\n'), ((12492, 12530), 'make_smile.zinc_processed_with_bracket', 'zinc_processed_with_bracket', (['smile_old'], {}), '(smile_old)\n', (12519, 12530), False, 'from make_smile import zinc_data_with_bracket_original, zinc_processed_with_bracket\n'), ((12717, 12773), 'load_model.loaded_model', 'loaded_model', (["(SBMolGen_PATH + '/RNN-model/' + model_name)"], {}), "(SBMolGen_PATH + '/RNN-model/' + model_name)\n", (12729, 12773), False, 'from load_model import loaded_model\n'), ((2959, 2971), 'numpy.amax', 'np.amax', (['ucb'], {}), '(ucb)\n', (2966, 2971), True, 'import numpy as np\n'), ((3026, 3044), 'random.choice', 'pr.choice', (['indices'], {}), '(indices)\n', (3035, 3044), True, 'import random as pr\n'), ((3326, 3353), 'add_node_type_zinc.predict_smile', 'predict_smile', (['model', 'state'], {}), '(model, state)\n', (3339, 3353), False, 'from add_node_type_zinc import chem_kn_simulation, make_input_smile, predict_smile, check_node_type, node_to_add, expanded_node\n'), ((3373, 3406), 'add_node_type_zinc.make_input_smile', 'make_input_smile', (['predicted_smile'], {}), '(predicted_smile)\n', (3389, 3406), False, 'from add_node_type_zinc import chem_kn_simulation, make_input_smile, predict_smile, check_node_type, node_to_add, expanded_node\n'), ((3779, 3790), 'time.time', 'time.time', ([], {}), '()\n', (3788, 3790), False, 'import time\n'), ((4492, 4503), 'time.time', 'time.time', ([], {}), '()\n', (4501, 4503), False, 'import time\n'), ((5437, 5502), 'add_node_type_zinc.expanded_node', 'expanded_node', (['model', 'state.position', 'val', 'loop_num_nodeExpansion'], {}), '(model, state.position, val, loop_num_nodeExpansion)\n', (5450, 5502), False, 'from add_node_type_zinc import chem_kn_simulation, make_input_smile, predict_smile, check_node_type, node_to_add, expanded_node\n'), ((6277, 6523), 'add_node_type_zinc.check_node_type', 'check_node_type', (['new_compound', 'score_type', 'generated_dict'], {'sa_threshold': 'sa_threshold', 'rule': 'rule5', 'radical': 'radical_check', 'docking_num': 'docking_num', 'target_dir': 'target_dir', 'hashimoto_filter': 'hashimoto_filter', 'dict_id': 'dict_id', 'trial': 'trial'}), '(new_compound, score_type, generated_dict, sa_threshold=\n sa_threshold, rule=rule5, radical=radical_check, docking_num=\n docking_num, target_dir=target_dir, hashimoto_filter=hashimoto_filter,\n dict_id=dict_id, trial=trial)\n', (6292, 6523), False, 'from add_node_type_zinc import chem_kn_simulation, make_input_smile, predict_smile, check_node_type, node_to_add, expanded_node\n'), ((2990, 3010), 'numpy.nonzero', 'np.nonzero', (['(ucb == m)'], {}), '(ucb == m)\n', (3000, 3010), True, 'import numpy as np\n'), ((5626, 5652), 'add_node_type_zinc.node_to_add', 'node_to_add', (['expanded', 'val'], {}), '(expanded, val)\n', (5637, 5652), False, 'from add_node_type_zinc import chem_kn_simulation, make_input_smile, predict_smile, check_node_type, node_to_add, expanded_node\n'), ((5677, 5738), 'add_node_type_zinc.chem_kn_simulation', 'chem_kn_simulation', (['model', 'state.position', 'val', 'nodeadded_tmp'], {}), '(model, state.position, val, nodeadded_tmp)\n', (5695, 5738), False, 'from add_node_type_zinc import chem_kn_simulation, make_input_smile, predict_smile, check_node_type, node_to_add, expanded_node\n'), ((5763, 5794), 'add_node_type_zinc.predict_smile', 'predict_smile', (['all_posible', 'val'], {}), '(all_posible, val)\n', (5776, 5794), False, 'from add_node_type_zinc import chem_kn_simulation, make_input_smile, predict_smile, check_node_type, node_to_add, expanded_node\n'), ((5825, 5857), 'add_node_type_zinc.make_input_smile', 'make_input_smile', (['generate_smile'], {}), '(generate_smile)\n', (5841, 5857), False, 'from add_node_type_zinc import chem_kn_simulation, make_input_smile, predict_smile, check_node_type, node_to_add, expanded_node\n'), ((6983, 6994), 'time.time', 'time.time', ([], {}), '()\n', (6992, 6994), False, 'import time\n')]
from argparse import ArgumentParser import pytorch_lightning as pl import torch from torch.nn import functional as F from pl_bolts.models.gans.basic.components import Discriminator, Generator class GAN(pl.LightningModule): """ Vanilla GAN implementation. Example:: from pl_bolts.models.gan import GAN m = GAN() Trainer(gpus=2).fit(m) Example CLI:: # mnist python basic_gan_module.py --gpus 1 # imagenet python basic_gan_module.py --gpus 1 --dataset 'imagenet2012' --data_dir /path/to/imagenet/folder/ --meta_dir ~/path/to/meta/bin/folder --batch_size 256 --learning_rate 0.0001 """ def __init__( self, input_channels: int, input_height: int, input_width: int, latent_dim: int = 32, learning_rate: float = 0.0002, **kwargs ): """ Args: input_channels: number of channels of an image input_height: image height input_width: image width latent_dim: emb dim for encoder learning_rate: the learning rate """ super().__init__() # makes self.hparams under the hood and saves to ckpt self.save_hyperparameters() self.img_dim = (input_channels, input_height, input_width) # networks self.generator = self.init_generator(self.img_dim) self.discriminator = self.init_discriminator(self.img_dim) def init_generator(self, img_dim): generator = Generator(latent_dim=self.hparams.latent_dim, img_shape=img_dim) return generator def init_discriminator(self, img_dim): discriminator = Discriminator(img_shape=img_dim) return discriminator def forward(self, z): """ Generates an image given input noise z Example:: z = torch.rand(batch_size, latent_dim) gan = GAN.load_from_checkpoint(PATH) img = gan(z) """ return self.generator(z) def generator_loss(self, x): # sample noise z = torch.randn(x.shape[0], self.hparams.latent_dim, device=self.device) y = torch.ones(x.size(0), 1, device=self.device) # generate images generated_imgs = self(z) D_output = self.discriminator(generated_imgs) # ground truth result (ie: all real) g_loss = F.binary_cross_entropy(D_output, y) return g_loss def discriminator_loss(self, x): # train discriminator on real b = x.size(0) x_real = x.view(b, -1) y_real = torch.ones(b, 1, device=self.device) # calculate real score D_output = self.discriminator(x_real) D_real_loss = F.binary_cross_entropy(D_output, y_real) # train discriminator on fake z = torch.randn(b, self.hparams.latent_dim, device=self.device) x_fake = self(z) y_fake = torch.zeros(b, 1, device=self.device) # calculate fake score D_output = self.discriminator(x_fake) D_fake_loss = F.binary_cross_entropy(D_output, y_fake) # gradient backprop & optimize ONLY D's parameters D_loss = D_real_loss + D_fake_loss return D_loss def training_step(self, batch, batch_idx, optimizer_idx): x, _ = batch # train generator result = None if optimizer_idx == 0: result = self.generator_step(x) # train discriminator if optimizer_idx == 1: result = self.discriminator_step(x) return result def generator_step(self, x): g_loss = self.generator_loss(x) # log to prog bar on each step AND for the full epoch # use the generator loss for checkpointing self.log('g_loss', g_loss, on_epoch=True, prog_bar=True) return g_loss def discriminator_step(self, x): # Measure discriminator's ability to classify real from generated samples d_loss = self.discriminator_loss(x) # log to prog bar on each step AND for the full epoch self.log('d_loss', d_loss, on_epoch=True, prog_bar=True) return d_loss def configure_optimizers(self): lr = self.hparams.learning_rate opt_g = torch.optim.Adam(self.generator.parameters(), lr=lr) opt_d = torch.optim.Adam(self.discriminator.parameters(), lr=lr) return [opt_g, opt_d], [] @staticmethod def add_model_specific_args(parent_parser): parser = ArgumentParser(parents=[parent_parser], add_help=False) parser.add_argument('--learning_rate', type=float, default=0.0002, help="adam: learning rate") parser.add_argument( '--adam_b1', type=float, default=0.5, help="adam: decay of first order momentum of gradient" ) parser.add_argument( '--adam_b2', type=float, default=0.999, help="adam: decay of first order momentum of gradient" ) parser.add_argument('--latent_dim', type=int, default=100, help="generator embedding dim") return parser def cli_main(args=None): from pl_bolts.callbacks import LatentDimInterpolator, TensorboardGenerativeModelImageSampler from pl_bolts.datamodules import CIFAR10DataModule, ImagenetDataModule, MNISTDataModule, STL10DataModule pl.seed_everything(1234) parser = ArgumentParser() parser.add_argument("--dataset", default="mnist", type=str, help="mnist, cifar10, stl10, imagenet") script_args, _ = parser.parse_known_args(args) if script_args.dataset == "mnist": dm_cls = MNISTDataModule elif script_args.dataset == "cifar10": dm_cls = CIFAR10DataModule elif script_args.dataset == "stl10": dm_cls = STL10DataModule elif script_args.dataset == "imagenet": dm_cls = ImagenetDataModule parser = dm_cls.add_argparse_args(parser) parser = pl.Trainer.add_argparse_args(parser) parser = GAN.add_model_specific_args(parser) args = parser.parse_args(args) dm = dm_cls.from_argparse_args(args) model = GAN(*dm.size(), **vars(args)) callbacks = [TensorboardGenerativeModelImageSampler(), LatentDimInterpolator(interpolate_epoch_interval=5)] trainer = pl.Trainer.from_argparse_args(args, callbacks=callbacks, progress_bar_refresh_rate=20) trainer.fit(model, dm) return dm, model, trainer if __name__ == '__main__': dm, model, trainer = cli_main()
[ "pytorch_lightning.Trainer.add_argparse_args", "argparse.ArgumentParser", "pl_bolts.callbacks.TensorboardGenerativeModelImageSampler", "pytorch_lightning.seed_everything", "torch.nn.functional.binary_cross_entropy", "torch.zeros", "pl_bolts.models.gans.basic.components.Discriminator", "pl_bolts.models...
[((5341, 5365), 'pytorch_lightning.seed_everything', 'pl.seed_everything', (['(1234)'], {}), '(1234)\n', (5359, 5365), True, 'import pytorch_lightning as pl\n'), ((5380, 5396), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (5394, 5396), False, 'from argparse import ArgumentParser\n'), ((5917, 5953), 'pytorch_lightning.Trainer.add_argparse_args', 'pl.Trainer.add_argparse_args', (['parser'], {}), '(parser)\n', (5945, 5953), True, 'import pytorch_lightning as pl\n'), ((6248, 6338), 'pytorch_lightning.Trainer.from_argparse_args', 'pl.Trainer.from_argparse_args', (['args'], {'callbacks': 'callbacks', 'progress_bar_refresh_rate': '(20)'}), '(args, callbacks=callbacks,\n progress_bar_refresh_rate=20)\n', (6277, 6338), True, 'import pytorch_lightning as pl\n'), ((1555, 1619), 'pl_bolts.models.gans.basic.components.Generator', 'Generator', ([], {'latent_dim': 'self.hparams.latent_dim', 'img_shape': 'img_dim'}), '(latent_dim=self.hparams.latent_dim, img_shape=img_dim)\n', (1564, 1619), False, 'from pl_bolts.models.gans.basic.components import Discriminator, Generator\n'), ((1713, 1745), 'pl_bolts.models.gans.basic.components.Discriminator', 'Discriminator', ([], {'img_shape': 'img_dim'}), '(img_shape=img_dim)\n', (1726, 1745), False, 'from pl_bolts.models.gans.basic.components import Discriminator, Generator\n'), ((2120, 2188), 'torch.randn', 'torch.randn', (['x.shape[0]', 'self.hparams.latent_dim'], {'device': 'self.device'}), '(x.shape[0], self.hparams.latent_dim, device=self.device)\n', (2131, 2188), False, 'import torch\n'), ((2424, 2459), 'torch.nn.functional.binary_cross_entropy', 'F.binary_cross_entropy', (['D_output', 'y'], {}), '(D_output, y)\n', (2446, 2459), True, 'from torch.nn import functional as F\n'), ((2629, 2665), 'torch.ones', 'torch.ones', (['b', '(1)'], {'device': 'self.device'}), '(b, 1, device=self.device)\n', (2639, 2665), False, 'import torch\n'), ((2766, 2806), 'torch.nn.functional.binary_cross_entropy', 'F.binary_cross_entropy', (['D_output', 'y_real'], {}), '(D_output, y_real)\n', (2788, 2806), True, 'from torch.nn import functional as F\n'), ((2858, 2917), 'torch.randn', 'torch.randn', (['b', 'self.hparams.latent_dim'], {'device': 'self.device'}), '(b, self.hparams.latent_dim, device=self.device)\n', (2869, 2917), False, 'import torch\n'), ((2960, 2997), 'torch.zeros', 'torch.zeros', (['b', '(1)'], {'device': 'self.device'}), '(b, 1, device=self.device)\n', (2971, 2997), False, 'import torch\n'), ((3098, 3138), 'torch.nn.functional.binary_cross_entropy', 'F.binary_cross_entropy', (['D_output', 'y_fake'], {}), '(D_output, y_fake)\n', (3120, 3138), True, 'from torch.nn import functional as F\n'), ((4533, 4588), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'parents': '[parent_parser]', 'add_help': '(False)'}), '(parents=[parent_parser], add_help=False)\n', (4547, 4588), False, 'from argparse import ArgumentParser\n'), ((6139, 6179), 'pl_bolts.callbacks.TensorboardGenerativeModelImageSampler', 'TensorboardGenerativeModelImageSampler', ([], {}), '()\n', (6177, 6179), False, 'from pl_bolts.callbacks import LatentDimInterpolator, TensorboardGenerativeModelImageSampler\n'), ((6181, 6232), 'pl_bolts.callbacks.LatentDimInterpolator', 'LatentDimInterpolator', ([], {'interpolate_epoch_interval': '(5)'}), '(interpolate_epoch_interval=5)\n', (6202, 6232), False, 'from pl_bolts.callbacks import LatentDimInterpolator, TensorboardGenerativeModelImageSampler\n')]
from django.db import models import uuid class Alvo(models.Model): identificador = models.UUIDField(verbose_name='UUID', default=uuid.uuid4, unique=True, primary_key=True) nome = models.CharField(max_length=30, verbose_name='Nome do Alvo') latitude = models.DecimalField(max_digits=10, decimal_places=6, verbose_name='Latitude', help_text='exemplo: 12.222200') longitude = models.DecimalField(max_digits=10, decimal_places=6, verbose_name='Longitude', help_text='exemplo: -12.222200') data_expiracao = models.DateField(null=True, verbose_name='Data da Expiracao', help_text='formato: YYYY-MM-DD') def __str__(self): return self.nome
[ "django.db.models.DecimalField", "django.db.models.DateField", "django.db.models.UUIDField", "django.db.models.CharField" ]
[((90, 182), 'django.db.models.UUIDField', 'models.UUIDField', ([], {'verbose_name': '"""UUID"""', 'default': 'uuid.uuid4', 'unique': '(True)', 'primary_key': '(True)'}), "(verbose_name='UUID', default=uuid.uuid4, unique=True,\n primary_key=True)\n", (106, 182), False, 'from django.db import models\n'), ((190, 250), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'verbose_name': '"""Nome do Alvo"""'}), "(max_length=30, verbose_name='Nome do Alvo')\n", (206, 250), False, 'from django.db import models\n'), ((266, 380), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(6)', 'verbose_name': '"""Latitude"""', 'help_text': '"""exemplo: 12.222200"""'}), "(max_digits=10, decimal_places=6, verbose_name=\n 'Latitude', help_text='exemplo: 12.222200')\n", (285, 380), False, 'from django.db import models\n'), ((392, 508), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(6)', 'verbose_name': '"""Longitude"""', 'help_text': '"""exemplo: -12.222200"""'}), "(max_digits=10, decimal_places=6, verbose_name=\n 'Longitude', help_text='exemplo: -12.222200')\n", (411, 508), False, 'from django.db import models\n'), ((525, 624), 'django.db.models.DateField', 'models.DateField', ([], {'null': '(True)', 'verbose_name': '"""Data da Expiracao"""', 'help_text': '"""formato: YYYY-MM-DD"""'}), "(null=True, verbose_name='Data da Expiracao', help_text=\n 'formato: YYYY-MM-DD')\n", (541, 624), False, 'from django.db import models\n')]
import sys import numpy as np from matplotlib import pyplot from matplotlib.animation import FuncAnimation import matplotlib as mpl sys.path.append('..') from submission import SubmissionBase def displayData(X, example_width=None, figsize=(10, 10)): """ Displays 2D data in a nice grid. Parameters ---------- X : array_like The input data of size (m x n) where m is the number of examples and n is the number of features. example_width : int, optional THe width of each 2-D image in pixels. If not provided, the image is assumed to be square, and the width is the floor of the square root of total number of pixels. figsize : tuple, optional A 2-element tuple indicating the width and height of figure in inches. """ # Compute rows, cols if X.ndim == 2: m, n = X.shape elif X.ndim == 1: n = X.size m = 1 X = X[None] # Promote to a 2 dimensional array else: raise IndexError('Input X should be 1 or 2 dimensional.') example_width = example_width or int(np.round(np.sqrt(n))) example_height = int(n / example_width) # Compute number of items to display display_rows = int(np.floor(np.sqrt(m))) display_cols = int(np.ceil(m / display_rows)) fig, ax_array = pyplot.subplots(display_rows, display_cols, figsize=figsize) fig.subplots_adjust(wspace=0.025, hspace=0.025) ax_array = [ax_array] if m == 1 else ax_array.ravel() for i, ax in enumerate(ax_array): ax.imshow(X[i].reshape(example_height, example_width, order='F'), cmap='gray') ax.axis('off') def featureNormalize(X): """ Normalizes the features in X returns a normalized version of X where the mean value of each feature is 0 and the standard deviation is 1. This is often a good preprocessing step to do when working with learning algorithms. Parameters ---------- X : array_like An dataset which is a (m x n) matrix, where m is the number of examples, and n is the number of dimensions for each example. Returns ------- X_norm : array_like The normalized input dataset. mu : array_like A vector of size n corresponding to the mean for each dimension across all examples. sigma : array_like A vector of size n corresponding to the standard deviations for each dimension across all examples. """ mu = np.mean(X, axis=0) X_norm = X - mu sigma = np.std(X_norm, axis=0, ddof=1) X_norm /= sigma return X_norm, mu, sigma def plotProgresskMeans(i, X, centroid_history, idx_history): """ A helper function that displays the progress of k-Means as it is running. It is intended for use only with 2D data. It plots data points with colors assigned to each centroid. With the previous centroids, it also plots a line between the previous locations and current locations of the centroids. Parameters ---------- i : int Current iteration number of k-means. Used for matplotlib animation function. X : array_like The dataset, which is a matrix (m x n). Note since the plot only supports 2D data, n should be equal to 2. centroid_history : list A list of computed centroids for all iteration. idx_history : list A list of computed assigned indices for all iterations. """ K = centroid_history[0].shape[0] pyplot.gcf().clf() cmap = pyplot.cm.rainbow norm = mpl.colors.Normalize(vmin=0, vmax=2) for k in range(K): current = np.stack([c[k, :] for c in centroid_history[:i+1]], axis=0) pyplot.plot(current[:, 0], current[:, 1], '-Xk', mec='k', lw=2, ms=10, mfc=cmap(norm(k)), mew=2) pyplot.scatter(X[:, 0], X[:, 1], c=idx_history[i], cmap=cmap, marker='o', s=8**2, linewidths=1,) pyplot.grid(False) pyplot.title('Iteration number %d' % (i+1)) def runkMeans(X, centroids, findClosestCentroids, computeCentroids, max_iters=10, plot_progress=False): """ Runs the K-means algorithm. Parameters ---------- X : array_like The data set of size (m, n). Each row of X is a single example of n dimensions. The data set is a total of m examples. centroids : array_like Initial centroid location for each clusters. This is a matrix of size (K, n). K is the total number of clusters and n is the dimensions of each data point. findClosestCentroids : func A function (implemented by student) reference which computes the cluster assignment for each example. computeCentroids : func A function(implemented by student) reference which computes the centroid of each cluster. max_iters : int, optional Specifies the total number of interactions of K-Means to execute. plot_progress : bool, optional A flag that indicates if the function should also plot its progress as the learning happens. This is set to false by default. Returns ------- centroids : array_like A (K x n) matrix of the computed (updated) centroids. idx : array_like A vector of size (m,) for cluster assignment for each example in the dataset. Each entry in idx is within the range [0 ... K-1]. anim : FuncAnimation, optional A matplotlib animation object which can be used to embed a video within the jupyter notebook. This is only returned if `plot_progress` is `True`. """ K = centroids.shape[0] idx = None idx_history = [] centroid_history = [] for i in range(max_iters): idx = findClosestCentroids(X, centroids) if plot_progress: idx_history.append(idx) centroid_history.append(centroids) centroids = computeCentroids(X, idx, K) if plot_progress: fig = pyplot.figure() anim = FuncAnimation(fig, plotProgresskMeans, frames=max_iters, interval=500, repeat_delay=2, fargs=(X, centroid_history, idx_history)) return centroids, idx, anim return centroids, idx class Grader(SubmissionBase): # Random Test Cases X = np.sin(np.arange(1, 166)).reshape(15, 11, order='F') Z = np.cos(np.arange(1, 122)).reshape(11, 11, order='F') C = Z[:5, :] idx = np.arange(1, 16) % 3 def __init__(self): part_names = ['Find Closest Centroids (k-Means)', 'Compute Centroid Means (k-Means)', 'PCA', 'Project Data (PCA)', 'Recover Data (PCA)'] super().__init__('k-means-clustering-and-pca', part_names) def __iter__(self): for part_id in range(1, 6): try: func = self.functions[part_id] # Each part has different expected arguments/different function if part_id == 1: res = 1 + func(self.X, self.C) elif part_id == 2: res = func(self.X, self.idx, 3) elif part_id == 3: U, S = func(self.X) res = np.hstack([U.ravel('F'), np.diag(S).ravel('F')]).tolist() elif part_id == 4: res = func(self.X, self.Z, 5) elif part_id == 5: res = func(self.X[:, :5], self.Z, 5) else: raise KeyError yield part_id, res except KeyError: yield part_id, 0
[ "numpy.mean", "numpy.ceil", "matplotlib.pyplot.grid", "numpy.sqrt", "matplotlib.animation.FuncAnimation", "matplotlib.pyplot.gcf", "numpy.diag", "numpy.stack", "matplotlib.pyplot.figure", "matplotlib.colors.Normalize", "numpy.std", "matplotlib.pyplot.scatter", "matplotlib.pyplot.title", "s...
[((133, 154), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (148, 154), False, 'import sys\n'), ((1316, 1376), 'matplotlib.pyplot.subplots', 'pyplot.subplots', (['display_rows', 'display_cols'], {'figsize': 'figsize'}), '(display_rows, display_cols, figsize=figsize)\n', (1331, 1376), False, 'from matplotlib import pyplot\n'), ((2456, 2474), 'numpy.mean', 'np.mean', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (2463, 2474), True, 'import numpy as np\n'), ((2508, 2538), 'numpy.std', 'np.std', (['X_norm'], {'axis': '(0)', 'ddof': '(1)'}), '(X_norm, axis=0, ddof=1)\n', (2514, 2538), True, 'import numpy as np\n'), ((3524, 3560), 'matplotlib.colors.Normalize', 'mpl.colors.Normalize', ([], {'vmin': '(0)', 'vmax': '(2)'}), '(vmin=0, vmax=2)\n', (3544, 3560), True, 'import matplotlib as mpl\n'), ((4113, 4131), 'matplotlib.pyplot.grid', 'pyplot.grid', (['(False)'], {}), '(False)\n', (4124, 4131), False, 'from matplotlib import pyplot\n'), ((4136, 4181), 'matplotlib.pyplot.title', 'pyplot.title', (["('Iteration number %d' % (i + 1))"], {}), "('Iteration number %d' % (i + 1))\n", (4148, 4181), False, 'from matplotlib import pyplot\n'), ((1268, 1293), 'numpy.ceil', 'np.ceil', (['(m / display_rows)'], {}), '(m / display_rows)\n', (1275, 1293), True, 'import numpy as np\n'), ((3603, 3664), 'numpy.stack', 'np.stack', (['[c[k, :] for c in centroid_history[:i + 1]]'], {'axis': '(0)'}), '([c[k, :] for c in centroid_history[:i + 1]], axis=0)\n', (3611, 3664), True, 'import numpy as np\n'), ((3897, 3999), 'matplotlib.pyplot.scatter', 'pyplot.scatter', (['X[:, 0]', 'X[:, 1]'], {'c': 'idx_history[i]', 'cmap': 'cmap', 'marker': '"""o"""', 's': '(8 ** 2)', 'linewidths': '(1)'}), "(X[:, 0], X[:, 1], c=idx_history[i], cmap=cmap, marker='o', s\n =8 ** 2, linewidths=1)\n", (3911, 3999), False, 'from matplotlib import pyplot\n'), ((6138, 6153), 'matplotlib.pyplot.figure', 'pyplot.figure', ([], {}), '()\n', (6151, 6153), False, 'from matplotlib import pyplot\n'), ((6169, 6301), 'matplotlib.animation.FuncAnimation', 'FuncAnimation', (['fig', 'plotProgresskMeans'], {'frames': 'max_iters', 'interval': '(500)', 'repeat_delay': '(2)', 'fargs': '(X, centroid_history, idx_history)'}), '(fig, plotProgresskMeans, frames=max_iters, interval=500,\n repeat_delay=2, fargs=(X, centroid_history, idx_history))\n', (6182, 6301), False, 'from matplotlib.animation import FuncAnimation\n'), ((6682, 6698), 'numpy.arange', 'np.arange', (['(1)', '(16)'], {}), '(1, 16)\n', (6691, 6698), True, 'import numpy as np\n'), ((1232, 1242), 'numpy.sqrt', 'np.sqrt', (['m'], {}), '(m)\n', (1239, 1242), True, 'import numpy as np\n'), ((3465, 3477), 'matplotlib.pyplot.gcf', 'pyplot.gcf', ([], {}), '()\n', (3475, 3477), False, 'from matplotlib import pyplot\n'), ((1101, 1111), 'numpy.sqrt', 'np.sqrt', (['n'], {}), '(n)\n', (1108, 1111), True, 'import numpy as np\n'), ((6548, 6565), 'numpy.arange', 'np.arange', (['(1)', '(166)'], {}), '(1, 166)\n', (6557, 6565), True, 'import numpy as np\n'), ((6609, 6626), 'numpy.arange', 'np.arange', (['(1)', '(122)'], {}), '(1, 122)\n', (6618, 6626), True, 'import numpy as np\n'), ((7530, 7540), 'numpy.diag', 'np.diag', (['S'], {}), '(S)\n', (7537, 7540), True, 'import numpy as np\n')]
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pytest FIXTURES_DIR = os.path.join(os.path.dirname(__file__), 'fixture') _BACKENDS = '[{balancing_mode="CONNECTION", group="foo", failover=false}]' def test_defaults(plan_runner): "Test variable defaults." _, resources = plan_runner(FIXTURES_DIR, backends=_BACKENDS) assert len(resources) == 3 resources = dict((r['type'], r['values']) for r in resources) fwd_rule = resources['google_compute_forwarding_rule'] assert fwd_rule['load_balancing_scheme'] == 'INTERNAL' assert fwd_rule['all_ports'] assert fwd_rule['allow_global_access'] is None backend = resources['google_compute_region_backend_service'] assert len(backend['backend']) == 1 assert backend['backend'][0]['group'] == 'foo' health_check = resources['google_compute_health_check'] for k, v in health_check.items(): if k == 'http_health_check': assert len(v) == 1 assert v[0]['port_specification'] == 'USE_SERVING_PORT' elif k.endswith('_health_check'): assert len(v) == 0 def test_forwarding_rule(plan_runner): "Test forwarding rule variables." _, resources = plan_runner( FIXTURES_DIR, backends=_BACKENDS, global_access='true', ports="[80]") assert len(resources) == 3 values = [r['values'] for r in resources if r['type'] == 'google_compute_forwarding_rule'][0] assert not values['all_ports'] assert values['ports'] == ['80'] assert values['allow_global_access']
[ "os.path.dirname" ]
[((631, 656), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (646, 656), False, 'import os\n')]
# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import mindspore as ms import mindspore.nn as nn from mindspore import Tensor from mindspore import context from mindspore.common.api import _executor from mindspore.ops import composite as C from mindspore.ops import operations as P from mindspore.ops.operations.comm_ops import _VirtualDataset context.set_context(mode=context.GRAPH_MODE) class NetWithLoss(nn.Cell): def __init__(self, network, strategy3, strategy4, axis): super(NetWithLoss, self).__init__() self.virtual_dataset = _VirtualDataset() self.one_hot = P.OneHot(axis=axis).set_strategy(strategy3) self.on_value = Tensor(2.0, ms.float32) self.off_value = Tensor(1.0, ms.float32) self.loss = P.SoftmaxCrossEntropyWithLogits().set_strategy(strategy4) self.network = network def construct(self, x, y, b): b_virtual = self.virtual_dataset(b) predict = self.network(x, y) label = self.one_hot(b_virtual, 64, self.on_value, self.off_value) return self.loss(predict, label)[0] class GradWrap(nn.Cell): def __init__(self, network): super(GradWrap, self).__init__() self.network = network def construct(self, x, y, b): return C.grad_all(self.network)(x, y, b) class Net(nn.Cell): def __init__(self, strategy1, strategy2): super().__init__() self.matmul = P.MatMul().set_strategy(strategy1) self.gelu = P.Gelu().set_strategy(strategy2) def construct(self, x, y): out = self.matmul(x, y) out = self.gelu(out) return out def compile_graph(strategy1, strategy2, strategy3, strategy4, auto=False, onthot_axis=-1): net = GradWrap(NetWithLoss(Net(strategy1, strategy2), strategy3, strategy4, axis=onthot_axis)) net.set_auto_parallel() if auto: context.set_auto_parallel_context(parallel_mode="auto_parallel") else: context.set_auto_parallel_context(parallel_mode="semi_auto_parallel") x = Tensor(np.ones([64, 32]), dtype=ms.float32) y = Tensor(np.ones([32, 64]), dtype=ms.float32) b = Tensor(np.ones([64]), dtype=ms.int32) _executor.compile(net, x, y, b) def test_onehot_model_parallel(): context.set_auto_parallel_context(device_num=16, global_rank=0) strategy1 = ((2, 4), (4, 2)) strategy2 = ((2, 8),) strategy3 = ((1, 16), (), ()) strategy4 = ((16, 1), (16, 1)) compile_graph(strategy1, strategy2, strategy3, strategy4) def test_onehot_batch_parallel(): context.set_auto_parallel_context(device_num=16, global_rank=0) strategy1 = ((2, 4), (4, 2)) strategy2 = ((2, 8),) strategy3 = ((16, 1), (), ()) strategy4 = ((16, 1), (16, 1)) compile_graph(strategy1, strategy2, strategy3, strategy4) def test_onehot_batch_parallel_invalid_strategy(): context.set_auto_parallel_context(device_num=16, global_rank=0) strategy1 = ((2, 4), (4, 2)) strategy2 = ((2, 8),) strategy3 = ((16,), (), ()) strategy4 = ((16, 1), (16, 1)) try: compile_graph(strategy1, strategy2, strategy3, strategy4) except: pass def test_onehot_repeated_calculation(): context.set_auto_parallel_context(device_num=16, global_rank=0) strategy1 = ((2, 4), (4, 2)) strategy2 = ((2, 8),) strategy3 = ((4, 1), (), ()) strategy4 = ((16, 1), (16, 1)) compile_graph(strategy1, strategy2, strategy3, strategy4) def test_onehot_auto(): context.set_auto_parallel_context(device_num=16, global_rank=0) strategy1 = None strategy2 = None strategy3 = None strategy4 = None compile_graph(strategy1, strategy2, strategy3, strategy4, auto=True) def test_onehot_batch_parallel_axis0(): context.set_auto_parallel_context(device_num=16, global_rank=0) strategy1 = ((2, 4), (4, 2)) strategy2 = ((2, 8),) strategy3 = ((16, 1), (), ()) strategy4 = ((16, 1), (16, 1)) compile_graph(strategy1, strategy2, strategy3, strategy4, onthot_axis=0) # auto parallel for onehot axis equal to 0 has not been supported yet def test_onehot_batch_parallel_invalid_strategy_axis0(): context.set_auto_parallel_context(device_num=16, global_rank=0) strategy1 = ((2, 4), (4, 2)) strategy2 = ((2, 8),) strategy3 = None strategy4 = ((16, 1), (16, 1)) try: compile_graph(strategy1, strategy2, strategy3, strategy4, onthot_axis=0) except: pass def test_onehot_repeated_calculation_axis0(): context.set_auto_parallel_context(device_num=16, global_rank=0) strategy1 = ((2, 4), (4, 2)) strategy2 = ((2, 8),) strategy3 = ((4, 1), (), ()) strategy4 = ((16, 1), (16, 1)) compile_graph(strategy1, strategy2, strategy3, strategy4, onthot_axis=0) def test_onehot_auto_axis0(): context.set_auto_parallel_context(device_num=16, global_rank=14) strategy1 = None strategy2 = None strategy3 = None strategy4 = None compile_graph(strategy1, strategy2, strategy3, strategy4, auto=True, onthot_axis=0)
[ "mindspore.ops.operations.SoftmaxCrossEntropyWithLogits", "numpy.ones", "mindspore.ops.operations.MatMul", "mindspore.context.set_context", "mindspore.ops.operations.comm_ops._VirtualDataset", "mindspore.ops.composite.grad_all", "mindspore.ops.operations.Gelu", "mindspore.common.api._executor.compile"...
[((906, 950), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.GRAPH_MODE'}), '(mode=context.GRAPH_MODE)\n', (925, 950), False, 'from mindspore import context\n'), ((2725, 2756), 'mindspore.common.api._executor.compile', '_executor.compile', (['net', 'x', 'y', 'b'], {}), '(net, x, y, b)\n', (2742, 2756), False, 'from mindspore.common.api import _executor\n'), ((2797, 2860), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': '(16)', 'global_rank': '(0)'}), '(device_num=16, global_rank=0)\n', (2830, 2860), False, 'from mindspore import context\n'), ((3091, 3154), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': '(16)', 'global_rank': '(0)'}), '(device_num=16, global_rank=0)\n', (3124, 3154), False, 'from mindspore import context\n'), ((3402, 3465), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': '(16)', 'global_rank': '(0)'}), '(device_num=16, global_rank=0)\n', (3435, 3465), False, 'from mindspore import context\n'), ((3738, 3801), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': '(16)', 'global_rank': '(0)'}), '(device_num=16, global_rank=0)\n', (3771, 3801), False, 'from mindspore import context\n'), ((4021, 4084), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': '(16)', 'global_rank': '(0)'}), '(device_num=16, global_rank=0)\n', (4054, 4084), False, 'from mindspore import context\n'), ((4288, 4351), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': '(16)', 'global_rank': '(0)'}), '(device_num=16, global_rank=0)\n', (4321, 4351), False, 'from mindspore import context\n'), ((4690, 4753), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': '(16)', 'global_rank': '(0)'}), '(device_num=16, global_rank=0)\n', (4723, 4753), False, 'from mindspore import context\n'), ((5036, 5099), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': '(16)', 'global_rank': '(0)'}), '(device_num=16, global_rank=0)\n', (5069, 5099), False, 'from mindspore import context\n'), ((5340, 5404), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'device_num': '(16)', 'global_rank': '(14)'}), '(device_num=16, global_rank=14)\n', (5373, 5404), False, 'from mindspore import context\n'), ((1117, 1134), 'mindspore.ops.operations.comm_ops._VirtualDataset', '_VirtualDataset', ([], {}), '()\n', (1132, 1134), False, 'from mindspore.ops.operations.comm_ops import _VirtualDataset\n'), ((1226, 1249), 'mindspore.Tensor', 'Tensor', (['(2.0)', 'ms.float32'], {}), '(2.0, ms.float32)\n', (1232, 1249), False, 'from mindspore import Tensor\n'), ((1275, 1298), 'mindspore.Tensor', 'Tensor', (['(1.0)', 'ms.float32'], {}), '(1.0, ms.float32)\n', (1281, 1298), False, 'from mindspore import Tensor\n'), ((2417, 2481), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'parallel_mode': '"""auto_parallel"""'}), "(parallel_mode='auto_parallel')\n", (2450, 2481), False, 'from mindspore import context\n'), ((2500, 2569), 'mindspore.context.set_auto_parallel_context', 'context.set_auto_parallel_context', ([], {'parallel_mode': '"""semi_auto_parallel"""'}), "(parallel_mode='semi_auto_parallel')\n", (2533, 2569), False, 'from mindspore import context\n'), ((2586, 2603), 'numpy.ones', 'np.ones', (['[64, 32]'], {}), '([64, 32])\n', (2593, 2603), True, 'import numpy as np\n'), ((2638, 2655), 'numpy.ones', 'np.ones', (['[32, 64]'], {}), '([32, 64])\n', (2645, 2655), True, 'import numpy as np\n'), ((2690, 2703), 'numpy.ones', 'np.ones', (['[64]'], {}), '([64])\n', (2697, 2703), True, 'import numpy as np\n'), ((1825, 1849), 'mindspore.ops.composite.grad_all', 'C.grad_all', (['self.network'], {}), '(self.network)\n', (1835, 1849), True, 'from mindspore.ops import composite as C\n'), ((1158, 1177), 'mindspore.ops.operations.OneHot', 'P.OneHot', ([], {'axis': 'axis'}), '(axis=axis)\n', (1166, 1177), True, 'from mindspore.ops import operations as P\n'), ((1319, 1352), 'mindspore.ops.operations.SoftmaxCrossEntropyWithLogits', 'P.SoftmaxCrossEntropyWithLogits', ([], {}), '()\n', (1350, 1352), True, 'from mindspore.ops import operations as P\n'), ((1976, 1986), 'mindspore.ops.operations.MatMul', 'P.MatMul', ([], {}), '()\n', (1984, 1986), True, 'from mindspore.ops import operations as P\n'), ((2031, 2039), 'mindspore.ops.operations.Gelu', 'P.Gelu', ([], {}), '()\n', (2037, 2039), True, 'from mindspore.ops import operations as P\n')]
# -*- coding: utf-8 -* # Licensed under a 3-clause BSD style license - see LICENSE.rst import pytest import requests import os from astropy.coordinates import SkyCoord import astropy.units as u from astropy.table import Table, Column from astropy.io.votable import parse from astroquery import log from astroquery.casda import Casda try: from unittest.mock import Mock, patch, PropertyMock, MagicMock except ImportError: pytest.skip("Install mock for the casda tests.", allow_module_level=True) DATA_FILES = {'CIRCLE': 'cone.xml', 'RANGE': 'box.xml', 'DATALINK': 'datalink.xml', 'RUN_JOB': 'run_job.xml', 'COMPLETED_JOB': 'completed_job.xml', 'DATALINK_NOACCESS': 'datalink_noaccess.xml'} class MockResponse: def __init__(self, content): self.content = content self.text = content.decode() def raise_for_status(self): return first_job_pass = True def get_mockreturn(self, method, url, data=None, timeout=10, files=None, params=None, headers=None, **kwargs): log.debug("get_mockreturn url:{} params:{} kwargs:{}".format(url, params, kwargs)) if kwargs and 'auth' in kwargs: auth = kwargs['auth'] if auth and (auth[0] != 'user' or auth[1] != 'password'): log.debug("Rejecting credentials") return create_auth_failure_response() if 'data/async' in str(url): # Responses for an asynchronous SODA job if str(url).endswith('data/async'): self.first_job_pass = True return create_soda_create_response('111-000-111-000') elif str(url).endswith('/phase') and method == 'POST': key = "RUN_JOB" elif str(url).endswith('111-000-111-000') and method == 'GET': key = "RUN_JOB" if self.first_job_pass else "COMPLETED_JOB" self.first_job_pass = False else: raise ValueError("Unexpected SODA async {} call to url {}".format(method, url)) elif 'datalink' in str(url): if 'cube-244' in str(url): key = 'DATALINK' else: key = 'DATALINK_NOACCESS' else: key = params['POS'].split()[0] if params['POS'] else None filename = data_path(DATA_FILES[key]) log.debug('providing ' + filename) content = open(filename, 'rb').read() return MockResponse(content) def create_soda_create_response(jobid): job_url = 'https://casda.csiro.au/casda_data_access/data/async/' + jobid create_response_headers = [ ['location', job_url] ] create_response = Mock(spec=requests.Response) create_response.configure_mock(status_code=303, message='OK', headers=create_response_headers, url=job_url) return create_response def create_auth_failure_response(): unauthenticated_headers = [ ['WWW-Authenticate', 'Basic realm="ATNF OPAL Login"'] ] create_response = MagicMock(spec=requests.Response) attrs = {'raise_for_status.side_effect': requests.exceptions.HTTPError()} create_response.configure_mock(status_code=401, message='OK', headers=unauthenticated_headers, **attrs) return create_response @pytest.fixture def patch_get(request): try: mp = request.getfixturevalue("monkeypatch") except AttributeError: # pytest < 3 mp = request.getfuncargvalue("monkeypatch") mp.setattr(requests.Session, 'request', get_mockreturn) return mp def data_path(filename): data_dir = os.path.join(os.path.dirname(__file__), 'data') return os.path.join(data_dir, filename) def isclose(value1, value2, abs_tol=1e-09): return abs(value1 - value2) < abs_tol def test_query_region_text_radius(patch_get): ra = 333.9092 dec = -45.8418 radius = 0.5 query_payload = Casda.query_region('22h15m38.2s -45d50m30.5s', radius=radius * u.deg, cache=False, get_query_payload=True) assert isinstance(query_payload, dict) assert 'POS' in query_payload assert query_payload['POS'].startswith('CIRCLE 333') pos_parts = query_payload['POS'].split(' ') assert pos_parts[0] == 'CIRCLE' assert isclose(float(pos_parts[1]), ra, abs_tol=1e-4) assert isclose(float(pos_parts[2]), dec, abs_tol=1e-4) assert isclose(float(pos_parts[3]), radius) assert len(pos_parts) == 4 responses = Casda.query_region('22h15m38.2s -45d50m30.5s', radius=0.5 * u.deg, cache=False) assert isinstance(responses, Table) assert len(responses) == 3 def test_query_region_radius(patch_get): ra = 333.9092 dec = -45.8418 radius = 0.5 centre = SkyCoord(ra, dec, unit=('deg', 'deg')) query_payload = Casda.query_region(centre, radius=radius * u.deg, cache=False, get_query_payload=True) assert isinstance(query_payload, dict) assert 'POS' in query_payload assert query_payload['POS'].startswith('CIRCLE 333') pos_parts = query_payload['POS'].split(' ') assert pos_parts[0] == 'CIRCLE' assert isclose(float(pos_parts[1]), ra, abs_tol=1e-5) assert isclose(float(pos_parts[2]), dec, abs_tol=1e-5) assert isclose(float(pos_parts[3]), radius) assert len(pos_parts) == 4 responses = Casda.query_region(centre, radius=0.5 * u.deg, cache=False) assert isinstance(responses, Table) assert len(responses) == 3 def test_query_region_async_radius(patch_get): ra = 333.9092 dec = -45.8418 radius = 0.5 centre = SkyCoord(ra, dec, unit=('deg', 'deg')) query_payload = Casda.query_region_async(centre, radius=radius * u.deg, cache=False, get_query_payload=True) assert isinstance(query_payload, dict) assert 'POS' in query_payload assert query_payload['POS'].startswith('CIRCLE 333') pos_parts = query_payload['POS'].split(' ') assert pos_parts[0] == 'CIRCLE' assert isclose(float(pos_parts[1]), ra, abs_tol=1e-5) assert isclose(float(pos_parts[2]), dec, abs_tol=1e-5) assert isclose(float(pos_parts[3]), radius) assert len(pos_parts) == 4 responses = Casda.query_region_async(centre, radius=0.5 * u.deg, cache=False) assert isinstance(responses, MockResponse) def test_query_region_box(patch_get): ra = 333.9092 dec = -45.8418 width = 0.5 height = 0.2 centre = SkyCoord(ra, dec, unit=('deg', 'deg')) query_payload = Casda.query_region(centre, width=width * u.deg, height=height * u.deg, cache=False, get_query_payload=True) assert isinstance(query_payload, dict) assert 'POS' in query_payload assert query_payload['POS'].startswith('RANGE 333') pos_parts = query_payload['POS'].split(' ') assert pos_parts[0] == 'RANGE' assert isclose(float(pos_parts[1]), ra - width / 2, abs_tol=1e-5) assert isclose(float(pos_parts[2]), ra + width / 2, abs_tol=1e-5) assert isclose(float(pos_parts[3]), dec - height / 2, abs_tol=1e-5) assert isclose(float(pos_parts[4]), dec + height / 2, abs_tol=1e-5) assert len(pos_parts) == 5 responses = Casda.query_region(centre, width=width * u.deg, height=height * u.deg, cache=False) assert isinstance(responses, Table) assert len(responses) == 2 def test_query_region_async_box(patch_get): ra = 333.9092 dec = -45.8418 width = 0.5 height = 0.2 centre = SkyCoord(ra, dec, unit=('deg', 'deg')) query_payload = Casda.query_region_async(centre, width=width * u.deg, height=height * u.deg, cache=False, get_query_payload=True) assert isinstance(query_payload, dict) assert 'POS' in query_payload assert query_payload['POS'].startswith('RANGE 333') pos_parts = query_payload['POS'].split(' ') assert pos_parts[0] == 'RANGE' assert isclose(float(pos_parts[1]), ra - width / 2, abs_tol=1e-5) assert isclose(float(pos_parts[2]), ra + width / 2, abs_tol=1e-5) assert isclose(float(pos_parts[3]), dec - height / 2, abs_tol=1e-5) assert isclose(float(pos_parts[4]), dec + height / 2, abs_tol=1e-5) assert len(pos_parts) == 5 responses = Casda.query_region_async(centre, width=width * u.deg, height=height * u.deg, cache=False) assert isinstance(responses, MockResponse) def test_filter_out_unreleased(): all_records = parse(data_path('partial_unreleased.xml'), verify='warn').get_first_table().to_table() assert all_records[0]['obs_release_date'] == '2017-08-02T03:51:19.728Z' assert all_records[1]['obs_release_date'] == '2218-01-02T16:51:00.728Z' assert all_records[2]['obs_release_date'] == '' assert len(all_records) == 3 # This should filter out the rows with either a future obs_release_date or no obs_release_date filtered = Casda.filter_out_unreleased(all_records) assert filtered[0]['obs_release_date'] == '2017-08-02T03:51:19.728Z' assert filtered[0]['obs_publisher_did'] == 'cube-502' assert len(filtered) == 1 def test_stage_data_unauthorised(patch_get): table = Table() with pytest.raises(ValueError) as excinfo: Casda.stage_data(table) assert "Credentials must be supplied" in str(excinfo.value) def test_stage_data_empty(patch_get): table = Table() casda = Casda('user', 'password') urls = casda.stage_data(table) assert urls == [] def test_stage_data_invalid_credentials(patch_get): prefix = 'https://somewhere/casda/datalink/links?' access_urls = [prefix + 'cube-220'] table = Table([Column(data=access_urls, name='access_url')]) casda = Casda('user', '<PASSWORD>') with pytest.raises(requests.exceptions.HTTPError) as excinfo: casda.stage_data(table) def test_stage_data_no_link(patch_get): prefix = 'https://somewhere/casda/datalink/links?' access_urls = [prefix + 'cube-240'] table = Table([Column(data=access_urls, name='access_url')]) casda = Casda('user', 'password') casda.POLL_INTERVAL = 1 with pytest.raises(ValueError) as excinfo: casda.stage_data(table) assert "You do not have access to any of the requested data files." in str(excinfo.value) def test_stage_data(patch_get): prefix = 'https://somewhere/casda/datalink/links?' access_urls = [prefix + 'cube-244'] table = Table([Column(data=access_urls, name='access_url')]) casda = Casda('user', 'password') casda.POLL_INTERVAL = 1 urls = casda.stage_data(table, verbose=True) assert urls == ['http://casda.csiro.au/download/web/111-000-111-000/askap_img.fits.checksum', 'http://casda.csiro.au/download/web/111-000-111-000/askap_img.fits']
[ "astroquery.casda.Casda.filter_out_unreleased", "astroquery.casda.Casda.stage_data", "unittest.mock.Mock", "astropy.table.Table", "unittest.mock.MagicMock", "os.path.join", "astropy.coordinates.SkyCoord", "astroquery.log.debug", "os.path.dirname", "astroquery.casda.Casda", "pytest.raises", "as...
[((2245, 2279), 'astroquery.log.debug', 'log.debug', (["('providing ' + filename)"], {}), "('providing ' + filename)\n", (2254, 2279), False, 'from astroquery import log\n'), ((2565, 2593), 'unittest.mock.Mock', 'Mock', ([], {'spec': 'requests.Response'}), '(spec=requests.Response)\n', (2569, 2593), False, 'from unittest.mock import Mock, patch, PropertyMock, MagicMock\n'), ((2893, 2926), 'unittest.mock.MagicMock', 'MagicMock', ([], {'spec': 'requests.Response'}), '(spec=requests.Response)\n', (2902, 2926), False, 'from unittest.mock import Mock, patch, PropertyMock, MagicMock\n'), ((3511, 3543), 'os.path.join', 'os.path.join', (['data_dir', 'filename'], {}), '(data_dir, filename)\n', (3523, 3543), False, 'import os\n'), ((3754, 3865), 'astroquery.casda.Casda.query_region', 'Casda.query_region', (['"""22h15m38.2s -45d50m30.5s"""'], {'radius': '(radius * u.deg)', 'cache': '(False)', 'get_query_payload': '(True)'}), "('22h15m38.2s -45d50m30.5s', radius=radius * u.deg, cache\n =False, get_query_payload=True)\n", (3772, 3865), False, 'from astroquery.casda import Casda\n'), ((4331, 4410), 'astroquery.casda.Casda.query_region', 'Casda.query_region', (['"""22h15m38.2s -45d50m30.5s"""'], {'radius': '(0.5 * u.deg)', 'cache': '(False)'}), "('22h15m38.2s -45d50m30.5s', radius=0.5 * u.deg, cache=False)\n", (4349, 4410), False, 'from astroquery.casda import Casda\n'), ((4592, 4630), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['ra', 'dec'], {'unit': "('deg', 'deg')"}), "(ra, dec, unit=('deg', 'deg'))\n", (4600, 4630), False, 'from astropy.coordinates import SkyCoord\n'), ((4651, 4741), 'astroquery.casda.Casda.query_region', 'Casda.query_region', (['centre'], {'radius': '(radius * u.deg)', 'cache': '(False)', 'get_query_payload': '(True)'}), '(centre, radius=radius * u.deg, cache=False,\n get_query_payload=True)\n', (4669, 4741), False, 'from astroquery.casda import Casda\n'), ((5169, 5228), 'astroquery.casda.Casda.query_region', 'Casda.query_region', (['centre'], {'radius': '(0.5 * u.deg)', 'cache': '(False)'}), '(centre, radius=0.5 * u.deg, cache=False)\n', (5187, 5228), False, 'from astroquery.casda import Casda\n'), ((5416, 5454), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['ra', 'dec'], {'unit': "('deg', 'deg')"}), "(ra, dec, unit=('deg', 'deg'))\n", (5424, 5454), False, 'from astropy.coordinates import SkyCoord\n'), ((5475, 5571), 'astroquery.casda.Casda.query_region_async', 'Casda.query_region_async', (['centre'], {'radius': '(radius * u.deg)', 'cache': '(False)', 'get_query_payload': '(True)'}), '(centre, radius=radius * u.deg, cache=False,\n get_query_payload=True)\n', (5499, 5571), False, 'from astroquery.casda import Casda\n'), ((5999, 6064), 'astroquery.casda.Casda.query_region_async', 'Casda.query_region_async', (['centre'], {'radius': '(0.5 * u.deg)', 'cache': '(False)'}), '(centre, radius=0.5 * u.deg, cache=False)\n', (6023, 6064), False, 'from astroquery.casda import Casda\n'), ((6235, 6273), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['ra', 'dec'], {'unit': "('deg', 'deg')"}), "(ra, dec, unit=('deg', 'deg'))\n", (6243, 6273), False, 'from astropy.coordinates import SkyCoord\n'), ((6294, 6405), 'astroquery.casda.Casda.query_region', 'Casda.query_region', (['centre'], {'width': '(width * u.deg)', 'height': '(height * u.deg)', 'cache': '(False)', 'get_query_payload': '(True)'}), '(centre, width=width * u.deg, height=height * u.deg,\n cache=False, get_query_payload=True)\n', (6312, 6405), False, 'from astroquery.casda import Casda\n'), ((6989, 7076), 'astroquery.casda.Casda.query_region', 'Casda.query_region', (['centre'], {'width': '(width * u.deg)', 'height': '(height * u.deg)', 'cache': '(False)'}), '(centre, width=width * u.deg, height=height * u.deg,\n cache=False)\n', (7007, 7076), False, 'from astroquery.casda import Casda\n'), ((7273, 7311), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['ra', 'dec'], {'unit': "('deg', 'deg')"}), "(ra, dec, unit=('deg', 'deg'))\n", (7281, 7311), False, 'from astropy.coordinates import SkyCoord\n'), ((7332, 7449), 'astroquery.casda.Casda.query_region_async', 'Casda.query_region_async', (['centre'], {'width': '(width * u.deg)', 'height': '(height * u.deg)', 'cache': '(False)', 'get_query_payload': '(True)'}), '(centre, width=width * u.deg, height=height * u.deg,\n cache=False, get_query_payload=True)\n', (7356, 7449), False, 'from astroquery.casda import Casda\n'), ((8039, 8132), 'astroquery.casda.Casda.query_region_async', 'Casda.query_region_async', (['centre'], {'width': '(width * u.deg)', 'height': '(height * u.deg)', 'cache': '(False)'}), '(centre, width=width * u.deg, height=height * u.deg,\n cache=False)\n', (8063, 8132), False, 'from astroquery.casda import Casda\n'), ((8669, 8709), 'astroquery.casda.Casda.filter_out_unreleased', 'Casda.filter_out_unreleased', (['all_records'], {}), '(all_records)\n', (8696, 8709), False, 'from astroquery.casda import Casda\n'), ((8930, 8937), 'astropy.table.Table', 'Table', ([], {}), '()\n', (8935, 8937), False, 'from astropy.table import Table, Column\n'), ((9135, 9142), 'astropy.table.Table', 'Table', ([], {}), '()\n', (9140, 9142), False, 'from astropy.table import Table, Column\n'), ((9155, 9180), 'astroquery.casda.Casda', 'Casda', (['"""user"""', '"""password"""'], {}), "('user', 'password')\n", (9160, 9180), False, 'from astroquery.casda import Casda\n'), ((9465, 9492), 'astroquery.casda.Casda', 'Casda', (['"""user"""', '"""<PASSWORD>"""'], {}), "('user', '<PASSWORD>')\n", (9470, 9492), False, 'from astroquery.casda import Casda\n'), ((9805, 9830), 'astroquery.casda.Casda', 'Casda', (['"""user"""', '"""password"""'], {}), "('user', 'password')\n", (9810, 9830), False, 'from astroquery.casda import Casda\n'), ((10240, 10265), 'astroquery.casda.Casda', 'Casda', (['"""user"""', '"""password"""'], {}), "('user', 'password')\n", (10245, 10265), False, 'from astroquery.casda import Casda\n'), ((435, 508), 'pytest.skip', 'pytest.skip', (['"""Install mock for the casda tests."""'], {'allow_module_level': '(True)'}), "('Install mock for the casda tests.', allow_module_level=True)\n", (446, 508), False, 'import pytest\n'), ((2972, 3003), 'requests.exceptions.HTTPError', 'requests.exceptions.HTTPError', ([], {}), '()\n', (3001, 3003), False, 'import requests\n'), ((3465, 3490), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3480, 3490), False, 'import os\n'), ((8948, 8973), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (8961, 8973), False, 'import pytest\n'), ((8994, 9017), 'astroquery.casda.Casda.stage_data', 'Casda.stage_data', (['table'], {}), '(table)\n', (9010, 9017), False, 'from astroquery.casda import Casda\n'), ((9502, 9546), 'pytest.raises', 'pytest.raises', (['requests.exceptions.HTTPError'], {}), '(requests.exceptions.HTTPError)\n', (9515, 9546), False, 'import pytest\n'), ((9869, 9894), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (9882, 9894), False, 'import pytest\n'), ((1277, 1311), 'astroquery.log.debug', 'log.debug', (['"""Rejecting credentials"""'], {}), "('Rejecting credentials')\n", (1286, 1311), False, 'from astroquery import log\n'), ((9406, 9449), 'astropy.table.Column', 'Column', ([], {'data': 'access_urls', 'name': '"""access_url"""'}), "(data=access_urls, name='access_url')\n", (9412, 9449), False, 'from astropy.table import Table, Column\n'), ((9747, 9790), 'astropy.table.Column', 'Column', ([], {'data': 'access_urls', 'name': '"""access_url"""'}), "(data=access_urls, name='access_url')\n", (9753, 9790), False, 'from astropy.table import Table, Column\n'), ((10182, 10225), 'astropy.table.Column', 'Column', ([], {'data': 'access_urls', 'name': '"""access_url"""'}), "(data=access_urls, name='access_url')\n", (10188, 10225), False, 'from astropy.table import Table, Column\n')]
# 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. """Defines functions for controlling debuggers for micro TVM binaries.""" import atexit import abc import errno import logging import os import shlex import signal import subprocess import sys import termios import threading import time import psutil from .._ffi import register_func from . import class_factory from . import transport from .transport.file_descriptor import FdTransport _LOG = logging.getLogger(__name__) class Debugger(metaclass=abc.ABCMeta): """An interface for controlling micro TVM debuggers.""" @abc.abstractmethod def start(self): """Start the debugger, but do not block on it. The runtime will continue to be driven in the background. """ raise NotImplementedError() @abc.abstractmethod def stop(self): """Terminate the debugger.""" raise NotImplementedError() class GdbDebugger(Debugger): """Handles launching, suspending signals, and potentially dealing with terminal issues.""" # Number of seconds to wait in stop() for a graceful shutdown. After this time has elapsed, # the debugger is kill()'d. _GRACEFUL_SHUTDOWN_TIMEOUT_SEC = 5.0 # The instance of GdbDebugger that's currently started. _STARTED_INSTANCE = None @classmethod def _stop_all(cls): if cls._STARTED_INSTANCE: cls._STARTED_INSTANCE.stop() def __init__(self): super(GdbDebugger, self).__init__() self._is_running = False self._is_running_lock = threading.RLock() self._child_exited_event = threading.Event() self._signals_reset_event = threading.Event() @abc.abstractmethod def popen_kwargs(self): raise NotImplementedError() def _internal_stop(self): if not self._is_running: return os.kill(os.getpid(), signal.SIGUSR1) self._signals_reset_event.wait() termios.tcsetattr(sys.stdin.fileno(), termios.TCSAFLUSH, self.old_termios) try: children = psutil.Process(self.popen.pid).children(recursive=True) for c in children: c.terminate() _, alive = psutil.wait_procs(children, timeout=self._GRACEFUL_SHUTDOWN_TIMEOUT_SEC) for a in alive: a.kill() except psutil.NoSuchProcess: pass finally: self.__class__._STARTED_INSTANCE = None self._is_running = False self._child_exited_event.set() def _wait_for_child(self): self.popen.wait() with self._is_running_lock: self._internal_stop() @classmethod def _sigusr1_handler(cls, signum, stack_frame): # pylint: disable=unused-argument assert ( cls._STARTED_INSTANCE is not None ), "overridden sigusr1 handler should not be invoked when GDB not started" signal.signal(signal.SIGINT, cls._STARTED_INSTANCE.old_sigint_handler) signal.signal(signal.SIGUSR1, cls._STARTED_INSTANCE.old_sigusr1_handler) cls._STARTED_INSTANCE._signals_reset_event.set() @classmethod def _sigint_handler(cls, signum, stack_frame): # pylint: disable=unused-argument assert ( cls._STARTED_INSTANCE is not None ), "overridden sigint handler should not be invoked when GDB not started" with cls._STARTED_INSTANCE._is_running_lock: exists = cls._STARTED_INSTANCE._is_running if exists: try: os.killpg(cls._STARTED_INSTANCE.child_pgid, signal.SIGINT) except ProcessLookupError: pass def start(self): with self._is_running_lock: assert not self._is_running assert not self._STARTED_INSTANCE kwargs = self.popen_kwargs() self.did_start_new_session = kwargs.setdefault("start_new_session", True) self.old_termios = termios.tcgetattr(sys.stdin.fileno()) self.popen = subprocess.Popen(**kwargs) self._is_running = True self.old_sigint_handler = signal.signal(signal.SIGINT, self._sigint_handler) self.old_sigusr1_handler = signal.signal(signal.SIGUSR1, self._sigusr1_handler) self.__class__._STARTED_INSTANCE = self try: self.child_pgid = os.getpgid(self.popen.pid) except Exception: self.stop() raise with self._is_running_lock: self._is_child_alive = True t = threading.Thread(target=self._wait_for_child) t.daemon = True t.start() def stop(self): self._child_exited_event.wait() atexit.register(GdbDebugger._stop_all) class GdbTransportDebugger(GdbDebugger): """A debugger that uses a single GDB subprocess as both the transport and the debugger. Opens pipes for the target's stdin and stdout, launches GDB and configures GDB's target arguments to read and write from the pipes using /dev/fd. """ def __init__(self, args, **popen_kw): super(GdbTransportDebugger, self).__init__() self.args = args self.popen_kw = popen_kw def popen_kwargs(self): stdin_read, stdin_write = os.pipe() stdout_read, stdout_write = os.pipe() os.set_inheritable(stdin_read, True) os.set_inheritable(stdout_write, True) sysname = os.uname()[0] if sysname == "Darwin": args = [ "lldb", "-O", f"target create {self.args[0]}", "-O", f"settings set target.input-path /dev/fd/{stdin_read}", "-O", f"settings set target.output-path /dev/fd/{stdout_write}", ] if len(self.args) > 1: args.extend( ["-O", "settings set target.run-args {}".format(" ".join(self.args[1:]))] ) elif sysname == "Linux": args = [ "gdb", "-ex", f"file {self.args[0]}", "-ex", ( f"set args {' '.join(shlex.quote(a) for a in self.args[1:])} " f"</dev/fd/{stdin_read} >/dev/fd/{stdout_write}" ), ] else: raise NotImplementedError(f"System {sysname} is not yet supported") self.fd_transport = FdTransport( stdout_read, stdin_write, transport.debug_transport_timeouts() ) self.fd_transport.open() return { "args": args, "pass_fds": [stdin_read, stdout_write], } def _internal_stop(self): self.fd_transport.close() super(GdbTransportDebugger, self)._internal_stop() class _Transport(transport.Transport): def __init__(self, gdb_transport_debugger): self.gdb_transport_debugger = gdb_transport_debugger def timeouts(self): return transport.debug_transport_timeouts() def open(self): pass # Pipes opened by parent class. def write(self, data, timeout_sec): end_time = time.monotonic() + timeout_sec if timeout_sec is not None else None while True: try: return self.gdb_transport_debugger.fd_transport.write(data, timeout_sec) except OSError as exc: # NOTE: this error sometimes happens when writes are initiated before the child # process launches. if exc.errno == errno.EAGAIN: if end_time is None or time.monotonic() < end_time: time.sleep(0.1) # sleep to avoid excessive CPU usage continue raise exc raise base.IoTimeoutError() def read(self, n, timeout_sec): end_time = time.monotonic() + timeout_sec if timeout_sec is not None else None while True: try: return self.gdb_transport_debugger.fd_transport.read(n, timeout_sec) except OSError as exc: # NOTE: this error sometimes happens when reads are initiated before the child # process launches. if exc.errno == errno.EAGAIN: if end_time is None or time.monotonic() < end_time: time.sleep(0.1) # sleep to avoid excessive CPU usage continue raise exc raise base.IoTimeoutError() def close(self): pass # Pipes closed by parent class. def transport(self): return self._Transport(self) class GdbRemoteDebugger(GdbDebugger): """A Debugger that invokes GDB and attaches to a remote GDBserver-based target.""" def __init__( self, gdb_binary, remote_hostport, debug_binary, wrapping_context_manager=None, **popen_kw ): super(GdbRemoteDebugger, self).__init__() self.gdb_binary = gdb_binary self.remote_hostport = remote_hostport self.debug_binary = debug_binary self.wrapping_context_manager = wrapping_context_manager self.popen_kw = popen_kw def popen_kwargs(self): kwargs = { "args": [ self.gdb_binary, "-iex", f"file {self.debug_binary}", "-iex", f"target remote {self.remote_hostport}", ], } kwargs.update(self.popen_kw) return kwargs def start(self): if self.wrapping_context_manager is not None: self.wrapping_context_manager.__enter__() super(GdbRemoteDebugger, self).start() def stop(self): try: super(GdbRemoteDebugger, self).stop() finally: if self.wrapping_context_manager is not None: self.wrapping_context_manager.__exit__(None, None, None) GLOBAL_DEBUGGER = None class DebuggerFactory(class_factory.ClassFactory): SUPERCLASS = Debugger def launch_debugger(debugger_factory, *args, **kw): global GLOBAL_DEBUGGER if GLOBAL_DEBUGGER is not None: stop_debugger() GLOBAL_DEBUGGER = debugger_factory.instantiate(*args, **kw) GLOBAL_DEBUGGER.start() @register_func("tvm.micro.debugger.launch_debugger") def _launch_debugger(debugger_factory_json): launch_debugger(DebuggerFactory.from_json(debugger_factory_json)) @register_func("tvm.micro.debugger.stop_debugger") def stop_debugger(): global GLOBAL_DEBUGGER if GLOBAL_DEBUGGER is not None: try: GLOBAL_DEBUGGER.stop() finally: GLOBAL_DEBUGGER = None class RpcDebugger(Debugger): """A Debugger instance that launches the actual debugger on a remote TVM RPC server.""" def __init__(self, rpc_session, factory, wrapping_context_manager=None): super(RpcDebugger, self).__init__() self._factory = factory self.launch_debugger = rpc_session.get_function("tvm.micro.debugger.launch_debugger") self.stop_debugger = rpc_session.get_function("tvm.micro.debugger.stop_debugger") self.wrapping_context_manager = wrapping_context_manager def start(self): if self.wrapping_context_manager is not None: self.wrapping_context_manager.__enter__() try: self.launch_debugger(self._factory.to_json) except Exception: if self.wrapping_context_manager is not None: self.wrapping_context_manager.__exit__(None, None, None) raise try: input("Press [Enter] when debugger is set") except Exception: self.stop() raise self._is_running = True def stop(self): try: self.stop_debugger() finally: if self.wrapping_context_manager is not None: self.wrapping_context_manager.__exit__(None, None, None)
[ "logging.getLogger", "os.set_inheritable", "psutil.Process", "time.sleep", "sys.stdin.fileno", "subprocess.Popen", "threading.RLock", "os.getpid", "shlex.quote", "atexit.register", "os.uname", "os.getpgid", "time.monotonic", "os.killpg", "signal.signal", "threading.Event", "psutil.wa...
[((1185, 1212), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1202, 1212), False, 'import logging\n'), ((5475, 5513), 'atexit.register', 'atexit.register', (['GdbDebugger._stop_all'], {}), '(GdbDebugger._stop_all)\n', (5490, 5513), False, 'import atexit\n'), ((2286, 2303), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (2301, 2303), False, 'import threading\n'), ((2339, 2356), 'threading.Event', 'threading.Event', ([], {}), '()\n', (2354, 2356), False, 'import threading\n'), ((2393, 2410), 'threading.Event', 'threading.Event', ([], {}), '()\n', (2408, 2410), False, 'import threading\n'), ((3658, 3728), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'cls._STARTED_INSTANCE.old_sigint_handler'], {}), '(signal.SIGINT, cls._STARTED_INSTANCE.old_sigint_handler)\n', (3671, 3728), False, 'import signal\n'), ((3737, 3809), 'signal.signal', 'signal.signal', (['signal.SIGUSR1', 'cls._STARTED_INSTANCE.old_sigusr1_handler'], {}), '(signal.SIGUSR1, cls._STARTED_INSTANCE.old_sigusr1_handler)\n', (3750, 3809), False, 'import signal\n'), ((6029, 6038), 'os.pipe', 'os.pipe', ([], {}), '()\n', (6036, 6038), False, 'import os\n'), ((6075, 6084), 'os.pipe', 'os.pipe', ([], {}), '()\n', (6082, 6084), False, 'import os\n'), ((6094, 6130), 'os.set_inheritable', 'os.set_inheritable', (['stdin_read', '(True)'], {}), '(stdin_read, True)\n', (6112, 6130), False, 'import os\n'), ((6139, 6177), 'os.set_inheritable', 'os.set_inheritable', (['stdout_write', '(True)'], {}), '(stdout_write, True)\n', (6157, 6177), False, 'import os\n'), ((2600, 2611), 'os.getpid', 'os.getpid', ([], {}), '()\n', (2609, 2611), False, 'import os\n'), ((2696, 2714), 'sys.stdin.fileno', 'sys.stdin.fileno', ([], {}), '()\n', (2712, 2714), False, 'import sys\n'), ((4762, 4788), 'subprocess.Popen', 'subprocess.Popen', ([], {}), '(**kwargs)\n', (4778, 4788), False, 'import subprocess\n'), ((4863, 4913), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'self._sigint_handler'], {}), '(signal.SIGINT, self._sigint_handler)\n', (4876, 4913), False, 'import signal\n'), ((4953, 5005), 'signal.signal', 'signal.signal', (['signal.SIGUSR1', 'self._sigusr1_handler'], {}), '(signal.SIGUSR1, self._sigusr1_handler)\n', (4966, 5005), False, 'import signal\n'), ((5316, 5361), 'threading.Thread', 'threading.Thread', ([], {'target': 'self._wait_for_child'}), '(target=self._wait_for_child)\n', (5332, 5361), False, 'import threading\n'), ((6197, 6207), 'os.uname', 'os.uname', ([], {}), '()\n', (6205, 6207), False, 'import os\n'), ((2934, 3006), 'psutil.wait_procs', 'psutil.wait_procs', (['children'], {'timeout': 'self._GRACEFUL_SHUTDOWN_TIMEOUT_SEC'}), '(children, timeout=self._GRACEFUL_SHUTDOWN_TIMEOUT_SEC)\n', (2951, 3006), False, 'import psutil\n'), ((4276, 4334), 'os.killpg', 'os.killpg', (['cls._STARTED_INSTANCE.child_pgid', 'signal.SIGINT'], {}), '(cls._STARTED_INSTANCE.child_pgid, signal.SIGINT)\n', (4285, 4334), False, 'import os\n'), ((4717, 4735), 'sys.stdin.fileno', 'sys.stdin.fileno', ([], {}), '()\n', (4733, 4735), False, 'import sys\n'), ((5109, 5135), 'os.getpgid', 'os.getpgid', (['self.popen.pid'], {}), '(self.popen.pid)\n', (5119, 5135), False, 'import os\n'), ((2790, 2820), 'psutil.Process', 'psutil.Process', (['self.popen.pid'], {}), '(self.popen.pid)\n', (2804, 2820), False, 'import psutil\n'), ((7979, 7995), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (7993, 7995), False, 'import time\n'), ((8745, 8761), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (8759, 8761), False, 'import time\n'), ((8518, 8533), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (8528, 8533), False, 'import time\n'), ((9279, 9294), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (9289, 9294), False, 'import time\n'), ((6962, 6976), 'shlex.quote', 'shlex.quote', (['a'], {}), '(a)\n', (6973, 6976), False, 'import shlex\n'), ((8461, 8477), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (8475, 8477), False, 'import time\n'), ((9222, 9238), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (9236, 9238), False, 'import time\n')]
from flask_marshmallow import Marshmallow from marshmallow import Schema, post_load from api.models import Book, Transaction, User ma = Marshmallow() class ResponseSchema(Schema): class Meta: fields = ('url', ) class BookSchema(ma.SQLAlchemyAutoSchema): ''' Serializes book from and to DB. ''' class Meta: model = Book include_fk = True url = ma.URLFor('book', values=dict(book_id='<id>')) @post_load def make_book(self, data, **kwargs): return Book(**data) class UserSchema(ma.SQLAlchemyAutoSchema): ''' Serializes book from and to DB. ''' class Meta: model = User include_fk = True url = ma.URLFor('user', values=dict(user_id='<id>')) @post_load def make_user(self, data, **kwargs): return User(**data) class TransactionSchema(ma.SQLAlchemyAutoSchema): ''' Serializes rent from and to DB. ''' class Meta: model = Transaction include_fk = True url = ma.URLFor('transaction', values=dict(transaction_id='<id>')) @post_load def make_transaction(self, data, **kwargs): return Transaction(**data) book_schema = BookSchema() user_schema = UserSchema() transaction_schema = TransactionSchema() response_schema = ResponseSchema()
[ "api.models.Book", "flask_marshmallow.Marshmallow", "api.models.User", "api.models.Transaction" ]
[((138, 151), 'flask_marshmallow.Marshmallow', 'Marshmallow', ([], {}), '()\n', (149, 151), False, 'from flask_marshmallow import Marshmallow\n'), ((517, 529), 'api.models.Book', 'Book', ([], {}), '(**data)\n', (521, 529), False, 'from api.models import Book, Transaction, User\n'), ((820, 832), 'api.models.User', 'User', ([], {}), '(**data)\n', (824, 832), False, 'from api.models import Book, Transaction, User\n'), ((1158, 1177), 'api.models.Transaction', 'Transaction', ([], {}), '(**data)\n', (1169, 1177), False, 'from api.models import Book, Transaction, User\n')]
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. """ Jobclass to execute python scripts and jupyter notebooks """ import os import shutil from pyiron_base.job.generic import GenericJob from pyiron_base.generic.parameters import GenericParameters from pyiron_base.generic.datacontainer import DataContainer __author__ = "<NAME>" __copyright__ = ( "Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - " "Computational Materials Design (CM) Department" ) __version__ = "1.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "production" __date__ = "Sep 1, 2017" class ScriptJob(GenericJob): """ The ScriptJob class allows to submit Python scripts and Jupyter notebooks to the pyiron job management system. Args: project (ProjectHDFio): ProjectHDFio instance which points to the HDF5 file the job is stored in job_name (str): name of the job, which has to be unique within the project Simple example: Step 1. Create the notebook to be submitted, for ex. 'example.ipynb', and save it -- Can contain any code like: ``` import json with open('script_output.json','w') as f: json.dump({'x': [0,1]}, f) # dump some data into a JSON file ``` Step 2. Create the submitter notebook, for ex. 'submit_example_job.ipynb', which submits 'example.ipynb' to the pyiron job management system, which can have the following code: ``` from pyiron_base import Project pr = Project('scriptjob_example') # save the ScriptJob in the 'scriptjob_example' project scriptjob = pr.create.job.ScriptJob('scriptjob') # create a ScriptJob named 'scriptjob' scriptjob.script_path = 'example.ipynb' # specify the PATH to the notebook you want to submit. ``` Step 3. Check the job table to get details about 'scriptjob' by using: ``` pr.job_table() ``` Step 4. If the status of 'scriptjob' is 'finished', load the data from the JSON file into the 'submit_example_job.ipynb' notebook by using: ``` import json with open(scriptjob.working_directory + '/script_output.json') as f: data = json.load(f) # load the data from the JSON file ``` More sophisticated example: The script in ScriptJob can also be more complex, e.g. running its own pyiron calculations. Here we show how it is leveraged to run a multi-core atomistic calculation. Step 1. 'example.ipynb' can contain pyiron_atomistics code like: ``` from pyiron_atomistics import Project pr = Project('example') job = pr.create.job.Lammps('job') # we name the job 'job' job.structure = pr.create.structure.ase_bulk('Fe') # specify structure # Optional: get an input value from 'submit_example_job.ipynb', the notebook which submits # 'example.ipynb' number_of_cores = pr.data.number_of_cores job.server.cores = number_of_cores job.run() # run the job # save a custom output, that can be used by the notebook 'submit_example_job.ipynb' job['user/my_custom_output'] = 16 ``` Step 2. 'submit_example_job.ipynb', can then have the following code: ``` from pyiron_base import Project pr = Project('scriptjob_example') # save the ScriptJob in the 'scriptjob_example' project scriptjob = pr.create.job.ScriptJob('scriptjob') # create a ScriptJob named 'scriptjob' scriptjob.script_path = 'example.ipynb' # specify the PATH to the notebook you want to submit. # In this example case, 'example.ipynb' is in the same # directory as 'submit_example_job.ipynb' # Optional: to submit the notebook to a queueing system number_of_cores = 1 # number of cores to be used scriptjob.server.cores = number_of_cores scriptjob.server.queue = 'cmfe' # specify the queue to which the ScriptJob job is to be submitted scriptjob.server.run_time = 120 # specify the runtime limit for the ScriptJob job in seconds # Optional: save an input, such that it can be accessed by 'example.ipynb' pr.data.number_of_cores = number_of_cores pr.data.write() # run the ScriptJob job scriptjob.run() ``` Step 3. Check the job table by using: ``` pr.job_table() ``` in addition to containing details on 'scriptjob', the job_table also contains the details of the child 'job/s' (if any) that were submitted within the 'example.ipynb' notebook. Step 4. Reload and analyse the child 'job/s': If the status of a child 'job' is 'finished', it can be loaded into the 'submit_example_job.ipynb' notebook using: ``` job = pr.load('job') # remember in Step 1., we wanted to run a job named 'job', which has now # 'finished' ``` this loads 'job' into the 'submit_example_job.ipynb' notebook, which can be then used for analysis, ``` job.output.energy_pot[-1] # via the auto-complete job['user/my_custom_output'] # the custom output, directly from the hdf5 file ``` Attributes: attribute: job_name name of the job, which has to be unique within the project .. attribute:: status execution status of the job, can be one of the following [initialized, appended, created, submitted, running, aborted, collect, suspended, refresh, busy, finished] .. attribute:: job_id unique id to identify the job in the pyiron database .. attribute:: parent_id job id of the predecessor job - the job which was executed before the current one in the current job series .. attribute:: master_id job id of the master job - a meta job which groups a series of jobs, which are executed either in parallel or in serial. .. attribute:: child_ids list of child job ids - only meta jobs have child jobs - jobs which list the meta job as their master .. attribute:: project Project instance the jobs is located in .. attribute:: project_hdf5 ProjectHDFio instance which points to the HDF5 file the job is stored in .. attribute:: job_info_str short string to describe the job by it is job_name and job ID - mainly used for logging .. attribute:: working_directory working directory of the job is executed in - outside the HDF5 file .. attribute:: path path to the job as a combination of absolute file system path and path within the HDF5 file. .. attribute:: version Version of the hamiltonian, which is also the version of the executable unless a custom executable is used. .. attribute:: executable Executable used to run the job - usually the path to an external executable. .. attribute:: library_activated For job types which offer a Python library pyiron can use the python library instead of an external executable. .. attribute:: server Server object to handle the execution environment for the job. .. attribute:: queue_id the ID returned from the queuing system - it is most likely not the same as the job ID. .. attribute:: logger logger object to monitor the external execution and internal pyiron warnings. .. attribute:: restart_file_list list of files which are used to restart the calculation from these files. .. attribute:: job_type Job type object with all the available job types: ['ExampleJob', 'SerialMaster', 'ParallelMaster', 'ScriptJob', 'ListMaster'] .. attribute:: script_path the absolute path to the python script """ def __init__(self, project, job_name): super(ScriptJob, self).__init__(project, job_name) self.__version__ = "0.1" self.__hdf_version__ = "0.2.0" self.__name__ = "Script" self._script_path = None self.input = DataContainer(table_name="custom_dict") @property def script_path(self): """ Python script path Returns: str: absolute path to the python script """ return self._script_path @script_path.setter def script_path(self, path): """ Python script path Args: path (str): relative or absolute path to the python script or a corresponding notebook """ if isinstance(path, str): self._script_path = self._get_abs_path(path) self.executable = self._executable_command( working_directory=self.working_directory, script_path=self._script_path ) else: raise TypeError( "path should be a string, but ", path, " is a ", type(path), " instead." ) def validate_ready_to_run(self): if self.script_path is None: raise TypeError( "ScriptJob.script_path expects a path but got None. Please provide a path before " + "running." ) def set_input_to_read_only(self): """ This function enforces read-only mode for the input classes, but it has to be implement in the individual classes. """ self.input.read_only = True def to_hdf(self, hdf=None, group_name=None): """ Store the ScriptJob in an HDF5 file Args: hdf (ProjectHDFio): HDF5 group object - optional group_name (str): HDF5 subgroup name - optional """ super(ScriptJob, self).to_hdf(hdf=hdf, group_name=group_name) with self.project_hdf5.open("input") as hdf5_input: hdf5_input["path"] = self._script_path self.input.to_hdf(hdf5_input) def from_hdf(self, hdf=None, group_name=None): """ Restore the ScriptJob from an HDF5 file Args: hdf (ProjectHDFio): HDF5 group object - optional group_name (str): HDF5 subgroup name - optional """ super(ScriptJob, self).from_hdf(hdf=hdf, group_name=group_name) if "HDF_VERSION" in self.project_hdf5.list_nodes(): version = self.project_hdf5["HDF_VERSION"] else: version = "0.1.0" if version == "0.1.0": with self.project_hdf5.open("input") as hdf5_input: try: self.script_path = hdf5_input["path"] gp = GenericParameters(table_name="custom_dict") gp.from_hdf(hdf5_input) for k in gp.keys(): self.input[k] = gp[k] except TypeError: pass elif version == "0.2.0": with self.project_hdf5.open("input") as hdf5_input: try: self.script_path = hdf5_input["path"] except TypeError: pass self.input.from_hdf(hdf5_input) else: raise ValueError("Cannot handle hdf version: {}".format(version)) def write_input(self): """ Copy the script to the working directory - only python scripts and jupyter notebooks are supported """ if self._script_path is not None: file_name = os.path.basename(self._script_path) shutil.copyfile( src=self._script_path, dst=os.path.join(self.working_directory, file_name), ) def collect_output(self): """ Collect output function updates the master ID entries for all the child jobs created by this script job, if the child job is already assigned to an master job nothing happens - master IDs are not overwritten. """ for job in self.project.iter_jobs(recursive=False, convert_to_object=False): pr_job = self.project.open( os.path.relpath(job.working_directory, self.project.path) ) for subjob_id in pr_job.get_job_ids(recursive=False): if pr_job.db.get_item_by_id(subjob_id)["masterid"] is None: pr_job.db.item_update({"masterid": str(job.job_id)}, subjob_id) def run_if_lib(self): """ Compatibility function - but library run mode is not available """ raise NotImplementedError( "Library run mode is not implemented for script jobs." ) def collect_logfiles(self): """ Compatibility function - but no log files are being collected """ pass @staticmethod def _executable_command(working_directory, script_path): """ internal function to generate the executable command to either use jupyter or python Args: working_directory (str): working directory of the current job script_path (str): path to the script which should be executed in the working directory Returns: str: executable command """ file_name = os.path.basename(script_path) path = os.path.join(working_directory, file_name) if file_name[-6:] == ".ipynb": return ( "jupyter nbconvert --ExecutePreprocessor.timeout=9999999 --to notebook --execute " + path ) elif file_name[-3:] == ".py": return "python " + path else: raise ValueError("Filename not recognized: ", path) def _executable_activate_mpi(self): """ Internal helper function to switch the executable to MPI mode """ pass @staticmethod def _get_abs_path(path): """ internal function to convert absolute or relative paths to absolute paths, using os.path.normpath, os.path.abspath and os.path.curdir Args: path (str): relative or absolute path Returns: str: absolute path """ return os.path.normpath(os.path.join(os.path.abspath(os.path.curdir), path))
[ "os.path.join", "pyiron_base.generic.datacontainer.DataContainer", "os.path.basename", "os.path.abspath", "pyiron_base.generic.parameters.GenericParameters", "os.path.relpath" ]
[((9158, 9197), 'pyiron_base.generic.datacontainer.DataContainer', 'DataContainer', ([], {'table_name': '"""custom_dict"""'}), "(table_name='custom_dict')\n", (9171, 9197), False, 'from pyiron_base.generic.datacontainer import DataContainer\n'), ((14228, 14257), 'os.path.basename', 'os.path.basename', (['script_path'], {}), '(script_path)\n', (14244, 14257), False, 'import os\n'), ((14273, 14315), 'os.path.join', 'os.path.join', (['working_directory', 'file_name'], {}), '(working_directory, file_name)\n', (14285, 14315), False, 'import os\n'), ((12488, 12523), 'os.path.basename', 'os.path.basename', (['self._script_path'], {}), '(self._script_path)\n', (12504, 12523), False, 'import os\n'), ((13096, 13153), 'os.path.relpath', 'os.path.relpath', (['job.working_directory', 'self.project.path'], {}), '(job.working_directory, self.project.path)\n', (13111, 13153), False, 'import os\n'), ((15192, 15223), 'os.path.abspath', 'os.path.abspath', (['os.path.curdir'], {}), '(os.path.curdir)\n', (15207, 15223), False, 'import os\n'), ((11655, 11698), 'pyiron_base.generic.parameters.GenericParameters', 'GenericParameters', ([], {'table_name': '"""custom_dict"""'}), "(table_name='custom_dict')\n", (11672, 11698), False, 'from pyiron_base.generic.parameters import GenericParameters\n'), ((12612, 12659), 'os.path.join', 'os.path.join', (['self.working_directory', 'file_name'], {}), '(self.working_directory, file_name)\n', (12624, 12659), False, 'import os\n')]
# coding: utf-8 """ Application Manager API Application Manager APIs to control Apache Flink jobs # noqa: E501 OpenAPI spec version: 2.0.1 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from ververica_api_sdk.api_client import ApiClient class SecretValueResourceApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def create_secret_value_using_post(self, namespace, secret_value, **kwargs): # noqa: E501 """Create a secret value # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_secret_value_using_post(namespace, secret_value, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: namespace (required) :param SecretValue secret_value: secretValue (required) :return: SecretValue If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.create_secret_value_using_post_with_http_info(namespace, secret_value, **kwargs) # noqa: E501 else: (data) = self.create_secret_value_using_post_with_http_info(namespace, secret_value, **kwargs) # noqa: E501 return data def create_secret_value_using_post_with_http_info(self, namespace, secret_value, **kwargs): # noqa: E501 """Create a secret value # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_secret_value_using_post_with_http_info(namespace, secret_value, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: namespace (required) :param SecretValue secret_value: secretValue (required) :return: SecretValue If the method is called asynchronously, returns the request thread. """ all_params = ['namespace', 'secret_value'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_secret_value_using_post" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'namespace' is set if ('namespace' not in params or params['namespace'] is None): raise ValueError("Missing the required parameter `namespace` when calling `create_secret_value_using_post`") # noqa: E501 # verify the required parameter 'secret_value' is set if ('secret_value' not in params or params['secret_value'] is None): raise ValueError("Missing the required parameter `secret_value` when calling `create_secret_value_using_post`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in params: path_params['namespace'] = params['namespace'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'secret_value' in params: body_params = params['secret_value'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json', 'application/yaml']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/namespaces/{namespace}/secret-values', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SecretValue', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def delete_secret_value_using_delete(self, name, namespace, **kwargs): # noqa: E501 """Delete a secret value # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_secret_value_using_delete(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name (required) :param str namespace: namespace (required) :return: SecretValue If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_secret_value_using_delete_with_http_info(name, namespace, **kwargs) # noqa: E501 else: (data) = self.delete_secret_value_using_delete_with_http_info(name, namespace, **kwargs) # noqa: E501 return data def delete_secret_value_using_delete_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """Delete a secret value # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_secret_value_using_delete_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name (required) :param str namespace: namespace (required) :return: SecretValue If the method is called asynchronously, returns the request thread. """ all_params = ['name', 'namespace'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method delete_secret_value_using_delete" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params or params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `delete_secret_value_using_delete`") # noqa: E501 # verify the required parameter 'namespace' is set if ('namespace' not in params or params['namespace'] is None): raise ValueError("Missing the required parameter `namespace` when calling `delete_secret_value_using_delete`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] # noqa: E501 if 'namespace' in params: path_params['namespace'] = params['namespace'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json', 'application/yaml']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/namespaces/{namespace}/secret-values/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SecretValue', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_secret_value_using_get(self, name, namespace, **kwargs): # noqa: E501 """Get a secret value by name # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_secret_value_using_get(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name (required) :param str namespace: namespace (required) :return: SecretValue If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_secret_value_using_get_with_http_info(name, namespace, **kwargs) # noqa: E501 else: (data) = self.get_secret_value_using_get_with_http_info(name, namespace, **kwargs) # noqa: E501 return data def get_secret_value_using_get_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """Get a secret value by name # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_secret_value_using_get_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name (required) :param str namespace: namespace (required) :return: SecretValue If the method is called asynchronously, returns the request thread. """ all_params = ['name', 'namespace'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_secret_value_using_get" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params or params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `get_secret_value_using_get`") # noqa: E501 # verify the required parameter 'namespace' is set if ('namespace' not in params or params['namespace'] is None): raise ValueError("Missing the required parameter `namespace` when calling `get_secret_value_using_get`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] # noqa: E501 if 'namespace' in params: path_params['namespace'] = params['namespace'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json', 'application/yaml']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/namespaces/{namespace}/secret-values/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SecretValue', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_secret_values_using_get(self, namespace, **kwargs): # noqa: E501 """List all secrets values # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_secret_values_using_get(namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: namespace (required) :return: ResourceListSecretValue If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_secret_values_using_get_with_http_info(namespace, **kwargs) # noqa: E501 else: (data) = self.get_secret_values_using_get_with_http_info(namespace, **kwargs) # noqa: E501 return data def get_secret_values_using_get_with_http_info(self, namespace, **kwargs): # noqa: E501 """List all secrets values # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_secret_values_using_get_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: namespace (required) :return: ResourceListSecretValue If the method is called asynchronously, returns the request thread. """ all_params = ['namespace'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_secret_values_using_get" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'namespace' is set if ('namespace' not in params or params['namespace'] is None): raise ValueError("Missing the required parameter `namespace` when calling `get_secret_values_using_get`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in params: path_params['namespace'] = params['namespace'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json', 'application/yaml']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/namespaces/{namespace}/secret-values', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ResourceListSecretValue', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_secret_value_using_patch(self, body, name, namespace, **kwargs): # noqa: E501 """Update a secret value # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_secret_value_using_patch(body, name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param ComDataartisansAppmanagerApiV1EntitySecretvalueSecretValue body: (required) :param str name: name (required) :param str namespace: namespace (required) :return: SecretValue If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.update_secret_value_using_patch_with_http_info(body, name, namespace, **kwargs) # noqa: E501 else: (data) = self.update_secret_value_using_patch_with_http_info(body, name, namespace, **kwargs) # noqa: E501 return data def update_secret_value_using_patch_with_http_info(self, body, name, namespace, **kwargs): # noqa: E501 """Update a secret value # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_secret_value_using_patch_with_http_info(body, name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param ComDataartisansAppmanagerApiV1EntitySecretvalueSecretValue body: (required) :param str name: name (required) :param str namespace: namespace (required) :return: SecretValue If the method is called asynchronously, returns the request thread. """ all_params = ['body', 'name', 'namespace'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method update_secret_value_using_patch" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'body' is set if ('body' not in params or params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_secret_value_using_patch`") # noqa: E501 # verify the required parameter 'name' is set if ('name' not in params or params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `update_secret_value_using_patch`") # noqa: E501 # verify the required parameter 'namespace' is set if ('namespace' not in params or params['namespace'] is None): raise ValueError("Missing the required parameter `namespace` when calling `update_secret_value_using_patch`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] # noqa: E501 if 'namespace' in params: path_params['namespace'] = params['namespace'] # noqa: E501 query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json', 'application/yaml']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/v1/namespaces/{namespace}/secret-values/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SecretValue', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
[ "ververica_api_sdk.api_client.ApiClient", "six.iteritems" ]
[((2890, 2921), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (2903, 2921), False, 'import six\n'), ((7308, 7339), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (7321, 7339), False, 'import six\n'), ((11689, 11720), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (11702, 11720), False, 'import six\n'), ((15947, 15978), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (15960, 15978), False, 'import six\n'), ((20211, 20242), 'six.iteritems', 'six.iteritems', (["params['kwargs']"], {}), "(params['kwargs'])\n", (20224, 20242), False, 'import six\n'), ((745, 756), 'ververica_api_sdk.api_client.ApiClient', 'ApiClient', ([], {}), '()\n', (754, 756), False, 'from ververica_api_sdk.api_client import ApiClient\n')]
#py3 """ ========================================================= Comparing different clustering algorithms on toy datasets ========================================================= This example shows characteristics of different clustering algorithms on datasets that are "interesting" but still in 2D. With the exception of the last dataset, the parameters of each of these dataset-algorithm pairs has been tuned to produce good clustering results. Some algorithms are more sensitive to parameter values than others. The last dataset is an example of a 'null' situation for clustering: the data is homogeneous, and there is no good clustering. For this example, the null dataset uses the same parameters as the dataset in the row above it, which represents a mismatch in the parameter values and the data structure. While these examples give some intuition about the algorithms, this intuition might not apply to very high dimensional data. """ print(__doc__) import time import warnings import numpy as np import matplotlib.pyplot as plt from sklearn import cluster, datasets, mixture from sklearn.neighbors import kneighbors_graph from sklearn.preprocessing import StandardScaler from itertools import cycle, islice import raster_sci as raster import matplotlib.patheffects as PathEffects np.random.seed(0) # ============ # Generate datasets. We choose the size big enough to see the scalability # of the algorithms, but not too big to avoid too long running times # ============ n_samples = 1500 noisy_circles = datasets.make_circles(n_samples=n_samples, factor=.5, noise=.05) noisy_moons = datasets.make_moons(n_samples=n_samples, noise=.05) blobs = datasets.make_blobs(n_samples=n_samples, random_state=8) no_structure = np.random.rand(n_samples, 2), None # Anisotropicly distributed data random_state = 170 X, y = datasets.make_blobs(n_samples=n_samples, random_state=random_state) transformation = [[0.6, -0.6], [-0.4, 0.8]] X_aniso = np.dot(X, transformation) aniso = (X_aniso, y) # blobs with varied variances varied = datasets.make_blobs(n_samples=n_samples, cluster_std=[1.0, 2.5, 0.5], random_state=random_state) # ============ # Set up cluster parameters # ============ plt.figure(figsize=(9 * 2 + 3, 12.5)) plt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.96, wspace=.05, hspace=.01) plot_num = 1 default_base = {'quantile': .3, 'eps': .3, 'damping': .9, 'preference': -200, 'n_neighbors': 10, 'n_clusters': 3} datasets = [ (noisy_circles, {'damping': .77, 'preference': -240, 'quantile': .2, 'n_clusters': 2}), (noisy_moons, {'damping': .75, 'preference': -220, 'n_clusters': 2}), (varied, {'eps': .18, 'n_neighbors': 2}), (aniso, {'eps': .15, 'n_neighbors': 2}), (blobs, {}), (no_structure, {})] for i_dataset, (dataset, algo_params) in enumerate(datasets): # update parameters with dataset-specific values params = default_base.copy() params.update(algo_params) X, y = dataset # normalize dataset for easier parameter selection X = StandardScaler().fit_transform(X) # estimate bandwidth for mean shift bandwidth = cluster.estimate_bandwidth(X, quantile=params['quantile']) # connectivity matrix for structured Ward connectivity = kneighbors_graph( X, n_neighbors=params['n_neighbors'], include_self=False) # make connectivity symmetric connectivity = 0.5 * (connectivity + connectivity.T) # ============ # Create cluster objects # ============ ms = cluster.MeanShift(bandwidth=bandwidth, bin_seeding=True) two_means = cluster.MiniBatchKMeans(n_clusters=params['n_clusters']) ward = cluster.AgglomerativeClustering( n_clusters=params['n_clusters'], linkage='ward', connectivity=connectivity) spectral = cluster.SpectralClustering( n_clusters=params['n_clusters'], eigen_solver='arpack', affinity="nearest_neighbors") dbscan = cluster.DBSCAN(eps=params['eps']) affinity_propagation = cluster.AffinityPropagation( damping=params['damping'], preference=params['preference']) average_linkage = cluster.AgglomerativeClustering( linkage="average", affinity="cityblock", n_clusters=params['n_clusters'], connectivity=connectivity) birch = cluster.Birch(n_clusters=params['n_clusters']) gmm = mixture.GaussianMixture( n_components=params['n_clusters'], covariance_type='full') threshold = 5 min_size = 5 rs = raster.Raster(threshold, min_size) clustering_algorithms = ( ('Mini-Batch k-Means', two_means), ('Affinity Propagation', affinity_propagation), ('Mean Shift', ms), ('Spectral', spectral), ('Ward', ward), ('Agglomerative', average_linkage), ('DBSCAN', dbscan), ('BIRCH', birch), ('Gaussian Mixture', gmm), ('RASTER', rs) ) for name, algorithm in clustering_algorithms: t0 = time.time() # catch warnings related to kneighbors_graph with warnings.catch_warnings(): warnings.filterwarnings( "ignore", message="the number of connected components of the " + "connectivity matrix is [0-9]{1,2}" + " > 1. Completing it to avoid stopping the tree early.", category=UserWarning) warnings.filterwarnings( "ignore", message="Graph is not fully connected, spectral embedding" + " may not work as expected.", category=UserWarning) algorithm.fit(X) t1 = time.time() if hasattr(algorithm, 'labels_'): y_pred = algorithm.labels_.astype(np.int) else: y_pred = algorithm.predict(X) plt.subplot(len(datasets), len(clustering_algorithms), plot_num) if i_dataset == 0: plt.title(name, size=11) colors = np.array(list(islice(cycle(['#377eb8', '#ff7f00', '#4daf4a', '#f781bf', '#a65628', '#984ea3', '#999999', '#e41a1c', '#dede00']), int(max(y_pred) + 1)))) # add black color for outliers (if any) colors = np.append(colors, ["#000000"]) plt.scatter(X[:, 0], X[:, 1], s=1, color=colors[y_pred]) plt.xlim(-2.5, 2.5) plt.ylim(-2.5, 2.5) plt.xticks(()) plt.yticks(()) # txt = plt.text(.99, .01, ('%.3fs' % (t1 - t0)).lstrip('0'), txt = plt.text(.98, .02, ('%.3fs' % (t1 - t0)), transform=plt.gca().transAxes, size=9, horizontalalignment='right') txt.set_path_effects([PathEffects.withStroke(linewidth=3, foreground='w')]) plot_num += 1 plt.show()
[ "sklearn.cluster.SpectralClustering", "numpy.random.rand", "sklearn.neighbors.kneighbors_graph", "sklearn.datasets.make_circles", "sklearn.cluster.MeanShift", "matplotlib.patheffects.withStroke", "sklearn.cluster.DBSCAN", "sklearn.cluster.AgglomerativeClustering", "sklearn.datasets.make_blobs", "r...
[((1303, 1320), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1317, 1320), True, 'import numpy as np\n'), ((1528, 1594), 'sklearn.datasets.make_circles', 'datasets.make_circles', ([], {'n_samples': 'n_samples', 'factor': '(0.5)', 'noise': '(0.05)'}), '(n_samples=n_samples, factor=0.5, noise=0.05)\n', (1549, 1594), False, 'from sklearn import cluster, datasets, mixture\n'), ((1645, 1697), 'sklearn.datasets.make_moons', 'datasets.make_moons', ([], {'n_samples': 'n_samples', 'noise': '(0.05)'}), '(n_samples=n_samples, noise=0.05)\n', (1664, 1697), False, 'from sklearn import cluster, datasets, mixture\n'), ((1705, 1761), 'sklearn.datasets.make_blobs', 'datasets.make_blobs', ([], {'n_samples': 'n_samples', 'random_state': '(8)'}), '(n_samples=n_samples, random_state=8)\n', (1724, 1761), False, 'from sklearn import cluster, datasets, mixture\n'), ((1872, 1939), 'sklearn.datasets.make_blobs', 'datasets.make_blobs', ([], {'n_samples': 'n_samples', 'random_state': 'random_state'}), '(n_samples=n_samples, random_state=random_state)\n', (1891, 1939), False, 'from sklearn import cluster, datasets, mixture\n'), ((1994, 2019), 'numpy.dot', 'np.dot', (['X', 'transformation'], {}), '(X, transformation)\n', (2000, 2019), True, 'import numpy as np\n'), ((2081, 2181), 'sklearn.datasets.make_blobs', 'datasets.make_blobs', ([], {'n_samples': 'n_samples', 'cluster_std': '[1.0, 2.5, 0.5]', 'random_state': 'random_state'}), '(n_samples=n_samples, cluster_std=[1.0, 2.5, 0.5],\n random_state=random_state)\n', (2100, 2181), False, 'from sklearn import cluster, datasets, mixture\n'), ((2295, 2332), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9 * 2 + 3, 12.5)'}), '(figsize=(9 * 2 + 3, 12.5))\n', (2305, 2332), True, 'import matplotlib.pyplot as plt\n'), ((2333, 2430), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.02)', 'right': '(0.98)', 'bottom': '(0.001)', 'top': '(0.96)', 'wspace': '(0.05)', 'hspace': '(0.01)'}), '(left=0.02, right=0.98, bottom=0.001, top=0.96, wspace=\n 0.05, hspace=0.01)\n', (2352, 2430), True, 'import matplotlib.pyplot as plt\n'), ((7029, 7039), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7037, 7039), True, 'import matplotlib.pyplot as plt\n'), ((1777, 1805), 'numpy.random.rand', 'np.random.rand', (['n_samples', '(2)'], {}), '(n_samples, 2)\n', (1791, 1805), True, 'import numpy as np\n'), ((3337, 3395), 'sklearn.cluster.estimate_bandwidth', 'cluster.estimate_bandwidth', (['X'], {'quantile': "params['quantile']"}), "(X, quantile=params['quantile'])\n", (3363, 3395), False, 'from sklearn import cluster, datasets, mixture\n'), ((3462, 3536), 'sklearn.neighbors.kneighbors_graph', 'kneighbors_graph', (['X'], {'n_neighbors': "params['n_neighbors']", 'include_self': '(False)'}), "(X, n_neighbors=params['n_neighbors'], include_self=False)\n", (3478, 3536), False, 'from sklearn.neighbors import kneighbors_graph\n'), ((3714, 3770), 'sklearn.cluster.MeanShift', 'cluster.MeanShift', ([], {'bandwidth': 'bandwidth', 'bin_seeding': '(True)'}), '(bandwidth=bandwidth, bin_seeding=True)\n', (3731, 3770), False, 'from sklearn import cluster, datasets, mixture\n'), ((3787, 3843), 'sklearn.cluster.MiniBatchKMeans', 'cluster.MiniBatchKMeans', ([], {'n_clusters': "params['n_clusters']"}), "(n_clusters=params['n_clusters'])\n", (3810, 3843), False, 'from sklearn import cluster, datasets, mixture\n'), ((3855, 3967), 'sklearn.cluster.AgglomerativeClustering', 'cluster.AgglomerativeClustering', ([], {'n_clusters': "params['n_clusters']", 'linkage': '"""ward"""', 'connectivity': 'connectivity'}), "(n_clusters=params['n_clusters'], linkage=\n 'ward', connectivity=connectivity)\n", (3886, 3967), False, 'from sklearn import cluster, datasets, mixture\n'), ((3995, 4112), 'sklearn.cluster.SpectralClustering', 'cluster.SpectralClustering', ([], {'n_clusters': "params['n_clusters']", 'eigen_solver': '"""arpack"""', 'affinity': '"""nearest_neighbors"""'}), "(n_clusters=params['n_clusters'], eigen_solver=\n 'arpack', affinity='nearest_neighbors')\n", (4021, 4112), False, 'from sklearn import cluster, datasets, mixture\n'), ((4138, 4171), 'sklearn.cluster.DBSCAN', 'cluster.DBSCAN', ([], {'eps': "params['eps']"}), "(eps=params['eps'])\n", (4152, 4171), False, 'from sklearn import cluster, datasets, mixture\n'), ((4199, 4291), 'sklearn.cluster.AffinityPropagation', 'cluster.AffinityPropagation', ([], {'damping': "params['damping']", 'preference': "params['preference']"}), "(damping=params['damping'], preference=params[\n 'preference'])\n", (4226, 4291), False, 'from sklearn import cluster, datasets, mixture\n'), ((4318, 4454), 'sklearn.cluster.AgglomerativeClustering', 'cluster.AgglomerativeClustering', ([], {'linkage': '"""average"""', 'affinity': '"""cityblock"""', 'n_clusters': "params['n_clusters']", 'connectivity': 'connectivity'}), "(linkage='average', affinity='cityblock',\n n_clusters=params['n_clusters'], connectivity=connectivity)\n", (4349, 4454), False, 'from sklearn import cluster, datasets, mixture\n'), ((4480, 4526), 'sklearn.cluster.Birch', 'cluster.Birch', ([], {'n_clusters': "params['n_clusters']"}), "(n_clusters=params['n_clusters'])\n", (4493, 4526), False, 'from sklearn import cluster, datasets, mixture\n'), ((4537, 4624), 'sklearn.mixture.GaussianMixture', 'mixture.GaussianMixture', ([], {'n_components': "params['n_clusters']", 'covariance_type': '"""full"""'}), "(n_components=params['n_clusters'], covariance_type=\n 'full')\n", (4560, 4624), False, 'from sklearn import cluster, datasets, mixture\n'), ((4682, 4716), 'raster_sci.Raster', 'raster.Raster', (['threshold', 'min_size'], {}), '(threshold, min_size)\n', (4695, 4716), True, 'import raster_sci as raster\n'), ((5157, 5168), 'time.time', 'time.time', ([], {}), '()\n', (5166, 5168), False, 'import time\n'), ((5829, 5840), 'time.time', 'time.time', ([], {}), '()\n', (5838, 5840), False, 'import time\n'), ((6495, 6525), 'numpy.append', 'np.append', (['colors', "['#000000']"], {}), "(colors, ['#000000'])\n", (6504, 6525), True, 'import numpy as np\n'), ((6534, 6590), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X[:, 0]', 'X[:, 1]'], {'s': '(1)', 'color': 'colors[y_pred]'}), '(X[:, 0], X[:, 1], s=1, color=colors[y_pred])\n', (6545, 6590), True, 'import matplotlib.pyplot as plt\n'), ((6600, 6619), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(-2.5)', '(2.5)'], {}), '(-2.5, 2.5)\n', (6608, 6619), True, 'import matplotlib.pyplot as plt\n'), ((6628, 6647), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-2.5)', '(2.5)'], {}), '(-2.5, 2.5)\n', (6636, 6647), True, 'import matplotlib.pyplot as plt\n'), ((6656, 6670), 'matplotlib.pyplot.xticks', 'plt.xticks', (['()'], {}), '(())\n', (6666, 6670), True, 'import matplotlib.pyplot as plt\n'), ((6679, 6693), 'matplotlib.pyplot.yticks', 'plt.yticks', (['()'], {}), '(())\n', (6689, 6693), True, 'import matplotlib.pyplot as plt\n'), ((3246, 3262), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (3260, 3262), False, 'from sklearn.preprocessing import StandardScaler\n'), ((5236, 5261), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (5259, 5261), False, 'import warnings\n'), ((5275, 5498), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': "('the number of connected components of the ' +\n 'connectivity matrix is [0-9]{1,2}' +\n ' > 1. Completing it to avoid stopping the tree early.')", 'category': 'UserWarning'}), "('ignore', message=\n 'the number of connected components of the ' +\n 'connectivity matrix is [0-9]{1,2}' +\n ' > 1. Completing it to avoid stopping the tree early.', category=\n UserWarning)\n", (5298, 5498), False, 'import warnings\n'), ((5574, 5729), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': "('Graph is not fully connected, spectral embedding' +\n ' may not work as expected.')", 'category': 'UserWarning'}), "('ignore', message=\n 'Graph is not fully connected, spectral embedding' +\n ' may not work as expected.', category=UserWarning)\n", (5597, 5729), False, 'import warnings\n'), ((6106, 6130), 'matplotlib.pyplot.title', 'plt.title', (['name'], {'size': '(11)'}), '(name, size=11)\n', (6115, 6130), True, 'import matplotlib.pyplot as plt\n'), ((6951, 7002), 'matplotlib.patheffects.withStroke', 'PathEffects.withStroke', ([], {'linewidth': '(3)', 'foreground': '"""w"""'}), "(linewidth=3, foreground='w')\n", (6973, 7002), True, 'import matplotlib.patheffects as PathEffects\n'), ((6170, 6280), 'itertools.cycle', 'cycle', (["['#377eb8', '#ff7f00', '#4daf4a', '#f781bf', '#a65628', '#984ea3',\n '#999999', '#e41a1c', '#dede00']"], {}), "(['#377eb8', '#ff7f00', '#4daf4a', '#f781bf', '#a65628', '#984ea3',\n '#999999', '#e41a1c', '#dede00'])\n", (6175, 6280), False, 'from itertools import cycle, islice\n'), ((6846, 6855), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (6853, 6855), True, 'import matplotlib.pyplot as plt\n')]
import os.path as osp from .builder import DATASETS from .custom import CustomDataset @DATASETS.register_module() class MaSTr1325(CustomDataset): """PascalContext dataset. In segmentation map annotation for PascalContext, 0 stands for background, which is included in 60 categories. ``reduce_zero_label`` is fixed to False. The ``img_suffix`` is fixed to '.jpg' and ``seg_map_suffix`` is fixed to '.png'. Args: split (str): Split txt file for PascalContext. """ CLASSES = ('land','water','sky') PALETTE = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0]] def __init__(self, split, **kwargs): super(MaSTr1325, self).__init__( img_suffix='.jpg', seg_map_suffix='.png', split=split, reduce_zero_label=False, #att_metrics=['PRE', 'REC', 'F-measure', 'F-max', 'FPR', 'FNR'], **kwargs) assert osp.exists(self.img_dir) and self.split is not None
[ "os.path.exists" ]
[((934, 958), 'os.path.exists', 'osp.exists', (['self.img_dir'], {}), '(self.img_dir)\n', (944, 958), True, 'import os.path as osp\n')]
from django.conf import settings from django.http import HttpResponse from django.views.decorators.cache import never_cache from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import get_object_or_404, render from models import Pelicula, ObraTeatro, Evento, Cine, CategoriaEvento, LiveEmbedEvent, ArchivedEvent @never_cache @staff_member_required def index(request): secciones = CategoriaEvento.objects.order_by('order') return render(request, 'cartelera/index.html', {'secciones': secciones}) @never_cache @staff_member_required def cine(request, slug): cine = get_object_or_404(Cine, slug=slug) return render(request, 'cartelera/cine.html', {'cine': cine}) @never_cache @staff_member_required def pelicula(request, slug): pelicula = get_object_or_404(Pelicula, slug=slug) return render(request, 'cartelera/pelicula.html', {'pelicula': pelicula}) @never_cache @staff_member_required def obrateatro(request, slug): obrateatro = get_object_or_404(ObraTeatro, slug=slug) return render(request, 'cartelera/obrateatro.html', {'obrateatro': obrateatro}) @never_cache @staff_member_required def evento(request, slug): """ TODO: This app is very old, has broken parts, should be fixed and merged with the app "comunidad" (both have similar purposes). Only the next "vivo" features are new. For example, here in this view, we had to treat the "evento" as a "pelicula" because we don't know why the evento.html template is missing. """ evento = get_object_or_404(Evento, slug=slug) return render(request, 'cartelera/pelicula.html', {'pelicula': evento}) @never_cache def vivo(request, archived_event_id=None): context = { 'logo_template': getattr(settings, 'CARTELERA_EVENTS_LOGO_TEMPLATE', None), 'resume_template': getattr(settings, 'CARTELERA_EVENTS_RESUME_TEMPLATE', 'core/templates/edition/resume.html')} if archived_event_id: context.update({'event': get_object_or_404(ArchivedEvent, id=archived_event_id), 'is_detail': True}) return render(request, 'cartelera/vivo_archive.html', context) try: active_event = LiveEmbedEvent.objects.get(active=True) except LiveEmbedEvent.DoesNotExist: active_event = None context.update({'event': active_event, 'is_detail': True}) return render(request, 'cartelera/vivo.html', context) @never_cache def notification_closed(request, live_embed_event_id): closed = request.session.get( 'live_embed_events_notifications_closed', set()) closed.add(int(live_embed_event_id)) request.session['live_embed_events_notifications_closed'] = closed return HttpResponse() @never_cache @staff_member_required def categoria(request, slug): categoria = get_object_or_404(CategoriaEvento, slug=slug) return render(request, 'cartelera/categoria.html', {'categoria': categoria})
[ "django.shortcuts.render", "models.LiveEmbedEvent.objects.get", "django.http.HttpResponse", "django.shortcuts.get_object_or_404", "models.CategoriaEvento.objects.order_by" ]
[((428, 469), 'models.CategoriaEvento.objects.order_by', 'CategoriaEvento.objects.order_by', (['"""order"""'], {}), "('order')\n", (460, 469), False, 'from models import Pelicula, ObraTeatro, Evento, Cine, CategoriaEvento, LiveEmbedEvent, ArchivedEvent\n'), ((481, 546), 'django.shortcuts.render', 'render', (['request', '"""cartelera/index.html"""', "{'secciones': secciones}"], {}), "(request, 'cartelera/index.html', {'secciones': secciones})\n", (487, 546), False, 'from django.shortcuts import get_object_or_404, render\n'), ((621, 655), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Cine'], {'slug': 'slug'}), '(Cine, slug=slug)\n', (638, 655), False, 'from django.shortcuts import get_object_or_404, render\n'), ((667, 721), 'django.shortcuts.render', 'render', (['request', '"""cartelera/cine.html"""', "{'cine': cine}"], {}), "(request, 'cartelera/cine.html', {'cine': cine})\n", (673, 721), False, 'from django.shortcuts import get_object_or_404, render\n'), ((804, 842), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Pelicula'], {'slug': 'slug'}), '(Pelicula, slug=slug)\n', (821, 842), False, 'from django.shortcuts import get_object_or_404, render\n'), ((854, 920), 'django.shortcuts.render', 'render', (['request', '"""cartelera/pelicula.html"""', "{'pelicula': pelicula}"], {}), "(request, 'cartelera/pelicula.html', {'pelicula': pelicula})\n", (860, 920), False, 'from django.shortcuts import get_object_or_404, render\n'), ((1007, 1047), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['ObraTeatro'], {'slug': 'slug'}), '(ObraTeatro, slug=slug)\n', (1024, 1047), False, 'from django.shortcuts import get_object_or_404, render\n'), ((1059, 1131), 'django.shortcuts.render', 'render', (['request', '"""cartelera/obrateatro.html"""', "{'obrateatro': obrateatro}"], {}), "(request, 'cartelera/obrateatro.html', {'obrateatro': obrateatro})\n", (1065, 1131), False, 'from django.shortcuts import get_object_or_404, render\n'), ((1567, 1603), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Evento'], {'slug': 'slug'}), '(Evento, slug=slug)\n', (1584, 1603), False, 'from django.shortcuts import get_object_or_404, render\n'), ((1615, 1679), 'django.shortcuts.render', 'render', (['request', '"""cartelera/pelicula.html"""', "{'pelicula': evento}"], {}), "(request, 'cartelera/pelicula.html', {'pelicula': evento})\n", (1621, 1679), False, 'from django.shortcuts import get_object_or_404, render\n'), ((2378, 2425), 'django.shortcuts.render', 'render', (['request', '"""cartelera/vivo.html"""', 'context'], {}), "(request, 'cartelera/vivo.html', context)\n", (2384, 2425), False, 'from django.shortcuts import get_object_or_404, render\n'), ((2710, 2724), 'django.http.HttpResponse', 'HttpResponse', ([], {}), '()\n', (2722, 2724), False, 'from django.http import HttpResponse\n'), ((2809, 2854), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['CategoriaEvento'], {'slug': 'slug'}), '(CategoriaEvento, slug=slug)\n', (2826, 2854), False, 'from django.shortcuts import get_object_or_404, render\n'), ((2866, 2935), 'django.shortcuts.render', 'render', (['request', '"""cartelera/categoria.html"""', "{'categoria': categoria}"], {}), "(request, 'cartelera/categoria.html', {'categoria': categoria})\n", (2872, 2935), False, 'from django.shortcuts import get_object_or_404, render\n'), ((2108, 2163), 'django.shortcuts.render', 'render', (['request', '"""cartelera/vivo_archive.html"""', 'context'], {}), "(request, 'cartelera/vivo_archive.html', context)\n", (2114, 2163), False, 'from django.shortcuts import get_object_or_404, render\n'), ((2196, 2235), 'models.LiveEmbedEvent.objects.get', 'LiveEmbedEvent.objects.get', ([], {'active': '(True)'}), '(active=True)\n', (2222, 2235), False, 'from models import Pelicula, ObraTeatro, Evento, Cine, CategoriaEvento, LiveEmbedEvent, ArchivedEvent\n'), ((2017, 2071), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['ArchivedEvent'], {'id': 'archived_event_id'}), '(ArchivedEvent, id=archived_event_id)\n', (2034, 2071), False, 'from django.shortcuts import get_object_or_404, render\n')]
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from collections import deque from collections import namedtuple # obervations structure observation = namedtuple( 'observation', ['time', 'qpos_robot', 'qvel_robot', 'qpos_object', 'qvel_object']) class Robot(object): def __init__(self, n_jnt, n_obj, n_dofs, pos_bounds=None, vel_bounds=None, **kwargs): self.n_jnt = n_jnt self.n_obj = n_obj self.n_dofs = n_dofs self.has_obj = False if self.n_obj>0: self.has_obj = True # Cache that gets updated self.observation_cache_maxsize = 5 self.observation_cache = deque([], maxlen=self.observation_cache_maxsize) # Pos and vel bounds self.pos_bounds = None if pos_bounds is not None: pos_bounds = np.array(pos_bounds, dtype=np.float32) assert pos_bounds.shape == (self.n_dofs, 2) for low, high in pos_bounds: assert low < high self.pos_bounds = pos_bounds self.vel_bounds = None if vel_bounds is not None: vel_bounds = np.array(vel_bounds, dtype=np.float32) assert vel_bounds.shape == (self.n_dofs, 2) for low, high in vel_bounds: assert low < high self.vel_bounds = vel_bounds # refresh the observation cache def _observation_cache_refresh(self, env): for _ in range(self.observation_cache_maxsize): self.get_obs(env, robot_noise_ratio=0, object_noise_ratio=0) # get past observation def get_obs_from_cache(self, env, index=-1): assert (index>=0 and index<self.observation_cache_maxsize) or \ (index<0 and index>=-self.observation_cache_maxsize), \ "cache index out of bound. (cache size is %2d)"%self.observation_cache_maxsize obs = self.observation_cache[index] if self.has_obj: return obs.time, obs.qpos_robot, obs.qvel_robot, obs.qpos_object, obs.qvel_object else: return obs.time, obs.qpos_robot, obs.qvel_robot # get observation def get_obs(self, env, robot_noise_ratio=0.05, object_noise_ratio=0.05): qp = env.sim.data.qpos[:self.n_jnt].ravel() qv = env.sim.data.qvel[:self.n_jnt].ravel() if self.has_obj: qp_obj = env.sim.data.qpos[-self.n_obj:].ravel() qv_obj = env.sim.data.qvel[-self.n_obj:].ravel() else: qp_obj = None qv_obj = None self.time = env.sim.data.time # Simulate observation noise if not env.initializing: noise_amp = robot_noise_ratio*(env.model.jnt_range[:self.n_jnt,1]-env.model.jnt_range[:self.n_jnt,0]) qp += noise_amp*env.np_random.uniform(low=-.5, high=.5, size=self.n_jnt) qv += noise_amp*env.np_random.uniform(low=-.5, high=.5, size=self.n_jnt) if self.has_obj: noise_amp = object_noise_ratio*(env.model.jnt_range[-self.n_obj:,1]-env.model.jnt_range[-self.n_obj:,0]) qp_obj += noise_amp*env.np_random.uniform(low=-.5, high=.5, size=self.n_obj) qv_obj += noise_amp*env.np_random.uniform(low=-.5, high=.5, size=self.n_obj) # cache observations obs = observation( time=self.time, qpos_robot=qp, qvel_robot=qv, qpos_object=qp_obj, qvel_object=qv_obj) self.observation_cache.append(obs) if self.has_obj: return obs.time, obs.qpos_robot, obs.qvel_robot, obs.qpos_object, obs.qvel_object else: return obs.time, obs.qpos_robot, obs.qvel_robot # clip only joint position limits # since we can only control those anyway def ctrl_position_limits(self, ctrl_position): ctrl_feasible_position = np.clip(ctrl_position, self.pos_bounds[:self.n_jnt, 0], self.pos_bounds[:self.n_jnt, 1]) return ctrl_feasible_position # enforce velocity limits. def enforce_velocity_limits(self, ctrl_position, step_duration): last_obs = self.observation_cache[-1] desired_vel = (ctrl_position[:self.n_jnt] - last_obs.qpos_robot[:self.n_jnt])/step_duration feasible_vel = np.clip(desired_vel, self.vel_bounds[:self.n_jnt, 0], self.vel_bounds[:self.n_jnt, 1]) feasible_position = last_obs.qpos_robot + feasible_vel*step_duration return feasible_position # step the robot env def step(self, env, ctrl_desired, step_duration): # Populate observation cache during startup if env.initializing: self._observation_cache_refresh(env) # enforce velocity limits ctrl_feasible = self.enforce_velocity_limits(ctrl_desired, step_duration) # enforce position limits ctrl_feasible = self.ctrl_position_limits(ctrl_feasible) # Send controls to the robot env.do_simulation(ctrl_feasible, int(step_duration/env.sim.model.opt.timestep)) # render is folded in here return 1 # clip the whole thing def clip_positions(self, positions): assert len(positions) == self.n_jnt or len(positions) == self.n_dofs pos_bounds = self.pos_bounds[:len(positions)] return np.clip(positions, pos_bounds[:, 0], pos_bounds[:, 1]) def reset(self, env, reset_pose, reset_vel): reset_pose = self.clip_positions(reset_pose) # env.sim.reset() env.sim.data.qpos[:self.n_jnt] = reset_pose[:self.n_jnt].copy() env.sim.data.qvel[:self.n_jnt] = reset_vel[:self.n_jnt].copy() if self.has_obj: env.sim.data.qpos[-self.n_obj:] = reset_pose[-self.n_obj:].copy() env.sim.data.qvel[-self.n_obj:] = reset_vel[-self.n_obj:].copy() env.sim.forward() # refresh observation cache before exit self._observation_cache_refresh(env)
[ "numpy.clip", "numpy.array", "collections.namedtuple", "collections.deque" ]
[((699, 796), 'collections.namedtuple', 'namedtuple', (['"""observation"""', "['time', 'qpos_robot', 'qvel_robot', 'qpos_object', 'qvel_object']"], {}), "('observation', ['time', 'qpos_robot', 'qvel_robot',\n 'qpos_object', 'qvel_object'])\n", (709, 796), False, 'from collections import namedtuple\n'), ((1198, 1246), 'collections.deque', 'deque', (['[]'], {'maxlen': 'self.observation_cache_maxsize'}), '([], maxlen=self.observation_cache_maxsize)\n', (1203, 1246), False, 'from collections import deque\n'), ((4402, 4495), 'numpy.clip', 'np.clip', (['ctrl_position', 'self.pos_bounds[:self.n_jnt, 0]', 'self.pos_bounds[:self.n_jnt, 1]'], {}), '(ctrl_position, self.pos_bounds[:self.n_jnt, 0], self.pos_bounds[:\n self.n_jnt, 1])\n', (4409, 4495), True, 'import numpy as np\n'), ((4882, 4973), 'numpy.clip', 'np.clip', (['desired_vel', 'self.vel_bounds[:self.n_jnt, 0]', 'self.vel_bounds[:self.n_jnt, 1]'], {}), '(desired_vel, self.vel_bounds[:self.n_jnt, 0], self.vel_bounds[:self\n .n_jnt, 1])\n', (4889, 4973), True, 'import numpy as np\n'), ((5894, 5948), 'numpy.clip', 'np.clip', (['positions', 'pos_bounds[:, 0]', 'pos_bounds[:, 1]'], {}), '(positions, pos_bounds[:, 0], pos_bounds[:, 1])\n', (5901, 5948), True, 'import numpy as np\n'), ((1368, 1406), 'numpy.array', 'np.array', (['pos_bounds'], {'dtype': 'np.float32'}), '(pos_bounds, dtype=np.float32)\n', (1376, 1406), True, 'import numpy as np\n'), ((1670, 1708), 'numpy.array', 'np.array', (['vel_bounds'], {'dtype': 'np.float32'}), '(vel_bounds, dtype=np.float32)\n', (1678, 1708), True, 'import numpy as np\n')]
"""The main engine for CHIRP. Enumerates and runs the relevant plugin coroutines.""" # Standard Python Libraries import asyncio import os from typing import Callable, Dict, Iterable, Iterator, List # cisagov Libraries from chirp import load from chirp.common import CRITICAL, DEBUG, ERROR, OUTPUT_DIR, PLUGINS from chirp.plugins import events, loader, network, registry, yara # noqa: F401 def run() -> None: """Run plugins and write out output.""" if not os.path.exists(OUTPUT_DIR): os.mkdir(OUTPUT_DIR) loaded_plugins = loader.load(PLUGINS) run_plugins(loaded_plugins) def run_plugins(plugins: Dict[str, Callable]) -> None: """Call our async method. :param plugins: A dictionary with the name of a plugin as the key and its entrypoint as the value. :type plugins: Dict[str, Callable] """ _loop = asyncio.get_event_loop() _loop.run_until_complete(_run_coroutines(plugins)) async def _run_coroutines(plugins: Dict[str, Callable]) -> None: """Run our plugin coroutines. :param plugins: A dictionary with the name of a plugin as the key and its entrypoint as the value. :type plugins: Dict[str, Callable] """ _indicators = list( check_valid_indicator_types( load.from_yaml(get_indicators()), list(plugins.keys()) ) ) await asyncio.gather( *[ entrypoint( [ indicator for indicator in _indicators if indicator["ioc_type"] == plugin ] ) for plugin, entrypoint in plugins.items() ] # Run entrypoint for each plugin, passing indicators for that plugin ) def check_valid_indicator_types( indicator_generator: Iterable[dict], plugins: List[str] ) -> Iterator[dict]: """Check that an indicator file has a matching plugin and if so yields the indicator. :param indicator_generator: A generator to yield parsed indicator files. :type indicator_generator: Iterable[dict] :param plugins: Names of valid plugins. :type plugins: List[str] :yield: Valid parsed indicators. :rtype: Iterator[dict] """ failed_types = [] for indicator in indicator_generator: if indicator["ioc_type"] in plugins: yield indicator DEBUG("Loaded {}".format(indicator["name"])) else: if (indicator["ioc_type"] in plugins or "all" in plugins) and indicator[ "ioc_type" ] not in failed_types: ERROR( """Can't locate plugin "{}". It is possible it has not loaded due to an error.""".format( indicator["ioc_type"] ) ) failed_types.append(indicator["ioc_type"]) continue def get_indicators() -> Iterator[str]: """Yield paths to indicators. :yield: A path to an indicator file. :rtype: Iterator[str] """ try: for f in os.listdir("indicators"): if "README" not in f and f.split(".")[-1] in ("yaml", "yml"): yield os.path.join("indicators", f) except FileNotFoundError: CRITICAL( "Could not find an indicators directory. Indicators should be in the same directory as this executable." )
[ "os.path.exists", "os.listdir", "os.path.join", "os.mkdir", "chirp.plugins.loader.load", "chirp.common.CRITICAL", "asyncio.get_event_loop" ]
[((546, 566), 'chirp.plugins.loader.load', 'loader.load', (['PLUGINS'], {}), '(PLUGINS)\n', (557, 566), False, 'from chirp.plugins import events, loader, network, registry, yara\n'), ((849, 873), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (871, 873), False, 'import asyncio\n'), ((468, 494), 'os.path.exists', 'os.path.exists', (['OUTPUT_DIR'], {}), '(OUTPUT_DIR)\n', (482, 494), False, 'import os\n'), ((504, 524), 'os.mkdir', 'os.mkdir', (['OUTPUT_DIR'], {}), '(OUTPUT_DIR)\n', (512, 524), False, 'import os\n'), ((3012, 3036), 'os.listdir', 'os.listdir', (['"""indicators"""'], {}), "('indicators')\n", (3022, 3036), False, 'import os\n'), ((3202, 3326), 'chirp.common.CRITICAL', 'CRITICAL', (['"""Could not find an indicators directory. Indicators should be in the same directory as this executable."""'], {}), "(\n 'Could not find an indicators directory. Indicators should be in the same directory as this executable.'\n )\n", (3210, 3326), False, 'from chirp.common import CRITICAL, DEBUG, ERROR, OUTPUT_DIR, PLUGINS\n'), ((3134, 3163), 'os.path.join', 'os.path.join', (['"""indicators"""', 'f'], {}), "('indicators', f)\n", (3146, 3163), False, 'import os\n')]
import re from marrow.schema.testing import ValidationTest from marrow.schema.validate.base import AlwaysRequired, Instance, Length, falsy, truthy, Concern from marrow.schema.validate.compound import All, Any, Compound, Iterable, Mapping, Pipe length = Length(slice(1, 21)) class CompoundSample(Compound): bar = AlwaysRequired() foo = Instance(str) class SampleAny(Any, CompoundSample): pass class SampleAll(All, CompoundSample): pass class SamplePipe(Pipe, CompoundSample): pass def test_compound_iteration(): sample = CompoundSample((length, )) assert list(sample._validators) == [sample.bar, sample.foo, length] class TestAny(ValidationTest): validator = SampleAny((length, )).validate valid = ('', True, 'Foo') invalid = ([], ) def test_total_failure(self): try: self.validator([]) except Concern as e: assert len(e.concerns) == 3 else: assert False, "Failed to raise a Concern." class TestAll(ValidationTest): validator = SampleAll((length, )).validate valid = ('Testing.', ) invalid = (True, ' ' * 21, ['foo']) def test_total_failure(self): try: self.validator([]) except Concern as e: assert not e.concerns, "Must give up on first failure." else: assert False, "Failed to raise a Concern." class TestPipe(ValidationTest): validator = SamplePipe((length, )).validate valid = TestAll.valid invalid = TestAll.invalid def _do(self, value, expect): try: self.validator(value) except Concern as e: assert len(e.concerns) == expect # Should collect the failures. else: assert False, "Failed to raise a Concern." def test_nested_concerns(self): for i, j in ((True, 2), (' ' * 21, 1), (('foo', ) * 21, 2), (['foo'], 1)): self._do(i, j) # For validation of iterables. INVALID = (None, 1, True) EMPTY = (tuple(), list(), dict(), "") STRINGS = (('a', 'b'), ['a', 'b'], {'a': "one", 'b': "two"}, set(['a', 'b']), "foo") INTEGERS = ((0, 1, 2), [0, 1, 2], {0: 0, 1: 1, 2: 2}, set([0, 1, 2])) TRUTHY = ((1, True, 'foo'), [1, True, 'foo'], {'a': 1, 'b': True, 1: 'foo'}, set([1, True, 'foo'])) FALSY = ((0, False, ''), [0, False, ''], {None: 0, '': False, 0: ''}, set([0, False, ''])) NONMAP = (tuple(), list(), "") class TestIterable(ValidationTest): validator = Iterable().validate valid = EMPTY + STRINGS + INTEGERS + TRUTHY + FALSY invalid = INVALID class TestTruthyIterable(ValidationTest): validator = Iterable([truthy]).validate valid = EMPTY + TRUTHY + STRINGS invalid = INVALID + FALSY + INTEGERS class TestFalsyIterable(ValidationTest): validator = Iterable([falsy]).validate valid = EMPTY + FALSY invalid = INVALID + TRUTHY class TestStringyIterable(ValidationTest): class Validator(Iterable): stringy = Instance(str) validator = Validator().validate valid = EMPTY + STRINGS invalid = INVALID + INTEGERS + TRUTHY + FALSY class TestIterableConcerns(object): def test_singular_failure(self): try: Iterable([truthy]).validate([True, False]) except Concern as e: assert "Element 1" in e.message, "Should identify element failing validation." assert not e.concerns, "Should not contain child concerns." def test_multiple_failure(self): try: Iterable([truthy]).validate([0, False]) except Concern as e: assert "multiple" in e.message.lower(), "Should indicate multiple failures." assert "Element 1" in e.concerns[1].message, "Should identify element failing validation." class TestMapping(ValidationTest): validator = Mapping([Instance(str)]).validate valid = ({}, {1: 'foo', 2: 'bar'}) invalid = INVALID + NONMAP + ({1: 2, 2: 'baz'}, ) class TestMappingConcerns(object): def test_singular_failure(self): try: Mapping([truthy]).validate({'bob': True, 'dole': False}) except Concern as e: assert "dole" in e.message, "Should identify element failing validation." assert not e.concerns, "Should not contain child concerns." def test_multiple_failure(self): try: Mapping([truthy]).validate({'bob': False, 'dole': False}) except Concern as e: assert "multiple" in e.message.lower(), "Should indicate multiple failures." assert "dole" in e.concerns[0].message or "dole" in e.concerns[1].message, "Should identify element failing validation."
[ "marrow.schema.validate.compound.Mapping", "marrow.schema.validate.compound.Iterable", "marrow.schema.validate.base.Instance", "marrow.schema.validate.base.AlwaysRequired" ]
[((318, 334), 'marrow.schema.validate.base.AlwaysRequired', 'AlwaysRequired', ([], {}), '()\n', (332, 334), False, 'from marrow.schema.validate.base import AlwaysRequired, Instance, Length, falsy, truthy, Concern\n'), ((342, 355), 'marrow.schema.validate.base.Instance', 'Instance', (['str'], {}), '(str)\n', (350, 355), False, 'from marrow.schema.validate.base import AlwaysRequired, Instance, Length, falsy, truthy, Concern\n'), ((2260, 2270), 'marrow.schema.validate.compound.Iterable', 'Iterable', ([], {}), '()\n', (2268, 2270), False, 'from marrow.schema.validate.compound import All, Any, Compound, Iterable, Mapping, Pipe\n'), ((2409, 2427), 'marrow.schema.validate.compound.Iterable', 'Iterable', (['[truthy]'], {}), '([truthy])\n', (2417, 2427), False, 'from marrow.schema.validate.compound import All, Any, Compound, Iterable, Mapping, Pipe\n'), ((2565, 2582), 'marrow.schema.validate.compound.Iterable', 'Iterable', (['[falsy]'], {}), '([falsy])\n', (2573, 2582), False, 'from marrow.schema.validate.compound import All, Any, Compound, Iterable, Mapping, Pipe\n'), ((2728, 2741), 'marrow.schema.validate.base.Instance', 'Instance', (['str'], {}), '(str)\n', (2736, 2741), False, 'from marrow.schema.validate.base import AlwaysRequired, Instance, Length, falsy, truthy, Concern\n'), ((3485, 3498), 'marrow.schema.validate.base.Instance', 'Instance', (['str'], {}), '(str)\n', (3493, 3498), False, 'from marrow.schema.validate.base import AlwaysRequired, Instance, Length, falsy, truthy, Concern\n'), ((2932, 2950), 'marrow.schema.validate.compound.Iterable', 'Iterable', (['[truthy]'], {}), '([truthy])\n', (2940, 2950), False, 'from marrow.schema.validate.compound import All, Any, Compound, Iterable, Mapping, Pipe\n'), ((3189, 3207), 'marrow.schema.validate.compound.Iterable', 'Iterable', (['[truthy]'], {}), '([truthy])\n', (3197, 3207), False, 'from marrow.schema.validate.compound import All, Any, Compound, Iterable, Mapping, Pipe\n'), ((3678, 3695), 'marrow.schema.validate.compound.Mapping', 'Mapping', (['[truthy]'], {}), '([truthy])\n', (3685, 3695), False, 'from marrow.schema.validate.compound import All, Any, Compound, Iterable, Mapping, Pipe\n'), ((3944, 3961), 'marrow.schema.validate.compound.Mapping', 'Mapping', (['[truthy]'], {}), '([truthy])\n', (3951, 3961), False, 'from marrow.schema.validate.compound import All, Any, Compound, Iterable, Mapping, Pipe\n')]
import numpy as np import pandas as pd from sklearn.base import TransformerMixin, ClassifierMixin from suricate.preutils import concatixnames, createmultiindex, addsuffix # THIS SHOULD BE OBSOLETE class PipeDfClf(ClassifierMixin): def __init__(self, transformer, classifier, ixname='ix', source_suffix='source', target_suffix='target', **kwargs): """ Args: transformer (TransformerMixin): Transformer --> CLF classifier (ClassifierMixin): ixname (str): source_suffix (str): target_suffix (str): n_jobs (int): pruning_ths (float): return only the pairs which have a score greater than the store_ths """ ClassifierMixin.__init__(self) self.ixname = ixname self.source_suffix = source_suffix self.target_suffix = target_suffix self.ixnamesource, self.ixnametarget, self.ixnamepairs = concatixnames( ixname=self.ixname, source_suffix=self.source_suffix, target_suffix=self.target_suffix ) self.fitted = False self.transformer = transformer self.classifier = classifier pass def fit(self, X, y): """ Fit the transformer Args: X (list): list of [df_source, df_target] y (pd.Series): pairs {['ix_source', 'ix_target']: y_true} Returns: self """ X_score = self.transformer.fit_transform(X=X, y=None) X_slice, y_slice, ix_slice = self.slice(X=X, X_score=X_score, y=y) self.classifier.fit(X=pd.DataFrame(X_slice, index=ix_slice), y=pd.Series(y_slice, index=ix_slice)) return self def slice(self, X, X_score, y=None): """ Transform X_score, output of X through the score, into X_slice, sliced according to y_true (pd.Series) X [df_source, df_target] -[scorer]-> X_score -[reindex]-> X_score.loc[y_true.index] Into Args: X (list) : is a list containing (df_source, df_target) X_score (np.ndarray): X is a numpy.ndarray which is a cartesian product of df_source and df_target y (pd.Series/np.ndarray): y is either: / - pd.Series containing the supervised scores: pairs {['ix_source', 'ix_target']: y_true} which can be a slice of x - numpy.ndarray of [0,1 ,0 ,1 ...] which must be same length as x - None --> return X Returns: np.ndarray, np.ndarray, pd.Index: Slice of X_score, y, common index """ ix_all = createmultiindex(X=X, names=self.ixnamepairs) X_score = pd.DataFrame(X_score, index=ix_all) if isinstance(y, pd.Series) or isinstance(y, pd.DataFrame): commonindex = X_score.index.intersection(y.index) return X_score.loc[commonindex].values, y.loc[commonindex].values, commonindex elif y is None: return X_score.values, None, ix_all else: return X_score.values, y, ix_all def predict(self, X): X_score = self.transformer.transform(X=X) return self.classifier.predict(X=X_score) def fit_predict(self, X, y): self.fit(X=X, y=y) y_pred = self.predict(X=X) return y_pred def predict_proba(self, X): X_score = self.transformer.transform(X=X) return self.classifier.predict_proba(X=X_score) def score(self, X, y, sampleweight=None): X_score = self.transformer.transform(X=X) X_slice, y_slice, ix_slice = self.slice(X=X, X_score=X_score, y=y) return self.classifier.score(X=X_slice, y=y_slice, sample_weight=sampleweight) def return_pairs(self, X): return pd.Series( index=createmultiindex(X=X, names=self.ixnamepairs), data=self.predict(X) ) def show_pairs(self, X, y=None, use_cols=None): """ Create a side by side table from a list of pairs (as a DataFrame) Args: X y (pd.DataFrame/pd.Series): of the form {['ix_source', 'ix_target']:['y_true']} use_cols (list): columns to use Returns: pd.DataFrame {['ix_source', 'ix_target'] : ['name_source', 'name_target', .....]} """ source = X[0] target = X[1] if y is None: xpairs = pd.DataFrame(index=createmultiindex(X=X, names=self.ixnamepairs)) elif isinstance(y, pd.DataFrame): xpairs = y.copy() else: assert isinstance(y, pd.Series) xpairs = pd.DataFrame(y.copy()) xpairs = xpairs.reset_index(drop=False) if use_cols is None or len(use_cols) == 0: use_cols = source.columns.intersection(target.columns) xsource = source[use_cols].copy().reset_index(drop=False) xright = target[use_cols].copy().reset_index(drop=False) xsource = addsuffix(xsource, self.source_suffix).set_index(self.ixnamesource) xright = addsuffix(xright, self.target_suffix).set_index(self.ixnametarget) sbs = xpairs.join( xsource, on=self.ixnamesource, how='left' ).join( xright, on=self.ixnametarget, how='left' ).set_index( self.ixnamepairs ) return sbs
[ "suricate.preutils.createmultiindex", "pandas.Series", "suricate.preutils.concatixnames", "sklearn.base.ClassifierMixin.__init__", "suricate.preutils.addsuffix", "pandas.DataFrame" ]
[((827, 857), 'sklearn.base.ClassifierMixin.__init__', 'ClassifierMixin.__init__', (['self'], {}), '(self)\n', (851, 857), False, 'from sklearn.base import TransformerMixin, ClassifierMixin\n'), ((1038, 1143), 'suricate.preutils.concatixnames', 'concatixnames', ([], {'ixname': 'self.ixname', 'source_suffix': 'self.source_suffix', 'target_suffix': 'self.target_suffix'}), '(ixname=self.ixname, source_suffix=self.source_suffix,\n target_suffix=self.target_suffix)\n', (1051, 1143), False, 'from suricate.preutils import concatixnames, createmultiindex, addsuffix\n'), ((2709, 2754), 'suricate.preutils.createmultiindex', 'createmultiindex', ([], {'X': 'X', 'names': 'self.ixnamepairs'}), '(X=X, names=self.ixnamepairs)\n', (2725, 2754), False, 'from suricate.preutils import concatixnames, createmultiindex, addsuffix\n'), ((2773, 2808), 'pandas.DataFrame', 'pd.DataFrame', (['X_score'], {'index': 'ix_all'}), '(X_score, index=ix_all)\n', (2785, 2808), True, 'import pandas as pd\n'), ((1720, 1757), 'pandas.DataFrame', 'pd.DataFrame', (['X_slice'], {'index': 'ix_slice'}), '(X_slice, index=ix_slice)\n', (1732, 1757), True, 'import pandas as pd\n'), ((1761, 1795), 'pandas.Series', 'pd.Series', (['y_slice'], {'index': 'ix_slice'}), '(y_slice, index=ix_slice)\n', (1770, 1795), True, 'import pandas as pd\n'), ((3880, 3925), 'suricate.preutils.createmultiindex', 'createmultiindex', ([], {'X': 'X', 'names': 'self.ixnamepairs'}), '(X=X, names=self.ixnamepairs)\n', (3896, 3925), False, 'from suricate.preutils import concatixnames, createmultiindex, addsuffix\n'), ((5042, 5080), 'suricate.preutils.addsuffix', 'addsuffix', (['xsource', 'self.source_suffix'], {}), '(xsource, self.source_suffix)\n', (5051, 5080), False, 'from suricate.preutils import concatixnames, createmultiindex, addsuffix\n'), ((5127, 5164), 'suricate.preutils.addsuffix', 'addsuffix', (['xright', 'self.target_suffix'], {}), '(xright, self.target_suffix)\n', (5136, 5164), False, 'from suricate.preutils import concatixnames, createmultiindex, addsuffix\n'), ((4504, 4549), 'suricate.preutils.createmultiindex', 'createmultiindex', ([], {'X': 'X', 'names': 'self.ixnamepairs'}), '(X=X, names=self.ixnamepairs)\n', (4520, 4549), False, 'from suricate.preutils import concatixnames, createmultiindex, addsuffix\n')]
# -*- coding: utf-8 -*- """ Created on Fri Apr 22 02:51:53 2016 @author: utkarsh """ # FREQEST - Estimate fingerprint ridge frequency within image block # # Function to estimate the fingerprint ridge frequency within a small block # of a fingerprint image. This function is used by RIDGEFREQ # # Usage: # freqim = freqest(im, orientim, windsze, minWaveLength, maxWaveLength) # # Arguments: # im - Image block to be processed. # orientim - Ridge orientation image of image block. # windsze - Window length used to identify peaks. This should be # an odd integer, say 3 or 5. # minWaveLength, maxWaveLength - Minimum and maximum ridge # wavelengths, in pixels, considered acceptable. # # Returns: # freqim - An image block the same size as im with all values # set to the estimated ridge spatial frequency. If a # ridge frequency cannot be found, or cannot be found # within the limits set by min and max Wavlength # freqim is set to zeros. # # Suggested parameters for a 500dpi fingerprint image # freqim = freqest(im,orientim, 5, 5, 15); # # See also: RIDGEFREQ, RIDGEORIENT, RIDGESEGMENT ### REFERENCES # <NAME> # School of Computer Science & Software Engineering # The University of Western Australia # pk at csse uwa edu au # http://www.csse.uwa.edu.au/~pk import numpy as np import math import scipy.ndimage #import cv2 def frequest(im,orientim,windsze,minWaveLength,maxWaveLength): rows,cols = np.shape(im) # Find mean orientation within the block. This is done by averaging the # sines and cosines of the doubled angles before reconstructing the # angle again. This avoids wraparound problems at the origin. cosorient = np.mean(np.cos(2*orientim)) sinorient = np.mean(np.sin(2*orientim)) orient = math.atan2(sinorient,cosorient)/2 # Rotate the image block so that the ridges are vertical #ROT_mat = cv2.getRotationMatrix2D((cols/2,rows/2),orient/np.pi*180 + 90,1) #rotim = cv2.warpAffine(im,ROT_mat,(cols,rows)) rotim = scipy.ndimage.rotate(im,orient/np.pi*180 + 90,axes=(1,0),reshape = False,order = 3,mode = 'nearest'); # Now crop the image so that the rotated image does not contain any # invalid regions. This prevents the projection down the columns # from being mucked up. cropsze = int(np.fix(rows/np.sqrt(2))); offset = int(np.fix((rows-cropsze)/2)); rotim = rotim[offset:offset+cropsze][:,offset:offset+cropsze]; # Sum down the columns to get a projection of the grey values down # the ridges. proj = np.sum(rotim,axis = 0); dilation = scipy.ndimage.grey_dilation(proj, windsze,structure=np.ones(windsze)); temp = np.abs(dilation - proj); peak_thresh = 2; maxpts = (temp<peak_thresh) & (proj > np.mean(proj)); maxind = np.where(maxpts); rows_maxind,cols_maxind = np.shape(maxind); # Determine the spatial frequency of the ridges by divinding the # distance between the 1st and last peaks by the (No of peaks-1). If no # peaks are detected, or the wavelength is outside the allowed bounds, # the frequency image is set to 0 if(cols_maxind<2): freqim = np.zeros(im.shape); else: NoOfPeaks = cols_maxind; waveLength = (maxind[0][cols_maxind-1] - maxind[0][0])/(NoOfPeaks - 1); if waveLength>=minWaveLength and waveLength<=maxWaveLength: freqim = 1/np.double(waveLength) * np.ones(im.shape); else: freqim = np.zeros(im.shape); return(freqim);
[ "numpy.abs", "numpy.mean", "numpy.sqrt", "numpy.ones", "numpy.double", "numpy.where", "numpy.fix", "numpy.sum", "numpy.zeros", "numpy.cos", "math.atan2", "numpy.sin", "numpy.shape" ]
[((1590, 1602), 'numpy.shape', 'np.shape', (['im'], {}), '(im)\n', (1598, 1602), True, 'import numpy as np\n'), ((2738, 2759), 'numpy.sum', 'np.sum', (['rotim'], {'axis': '(0)'}), '(rotim, axis=0)\n', (2744, 2759), True, 'import numpy as np\n'), ((2860, 2883), 'numpy.abs', 'np.abs', (['(dilation - proj)'], {}), '(dilation - proj)\n', (2866, 2883), True, 'import numpy as np\n'), ((2991, 3007), 'numpy.where', 'np.where', (['maxpts'], {}), '(maxpts)\n', (2999, 3007), True, 'import numpy as np\n'), ((3044, 3060), 'numpy.shape', 'np.shape', (['maxind'], {}), '(maxind)\n', (3052, 3060), True, 'import numpy as np\n'), ((1861, 1881), 'numpy.cos', 'np.cos', (['(2 * orientim)'], {}), '(2 * orientim)\n', (1867, 1881), True, 'import numpy as np\n'), ((1905, 1925), 'numpy.sin', 'np.sin', (['(2 * orientim)'], {}), '(2 * orientim)\n', (1911, 1925), True, 'import numpy as np\n'), ((1938, 1970), 'math.atan2', 'math.atan2', (['sinorient', 'cosorient'], {}), '(sinorient, cosorient)\n', (1948, 1970), False, 'import math\n'), ((2534, 2562), 'numpy.fix', 'np.fix', (['((rows - cropsze) / 2)'], {}), '((rows - cropsze) / 2)\n', (2540, 2562), True, 'import numpy as np\n'), ((3374, 3392), 'numpy.zeros', 'np.zeros', (['im.shape'], {}), '(im.shape)\n', (3382, 3392), True, 'import numpy as np\n'), ((2829, 2845), 'numpy.ones', 'np.ones', (['windsze'], {}), '(windsze)\n', (2836, 2845), True, 'import numpy as np\n'), ((2962, 2975), 'numpy.mean', 'np.mean', (['proj'], {}), '(proj)\n', (2969, 2975), True, 'import numpy as np\n'), ((3686, 3704), 'numpy.zeros', 'np.zeros', (['im.shape'], {}), '(im.shape)\n', (3694, 3704), True, 'import numpy as np\n'), ((2503, 2513), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (2510, 2513), True, 'import numpy as np\n'), ((3632, 3649), 'numpy.ones', 'np.ones', (['im.shape'], {}), '(im.shape)\n', (3639, 3649), True, 'import numpy as np\n'), ((3608, 3629), 'numpy.double', 'np.double', (['waveLength'], {}), '(waveLength)\n', (3617, 3629), True, 'import numpy as np\n')]
#!/usr/bin/python # # Copyright (c) 2015 CenturyLink # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: clc_alert_policy short_description: Create or Delete Alert Policies at CenturyLink Cloud. description: - An Ansible module to Create or Delete Alert Policies at CenturyLink Cloud. version_added: "2.0" options: alias: description: - The alias of your CLC Account required: True name: description: - The name of the alert policy. This is mutually exclusive with id id: description: - The alert policy id. This is mutually exclusive with name alert_recipients: description: - A list of recipient email ids to notify the alert. This is required for state 'present' metric: description: - The metric on which to measure the condition that will trigger the alert. This is required for state 'present' choices: ['cpu','memory','disk'] duration: description: - The length of time in minutes that the condition must exceed the threshold. This is required for state 'present' threshold: description: - The threshold that will trigger the alert when the metric equals or exceeds it. This is required for state 'present' This number represents a percentage and must be a value between 5.0 - 95.0 that is a multiple of 5.0 state: description: - Whether to create or delete the policy. default: present choices: ['present','absent'] requirements: - python = 2.7 - requests >= 2.5.0 - clc-sdk author: "CLC Runner (@clc-runner)" notes: - To use this module, it is required to set the below environment variables which enables access to the Centurylink Cloud - CLC_V2_API_USERNAME, the account login id for the centurylink cloud - CLC_V2_API_PASSWORD, the account password for the centurylink cloud - Alternatively, the module accepts the API token and account alias. The API token can be generated using the CLC account login and password via the HTTP api call @ https://api.ctl.io/v2/authentication/login - CLC_V2_API_TOKEN, the API token generated from https://api.ctl.io/v2/authentication/login - CLC_ACCT_ALIAS, the account alias associated with the centurylink cloud - Users can set CLC_V2_API_URL to specify an endpoint for pointing to a different CLC environment. ''' EXAMPLES = ''' # Note - You must set the CLC_V2_API_USERNAME And CLC_V2_API_PASSWD Environment variables before running these examples --- - name: Create Alert Policy Example hosts: localhost gather_facts: False connection: local tasks: - name: Create an Alert Policy for disk above 80% for 5 minutes clc_alert_policy: alias: wfad name: 'alert for disk > 80%' alert_recipients: - <EMAIL> - <EMAIL> metric: 'disk' duration: '00:05:00' threshold: 80 state: present register: policy - name: debug debug: var=policy --- - name: Delete Alert Policy Example hosts: localhost gather_facts: False connection: local tasks: - name: Delete an Alert Policy clc_alert_policy: alias: wfad name: 'alert for disk > 80%' state: absent register: policy - name: debug debug: var=policy ''' RETURN = ''' policy: description: The alert policy information returned: success type: dict sample: { "actions": [ { "action": "email", "settings": { "recipients": [ "<EMAIL>", "<EMAIL>" ] } } ], "id": "ba54ac54a60d4a4f1ed6d48c1ce240a7", "links": [ { "href": "/v2/alertPolicies/alias/ba54ac54a60d4a4fb1d6d48c1ce240a7", "rel": "self", "verbs": [ "GET", "DELETE", "PUT" ] } ], "name": "test_alert", "triggers": [ { "duration": "00:05:00", "metric": "disk", "threshold": 80.0 } ] } ''' __version__ = '${version}' import json import os import traceback from distutils.version import LooseVersion REQUESTS_IMP_ERR = None try: import requests except ImportError: REQUESTS_IMP_ERR = traceback.format_exc() REQUESTS_FOUND = False else: REQUESTS_FOUND = True # # Requires the clc-python-sdk. # sudo pip install clc-sdk # CLC_IMP_ERR = None try: import clc as clc_sdk from clc import APIFailedResponse except ImportError: CLC_IMP_ERR = traceback.format_exc() CLC_FOUND = False clc_sdk = None else: CLC_FOUND = True from ansible.module_utils.basic import AnsibleModule, missing_required_lib class ClcAlertPolicy: clc = clc_sdk module = None def __init__(self, module): """ Construct module """ self.module = module self.policy_dict = {} if not CLC_FOUND: self.module.fail_json(msg=missing_required_lib('clc-sdk'), exception=CLC_IMP_ERR) if not REQUESTS_FOUND: self.module.fail_json(msg=missing_required_lib('requests'), exception=REQUESTS_IMP_ERR) if requests.__version__ and LooseVersion(requests.__version__) < LooseVersion('2.5.0'): self.module.fail_json( msg='requests library version should be >= 2.5.0') self._set_user_agent(self.clc) @staticmethod def _define_module_argument_spec(): """ Define the argument spec for the ansible module :return: argument spec dictionary """ argument_spec = dict( name=dict(default=None), id=dict(default=None), alias=dict(required=True, default=None), alert_recipients=dict(type='list', default=None), metric=dict( choices=[ 'cpu', 'memory', 'disk'], default=None), duration=dict(type='str', default=None), threshold=dict(type='int', default=None), state=dict(default='present', choices=['present', 'absent']) ) mutually_exclusive = [ ['name', 'id'] ] return {'argument_spec': argument_spec, 'mutually_exclusive': mutually_exclusive} # Module Behavior Goodness def process_request(self): """ Process the request - Main Code Path :return: Returns with either an exit_json or fail_json """ p = self.module.params self._set_clc_credentials_from_env() self.policy_dict = self._get_alert_policies(p['alias']) if p['state'] == 'present': changed, policy = self._ensure_alert_policy_is_present() else: changed, policy = self._ensure_alert_policy_is_absent() self.module.exit_json(changed=changed, policy=policy) def _set_clc_credentials_from_env(self): """ Set the CLC Credentials on the sdk by reading environment variables :return: none """ env = os.environ v2_api_token = env.get('CLC_V2_API_TOKEN', False) v2_api_username = env.get('CLC_V2_API_USERNAME', False) v2_api_passwd = env.get('CLC_V2_API_PASSWD', False) clc_alias = env.get('CLC_ACCT_ALIAS', False) api_url = env.get('CLC_V2_API_URL', False) if api_url: self.clc.defaults.ENDPOINT_URL_V2 = api_url if v2_api_token and clc_alias: self.clc._LOGIN_TOKEN_V2 = v2_api_token self.clc._V2_ENABLED = True self.clc.ALIAS = clc_alias elif v2_api_username and v2_api_passwd: self.clc.v2.SetCredentials( api_username=v2_api_username, api_passwd=v2_api_passwd) else: return self.module.fail_json( msg="You must set the CLC_V2_API_USERNAME and CLC_V2_API_PASSWD " "environment variables") def _ensure_alert_policy_is_present(self): """ Ensures that the alert policy is present :return: (changed, policy) changed: A flag representing if anything is modified policy: the created/updated alert policy """ changed = False p = self.module.params policy_name = p.get('name') if not policy_name: self.module.fail_json(msg='Policy name is a required') policy = self._alert_policy_exists(policy_name) if not policy: changed = True policy = None if not self.module.check_mode: policy = self._create_alert_policy() else: changed_u, policy = self._ensure_alert_policy_is_updated(policy) if changed_u: changed = True return changed, policy def _ensure_alert_policy_is_absent(self): """ Ensures that the alert policy is absent :return: (changed, None) changed: A flag representing if anything is modified """ changed = False p = self.module.params alert_policy_id = p.get('id') alert_policy_name = p.get('name') alias = p.get('alias') if not alert_policy_id and not alert_policy_name: self.module.fail_json( msg='Either alert policy id or policy name is required') if not alert_policy_id and alert_policy_name: alert_policy_id = self._get_alert_policy_id( self.module, alert_policy_name) if alert_policy_id and alert_policy_id in self.policy_dict: changed = True if not self.module.check_mode: self._delete_alert_policy(alias, alert_policy_id) return changed, None def _ensure_alert_policy_is_updated(self, alert_policy): """ Ensures the alert policy is updated if anything is changed in the alert policy configuration :param alert_policy: the target alert policy :return: (changed, policy) changed: A flag representing if anything is modified policy: the updated the alert policy """ changed = False p = self.module.params alert_policy_id = alert_policy.get('id') email_list = p.get('alert_recipients') metric = p.get('metric') duration = p.get('duration') threshold = p.get('threshold') policy = alert_policy if (metric and metric != str(alert_policy.get('triggers')[0].get('metric'))) or \ (duration and duration != str(alert_policy.get('triggers')[0].get('duration'))) or \ (threshold and float(threshold) != float(alert_policy.get('triggers')[0].get('threshold'))): changed = True elif email_list: t_email_list = list( alert_policy.get('actions')[0].get('settings').get('recipients')) if set(email_list) != set(t_email_list): changed = True if changed and not self.module.check_mode: policy = self._update_alert_policy(alert_policy_id) return changed, policy def _get_alert_policies(self, alias): """ Get the alert policies for account alias by calling the CLC API. :param alias: the account alias :return: the alert policies for the account alias """ response = {} policies = self.clc.v2.API.Call('GET', '/v2/alertPolicies/%s' % alias) for policy in policies.get('items'): response[policy.get('id')] = policy return response def _create_alert_policy(self): """ Create an alert Policy using the CLC API. :return: response dictionary from the CLC API. """ p = self.module.params alias = p['alias'] email_list = p['alert_recipients'] metric = p['metric'] duration = p['duration'] threshold = p['threshold'] policy_name = p['name'] arguments = json.dumps( { 'name': policy_name, 'actions': [{ 'action': 'email', 'settings': { 'recipients': email_list } }], 'triggers': [{ 'metric': metric, 'duration': duration, 'threshold': threshold }] } ) try: result = self.clc.v2.API.Call( 'POST', '/v2/alertPolicies/%s' % alias, arguments) except APIFailedResponse as e: return self.module.fail_json( msg='Unable to create alert policy "{0}". {1}'.format( policy_name, str(e.response_text))) return result def _update_alert_policy(self, alert_policy_id): """ Update alert policy using the CLC API. :param alert_policy_id: The clc alert policy id :return: response dictionary from the CLC API. """ p = self.module.params alias = p['alias'] email_list = p['alert_recipients'] metric = p['metric'] duration = p['duration'] threshold = p['threshold'] policy_name = p['name'] arguments = json.dumps( { 'name': policy_name, 'actions': [{ 'action': 'email', 'settings': { 'recipients': email_list } }], 'triggers': [{ 'metric': metric, 'duration': duration, 'threshold': threshold }] } ) try: result = self.clc.v2.API.Call( 'PUT', '/v2/alertPolicies/%s/%s' % (alias, alert_policy_id), arguments) except APIFailedResponse as e: return self.module.fail_json( msg='Unable to update alert policy "{0}". {1}'.format( policy_name, str(e.response_text))) return result def _delete_alert_policy(self, alias, policy_id): """ Delete an alert policy using the CLC API. :param alias : the account alias :param policy_id: the alert policy id :return: response dictionary from the CLC API. """ try: result = self.clc.v2.API.Call( 'DELETE', '/v2/alertPolicies/%s/%s' % (alias, policy_id), None) except APIFailedResponse as e: return self.module.fail_json( msg='Unable to delete alert policy id "{0}". {1}'.format( policy_id, str(e.response_text))) return result def _alert_policy_exists(self, policy_name): """ Check to see if an alert policy exists :param policy_name: name of the alert policy :return: boolean of if the policy exists """ result = False for policy_id in self.policy_dict: if self.policy_dict.get(policy_id).get('name') == policy_name: result = self.policy_dict.get(policy_id) return result def _get_alert_policy_id(self, module, alert_policy_name): """ retrieves the alert policy id of the account based on the name of the policy :param module: the AnsibleModule object :param alert_policy_name: the alert policy name :return: alert_policy_id: The alert policy id """ alert_policy_id = None for policy_id in self.policy_dict: if self.policy_dict.get(policy_id).get('name') == alert_policy_name: if not alert_policy_id: alert_policy_id = policy_id else: return module.fail_json( msg='multiple alert policies were found with policy name : %s' % alert_policy_name) return alert_policy_id @staticmethod def _set_user_agent(clc): if hasattr(clc, 'SetRequestsSession'): agent_string = "ClcAnsibleModule/" + __version__ ses = requests.Session() ses.headers.update({"Api-Client": agent_string}) ses.headers['User-Agent'] += " " + agent_string clc.SetRequestsSession(ses) def main(): """ The main function. Instantiates the module and calls process_request. :return: none """ argument_dict = ClcAlertPolicy._define_module_argument_spec() module = AnsibleModule(supports_check_mode=True, **argument_dict) clc_alert_policy = ClcAlertPolicy(module) clc_alert_policy.process_request() if __name__ == '__main__': main()
[ "traceback.format_exc", "ansible.module_utils.basic.AnsibleModule", "requests.Session", "json.dumps", "ansible.module_utils.basic.missing_required_lib", "distutils.version.LooseVersion" ]
[((17381, 17437), 'ansible.module_utils.basic.AnsibleModule', 'AnsibleModule', ([], {'supports_check_mode': '(True)'}), '(supports_check_mode=True, **argument_dict)\n', (17394, 17437), False, 'from ansible.module_utils.basic import AnsibleModule, missing_required_lib\n'), ((4862, 4884), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (4882, 4884), False, 'import traceback\n'), ((5135, 5157), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (5155, 5157), False, 'import traceback\n'), ((12778, 12973), 'json.dumps', 'json.dumps', (["{'name': policy_name, 'actions': [{'action': 'email', 'settings': {\n 'recipients': email_list}}], 'triggers': [{'metric': metric, 'duration':\n duration, 'threshold': threshold}]}"], {}), "({'name': policy_name, 'actions': [{'action': 'email', 'settings':\n {'recipients': email_list}}], 'triggers': [{'metric': metric,\n 'duration': duration, 'threshold': threshold}]})\n", (12788, 12973), False, 'import json\n'), ((14103, 14298), 'json.dumps', 'json.dumps', (["{'name': policy_name, 'actions': [{'action': 'email', 'settings': {\n 'recipients': email_list}}], 'triggers': [{'metric': metric, 'duration':\n duration, 'threshold': threshold}]}"], {}), "({'name': policy_name, 'actions': [{'action': 'email', 'settings':\n {'recipients': email_list}}], 'triggers': [{'metric': metric,\n 'duration': duration, 'threshold': threshold}]})\n", (14113, 14298), False, 'import json\n'), ((16999, 17017), 'requests.Session', 'requests.Session', ([], {}), '()\n', (17015, 17017), False, 'import requests\n'), ((5792, 5826), 'distutils.version.LooseVersion', 'LooseVersion', (['requests.__version__'], {}), '(requests.__version__)\n', (5804, 5826), False, 'from distutils.version import LooseVersion\n'), ((5829, 5850), 'distutils.version.LooseVersion', 'LooseVersion', (['"""2.5.0"""'], {}), "('2.5.0')\n", (5841, 5850), False, 'from distutils.version import LooseVersion\n'), ((5569, 5600), 'ansible.module_utils.basic.missing_required_lib', 'missing_required_lib', (['"""clc-sdk"""'], {}), "('clc-sdk')\n", (5589, 5600), False, 'from ansible.module_utils.basic import AnsibleModule, missing_required_lib\n'), ((5694, 5726), 'ansible.module_utils.basic.missing_required_lib', 'missing_required_lib', (['"""requests"""'], {}), "('requests')\n", (5714, 5726), False, 'from ansible.module_utils.basic import AnsibleModule, missing_required_lib\n')]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from decimal import Decimal class Migration(migrations.Migration): dependencies = [ ('shopping', '0005_auto_20151125_1001'), ] operations = [ migrations.AddField( model_name='customorder', name='payment_cost', field=models.DecimalField(null=True, verbose_name='shipping cost', max_digits=18, decimal_places=10, blank=True), ), migrations.AddField( model_name='customorder', name='payment_tax', field=models.DecimalField(default=Decimal('0.00'), verbose_name='shipping tax', max_digits=18, decimal_places=10), ), ]
[ "django.db.models.DecimalField", "decimal.Decimal" ]
[((390, 500), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'null': '(True)', 'verbose_name': '"""shipping cost"""', 'max_digits': '(18)', 'decimal_places': '(10)', 'blank': '(True)'}), "(null=True, verbose_name='shipping cost', max_digits=18,\n decimal_places=10, blank=True)\n", (409, 500), False, 'from django.db import models, migrations\n'), ((654, 669), 'decimal.Decimal', 'Decimal', (['"""0.00"""'], {}), "('0.00')\n", (661, 669), False, 'from decimal import Decimal\n')]
import csv import os #field names field = ['Image', 'Label'] #data rows of csv file rows = [] #def rows_item(n): filename = 'data.csv' # This Python code is for creating a csv file. In this CSV file one column is for the location of the image and other column is for # the 'label'. # create two blank array. One for image_names and other for image_labels. image_name = [] image_label = [] for folder in os.listdir('Dataset/covid_ctscan/New_Data_CoV2'): data_folder = 'Dataset/covid_ctscan/New_Data_CoV2/' + folder for subfolder in os.listdir(data_folder): sub_folder = data_folder + '/' + subfolder for files in os.listdir(sub_folder): filename, fileextension = os.path.splitext(files) if(fileextension == '.png'): file_path = sub_folder + '/' + files image_name.append(file_path) image_label.append(folder) for i in range(len(image_name)): rows_element = [image_name[i], image_label[i]] rows.append(rows_element) #print(rows) with open('data.csv', 'w', newline='') as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile,delimiter = ',', quotechar = '|', quoting = csv.QUOTE_MINIMAL) # writing the fields csvwriter.writerow(['Image', 'label']) #writing the data rows csvwriter.writerows(rows)
[ "csv.writer", "os.listdir", "os.path.splitext" ]
[((411, 459), 'os.listdir', 'os.listdir', (['"""Dataset/covid_ctscan/New_Data_CoV2"""'], {}), "('Dataset/covid_ctscan/New_Data_CoV2')\n", (421, 459), False, 'import os\n'), ((547, 570), 'os.listdir', 'os.listdir', (['data_folder'], {}), '(data_folder)\n', (557, 570), False, 'import os\n'), ((1155, 1231), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""|"""', 'quoting': 'csv.QUOTE_MINIMAL'}), "(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n", (1165, 1231), False, 'import csv\n'), ((644, 666), 'os.listdir', 'os.listdir', (['sub_folder'], {}), '(sub_folder)\n', (654, 666), False, 'import os\n'), ((706, 729), 'os.path.splitext', 'os.path.splitext', (['files'], {}), '(files)\n', (722, 729), False, 'import os\n')]
from django.urls import path from users_app import views from django.contrib.auth.views import LogoutView app_name = 'users_app' urlpatterns = [ path('login/', views.UserLoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('register/', views.UserCreateView.as_view(), name='register'), path('pass_change/', views.PasswordResetByUser.as_view(), name='pass_change'), ]
[ "users_app.views.UserLoginView.as_view", "django.contrib.auth.views.LogoutView.as_view", "users_app.views.PasswordResetByUser.as_view", "users_app.views.UserCreateView.as_view" ]
[((166, 195), 'users_app.views.UserLoginView.as_view', 'views.UserLoginView.as_view', ([], {}), '()\n', (193, 195), False, 'from users_app import views\n'), ((232, 252), 'django.contrib.auth.views.LogoutView.as_view', 'LogoutView.as_view', ([], {}), '()\n', (250, 252), False, 'from django.contrib.auth.views import LogoutView\n'), ((292, 322), 'users_app.views.UserCreateView.as_view', 'views.UserCreateView.as_view', ([], {}), '()\n', (320, 322), False, 'from users_app import views\n'), ((367, 402), 'users_app.views.PasswordResetByUser.as_view', 'views.PasswordResetByUser.as_view', ([], {}), '()\n', (400, 402), False, 'from users_app import views\n')]
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import tensorflow as tf from tensorflow.keras.layers import Dense, Input from tensorflow.keras import Model, layers class Encoder(layers.Layer): def __init__(self, nLatent, layers, activations, name='encoder'): super(Encoder, self).__init__(name=name) self.layers = [ Dense(l, activation=a) for l, a in zip(layers, activations) ] self.mean = Dense(nLatent) self.logVar = Dense(nLatent) def call(self, inputs): # Go through the Dense layers x = inputs * 1 for dl in self.layers: x = dl(x) # Create the latent layer (z) zMean = self.mean(x) zLogVar = self.logVar(x) epsilon = tf.random.normal( shape=zMean.shape, mean=0, stddev=1 ) z = zMean + tf.exp( 0.5 * zLogVar )*epsilon return zMean, zLogVar, z class Decoder(layers.Layer): def __init__(self, nInp, layers, activations, name='encoder'): super(Decoder, self).__init__(name=name) layers = list(reversed(layers)) activations = list(reversed(activations)) self.layers = [ Dense(l, activation=a) for l, a in zip(layers, activations) ] self.result = Dense(nInp, activation=None) def call(self, inputs): # Go through the Dense layers x = inputs * 1 for dl in self.layers: x = dl(x) result = self.result(x) return result class VAE(Model): def __init__(self, nInp, layers, activations, nLatent, lr = 1e-3, name='vae'): super(VAE, self).__init__(name=name) self.nInp = nInp self.nLatent = nLatent self.encoder = Encoder(nLatent=nLatent, layers=layers, activations=activations) self.decoder = Decoder(nInp, layers=layers, activations=activations) self.optimizer = tf.keras.optimizers.Adam(learning_rate = lr) def call(self, inputs): zMean, zLogVar, z = self.encoder(inputs) reconstructed = self.decoder(z) return reconstructed def step(self, x): with tf.GradientTape() as tape: zMean, zLogVar, z = self.encoder(x) xHat = self.decoder( z ) # Reconstruction Loss reconLoss = tf.nn.sigmoid_cross_entropy_with_logits( x, xHat ) reconLoss = tf.reduce_sum( reconLoss, 1 ) reconLoss = tf.reduce_mean( reconLoss ) reconLoss = reconLoss # KL - divergence loss klLoss = - 0.5 * tf.reduce_sum(zLogVar - tf.square(zMean) - tf.exp(zLogVar) + 1, 1) klLoss = tf.reduce_mean( klLoss ) klLoss = klLoss # Calculate the total loss loss = reconLoss + 1e1*klLoss # Optimize grads = tape.gradient(loss, self.trainable_weights) self.optimizer.apply_gradients(zip(grads, self.trainable_weights)) return reconLoss.numpy(), klLoss.numpy(), loss.numpy() def checkpoint(self, folder): folder = os.path.join( folder, 'model', 'modelData' ) os.makedirs( folder, exist_ok=True ) self.save_weights( folder ) return
[ "tensorflow.random.normal", "os.makedirs", "tensorflow.reduce_sum", "os.path.join", "tensorflow.keras.optimizers.Adam", "tensorflow.GradientTape", "tensorflow.keras.layers.Dense", "tensorflow.square", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "tensorflow.reduce_mean", "tensorflow.exp" ]
[((432, 446), 'tensorflow.keras.layers.Dense', 'Dense', (['nLatent'], {}), '(nLatent)\n', (437, 446), False, 'from tensorflow.keras.layers import Dense, Input\n'), ((470, 484), 'tensorflow.keras.layers.Dense', 'Dense', (['nLatent'], {}), '(nLatent)\n', (475, 484), False, 'from tensorflow.keras.layers import Dense, Input\n'), ((758, 811), 'tensorflow.random.normal', 'tf.random.normal', ([], {'shape': 'zMean.shape', 'mean': '(0)', 'stddev': '(1)'}), '(shape=zMean.shape, mean=0, stddev=1)\n', (774, 811), True, 'import tensorflow as tf\n'), ((1261, 1289), 'tensorflow.keras.layers.Dense', 'Dense', (['nInp'], {'activation': 'None'}), '(nInp, activation=None)\n', (1266, 1289), False, 'from tensorflow.keras.layers import Dense, Input\n'), ((1915, 1957), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': 'lr'}), '(learning_rate=lr)\n', (1939, 1957), True, 'import tensorflow as tf\n'), ((3112, 3154), 'os.path.join', 'os.path.join', (['folder', '"""model"""', '"""modelData"""'], {}), "(folder, 'model', 'modelData')\n", (3124, 3154), False, 'import os\n'), ((3165, 3199), 'os.makedirs', 'os.makedirs', (['folder'], {'exist_ok': '(True)'}), '(folder, exist_ok=True)\n', (3176, 3199), False, 'import os\n'), ((347, 369), 'tensorflow.keras.layers.Dense', 'Dense', (['l'], {'activation': 'a'}), '(l, activation=a)\n', (352, 369), False, 'from tensorflow.keras.layers import Dense, Input\n'), ((1176, 1198), 'tensorflow.keras.layers.Dense', 'Dense', (['l'], {'activation': 'a'}), '(l, activation=a)\n', (1181, 1198), False, 'from tensorflow.keras.layers import Dense, Input\n'), ((2159, 2176), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (2174, 2176), True, 'import tensorflow as tf\n'), ((2331, 2379), 'tensorflow.nn.sigmoid_cross_entropy_with_logits', 'tf.nn.sigmoid_cross_entropy_with_logits', (['x', 'xHat'], {}), '(x, xHat)\n', (2370, 2379), True, 'import tensorflow as tf\n'), ((2406, 2433), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['reconLoss', '(1)'], {}), '(reconLoss, 1)\n', (2419, 2433), True, 'import tensorflow as tf\n'), ((2460, 2485), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['reconLoss'], {}), '(reconLoss)\n', (2474, 2485), True, 'import tensorflow as tf\n'), ((2681, 2703), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['klLoss'], {}), '(klLoss)\n', (2695, 2703), True, 'import tensorflow as tf\n'), ((840, 861), 'tensorflow.exp', 'tf.exp', (['(0.5 * zLogVar)'], {}), '(0.5 * zLogVar)\n', (846, 861), True, 'import tensorflow as tf\n'), ((2633, 2648), 'tensorflow.exp', 'tf.exp', (['zLogVar'], {}), '(zLogVar)\n', (2639, 2648), True, 'import tensorflow as tf\n'), ((2614, 2630), 'tensorflow.square', 'tf.square', (['zMean'], {}), '(zMean)\n', (2623, 2630), True, 'import tensorflow as tf\n')]
import numpy as np import sys import argparse from data_util import Dataset from tqdm import tqdm, trange import matplotlib.pyplot as plt class Error(Exception): pass class MoreNeighbours(Error): pass def nearest_neighbour(train_data, test_data, k=1): # print(k) test_data = test_data[None, :, None] norm_l2 = np.linalg.norm(train_data - test_data, axis=1) flattened = np.ravel(norm_l2.T) index = np.argsort(flattened) index = index[:k] index = [int(i / train_data.shape[0]) for i in index] counts = np.bincount(index) # print(counts) # Breaking the tie max_count = np.max(counts) inds = np.where(counts == max_count)[0] np.random.seed(10) if len(inds) > 1: random = np.random.rand(len(inds)) index = np.argmax(random) return inds[index] else: return np.argmax(counts) def knn_classification(data, k=1): try: if k > data.train_data.shape[0]: raise MoreNeighbours except MoreNeighbours: print("More nearest neighbours needed than data in any class") sys.exit() correct = 0 total_samples = data.test_data.shape[-1] * data.test_data.shape[0] for i in trange(data.test_data.shape[-1], desc='testing'): for j in range(data.test_data.shape[0]): distance = nearest_neighbour(data.train_data, data.test_data[j, :, i], k) if distance == i: correct = correct + 1 acc = correct * 100 / total_samples print(f"Test accuracy: {acc}") return acc if __name__ == '__main__': parser = argparse.ArgumentParser(description="Bayes") parser.add_argument('--data_name', type=str, default='data', help='choose from data, pose and illum') parser.add_argument('--task_id', type=int, default=1) parser.add_argument('--transform', type=str, default='PCA', help='PCA or MDA') args = parser.parse_args() data_name = args.data_name # threshold = {'data': 0.3, # 'pose': 0.08, # 'illum': 0.1} # k = {'data': 1, # 'pose': 3, # 'illum': 1} # data = Dataset() # data.load_data(transform='PCA', threshold=threshold[data_name], data_name=data_name) # data.train_val_test_split(data_name=data_name) # knn_classification(data, k=k[data_name]) test_acc_list = {} split = [] if data_name =='data': indexes = np.arange(0.02, 0.3, 0.01) else: indexes = np.arange(0.02, 0.1, 0.01) for _, j in enumerate(indexes): if args.task_id == 1: threshold = {'data': j, 'pose': j, 'illum': j} elif args.task_id == 2: threshold = {'data': j} data = Dataset(task_id=args.task_id) data.load_data(transform=args.transform, threshold=threshold[data_name], data_name=data_name) data.train_val_test_split(data_name=data_name) for i in range(min(data.train_data.shape[0], 10)): k = {'data': i + 1, 'pose': i + 1, 'illum': i + 1} test_acc = knn_classification(data, k=k[data_name]) if i + 1 in test_acc_list.keys(): test_acc_list[i + 1].append(test_acc) else: test_acc_list[i + 1] = [test_acc] # split = list(indexes) # # fig = plt.figure() # for keys in test_acc_list.keys(): # plt.plot(split, test_acc_list[keys], label=f'k={keys}') # plt.legend(bbox_to_anchor=(0.82, 1), loc='upper left', borderaxespad=0.) # plt.xlabel('Fraction of Principal Components Taken') # plt.ylabel('Test Accuracy') # # plt.savefig(f'./Dataset/{data_name}/knn/test_acc_transform={args.transform}_taskid={args.task_id}.png') # plt.close()
[ "sys.exit", "argparse.ArgumentParser", "numpy.where", "numpy.argmax", "numpy.max", "numpy.argsort", "numpy.random.seed", "numpy.linalg.norm", "numpy.ravel", "numpy.bincount", "tqdm.trange", "numpy.arange", "data_util.Dataset" ]
[((333, 379), 'numpy.linalg.norm', 'np.linalg.norm', (['(train_data - test_data)'], {'axis': '(1)'}), '(train_data - test_data, axis=1)\n', (347, 379), True, 'import numpy as np\n'), ((396, 415), 'numpy.ravel', 'np.ravel', (['norm_l2.T'], {}), '(norm_l2.T)\n', (404, 415), True, 'import numpy as np\n'), ((428, 449), 'numpy.argsort', 'np.argsort', (['flattened'], {}), '(flattened)\n', (438, 449), True, 'import numpy as np\n'), ((543, 561), 'numpy.bincount', 'np.bincount', (['index'], {}), '(index)\n', (554, 561), True, 'import numpy as np\n'), ((622, 636), 'numpy.max', 'np.max', (['counts'], {}), '(counts)\n', (628, 636), True, 'import numpy as np\n'), ((685, 703), 'numpy.random.seed', 'np.random.seed', (['(10)'], {}), '(10)\n', (699, 703), True, 'import numpy as np\n'), ((1211, 1259), 'tqdm.trange', 'trange', (['data.test_data.shape[-1]'], {'desc': '"""testing"""'}), "(data.test_data.shape[-1], desc='testing')\n", (1217, 1259), False, 'from tqdm import tqdm, trange\n'), ((1600, 1644), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Bayes"""'}), "(description='Bayes')\n", (1623, 1644), False, 'import argparse\n'), ((648, 677), 'numpy.where', 'np.where', (['(counts == max_count)'], {}), '(counts == max_count)\n', (656, 677), True, 'import numpy as np\n'), ((785, 802), 'numpy.argmax', 'np.argmax', (['random'], {}), '(random)\n', (794, 802), True, 'import numpy as np\n'), ((856, 873), 'numpy.argmax', 'np.argmax', (['counts'], {}), '(counts)\n', (865, 873), True, 'import numpy as np\n'), ((2441, 2467), 'numpy.arange', 'np.arange', (['(0.02)', '(0.3)', '(0.01)'], {}), '(0.02, 0.3, 0.01)\n', (2450, 2467), True, 'import numpy as np\n'), ((2496, 2522), 'numpy.arange', 'np.arange', (['(0.02)', '(0.1)', '(0.01)'], {}), '(0.02, 0.1, 0.01)\n', (2505, 2522), True, 'import numpy as np\n'), ((2784, 2813), 'data_util.Dataset', 'Dataset', ([], {'task_id': 'args.task_id'}), '(task_id=args.task_id)\n', (2791, 2813), False, 'from data_util import Dataset\n'), ((1100, 1110), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1108, 1110), False, 'import sys\n')]
"""Provides LogPipe class to pipe output from subprocess to a log. Adapted from https://codereview.stackexchange.com/questions/6567""" import logging import threading import os class LogPipe(threading.Thread): def __init__(self, logger, level): """Setup the object with a logger and a loglevel and start the thread""" super(LogPipe, self).__init__() # threading.Thread.__init__(self) self.logger = logging.getLogger(logger) self.daemon = False self.level = level self.fdRead, self.fdWrite = os.pipe() self.pipeReader = os.fdopen(self.fdRead) self.start() def fileno(self): """Return the write file descriptor of the pipe""" return self.fdWrite def run(self): """Run the thread, logging everything.""" for line in iter(self.pipeReader.readline, ''): self.logger.log(self.level, line.strip('\n')) self.pipeReader.close() def close(self): """Close the write end of the pipe.""" os.close(self.fdWrite)
[ "logging.getLogger", "os.pipe", "os.fdopen", "os.close" ]
[((436, 461), 'logging.getLogger', 'logging.getLogger', (['logger'], {}), '(logger)\n', (453, 461), False, 'import logging\n'), ((553, 562), 'os.pipe', 'os.pipe', ([], {}), '()\n', (560, 562), False, 'import os\n'), ((589, 611), 'os.fdopen', 'os.fdopen', (['self.fdRead'], {}), '(self.fdRead)\n', (598, 611), False, 'import os\n'), ((1036, 1058), 'os.close', 'os.close', (['self.fdWrite'], {}), '(self.fdWrite)\n', (1044, 1058), False, 'import os\n')]
# -*- coding: utf-8 -*- ''' Control concurrency of steps within state execution using zookeeper ========================================================================= This module allows you to "wrap" a state's execution with concurrency control. This is useful to protect against all hosts executing highstate simultaneously if your services don't all HUP restart. The common way of protecting against this is to run in batch mode, but that doesn't protect from another person running the same batch command (and thereby having 2x the number of nodes deploying at once). This module will bock while acquiring a slot, meaning that however the command gets called it will coordinate with zookeeper to ensure that no more than max_concurrency steps are executing with a single path. .. code-block:: yaml acquire_lock: zk_concurrency.lock: - zk_hosts: 'zookeeper:2181' - path: /trafficserver - max_concurrency: 4 - prereq: - service: trafficserver trafficserver: service.running: - watch: - file: /etc/trafficserver/records.config /etc/trafficserver/records.config: file.managed: - source: salt://records.config release_lock: zk_concurrency.unlock: - path: /trafficserver - require: - service: trafficserver This example would allow the file state to change, but would limit the concurrency of the trafficserver service restart to 4. ''' import logging try: from kazoo.client import KazooClient from kazoo.retry import ( ForceRetryError ) import kazoo.recipe.lock from kazoo.exceptions import CancelledError from kazoo.exceptions import NoNodeError # TODO: use the kazoo one, waiting for pull req: # https://github.com/python-zk/kazoo/pull/206 class _Semaphore(kazoo.recipe.lock.Semaphore): def __init__(self, client, path, identifier=None, max_leases=1, ephemeral_lease=True, ): kazoo.recipe.lock.Semaphore.__init__(self, client, path, identifier=identifier, max_leases=max_leases) self.ephemeral_lease = ephemeral_lease # if its not ephemeral, make sure we didn't already grab it if not self.ephemeral_lease: for child in self.client.get_children(self.path): try: data, stat = self.client.get(self.path + "/" + child) if identifier == data.decode('utf-8'): self.create_path = self.path + "/" + child self.is_acquired = True break except NoNodeError: # pragma: nocover pass def _get_lease(self, data=None): # Make sure the session is still valid if self._session_expired: raise ForceRetryError("Retry on session loss at top") # Make sure that the request hasn't been canceled if self.cancelled: raise CancelledError("Semaphore cancelled") # Get a list of the current potential lock holders. If they change, # notify our wake_event object. This is used to unblock a blocking # self._inner_acquire call. children = self.client.get_children(self.path, self._watch_lease_change) # If there are leases available, acquire one if len(children) < self.max_leases: self.client.create(self.create_path, self.data, ephemeral=self.ephemeral_lease) # Check if our acquisition was successful or not. Update our state. if self.client.exists(self.create_path): self.is_acquired = True else: self.is_acquired = False # Return current state return self.is_acquired HAS_DEPS = True except ImportError: HAS_DEPS = False ZK_CONNECTION = None SEMAPHORE_MAP = {} __virtualname__ = 'zk_concurrency' def __virtual__(): if not HAS_DEPS: return False return __virtualname__ def _get_zk_conn(hosts): global ZK_CONNECTION if ZK_CONNECTION is None: ZK_CONNECTION = KazooClient(hosts=hosts) ZK_CONNECTION.start() return ZK_CONNECTION def _close_zk_conn(): global ZK_CONNECTION if ZK_CONNECTION is None: return ZK_CONNECTION.stop() ZK_CONNECTION = None def lock(zk_hosts, path, max_concurrency, timeout=None, ephemeral_lease=False): ''' Block state execution until you are able to get the lock (or hit the timeout) ''' ret = {'name': path, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: ret['result'] = None ret['comment'] = 'attempt to aqcuire lock' return ret zk = _get_zk_conn(zk_hosts) if path not in SEMAPHORE_MAP: SEMAPHORE_MAP[path] = _Semaphore(zk, path, __grains__['id'], max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) # block waiting for lock acquisition if timeout: logging.info('Acquiring lock with timeout={0}'.format(timeout)) SEMAPHORE_MAP[path].acquire(timeout=timeout) else: logging.info('Acquiring lock with no timeout') SEMAPHORE_MAP[path].acquire() if SEMAPHORE_MAP[path].is_acquired: ret['result'] = True ret['comment'] = 'lock acquired' else: ret['comment'] = 'Unable to acquire lock' return ret def unlock(path): ''' Remove lease from semaphore ''' ret = {'name': path, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: ret['result'] = None ret['comment'] = 'released lock if its here' return ret if path in SEMAPHORE_MAP: SEMAPHORE_MAP[path].release() del SEMAPHORE_MAP[path] else: ret['comment'] = 'Unable to find lease for path {0}'.format(path) return ret ret['result'] = True return ret
[ "kazoo.exceptions.CancelledError", "kazoo.retry.ForceRetryError", "kazoo.client.KazooClient", "logging.info" ]
[((4581, 4605), 'kazoo.client.KazooClient', 'KazooClient', ([], {'hosts': 'hosts'}), '(hosts=hosts)\n', (4592, 4605), False, 'from kazoo.client import KazooClient\n'), ((5811, 5857), 'logging.info', 'logging.info', (['"""Acquiring lock with no timeout"""'], {}), "('Acquiring lock with no timeout')\n", (5823, 5857), False, 'import logging\n'), ((3203, 3250), 'kazoo.retry.ForceRetryError', 'ForceRetryError', (['"""Retry on session loss at top"""'], {}), "('Retry on session loss at top')\n", (3218, 3250), False, 'from kazoo.retry import ForceRetryError\n'), ((3367, 3404), 'kazoo.exceptions.CancelledError', 'CancelledError', (['"""Semaphore cancelled"""'], {}), "('Semaphore cancelled')\n", (3381, 3404), False, 'from kazoo.exceptions import CancelledError\n')]
""" type-id: type-specifier-seq abstract-declarator? defining-type-id: defining-type-specifier-seq abstract-declarator? abstract-declarator: ptr-abstract-declarator noptr-abstract-declarator? parameters-and-qualifiers trailing-return-type abstract-pack-declarator ptr-abstract-declarator: noptr-abstract-declarator ptr-operator ptr-abstract-declarator? noptr-abstract-declarator: noptr-abstract-declarator? parameters-and-qualifiers noptr-abstract-declarator? [ constant-expression? ] attribute-specifier-seq? ( ptr-abstract-declarator ) abstract-pack-declarator: noptr-abstract-pack-declarator ptr-operator abstract-pack-declarator noptr-abstract-pack-declarator: noptr-abstract-pack-declarator parameters-and-qualifiers noptr-abstract-pack-declarator [ constant-expression? ] attribute-specifier-seq? ... """ import glrp from ....parser import cxx98, cxx11 from motor_typing import TYPE_CHECKING @glrp.rule('type-id : type-specifier-seq abstract-declarator?') @cxx98 def type_id(self, p): # type: (CxxParser, glrp.Production) -> None pass @glrp.rule('defining-type-id : defining-type-specifier-seq abstract-declarator?') @cxx98 def defining_type_id(self, p): # type: (CxxParser, glrp.Production) -> None pass @glrp.rule('abstract-declarator? : ptr-abstract-declarator') @glrp.rule('abstract-declarator? : [split:declarator_end]') @cxx98 def abstract_declarator_opt(self, p): # type: (CxxParser, glrp.Production) -> None pass @glrp.rule('abstract-declarator? : parameters-and-qualifiers trailing-return-type') @glrp.rule('abstract-declarator? : noptr-abstract-declarator parameters-and-qualifiers trailing-return-type') #@glrp.rule('abstract-declarator? : abstract-pack-declarator') @cxx11 def abstract_declarator_opt_cxx11(self, p): # type: (CxxParser, glrp.Production) -> None pass @glrp.rule('ptr-abstract-declarator : noptr-abstract-declarator[split:declarator_end]') @glrp.rule('ptr-abstract-declarator : ptr-operator[split:declarator_end]') @glrp.rule('ptr-abstract-declarator : ptr-operator ptr-abstract-declarator') @cxx98 def ptr_abstract_declarator(self, p): # type: (CxxParser, glrp.Production) -> None pass @glrp.rule('noptr-abstract-declarator : parameters-and-qualifiers') @glrp.rule('noptr-abstract-declarator : "[" constant-expression? "]" attribute-specifier-seq?') @glrp.rule('noptr-abstract-declarator : noptr-abstract-declarator parameters-and-qualifiers') @glrp.rule( 'noptr-abstract-declarator : noptr-abstract-declarator "[" constant-expression? "]" attribute-specifier-seq?' ) @glrp.rule( 'noptr-abstract-declarator : [split:declarator_continue]"(" noptr-abstract-declarator-disambiguation ptr-abstract-declarator ")"' ) @cxx98 def noptr_abstract_declarator(self, p): # type: (CxxParser, glrp.Production) -> None pass @glrp.rule('noptr-abstract-declarator-disambiguation[split:noptr_abstract_declarator] :') @cxx98 def noptr_abstract_declarator_disambiguation(self, p): # type: (CxxParser, glrp.Production) -> None pass @glrp.rule('abstract-pack-declarator : noptr-abstract-pack-declarator') @glrp.rule('abstract-pack-declarator : ptr-operator abstract-pack-declarator') @cxx11 def abstract_pack_declarator(self, p): # type: (CxxParser, glrp.Production) -> None pass @glrp.rule('noptr-abstract-pack-declarator : noptr-abstract-pack-declarator parameters-and-qualifiers') @glrp.rule( 'noptr-abstract-pack-declarator : noptr-abstract-pack-declarator "[" constant-expression? "]" attribute-specifier-seq?' ) @glrp.rule('noptr-abstract-pack-declarator : [split:pack_declarator]"..."') @cxx11 def noptr_abstract_pack_declarator(self, p): # type: (CxxParser, glrp.Production) -> None pass if TYPE_CHECKING: from ....parser import CxxParser
[ "glrp.rule" ]
[((968, 1030), 'glrp.rule', 'glrp.rule', (['"""type-id : type-specifier-seq abstract-declarator?"""'], {}), "('type-id : type-specifier-seq abstract-declarator?')\n", (977, 1030), False, 'import glrp\n'), ((1121, 1206), 'glrp.rule', 'glrp.rule', (['"""defining-type-id : defining-type-specifier-seq abstract-declarator?"""'], {}), "('defining-type-id : defining-type-specifier-seq abstract-declarator?'\n )\n", (1130, 1206), False, 'import glrp\n'), ((1301, 1360), 'glrp.rule', 'glrp.rule', (['"""abstract-declarator? : ptr-abstract-declarator"""'], {}), "('abstract-declarator? : ptr-abstract-declarator')\n", (1310, 1360), False, 'import glrp\n'), ((1362, 1420), 'glrp.rule', 'glrp.rule', (['"""abstract-declarator? : [split:declarator_end]"""'], {}), "('abstract-declarator? : [split:declarator_end]')\n", (1371, 1420), False, 'import glrp\n'), ((1527, 1614), 'glrp.rule', 'glrp.rule', (['"""abstract-declarator? : parameters-and-qualifiers trailing-return-type"""'], {}), "(\n 'abstract-declarator? : parameters-and-qualifiers trailing-return-type')\n", (1536, 1614), False, 'import glrp\n'), ((1611, 1729), 'glrp.rule', 'glrp.rule', (['"""abstract-declarator? : noptr-abstract-declarator parameters-and-qualifiers trailing-return-type"""'], {}), "(\n 'abstract-declarator? : noptr-abstract-declarator parameters-and-qualifiers trailing-return-type'\n )\n", (1620, 1729), False, 'import glrp\n'), ((1895, 1991), 'glrp.rule', 'glrp.rule', (['"""ptr-abstract-declarator : noptr-abstract-declarator[split:declarator_end]"""'], {}), "(\n 'ptr-abstract-declarator : noptr-abstract-declarator[split:declarator_end]'\n )\n", (1904, 1991), False, 'import glrp\n'), ((1983, 2056), 'glrp.rule', 'glrp.rule', (['"""ptr-abstract-declarator : ptr-operator[split:declarator_end]"""'], {}), "('ptr-abstract-declarator : ptr-operator[split:declarator_end]')\n", (1992, 2056), False, 'import glrp\n'), ((2058, 2133), 'glrp.rule', 'glrp.rule', (['"""ptr-abstract-declarator : ptr-operator ptr-abstract-declarator"""'], {}), "('ptr-abstract-declarator : ptr-operator ptr-abstract-declarator')\n", (2067, 2133), False, 'import glrp\n'), ((2240, 2306), 'glrp.rule', 'glrp.rule', (['"""noptr-abstract-declarator : parameters-and-qualifiers"""'], {}), "('noptr-abstract-declarator : parameters-and-qualifiers')\n", (2249, 2306), False, 'import glrp\n'), ((2308, 2412), 'glrp.rule', 'glrp.rule', (['"""noptr-abstract-declarator : "[" constant-expression? "]" attribute-specifier-seq?"""'], {}), '(\n \'noptr-abstract-declarator : "[" constant-expression? "]" attribute-specifier-seq?\'\n )\n', (2317, 2412), False, 'import glrp\n'), ((2404, 2506), 'glrp.rule', 'glrp.rule', (['"""noptr-abstract-declarator : noptr-abstract-declarator parameters-and-qualifiers"""'], {}), "(\n 'noptr-abstract-declarator : noptr-abstract-declarator parameters-and-qualifiers'\n )\n", (2413, 2506), False, 'import glrp\n'), ((2498, 2628), 'glrp.rule', 'glrp.rule', (['"""noptr-abstract-declarator : noptr-abstract-declarator "[" constant-expression? "]" attribute-specifier-seq?"""'], {}), '(\n \'noptr-abstract-declarator : noptr-abstract-declarator "[" constant-expression? "]" attribute-specifier-seq?\'\n )\n', (2507, 2628), False, 'import glrp\n'), ((2626, 2777), 'glrp.rule', 'glrp.rule', (['"""noptr-abstract-declarator : [split:declarator_continue]"(" noptr-abstract-declarator-disambiguation ptr-abstract-declarator ")\\""""'], {}), '(\n \'noptr-abstract-declarator : [split:declarator_continue]"(" noptr-abstract-declarator-disambiguation ptr-abstract-declarator ")"\'\n )\n', (2635, 2777), False, 'import glrp\n'), ((2882, 2980), 'glrp.rule', 'glrp.rule', (['"""noptr-abstract-declarator-disambiguation[split:noptr_abstract_declarator] :"""'], {}), "(\n 'noptr-abstract-declarator-disambiguation[split:noptr_abstract_declarator] :'\n )\n", (2891, 2980), False, 'import glrp\n'), ((3094, 3164), 'glrp.rule', 'glrp.rule', (['"""abstract-pack-declarator : noptr-abstract-pack-declarator"""'], {}), "('abstract-pack-declarator : noptr-abstract-pack-declarator')\n", (3103, 3164), False, 'import glrp\n'), ((3166, 3243), 'glrp.rule', 'glrp.rule', (['"""abstract-pack-declarator : ptr-operator abstract-pack-declarator"""'], {}), "('abstract-pack-declarator : ptr-operator abstract-pack-declarator')\n", (3175, 3243), False, 'import glrp\n'), ((3351, 3463), 'glrp.rule', 'glrp.rule', (['"""noptr-abstract-pack-declarator : noptr-abstract-pack-declarator parameters-and-qualifiers"""'], {}), "(\n 'noptr-abstract-pack-declarator : noptr-abstract-pack-declarator parameters-and-qualifiers'\n )\n", (3360, 3463), False, 'import glrp\n'), ((3455, 3595), 'glrp.rule', 'glrp.rule', (['"""noptr-abstract-pack-declarator : noptr-abstract-pack-declarator "[" constant-expression? "]" attribute-specifier-seq?"""'], {}), '(\n \'noptr-abstract-pack-declarator : noptr-abstract-pack-declarator "[" constant-expression? "]" attribute-specifier-seq?\'\n )\n', (3464, 3595), False, 'import glrp\n'), ((3593, 3667), 'glrp.rule', 'glrp.rule', (['"""noptr-abstract-pack-declarator : [split:pack_declarator]"...\\""""'], {}), '(\'noptr-abstract-pack-declarator : [split:pack_declarator]"..."\')\n', (3602, 3667), False, 'import glrp\n')]
from fjord.base.plugin_utils import load_providers from fjord.redirector import _REDIRECTORS class RedirectorTestMixin(object): """Mixin that loads Redirectors specified with ``redirectors`` attribute""" redirectors = [] def setUp(self): _REDIRECTORS[:] = load_providers(self.redirectors) super(RedirectorTestMixin, self).setUp() def tearDown(self): _REDIRECTORS[:] = [] super(RedirectorTestMixin, self).tearDown()
[ "fjord.base.plugin_utils.load_providers" ]
[((279, 311), 'fjord.base.plugin_utils.load_providers', 'load_providers', (['self.redirectors'], {}), '(self.redirectors)\n', (293, 311), False, 'from fjord.base.plugin_utils import load_providers\n')]
# Author: <NAME> # Contributors: <NAME> import numpy as np import scipy import torch class Geometry(): """Helper class to calculate distances, angles, and dihedrals with a unified, vectorized framework depending on whether pytorch or numpy is used. Parameters ---------- method : 'torch' or 'numpy' (default='torch') Library used for compuations device : torch.device (default=torch.device('cpu')) Device upon which geometrical calculations will take place. When embedded as an attribute for a feature class, the device will inherit from the feature device attribute """ def __init__(self, method='torch', device=torch.device('cpu')): self.device = device if method not in ['torch', 'numpy']: raise RuntimeError("Allowed methods are 'torch' and 'numpy'") self.method = method # # # # # # # # # # # # # # Define any types here # # # # # # # # # # # # # # if method == 'torch': self.bool = torch.bool self.float32 = torch.float32 elif self.method == 'numpy': self.bool = np.bool self.float32 = np.float32 def check_for_nans(self, object, name=None): """This method checks an object for the presence of nans and returns an error if any nans are found. """ if name is None: name = '' if self.isnan(object).any(): raise ValueError( "Nan found in {}. Check your coordinates!)".format( name) ) def check_array_vs_tensor(self, object, name=None): """This method checks whether the object (i.e., numpy array or torch tensor) is consistent with the method chosen for the Geometry instance (i.e., 'numpy' or 'torch', respectively). """ if name is None: name = '' if self.method == 'numpy' and type(object) is not np.ndarray: raise ValueError( "Input argument {} must be type np.ndarray for Geometry(method='numpy')".format( name) ) if self.method == 'torch' and type(object) is not torch.Tensor: raise ValueError( "Input argument {} must be type torch.Tensor for Geometry(method='torch')".format( name) ) def get_distance_indices(self, n_beads, backbone_inds=[], backbone_map=None): """Determines indices of pairwise distance features. """ pair_order = [] adj_backbone_pairs = [] for increment in range(1, n_beads): for i in range(n_beads - increment): pair_order.append((i, i+increment)) if len(backbone_inds) > 0: if (backbone_map[i+increment] - backbone_map[i] == 1): adj_backbone_pairs.append((i, i+increment)) return pair_order, adj_backbone_pairs def get_redundant_distance_mapping(self, pair_order): """Reformulates pairwise distances from shape [n_frames, n_dist] to shape [n_frames, n_beads, n_neighbors] This is done by finding the index mapping between non-redundant and redundant representations of the pairwise distances. This mapping can then be supplied to Schnet-related features, such as a RadialBasisFunction() layer, which use redundant pairwise distance representations. """ pairwise_dist_inds = [zipped_pair[1] for zipped_pair in sorted( [z for z in zip(pair_order, np.arange(len(pair_order))) ]) ] map_matrix = scipy.spatial.distance.squareform(pairwise_dist_inds) map_matrix = map_matrix[~np.eye(map_matrix.shape[0], dtype=bool)].reshape( map_matrix.shape[0], -1) return map_matrix def get_vectorize_inputs(self, inds, data): """Helper function to obtain indices for vectorized calculations. """ if len(np.unique([len(feat) for feat in inds])) > 1: raise ValueError( "All features must be the same length." ) feat_length = len(inds[0]) ind_list = [[feat[i] for feat in inds] for i in range(feat_length)] dist_list = [data[:, ind_list[i+1], :] - data[:, ind_list[i], :] for i in range(feat_length - 1)] if len(dist_list) == 1: dist_list = dist_list[0] return dist_list def get_distances(self, distance_inds, data, norm=True): """Calculates distances in a vectorized fashion. """ self.check_array_vs_tensor(data, 'data') distances = self.get_vectorize_inputs(distance_inds, data) if norm: distances = self.norm(distances, axis=2) self.check_for_nans(distances, 'distances') return distances def get_angles(self, angle_inds, data, clip=True): """Calculates angles in a vectorized fashion. If clip is True (default), then the angle cosines are clipped to be between -1 and 1 to account for numerical error. """ self.check_array_vs_tensor(data, 'data') base, offset = self.get_vectorize_inputs(angle_inds, data) # This convention assumes that the middle index of the angle triplet # is the angle vertex. Scalar multiplication of the first vector # of the angle triplet by -1 means that the vertex point is # subtracted from the non-vertex point for the first vector. # This ensures that the arccos operation returns the acute angle # at the vertex. See test_geometry_features for a non-parallel # formulation. base *= -1 angles = self.sum(base * offset, axis=2) / self.norm(base, axis=2) / self.norm( offset, axis=2) if clip: # Clipping to prevent the arccos to be NaN angles = self.arccos(self.clip(angles, lower_bound=-1., upper_bound=1.)) self.check_for_nans(angles, 'angles') return angles def get_dihedrals(self, dihed_inds, data): """Calculates dihedrals in a vectorized fashion. Note ---- This is implemented in a hacky/bad way. It calculates twice as many dihedrals as needed and removes every other one. There is a better way to do this, I think using two lists of angles, but for now this has the correct functionality. """ self.check_array_vs_tensor(data, 'data') angle_inds = np.concatenate([[(f[i], f[i+1], f[i+2]) for i in range(2)] for f in dihed_inds]) base, offset = self.get_vectorize_inputs(angle_inds, data) offset_2 = base[:, 1:] cross_product_adj = self.cross(base, offset, axis=2) cp_base = cross_product_adj[:, :-1, :] cp_offset = cross_product_adj[:, 1:, :] plane_vector = self.cross(cp_offset, offset_2, axis=2) dihedral_cosines = self.sum(cp_base[:, ::2]*cp_offset[:, ::2], axis=2)/self.norm( cp_base[:, ::2], axis=2)/self.norm(cp_offset[:, ::2], axis=2) dihedral_sines = self.sum(cp_base[:, ::2]*plane_vector[:, ::2], axis=2)/self.norm( cp_base[:, ::2], axis=2)/self.norm(plane_vector[:, ::2], axis=2) dihedral_rad = self.arctan(dihedral_sines / dihedral_cosines) #dihedral_rad = self.arccos(dihedral_cosines) #dihedral_rad = self.arccos(self.clip(dihedral_cosines, # lower_bound=-1., # upper_bound=1.)) self.check_for_nans(dihedral_rad, 'dihedral') return dihedral_rad def get_neighbors(self, distances, cutoff=None): """Calculates a simple neighbor list in which every bead sees each other. If a cutoff is specified, only beads inside that distance cutoff are considered as neighbors. Parameters ---------- distances: torch.Tensor or np.array Redundant distance matrix of shape (n_frames, n_beads, n_neighbors). cutoff: float (default=None) Distance cutoff in Angstrom in which beads are considered neighbors. Returns ------- neighbors: torch.Tensor or np.array Indices of all neighbors of each bead. This is not affected by the mask. Shape [n_frames, n_beads, n_neighbors] neighbor_mask: torch.Tensor or np.array Index mask to filter out non-existing neighbors that were introduced to due distance cutoffs. Shape [n_frames, n_beads, n_neighbors] """ self.check_array_vs_tensor(distances, 'distances') n_frames, n_beads, n_neighbors = distances.shape # Create a simple neighbor list of shape [n_frames, n_beads, n_neighbors] # in which every bead sees each other but themselves. # First, create a matrix that contains all indices. neighbors = self.tile(self.arange(n_beads), (n_frames, n_beads, 1)) # To remove the self interaction of beads, an inverted identity matrix # is used to exclude the respective indices in the neighbor list. neighbors = neighbors[:, ~self.eye(n_beads, dtype=self.bool)].reshape( n_frames, n_beads, n_neighbors) if cutoff is not None: # Create an index mask for neighbors that are inside the cutoff neighbor_mask = distances < cutoff neighbor_mask = self.to_type(neighbor_mask, self.float32) else: neighbor_mask = self.ones((n_frames, n_beads, n_neighbors), dtype=self.float32) return neighbors, neighbor_mask def _torch_eye(self, n, dtype): if dtype == torch.bool: # Only in pytorch>=1.2! return torch.BoolTensor(np.eye(n, dtype=np.bool)) else: return torch.eye(n, dtype=dtype) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Versatile Methods # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # The methods implemented below should modify the originals as little as # possible, such that the documentation for the respective method on the # numpy and pytorch websites should be sufficient. # Methods defined: arccos, cross, norm, sum, arange, tile, eye, ones, # to_type, clip, isnan def arccos(self, x): if self.method == 'torch': return torch.acos(x) elif self.method == 'numpy': return np.arccos(x) def arctan(self, x): if self.method == 'torch': return torch.atan(x) elif self.method == 'numpy': return np.arctan(x) def cross(self, x, y, axis): if self.method == 'torch': return torch.cross(x, y, dim=axis) elif self.method == 'numpy': return np.cross(x, y, axis=axis) def norm(self, x, axis): if self.method == 'torch': return torch.norm(x, dim=axis) elif self.method == 'numpy': return np.linalg.norm(x, axis=axis) def sum(self, x, axis): if self.method == 'torch': return torch.sum(x, dim=axis) elif self.method == 'numpy': return np.sum(x, axis=axis) def arange(self, n): if self.method == 'torch': return torch.arange(n) elif self.method == 'numpy': return np.arange(n) def tile(self, x, shape): if self.method == 'torch': return x.repeat(*shape) elif self.method == 'numpy': return np.tile(x, shape) def eye(self, n, dtype): # As of pytorch 1.2.0, BoolTensors are implemented. However, # torch.eye does not take dtype=torch.bool on CPU devices yet. # Watch pytorch PR #24148 for the implementation, which would # allow us to return torch.eye(n, dtype=dtype) # For now, we do this: if self.method == 'torch': return self._torch_eye(n, dtype).to(self.device) elif self.method == 'numpy': return np.eye(n, dtype=dtype) def ones(self, shape, dtype): if self.method == 'torch': return torch.ones(*shape, dtype=dtype).to(self.device) elif self.method == 'numpy': return np.ones(shape, dtype=dtype) def to_type(self, x, dtype): if self.method == 'torch': return x.type(dtype) elif self.method == 'numpy': return x.astype(dtype) def clip(self, x, lower_bound, upper_bound, out=None): if self.method == 'torch': return torch.clamp(x, min=lower_bound, max=upper_bound, out=out) elif self.method == 'numpy': return np.clip(x, a_min=lower_bound, a_max=upper_bound, out=out) def isnan(self, x): if self.method == 'torch': return torch.isnan(x) elif self.method == 'numpy': return np.isnan(x)
[ "numpy.clip", "numpy.arccos", "torch.sum", "numpy.linalg.norm", "numpy.arange", "torch.arange", "numpy.cross", "torch.eye", "torch.acos", "numpy.arctan", "numpy.tile", "numpy.eye", "scipy.spatial.distance.squareform", "numpy.ones", "torch.norm", "numpy.isnan", "torch.atan", "torch....
[((686, 705), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (698, 705), False, 'import torch\n'), ((3751, 3804), 'scipy.spatial.distance.squareform', 'scipy.spatial.distance.squareform', (['pairwise_dist_inds'], {}), '(pairwise_dist_inds)\n', (3784, 3804), False, 'import scipy\n'), ((10447, 10472), 'torch.eye', 'torch.eye', (['n'], {'dtype': 'dtype'}), '(n, dtype=dtype)\n', (10456, 10472), False, 'import torch\n'), ((11117, 11130), 'torch.acos', 'torch.acos', (['x'], {}), '(x)\n', (11127, 11130), False, 'import torch\n'), ((11280, 11293), 'torch.atan', 'torch.atan', (['x'], {}), '(x)\n', (11290, 11293), False, 'import torch\n'), ((11451, 11478), 'torch.cross', 'torch.cross', (['x', 'y'], {'dim': 'axis'}), '(x, y, dim=axis)\n', (11462, 11478), False, 'import torch\n'), ((11645, 11668), 'torch.norm', 'torch.norm', (['x'], {'dim': 'axis'}), '(x, dim=axis)\n', (11655, 11668), False, 'import torch\n'), ((11837, 11859), 'torch.sum', 'torch.sum', (['x'], {'dim': 'axis'}), '(x, dim=axis)\n', (11846, 11859), False, 'import torch\n'), ((12017, 12032), 'torch.arange', 'torch.arange', (['n'], {}), '(n)\n', (12029, 12032), False, 'import torch\n'), ((13288, 13345), 'torch.clamp', 'torch.clamp', (['x'], {'min': 'lower_bound', 'max': 'upper_bound', 'out': 'out'}), '(x, min=lower_bound, max=upper_bound, out=out)\n', (13299, 13345), False, 'import torch\n'), ((13539, 13553), 'torch.isnan', 'torch.isnan', (['x'], {}), '(x)\n', (13550, 13553), False, 'import torch\n'), ((10388, 10412), 'numpy.eye', 'np.eye', (['n'], {'dtype': 'np.bool'}), '(n, dtype=np.bool)\n', (10394, 10412), True, 'import numpy as np\n'), ((11187, 11199), 'numpy.arccos', 'np.arccos', (['x'], {}), '(x)\n', (11196, 11199), True, 'import numpy as np\n'), ((11350, 11362), 'numpy.arctan', 'np.arctan', (['x'], {}), '(x)\n', (11359, 11362), True, 'import numpy as np\n'), ((11535, 11560), 'numpy.cross', 'np.cross', (['x', 'y'], {'axis': 'axis'}), '(x, y, axis=axis)\n', (11543, 11560), True, 'import numpy as np\n'), ((11725, 11753), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {'axis': 'axis'}), '(x, axis=axis)\n', (11739, 11753), True, 'import numpy as np\n'), ((11916, 11936), 'numpy.sum', 'np.sum', (['x'], {'axis': 'axis'}), '(x, axis=axis)\n', (11922, 11936), True, 'import numpy as np\n'), ((12089, 12101), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (12098, 12101), True, 'import numpy as np\n'), ((12260, 12277), 'numpy.tile', 'np.tile', (['x', 'shape'], {}), '(x, shape)\n', (12267, 12277), True, 'import numpy as np\n'), ((12756, 12778), 'numpy.eye', 'np.eye', (['n'], {'dtype': 'dtype'}), '(n, dtype=dtype)\n', (12762, 12778), True, 'import numpy as np\n'), ((12972, 12999), 'numpy.ones', 'np.ones', (['shape'], {'dtype': 'dtype'}), '(shape, dtype=dtype)\n', (12979, 12999), True, 'import numpy as np\n'), ((13402, 13459), 'numpy.clip', 'np.clip', (['x'], {'a_min': 'lower_bound', 'a_max': 'upper_bound', 'out': 'out'}), '(x, a_min=lower_bound, a_max=upper_bound, out=out)\n', (13409, 13459), True, 'import numpy as np\n'), ((13610, 13621), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (13618, 13621), True, 'import numpy as np\n'), ((12868, 12899), 'torch.ones', 'torch.ones', (['*shape'], {'dtype': 'dtype'}), '(*shape, dtype=dtype)\n', (12878, 12899), False, 'import torch\n'), ((3838, 3877), 'numpy.eye', 'np.eye', (['map_matrix.shape[0]'], {'dtype': 'bool'}), '(map_matrix.shape[0], dtype=bool)\n', (3844, 3877), True, 'import numpy as np\n')]
from django.contrib.auth import get_user_model from django.test.client import RequestFactory from core.models import Person import random import string def random_user(): user = get_user_model().objects.create_user( ''.join(random.choice(string.lowercase) for _ in range(12))) person = Person.objects.create(user=user) return user def mock_req(path='/', user = None): """ Mock request -- with user! """ if not user: user = random_user() req = RequestFactory().get(path) req.user = user return req
[ "random.choice", "django.contrib.auth.get_user_model", "core.models.Person.objects.create", "django.test.client.RequestFactory" ]
[((307, 339), 'core.models.Person.objects.create', 'Person.objects.create', ([], {'user': 'user'}), '(user=user)\n', (328, 339), False, 'from core.models import Person\n'), ((498, 514), 'django.test.client.RequestFactory', 'RequestFactory', ([], {}), '()\n', (512, 514), False, 'from django.test.client import RequestFactory\n'), ((183, 199), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (197, 199), False, 'from django.contrib.auth import get_user_model\n'), ((241, 272), 'random.choice', 'random.choice', (['string.lowercase'], {}), '(string.lowercase)\n', (254, 272), False, 'import random\n')]
#!/usr/bin/env python # coding=utf-8 """ neoepiscope Identifies neoepitopes from DNA-seq, VCF, GTF, and Bowtie index. The MIT License (MIT) Copyright (c) 2018 <NAME>, <NAME>, <NAME>, and <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import, division, print_function import argparse from . import bowtie_index import sys import string import copy import pickle import copy import random import re import os import collections import tempfile import subprocess import warnings from . import paths from .transcript import ( Transcript, gtf_to_cds, cds_to_tree, get_transcripts_from_tree, process_haplotypes, get_peptides_from_transcripts, ) from .binding_scores import gather_binding_scores from .file_processing import ( adjust_tumor_column, combine_vcf, prep_hapcut_output, which, get_vaf_pos, write_results, ) from operator import itemgetter from intervaltree import Interval, IntervalTree _help_intro = ( """neoepiscope searches for neoepitopes using tumor/normal DNA-seq data.""" ) def help_formatter(prog): """ So formatter_class's max_help_position can be changed. """ return argparse.HelpFormatter(prog, max_help_position=40) def main(): """ Entry point for neoepiscope software """ parser = argparse.ArgumentParser( description=_help_intro, formatter_class=help_formatter ) subparsers = parser.add_subparsers( help=( 'subcommands; add "-h" or "--help" ' "after a subcommand for its parameters" ), dest="subparser_name", ) index_parser = subparsers.add_parser( "index", help=( "produces pickled dictionaries " "linking transcripts to intervals and " " CDS lines in a GTF" ), ) swap_parser = subparsers.add_parser( "swap", help=( "swaps tumor and normal columns " "in a somatic vcf if necessary for " "proper HapCUT2 results" ), ) merge_parser = subparsers.add_parser( "merge", help=( "merges germline and somatic " "VCFS for combined mutation " "phasing with HAPCUT2" ), ) download_parser = subparsers.add_parser("download", help="downloads dependencies") prep_parser = subparsers.add_parser( "prep", help=("combines HAPCUT2 output with unphased variants for call mode") ) call_parser = subparsers.add_parser("call", help="calls neoepitopes") # Index parser options (produces pickled dictionaries for transcript data) index_parser.add_argument( "-g", "--gtf", type=str, required=True, help="input path to GTF file" ) index_parser.add_argument( "-d", "--dicts", type=str, required=True, help="output path to pickled CDS dictionary directory", ) # Swap parser options (swaps columns in somatic VCF) swap_parser.add_argument( "-i", "--input", type=str, required=True, help="input path to somatic VCF" ) swap_parser.add_argument( "-o", "--output", type=str, required=False, default="-", help="output path to column-swapped VCF; use - for stdout", ) # Merger parser options (merges somatic and germline VCFs) merge_parser.add_argument( "-g", "--germline", type=str, required=True, help="input path to germline VCF" ) merge_parser.add_argument( "-s", "--somatic", type=str, required=True, help="input path to somatic VCF" ) merge_parser.add_argument( "-o", "--output", type=str, required=False, default="-", help="output path to combined VCF; use - for stdout", ) merge_parser.add_argument( "-t", "--tumor-id", type=str, required=False, default="TUMOR", help="tumor ID (matching the sample in your tumor BAM file " "if using GATK ReadBackedPhasing)", ) # Prep parser options (adds unphased mutations as their own haplotype) prep_parser.add_argument("-v", "--vcf", type=str, required=True, help="input VCF") prep_parser.add_argument( "-c", "--hapcut2-output", type=str, required=False, help="path to output file of HAPCUT2 run on input VCF", ) prep_parser.add_argument( "-o", "--output", type=str, required=False, default="-", help="path to output file to be input to call mode; use - for stdout", ) prep_parser.add_argument( "-p", "--phased", required=False, action="store_true", help="indicates that input VCF is phased using GATK ReadBackedPhasing", ) # Call parser options (calls neoepitopes) call_parser.add_argument( "-x", "--bowtie-index", type=str, required=False, help="path to Bowtie index basename", ) call_parser.add_argument( "-v", "--vcf", type=str, required=False, help="input path to VCF" ) call_parser.add_argument( "-d", "--dicts", type=str, required=False, help="input path to pickled CDS dictionary directory", ) call_parser.add_argument( "-c", "--merged-hapcut2-output", type=str, required=False, default="-", help="path to output of prep subcommand; use - for stdin", ) call_parser.add_argument( "-k", "--kmer-size", type=str, required=False, default="8,11", help="kmer size for epitope calculation", ) call_parser.add_argument( "-p", "--affinity-predictor", type=str, nargs=3, required=False, action="append", default=[["mhcflurry", "1", "affinity,rank"]], help="binding affinity prediction software," "associated version number, and scoring method(s) " "(e.g. -p netMHCpan 4 rank,affinity); " "for multiple programs, repeat the argument; " "see documentation for details", ) call_parser.add_argument( "-n", "--no-affinity", required=False, action="store_true", help="do not run binding affinity predictions; overrides any " "binding affinity prediction tools specified via " "--affinity-predictor option", ) call_parser.add_argument( "-a", "--alleles", type=str, required=False, help="comma separated list of alleles; " "see documentation online for more information", ) call_parser.add_argument( "-o", "--output", type=str, required=False, default="-", help="path to output file; use - for stdout", ) call_parser.add_argument( "-f", "--fasta", required=False, action="store_true", help="produce additional fasta output; see documentation", ) call_parser.add_argument( "-u", "--upstream-atgs", type=str, required=False, default="none", help="how to handle upstream start codons, see " "documentation online for more information", ) call_parser.add_argument( "-g", "--germline", type=str, required=False, default="background", help="how to handle germline mutations in " "neoepitope enumeration; documentation online for more information", ) call_parser.add_argument( "-s", "--somatic", type=str, required=False, default="include", help="how to handle somatic mutations in " "neoepitope enumeration; documentation online for more information", ) call_parser.add_argument( "-b", "--build", type=str, required=False, help="which default genome build to use (hg19 or GRCh38); " "must have used download.py script to install these", ) call_parser.add_argument( "-i", "--isolate", required=False, action="store_true", help="isolate mutations - do not use phasing information to " "combine nearby mutations in the same neoepitope", ) call_parser.add_argument( "-r", "--rna-bam", type=str, required=False, help="path to tumor RNA-seq BAM alignment file") call_parser.add_argument( "--nmd", required=False, action="store_true", default=False, help="enumerate neoepitopes from nonsense mediated decay transcripts", ) call_parser.add_argument( "--pp", required=False, action="store_true", default=False, help="enumerate neoepitopes from polymorphic pseudogene transcripts", ) call_parser.add_argument( "--igv", required=False, action="store_true", default=False, help="enumerate neoepitopes IGV transcripts", ) call_parser.add_argument( "--trv", required=False, action="store_true", default=False, help="enumerate neoepitopes from TRV transcripts", ) call_parser.add_argument( "--allow-nonstart", required=False, action="store_true", default=False, help="enumerate neoepitopes from transcripts without annotated start codons", ) call_parser.add_argument( "--allow-nonstop", required=False, action="store_true", default=False, help="enumerate neoepitopes from transcripts without annotated stop codons", ) args = parser.parse_args() if args.subparser_name == "download": from .download import NeoepiscopeDownloader downloader = NeoepiscopeDownloader() downloader.run() elif args.subparser_name == "index": cds_dict = gtf_to_cds(args.gtf, args.dicts) tree = cds_to_tree(cds_dict, args.dicts) elif args.subparser_name == "swap": adjust_tumor_column(args.input, args.output) elif args.subparser_name == "merge": combine_vcf(args.germline, args.somatic, outfile=args.output, tumor_id=args.tumor_id) elif args.subparser_name == "prep": prep_hapcut_output(args.output, args.hapcut2_output, args.vcf, args.phased) elif args.subparser_name == "call": # Check that output options are compatible if args.fasta and args.output == "-": sys.exit( "Cannot write fasta results when writing output to standard out; " "please specify an output file using the -o/--output option when " "using the -f/--fasta flag" ) # Load pickled dictionaries and prepare bowtie index if args.build is not None: if ( args.build == "GRCh38" and paths.gencode_v29 is not None and paths.bowtie_grch38 is not None ): with open( os.path.join(paths.gencode_v29, "intervals_to_transcript.pickle"), "rb", ) as interval_stream: interval_dict = pickle.load(interval_stream) with open( os.path.join(paths.gencode_v29, "transcript_to_CDS.pickle"), "rb" ) as cds_stream: cds_dict = pickle.load(cds_stream) reference_index = bowtie_index.BowtieIndexReference(paths.bowtie_grch38) elif ( args.build == "hg19" and paths.gencode_v19 is not None and paths.bowtie_hg19 is not None ): with open( os.path.join(paths.gencode_v19, "intervals_to_transcript.pickle"), "rb", ) as interval_stream: interval_dict = pickle.load(interval_stream) with open( os.path.join(paths.gencode_v19, "transcript_to_CDS.pickle"), "rb" ) as cds_stream: cds_dict = pickle.load(cds_stream) reference_index = bowtie_index.BowtieIndexReference(paths.bowtie_hg19) else: raise RuntimeError( "".join( [ args.build, " is not an available genome build. Please " "check that you have run neoepiscope download and are " "using 'hg19' or 'GRCh38' for this argument.", ] ) ) else: if args.bowtie_index is not None and args.dicts is not None: intervals_path = os.path.join( args.dicts, "intervals_to_transcript.pickle" ) if os.path.isfile(intervals_path): with open(intervals_path, "rb") as interval_stream: interval_dict = pickle.load(interval_stream) else: raise RuntimeError( "".join( [ "Cannot find ", intervals_path, "; have you indexed your GTF with neoepiscope index?", ] ) ) cds_path = os.path.join(args.dicts, "transcript_to_CDS.pickle") if os.path.isfile(cds_path): with open(cds_path, "rb") as cds_stream: cds_dict = pickle.load(cds_stream) else: raise RuntimeError( "".join( [ "Cannot find ", cds_path, "; have you indexed your GTF with neoepiscope index?", ] ) ) bowtie_files = [ "".join([args.bowtie_index, ".", str(x), ".ebwt"]) for x in range(1, 5) ] if list(set([os.path.isfile(x) for x in bowtie_files])) == [True]: reference_index = bowtie_index.BowtieIndexReference( args.bowtie_index ) else: raise RuntimeError("Cannot find specified bowtie index") else: raise RuntimeError( "User must specify either --build OR " "--bowtie_index and --dicts options" ) # Check affinity predictor tool_dict = {} if args.no_affinity: args.affinity_predictor = None if args.affinity_predictor is not None: if len(args.affinity_predictor) > 1: args.affinity_predictor.remove(["mhcflurry", "1", "affinity,rank"]) for tool in args.affinity_predictor: program = tool[0] version = tool[1] scoring = tool[2].split(",") if "mhcflurry" in program.lower(): if version == "1" and "mhcflurry1" not in tool_dict: program = "mhcflurry-predict" acceptable_scoring = ["rank", "affinity", "high", "low"] for method in scoring: if method not in acceptable_scoring: warnings.warn( " ".join([method, "not compatible with mhcflurry"]), Warning, ) scoring.remove(method) if len(scoring) > 0: tool_dict["mhcflurry1"] = [program, sorted(scoring)] elif "mhcflurry1" in tool_dict: raise RuntimeError( "Conflicting or repetitive installs of mhcflurry given" ) else: raise NotImplementedError( " ".join( [ "neoepiscope does not support version", version, "of mhcflurry", ] ) ) elif "mhcnuggets" in program.lower(): if version == "2" and "mhcnuggets2" not in tool_dict: program = "NA" acceptable_scoring = ["affinity"] for method in scoring: if method not in acceptable_scoring: warnings.warn( " ".join( [method, "not compatible with mhcnuggets"] ), Warning, ) scoring.remove(method) if len(scoring) > 0: tool_dict["mhcnuggets2"] = [program, sorted(scoring)] elif "mhcnuggets2" in tool_dict: raise RuntimeError( "Conflicting or repetitive installs of mhcnuggets given" ) else: raise NotImplementedError( " ".join( [ "neoepiscope does not support version", version, "of mhcnuggets", ] ) ) elif "netMHCIIpan" in program: if version == "3" and "netMHCIIpan3" not in tool_dict: program = paths.netMHCIIpan3 if program is None: program = which("netMHCIIpan3") else: program = which(program) if program is None: warnings.warn( " ".join( ["No valid install of", "netMHCIIpan available"] ), Warning, ) continue acceptable_scoring = ["rank", "affinity"] for method in scoring: if method not in acceptable_scoring: warnings.warn( " ".join( [method, "not compatible with netMHCIIpan"] ), Warning, ) scoring.remove(method) if len(scoring) > 0: tool_dict["netMHCIIpan3"] = [program, sorted(scoring)] elif "netMHCIIpan3" in tool_dict: raise RuntimeError( "Conflicting or repetitive installs of netMHCIIpan given" ) else: raise NotImplementedError( " ".join( [ "neoepiscope does not support version", version, "of netMHCIIpan", ] ) ) elif "netMHCpan" in program: if ("netMHCpan3" not in tool_dict and version == "3") or ( "netMHCpan4" not in tool_dict and version == "4" ): if version == "3": program = paths.netMHCpan3 if program is None: program = which("netMHCpan3") else: program = which(program) elif version == "4": program = paths.netMHCpan4 if program is None: program = which("netMHCpan4") else: program = which(program) if program is None: warnings.warn( " ".join( ["No valid install of ", "netMHCIIpan available"] ), Warning, ) continue if program is None: warnings.warn( " ".join( [ "No valid install of", "netMHCpan version", version, "available", ] ), Warning, ) continue acceptable_scoring = ["rank", "affinity"] for method in scoring: if method not in acceptable_scoring: warnings.warn( " ".join([method, "not compatible with netMHCpan"]), Warning, ) scoring.remove(method) if len(scoring) > 0: if version == "3": name = "netMHCpan3" elif version == "4": name = "netMHCpan4" tool_dict[name] = [program, sorted(scoring)] elif ("netMHCpan3" in tool_dict and version == "3") or ( "netMHCpan4" in tool_dict and version == "4" ): raise RuntimeError( "Conflicting or repetitive installs of netMHCpan given" ) else: raise NotImplementedError( " ".join( [ "neoepiscope does not support version", version, "of netMHCpan", ] ) ) else: raise NotImplementedError( " ".join( [ "neoepiscope does not support", program, "for binding predictions", ] ) ) if not tool_dict: warnings.warn( "No binding prediction tools specified; " "will proceed without binding predictions", Warning, ) hla_alleles = [] else: if args.alleles: hla_alleles = sorted(args.alleles.split(",")) else: raise RuntimeError( "To perform binding affinity predictions, " "user must specify at least one allele " "via the --alleles option" ) # Obtain VAF frequency VCF position if args.vcf: vaf_pos = get_vaf_pos(args.vcf) else: vaf_pos = None # Obtain peptide sizes for kmerizing peptides if "," in args.kmer_size: size_list = args.kmer_size.split(",") size_list.sort(reverse=True) for i in range(0, len(size_list)): size_list[i] = int(size_list[i]) else: size_list = [int(args.kmer_size)] # Establish handling of ATGs if args.upstream_atgs == "none": only_novel_upstream = False only_downstream = True only_reference = False elif args.upstream_atgs == "novel": only_novel_upstream = True only_downstream = False only_reference = False elif args.upstream_atgs == "all": only_novel_upstream = False only_downstream = False only_reference = False elif args.upstream_atgs == "reference": only_novel_upstream = False only_downstream = False only_reference = True else: raise RuntimeError( "--upstream-atgs must be one of " '{"novel", "all", "none", "reference"}' ) # Establish handling of germline mutations: if args.germline == "background": include_germline = 2 elif args.germline == "include": include_germline = 1 elif args.germline == "exclude": include_germline = 0 else: raise RuntimeError( "--germline must be one of " '{"background", "include", "exclude"}' ) # Establish handling of somatic mutations: if args.somatic == "include": include_somatic = 1 elif args.somatic == "background": include_somatic = 2 elif args.somatic == "exclude": include_somatic = 0 else: raise RuntimeError( "--somatic must be one of " '{"background", "include", "exclude"}' ) # Warn if somatic and germline are both excluded if include_somatic == 0 and include_germline == 0: warnings.warn( "Germline and somatic mutations are both being " "excluded, no epitopes will be returned", Warning, ) if not args.isolate: phase_mutations = True else: phase_mutations = False # Find transcripts that haplotypes overlap relevant_transcripts, homozygous_variants = process_haplotypes( args.merged_hapcut2_output, interval_dict, phase_mutations ) # Apply mutations to transcripts and get neoepitopes neoepitopes, fasta = get_peptides_from_transcripts( relevant_transcripts, homozygous_variants, vaf_pos, cds_dict, only_novel_upstream, only_downstream, only_reference, reference_index, size_list, args.nmd, args.pp, args.igv, args.trv, args.allow_nonstart, args.allow_nonstop, include_germline, include_somatic, protein_fasta=args.fasta, ) # If neoepitopes are found, get binding scores and write results if len(neoepitopes) > 0: full_neoepitopes = gather_binding_scores( neoepitopes, tool_dict, hla_alleles ) write_results(args.output, hla_alleles, full_neoepitopes, tool_dict) if args.fasta: fasta_file = "".join([args.output, ".fasta"]) with open(fasta_file, "w") as f: for tx in fasta: proteins = sorted(list(fasta[tx])) for i in range(0, len(proteins)): identifier = "".join([">", tx, "_v", str(i)]) print(identifier, file=f) print(proteins[i], file=f) else: print("No neoepitopes found", file=sys.stderr) else: parser.print_usage() if __name__ == "__main__": main()
[ "argparse.ArgumentParser", "argparse.HelpFormatter", "os.path.join", "pickle.load", "os.path.isfile", "sys.exit", "warnings.warn" ]
[((2259, 2309), 'argparse.HelpFormatter', 'argparse.HelpFormatter', (['prog'], {'max_help_position': '(40)'}), '(prog, max_help_position=40)\n', (2281, 2309), False, 'import argparse\n'), ((2391, 2476), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '_help_intro', 'formatter_class': 'help_formatter'}), '(description=_help_intro, formatter_class=help_formatter\n )\n', (2414, 2476), False, 'import argparse\n'), ((12010, 12185), 'sys.exit', 'sys.exit', (['"""Cannot write fasta results when writing output to standard out; please specify an output file using the -o/--output option when using the -f/--fasta flag"""'], {}), "(\n 'Cannot write fasta results when writing output to standard out; please specify an output file using the -o/--output option when using the -f/--fasta flag'\n )\n", (12018, 12185), False, 'import sys\n'), ((25502, 25617), 'warnings.warn', 'warnings.warn', (['"""No binding prediction tools specified; will proceed without binding predictions"""', 'Warning'], {}), "(\n 'No binding prediction tools specified; will proceed without binding predictions'\n , Warning)\n", (25515, 25617), False, 'import warnings\n'), ((28388, 28508), 'warnings.warn', 'warnings.warn', (['"""Germline and somatic mutations are both being excluded, no epitopes will be returned"""', 'Warning'], {}), "(\n 'Germline and somatic mutations are both being excluded, no epitopes will be returned'\n , Warning)\n", (28401, 28508), False, 'import warnings\n'), ((14365, 14423), 'os.path.join', 'os.path.join', (['args.dicts', '"""intervals_to_transcript.pickle"""'], {}), "(args.dicts, 'intervals_to_transcript.pickle')\n", (14377, 14423), False, 'import os\n'), ((14484, 14514), 'os.path.isfile', 'os.path.isfile', (['intervals_path'], {}), '(intervals_path)\n', (14498, 14514), False, 'import os\n'), ((15083, 15135), 'os.path.join', 'os.path.join', (['args.dicts', '"""transcript_to_CDS.pickle"""'], {}), "(args.dicts, 'transcript_to_CDS.pickle')\n", (15095, 15135), False, 'import os\n'), ((15156, 15180), 'os.path.isfile', 'os.path.isfile', (['cds_path'], {}), '(cds_path)\n', (15170, 15180), False, 'import os\n'), ((12743, 12771), 'pickle.load', 'pickle.load', (['interval_stream'], {}), '(interval_stream)\n', (12754, 12771), False, 'import pickle\n'), ((12953, 12976), 'pickle.load', 'pickle.load', (['cds_stream'], {}), '(cds_stream)\n', (12964, 12976), False, 'import pickle\n'), ((12573, 12638), 'os.path.join', 'os.path.join', (['paths.gencode_v29', '"""intervals_to_transcript.pickle"""'], {}), "(paths.gencode_v29, 'intervals_to_transcript.pickle')\n", (12585, 12638), False, 'import os\n'), ((12821, 12880), 'os.path.join', 'os.path.join', (['paths.gencode_v29', '"""transcript_to_CDS.pickle"""'], {}), "(paths.gencode_v29, 'transcript_to_CDS.pickle')\n", (12833, 12880), False, 'import os\n'), ((13462, 13490), 'pickle.load', 'pickle.load', (['interval_stream'], {}), '(interval_stream)\n', (13473, 13490), False, 'import pickle\n'), ((13672, 13695), 'pickle.load', 'pickle.load', (['cds_stream'], {}), '(cds_stream)\n', (13683, 13695), False, 'import pickle\n'), ((14630, 14658), 'pickle.load', 'pickle.load', (['interval_stream'], {}), '(interval_stream)\n', (14641, 14658), False, 'import pickle\n'), ((15280, 15303), 'pickle.load', 'pickle.load', (['cds_stream'], {}), '(cds_stream)\n', (15291, 15303), False, 'import pickle\n'), ((13292, 13357), 'os.path.join', 'os.path.join', (['paths.gencode_v19', '"""intervals_to_transcript.pickle"""'], {}), "(paths.gencode_v19, 'intervals_to_transcript.pickle')\n", (13304, 13357), False, 'import os\n'), ((13540, 13599), 'os.path.join', 'os.path.join', (['paths.gencode_v19', '"""transcript_to_CDS.pickle"""'], {}), "(paths.gencode_v19, 'transcript_to_CDS.pickle')\n", (13552, 13599), False, 'import os\n'), ((15870, 15887), 'os.path.isfile', 'os.path.isfile', (['x'], {}), '(x)\n', (15884, 15887), False, 'import os\n')]
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import os from setuptools import setup, find_packages def read(file_name): return open(os.path.join(os.path.dirname(__file__), file_name)).read() setup( name="hb_downloader", # your package name (i.e. for import) version="0.7.0", maintainer="<NAME>", maintainer_email="<EMAIL>", author="<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>", author_email="N/A, <EMAIL>, N/A, N/A, N/A, <EMAIL>", description="An automated utility to download your Humble Bundle purchases.", license="MIT", keywords="humble bundle download games", url="https://github.com/MKindy/hb-downloader", packages=find_packages(exclude=["*test*", "*TEST*"]), install_requires=[ 'requests', 'pyyaml', 'lxml' ], long_description=read('README.md'), classifiers=[ "Development Status :: 4 - Beta", "Topic :: Utilities", "License :: OSI Approved :: MIT", "Natural Language :: English" ], zip_safe=True, )
[ "os.path.dirname", "setuptools.find_packages" ]
[((678, 721), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['*test*', '*TEST*']"}), "(exclude=['*test*', '*TEST*'])\n", (691, 721), False, 'from setuptools import setup, find_packages\n'), ((153, 178), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (168, 178), False, 'import os\n')]
import ui, console import os import math def save_action(sender): with open('image_file.png', 'wb') as fp: fp.write(img.to_png()) console.hud_alert('image saved in the file image_file.png') def showimage_action(sender): img.show() def create_image(): img = None with ui.ImageContext(500, 500) as ctx: path = ui.Path.oval(50,50,400, 100) ui.set_color((1.0, 0.4, 0.4, 1.0)) path.fill() path.line_width = 10.0 ui.set_color((0.8, 1.0, 0.5, 1.0)) path.stroke() ui.draw_string('Label', rect=(50,175,400,100), font=tuple(('Georgia', 20)), color=(0.4, 0.6, 1.0, 1.0), alignment=0, line_break_mode=4) ui.Image("Dog_Face").draw(50,200,300,300) img = ctx.get_image() return img img = create_image() #img.show() main_view = ui.View(frame=(0,0,500,500)) imgview = ui.ImageView(frame=(0,0,500,500)) imgview.image = img main_view.add_subview(imgview) save_button = ui.ButtonItem() save_button.title = 'Save' save_button.action = save_action show_button = ui.ButtonItem() show_button.title = 'Show' show_button.action = showimage_action main_view.right_button_items = [save_button, show_button] main_view.present('sheet')
[ "console.hud_alert", "ui.Image", "ui.ImageContext", "ui.Path.oval", "ui.View", "ui.ImageView", "ui.ButtonItem", "ui.set_color" ]
[((887, 918), 'ui.View', 'ui.View', ([], {'frame': '(0, 0, 500, 500)'}), '(frame=(0, 0, 500, 500))\n', (894, 918), False, 'import ui, console\n'), ((926, 962), 'ui.ImageView', 'ui.ImageView', ([], {'frame': '(0, 0, 500, 500)'}), '(frame=(0, 0, 500, 500))\n', (938, 962), False, 'import ui, console\n'), ((1025, 1040), 'ui.ButtonItem', 'ui.ButtonItem', ([], {}), '()\n', (1038, 1040), False, 'import ui, console\n'), ((1115, 1130), 'ui.ButtonItem', 'ui.ButtonItem', ([], {}), '()\n', (1128, 1130), False, 'import ui, console\n'), ((147, 206), 'console.hud_alert', 'console.hud_alert', (['"""image saved in the file image_file.png"""'], {}), "('image saved in the file image_file.png')\n", (164, 206), False, 'import ui, console\n'), ((303, 328), 'ui.ImageContext', 'ui.ImageContext', (['(500)', '(500)'], {}), '(500, 500)\n', (318, 328), False, 'import ui, console\n'), ((356, 386), 'ui.Path.oval', 'ui.Path.oval', (['(50)', '(50)', '(400)', '(100)'], {}), '(50, 50, 400, 100)\n', (368, 386), False, 'import ui, console\n'), ((393, 427), 'ui.set_color', 'ui.set_color', (['(1.0, 0.4, 0.4, 1.0)'], {}), '((1.0, 0.4, 0.4, 1.0))\n', (405, 427), False, 'import ui, console\n'), ((487, 521), 'ui.set_color', 'ui.set_color', (['(0.8, 1.0, 0.5, 1.0)'], {}), '((0.8, 1.0, 0.5, 1.0))\n', (499, 521), False, 'import ui, console\n'), ((747, 767), 'ui.Image', 'ui.Image', (['"""Dog_Face"""'], {}), "('Dog_Face')\n", (755, 767), False, 'import ui, console\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Author: USER Email: <EMAIL> Date: 2/24/2021 Basic patterns for creation of required components. """ import ast import inspect from enum import Enum from typing import Type, Any, Union from fastapi import Form from fastapi.exceptions import RequestValidationError from pydantic import BaseModel, ValidationError from pydantic.fields import ModelField, FieldInfo from modelci.utils.misc import isgeneric def _make_form_parameter(field_info: FieldInfo) -> Any: """ Converts a field from a `Pydantic` model to the appropriate `FastAPI` parameter type. Args: field_info (FieldInfo): The field information to convert. Returns: A form. """ return Form( default=field_info.default, alias=field_info.alias, title=field_info.title, description=field_info.description, gt=field_info.gt, lt=field_info.lt, le=field_info.le, min_length=field_info.min_length, max_length=field_info.max_length, regex=field_info.regex, **field_info.extra, ) def _make_form_enum(enum_cls: Type[Enum]): """ Modify an :class:`Enum` class that uses int value to accept string value member. Args: enum_cls (Type[Enum]): An enum class. Returns: Type[Enum]: the modified enum class. """ def _missing_(cls, value): for member in cls: if str(member.value) == value: # save to value -> member mapper cls._value2member_map_[value] = member return member return missing_old(value) if hasattr(enum_cls, '__form__') or all(isinstance(e.value, str) for e in enum_cls): return missing_old = getattr(enum_cls, '_missing_') setattr(enum_cls, '_missing_', classmethod(_missing_)) setattr(enum_cls, '__form__', True) return enum_cls def make_annotation(field: ModelField): """ Convert a field annotation type to form data accepted type. The method convert structural field such as `BaseModel` and `Dict` to a str. Such as the model's value is supplied as a serialized JSON string format. Such string will be converted back to a dictionary, and used for initialize previous field. """ field_outer_type = field.outer_type_ is_literal = False # check outer type if isgeneric(field_outer_type): # outer type is a generic class if field_outer_type.__origin__ is Union: # only Union is valid generic class inner_types = field_outer_type.__args__ else: return str, True else: inner_types = (field_outer_type,) field_outer_type = None # check inner types inner_types_new = list() for inner_type in inner_types: if inner_type in (str, int, float, ..., Any): # inner type of `str`, `int` and `float` will be natively used as form data value inner_types_new.append(inner_type) elif issubclass(inner_type, Enum): inner_types_new.append(_make_form_enum(inner_type)) else: # other types will be converted to string literal is_literal = True inner_types_new.append(str) if field_outer_type is None: field_outer_type = inner_types_new[0] else: # set new generic type args field_outer_type = field_outer_type.__origin__[tuple(inner_types_new)] return field_outer_type, is_literal def as_form(cls: Type[BaseModel]) -> Type[BaseModel]: """ Adds an `as_form` class method to decorated models. The `as_form` class method can be used with `FastAPI` endpoints. TODO: auto generate OpenAPI example Args: cls: The model class to decorate. Returns: The decorated class. References: * https://github.com/tiangolo/fastapi/issues/2387#issuecomment-731662551 """ literal_fields = set() new_params = list() for field in cls.__fields__.values(): annotation, is_literal = make_annotation(field) if is_literal: literal_fields.add(field.alias) new_params.append( inspect.Parameter( field.alias, inspect.Parameter.POSITIONAL_ONLY, default=_make_form_parameter(field.field_info), annotation=annotation, ) ) async def _as_form(**data): """ Create the model as a form data. """ # parse literal back to dictionary for field_alias in literal_fields: value = data.pop(field_alias, None) data[field_alias] = ast.literal_eval(str(value)) try: cls.parse_obj(data) return cls(**data) except ValidationError as exc: raise RequestValidationError(exc.raw_errors) sig = inspect.signature(_as_form) sig = sig.replace(parameters=new_params) _as_form.__signature__ = sig setattr(cls, "as_form", _as_form) return cls
[ "fastapi.Form", "modelci.utils.misc.isgeneric", "inspect.signature", "fastapi.exceptions.RequestValidationError" ]
[((741, 1042), 'fastapi.Form', 'Form', ([], {'default': 'field_info.default', 'alias': 'field_info.alias', 'title': 'field_info.title', 'description': 'field_info.description', 'gt': 'field_info.gt', 'lt': 'field_info.lt', 'le': 'field_info.le', 'min_length': 'field_info.min_length', 'max_length': 'field_info.max_length', 'regex': 'field_info.regex'}), '(default=field_info.default, alias=field_info.alias, title=field_info.\n title, description=field_info.description, gt=field_info.gt, lt=\n field_info.lt, le=field_info.le, min_length=field_info.min_length,\n max_length=field_info.max_length, regex=field_info.regex, **field_info.\n extra)\n', (745, 1042), False, 'from fastapi import Form\n'), ((2401, 2428), 'modelci.utils.misc.isgeneric', 'isgeneric', (['field_outer_type'], {}), '(field_outer_type)\n', (2410, 2428), False, 'from modelci.utils.misc import isgeneric\n'), ((4920, 4947), 'inspect.signature', 'inspect.signature', (['_as_form'], {}), '(_as_form)\n', (4937, 4947), False, 'import inspect\n'), ((4870, 4908), 'fastapi.exceptions.RequestValidationError', 'RequestValidationError', (['exc.raw_errors'], {}), '(exc.raw_errors)\n', (4892, 4908), False, 'from fastapi.exceptions import RequestValidationError\n')]
from pathlib import Path import bpy from ....library.source1.dmx.sfm.animation_set import AnimationSet from ....library.source1.dmx.sfm.film_clip import FilmClip from ....library.source1.dmx.sfm_utils import * from ....library.shared.content_providers.content_manager import ContentManager from ...shared.model_container import Source1ModelContainer from ....library.utils.math_utilities import SOURCE1_HAMMER_UNIT_TO_METERS from ....library.utils.path_utilities import find_vtx_cm from ....library.source1.dmx.sfm import open_session from ....library.source1.dmx.sfm.camera import Camera from ....blender_bindings.source1.bsp.import_bsp import BSP from ...source1.mdl.v49.import_mdl import import_model, put_into_collections def _convert_quat(quat): # return Quaternion(quat[1:] + [quat[0]]) return quat def import_gamemodel(mdl_path, scale=SOURCE1_HAMMER_UNIT_TO_METERS): mdl_path = Path(mdl_path) mld_file = ContentManager().find_file(mdl_path) if mld_file: vvd_file = ContentManager().find_file(mdl_path.with_suffix('.vvd')) vtx_file = find_vtx_cm(mdl_path, ContentManager()) model_container = import_model(mld_file, vvd_file, vtx_file, None, scale, False, True) # import_materials(model_container.mdl) put_into_collections(model_container, mdl_path.stem, bodygroup_grouping=True) return model_container return None def create_camera(dme_camera: Camera, scale=SOURCE1_HAMMER_UNIT_TO_METERS): camera = bpy.data.cameras.new(name=dme_camera.name) camera_obj = bpy.data.objects.new(dme_camera.name, camera) bpy.context.scene.collection.objects.link(camera_obj) camera_obj.location = Vector(dme_camera.transform.position) * scale camera_obj.rotation_mode = 'QUATERNION' camera_obj.rotation_quaternion = Quaternion(dme_camera.transform.orientation) camera.lens = dme_camera.milliliters def _apply_transforms(container: Source1ModelContainer, animset: AnimationSet, scale=SOURCE1_HAMMER_UNIT_TO_METERS): for control in animset.controls: if control.type == 'DmElement': for obj in container.objects: if obj.type != 'MESH': continue if obj.data.shape_keys and control.name in obj.data.shape_keys.key_blocks: obj.data.shape_keys.key_blocks[control.name].value = control['value'] pass # flex elif control.type == 'DmeTransformControl': bone_name = control.name tmp = control['valuePosition'] pos = Vector(tmp) * scale rot = _convert_quat(control['valueOrientation']) if container.armature: arm = container.armature bone = arm.pose.bones.get(bone_name, None) if bone: qrot = Quaternion() qrot.x, qrot.y, qrot.z, qrot.w = rot # rot.x,rot.y,rot.z,rot.w = bone_.valueOrientation erot = qrot.to_euler('YXZ') if not bone.parent: pos = arm.data.bones.get(bone_name).head - pos # new_rot = Euler([math.pi / 2, 0, 0]).rotate(erot) mat = Matrix.Translation(pos) @ erot.to_matrix().to_4x4() bone.matrix_basis.identity() bone.matrix = bone.parent.matrix @ mat if bone.parent else mat def load_animset(animset: AnimationSet, shot: FilmClip, scale=SOURCE1_HAMMER_UNIT_TO_METERS): if animset.game_model: container = import_gamemodel(animset.game_model.model_name, scale) if container is None: print(f'Failed to load {animset.name} model') return None if container.armature: qrot = convert_source_rotation(animset.game_model.transform.orientation) pos = convert_source_position(animset.game_model.transform.position) container.armature.rotation_mode = 'QUATERNION' container.armature.location = pos * scale container.armature.rotation_quaternion = qrot # _apply_bone_transforms(animset, container, scale) else: for obj in container.objects: qrot = convert_source_rotation(animset.game_model.transform.orientation) pos = convert_source_position(animset.game_model.transform.position) obj.location = pos * scale obj.rotation_quaternion = qrot _apply_transforms(container, animset, scale) def load_session(session_path: Path, scale=SOURCE1_HAMMER_UNIT_TO_METERS): session = open_session(session_path) active_clip = session.active_clip map_file = active_clip.map_file if map_file: print(f'Loading {active_clip.map_name}') bsp_map = BSP(map_file, scale=scale) # bsp_map.load_disp() # bsp_map.load_entities() # bsp_map.load_static_props() # bsp_map.load_detail_props() # bsp_map.load_materials() for shot in active_clip.sub_clip_track_group.tracks[0].children[:1]: camera = shot.camera create_camera(camera) for anim_set in shot.animation_sets: load_animset(anim_set, shot, scale)
[ "bpy.context.scene.collection.objects.link", "bpy.data.cameras.new", "bpy.data.objects.new", "pathlib.Path" ]
[((902, 916), 'pathlib.Path', 'Path', (['mdl_path'], {}), '(mdl_path)\n', (906, 916), False, 'from pathlib import Path\n'), ((1488, 1530), 'bpy.data.cameras.new', 'bpy.data.cameras.new', ([], {'name': 'dme_camera.name'}), '(name=dme_camera.name)\n', (1508, 1530), False, 'import bpy\n'), ((1548, 1593), 'bpy.data.objects.new', 'bpy.data.objects.new', (['dme_camera.name', 'camera'], {}), '(dme_camera.name, camera)\n', (1568, 1593), False, 'import bpy\n'), ((1599, 1652), 'bpy.context.scene.collection.objects.link', 'bpy.context.scene.collection.objects.link', (['camera_obj'], {}), '(camera_obj)\n', (1640, 1652), False, 'import bpy\n')]
""" script to ease construction of CSDGM2-style metadata for an GeMS-style geodatabase. To use, Run ValidateDatabase to make sure that the database is complete and there are no missing DMU, Glossary, or DataSources entries In ArcCatalog, go to Customize>Options>Metadata and set Metadata Style to "FGDC CSDGM Metadata". OK and exit. In ArcCatalog, use the ArcGIS metadata editor to complete the record for the GeologicMap feature dataset. Save. NOTE THAT whatever errors or you create in this master metadata record will be faithfully propagated to metadata records for all parts of the geodatabase! Run script GeMS_MetadataCSDGM2_Arc10.1.py. This script will: Export the GeologicMap metadata record in CSDGM2 format Polish this metadata slightly for use as a master record For the geodatabase as a whole and for each entity (table, feature dataset, feature class) in the geodatabase: Copies the master record. Adds supplemental information (ArcGIS reports this in Resouce:Details) about the the GeMS standard and continents of the geodatabase. Adds a description of the entity taken from the GeMS documentation. Adds entity-attribute information taken from the GeMS documentation and the DMU, Glossary, and DataSources tables of the geodatabase. Writes this XML to a file in the directory that contains the geodatabase. Imports this XML into the geodatabase as metadata for the appropriate entity. Look at file <geodatabasename>-metadataLog.txt to see what parts of which metadata records need to be completed by hand. This will occur wherever you extend the database schema beyond the schema outlined in the GeMS documentation. ***Note that this script provides for a file that automates description of your extensions to the GeMS schema so that you need not edit metadata by hand--see file my_GeMSDefinitions.py in the GeMS Scripts directory.*** Inspect metadata records in ArcCatalog (the Description tab) to see that they are complete. Open saved XML files in browser to see that they are appropriate. Scan for duplicate entries. You want ISO metadata? Change your Metadata Style and fix records using the ArcCatalog metadata editor. Export as ISO of your flavor, insofar as ArcCatalog allows. Let us know how this works. Usage: prompt>GeMS_MetadataCSDGM2_Arc10.1.py <geodatabase> <NAME> and <NAME>, US Geological Survey <EMAIL>, <EMAIL> """ # 17 March 2017 Changed NCGMP09 to GeMS, etc. # 18 April 2017 Added utility functions, local definition-extension file # 12 August 2017 Modified to recognize GeoMaterial, GeoMaterialConfidence, and GeoMaterialDict. # Added number of rows in each table to gdb description in SupplementalInfo #Metadata conversion (ImportMetadata_conversion) is not supported in Pro as of 180926, but is on the roadmap. import arcpy, sys, os.path, copy, imp, glob from GeMS_Definition import enumeratedValueDomainFieldList, rangeDomainDict, unrepresentableDomainDict, attribDict, entityDict, GeoMatConfDict from GeMS_utilityFunctions import * from xml.dom.minidom import * versionString = 'GeMS_MetadataCSDGM2_Arc10.py, version of 10 December 2017' translator = arcpy.GetInstallInfo("desktop")["InstallDir"]+'Metadata/Translator/ARCGIS2FGDC.xml' debug = False ncgmp = 'GeMS' ncgmpFullRef = '"GeMS (Geologic Map Schema)--a standard format for digital publication of geologic maps, version 2.0", available at http://ngmdb.usgs.gov/Info/standards/GeMS/' eaoverviewCitation = 'Detailed descriptions of entities, attributes, and attribute values are given in metadata for constituent elements of this composite dataset. See also '+ncgmpFullRef+'.' gdbDesc0a = ' is a composite geodataset that conforms to '+ncgmpFullRef+'. ' gdbDesc0b = ' is part of a composite geodataset that conforms to '+ncgmpFullRef+'. ' gdbDesc2 = 'Metadata records associated with each element within the geodataset contain more detailed descriptions of their purposes, constituent entities, and attributes. ' gdbDesc3 = ('Two shapefile versions of the dataset are also available. The OPEN shapefile version consists '+ 'of shapefiles, DBF files, and delimited text files and retains all information in the native '+ 'geodatabase, but some programming will likely be necessary to assemble these components into '+ 'usable formats. The SIMPLE shapefile version consists only of shapefiles and is easily used, but '+ 'lacks some information present in the native geodatabase.') def __appendOrReplace(rootNode,newNode,nodeTag): if len(rootNode.getElementsByTagName(nodeTag)) == 0: rootNode.appendChild(newNode) else: rootNode.replaceChild(newNode,rootNode.getElementsByTagName(nodeTag)[0]) def __fieldNameList(fc): #Returns a list of field names from Field.name in arcpy.ListFields fldList = arcpy.ListFields(fc) nameList = [] for fld in fldList: if not fld.name in ('OBJECTID', 'SHAPE','Shape', 'Shape_Length', 'Shape_Area'): nameList.append(fld.name) return nameList def __findInlineRef(sourceID): # finds the Inline reference for each DataSource_ID query = '"DataSources_ID" = \'' + sourceID + '\'' rows = arcpy.SearchCursor(dataSources, query) row = next(rows) if not row is None: #return row.Inline return row.Source else: return "" def __newElement(dom,tag,text): nd = dom.createElement(tag) ndText = dom.createTextNode(text) nd.appendChild(ndText) return nd def __updateAttrDef(fld,dom): ##element tag names are ## attr = Attribute ## attrlabl = Attribute_Label ## attrdef = Attribute_Definition ## attrdefs = Attribute_Definition_Source labelNodes = dom.getElementsByTagName('attrlabl') for attrlabl in labelNodes: if attrlabl.firstChild.data == fld: attr = attrlabl.parentNode if fld.find('_ID') > -1: # substitute generic _ID field for specific attrdefText = attribDict['_ID'] else: attrdefText = attribDict[fld] attrdef = __newElement(dom,'attrdef',attrdefText) __appendOrReplace(attr,attrdef,'attrdef') attrdefs = __newElement(dom,'attrdefs',ncgmp) __appendOrReplace(attr,attrdefs,'attrdefs') return dom def __updateEdom(fld, defs, dom): ##element tag names are ## attr = Attribute ## attrdomv = Attribute_Domain_Values ## edom = Enumerated_Domain ## edomv = Enumerated_Domain_Value ## edomd = Enumerated_Domain_Definition ## edomvds = Enumerated_Domain_Value_Definition_Source labelNodes = dom.getElementsByTagName('attrlabl') for attrlabl in labelNodes: if attrlabl.firstChild.data == fld: attr = attrlabl.parentNode attrdomv = dom.createElement('attrdomv') for k in defs.items(): edom = dom.createElement('edom') edomv = __newElement(dom,'edomv',k[0]) edomvd = __newElement(dom,'edomvd',k[1][0]) edom.appendChild(edomv) edom.appendChild(edomvd) if len(k[1][1]) > 0: edomvds = __newElement(dom,'edomvds',k[1][1]) edom.appendChild(edomvds) attrdomv.appendChild(edom) __appendOrReplace(attr,attrdomv,'attrdomv') return dom def __updateEntityAttributes(fc, fldList, dom, logFile): """For each attribute (field) in fldList, adds attribute definition and definition source, classifies as range domain, unrepresentable-value domain or enumerated-value domain, and for range domains, adds rangemin, rangemax, and units; for unrepresentable value domains, adds unrepresentable value statement; for enumerated value domains: 1) Finds all controlled-vocabulary fields in the table sent to it 2) Builds a set of unique terms in each field, ie, the domain 3) Matches each domain value to an entry in the glossary 4) Builds a dictionary of term:(definition, source) items 5) Takes the dictionary items and put them into the metadata document as Attribute_Domain_Values Field MapUnit in table DescriptionOfMapUnits is treated as a special case. """ cantfindTerm = [] cantfindValue = [] for fld in fldList: addMsgAndPrint( ' Field: '+ fld) # if is _ID field or if field definition is available, update definition if fld.find('_ID') > -1 or fld in attribDict: dom = __updateAttrDef(fld,dom) else: cantfindTerm.append(fld) #if this is an _ID field if fld.find('_ID') > -1: dom = __updateUdom(fld,dom,unrepresentableDomainDict['_ID']) #if this is another unrepresentable-domain field if fld in unrepresentableDomainDict: dom = __updateUdom(fld,dom,unrepresentableDomainDict[fld]) #if this is a defined range-domain field elif fld in rangeDomainDict: dom = __updateRdom(fld,dom) #if this is MapUnit in DMU elif fld == 'MapUnit' and fc == 'DescriptionOfMapUnits': dom = __updateUdom(fld,dom,unrepresentableDomainDict['default']) #if this is a defined Enumerated Value Domain field elif fld in enumeratedValueDomainFieldList: valList = [] #create a search cursor on the field rows = arcpy.SearchCursor(fc,'','', fld) row = next(rows) #collect all values/terms in that field while row: if not row.getValue(fld) is None: valList.append(row.getValue(fld)) row = next(rows) #uniquify the list by converting it to a set object valList = set(valList) #create an empty dictionary object to hold the matches between the unique terms #and their definitions (grabbed from the glossary) defs = {} #for each unique term, try to create a search cursor of just one record where the term #matchs a Term field value from the glossary if fld == 'MapUnit' and fc != 'DescriptionOfMapUnits': for t in valList: query = '"MapUnit" = \'' + t + '\'' rows = arcpy.SearchCursor(DMU, query) row = next(rows) #if the searchcursor contains a row if row: #create an entry in the dictionary of term:[definition, source] key:value pairs #this is how we will enumerate through the enumerated_domain section defs[t] = [] if row.FullName != None: defs[t].append(row.FullName.encode('utf_8')) defs[t].append('this report, table DescriptionOfMapUnits') else: addMsgAndPrint('MapUnit = '+t+', FullName not defined') defs[t].append(row.Name.encode('utf_8')) defs[t].append('this report, table DescriptionOfMapUnits') else: if not t in ('',' '): cantfindValue.append([fld,t]) elif fld == 'GeoMaterialConfidence' and fc == 'DescriptionOfMapUnits': if debug: addMsgAndPrint('DMU / GeoMaterialsConfidence') defs = GeoMatConfDict elif fld == 'GeoMaterial' and fc == 'DescriptionOfMapUnits': if debug: addMsgAndPrint('DMU / GeoMaterials!') for t in valList: query = '"GeoMaterial" = \'' + t + '\'' if debug: addMsgAndPrint('query='+query) rows = arcpy.SearchCursor(gmDict, query) row = next(rows) #if the searchcursor contains a row if row: if debug: addMsgAndPrint(row.GeoMaterial+' : '+row.Definition.encode('utf_8')) #create an entry in the dictionary of term:[definition, source] key:value pairs #this is how we will enumerate through the enumerated_domain section defs[t] = [] defs[t].append(row.Definition.encode('utf_8')) defs[t].append(' GeMS documentation') else: addMsgAndPrint('GeoMaterial = '+t+': not defined in GeoMaterialDict') cantfindValue.append([fld,t]) elif fld.find('SourceID') > -1: # is a source field for t in valList: query = '"DataSources_ID" = \'' + t + '\'' rows = arcpy.SearchCursor(dataSources, query) row = next(rows) #if the searchcursor contains a row if row: #create an entry in the dictionary of term:[definition, source] key:value pairs #this is how we will enumerate through the enumerated_domain section defs[t] = [] defs[t].append(row.Source.encode('utf_8')) defs[t].append('this report, table DataSources') else: cantfindValue.append([fld,t]) else: for t in valList: query = '"Term" = '+"'"+ t + "'" if debug: addMsgAndPrint('query='+query) rows = arcpy.SearchCursor(gloss, query) row = next(rows) #if the searchcursor contains a row if row: #create an entry in the dictionary of term:[definition, source] key:value pairs #this is how we will enumerate through the enumerated_domain section defs[t] = [] defs[t].append(row.Definition.encode('utf_8')) defs[t].append(__findInlineRef(row.DefinitionSourceID).encode('utf_8')) else: if fld != 'GeoMaterial' and fc != 'GeoMaterialDict': cantfindValue.append([fld,t]) dom = __updateEdom(fld, defs, dom) else: #presumed to be an unrepresentable domain dom = __updateUdom(fld,dom,unrepresentableDomainDict['default']) if len(cantfindValue) > 0: logFile.write('Missing enumerated-domain values\n') logFile.write(' ENTITY TERM VALUE\n') for term in cantfindValue: logFile.write(' '+fc+' '+term[0]+' **'+term[1]+'**\n') if len(cantfindTerm) > 0: logFile.write('Missing terms\n') logFile.write(' ENTITY TERM\n') for term in cantfindTerm: logFile.write(' '+fc + ' '+term+'\n') return dom def __updateRdom(fld,dom): labelNodes = dom.getElementsByTagName('attrlabl') for attrlabl in labelNodes: if attrlabl.firstChild.data == fld: attr = attrlabl.parentNode attrdomv = dom.createElement('attrdomv') rdom = dom.createElement('rdom') rdommin = __newElement(dom,'rdommin',rangeDomainDict[fld][0]) rdom.appendChild(rdommin) rdommax = __newElement(dom,'rdommax',rangeDomainDict[fld][1]) rdom.appendChild(rdommax) attrunit = __newElement(dom,'attrunit',rangeDomainDict[fld][2]) rdom.appendChild(attrunit) attrdomv.appendChild(rdom) __appendOrReplace(attr,attrdomv,'attrdomv') return dom def __updateUdom(fld,dom,udomTextString): labelNodes = dom.getElementsByTagName('attrlabl') for attrlabl in labelNodes: if attrlabl.firstChild.data == fld: attr = attrlabl.parentNode attrdomv = dom.createElement('attrdomv') udom = __newElement(dom,'udom',udomTextString) attrdomv.appendChild(udom) __appendOrReplace(attr,attrdomv,'attrdomv') return dom def addSupplinf(dom,supplementaryInfo): rtNode = dom.getElementsByTagName('descript')[0] siNode = __newElement(dom,'supplinf',supplementaryInfo) __appendOrReplace(rtNode,siNode,'supplinf') return dom def cleanTitle(dom): # trims all ": table...", ": feature..." from title title = dom.getElementsByTagName('title')[0] titleText = title.firstChild.data #if debug: addMsgAndPrint(titleText) for txt in (': feature',': table'): cn = titleText.find(txt) if cn > 0: titleText = titleText[0:cn] title.firstChild.data = titleText return dom def eaoverviewDom(dom,eainfo,eaoverText,edcTxt): overview = dom.createElement('overview') eaover = __newElement(dom,'eaover',eaoverText) overview.appendChild(eaover) eadetcit = __newElement(dom,'eadetcit',edcTxt) overview.appendChild(eadetcit) eainfo.appendChild(overview) return dom def purgeChildren(dom,nodeTag): nodes = dom.getElementsByTagName(nodeTag) for aNode in nodes: while len(aNode.childNodes) > 0: aNode.removeChild(aNode.lastChild) return dom def purgeIdenticalSiblings(dom,ndTag,ndTxt): nodes = dom.getElementsByTagName(ndTag) parentNodes = [] n = 0 for nd in nodes: if nd.firstChild.data == ndTxt: parentNodes.append(nd.parentNode) n = n+1 for i in range(1,n): grandparent = parentNodes[i].parentNode grandparent.removeChild(parentNodes[i]) return dom def titleSuffix(dom,suffix): # adds suffix to title text title = dom.getElementsByTagName('title')[0] titleText = title.firstChild.data if titleText.find(suffix) == -1: # titleSuffix isn't already present title.firstChild.data = titleText+suffix return dom def updateTableDom(dom,fc,logFile): #def __updateTable(domMR,fc,gdbFolder,titleSuffix,logFile,isAnno): #try to export metadata from fc desc = arcpy.Describe(fc) if desc.datasetType == 'FeatureClass' and desc.FeatureType == 'Annotation': isAnno = True else: isAnno = False if fc in entityDict: hasDesc = True descText = entityDict[fc] descSourceText = ncgmp else: hasDesc = False if not isAnno: descText = '**Need Description of '+fc+'**' descSourceText = '**Need Description Source**' logFile.write('No description for entity '+fc+'\n') logFile.write('No description source for entity '+fc+'\n') eainfo = dom.getElementsByTagName('eainfo')[0] # DELETE EXISTING CHILD NODES while len(eainfo.childNodes) > 0: eainfo.removeChild(eainfo.lastChild) if isAnno: if hasDesc: eaoverText = descText else: eaoverText = 'annotation feature class' if hasDesc: edcTxt = descSourceText else: edcTxt = 'See ESRI documentation for structure of annotation feature classes.' # add overview to dom dom = eaoverviewDom(dom,eainfo,eaoverText,edcTxt) #overview = dom.createElement('overview') #eaover = __newElement(dom,'eaover',eaoverText) #overview.appendChild(eaover) #eadetcit = __newElement(dom,'eadetcit',edcTxt) #overview.appendChild(eadetcit) #eainfo.appendChild(overview) else: # is table or non-Anno feature class # check for e-a detailed node, add if necessary if len(eainfo.getElementsByTagName('detailed')) == 0: #add detailed/enttyp/enttypl nodes detailed = dom.createElement('detailed') enttyp = dom.createElement('enttyp') enttypl = __newElement(dom,'enttypl',fc) enttypd = __newElement(dom,'enttypd',descText) enttypds = __newElement(dom,'enttypds',descSourceText) for nd in enttypl,enttypd,enttypds: enttyp.appendChild(nd) detailed.appendChild(enttyp) eainfo.appendChild(detailed) ##check that each field has a corresponding attr node #get a list of the field names in the fc fldNameList = __fieldNameList(fc) #get list of attributes in this metadata record # we assume there eainfoNode has only one 'detailed' child attrlablNodes = eainfo.getElementsByTagName('attrlabl') attribs = [] detailed = dom.getElementsByTagName('detailed')[0] for nd in attrlablNodes: attribs.append(nd.firstChild.data) for fieldName in fldNameList: if not fieldName in attribs: attr = dom.createElement('attr') attrlabl = __newElement(dom,'attrlabl',fieldName) attr.appendChild(attrlabl) detailed.appendChild(attr) #update the entity description and entity description source if fc in entityDict or ( fc[0:2] == 'CS' and fc[2:] in entityDict): enttypl = dom.getElementsByTagName('enttypl') if len(enttypl) > 0: enttyp = enttypl[0].parentNode # entity description node if fc[0:2] == 'CS': descriptionText = entityDict[fc[2:]] else: descriptionText = entityDict[fc] newEnttypd = __newElement(dom,'enttypd',descriptionText) __appendOrReplace(enttyp,newEnttypd,'enttypd') # entity description source node newEnttypds = __newElement(dom,'enttypds',ncgmp) __appendOrReplace(enttyp,newEnttypds,'enttypds') #update attribute descriptions and value domains dom = __updateEntityAttributes(fc, fldNameList, dom, logFile) return dom def writeDomToFile(workDir,dom,fileName): if debug: addMsgAndPrint(arcpy.env.workspace) addMsgAndPrint('fileName='+fileName) outf = open(os.path.join(workDir,fileName),'w') dom.writexml(outf) outf.close() def writeGdbDesc(gdb): desc = 'The geodatabase contains the following elements: ' arcpy.env.workspace = gdb for aTable in arcpy.ListTables(): desc = desc+'non-spatial table '+ aTable+' ('+str(numberOfRows(aTable))+' rows); ' for anFds in arcpy.ListDatasets(): desc = desc + 'feature dataset '+anFds+' which contains ' fcs = arcpy.ListFeatureClasses('','All',anFds) if len(fcs) == 1: desc = desc + 'feature class '+fcs[0]+' ('+str(numberOfRows(fcs[0]))+' features); ' else: for n in range(0,len(fcs)-1): desc = desc+'feature class '+fcs[n]+' ('+str(numberOfRows(fcs[n]))+' features), ' lastn = len(fcs)-1 desc = desc+'and feature class '+fcs[lastn]+' ('+str(numberOfRows(fcs[lastn]))+' features); ' desc = desc[:-2]+'. ' return desc def writeFdsDesc(gdb,fdsName): if fdsName in entityDict: desc = entityDict[fdsName] +' It contains the following elements: ' else: desc = 'Feature dataset '+fdsName+' contains the following elements: ' arcpy.env.workspace = gdb+'/'+fdsName fcs = arcpy.ListFeatureClasses('','All') if len(fcs) == 1: desc = desc + 'feature class '+fcs[0]+' ('+str(numberOfRows(fcs[0]))+' features); ' else: for n in range(0,len(fcs)-2): desc = desc+'feature class '+fcs[n]+' ('+str(numberOfRows(fcs[n]))+' features), ' lastn = len(fcs)-1 desc = desc+'and feature class '+fcs[lastn]+' ('+str(numberOfRows(fcs[lastn]))+' features). ' desc = desc[:-2]+'. ' return desc ############################################################################## inGdb = sys.argv[1] inGdb = os.path.abspath(inGdb) workDir = os.path.dirname(inGdb) gdb = os.path.basename(inGdb) ## supplement entity and field dictionaries from GeMS_Definition if sys.argv[2] != '#': if os.path.exists(sys.argv[2]): myDefs = imp.load_source('module1',sys.argv[2]) myDefs.addDefs() #forceExit() ###### gloss = os.path.join(inGdb, 'Glossary') dataSources = os.path.join(inGdb, 'DataSources') DMU = os.path.join(inGdb, 'DescriptionOfMapUnits') gmDict = os.path.join(inGdb, 'GeoMaterialDict') logFileName = inGdb+'-metadataLog.txt' xmlFileMR = gdb+'-MR.xml' xmlFileGdb = gdb+'.xml' # export master record fXML = workDir+'/'+gdb+ '.xml' addMsgAndPrint('fXML = '+fXML) if os.path.exists(fXML): os.remove(fXML) gdbObj = inGdb+'/GeologicMap' if debug: addMsgAndPrint(' gdbObj = '+gdbObj) addMsgAndPrint(' translator = '+translator) addMsgAndPrint(' fXML = '+fXML) arcpy.ExportMetadata_conversion(gdbObj,translator,fXML) addMsgAndPrint(' Metadata for GeologicMap exported to file ') addMsgAndPrint(' '+fXML) # parse xml to DOM try: domMR = xml.dom.minidom.parse(fXML) addMsgAndPrint(' Master record parsed successfully') # should then delete xml file if not debug: os.remove(fXML) except: addMsgAndPrint(arcpy.GetMessages()) addMsgAndPrint('Failed to parse '+fXML) raise arcpy.ExecuteError sys.exit() # clean up master record ## purge of eainfo and spdoinfo for nodeTag in ('eainfo','spdoinfo'): domMR = purgeChildren(domMR,nodeTag) ## get rid of extra <themekt>ISO 19115 Topic Categories entries #domMR = purgeIdenticalSiblings(domMR,'themekt','ISO 19115 Topic Categories') ## fix title domMR = cleanTitle(domMR) ## ensure that there is an eainfo node try: eanode = domMR.getElementsByTagName('eainfo')[0] except: rtNode = domMR.getElementsByTagName('metadata')[0] eanode = domMR.createElement('eainfo') rtNode.appendChild(eanode) writeDomToFile(workDir,domMR,xmlFileMR) addMsgAndPrint(' Running mp on master metadata record '+xmlFileMR+':') if os.path.exists(logFileName): os.remove(logFileName) arcpy.USGSMPTranslator_conversion(os.path.join(workDir,xmlFileMR),'#','#','#',logFileName) for aline in open(logFileName,'r').readlines(): addMsgAndPrint(aline[:-1]) addMsgAndPrint(' ') logFile = open(logFileName,'a') # import to geodatabase as whole arcpy.env.workspace = workDir supplementaryInfo = gdb+gdbDesc0a+gdbDesc2+gdbDesc3 dom = addSupplinf(domMR,supplementaryInfo) eainfo = dom.getElementsByTagName('eainfo')[0] gdbDesc = writeGdbDesc(inGdb) # listing of all tables, feature datasets, feature classes dom = eaoverviewDom(dom,eainfo,gdbDesc,eaoverviewCitation) addMsgAndPrint(' Importing XML to metadata for GDB as a whole') writeDomToFile(workDir,dom,xmlFileGdb) try: arcpy.ImportMetadata_conversion(os.path.join(workDir,xmlFileGdb),'FROM_FGDC',inGdb,'ENABLED') except: addMsgAndPrint('Failed to import '+os.path.join(workDir,xmlFileGdb)) # import to tables arcpy.env.workspace = inGdb tables = arcpy.ListTables() for aTable in tables: revisedMetadata = gdb+'-'+aTable+'.xml' addMsgAndPrint(' Creating XML for '+aTable) dom = xml.dom.minidom.parse(os.path.join(workDir,xmlFileMR)) dom = titleSuffix(dom,': table '+aTable) supplementaryInfo = 'Table '+aTable+gdbDesc0b+gdbDesc2 dom = addSupplinf(dom,supplementaryInfo) dom = updateTableDom(dom,aTable,logFile) addMsgAndPrint(' Importing XML to metadata for table '+aTable) writeDomToFile(workDir,dom,revisedMetadata) try: arcpy.ImportMetadata_conversion(os.path.join(workDir,revisedMetadata),'FROM_FGDC',inGdb+'/'+aTable,'ENABLED') except: addMsgAndPrint('Failed to import '+os.path.join(workDir,revisedMetadata)) # import to feature datasets and constituent feature classes arcpy.env.workspace = inGdb fds = arcpy.ListDatasets('','Feature') for anFds in fds: revisedMetadata = gdb+'-'+anFds+'.xml' addMsgAndPrint(' Creating XML for '+anFds) dom = xml.dom.minidom.parse(os.path.join(workDir,xmlFileMR)) dom = titleSuffix(dom,': feature dataset '+anFds) supplementaryInfo = 'Feature dataset '+anFds+gdbDesc0b+gdbDesc2 dom = addSupplinf(dom,supplementaryInfo) if anFds in entityDict: overText = entityDict[anFds] overSrc = ncgmpFullRef elif anFds.find('CrossSection') == 0: overText = entityDict['CrossSection'] overSrc = ncgmpFullRef else: overText = '**Need Description of '+anFds+'**' overSrc = '**Need Description Source**' logFile.write('No description for entity '+anFds+'\n') logFile.write('No description source for entity '+anFds+'\n') eainfo = dom.getElementsByTagName('eainfo')[0] dom = eaoverviewDom(dom,eainfo,overText,overSrc) addMsgAndPrint(' Importing XML to metadata for '+anFds) writeDomToFile(workDir,dom,revisedMetadata) arcpy.ImportMetadata_conversion(os.path.join(workDir,revisedMetadata),'FROM_FGDC',inGdb+'/'+anFds,'ENABLED') fcs = arcpy.ListFeatureClasses('','All',anFds) del dom for anFc in fcs: revisedMetadata = inGdb + '-' + anFc + '.xml' addMsgAndPrint(' Creating XML for '+anFc) dom = xml.dom.minidom.parse(os.path.join(workDir,xmlFileMR)) dom = titleSuffix(dom,': feature class '+anFds+'/'+anFc) supplementaryInfo = 'Feature class '+anFc+gdbDesc0b+gdbDesc2 dom = addSupplinf(dom,supplementaryInfo) dom = updateTableDom(dom,anFc,logFile) addMsgAndPrint(' Importing XML to metadata for '+anFc) writeDomToFile(workDir,dom,revisedMetadata) arcpy.ImportMetadata_conversion(revisedMetadata,'FROM_FGDC',inGdb+'/'+anFds+'/'+anFc,'ENABLED') del dom # clean up empty log files addMsgAndPrint(' Deleting empty log files') logfiles = glob.glob(workDir+'/*.log') for lf in logfiles: if os.path.getsize(lf) == 0: addMsgAndPrint(' deleting '+os.path.basename(lf)) os.remove(lf) addMsgAndPrint('\nBe sure to check file '+os.path.basename(logFileName)+' !') logFile.close()
[ "arcpy.SearchCursor", "arcpy.GetMessages", "arcpy.ListTables", "imp.load_source", "arcpy.Describe", "arcpy.ListFeatureClasses", "arcpy.ListFields", "arcpy.ListDatasets", "arcpy.GetInstallInfo", "sys.exit", "arcpy.ImportMetadata_conversion", "arcpy.ExportMetadata_conversion", "glob.glob" ]
[((25345, 25402), 'arcpy.ExportMetadata_conversion', 'arcpy.ExportMetadata_conversion', (['gdbObj', 'translator', 'fXML'], {}), '(gdbObj, translator, fXML)\n', (25376, 25402), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((27478, 27496), 'arcpy.ListTables', 'arcpy.ListTables', ([], {}), '()\n', (27494, 27496), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((28316, 28349), 'arcpy.ListDatasets', 'arcpy.ListDatasets', (['""""""', '"""Feature"""'], {}), "('', 'Feature')\n", (28334, 28349), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((30294, 30323), 'glob.glob', 'glob.glob', (["(workDir + '/*.log')"], {}), "(workDir + '/*.log')\n", (30303, 30323), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((4977, 4997), 'arcpy.ListFields', 'arcpy.ListFields', (['fc'], {}), '(fc)\n', (4993, 4997), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((5343, 5381), 'arcpy.SearchCursor', 'arcpy.SearchCursor', (['dataSources', 'query'], {}), '(dataSources, query)\n', (5361, 5381), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((18686, 18704), 'arcpy.Describe', 'arcpy.Describe', (['fc'], {}), '(fc)\n', (18700, 18704), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((22872, 22890), 'arcpy.ListTables', 'arcpy.ListTables', ([], {}), '()\n', (22888, 22890), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((23000, 23020), 'arcpy.ListDatasets', 'arcpy.ListDatasets', ([], {}), '()\n', (23018, 23020), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((23879, 23914), 'arcpy.ListFeatureClasses', 'arcpy.ListFeatureClasses', (['""""""', '"""All"""'], {}), "('', 'All')\n", (23903, 23914), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((29490, 29532), 'arcpy.ListFeatureClasses', 'arcpy.ListFeatureClasses', (['""""""', '"""All"""', 'anFds'], {}), "('', 'All', anFds)\n", (29514, 29532), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((3340, 3371), 'arcpy.GetInstallInfo', 'arcpy.GetInstallInfo', (['"""desktop"""'], {}), "('desktop')\n", (3360, 3371), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((23102, 23144), 'arcpy.ListFeatureClasses', 'arcpy.ListFeatureClasses', (['""""""', '"""All"""', 'anFds'], {}), "('', 'All', anFds)\n", (23126, 23144), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((24684, 24723), 'imp.load_source', 'imp.load_source', (['"""module1"""', 'sys.argv[2]'], {}), "('module1', sys.argv[2])\n", (24699, 24723), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((25809, 25819), 'sys.exit', 'sys.exit', ([], {}), '()\n', (25817, 25819), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((30096, 30206), 'arcpy.ImportMetadata_conversion', 'arcpy.ImportMetadata_conversion', (['revisedMetadata', '"""FROM_FGDC"""', "(inGdb + '/' + anFds + '/' + anFc)", '"""ENABLED"""'], {}), "(revisedMetadata, 'FROM_FGDC', inGdb + '/' +\n anFds + '/' + anFc, 'ENABLED')\n", (30127, 30206), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((25711, 25730), 'arcpy.GetMessages', 'arcpy.GetMessages', ([], {}), '()\n', (25728, 25730), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((9816, 9851), 'arcpy.SearchCursor', 'arcpy.SearchCursor', (['fc', '""""""', '""""""', 'fld'], {}), "(fc, '', '', fld)\n", (9834, 9851), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((10742, 10772), 'arcpy.SearchCursor', 'arcpy.SearchCursor', (['DMU', 'query'], {}), '(DMU, query)\n', (10760, 10772), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((12311, 12344), 'arcpy.SearchCursor', 'arcpy.SearchCursor', (['gmDict', 'query'], {}), '(gmDict, query)\n', (12329, 12344), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((13351, 13389), 'arcpy.SearchCursor', 'arcpy.SearchCursor', (['dataSources', 'query'], {}), '(dataSources, query)\n', (13369, 13389), False, 'import arcpy, sys, os.path, copy, imp, glob\n'), ((14182, 14214), 'arcpy.SearchCursor', 'arcpy.SearchCursor', (['gloss', 'query'], {}), '(gloss, query)\n', (14200, 14214), False, 'import arcpy, sys, os.path, copy, imp, glob\n')]
# # pr9_3_2 from audiolazy import lazy_lpc from scipy.signal import lfilter from Universal import * from VAD import VAD def Ext_frmnt(y, p, thr1, fs): """ LPC Formant Detection :param y: enframe signal ( N x frame number(fn)) :param p: LPC order :param thr1: threshold :param fs: sample frequency :return formant: 3 x fn """ fn = y.shape[1] # frame number formant = np.zeros((fn, 3)) # formant for i in range(fn): u = y[:, i] # one frame data ar = lazy_lpc.lpc.autocor(u, p) # LPC coefficients a = ar.numerator root = np.roots(a) # roots of polynomial mag_root = np.abs(root) # magnitude arg_root = np.angle(root) # angle f_root = arg_root / np.pi * fs / 2 # angle --> frequency k = 0 fmn = [] for j in range(p): if mag_root[j] > thr1: if arg_root[j] > 0 and arg_root[j] < np.pi and f_root[j] > 200: fmn.append(f_root[j]) k = k + 1 if fmn: f1 = len(fmn) fmn = np.sort(fmn) formant[i, 0: min(f1, 3)] = fmn[0: min(f1, 3)] # just need three frequency return formant if __name__ == '__main__': filename = 'vowels8.wav' speech = Speech() xx, fs = speech.audioread(filename, None) # read one frame data x = xx - np.mean(xx) # DC y = lfilter(b=np.array([1, -0.99]), a=1, x=x) # pre-emphasis wlen = 200 # frame length inc = 80 # frame shift xy = speech.enframe(y, wlen, inc).T # enframe fn = xy.shape[1] # frame number Nx = len(y) # data length time = np.arange(0, Nx) / fs # time scale frameTime = speech.FrameTime(fn, wlen, inc, fs) # frame to time T1 = 0.1 miniL = 20 # voice segment minimal frame number p = 9 thr1 = 0.75 voiceseg, vosl, SF, Ef = VAD().pitch_vad1(xy, fn, T1, miniL) # VAD Msf = np.tile(SF.reshape((len(SF), 1)), (1, 3)) # SF ---> fn x 3 formant = Ext_frmnt(xy, p, thr1, fs) Fmap = np.multiply(Msf, formant) # just voice segment findex = np.where(Fmap == 0) Fmap[findex] = np.nan nfft = 512 d = speech.stftms(y, wlen, nfft, inc) # spectrogram W2 = int(1 + nfft / 2) n2 = np.arange(0, W2) freq = n2 * fs / nfft # figure plt.figure(1, figsize=(16, 9)) plt.subplot(2, 1, 1) plt.plot(time, x) plt.xlabel('Time [s]') plt.ylabel('Amplitude') plt.title('/a-i-u/ Three Vowels Signal') plt.axis([0, max(time), -1, 1]) plt.subplot(2, 1, 2) plt.plot(frameTime, Ef) plt.plot(np.array([0, max(time)], dtype=object), np.array([T1, T1], dtype=object), 'k--', linewidth=2) for k in range(vosl): nx1 = voiceseg['begin'][k] nx2 = voiceseg['end'][k] plt.plot(np.array([frameTime[nx1], frameTime[nx1]]), np.array([-1, 1]), 'k-.', linewidth=2) plt.plot(np.array([frameTime[nx2], frameTime[nx2]]), np.array([-1, 1]), 'k-.', linewidth=2) plt.xlabel('Time [s]') plt.ylabel('Amplitude') plt.title('Normalized Power Entropy Ratio') plt.axis([0, max(time), 0, 1]) plt.savefig('images/simple_lpc_format_detection_1.png', bbox_inches='tight', dpi=600) plt.figure(2, figsize=(16, 9)) Xdb = librosa.amplitude_to_db(abs(d)) librosa.display.specshow(Xdb, sr=fs, x_coords=frameTime, x_axis='time', y_axis='linear') plt.plot(frameTime, Fmap, 'k', linewidth=2) plt.colorbar() plt.xlabel('Time [s]') plt.ylabel('Frequency [Hz]') plt.title('Spectorgram') plt.savefig('images/simple_lpc_format_detection_2.png', bbox_inches='tight', dpi=600) plt.show()
[ "audiolazy.lazy_lpc.lpc.autocor", "VAD.VAD" ]
[((470, 496), 'audiolazy.lazy_lpc.lpc.autocor', 'lazy_lpc.lpc.autocor', (['u', 'p'], {}), '(u, p)\n', (490, 496), False, 'from audiolazy import lazy_lpc\n'), ((1651, 1656), 'VAD.VAD', 'VAD', ([], {}), '()\n', (1654, 1656), False, 'from VAD import VAD\n')]
# -*- coding: utf-8 -*- from uuid import uuid4 from decimal import Decimal from zope.interface import implementer from schematics.exceptions import ValidationError from schematics.transforms import whitelist, blacklist from schematics.types import StringType, FloatType, IntType, MD5Type from schematics.types.compound import ModelType from schematics.types.serializable import serializable from openprocurement.api.utils import get_now from openprocurement.api.models import ( plain_role, schematics_default_role, Value as BaseValue, Period, Model, ListType, DecimalType, SifterListType ) from openprocurement.contracting.core.models import ( IContract, IsoDateTimeType, Contract as BaseContract, Document as BaseDocument, get_contract, ) from openprocurement.contracting.core.models import ( contract_create_role as base_contract_create_role, contract_view_role, contract_administrator_role ) from openprocurement.tender.esco.models import ( ESCOValue as BaseESCOValue, to_decimal, view_value_role_esco as base_view_value_role_esco ) from esculator import escp, npv contract_create_role = base_contract_create_role + \ whitelist('NBUdiscountRate', 'noticePublicationDate', 'yearlyPaymentsPercentageRange', 'minValue', 'milestones', 'fundingKind') contract_edit_role = (whitelist( 'title', 'title_en', 'title_ru', 'description', 'description_en', 'description_ru', 'status', 'period', 'items', 'terminationDetails', )) view_value_role_esco = base_view_value_role_esco + whitelist('amount_escp') class IESCOContract(IContract): """ ESCO Contract marker interface """ class ESCOValue(BaseESCOValue): class Options: roles = { 'embedded': view_value_role_esco, 'view': view_value_role_esco, 'create': whitelist('amount', 'amount_escp', 'amountPerformance', 'amountPerformance_npv', 'yearlyPaymentsPercentage', 'annualCostsReduction', 'contractDuration', 'currency', 'valueAddedTaxIncluded'), 'edit': whitelist('amount', 'amount_escp', 'amountPerformance', 'amountPerformance_npv', 'yearlyPaymentsPercentage', 'annualCostsReduction', 'contractDuration', 'currency', 'valueAddedTaxIncluded'), 'auction_view': whitelist('amountPerformance', 'yearlyPaymentsPercentage', 'annualCostsReduction', 'contractDuration', 'currency', 'valueAddedTaxIncluded'), 'auction_post': whitelist('amount_escp', 'amountPerformance_npv', 'yearlyPaymentsPercentage', 'contractDuration'), 'active.qualification': view_value_role_esco, 'active.awarded': view_value_role_esco, 'complete': view_value_role_esco, 'unsuccessful': view_value_role_esco, 'cancelled': view_value_role_esco, } def validate_yearlyPaymentsPercentage(self, data, value): pass @serializable(serialized_name='amountPerformance', type=DecimalType(precision=-2)) def amountPerformance_npv(self): """ Calculated energy service contract performance indicator """ return to_decimal(npv( self.contractDuration.years, self.contractDuration.days, self.yearlyPaymentsPercentage, self.annualCostsReduction, self.__parent__.noticePublicationDate, self.__parent__.NBUdiscountRate)) @serializable(serialized_name='amount', type=DecimalType(precision=-2)) def amount_escp(self): return sum([milestone.value.amount for milestone in self.__parent__.milestones if milestone.status != 'spare']) class Value(BaseValue): amount = DecimalType(required=True, precision=-2, min_value=Decimal('0')) class Options: roles = { 'edit': whitelist('amount') } class Document(BaseDocument): """ Contract Document """ documentOf = StringType( required=True, choices=['tender', 'item', 'lot', 'contract', 'change', 'milestone'], default='contract' ) def validate_relatedItem(self, data, relatedItem): if not relatedItem and \ data.get('documentOf') in ['item', 'change', 'milestone']: raise ValidationError(u'This field is required.') if relatedItem and isinstance(data['__parent__'], Model): contract = get_contract(data['__parent__']) if data.get('documentOf') == 'change' and \ relatedItem not in [i.id for i in contract.changes]: raise ValidationError( u"relatedItem should be one of changes" ) if data.get('documentOf') == 'item' and \ relatedItem not in [i.id for i in contract.items]: raise ValidationError( u"relatedItem should be one of items" ) if data.get('documentOf') == 'milestone' and \ relatedItem not in [i.id for i in contract.milestones]: raise ValidationError( u"relatedItem should be one of milestones" ) class Milestone(Model): """ Contract Milestone """ id = MD5Type(required=True, default=lambda: uuid4().hex) date = IsoDateTimeType() dateModified = IsoDateTimeType() description = StringType() period = ModelType(Period) sequenceNumber = IntType(required=True) status = StringType( required=True, choices=['scheduled', 'met', 'notMet', 'partiallyMet', 'pending', 'spare'], ) value = ModelType(Value, required=True) amountPaid = ModelType(Value) title = StringType() class Options: roles = { 'view': whitelist(), 'spare': whitelist(), 'scheduled': schematics_default_role, 'pending': schematics_default_role, 'met': schematics_default_role, 'notMet': schematics_default_role, 'partiallyMet': schematics_default_role, 'edit': whitelist('status', 'amountPaid', 'value', 'title', 'description') } def validate_status(self, data, status): if status in ['met', 'partiallyMet', 'notMet']: if len(data['title']) == 0: raise ValidationError(u"Title can't be empty in follow statuses (met, notMet, partiallyMet)") if len(data['description']) == 0: raise ValidationError(u"Description can't be empty in follow statuses (met, notMet, partiallyMet)") if status == 'met' and not data['amountPaid'].amount >= data['value'].amount: raise ValidationError(u"Milestone can't be in status 'met' if amountPaid.amount less than value.amount") elif status == 'notMet' and data['amountPaid'].amount > 0: raise ValidationError(u"Milestone can't be in status 'notMet' if amountPaid.amount greater than 0") elif status == 'partiallyMet' and not 0 < data['amountPaid'].amount < data['value'].amount: raise ValidationError( u"Milestone can't be in status 'partiallyMet' if amountPaid.amount not greater then 0 " "or not less value.amount" ) @implementer(IESCOContract) class Contract(BaseContract): """ ESCO Contract """ contractType = StringType(default='esco') fundingKind = StringType(choices=['budget', 'other'], required=True) milestones = SifterListType( ModelType(Milestone), default=list(), filter_by='status', filter_in_values=['scheduled', 'pending', 'met', 'notMet', 'partiallyMet'] ) minValue = ModelType( Value, required=False, default={'amount': 0, 'currency': 'UAH', 'valueAddedTaxIncluded': True} ) NBUdiscountRate = DecimalType( required=True, min_value=Decimal('0'), max_value=Decimal('0.99'), precision=-5 ) noticePublicationDate = IsoDateTimeType() value = ModelType(ESCOValue) amountPaid = ModelType(Value) yearlyPaymentsPercentageRange = DecimalType(required=True) documents = ListType(ModelType(Document), default=list()) class Options: roles = { 'plain': plain_role, 'create': contract_create_role, 'edit_active': contract_edit_role, 'edit_terminated': whitelist(), 'view': contract_view_role + whitelist('NBUdiscountRate', 'contractType', 'milestones'), 'Administrator': contract_administrator_role, 'default': schematics_default_role, } @serializable(serialized_name='amountPaid', serialize_when_none=False, type=ModelType(Value)) def contract_amountPaid(self): amount = sum([milestone.amountPaid.amount for milestone in self.milestones if milestone.status != 'spare']) return Value(dict(amount=amount, currency=self.value.currency, valueAddedTaxIncluded=self.value.valueAddedTaxIncluded))
[ "esculator.npv", "schematics.types.IntType", "zope.interface.implementer", "openprocurement.contracting.core.models.IsoDateTimeType", "uuid.uuid4", "schematics.exceptions.ValidationError", "schematics.types.StringType", "schematics.transforms.whitelist", "openprocurement.api.models.DecimalType", "...
[((1343, 1491), 'schematics.transforms.whitelist', 'whitelist', (['"""title"""', '"""title_en"""', '"""title_ru"""', '"""description"""', '"""description_en"""', '"""description_ru"""', '"""status"""', '"""period"""', '"""items"""', '"""terminationDetails"""'], {}), "('title', 'title_en', 'title_ru', 'description', 'description_en',\n 'description_ru', 'status', 'period', 'items', 'terminationDetails')\n", (1352, 1491), False, 'from schematics.transforms import whitelist, blacklist\n'), ((7531, 7557), 'zope.interface.implementer', 'implementer', (['IESCOContract'], {}), '(IESCOContract)\n', (7542, 7557), False, 'from zope.interface import implementer\n'), ((1164, 1295), 'schematics.transforms.whitelist', 'whitelist', (['"""NBUdiscountRate"""', '"""noticePublicationDate"""', '"""yearlyPaymentsPercentageRange"""', '"""minValue"""', '"""milestones"""', '"""fundingKind"""'], {}), "('NBUdiscountRate', 'noticePublicationDate',\n 'yearlyPaymentsPercentageRange', 'minValue', 'milestones', 'fundingKind')\n", (1173, 1295), False, 'from schematics.transforms import whitelist, blacklist\n'), ((1551, 1575), 'schematics.transforms.whitelist', 'whitelist', (['"""amount_escp"""'], {}), "('amount_escp')\n", (1560, 1575), False, 'from schematics.transforms import whitelist, blacklist\n'), ((4145, 4264), 'schematics.types.StringType', 'StringType', ([], {'required': '(True)', 'choices': "['tender', 'item', 'lot', 'contract', 'change', 'milestone']", 'default': '"""contract"""'}), "(required=True, choices=['tender', 'item', 'lot', 'contract',\n 'change', 'milestone'], default='contract')\n", (4155, 4264), False, 'from schematics.types import StringType, FloatType, IntType, MD5Type\n'), ((5590, 5607), 'openprocurement.contracting.core.models.IsoDateTimeType', 'IsoDateTimeType', ([], {}), '()\n', (5605, 5607), False, 'from openprocurement.contracting.core.models import IContract, IsoDateTimeType, Contract as BaseContract, Document as BaseDocument, get_contract\n'), ((5627, 5644), 'openprocurement.contracting.core.models.IsoDateTimeType', 'IsoDateTimeType', ([], {}), '()\n', (5642, 5644), False, 'from openprocurement.contracting.core.models import IContract, IsoDateTimeType, Contract as BaseContract, Document as BaseDocument, get_contract\n'), ((5663, 5675), 'schematics.types.StringType', 'StringType', ([], {}), '()\n', (5673, 5675), False, 'from schematics.types import StringType, FloatType, IntType, MD5Type\n'), ((5689, 5706), 'schematics.types.compound.ModelType', 'ModelType', (['Period'], {}), '(Period)\n', (5698, 5706), False, 'from schematics.types.compound import ModelType\n'), ((5728, 5750), 'schematics.types.IntType', 'IntType', ([], {'required': '(True)'}), '(required=True)\n', (5735, 5750), False, 'from schematics.types import StringType, FloatType, IntType, MD5Type\n'), ((5764, 5869), 'schematics.types.StringType', 'StringType', ([], {'required': '(True)', 'choices': "['scheduled', 'met', 'notMet', 'partiallyMet', 'pending', 'spare']"}), "(required=True, choices=['scheduled', 'met', 'notMet',\n 'partiallyMet', 'pending', 'spare'])\n", (5774, 5869), False, 'from schematics.types import StringType, FloatType, IntType, MD5Type\n'), ((5901, 5932), 'schematics.types.compound.ModelType', 'ModelType', (['Value'], {'required': '(True)'}), '(Value, required=True)\n', (5910, 5932), False, 'from schematics.types.compound import ModelType\n'), ((5950, 5966), 'schematics.types.compound.ModelType', 'ModelType', (['Value'], {}), '(Value)\n', (5959, 5966), False, 'from schematics.types.compound import ModelType\n'), ((5979, 5991), 'schematics.types.StringType', 'StringType', ([], {}), '()\n', (5989, 5991), False, 'from schematics.types import StringType, FloatType, IntType, MD5Type\n'), ((7634, 7660), 'schematics.types.StringType', 'StringType', ([], {'default': '"""esco"""'}), "(default='esco')\n", (7644, 7660), False, 'from schematics.types import StringType, FloatType, IntType, MD5Type\n'), ((7679, 7733), 'schematics.types.StringType', 'StringType', ([], {'choices': "['budget', 'other']", 'required': '(True)'}), "(choices=['budget', 'other'], required=True)\n", (7689, 7733), False, 'from schematics.types import StringType, FloatType, IntType, MD5Type\n'), ((7937, 8046), 'schematics.types.compound.ModelType', 'ModelType', (['Value'], {'required': '(False)', 'default': "{'amount': 0, 'currency': 'UAH', 'valueAddedTaxIncluded': True}"}), "(Value, required=False, default={'amount': 0, 'currency': 'UAH',\n 'valueAddedTaxIncluded': True})\n", (7946, 8046), False, 'from schematics.types.compound import ModelType\n'), ((8221, 8238), 'openprocurement.contracting.core.models.IsoDateTimeType', 'IsoDateTimeType', ([], {}), '()\n', (8236, 8238), False, 'from openprocurement.contracting.core.models import IContract, IsoDateTimeType, Contract as BaseContract, Document as BaseDocument, get_contract\n'), ((8251, 8271), 'schematics.types.compound.ModelType', 'ModelType', (['ESCOValue'], {}), '(ESCOValue)\n', (8260, 8271), False, 'from schematics.types.compound import ModelType\n'), ((8289, 8305), 'schematics.types.compound.ModelType', 'ModelType', (['Value'], {}), '(Value)\n', (8298, 8305), False, 'from schematics.types.compound import ModelType\n'), ((8342, 8368), 'openprocurement.api.models.DecimalType', 'DecimalType', ([], {'required': '(True)'}), '(required=True)\n', (8353, 8368), False, 'from openprocurement.api.models import plain_role, schematics_default_role, Value as BaseValue, Period, Model, ListType, DecimalType, SifterListType\n'), ((7775, 7795), 'schematics.types.compound.ModelType', 'ModelType', (['Milestone'], {}), '(Milestone)\n', (7784, 7795), False, 'from schematics.types.compound import ModelType\n'), ((8394, 8413), 'schematics.types.compound.ModelType', 'ModelType', (['Document'], {}), '(Document)\n', (8403, 8413), False, 'from schematics.types.compound import ModelType\n'), ((1834, 2035), 'schematics.transforms.whitelist', 'whitelist', (['"""amount"""', '"""amount_escp"""', '"""amountPerformance"""', '"""amountPerformance_npv"""', '"""yearlyPaymentsPercentage"""', '"""annualCostsReduction"""', '"""contractDuration"""', '"""currency"""', '"""valueAddedTaxIncluded"""'], {}), "('amount', 'amount_escp', 'amountPerformance',\n 'amountPerformance_npv', 'yearlyPaymentsPercentage',\n 'annualCostsReduction', 'contractDuration', 'currency',\n 'valueAddedTaxIncluded')\n", (1843, 2035), False, 'from schematics.transforms import whitelist, blacklist\n'), ((2141, 2342), 'schematics.transforms.whitelist', 'whitelist', (['"""amount"""', '"""amount_escp"""', '"""amountPerformance"""', '"""amountPerformance_npv"""', '"""yearlyPaymentsPercentage"""', '"""annualCostsReduction"""', '"""contractDuration"""', '"""currency"""', '"""valueAddedTaxIncluded"""'], {}), "('amount', 'amount_escp', 'amountPerformance',\n 'amountPerformance_npv', 'yearlyPaymentsPercentage',\n 'annualCostsReduction', 'contractDuration', 'currency',\n 'valueAddedTaxIncluded')\n", (2150, 2342), False, 'from schematics.transforms import whitelist, blacklist\n'), ((2420, 2567), 'schematics.transforms.whitelist', 'whitelist', (['"""amountPerformance"""', '"""yearlyPaymentsPercentage"""', '"""annualCostsReduction"""', '"""contractDuration"""', '"""currency"""', '"""valueAddedTaxIncluded"""'], {}), "('amountPerformance', 'yearlyPaymentsPercentage',\n 'annualCostsReduction', 'contractDuration', 'currency',\n 'valueAddedTaxIncluded')\n", (2429, 2567), False, 'from schematics.transforms import whitelist, blacklist\n'), ((2665, 2766), 'schematics.transforms.whitelist', 'whitelist', (['"""amount_escp"""', '"""amountPerformance_npv"""', '"""yearlyPaymentsPercentage"""', '"""contractDuration"""'], {}), "('amount_escp', 'amountPerformance_npv',\n 'yearlyPaymentsPercentage', 'contractDuration')\n", (2674, 2766), False, 'from schematics.transforms import whitelist, blacklist\n'), ((3365, 3565), 'esculator.npv', 'npv', (['self.contractDuration.years', 'self.contractDuration.days', 'self.yearlyPaymentsPercentage', 'self.annualCostsReduction', 'self.__parent__.noticePublicationDate', 'self.__parent__.NBUdiscountRate'], {}), '(self.contractDuration.years, self.contractDuration.days, self.\n yearlyPaymentsPercentage, self.annualCostsReduction, self.__parent__.\n noticePublicationDate, self.__parent__.NBUdiscountRate)\n', (3368, 3565), False, 'from esculator import escp, npv\n'), ((3202, 3227), 'openprocurement.api.models.DecimalType', 'DecimalType', ([], {'precision': '(-2)'}), '(precision=-2)\n', (3213, 3227), False, 'from openprocurement.api.models import plain_role, schematics_default_role, Value as BaseValue, Period, Model, ListType, DecimalType, SifterListType\n'), ((3680, 3705), 'openprocurement.api.models.DecimalType', 'DecimalType', ([], {'precision': '(-2)'}), '(precision=-2)\n', (3691, 3705), False, 'from openprocurement.api.models import plain_role, schematics_default_role, Value as BaseValue, Period, Model, ListType, DecimalType, SifterListType\n'), ((3964, 3976), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (3971, 3976), False, 'from decimal import Decimal\n'), ((4035, 4054), 'schematics.transforms.whitelist', 'whitelist', (['"""amount"""'], {}), "('amount')\n", (4044, 4054), False, 'from schematics.transforms import whitelist, blacklist\n'), ((4485, 4528), 'schematics.exceptions.ValidationError', 'ValidationError', (['u"""This field is required."""'], {}), "(u'This field is required.')\n", (4500, 4528), False, 'from schematics.exceptions import ValidationError\n'), ((4626, 4658), 'openprocurement.contracting.core.models.get_contract', 'get_contract', (["data['__parent__']"], {}), "(data['__parent__'])\n", (4638, 4658), False, 'from openprocurement.contracting.core.models import IContract, IsoDateTimeType, Contract as BaseContract, Document as BaseDocument, get_contract\n'), ((6050, 6061), 'schematics.transforms.whitelist', 'whitelist', ([], {}), '()\n', (6059, 6061), False, 'from schematics.transforms import whitelist, blacklist\n'), ((6084, 6095), 'schematics.transforms.whitelist', 'whitelist', ([], {}), '()\n', (6093, 6095), False, 'from schematics.transforms import whitelist, blacklist\n'), ((6359, 6425), 'schematics.transforms.whitelist', 'whitelist', (['"""status"""', '"""amountPaid"""', '"""value"""', '"""title"""', '"""description"""'], {}), "('status', 'amountPaid', 'value', 'title', 'description')\n", (6368, 6425), False, 'from schematics.transforms import whitelist, blacklist\n'), ((6954, 7062), 'schematics.exceptions.ValidationError', 'ValidationError', (['u"""Milestone can\'t be in status \'met\' if amountPaid.amount less than value.amount"""'], {}), '(\n u"Milestone can\'t be in status \'met\' if amountPaid.amount less than value.amount"\n )\n', (6969, 7062), False, 'from schematics.exceptions import ValidationError\n'), ((8133, 8145), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (8140, 8145), False, 'from decimal import Decimal\n'), ((8157, 8172), 'decimal.Decimal', 'Decimal', (['"""0.99"""'], {}), "('0.99')\n", (8164, 8172), False, 'from decimal import Decimal\n'), ((8625, 8636), 'schematics.transforms.whitelist', 'whitelist', ([], {}), '()\n', (8634, 8636), False, 'from schematics.transforms import whitelist, blacklist\n'), ((8936, 8952), 'schematics.types.compound.ModelType', 'ModelType', (['Value'], {}), '(Value)\n', (8945, 8952), False, 'from schematics.types.compound import ModelType\n'), ((4822, 4878), 'schematics.exceptions.ValidationError', 'ValidationError', (['u"""relatedItem should be one of changes"""'], {}), "(u'relatedItem should be one of changes')\n", (4837, 4878), False, 'from schematics.exceptions import ValidationError\n'), ((5084, 5138), 'schematics.exceptions.ValidationError', 'ValidationError', (['u"""relatedItem should be one of items"""'], {}), "(u'relatedItem should be one of items')\n", (5099, 5138), False, 'from schematics.exceptions import ValidationError\n'), ((5354, 5413), 'schematics.exceptions.ValidationError', 'ValidationError', (['u"""relatedItem should be one of milestones"""'], {}), "(u'relatedItem should be one of milestones')\n", (5369, 5413), False, 'from schematics.exceptions import ValidationError\n'), ((6600, 6692), 'schematics.exceptions.ValidationError', 'ValidationError', (['u"""Title can\'t be empty in follow statuses (met, notMet, partiallyMet)"""'], {}), '(\n u"Title can\'t be empty in follow statuses (met, notMet, partiallyMet)")\n', (6615, 6692), False, 'from schematics.exceptions import ValidationError\n'), ((6756, 6859), 'schematics.exceptions.ValidationError', 'ValidationError', (['u"""Description can\'t be empty in follow statuses (met, notMet, partiallyMet)"""'], {}), '(\n u"Description can\'t be empty in follow statuses (met, notMet, partiallyMet)"\n )\n', (6771, 6859), False, 'from schematics.exceptions import ValidationError\n'), ((7138, 7241), 'schematics.exceptions.ValidationError', 'ValidationError', (['u"""Milestone can\'t be in status \'notMet\' if amountPaid.amount greater than 0"""'], {}), '(\n u"Milestone can\'t be in status \'notMet\' if amountPaid.amount greater than 0"\n )\n', (7153, 7241), False, 'from schematics.exceptions import ValidationError\n'), ((8679, 8737), 'schematics.transforms.whitelist', 'whitelist', (['"""NBUdiscountRate"""', '"""contractType"""', '"""milestones"""'], {}), "('NBUdiscountRate', 'contractType', 'milestones')\n", (8688, 8737), False, 'from schematics.transforms import whitelist, blacklist\n'), ((5566, 5573), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (5571, 5573), False, 'from uuid import uuid4\n'), ((7350, 7488), 'schematics.exceptions.ValidationError', 'ValidationError', (['u"""Milestone can\'t be in status \'partiallyMet\' if amountPaid.amount not greater then 0 or not less value.amount"""'], {}), '(\n u"Milestone can\'t be in status \'partiallyMet\' if amountPaid.amount not greater then 0 or not less value.amount"\n )\n', (7365, 7488), False, 'from schematics.exceptions import ValidationError\n')]
import numpy as np import io import matplotlib.pyplot as plt import SurfaceTopography.Uniform.GeometryAnalysis as CAA with io.StringIO( """ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 """) as file: contacting_points = np.loadtxt(file) nx, ny = contacting_points.shape x, y = np.mgrid[:nx, :ny] fig, ax = plt.subplots() ax.imshow(contacting_points.T, cmap="Greys") iper = CAA.inner_perimeter_area(contacting_points, True, stencil=CAA.nn_stencil) ax.plot(x[iper], y[iper], ".r", label="inner_perimeter, nn") iper = CAA.inner_perimeter_area(contacting_points, True, stencil=CAA.nnn_stencil) ax.plot(x[iper], y[iper], "xr", label="inner_perimeter, nnn") oper = CAA.outer_perimeter_area(contacting_points, True, stencil=CAA.nn_stencil) ax.plot(x[oper], y[oper], "ob", mfc="none", label="outer_perimeter, nn") oper = CAA.outer_perimeter_area(contacting_points, True, stencil=CAA.nnn_stencil) ax.plot(x[oper], y[oper], "+b", label="outer_perimeter, nnn") ax.legend() fig.savefig("caa.pdf")
[ "SurfaceTopography.Uniform.GeometryAnalysis.outer_perimeter_area", "io.StringIO", "numpy.loadtxt", "SurfaceTopography.Uniform.GeometryAnalysis.inner_perimeter_area", "matplotlib.pyplot.subplots" ]
[((960, 974), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (972, 974), True, 'import matplotlib.pyplot as plt\n'), ((1027, 1100), 'SurfaceTopography.Uniform.GeometryAnalysis.inner_perimeter_area', 'CAA.inner_perimeter_area', (['contacting_points', '(True)'], {'stencil': 'CAA.nn_stencil'}), '(contacting_points, True, stencil=CAA.nn_stencil)\n', (1051, 1100), True, 'import SurfaceTopography.Uniform.GeometryAnalysis as CAA\n'), ((1169, 1243), 'SurfaceTopography.Uniform.GeometryAnalysis.inner_perimeter_area', 'CAA.inner_perimeter_area', (['contacting_points', '(True)'], {'stencil': 'CAA.nnn_stencil'}), '(contacting_points, True, stencil=CAA.nnn_stencil)\n', (1193, 1243), True, 'import SurfaceTopography.Uniform.GeometryAnalysis as CAA\n'), ((1314, 1387), 'SurfaceTopography.Uniform.GeometryAnalysis.outer_perimeter_area', 'CAA.outer_perimeter_area', (['contacting_points', '(True)'], {'stencil': 'CAA.nn_stencil'}), '(contacting_points, True, stencil=CAA.nn_stencil)\n', (1338, 1387), True, 'import SurfaceTopography.Uniform.GeometryAnalysis as CAA\n'), ((1468, 1542), 'SurfaceTopography.Uniform.GeometryAnalysis.outer_perimeter_area', 'CAA.outer_perimeter_area', (['contacting_points', '(True)'], {'stencil': 'CAA.nnn_stencil'}), '(contacting_points, True, stencil=CAA.nnn_stencil)\n', (1492, 1542), True, 'import SurfaceTopography.Uniform.GeometryAnalysis as CAA\n'), ((124, 838), 'io.StringIO', 'io.StringIO', (['"""\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0\n 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0\n 1 1 0 0 1 1 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0\n 0 1 1 0 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0\n 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0\n 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n """'], {}), '(\n """\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0\n 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0\n 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0\n 1 1 0 0 1 1 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0\n 0 1 1 0 1 1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0\n 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0\n 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n """\n )\n', (135, 838), False, 'import io\n'), ((871, 887), 'numpy.loadtxt', 'np.loadtxt', (['file'], {}), '(file)\n', (881, 887), True, 'import numpy as np\n')]
from ctypes import c_char from django.contrib.gis.geos.libgeos import ( GEOM_PTR, PREPGEOM_PTR, GEOSFuncFactory, ) from django.contrib.gis.geos.prototypes.errcheck import check_predicate # Prepared geometry constructor and destructors. geos_prepare = GEOSFuncFactory('GEOSPrepare', argtypes=[GEOM_PTR], restype=PREPGEOM_PTR) prepared_destroy = GEOSFuncFactory('GEOSPreparedGeom_destroy', argtpes=[PREPGEOM_PTR]) # Prepared geometry binary predicate support. class PreparedPredicate(GEOSFuncFactory): argtypes = [PREPGEOM_PTR, GEOM_PTR] restype = c_char errcheck = staticmethod(check_predicate) prepared_contains = PreparedPredicate('GEOSPreparedContains') prepared_contains_properly = PreparedPredicate('GEOSPreparedContainsProperly') prepared_covers = PreparedPredicate('GEOSPreparedCovers') prepared_crosses = PreparedPredicate('GEOSPreparedCrosses') prepared_disjoint = PreparedPredicate('GEOSPreparedDisjoint') prepared_intersects = PreparedPredicate('GEOSPreparedIntersects') prepared_overlaps = PreparedPredicate('GEOSPreparedOverlaps') prepared_touches = PreparedPredicate('GEOSPreparedTouches') prepared_within = PreparedPredicate('GEOSPreparedWithin')
[ "django.contrib.gis.geos.libgeos.GEOSFuncFactory" ]
[((257, 330), 'django.contrib.gis.geos.libgeos.GEOSFuncFactory', 'GEOSFuncFactory', (['"""GEOSPrepare"""'], {'argtypes': '[GEOM_PTR]', 'restype': 'PREPGEOM_PTR'}), "('GEOSPrepare', argtypes=[GEOM_PTR], restype=PREPGEOM_PTR)\n", (272, 330), False, 'from django.contrib.gis.geos.libgeos import GEOM_PTR, PREPGEOM_PTR, GEOSFuncFactory\n'), ((350, 417), 'django.contrib.gis.geos.libgeos.GEOSFuncFactory', 'GEOSFuncFactory', (['"""GEOSPreparedGeom_destroy"""'], {'argtpes': '[PREPGEOM_PTR]'}), "('GEOSPreparedGeom_destroy', argtpes=[PREPGEOM_PTR])\n", (365, 417), False, 'from django.contrib.gis.geos.libgeos import GEOM_PTR, PREPGEOM_PTR, GEOSFuncFactory\n')]
# Copyright (c) OpenMMLab. All rights reserved. """ python demo/bottom_up_img_auto_annotation.py \ configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_anim_512x512_udp.py \ checkpoints/best_AP_epoch_80.pth \ --img_dir /mnt/d/workspace/anim/screenshots/RAW/rezero \ --out_dir /mnt/d/workspace/anim/screenshots/posed/rezero/pose \ --sample-span 30 """ import os import os.path as osp import warnings from pathlib import Path from argparse import ArgumentParser import json import shutil import mmcv from mmpose.apis import inference_bottom_up_pose_model, init_pose_model, vis_pose_result from mmpose.datasets import DatasetInfo def main(): """Visualize the demo images.""" parser = ArgumentParser() parser.add_argument("pose_config", help="Config file for detection") parser.add_argument("pose_checkpoint", help="Checkpoint file") parser.add_argument( "--img_dir", type=str, help="Path to an image file or a image folder." ) parser.add_argument( "--out_dir", type=str, default="", help="Root of the output img file. " "Default not saving the visualization images.", ) parser.add_argument("--device", default="cuda:0", help="Device used for inference") parser.add_argument( "--kpt-thr", type=float, default=0.5, help="Keypoint score threshold" ) parser.add_argument( "--pose-nms-thr", type=float, default=0.9, help="OKS threshold for pose NMS" ) parser.add_argument( "--sample-span", type=int, default=1, help="OKS threshold for pose NMS" ) args = parser.parse_args() Path(args.out_dir).mkdir(exist_ok=True) # prepare image list image_list = [ osp.join(args.img_dir, fn) for fn in os.listdir(args.img_dir) if fn.lower().endswith((".png", ".jpg", ".jpeg", ".tiff", ".bmp")) ] # build the pose model from a config file and a checkpoint file pose_model = init_pose_model( args.pose_config, args.pose_checkpoint, device=args.device.lower() ) dataset = pose_model.cfg.data["test"]["type"] dataset_info = pose_model.cfg.data["test"].get("dataset_info", None) if dataset_info is None: warnings.warn( "Please set `dataset_info` in the config." "Check https://github.com/open-mmlab/mmpose/pull/663 for details.", DeprecationWarning, ) assert dataset == "BottomUpCocoDataset" else: dataset_info = DatasetInfo(dataset_info) # optional return_heatmap = False # e.g. use ('backbone', ) to return backbone feature output_layer_names = None # process each image annotations = [] image_list = image_list[:: args.sample_span] for i, image_name in enumerate(image_list): if i % 10 == 0: print( f"[{i+1}/{len(image_list)}] {Path(image_name).name}" f" ({len(annotations)} annotations found)" ) # test a single image, with a list of bboxes. pose_results, returned_outputs = inference_bottom_up_pose_model( pose_model, image_name, dataset=dataset, dataset_info=dataset_info, pose_nms_thr=args.pose_nms_thr, return_heatmap=return_heatmap, outputs=output_layer_names, ) people = [] for res in pose_results: kps = res["keypoints"] n_kps = 0 keypoints = [] for x, y, score in kps: keypoints += [int(x), int(y), 1] if score > args.kpt_thr: n_kps += 1 if n_kps > 4: people.append( { "person_name": f"P{len(people)}", "person_id": len(people), "keypoints": keypoints, } ) out_img_path = Path(args.out_dir) / Path(image_name).name shutil.copy(image_name, out_img_path) annotations.append( { "image_name": Path(image_name).name, "image_id": i, "people": people, } ) d = { "annotations": annotations, } out_json_path = Path(args.out_dir) / "keypoints.json" with open(out_json_path, "w") as f: json.dump(d, f) if __name__ == "__main__": main()
[ "os.listdir", "argparse.ArgumentParser", "pathlib.Path", "os.path.join", "shutil.copy", "mmpose.apis.inference_bottom_up_pose_model", "warnings.warn", "json.dump", "mmpose.datasets.DatasetInfo" ]
[((744, 760), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (758, 760), False, 'from argparse import ArgumentParser\n'), ((1757, 1783), 'os.path.join', 'osp.join', (['args.img_dir', 'fn'], {}), '(args.img_dir, fn)\n', (1765, 1783), True, 'import os.path as osp\n'), ((2253, 2404), 'warnings.warn', 'warnings.warn', (['"""Please set `dataset_info` in the config.Check https://github.com/open-mmlab/mmpose/pull/663 for details."""', 'DeprecationWarning'], {}), "(\n 'Please set `dataset_info` in the config.Check https://github.com/open-mmlab/mmpose/pull/663 for details.'\n , DeprecationWarning)\n", (2266, 2404), False, 'import warnings\n'), ((2526, 2551), 'mmpose.datasets.DatasetInfo', 'DatasetInfo', (['dataset_info'], {}), '(dataset_info)\n', (2537, 2551), False, 'from mmpose.datasets import DatasetInfo\n'), ((3108, 3305), 'mmpose.apis.inference_bottom_up_pose_model', 'inference_bottom_up_pose_model', (['pose_model', 'image_name'], {'dataset': 'dataset', 'dataset_info': 'dataset_info', 'pose_nms_thr': 'args.pose_nms_thr', 'return_heatmap': 'return_heatmap', 'outputs': 'output_layer_names'}), '(pose_model, image_name, dataset=dataset,\n dataset_info=dataset_info, pose_nms_thr=args.pose_nms_thr,\n return_heatmap=return_heatmap, outputs=output_layer_names)\n', (3138, 3305), False, 'from mmpose.apis import inference_bottom_up_pose_model, init_pose_model, vis_pose_result\n'), ((4038, 4075), 'shutil.copy', 'shutil.copy', (['image_name', 'out_img_path'], {}), '(image_name, out_img_path)\n', (4049, 4075), False, 'import shutil\n'), ((4334, 4352), 'pathlib.Path', 'Path', (['args.out_dir'], {}), '(args.out_dir)\n', (4338, 4352), False, 'from pathlib import Path\n'), ((4420, 4435), 'json.dump', 'json.dump', (['d', 'f'], {}), '(d, f)\n', (4429, 4435), False, 'import json\n'), ((1664, 1682), 'pathlib.Path', 'Path', (['args.out_dir'], {}), '(args.out_dir)\n', (1668, 1682), False, 'from pathlib import Path\n'), ((1802, 1826), 'os.listdir', 'os.listdir', (['args.img_dir'], {}), '(args.img_dir)\n', (1812, 1826), False, 'import os\n'), ((3987, 4005), 'pathlib.Path', 'Path', (['args.out_dir'], {}), '(args.out_dir)\n', (3991, 4005), False, 'from pathlib import Path\n'), ((4008, 4024), 'pathlib.Path', 'Path', (['image_name'], {}), '(image_name)\n', (4012, 4024), False, 'from pathlib import Path\n'), ((4148, 4164), 'pathlib.Path', 'Path', (['image_name'], {}), '(image_name)\n', (4152, 4164), False, 'from pathlib import Path\n'), ((2916, 2932), 'pathlib.Path', 'Path', (['image_name'], {}), '(image_name)\n', (2920, 2932), False, 'from pathlib import Path\n')]
# This file is part of the Etsin service # # Copyright 2017-2018 Ministry of Education and Culture, Finland # # :author: CSC - IT Center for Science Ltd., Espoo Finland <<EMAIL>> # :license: MIT import requests from requests import HTTPError, ConnectionError, Timeout import json from time import sleep from etsin_finder_search.reindexing_log import get_logger log = get_logger(__name__) TIMEOUT = 1200 NUM_RETRIES = 3 class MetaxAPIService: def __init__(self, metax_api_config): self.METAX_CATALOG_RECORDS_BASE_URL = 'https://{0}/rest/datasets'.format(metax_api_config['HOST']) self.METAX_GET_PIDS_URL = self.METAX_CATALOG_RECORDS_BASE_URL + '/identifiers?latest' self.METAX_GET_ALL_LATEST_DATASETS = \ self.METAX_CATALOG_RECORDS_BASE_URL + '?no_pagination=true&latest&expand_relation=data_catalog' self.METAX_GET_CATALOG_RECORD_URL = self.METAX_CATALOG_RECORDS_BASE_URL + '/{0}?expand_relation=data_catalog' self.USER = metax_api_config['USER'] self.PW = metax_api_config['PASSWORD'] self.VERIFY_SSL = metax_api_config.get('VERIFY_SSL', True) @classmethod def get_metax_api_service(cls, metax_api_config): if metax_api_config: return cls(metax_api_config) else: log.error("Unable to get Metax API config") return None @staticmethod def _do_request(request_func, arg=None): sleep_time = 4 for x in range(0, NUM_RETRIES): try: if arg: response = request_func(arg) else: response = request_func() str_error = None except (ConnectionError, Timeout) as e: str_error = e if str_error: sleep(sleep_time) # wait before trying to fetch the data again sleep_time *= 2 # exponential backoff else: break if not str_error and response: return response return None def get_catalog_record(self, cr_identifier): """ Get a catalog record with the given catalog record identifier from MetaX API. :return: Metax catalog record as json """ def get(identifier): return requests.get(self.METAX_GET_CATALOG_RECORD_URL.format(identifier), headers={'Accept': 'application/json'}, auth=(self.USER, self.PW), verify=self.VERIFY_SSL, timeout=TIMEOUT) response = self._do_request(get, cr_identifier) if not response: log.error("Not able to get response from Metax API with identifier {0}".format(cr_identifier)) return None try: response.raise_for_status() except HTTPError as e: log.error('Failed to get catalog record: \nidentifier={id}, \nerror={error}, \njson={json}'.format( id=cr_identifier, error=repr(e), json=self.json_or_empty(response))) log.error('Response text: %s', response.text) return None return json.loads(response.text) def get_latest_catalog_record_identifiers(self): """ Get a list of latest catalog record identifiers in terms of dataset versioning from MetaX API. :return: List of latest catalog record identifiers in Metax """ def get(): return requests.get(self.METAX_GET_PIDS_URL, headers={'Accept': 'application/json'}, auth=(self.USER, self.PW), verify=self.VERIFY_SSL, timeout=TIMEOUT) response = self._do_request(get) if not response: log.error("Unable to connect to Metax API") return None try: response.raise_for_status() except HTTPError as e: log.error('Failed to get identifiers from Metax: \nerror={error}, \njson={json}'.format( error=repr(e), json=self.json_or_empty(response))) log.error('Response text: %s', response.text) return None return json.loads(response.text) def get_latest_catalog_records(self): """ Get a list of latest catalog records in terms of dataset versioning from MetaX API. :return: List of latest catalog records in Metax """ def get(): return requests.get(self.METAX_GET_ALL_LATEST_DATASETS, headers={'Accept': 'application/json'}, auth=(self.USER, self.PW), verify=self.VERIFY_SSL, timeout=TIMEOUT) response = self._do_request(get) if not response: log.error("Unable to connect to Metax API") return None try: response.raise_for_status() except HTTPError as e: log.error('Failed to get identifiers from Metax: \nerror={error}, \njson={json}'.format( error=repr(e), json=self.json_or_empty(response))) log.error('Response text: %s', response.text) return None return json.loads(response.text) @staticmethod def json_or_empty(response): response_json = "" try: response_json = response.json() except Exception: pass return response_json
[ "etsin_finder_search.reindexing_log.get_logger", "time.sleep", "json.loads", "requests.get" ]
[((370, 390), 'etsin_finder_search.reindexing_log.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (380, 390), False, 'from etsin_finder_search.reindexing_log import get_logger\n'), ((3194, 3219), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (3204, 3219), False, 'import json\n'), ((4281, 4306), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (4291, 4306), False, 'import json\n'), ((5346, 5371), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (5356, 5371), False, 'import json\n'), ((3509, 3659), 'requests.get', 'requests.get', (['self.METAX_GET_PIDS_URL'], {'headers': "{'Accept': 'application/json'}", 'auth': '(self.USER, self.PW)', 'verify': 'self.VERIFY_SSL', 'timeout': 'TIMEOUT'}), "(self.METAX_GET_PIDS_URL, headers={'Accept': 'application/json'\n }, auth=(self.USER, self.PW), verify=self.VERIFY_SSL, timeout=TIMEOUT)\n", (3521, 3659), False, 'import requests\n'), ((4563, 4727), 'requests.get', 'requests.get', (['self.METAX_GET_ALL_LATEST_DATASETS'], {'headers': "{'Accept': 'application/json'}", 'auth': '(self.USER, self.PW)', 'verify': 'self.VERIFY_SSL', 'timeout': 'TIMEOUT'}), "(self.METAX_GET_ALL_LATEST_DATASETS, headers={'Accept':\n 'application/json'}, auth=(self.USER, self.PW), verify=self.VERIFY_SSL,\n timeout=TIMEOUT)\n", (4575, 4727), False, 'import requests\n'), ((1803, 1820), 'time.sleep', 'sleep', (['sleep_time'], {}), '(sleep_time)\n', (1808, 1820), False, 'from time import sleep\n')]
# This file is part of sv-witnesses repository: https://github.com/sosy-lab/sv-witnesses # # SPDX-FileCopyrightText: 2020 <NAME> <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 """ This module contains a linter that can check witnesses for consistency with the witness format [1]. [1]: github.com/sosy-lab/sv-witnesses/blob/master/README.md """ __version__ = "1.1" import argparse import collections import hashlib import re import sys from lxml import etree # noqa: S410 does not matter from . import logger as logging from . import witness CREATIONTIME_PATTERN = r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|[+-]\d{2}:\d{2})$" SV_COMP_SPECIFICATIONS = [ "CHECK( init(main()), LTL(G ! call(reach_error())) )", "CHECK( init(main()), LTL(G valid-free) )", "CHECK( init(main()), LTL(G valid-deref) )", "CHECK( init(main()), LTL(G valid-memtrack) )", "CHECK( init(main()), LTL(G valid-memcleanup) )", "CHECK( init(main()), LTL(G ! overflow) )", "CHECK( init(main()), LTL(G ! data-race) )", "CHECK( init(main()), LTL(F end) )", ] WITNESS_VALID = 0 WITNESS_FAULTY = 1 NO_WITNESS = 5 NO_PROGRAM = 6 INTERNAL_ERROR = 7 def create_linter(argv): arg_parser = create_arg_parser() parsed_args = arg_parser.parse_args(argv) logging.create_logger(parsed_args.loglevel) program = parsed_args.program if program is not None: program = program.name return WitnessLinter( witness.Witness(parsed_args.witness.name), program, parsed_args ) def witness_file(path): try: return open(path, "r") except FileNotFoundError as e: print(e) _exit(NO_WITNESS) def program_file(path): try: return open(path, "r") except FileNotFoundError as e: print(e) _exit(NO_PROGRAM) def create_arg_parser(): parser = argparse.ArgumentParser() parser.add_argument( "--version", action="version", version="This is version {} of the witness linter.".format(__version__), ) parser.add_argument( "--witness", required=True, help="GraphML file containing a witness. Mandatory argument.", type=witness_file, metavar="WITNESS", ) parser.add_argument( "--loglevel", default="warning", choices=["critical", "error", "warning", "info", "debug"], help="Desired verbosity of logging output. Only log messages at or above " "the specified level are displayed.", metavar="LOGLEVEL", ) parser.add_argument( "program", nargs="?", default=None, help="The program for which the witness was created.", type=program_file, metavar="PROGRAM", ) parser.add_argument( "--strictChecking", help="Also check smaller details, like line numbers from startline tags, " "or whether values of enterFunction and returnFromFunction are consistent. " "This option is better left disabled for big witnesses.", action="store_true", ) parser.add_argument( "--ignoreSelfLoops", help="Produce no warnings when encountering " "edges that represent a self-loop.", action="store_true", ) parser.add_argument( "--svcomp", help="Run some additional checks specific to SV-COMP.", action="store_true", ) parser.add_argument( "--excludeRecentChecks", type=int, nargs="?", metavar="RECENCY_LEVEL", const=1, default=1024, help="Allow failing recently introduced checks." "An optional recency level can be given to specify how recent checks have to be in order to get excluded.", ) return parser class WitnessLinter: """ Contains methods that check different parts of a witness for consistency with the witness format as well as some utility methods for this purpose. The lint() method checks the whole witness. """ def __init__(self, witness, program, options): self.witness = witness self.program_info = None if program is not None: self.collect_program_info(program) self.options = options self.violation_witness_only = set() self.correctness_witness_only = set() self.check_existence_later = set() self.check_later = [] self.key_defaults = {} def collect_program_info(self, program): """ Collects and stores some data about the program for later usage. This method assumes that the given program can be accessed. """ with open(program, "r") as source: content = source.read() num_chars = len(content) num_lines = len(content.split("\n")) # TODO: Collect all function names function_names = [] with open(program, "rb") as source: content = source.read() sha256_hash = hashlib.sha256(content).hexdigest() self.program_info = { "name": program, "num_chars": num_chars, "num_lines": num_lines, "sha256_hash": sha256_hash, "function_names": function_names, } def check_functionname(self, name, pos): if not self.options.strictChecking: return if self.program_info is None: self.check_later.append(lambda: self.check_functionname(name, pos)) elif name not in self.program_info["function_names"]: logging.warning( "'{}' is not a functionname of the program".format(name), pos ) def check_linenumber(self, line, pos): if not self.options.strictChecking: return if self.program_info is None: self.check_later.append(lambda: self.check_linenumber(line, pos)) elif int(line) < 1 or int(line) > self.program_info["num_lines"]: logging.warning("{} is not a valid linenumber".format(line), pos) def check_character_offset(self, offset, pos): if not self.options.strictChecking: return if self.program_info is None: self.check_later.append(lambda: self.check_character_offset(offset, pos)) elif int(offset) < 0 or int(offset) >= self.program_info["num_chars"]: logging.warning("{} is not a valid character offset".format(offset), pos) def check_function_stack(self, transitions, start_node): """ Performs DFS on the given transitions to make sure that all possible paths have a consistent order of function entries and exits. """ to_visit = [(start_node, [])] visited = set() while to_visit: current_node, current_stack = to_visit.pop() if current_node in visited: continue visited.add(current_node) if current_node not in transitions and current_stack: logging.warning( "No leaving transition for node {} but not all " "functions have been left".format(current_node) ) for outgoing in transitions.get(current_node, []): function_stack = current_stack[:] if outgoing[2] is not None and outgoing[2] != outgoing[1]: if not function_stack: logging.warning( "Trying to return from function '{0}' in transition " "{1} -> {2} but currently not in a function".format( outgoing[2], current_node, outgoing[0] ) ) elif outgoing[2] == current_stack[-1]: function_stack.pop() else: logging.warning( "Trying to return from function '{0}' in transition " "{1} -> {2} but currently in function {3}".format( outgoing[2], current_node, outgoing[0], function_stack[-1], ) ) if outgoing[1] is not None and outgoing[1] != outgoing[2]: function_stack.append(outgoing[1]) to_visit.append((outgoing[0], function_stack)) def handle_data(self, data, parent): """ Performs checks that are common to all data elements and invokes appropriate specialized checks. A data element must have a 'key' attribute specifying the kind of data it holds. Data elements in a witness are currently not supposed have any children. """ if len(data) > 0: logging.warning( "Expected data element to not have any children but has {}".format( len(data) ), data.sourceline, ) if len(data.attrib) > 1: logging.warning( "Expected data element to have exactly one attribute " "but has {}".format(len(data.attrib)), data.sourceline, ) key = data.attrib.get(witness.KEY) if key is None: logging.warning( "Expected data element to have attribute 'key'", data.sourceline ) else: self.witness.used_keys.add(key) _, _, tag = parent.tag.rpartition("}") if tag == witness.NODE: self.handle_node_data(data, key, parent) elif tag == witness.EDGE: self.handle_edge_data(data, key, parent) elif tag == witness.GRAPH: self.handle_graph_data(data, key) else: raise AssertionError("Invalid parent element of type " + parent.tag) def handle_node_data(self, data, key, parent): """ Performs checks for data elements that are direct children of a node element. """ data.text = data.text.strip() if key == witness.ENTRY: if data.text == "true": if self.witness.entry_node is None: self.witness.entry_node = parent.attrib.get("id", "") else: logging.warning("Found multiple entry nodes", data.sourceline) elif data.text == "false": logging.info( "Specifying value 'false' for key 'entry' is unnecessary", data.sourceline, ) else: logging.warning( "Invalid value for key 'entry': {}".format(data.text), data.sourceline, ) elif key == witness.SINK: if data.text == "false": logging.info( "Specifying value 'false' for key 'sink' is unnecessary", data.sourceline, ) elif data.text == "true": node_id = parent.attrib.get("id") if node_id is not None: if ( node_id in self.witness.transition_sources or node_id in self.witness.transitions ): logging.warning( "Sink node should have no leaving edges", data.sourceline ) self.witness.sink_nodes.add(node_id) else: logging.warning( "Invalid value for key 'sink': {}".format(data.text), data.sourceline, ) self.violation_witness_only.add(key) elif key == witness.VIOLATION: if data.text == "false": logging.info( "Specifying value 'false' for key 'violation' is unnecessary", data.sourceline, ) elif not data.text == "true": logging.warning( "Invalid value for key 'violation': {}".format(data.text), data.sourceline, ) self.violation_witness_only.add(key) elif key == witness.INVARIANT: self.correctness_witness_only.add(key) # TODO: Check whether data.text is a valid invariant elif key == witness.INVARIANT_SCOPE: self.correctness_witness_only.add(key) self.check_functionname(data.text, data.sourceline) elif key == witness.CYCLEHEAD: if data.text == "true": if self.witness.cyclehead is None: self.witness.cyclehead = parent.attrib.get("id", "") else: logging.warning("Found multiple cycleheads", data.sourceline) # Check disabled for SV-COMP'21 as questions about the specification # need to be resolved first, see # https://github.com/sosy-lab/sv-witnesses/issues/32 # if not self.invariant_present(parent): # logging.warning( # "Cyclehead does not contain an invariant", # data.sourceline, # ) elif data.text == "false": logging.info( "Specifying value 'false' for key 'cyclehead' is unnecessary", data.sourceline, ) else: logging.warning( "Invalid value for key 'cyclehead': {}".format(data.text), data.sourceline, ) elif self.witness.defined_keys.get(key) == witness.NODE: # Other, tool-specific keys are allowed as long as they have been defined pass else: logging.warning( "Unknown key for node data element: {}".format(key), data.sourceline ) def invariant_present(self, elem): if witness.INVARIANT in self.key_defaults: return True for child in elem: if ( child.tag.rpartition("}")[2] == witness.DATA and child.attrib.get(witness.KEY) == witness.INVARIANT ): return True return False def handle_edge_data(self, data, key, parent): """ Performs checks for data elements that are direct children of an edge element. """ data.text = data.text.strip() if key == witness.ASSUMPTION: self.violation_witness_only.add(key) # TODO: Check whether all expressions from data.text are valid assumptions if "\\result" in data.text: resultfunction_present = False for child in parent: if ( child.tag.rpartition("}")[2] == witness.DATA and child.attrib.get(witness.KEY) == witness.ASSUMPTION_RESULTFUNCTION ): resultfunction_present = True break if not resultfunction_present: logging.warning( "Found assumption containing '\\result' but " "no resultfunction was specified", data.sourceline, ) elif key == witness.ASSUMPTION_SCOPE: self.violation_witness_only.add(key) self.check_functionname(data.text, data.sourceline) elif key == witness.ASSUMPTION_RESULTFUNCTION: self.violation_witness_only.add(key) self.check_functionname(data.text, data.sourceline) elif key == witness.CONTROL: if data.text not in ["condition-true", "condition-false"]: logging.warning( "Invalid value for key 'control': {}".format(data.text), data.sourceline, ) elif key == witness.STARTLINE: self.check_linenumber(data.text, data.sourceline) elif key == witness.ENDLINE: self.check_linenumber(data.text, data.sourceline) elif key == witness.STARTOFFSET: self.check_character_offset(data.text, data.sourceline) elif key == witness.ENDOFFSET: self.check_character_offset(data.text, data.sourceline) elif key == witness.ENTERLOOPHEAD: if data.text == "false": logging.info( "Specifying value 'false' for key 'enterLoopHead' is unnecessary", data.sourceline, ) elif not data.text == "true": logging.warning( "Invalid value for key 'enterLoopHead': {}".format(data.text), data.sourceline, ) elif key == witness.ENTERFUNCTION: for child in parent: child.text = child.text.strip() if ( child.tag.rpartition("}")[2] == witness.DATA and child.attrib.get(witness.KEY) == witness.THREADID and child.text in self.witness.threads and self.witness.threads[child.text] is None ): self.witness.threads[child.text] = data.text break self.check_functionname(data.text, data.sourceline) elif key in ["returnFrom", witness.RETURNFROMFUNCTION]: for child in parent: child.text = child.text.strip() if ( child.tag.rpartition("}")[2] == witness.DATA and child.attrib.get(witness.KEY) == witness.THREADID and child.text in self.witness.threads and self.witness.threads[child.text] == data.text ): del self.witness.threads[child.text] break self.check_functionname(data.text, data.sourceline) elif key == witness.THREADID: # Check disabled for SV-COMP'21 as questions about the specification # need to be resolved first, see # https://gitlab.com/sosy-lab/sv-comp/archives-2021/-/issues/30 # if data.text not in self.witness.threads: # logging.warning( # "Thread with id {} doesn't exist".format(data.text), # data.sourceline, # ) pass elif key == witness.CREATETHREAD: if data.text in self.witness.threads: # logging.warning( # "Thread with id {} has already been created".format(data.text), # data.sourceline, # ) pass else: self.witness.threads[data.text] = None elif self.witness.defined_keys.get(key) == witness.EDGE: # Other, tool-specific keys are allowed as long as they have been defined pass else: logging.warning( "Unknown key for edge data element: {}".format(key), data.sourceline ) def handle_graph_data(self, data, key): """ Performs checks for data elements that are direct children of a graph element. """ data.text = data.text.strip() if key == witness.WITNESS_TYPE: if data.text not in ["correctness_witness", "violation_witness"]: logging.warning( "Invalid value for key 'witness-type': {}".format(data.text), data.sourceline, ) elif self.witness.witness_type is None: self.witness.witness_type = data.text else: logging.warning( "Found multiple definitions of witness-type", data.sourceline ) elif key == witness.SOURCECODELANG: if data.text not in ["C", "Java"]: logging.warning( "Invalid value for key 'sourcecodelang': {}".format(data.text), data.sourceline, ) elif self.witness.sourcecodelang is None: self.witness.sourcecodelang = data.text else: logging.warning( "Found multiple definitions of sourcecodelang", data.sourceline ) elif key == witness.PRODUCER: if self.witness.producer is None: self.witness.producer = data.text else: logging.warning( "Found multiple definitions of producer", data.sourceline ) elif key == witness.SPECIFICATION: self.witness.specifications.add(data.text) if self.options.svcomp and data.text not in SV_COMP_SPECIFICATIONS: logging.warning("Invalid specification for SV-COMP", data.sourceline) elif key == witness.PROGRAMFILE: if self.witness.programfile is None: self.witness.programfile = data.text try: source = open(self.witness.programfile) source.close() if self.program_info is None: self.collect_program_info(self.witness.programfile) except FileNotFoundError: logging.info( "Programfile specified in witness could not be accessed", data.sourceline, ) else: logging.warning( "Found multiple definitions of programfile", data.sourceline ) elif key == witness.PROGRAMHASH: if ( self.program_info is not None and self.options.excludeRecentChecks > 1 and data.text.lower() != self.program_info.get("sha256_hash") ): logging.warning( "Programhash does not match the hash specified in the witness", data.sourceline, ) if self.witness.programhash is None: self.witness.programhash = data.text else: logging.warning( "Found multiple definitions of programhash", data.sourceline ) elif key == witness.ARCHITECTURE: if self.witness.architecture is not None: logging.warning( "Found multiple definitions of architecture", data.sourceline ) elif data.text in ["32bit", "64bit"]: self.witness.architecture = data.text else: logging.warning("Invalid architecture identifier", data.sourceline) elif key == witness.CREATIONTIME: if self.witness.creationtime is not None: logging.warning( "Found multiple definitions of creationtime", data.sourceline ) else: self.witness.creationtime = data.text if self.options.excludeRecentChecks > 1 and not re.match( CREATIONTIME_PATTERN, data.text ): logging.warning("Invalid format for creationtime", data.sourceline) elif self.witness.defined_keys.get(key) == witness.GRAPH: # Other, tool-specific keys are allowed as long as they have been defined pass else: logging.warning( "Unknown key for graph data element: {}".format(key), data.sourceline ) def handle_key(self, key): """ Checks a key definition for validity. Should the key definition contain the mandatory 'id' and 'for' attributes the defined key may be used in the appropriate data elements of any following graph definitions, even if the key definition is faulty for other reasons. Appropriate are all data elements that are direct children of an element of type key_domain, which is the value of the 'for' attribute. Key definitions in a witness may have a child element of type 'default' specifying the default value for this key, but are currently expected to have no other children. """ key_id = key.attrib.get("id") key_domain = key.attrib.get("for") if key_id and key_domain: if key_id in self.witness.defined_keys: logging.warning( "Found multiple key definitions with id '{}'".format(key_id), key.sourceline, ) else: if witness.COMMON_KEYS.get(key_id, key_domain) != key_domain: logging.warning( "Key '{0}' should be used for '{1}' elements but " "was defined for '{2}' elements".format( key_id, witness.COMMON_KEYS[key_id], key_domain ), key.sourceline, ) self.witness.defined_keys[key_id] = key_domain else: if key_id is None: logging.warning("Key is missing attribute 'id'", key.sourceline) if key_domain is None: logging.warning("Key is missing attribute 'for'", key.sourceline) if len(key) > 1: logging.warning( "Expected key to have at most one child but has {}".format(len(key)), key.sourceline, ) for child in key: child.text = child.text.strip() if child.tag.rpartition("}")[2] == witness.DEFAULT: if len(child.attrib) != 0: logging.warning( "Expected no attributes for 'default'" "element but found {0} ({1})".format( len(child.attrib), list(child.attrib) ), key.sourceline, ) if key_id in [ witness.ENTRY, witness.SINK, witness.VIOLATION, witness.ENTERLOOPHEAD, ]: if not child.text == "false": logging.warning( "Default value for {} should be 'false'".format(key_id), key.sourceline, ) self.key_defaults[key_id] = child.text else: logging.warning( "Invalid child for key element: {}".format(child.tag), child.sourceline, ) def handle_node(self, node): """ Checks a node element for validity. Nodes must have an unique id but should not have any other attributes. Nodes in a witness are currently not supposed have any non-data children. """ if len(node.attrib) > 1: logging.warning( "Expected node element to have exactly one attribute " "but has {}".format(len(node.attrib)), node.sourceline, ) node_id = node.attrib.get("id") if node_id is None: logging.warning( "Expected node element to have attribute 'id'", node.sourceline ) elif node_id in self.witness.node_ids: logging.warning( "Found multiple nodes with id '{}'".format(node_id), node.sourceline ) else: self.witness.node_ids.add(node_id) for child in node: if child.tag.rpartition("}")[2] == witness.DATA: self.handle_data(child, node) else: logging.warning( "Node has unexpected child element of type '{}'".format(child.tag), child.sourceline, ) def handle_edge(self, edge): """ Checks an edge element for validity. Edges must have attributes 'source' and 'target', each referencing a different existing node by its id. Other attributes are allowed but no checks are currently performed for them. Edges in a witness are currently not supposed to have any non-data children. """ source = edge.attrib.get("source") if source is None: logging.warning("Edge is missing attribute 'source'", edge.sourceline) else: if source in self.witness.sink_nodes: logging.warning( "Sink node should have no leaving edges", edge.sourceline ) if not self.options.strictChecking: # Otherwise this information is stored in self.witness.transitions self.witness.transition_sources.add(source) if source not in self.witness.node_ids: self.check_existence_later.add(source) target = edge.attrib.get("target") if target is None: logging.warning("Edge is missing attribute 'target'", edge.sourceline) else: if source == target and not self.options.ignoreSelfLoops: logging.warning( "Node '{}' has self-loop".format(source), edge.sourceline ) if target not in self.witness.node_ids: self.check_existence_later.add(target) if self.options.strictChecking: enter, return_from = (None, None) for child in edge: child.text = child.text.strip() if child.tag.rpartition("}")[2] == witness.DATA: self.handle_data(child, edge) key = child.attrib.get(witness.KEY) if key == witness.ENTERFUNCTION: enter = child.text elif key in ["returnFrom", witness.RETURNFROMFUNCTION]: return_from = child.text else: logging.warning( "Edge has unexpected child element of type '{}'".format( child.tag ), child.sourceline, ) if source and target: if source in self.witness.transitions: self.witness.transitions[source].append( (target, enter, return_from) ) else: self.witness.transitions[source] = [(target, enter, return_from)] else: for child in edge: if child.tag.rpartition("}")[2] == witness.DATA: self.handle_data(child, edge) else: logging.warning( "Edge has unexpected child element of type '{}'".format( child.tag ), child.sourceline, ) def handle_graph(self, graph): """ Checks a graph element for validity. A graph may have an 'edgedefault' attribute specifying whether edges are directed or undirected by default. As edges of witnesses should always be directed the value of the 'edgedefault' attribute is checked to be 'directed'. Other attributes are allowed but no checks are currently performed for them. Currently a witness graph is not supposed to have any children of types other than 'node', 'edge' or 'data'. """ edge_default = graph.attrib.get("edgedefault") if edge_default is None: logging.warning( "Graph definition is missing attribute 'edgedefault'", graph.sourceline ) elif edge_default != "directed": logging.warning("Edgedefault should be 'directed'", graph.sourceline) for child in graph: child_tag = child.tag.rpartition("}")[2] if child_tag == witness.DATA: self.handle_data(child, graph) elif child_tag not in [witness.NODE, witness.EDGE]: logging.warning( "Graph element has unexpected child " "of type '{}'".format(child.tag), child.sourceline, ) def handle_graphml_elem(self, graphml_elem): if None not in graphml_elem.nsmap: logging.warning("Missing default namespace", graphml_elem.sourceline) elif graphml_elem.nsmap[None] != "http://graphml.graphdrawing.org/xmlns": logging.warning( "Unexpected default namespace: {}".format(graphml_elem.nsmap[None]), graphml_elem.sourceline, ) if "xsi" not in graphml_elem.nsmap: logging.warning( "Missing xml schema namespace or namespace prefix is not called 'xsi'", graphml_elem.sourceline, ) elif graphml_elem.nsmap["xsi"] != "http://www.w3.org/2001/XMLSchema-instance": logging.warning( "Expected 'xsi' to be namespace prefix " "for 'http://www.w3.org/2001/XMLSchema-instance'", graphml_elem.sourceline, ) for attr in graphml_elem.attrib.items(): if attr[0] != "{http://www.w3.org/2001/XMLSchema-instance}schemaLocation": logging.warning( "Unexpected attribute on graphml element{}".format( attr[0].rpartition("}")[2] ), graphml_elem.sourceline, ) for child in graphml_elem: if child.tag.rpartition("}")[2] not in [witness.GRAPH, witness.KEY]: logging.warning( "Graphml element has unexpected child of type '{}'".format( child.tag ), graphml_elem.sourceline, ) def final_checks(self): """ Performs checks that cannot be done before the whole witness has been traversed because elements may appear in almost arbitrary order. """ for key in self.witness.used_keys - set(self.witness.defined_keys): if key in witness.COMMON_KEYS: # Already handled for other keys logging.warning("Key '{}' has been used but not defined".format(key)) for key in set(self.witness.defined_keys) - self.witness.used_keys: logging.info( "Unnecessary definition of key '{}', key has never been used".format( key ) ) if self.witness.witness_type is None: logging.warning("Witness-type has not been specified") elif self.witness.witness_type == "correctness_witness": for key in self.violation_witness_only: logging.warning( "Key '{}' is not allowed in correctness witness".format(key) ) elif self.witness.witness_type == "violation_witness": for key in self.correctness_witness_only: if key == witness.INVARIANT and self.witness.is_termination_witness(): continue logging.warning( "Key '{}' is not allowed in violation witness".format(key) ) else: raise AssertionError("Invalid witness type.") if self.witness.sourcecodelang is None: logging.warning("Sourcecodelang has not been specified") if self.witness.producer is None: logging.warning("Producer has not been specified") if not self.witness.specifications: logging.warning("No specification has been specified") if self.witness.programfile is None: logging.warning("Programfile has not been specified") if self.witness.programhash is None: logging.warning("Programhash has not been specified") if self.witness.architecture is None: logging.warning("Architecture has not been specified") if self.witness.creationtime is None and self.options.excludeRecentChecks > 0: logging.warning("Creationtime has not been specified") if self.witness.entry_node is None and self.witness.node_ids: logging.warning("No entry node has been specified") for node_id in self.check_existence_later: if node_id not in self.witness.node_ids: logging.warning("Node {} has not been declared".format(node_id)) if self.options.strictChecking: self.check_function_stack( collections.OrderedDict(sorted(self.witness.transitions.items())), self.witness.entry_node, ) if self.program_info is not None: for check in self.check_later: check() def lint(self): """ Splits the witness into manageable chunks and triggers or performs checks for the resulting elements. Also stores some information to be able to trigger checks for the witness as a whole. """ try: saw_graph = False saw_graphml = False element_stack = [] for (event, elem) in etree.iterparse( self.witness.witness_file, events=("start", "end") ): if event == "start": element_stack.append(elem) else: element_stack.pop() _, _, tag = elem.tag.rpartition("}") if not element_stack and tag != witness.GRAPHML: logging.error("Document root is not a GraphML element") if tag == witness.DATA: # Will be handled later pass elif tag == witness.DEFAULT: # Will be handled later pass elif tag == witness.KEY: self.handle_key(elem) elem.clear() elif tag == witness.NODE: self.handle_node(elem) elem.clear() elif tag == witness.EDGE: self.handle_edge(elem) elem.clear() elif tag == witness.GRAPH: if saw_graph: logging.warning( "Found multiple graph definitions", elem.sourceline ) else: saw_graph = True self.handle_graph(elem) elem.clear() elif tag == witness.GRAPHML: if saw_graphml: logging.warning( "Found multiple graphml elements", elem.sourceline ) else: saw_graphml = True self.handle_graphml_elem(elem) else: logging.warning( "Unknown tag: {}".format(elem.tag), elem.sourceline ) self.final_checks() except etree.XMLSyntaxError as err: logging.critical("Malformed witness:\n\t{}".format(err.msg), err.lineno) def _exit(exit_code=None): if exit_code is None: if logging.critical.counter or logging.error.counter or logging.warning.counter: exit_code = WITNESS_FAULTY else: exit_code = WITNESS_VALID print("\nwitnesslint finished with exit code {}".format(exit_code)) sys.exit(exit_code) def main(argv): try: linter = create_linter(argv[1:]) linter.lint() _exit() except Exception as e: print(type(e).__name__, ":", e) _exit(INTERNAL_ERROR)
[ "hashlib.sha256", "argparse.ArgumentParser", "re.match", "lxml.etree.iterparse", "sys.exit" ]
[((1852, 1877), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1875, 1877), False, 'import argparse\n'), ((40347, 40366), 'sys.exit', 'sys.exit', (['exit_code'], {}), '(exit_code)\n', (40355, 40366), False, 'import sys\n'), ((37821, 37888), 'lxml.etree.iterparse', 'etree.iterparse', (['self.witness.witness_file'], {'events': "('start', 'end')"}), "(self.witness.witness_file, events=('start', 'end'))\n", (37836, 37888), False, 'from lxml import etree\n'), ((4991, 5014), 'hashlib.sha256', 'hashlib.sha256', (['content'], {}), '(content)\n', (5005, 5014), False, 'import hashlib\n'), ((23451, 23492), 're.match', 're.match', (['CREATIONTIME_PATTERN', 'data.text'], {}), '(CREATIONTIME_PATTERN, data.text)\n', (23459, 23492), False, 'import re\n')]
import sys from io import StringIO from PySide6.QtCore import * from PySide6.QtGui import * from PySide6.QtWidgets import * from modules.settings.settings import SettingsManager from modules.pseudo_id.pseudo_id import PseudoIDManager from gms_uploader.modules.models.pandasmodel import PandasModel from gms_uploader.modules.delegates.delegates import ComboBoxDelegate, \ DateAutoCorrectDelegate, AgeDelegate, IconCheckBoxDelegate from gms_uploader.modules.fx.fx_manager import FxManager from gms_uploader.modules.dialogs.dialogs import ValidationDialog, MsgAlert, MsgOKCancel from gms_uploader.modules.models.sortfilterproxymodel import MultiSortFilterProxyModel from gms_uploader.modules.extra.auxiliary_functions import to_list, get_pd_row_index, \ date_validate, age_validate, add_gridlayout_row, update_df from gms_uploader.modules.credentials.credentials import CredManager from gms_uploader.modules.validate.validate import validate from gms_uploader.modules.upload.uploader import Uploader import pandas as pd from datetime import datetime from pathlib import Path import yaml import json import csv from gms_uploader.ui.mw import Ui_MainWindow import qdarktheme import resources __version__ = '0.2.0' __title__ = 'GMS-uploader' class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self): super(MainWindow, self).__init__() self.setup_complete = False self.setupUi(self) self.setAcceptDrops(True) self.clipboard = QGuiApplication.clipboard() self.setWindowIcon(QIcon(':/img/GMS-logo.png')) self.setWindowTitle(__title__ + " " + __version__) self.set_tb_bkg() self.fx_manager = FxManager(Path('fx')) self.fx = None # add icons self.set_icons() default_config_path = Path('config', 'config.yaml') with default_config_path.open(encoding='utf8') as fp: self.conf = yaml.safe_load(fp) self.settm = SettingsManager(self.conf) self.credm = CredManager(self.settm) self.pidm = PseudoIDManager(self.conf['tr']['lab_to_code'], self.settm) self.fx_config = None self.tableView_columns = list(self.conf['model_fields'].keys()) self.df = pd.DataFrame(columns=self.tableView_columns) self.model = PandasModel(self.df, self.conf['model_fields']) self.mfilter_sort_proxy_model = MultiSortFilterProxyModel() self.filter_cols = self.get_filter_cols() # setup settings self.delegates = {} self.delegates['patient'] = {} self.delegates['lab'] = {} self.delegates['organism'] = {} self.set_signals() self.setup_tableviews() # self.set_dataview_setting_widget_values() self.stackedWidget.setCurrentIndex(0) self.tabWidget_metadata.setCurrentIndex(0) self.set_hidden_columns() self.set_col_widths() self.setup_settingview_widgets() self.set_delegates() # Status widgets change status to activated when there is data in the model. Default is disabled. self.status_widgets = [ self.action_import_csv, self.action_upload_meta_seqs, self.pushButton_filtermarked, self.pushButton_invert, self.pushButton_drop, self.pushButton_clear, self.pushButton_filldown, self.pushButton_resetfilters, self.action_save_meta, self.action_import_fx, self.action_paste_fx, self.lineEdit_filter ] self.set_datastatus_empty(True) self.ui_init() self.setup_complete = True # setup and init-related functions def ui_init(self): self.tabWidget_metadata.setStyleSheet("QTabWidget::pane { border: 0; }") self.scrollArea.setStyleSheet("QScrollArea { border: 0; }") self.toolBar.setFixedWidth(50) self.toolBar.setMovable(False) self.tabWidget_metadata.setTabText(0, "patient metadata") self.tabWidget_metadata.setTabText(1, "organism metadata") self.tabWidget_metadata.setTabText(2, "lab metadata") self.lineEdit_filter.setPlaceholderText("freetext filter") self.action_import_fx.setDisabled(True) self.action_paste_fx.setDisabled(True) def get_filter_cols(self): cols = list(self.df.columns) used_cols = self.conf['freetext_filter']['model_fields'] return [self.df.columns.get_loc(c) for c in cols if c in used_cols] def set_tb_bkg(self): """ Sets bg image to tableviews. Image shown before metadata is imported. :return: None """ img = ':/img/GMS-logo.png' for tbv in [self.tableView_patient, self.tableView_organism, self.tableView_lab]: tbv.setStyleSheet( """ background-repeat: no-repeat; background-position: center; background-image: url(%s); """ % img ) tbv.horizontalScrollBar().setStyleSheet( """ background: white; """ ) def rem_tb_bkg(self): """ Removes bg image from tableviews. Images removed when metadata is imported, otherwise they are visible through the tables. :return: None """ for tbv in [self.tableView_patient, self.tableView_organism, self.tableView_lab]: tbv.setStyleSheet("background-image: none;") def set_signals(self): """ Setup of signals for static widgets (pushbuttons, actionbuttons, lineedit for filter). :return: """ self.action_show_prefs.triggered.connect(lambda: self.stackedWidget.setCurrentIndex(1)) self.action_show_meta.triggered.connect(lambda: self.stackedWidget.setCurrentIndex(0)) self.lineEdit_filter.textChanged.connect(self.set_free_filter) self.pushButton_filtermarked.setCheckable(True) self.pushButton_filtermarked.clicked.connect(self.set_mark_filter) self.pushButton_drop.clicked.connect(self.drop_rows) self.pushButton_clear.clicked.connect(self.clear_table) self.action_select_seq_files.triggered.connect(self.get_seq_files) self.action_upload_meta_seqs.triggered.connect(self.upload) self.action_save_meta.triggered.connect(self.save_metadata_file) self.action_open_meta.triggered.connect(self.open_metadata_file) self.pushButton_invert.clicked.connect(self.invert_marks) self.action_import_csv.triggered.connect(self.get_csv_file_combine) def set_icons(self): self.action_open_meta.setIcon(QIcon(':/icons/AppIcons/folder-open-outline_mdi.svg')) self.action_save_meta.setIcon(QIcon(':/icons/AppIcons/content-save-outline_mdi.svg')) self.action_show_meta.setIcon(QIcon(':/table')) # ':/icons/AppIcons/table_mdi.svg')) self.action_show_prefs.setIcon(QIcon(':/cog')) #:/icons/AppIcons/cog-outline_mdi.svg')) self.action_upload_meta_seqs.setIcon(QIcon(':/icons/AppIcons/tray-arrow-up_mdi.svg')) self.action_select_seq_files.setIcon(QIcon(':/icons/AppIcons/folder-open-outline-dna_mdi.svg')) self.action_import_csv.setIcon(QIcon(':/import-csv')) #':/icons/AppIcons/import-csv_own.svg')) self.action_import_fx.setIcon(QIcon(':/import-fx')) #':/icons/AppIcons/content-import-fx_own.svg')) self.action_paste_fx.setIcon(QIcon(':/paste-fx')) #':/icons/AppIcons/content-paste-fx_own.svg')) self.pushButton_filldown.setIcon(QIcon(':/arrow-down')) #':/icons/AppIcons/arrow-down_mdi.svg')) self.pushButton_drop.setIcon(QIcon(':/close')) #':/icons/AppIcons/close_mdi.svg')) self.pushButton_clear.setIcon(QIcon(':/clear')) # ':/icons/AppIcons/delete-outline_mdi.svg')) self.pushButton_resetfilters.setIcon(QIcon('/filter-remove')) #QIcon(':/icons/AppIcons/filter-remove-outline_mdi.svg')) self.pushButton_filtermarked.setIcon(QIcon(':/filter')) # QIcon(':/icons/AppIcons/filter-outline_mdi.svg')) self.pushButton_invert.setIcon(QIcon(':/invert')) #':/icons/AppIcons/invert_own.svg')) def set_col_widths(self): for i, name in enumerate(self.conf['model_fields']): self.tableView_patient.setColumnWidth(i, self.conf['model_fields'][name]['col_width']) self.tableView_organism.setColumnWidth(i, self.conf['model_fields'][name]['col_width']) self.tableView_lab.setColumnWidth(i, self.conf['model_fields'][name]['col_width']) def set_hidden_columns(self): for i, name in enumerate(self.conf['model_fields']): if 'patient' not in self.conf['model_fields'][name]['view']: self.tableView_patient.setColumnHidden(i, True) if 'organism' not in self.conf['model_fields'][name]['view']: self.tableView_organism.setColumnHidden(i, True) if 'lab' not in self.conf['model_fields'][name]['view']: self.tableView_lab.setColumnHidden(i, True) def set_dataview_setting_widget_values(self): """ Sets values in static lineedits on the dataview pane. :return: None """ print("reset dataviews") self.lineEdit_submitter.setText(str(self.settm.get_value("entered_value", "submitter"))) self.lineEdit_lab.setText(str(self.settm.get_value("select_single", "lab"))) self.lineEdit_seq_technology.setText(str(self.settm.get_value("select_single", "seq_technology"))) self.lineEdit_host.setText(str(self.settm.get_value("select_single", "host"))) self.lineEdit_lib_method.setText(str(self.settm.get_value("select_single", "library_method"))) self.lineEdit_import_fx.setText(str(self.settm.get_value("select_single", "fx"))) self.lineEdit_pseudo_id.setText(str(self.pidm.get_first_pid())) self.lineEdit_ul_target_label.setText(str(self.credm.get_current_target_label())) self.lineEdit_ul_protocol.setText(str(self.credm.get_current_protocol())) def setup_settingview_widgets(self): """ Creates and sets up dymamic setting widgets based on the config file :return: None """ for category in self.conf['settings_structure']: if category['target_layout'] == "form": category_name = category['label'] label = QLabel(category_name) label.setProperty("class", "bold") self.verticalLayout_forms.addWidget(label) grid_layout = QGridLayout() grid_layout.setColumnMinimumWidth(0, 150) self.verticalLayout_forms.addLayout(grid_layout) for item in category['items']: for field_type, fields in item.items(): if field_type == "entered_value": for field in fields: func = self.get_button_func(field) if func is not None: button_name = field + "button" button = QPushButton("...", objectName=button_name) button.clicked.connect(func) edit = QLineEdit(objectName=field) edit.textChanged.connect(self.update_setting) edit.setReadOnly(True) hbox = QHBoxLayout() hbox.addWidget(edit) hbox.addWidget(button) label = QLabel(field) label.setProperty("class", "padding-left") label.setMinimumWidth(40) value = self.settm.get_value(field_type, field) edit.setText(str(value)) add_gridlayout_row(grid_layout, label, hbox) else: edit = QLineEdit(objectName=field, editingFinished=self.update_setting) value = self.settm.get_value(field_type, field) edit.setText(value) label = QLabel(field) label.setProperty("class", "padding-left") label.setMinimumWidth(40) add_gridlayout_row(grid_layout, label, edit) elif field_type == "select_single": for field in fields: combo = QComboBox(objectName=field) combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) items = [] if field in self.conf['add_empty_selection']: items = ['None'] if field == "fx": for name in self.fx_manager.get_fx_names(): items.append(name) else: if self.conf['settings_values']['select_single'][field] != "None": items.extend(list(self.conf['settings_values']['select_single'][field].keys())) combo.addItems(items) value = self.settm.get_value(field_type, field) combo.setCurrentText(value) label = QLabel(field) label.setProperty("class", "padding-left") label.setMinimumWidth(40) combo.currentTextChanged.connect(self.update_setting) add_gridlayout_row(grid_layout, label, combo) elif field_type == "select_single_fx": for field in fields: combo = QComboBox(objectName=field) combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) combo.addItem(str('None')) for name in self.fx_manager.get_fx_names(): combo.addItem(str(name)) label = QLabel(field) label.setProperty("class", "padding-left") label.setMinimumWidth(40) value = self.settm.get_value('select_single', field) if value is not None: if combo.findText(value) >= 0: combo.setCurrentText(value) combo.currentTextChanged.connect(self.update_setting) add_gridlayout_row(grid_layout, label, combo) elif category['target_layout'] == "tabs": category_name = category['label'] label = QLabel(category_name) label.setProperty("class", "bold") self.verticalLayout_tabs.addWidget(QLabel()) self.verticalLayout_tabs.addWidget(label) tabwidget_settings = QTabWidget(objectName='tabwidget_settings') tabwidget_settings.setMinimumHeight(420) tabwidget_settings.setStyleSheet("QTabWidget::pane { border: 0; }") tabwidget_settings.setMinimumHeight(550) self.verticalLayout_tabs.addWidget(tabwidget_settings) for item in category['items']: for field_type, fields in item.items(): if field_type == "select_multi": for field in fields: value = self.settm.get_value(field_type, field) store_checked = to_list(value) model = QStandardItemModel() model.setColumnCount(2) tableview = QTableView() model = QStandardItemModel(objectName=field) model.setColumnCount(2) for key, checked in self.conf['settings_values'][field_type][field].items(): item1 = QStandardItem("0") item2 = QStandardItem(key) if key in store_checked: item1.setText("1") model.appendRow([item1, item2]) tableview.setModel(model) tableview.setItemDelegateForColumn(0, IconCheckBoxDelegate(None)) tableview.setColumnWidth(0, 15) hheader = tableview.horizontalHeader() hheader.setStretchLastSection(True) hheader.hide() tableview.verticalHeader().setDefaultSectionSize(20) tableview.verticalHeader().hide() tableview.setShowGrid(False) model.itemChanged.connect(self.update_setting) tabwidget_settings.addTab(tableview, field) self.set_target_label_items() self.set_dataview_setting_widget_values() self.set_fx() def set_fx(self): value = self.settm.get_value('select_single', 'fx') if value is not None and value != 'None': self.fx = self.fx_manager.load_fx(value) self.fx.set_path(self.settm.get_value('entered_value', 'fx_import_path')) if self.fx.from_clipboard: self.action_paste_fx.triggered.connect(self.import_fx_clipboard) if self.fx.from_file: self.action_import_fx.triggered.connect(self.import_fx_file) def update_setting(self, item=None): if self.setup_complete: if isinstance(item, QStandardItem): self.settm.update_setting(item=item) else: obj = self.sender() self.settm.update_setting(obj=obj) self.pidm.init_settings() self.set_dataview_setting_widget_values() self.update_delegates() self.set_fx() def setup_tableviews(self): """ Setup of data tableviews, connects to mfilter_sort_proxy_model, and the pandas model. :return: None """ self.mfilter_sort_proxy_model.setSourceModel(self.model) self.tableView_patient.setModel(self.mfilter_sort_proxy_model) self.tableView_patient.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked | QAbstractItemView.EditKeyPressed) self.tableView_patient.horizontalHeader().setStretchLastSection(True) self.tableView_patient.horizontalHeader().setSectionsMovable(True) self.tableView_patient.setSortingEnabled(True) self.tableView_organism.setModel(self.mfilter_sort_proxy_model) self.tableView_organism.setEditTriggers( QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked | QAbstractItemView.EditKeyPressed) self.tableView_organism.horizontalHeader().setStretchLastSection(True) self.tableView_organism.horizontalHeader().setSectionsMovable(True) self.tableView_organism.setSortingEnabled(True) self.tableView_lab.setModel(self.mfilter_sort_proxy_model) self.tableView_lab.setEditTriggers( QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked | QAbstractItemView.EditKeyPressed) self.tableView_lab.horizontalHeader().setStretchLastSection(True) self.tableView_lab.horizontalHeader().setSectionsMovable(True) self.tableView_lab.setSortingEnabled(True) self.pushButton_resetfilters.clicked.connect(self.reset_sort_filter) self.pushButton_filldown.clicked.connect(self.filldown) self.tableView_patient.verticalHeader().hide() self.tableView_lab.verticalHeader().hide() self.tableView_organism.verticalHeader().hide() self.update_model() def setup_credentials(self): self.credm = CredManager(self.settm) # def load_fx_settings(self): # store_key = "/".join(['select_single', 'import_fx']) # fx_name = self.qsettings.value(store_key) # # # default_config_path = Path('config', 'config.yaml') # with default_config_path.open(encoding='utf8') as fp: # self.conf = yaml.safe_load(fp) # model and data-import related functions def update_model(self): self.model = PandasModel(self.df, self.conf['model_fields']) self.mfilter_sort_proxy_model = MultiSortFilterProxyModel() self.mfilter_sort_proxy_model.setSourceModel(self.model) self.tableView_patient.setModel(self.mfilter_sort_proxy_model) self.tableView_lab.setModel(self.mfilter_sort_proxy_model) self.tableView_organism.setModel(self.mfilter_sort_proxy_model) self.set_col_widths() def df_insert(self, df, row): insert_loc = df.index.max() if pd.isna(insert_loc): df.loc[0] = row else: df.loc[insert_loc + 1] = row def verify_files(self, files): """ Ensures that all filespaths in a list exist and have correct suffixes, corresponding to raw sequence data files. Only correct files are returned. If a path is a dir, paths for files in that directory are listed, verified and returned. :param files: list of filepaths and/or dirpaths :return: list of verified filepaths """ verified_files = [] for file in files: f = Path(file) if f.is_dir(): for type in self.conf['seq_files']: ext = self.conf['seq_files'][type]['ext'] for fp in f.rglob(ext): if Path(fp).exists(): verified_files.append(fp) else: for type in self.conf['seq_files']: ext = self.conf['seq_files'][type]['ext'] if f.match(ext) and f.exists(): verified_files.append(f) return verified_files def extract_metadata_from_filenames(self, files): """ Extract metadata from sequence data filenames :param files: list of filepaths :return: list of dicts with metadata from filenames """ _data = {} for file in files: seq_path = file.parent filename = file.name filename_obj = Path(filename) sample = filename.split('_')[0] if sample not in _data: _data[sample] = {} _data[sample]['seq_path'] = str(seq_path) if filename_obj.match(self.conf['seq_files']['fastq_gz']['ext']): f = file.stem.split('.')[0] lane = f.split('_')[-1] _data[sample]['lane'] = lane if 'fastq' not in _data[sample]: _data[sample]['fastq'] = [] fastq_list = _data[sample]['fastq'] fastq_list.append(filename) elif filename_obj.match(self.conf['seq_files']['fast5']['ext']): if 'fast5' not in _data[sample]: _data[sample]['fast5'] = [] fast5_list = _data[sample]['fast5'] fast5_list.append(filename) filename_metadata = [] for sample in _data: row = dict() row['mark'] = 0 # add mark column row['internal_lab_id'] = sample for key in _data[sample]: value = _data[sample][key] if isinstance(value, list): sorted_files = sorted(value) row[key] = sorted_files else: row[key] = value filename_metadata.append(row) return filename_metadata def find_duplicates(self, df1, df2): """ Checks if the same internal_lab_id are present in two dataframes :param df1: dataframe1 :param df2: dataframe2 :return: Bool """ df3 = df1.append(df2) return df3['internal_lab_id'].duplicated().any() def add_files_metadata_to_model(self, data): """ Creates new pandas df, from files and metadata, check for duplicates and merge with existing df dataset and create new model. :param data: list of dicts containing metadata and filenames :return: None """ new_df = pd.DataFrame(data) if not new_df.empty: if not self.find_duplicates(self.df, new_df): self.df = self.df.append(new_df) self.df = self.df.fillna('') self.update_model() self.rem_tb_bkg() self.set_datastatus_empty(False) else: msg_box = QMessageBox() msg_box.setText("Duplicate SampleIDs present in imported data.") msg_box.exec() # set path functions def get_button_func(self, name): """ gets correct slot function for button :param name: name of settings field :return: func or None if field has no associated button """ func = None if name == "pseudo_id_filepath": func = self.set_pseudo_id_filepath elif name == "seq_base_path": func = self.set_seq_path elif name == "csv_base_path": func = self.set_csv_path elif name == "metadata_output_path": func = self.set_metadata_output_path elif name == "metadata_docs_path": func = self.set_metadata_docs_path elif name == "credentials_path": func = self.set_credentials_path elif name == "fx_import_path": func = self.set_fx_import_path return func def set_seq_path(self): """ Sets sequence base path in dynamic lineedit widget from file-picker. :return: None """ obj = self.sender() button_name = obj.objectName() name = button_name.strip("button") dialog = QFileDialog() default_path = str(Path.home()) dirpath = dialog.getExistingDirectory(self, 'Set an awesome seq root dir path', default_path, options=QFileDialog.ShowDirsOnly | QFileDialog.DontUseNativeDialog) if dirpath: edit = self.stackedWidgetPage2.findChild(QLineEdit, name, Qt.FindChildrenRecursively) edit.setText(dirpath) def set_csv_path(self): """ Set base path to for filedialog for importing csv files. :return: None """ obj = self.sender() button_name = obj.objectName() name = button_name.strip("button") dialog = QFileDialog() default_fn = str(Path.home()) dirpath = dialog.getExistingDirectory(self, 'Set an awesome csv root dir path', default_fn, options=QFileDialog.ShowDirsOnly | QFileDialog.DontUseNativeDialog) if dirpath: edit = self.stackedWidgetPage2.findChild(QLineEdit, name, Qt.FindChildrenRecursively) edit.setText(dirpath) def set_fx_import_path(self): """ :return: """ obj = self.sender() button_name = obj.objectName() name = button_name.strip("button") dialog = QFileDialog() default_fn = str(Path.home()) dirpath = dialog.getExistingDirectory(self, 'Set an awesome fx import root dir path', default_fn, options=QFileDialog.ShowDirsOnly | QFileDialog.DontUseNativeDialog) if dirpath: edit = self.stackedWidgetPage2.findChild(QLineEdit, name, Qt.FindChildrenRecursively) edit.setText(dirpath) if self.fx is not None: self.fx.set_path(Path(dirpath)) def set_metadata_output_path(self): """ Sets dir where metadata json files should be stored. :return: None """ obj = self.sender() button_name = obj.objectName() name = button_name.strip("button") dialog = QFileDialog() default_fn = str(Path.home()) dirpath = dialog.getExistingDirectory(self, 'Set an awesome metadata output dir path', default_fn, options=QFileDialog.ShowDirsOnly | QFileDialog.DontUseNativeDialog) edit = self.stackedWidgetPage2.findChild(QLineEdit, name, Qt.FindChildrenRecursively) edit.setText(dirpath) def set_metadata_docs_path(self): """ Sets base dir path where to save and open pickeled metadata dataframes. :return: None """ obj = self.sender() button_name = obj.objectName() name = button_name.strip("button") dialog = QFileDialog() default_fn = str(Path.home()) dirpath = dialog.getExistingDirectory(self, 'Set an awesome metadata docs dir path', default_fn, options=QFileDialog.ShowDirsOnly | QFileDialog.DontUseNativeDialog) edit = self.stackedWidgetPage2.findChild(QLineEdit, name, Qt.FindChildrenRecursively) edit.setText(dirpath) def set_pseudo_id_filepath(self): """ Set filepath to textfile where pseudo_ids should be stored :return: None """ obj = self.sender() button_name = obj.objectName() name = button_name.strip("button") dialog = QFileDialog() default_fn = "gms-uploader_1_pseudoids.txt" pseudo_id_fp, _ = dialog.getSaveFileName(self, 'Set an awesome pseudo_id filepath', default_fn, "pseudo_ID files (*_pseudoids.txt)", options=QFileDialog.DontUseNativeDialog | QFileDialog.DontConfirmOverwrite) pif_obj = Path(pseudo_id_fp) if pif_obj.parent.exists(): edit = self.stackedWidgetPage2.findChild(QLineEdit, name, Qt.FindChildrenRecursively) edit.setText(pseudo_id_fp) def set_credentials_path(self): """ Sets filepath to credentials json file, used for S3 upload to the HCP/NGP :return: None """ obj = self.sender() button_name = obj.objectName() name = button_name.strip("button") dialog = QFileDialog() default_fn = str(Path.home()) credentials_path = dialog.getExistingDirectory(self, 'Set an awesome credentials dir path', default_fn, options=QFileDialog.ShowDirsOnly | QFileDialog.DontUseNativeDialog) f_obj = Path(credentials_path) if f_obj.is_dir(): edit = self.stackedWidgetPage2.findChild(QLineEdit, name, Qt.FindChildrenRecursively) edit.setText(credentials_path) self.settm.set_value('entered_value', 'credentials_path', credentials_path) self.credm = CredManager(self.settm) self.set_target_label_items() def set_target_label_items(self): print(self.settm.get_value('entered_value', 'credentials_path')) keys = self.credm.get_cred_keys() combobox = self.stackedWidgetPage2.findChild(QComboBox, 'target_label', Qt.FindChildrenRecursively) combobox.clear() items = ['None'] for key in keys: items.append(key) combobox.addItems(items) selected = self.settm.get_value('select_single', 'target_label') if selected is not None: index = combobox.findText(selected) if index >= 0: combobox.setCurrentIndex(index) # delegates def update_delegates(self): if self.setup_complete: self.set_delegates() def set_delegates(self): for field in self.conf['model_fields']: if 'checkbox' in self.conf['model_fields'][field]['delegates']: self.set_checkbox_delegate(field) elif 'combobox' in self.conf['model_fields'][field]['delegates']: self.set_combobox_delegate(field) elif 'date' in self.conf['model_fields'][field]['delegates']: self.set_date_delegate(field) elif 'age' in self.conf['model_fields'][field]['delegates']: self.set_age_delegate(field) def set_combobox_delegate(self, field): items = [''] items.extend(to_list(self.settm.get_value("select_multi", field))) for view in self.conf['model_fields'][field]['view']: self.delegates[view][field] = ComboBoxDelegate(items) if view == 'patient': self.tableView_patient.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) elif view == 'lab': self.tableView_lab.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) elif view == 'organism': self.tableView_organism.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) def set_date_delegate(self, field): for view in self.conf['model_fields'][field]['view']: self.delegates[view][field] = DateAutoCorrectDelegate() if view == 'patient': self.tableView_patient.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) elif view == 'lab': self.tableView_lab.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) elif view == 'organism': self.tableView_organism.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) def set_age_delegate(self, field): for view in self.conf['model_fields'][field]['view']: self.delegates[view][field] = AgeDelegate() if view == 'patient': self.tableView_patient.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) elif view == 'lab': self.tableView_lab.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) elif view == 'organism': self.tableView_organism.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) def set_checkbox_delegate(self, field): """ sets checboxdelegate :param field: field name :return: Nothing """ for view in self.conf['model_fields'][field]['view']: self.delegates[view][field] = IconCheckBoxDelegate(None) if view == 'patient': self.tableView_patient.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) elif view == 'lab': self.tableView_lab.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) elif view == 'organism': self.tableView_organism.setItemDelegateForColumn(self.tableView_columns.index(field), self.delegates[view][field]) # Data-view, filter and related functions, utility functions def accept_paste(self, value, colname): if not self.conf['model_fields'][colname]['edit'] or colname == 'mark': return False if isinstance(self.conf['paste_validators']['model_fields'][colname], bool): if self.conf['paste_validators']['model_fields'][colname] is True: return True else: return False if 'qsettings' in self.conf['paste_validators']['model_fields'][colname]: field_type, field = self.conf['paste_validators']['model_fields'][colname]['qsettings'] accepted = self.settm.get_value(field_type, field) if isinstance(accepted, list): if value not in accepted: return False if isinstance(accepted, str): if value != accepted: return False if 'func' in self.conf['paste_validators']['model_fields'][colname]: func = self.conf['paste_validators']['model_fields'][colname]['func'] if func == "date_validate": return date_validate(value) if func == "age_validate": return age_validate(value) return value def set_mark_filter(self): if self.pushButton_filtermarked.isChecked(): self.mfilter_sort_proxy_model.setCheckedFilter() else: self.mfilter_sort_proxy_model.clearCheckedFilter() def set_free_filter(self): text = self.lineEdit_filter.text() search = QRegularExpression(text, QRegularExpression.CaseInsensitiveOption) self.mfilter_sort_proxy_model.setFilterByColumns(self.filter_cols, search) def drop_rows(self): self.model.dropMarkedRows() if self.df.empty: self.set_datastatus_empty(True) def filldown(self): visible_tableview = self.get_current_tableview() if visible_tableview: select = visible_tableview.selectionModel() index = select.currentIndex() max_rows = self.mfilter_sort_proxy_model.rowCount() data_orig = self.mfilter_sort_proxy_model.data(index, Qt.DisplayRole) for r in range(index.row() + 1, max_rows): index_new = self.mfilter_sort_proxy_model.index(r, index.column()) data_new = self.mfilter_sort_proxy_model.data(index_new, Qt.DisplayRole) if data_new == '': self.mfilter_sort_proxy_model.setData(index_new, data_orig, Qt.EditRole) else: break def clear_table(self): self.df = pd.DataFrame(columns=self.tableView_columns) self.update_model() self.set_datastatus_empty(True) def reset_sort_filter(self): self.mfilter_sort_proxy_model.sort(-1) self.tableView_patient.horizontalHeader().setSortIndicator(-1, Qt.SortOrder.DescendingOrder) self.lineEdit_filter.setText('') self.pushButton_filtermarked.setChecked(False) self.set_mark_filter() for i in range(0, self.model.rowCount()): idx = self.model.index(i, 0) new_value = "0" self.model.setData(idx, new_value, Qt.EditRole) def get_current_tableview(self): for tbv in [self.tableView_patient, self.tableView_lab, self.tableView_organism]: if tbv.isVisible(): return tbv def invert_marks(self): for i in range(0, self.model.rowCount()): idx = self.model.index(i, 0) value = self.model.data(idx, Qt.DisplayRole) if value == "0": new_value = "1" else: new_value = "0" self.model.setData(idx, new_value, Qt.EditRole) def set_datastatus_empty(self, value): for w in self.status_widgets: if w is self.action_paste_fx: if self.fx is not None and self.fx.from_clipboard: w.setDisabled(value) elif w is self.action_import_fx: if self.fx is not None and self.fx.from_file: w.setDisabled(value) else: w.setDisabled(value) # Import/export functions def upload(self): cred = self.credm.get_current_cred() if not isinstance(cred, dict): return False metadata_dir = self.settm.get_valid_metadata_dir() if metadata_dir is None: msg = MsgAlert("Metadata output path is not valid.") msg.exec() return False pseudo_id_file = self.pidm.get_file() if pseudo_id_file is None: msg = MsgAlert("Path for pseudo_id file is not valid.") msg.exec() return False if not self.pidm.validate_lab_code(): msg = MsgAlert("pseudo_id file is not empty and lab_code does not " "exist in pseudo_id file. lab_code has been changed. " "Exiting.") msg.exec() return False self.df['lab'] = self.settm.get_value('select_single', 'lab') self.df['host'] = self.settm.get_value('select_single', 'host') self.df['seq_technology'] = self.settm.get_value('select_single', 'seq_technology') df2 = self.df.fillna('') errors = validate(df2) if errors: v_dialog = ValidationDialog(errors) v_dialog.exec() return False self.df['lab_code'] = self.df['lab'].apply(lambda x: self.conf['tr']['lab_to_code'][x]) self.df['region_code'] = self.df['region'].apply(lambda x: self.conf['tr']['region_to_code'][x]) lids = list(self.df['internal_lab_id']) print(f"validate lids: {self.pidm.validate_lids(lids)}") if not self.pidm.validate_lids(lids): msg = MsgOKCancel("internal_lab_id(s) already stored in pseudo_id file.\n" "Continue to upload anyway?") ret = msg.exec() if ret != QMessageBox.Ok: return False pseudo_ids = self.pidm.generate_pids_from_lids(self.df['internal_lab_id'].tolist()) print(pseudo_ids) if pseudo_ids is None: return False self.df['pseudo_id'] = pseudo_ids meta_fields = [field for field in self.conf['model_fields'] if self.conf['model_fields'][field]['to_meta']] df_submit = self.df[meta_fields] now = datetime.now() tag = now.strftime("%Y-%m-%dT%H.%M.%S") json_file = Path(metadata_dir, tag + "_meta.json") with open(json_file, 'w', encoding='utf-8') as outfile: df_submit.to_json(outfile, orient="records", force_ascii=False) complete_file = Path(self.conf['upload_complete_file']['filepath']) uploader = Uploader(cred, tag, self.df, json_file, complete_file, self.pidm) uploader.exec() def save_metadata_file(self): now = datetime.now() dt_str = now.strftime("%Y-%m-%dT%H.%M.%S") dialog = QFileDialog() p_str = self.settm.get_value('entered_value', 'metadata_docs_path') if p_str and Path(p_str).exists(): default_path = p_str else: default_path = str(Path.home()) default_path = Path(default_path, dt_str + "_metadata.pkl") filepath, _ = dialog.getSaveFileName(self, 'Save an awesome metadata file', str(default_path), "metadata files (*.pkl)", options=QFileDialog.DontUseNativeDialog) if filepath: self.df.to_pickle(filepath) def open_metadata_file(self): p_str = self.settm.get_value('entered_value', 'metadata_docs_path') if p_str and Path(p_str).exists(): default_path = p_str else: default_path = str(Path.home()) dialog = QFileDialog() filepath, _ = dialog.getOpenFileName(self, 'Open an awesome metadata file', default_path, "metadata files (*.pkl)", options=QFileDialog.DontUseNativeDialog) if filepath: self.df = pd.read_pickle(filepath) self.update_model() if not self.df.empty: self.rem_tb_bkg() self.set_datastatus_empty(False) def get_seq_files(self): p_str = self.settm.get_value('entered_value', 'seq_base_path') if p_str and Path(p_str).exists(): default_path = p_str else: default_path = str(Path.home()) dialog = QFileDialog() files, _ = dialog.getOpenFileNames(self, "Select sequence data files", default_path, "Sequence files (*.fast5 *.fastq.gz *.fastq *.fq.gz *.fq", options=QFileDialog.DontUseNativeDialog) verified_files = self.verify_files(files) file_metadata = self.extract_metadata_from_filenames(verified_files) self.add_files_metadata_to_model(file_metadata) def get_csv_file_combine(self): p_str = self.settm.get_value('entered_value', 'csv_base_path') if p_str and Path(p_str).exists(): default_path = p_str else: default_path = str(Path.home()) dialog = QFileDialog() filepath, _ = dialog.getOpenFileName(self, 'Open an awesome metadata file', default_path, "metadata csv files (*.csv)", options=QFileDialog.DontUseNativeDialog) if filepath: colnames = list(self.df.columns) with open(filepath, encoding='utf-8-sig') as csvfile: reader = csv.DictReader(csvfile) for row in reader: r = get_pd_row_index(self.df, row['internal_lab_id'], 'internal_lab_id') for key, value in row.items(): if key in colnames: self.df.at[r, key] = value self.update_model() def str_to_pd(self): clipboard = QGuiApplication.clipboard() mime_data = clipboard.mimeData() data_str = mime_data.text() str_obj = StringIO(data_str) df = pd.read_csv(str_obj, sep="\t") # for i, r in enumerate(rows): # columns = r.split("\t") # for j, value in enumerate(columns): # colname = self.df.columns[i_col + j] # valid_value = self.accept_paste(value, colname) # if valid_value: # model.setData(model.index(i_row + i, i_col + j), valid_value) # def import_fx_file(self): if self.fx is not None and self.fx.from_file: df_fx = self.fx.get_from_file() if isinstance(df_fx, pd.DataFrame): self.df = update_df(self.df, df_fx, key="internal_lab_id") cols = self.settm.get_ordered_fieldnames() self.df = self.df[cols] self.update_model() def import_fx_clipboard(self): if self.fx is not None and self.fx.from_clipboard: matrix = self.fx.get_from_clipboard() self.paste(matrix) def paste(self, matrix): curr_view = self.get_current_tableview() model = curr_view.model() index = curr_view.selectionModel().currentIndex() i_row = index.row() i_col = index.column() for i, r in enumerate(matrix): for j, value in enumerate(r): colname = self.df.columns[i_col + j] valid_value = self.accept_paste(value, colname) if valid_value: model.setData(model.index(i_row + i, i_col + j), valid_value) # Reimplemented functions def dragEnterEvent(self, event): if event.mimeData().hasUrls: event.accept() else: event.ignore() def dragMoveEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(Qt.CopyAction) event.accept() else: event.ignore() def dropEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(Qt.CopyAction) event.accept() files = [] for url in event.mimeData().urls(): files.append(str(url.toLocalFile())) verified_files = self.verify_files(files) file_metadata = self.extract_metadata_from_filenames(verified_files) self.add_files_metadata_to_model(file_metadata) else: event.ignore() def keyPressEvent(self, event): if event.key() == Qt.Key_Return: visible_tableview = self.get_current_tableview() if visible_tableview: indexes = visible_tableview.selectedIndexes() visible_tableview.edit(indexes[0]) elif event.key() == (Qt.Key_Control and Qt.Key_D): self.filldown() elif event.key() == Qt.Key_Delete: visible_tableview = self.get_current_tableview() if visible_tableview: indexes = visible_tableview.selectedIndexes() model = visible_tableview.model() for i in indexes: if model.flags(i) & Qt.ItemIsEditable: model.setData(i, "", Qt.EditRole) elif event.matches(QKeySequence.Copy): visible_tableview = self.get_current_tableview() if visible_tableview: indexes = visible_tableview.selectedIndexes() model = visible_tableview.model() c = [] r = [] old_row = None for i in indexes: if i.row() == old_row or old_row is None: c.append(model.data(i, Qt.DisplayRole)) old_row = i.row() else: r.append("\t".join(c)) c = [model.data(i, Qt.DisplayRole)] old_row = i.row() r.append("\t".join(c)) copy_data = "\n".join(r) self.clipboard.setText(copy_data) elif event.matches(QKeySequence.Paste): matrix = list() clipboard = QGuiApplication.clipboard() mime_data = clipboard.mimeData() rows = mime_data.text().split("\n") for i, r in enumerate(rows): columns = r.split("\t") matrix.append(columns) self.paste(matrix) elif event.key() == (Qt.Key_Control and Qt.Key_Alt and Qt.Key_V ): if self.fx is not None and self.fx.from_clipboard: matrix = self.fx.get_from_clipboard() self.paste(matrix) # elif event.matches(QKeySequence.Paste): # # clipboard = QGuiApplication.clipboard() # mime_data = clipboard.mimeData() # # curr_view = self.get_current_tableview() # # model = curr_view.model() # index = curr_view.selectionModel().currentIndex() # i_row = index.row() # i_col = index.column() # # rows = mime_data.text().split("\n") # for i, r in enumerate(rows): # columns = r.split("\t") # for j, value in enumerate(columns): # colname = self.df.columns[i_col + j] # valid_value = self.accept_paste(value, colname) # if valid_value: # model.setData(model.index(i_row + i, i_col + j), valid_value) else: super().keyPressEvent(event) def main(): try: import pyi_splash except: pass app = QApplication(sys.argv) window = MainWindow() style_add = """ QTableView { gridline-color: lightgrey; } .bold { font-weight: bold; font-size: 16px; padding-top: 10px; padding-bottom: 10px; color: grey; } .padding-left { padding-left: 10px; } """ style = qdarktheme.load_stylesheet("light") + style_add app.setStyleSheet(style) try: pyi_splash.close() except: pass window.show() sys.exit(app.exec()) if __name__ == "__main__": main()
[ "csv.DictReader", "pandas.read_csv", "gms_uploader.modules.models.sortfilterproxymodel.MultiSortFilterProxyModel", "gms_uploader.modules.dialogs.dialogs.MsgOKCancel", "pathlib.Path.home", "gms_uploader.modules.delegates.delegates.DateAutoCorrectDelegate", "gms_uploader.modules.upload.uploader.Uploader",...
[((1804, 1833), 'pathlib.Path', 'Path', (['"""config"""', '"""config.yaml"""'], {}), "('config', 'config.yaml')\n", (1808, 1833), False, 'from pathlib import Path\n'), ((1961, 1987), 'modules.settings.settings.SettingsManager', 'SettingsManager', (['self.conf'], {}), '(self.conf)\n', (1976, 1987), False, 'from modules.settings.settings import SettingsManager\n'), ((2009, 2032), 'gms_uploader.modules.credentials.credentials.CredManager', 'CredManager', (['self.settm'], {}), '(self.settm)\n', (2020, 2032), False, 'from gms_uploader.modules.credentials.credentials import CredManager\n'), ((2053, 2112), 'modules.pseudo_id.pseudo_id.PseudoIDManager', 'PseudoIDManager', (["self.conf['tr']['lab_to_code']", 'self.settm'], {}), "(self.conf['tr']['lab_to_code'], self.settm)\n", (2068, 2112), False, 'from modules.pseudo_id.pseudo_id import PseudoIDManager\n'), ((2236, 2280), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'self.tableView_columns'}), '(columns=self.tableView_columns)\n', (2248, 2280), True, 'import pandas as pd\n'), ((2302, 2349), 'gms_uploader.modules.models.pandasmodel.PandasModel', 'PandasModel', (['self.df', "self.conf['model_fields']"], {}), "(self.df, self.conf['model_fields'])\n", (2313, 2349), False, 'from gms_uploader.modules.models.pandasmodel import PandasModel\n'), ((2390, 2417), 'gms_uploader.modules.models.sortfilterproxymodel.MultiSortFilterProxyModel', 'MultiSortFilterProxyModel', ([], {}), '()\n', (2415, 2417), False, 'from gms_uploader.modules.models.sortfilterproxymodel import MultiSortFilterProxyModel\n'), ((20924, 20947), 'gms_uploader.modules.credentials.credentials.CredManager', 'CredManager', (['self.settm'], {}), '(self.settm)\n', (20935, 20947), False, 'from gms_uploader.modules.credentials.credentials import CredManager\n'), ((21378, 21425), 'gms_uploader.modules.models.pandasmodel.PandasModel', 'PandasModel', (['self.df', "self.conf['model_fields']"], {}), "(self.df, self.conf['model_fields'])\n", (21389, 21425), False, 'from gms_uploader.modules.models.pandasmodel import PandasModel\n'), ((21466, 21493), 'gms_uploader.modules.models.sortfilterproxymodel.MultiSortFilterProxyModel', 'MultiSortFilterProxyModel', ([], {}), '()\n', (21491, 21493), False, 'from gms_uploader.modules.models.sortfilterproxymodel import MultiSortFilterProxyModel\n'), ((21883, 21902), 'pandas.isna', 'pd.isna', (['insert_loc'], {}), '(insert_loc)\n', (21890, 21902), True, 'import pandas as pd\n'), ((25444, 25462), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (25456, 25462), True, 'import pandas as pd\n'), ((31580, 31598), 'pathlib.Path', 'Path', (['pseudo_id_fp'], {}), '(pseudo_id_fp)\n', (31584, 31598), False, 'from pathlib import Path\n'), ((32480, 32502), 'pathlib.Path', 'Path', (['credentials_path'], {}), '(credentials_path)\n', (32484, 32502), False, 'from pathlib import Path\n'), ((40466, 40510), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'self.tableView_columns'}), '(columns=self.tableView_columns)\n', (40478, 40510), True, 'import pandas as pd\n'), ((43192, 43205), 'gms_uploader.modules.validate.validate.validate', 'validate', (['df2'], {}), '(df2)\n', (43200, 43205), False, 'from gms_uploader.modules.validate.validate import validate\n'), ((44328, 44342), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (44340, 44342), False, 'from datetime import datetime\n'), ((44412, 44450), 'pathlib.Path', 'Path', (['metadata_dir', "(tag + '_meta.json')"], {}), "(metadata_dir, tag + '_meta.json')\n", (44416, 44450), False, 'from pathlib import Path\n'), ((44617, 44668), 'pathlib.Path', 'Path', (["self.conf['upload_complete_file']['filepath']"], {}), "(self.conf['upload_complete_file']['filepath'])\n", (44621, 44668), False, 'from pathlib import Path\n'), ((44689, 44754), 'gms_uploader.modules.upload.uploader.Uploader', 'Uploader', (['cred', 'tag', 'self.df', 'json_file', 'complete_file', 'self.pidm'], {}), '(cred, tag, self.df, json_file, complete_file, self.pidm)\n', (44697, 44754), False, 'from gms_uploader.modules.upload.uploader import Uploader\n'), ((44828, 44842), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (44840, 44842), False, 'from datetime import datetime\n'), ((45161, 45205), 'pathlib.Path', 'Path', (['default_path', "(dt_str + '_metadata.pkl')"], {}), "(default_path, dt_str + '_metadata.pkl')\n", (45165, 45205), False, 'from pathlib import Path\n'), ((48573, 48591), 'io.StringIO', 'StringIO', (['data_str'], {}), '(data_str)\n', (48581, 48591), False, 'from io import StringIO\n'), ((48605, 48635), 'pandas.read_csv', 'pd.read_csv', (['str_obj'], {'sep': '"""\t"""'}), "(str_obj, sep='\\t')\n", (48616, 48635), True, 'import pandas as pd\n'), ((54573, 54608), 'qdarktheme.load_stylesheet', 'qdarktheme.load_stylesheet', (['"""light"""'], {}), "('light')\n", (54599, 54608), False, 'import qdarktheme\n'), ((54669, 54687), 'pyi_splash.close', 'pyi_splash.close', ([], {}), '()\n', (54685, 54687), False, 'import pyi_splash\n'), ((1692, 1702), 'pathlib.Path', 'Path', (['"""fx"""'], {}), "('fx')\n", (1696, 1702), False, 'from pathlib import Path\n'), ((1920, 1938), 'yaml.safe_load', 'yaml.safe_load', (['fp'], {}), '(fp)\n', (1934, 1938), False, 'import yaml\n'), ((22477, 22487), 'pathlib.Path', 'Path', (['file'], {}), '(file)\n', (22481, 22487), False, 'from pathlib import Path\n'), ((23413, 23427), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (23417, 23427), False, 'from pathlib import Path\n'), ((27129, 27140), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (27138, 27140), False, 'from pathlib import Path\n'), ((27912, 27923), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (27921, 27923), False, 'from pathlib import Path\n'), ((28630, 28641), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (28639, 28641), False, 'from pathlib import Path\n'), ((29509, 29520), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (29518, 29520), False, 'from pathlib import Path\n'), ((30294, 30305), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (30303, 30305), False, 'from pathlib import Path\n'), ((32104, 32115), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (32113, 32115), False, 'from pathlib import Path\n'), ((32785, 32808), 'gms_uploader.modules.credentials.credentials.CredManager', 'CredManager', (['self.settm'], {}), '(self.settm)\n', (32796, 32808), False, 'from gms_uploader.modules.credentials.credentials import CredManager\n'), ((34419, 34442), 'gms_uploader.modules.delegates.delegates.ComboBoxDelegate', 'ComboBoxDelegate', (['items'], {}), '(items)\n', (34435, 34442), False, 'from gms_uploader.modules.delegates.delegates import ComboBoxDelegate, DateAutoCorrectDelegate, AgeDelegate, IconCheckBoxDelegate\n'), ((35268, 35293), 'gms_uploader.modules.delegates.delegates.DateAutoCorrectDelegate', 'DateAutoCorrectDelegate', ([], {}), '()\n', (35291, 35293), False, 'from gms_uploader.modules.delegates.delegates import ComboBoxDelegate, DateAutoCorrectDelegate, AgeDelegate, IconCheckBoxDelegate\n'), ((36117, 36130), 'gms_uploader.modules.delegates.delegates.AgeDelegate', 'AgeDelegate', ([], {}), '()\n', (36128, 36130), False, 'from gms_uploader.modules.delegates.delegates import ComboBoxDelegate, DateAutoCorrectDelegate, AgeDelegate, IconCheckBoxDelegate\n'), ((37071, 37097), 'gms_uploader.modules.delegates.delegates.IconCheckBoxDelegate', 'IconCheckBoxDelegate', (['None'], {}), '(None)\n', (37091, 37097), False, 'from gms_uploader.modules.delegates.delegates import ComboBoxDelegate, DateAutoCorrectDelegate, AgeDelegate, IconCheckBoxDelegate\n'), ((42316, 42362), 'gms_uploader.modules.dialogs.dialogs.MsgAlert', 'MsgAlert', (['"""Metadata output path is not valid."""'], {}), "('Metadata output path is not valid.')\n", (42324, 42362), False, 'from gms_uploader.modules.dialogs.dialogs import ValidationDialog, MsgAlert, MsgOKCancel\n'), ((42511, 42560), 'gms_uploader.modules.dialogs.dialogs.MsgAlert', 'MsgAlert', (['"""Path for pseudo_id file is not valid."""'], {}), "('Path for pseudo_id file is not valid.')\n", (42519, 42560), False, 'from gms_uploader.modules.dialogs.dialogs import ValidationDialog, MsgAlert, MsgOKCancel\n'), ((42674, 42806), 'gms_uploader.modules.dialogs.dialogs.MsgAlert', 'MsgAlert', (['"""pseudo_id file is not empty and lab_code does not exist in pseudo_id file. lab_code has been changed. Exiting."""'], {}), "(\n 'pseudo_id file is not empty and lab_code does not exist in pseudo_id file. lab_code has been changed. Exiting.'\n )\n", (42682, 42806), False, 'from gms_uploader.modules.dialogs.dialogs import ValidationDialog, MsgAlert, MsgOKCancel\n'), ((43249, 43273), 'gms_uploader.modules.dialogs.dialogs.ValidationDialog', 'ValidationDialog', (['errors'], {}), '(errors)\n', (43265, 43273), False, 'from gms_uploader.modules.dialogs.dialogs import ValidationDialog, MsgAlert, MsgOKCancel\n'), ((43709, 43817), 'gms_uploader.modules.dialogs.dialogs.MsgOKCancel', 'MsgOKCancel', (['"""internal_lab_id(s) already stored in pseudo_id file.\nContinue to upload anyway?"""'], {}), '(\n """internal_lab_id(s) already stored in pseudo_id file.\nContinue to upload anyway?"""\n )\n', (43720, 43817), False, 'from gms_uploader.modules.dialogs.dialogs import ValidationDialog, MsgAlert, MsgOKCancel\n'), ((46289, 46313), 'pandas.read_pickle', 'pd.read_pickle', (['filepath'], {}), '(filepath)\n', (46303, 46313), True, 'import pandas as pd\n'), ((38935, 38955), 'gms_uploader.modules.extra.auxiliary_functions.date_validate', 'date_validate', (['value'], {}), '(value)\n', (38948, 38955), False, 'from gms_uploader.modules.extra.auxiliary_functions import to_list, get_pd_row_index, date_validate, age_validate, add_gridlayout_row, update_df\n'), ((39019, 39038), 'gms_uploader.modules.extra.auxiliary_functions.age_validate', 'age_validate', (['value'], {}), '(value)\n', (39031, 39038), False, 'from gms_uploader.modules.extra.auxiliary_functions import to_list, get_pd_row_index, date_validate, age_validate, add_gridlayout_row, update_df\n'), ((45124, 45135), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (45133, 45135), False, 'from pathlib import Path\n'), ((45852, 45863), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (45861, 45863), False, 'from pathlib import Path\n'), ((46684, 46695), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (46693, 46695), False, 'from pathlib import Path\n'), ((47509, 47520), 'pathlib.Path.home', 'Path.home', ([], {}), '()\n', (47518, 47520), False, 'from pathlib import Path\n'), ((48067, 48090), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {}), '(csvfile)\n', (48081, 48090), False, 'import csv\n'), ((49217, 49265), 'gms_uploader.modules.extra.auxiliary_functions.update_df', 'update_df', (['self.df', 'df_fx'], {'key': '"""internal_lab_id"""'}), "(self.df, df_fx, key='internal_lab_id')\n", (49226, 49265), False, 'from gms_uploader.modules.extra.auxiliary_functions import to_list, get_pd_row_index, date_validate, age_validate, add_gridlayout_row, update_df\n'), ((29178, 29191), 'pathlib.Path', 'Path', (['dirpath'], {}), '(dirpath)\n', (29182, 29191), False, 'from pathlib import Path\n'), ((45024, 45035), 'pathlib.Path', 'Path', (['p_str'], {}), '(p_str)\n', (45028, 45035), False, 'from pathlib import Path\n'), ((45752, 45763), 'pathlib.Path', 'Path', (['p_str'], {}), '(p_str)\n', (45756, 45763), False, 'from pathlib import Path\n'), ((46584, 46595), 'pathlib.Path', 'Path', (['p_str'], {}), '(p_str)\n', (46588, 46595), False, 'from pathlib import Path\n'), ((47409, 47420), 'pathlib.Path', 'Path', (['p_str'], {}), '(p_str)\n', (47413, 47420), False, 'from pathlib import Path\n'), ((48150, 48218), 'gms_uploader.modules.extra.auxiliary_functions.get_pd_row_index', 'get_pd_row_index', (['self.df', "row['internal_lab_id']", '"""internal_lab_id"""'], {}), "(self.df, row['internal_lab_id'], 'internal_lab_id')\n", (48166, 48218), False, 'from gms_uploader.modules.extra.auxiliary_functions import to_list, get_pd_row_index, date_validate, age_validate, add_gridlayout_row, update_df\n'), ((22700, 22708), 'pathlib.Path', 'Path', (['fp'], {}), '(fp)\n', (22704, 22708), False, 'from pathlib import Path\n'), ((12136, 12180), 'gms_uploader.modules.extra.auxiliary_functions.add_gridlayout_row', 'add_gridlayout_row', (['grid_layout', 'label', 'hbox'], {}), '(grid_layout, label, hbox)\n', (12154, 12180), False, 'from gms_uploader.modules.extra.auxiliary_functions import to_list, get_pd_row_index, date_validate, age_validate, add_gridlayout_row, update_df\n'), ((12705, 12749), 'gms_uploader.modules.extra.auxiliary_functions.add_gridlayout_row', 'add_gridlayout_row', (['grid_layout', 'label', 'edit'], {}), '(grid_layout, label, edit)\n', (12723, 12749), False, 'from gms_uploader.modules.extra.auxiliary_functions import to_list, get_pd_row_index, date_validate, age_validate, add_gridlayout_row, update_df\n'), ((14156, 14201), 'gms_uploader.modules.extra.auxiliary_functions.add_gridlayout_row', 'add_gridlayout_row', (['grid_layout', 'label', 'combo'], {}), '(grid_layout, label, combo)\n', (14174, 14201), False, 'from gms_uploader.modules.extra.auxiliary_functions import to_list, get_pd_row_index, date_validate, age_validate, add_gridlayout_row, update_df\n'), ((16321, 16335), 'gms_uploader.modules.extra.auxiliary_functions.to_list', 'to_list', (['value'], {}), '(value)\n', (16328, 16335), False, 'from gms_uploader.modules.extra.auxiliary_functions import to_list, get_pd_row_index, date_validate, age_validate, add_gridlayout_row, update_df\n'), ((15261, 15306), 'gms_uploader.modules.extra.auxiliary_functions.add_gridlayout_row', 'add_gridlayout_row', (['grid_layout', 'label', 'combo'], {}), '(grid_layout, label, combo)\n', (15279, 15306), False, 'from gms_uploader.modules.extra.auxiliary_functions import to_list, get_pd_row_index, date_validate, age_validate, add_gridlayout_row, update_df\n'), ((17199, 17225), 'gms_uploader.modules.delegates.delegates.IconCheckBoxDelegate', 'IconCheckBoxDelegate', (['None'], {}), '(None)\n', (17219, 17225), False, 'from gms_uploader.modules.delegates.delegates import ComboBoxDelegate, DateAutoCorrectDelegate, AgeDelegate, IconCheckBoxDelegate\n')]
import logging from functools import wraps import pytest from eth_tester import EthereumTester from web3 import Web3 from web3.providers.eth_tester import EthereumTesterProvider from vyper import compile_lll, compiler, optimizer from vyper.parser.parser import parse_to_lll from vyper.parser.parser_utils import LLLnode from .base_conftest import ( VyperContract, _get_contract, zero_gas_price_strategy, ) # Import the base_conftest fixtures pytest_plugins = ["tests.base_conftest"] ############ # PATCHING # ############ def set_evm_verbose_logging(): logger = logging.getLogger("evm") logger.setLevel("TRACE") # Useful options to comment out whilst working: # set_evm_verbose_logging() # from vdb import vdb # vdb.set_evm_opcode_debugger() @pytest.fixture def keccak(): return Web3.keccak @pytest.fixture def bytes_helper(): def bytes_helper(str, length): return bytes(str, "utf-8") + bytearray(length - len(str)) return bytes_helper @pytest.fixture def get_contract_from_lll(w3): def lll_compiler(lll, *args, **kwargs): lll = optimizer.optimize(LLLnode.from_list(lll)) bytecode, _ = compile_lll.assembly_to_evm(compile_lll.compile_to_assembly(lll)) abi = kwargs.get("abi") or [] c = w3.eth.contract(abi=abi, bytecode=bytecode) deploy_transaction = c.constructor() tx_hash = deploy_transaction.transact() address = w3.eth.getTransactionReceipt(tx_hash)["contractAddress"] contract = w3.eth.contract( address, abi=abi, bytecode=bytecode, ContractFactoryClass=VyperContract, ) return contract return lll_compiler @pytest.fixture(scope="module") def get_contract_module(): """ This fixture is used for Hypothesis tests to ensure that the same contract is called over multiple runs of the test. """ tester = EthereumTester() w3 = Web3(EthereumTesterProvider(tester)) w3.eth.setGasPriceStrategy(zero_gas_price_strategy) def get_contract_module(source_code, *args, **kwargs): return _get_contract(w3, source_code, *args, **kwargs) return get_contract_module def get_compiler_gas_estimate(code, func): lll_nodes = optimizer.optimize(parse_to_lll(code)) if func: return compiler.utils.build_gas_estimates(lll_nodes)[func] + 22000 else: return sum(compiler.utils.build_gas_estimates(lll_nodes).values()) + 22000 def check_gas_on_chain(w3, tester, code, func=None, res=None): gas_estimate = get_compiler_gas_estimate(code, func) gas_actual = tester.get_block_by_number("latest")["gas_used"] # Computed upper bound on the gas consumption should # be greater than or equal to the amount of gas used if gas_estimate < gas_actual: raise Exception(f"Gas upper bound fail: bound {gas_estimate} actual {gas_actual}") print(f"Function name: {func} - Gas estimate {gas_estimate}, Actual: {gas_actual}") def gas_estimation_decorator(w3, tester, fn, source_code, func): def decorator(*args, **kwargs): @wraps(fn) def decorated_function(*args, **kwargs): result = fn(*args, **kwargs) if "transact" in kwargs: check_gas_on_chain(w3, tester, source_code, func, res=result) return result return decorated_function(*args, **kwargs) return decorator def set_decorator_to_contract_function(w3, tester, contract, source_code, func): func_definition = getattr(contract, func) func_with_decorator = gas_estimation_decorator(w3, tester, func_definition, source_code, func) setattr(contract, func, func_with_decorator) @pytest.fixture def get_contract_with_gas_estimation(tester, w3): def get_contract_with_gas_estimation(source_code, *args, **kwargs): contract = _get_contract(w3, source_code, *args, **kwargs) for abi in contract._classic_contract.functions.abi: if abi["type"] == "function": set_decorator_to_contract_function(w3, tester, contract, source_code, abi["name"]) return contract return get_contract_with_gas_estimation @pytest.fixture def get_contract_with_gas_estimation_for_constants(w3): def get_contract_with_gas_estimation_for_constants(source_code, *args, **kwargs): return _get_contract(w3, source_code, *args, **kwargs) return get_contract_with_gas_estimation_for_constants @pytest.fixture def assert_compile_failed(): def assert_compile_failed(function_to_test, exception=Exception): with pytest.raises(exception): function_to_test() return assert_compile_failed @pytest.fixture def search_for_sublist(): def search_for_sublist(lll, sublist): _list = lll.to_list() if hasattr(lll, "to_list") else lll if _list == sublist: return True if isinstance(_list, list): for i in _list: ret = search_for_sublist(i, sublist) if ret is True: return ret return False return search_for_sublist
[ "logging.getLogger", "vyper.compiler.utils.build_gas_estimates", "vyper.compile_lll.compile_to_assembly", "functools.wraps", "web3.providers.eth_tester.EthereumTesterProvider", "pytest.raises", "eth_tester.EthereumTester", "vyper.parser.parser_utils.LLLnode.from_list", "pytest.fixture", "vyper.par...
[((1673, 1703), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1687, 1703), False, 'import pytest\n'), ((585, 609), 'logging.getLogger', 'logging.getLogger', (['"""evm"""'], {}), "('evm')\n", (602, 609), False, 'import logging\n'), ((1885, 1901), 'eth_tester.EthereumTester', 'EthereumTester', ([], {}), '()\n', (1899, 1901), False, 'from eth_tester import EthereumTester\n'), ((1916, 1946), 'web3.providers.eth_tester.EthereumTesterProvider', 'EthereumTesterProvider', (['tester'], {}), '(tester)\n', (1938, 1946), False, 'from web3.providers.eth_tester import EthereumTesterProvider\n'), ((2239, 2257), 'vyper.parser.parser.parse_to_lll', 'parse_to_lll', (['code'], {}), '(code)\n', (2251, 2257), False, 'from vyper.parser.parser import parse_to_lll\n'), ((3068, 3077), 'functools.wraps', 'wraps', (['fn'], {}), '(fn)\n', (3073, 3077), False, 'from functools import wraps\n'), ((1116, 1138), 'vyper.parser.parser_utils.LLLnode.from_list', 'LLLnode.from_list', (['lll'], {}), '(lll)\n', (1133, 1138), False, 'from vyper.parser.parser_utils import LLLnode\n'), ((1190, 1226), 'vyper.compile_lll.compile_to_assembly', 'compile_lll.compile_to_assembly', (['lll'], {}), '(lll)\n', (1221, 1226), False, 'from vyper import compile_lll, compiler, optimizer\n'), ((4551, 4575), 'pytest.raises', 'pytest.raises', (['exception'], {}), '(exception)\n', (4564, 4575), False, 'import pytest\n'), ((2287, 2332), 'vyper.compiler.utils.build_gas_estimates', 'compiler.utils.build_gas_estimates', (['lll_nodes'], {}), '(lll_nodes)\n', (2321, 2332), False, 'from vyper import compile_lll, compiler, optimizer\n'), ((2376, 2421), 'vyper.compiler.utils.build_gas_estimates', 'compiler.utils.build_gas_estimates', (['lll_nodes'], {}), '(lll_nodes)\n', (2410, 2421), False, 'from vyper import compile_lll, compiler, optimizer\n')]
import mock def test_redis(): from dallinger.db import redis_conn assert redis_conn.ping() def test_serialized(db_session): from dallinger.db import serialized from dallinger.models import Participant counts = [] # Define a function which adds a new participant # with an id based on a database query. def add_participant(session, interruptor=None): count = session.query(Participant).count() counts.append(count) # This is for the sake of the test, # to let us change the count from a different session # on the first try. if interruptor: interruptor() session.add( Participant( recruiter_id="hotair", worker_id="serialized_{}".format(count + 1), assignment_id="test", hit_id="test", mode="test", ) ) # Define a function to get in the way of our transaction # by changing the participant count from another db session # the first time that our serialized transaction is called. interrupted = [] def interruptor(): if not interrupted: session2 = db_session.session_factory() session2.connection(execution_options={"isolation_level": "SERIALIZABLE"}) add_participant(session2) session2.commit() interrupted.append(True) # Now define the test function which will try to add # a participant using the scoped db session, # but will fail the first time due to the interruption. @serialized def serialized_write(): add_participant(db_session, interruptor) # Now run the serialized write. # It should succeed, but only after retrying the transaction. serialized_write() # Which we can check by making sure that `add_participant` # calculated the count at least 3 times assert counts == [0, 0, 1] def test_after_commit_hook(db_session): with mock.patch("dallinger.db.redis_conn") as redis: from dallinger.db import queue_message queue_message("test", "test") db_session.commit() assert redis.called_once_with("test", "test")
[ "dallinger.db.queue_message", "dallinger.db.redis_conn.ping", "mock.patch" ]
[((84, 101), 'dallinger.db.redis_conn.ping', 'redis_conn.ping', ([], {}), '()\n', (99, 101), False, 'from dallinger.db import redis_conn\n'), ((2006, 2043), 'mock.patch', 'mock.patch', (['"""dallinger.db.redis_conn"""'], {}), "('dallinger.db.redis_conn')\n", (2016, 2043), False, 'import mock\n'), ((2110, 2139), 'dallinger.db.queue_message', 'queue_message', (['"""test"""', '"""test"""'], {}), "('test', 'test')\n", (2123, 2139), False, 'from dallinger.db import queue_message\n')]
# pylint: disable=print-statement,missing-docstring,no-self-use,too-few-public-methods,bare-except,broad-except, useless-object-inheritance # pylint: disable=using-constant-test,expression-not-assigned, assigning-non-slot, unused-variable,pointless-statement from __future__ import print_function import six class Provider(object): """provide some attributes and method""" cattr = 4 def __init__(self): self.attr = 4 def method(self, val): """impressive method""" return self.attr * val def hophop(self): """hop method""" print('hop hop hop', self) class Client(object): """use provider class""" def __init__(self): self._prov = Provider() self._prov_attr = Provider.cattr self._prov_attr2 = Provider.cattribute # [no-member] self.set_later = 0 def set_set_later(self, value): """set set_later attribute (introduce an inference ambiguity)""" self.set_later = value def use_method(self): """use provider's method""" self._prov.hophop() self._prov.hophophop() # [no-member] def use_attr(self): """use provider's attr""" print(self._prov.attr) print(self._prov.attribute) # [no-member] def debug(self): """print debug information""" print(self.__class__.__name__) print(self.__doc__) print(self.__dict__) print(self.__module__) def test_bt_types(self): """test access to unexistant member of builtin types""" lis = [] lis.apppend(self) # [no-member] dic = {} dic.set(self) # [no-member] tup = () tup.append(self) # [no-member] string = 'toto' print(string.loower()) # [no-member] integer = 1 print(integer.whatever) # [no-member] def test_no_false_positives(self): none = None print(none.whatever) # No misssing in the parents. super(Client, self).misssing() # [no-member] class Mixin(object): """No no-member should be emitted for mixins.""" class Getattr(object): """no-member shouldn't be emitted for classes with dunder getattr.""" def __getattr__(self, attr): return self.__dict__[attr] class Getattribute(object): """no-member shouldn't be emitted for classes with dunder getattribute.""" def __getattribute__(self, attr): return 42 print(object.__init__) print(property.__init__) print(Client().set_later.lower()) print(Mixin().nanana()) print(Getattr().nananan()) print(Getattribute().batman()) try: Client().missing_method() except AttributeError: pass try: Client().indeed() # [no-member] except ImportError: pass try: Client.missing() except AttributeError: Client.missing() # [no-member] try: Client.missing() except AttributeError: try: Client.missing() # [no-member] except ValueError: pass try: if Client: Client().missing() except AttributeError: pass try: Client().indeed() except AttributeError: try: Client.missing() # [no-member] except Exception: pass class SuperChecks(str, str): # pylint: disable=duplicate-bases """Don't fail when the MRO is invalid.""" def test(self): super(SuperChecks, self).lalala() type(Client()).ala # [no-member] type({}).bala # [no-member] type('').portocala # [no-member] def socket_false_positive(): """Test a regression Version used: - Pylint 0.10.0 - Logilab common 0.15.0 - Logilab astroid 0.15.1 False E1101 positive, line 23: Instance of '_socketobject' has no 'connect' member """ import socket sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sckt.connect(('127.0.0.1', 80)) sckt.close() def no_conjugate_member(magic_flag): """should not raise E1101 on something.conjugate""" if magic_flag: something = 1.0 else: something = 1.0j if isinstance(something, float): return something return something.conjugate() class NoDunderNameInInstance(object): """Emit a warning when accessing __name__ from an instance.""" def __init__(self): self.var = self.__name__ # [no-member] class InvalidAccessBySlots(object): __slots__ = ('a', ) def __init__(self): var = self.teta # [no-member] self.teta = 24 class MetaWithDynamicGetattr(type): def __getattr__(cls, attr): return attr @six.add_metaclass(MetaWithDynamicGetattr) class SomeClass(object): pass SomeClass.does_not_exist class ClassWithMangledAttribute(object): def __init__(self): self.name = 'Bug1643' def __bar(self): print(self.name + "xD") ClassWithMangledAttribute()._ClassWithMangledAttribute__bar() # pylint: disable=protected-access
[ "six.add_metaclass", "socket.socket" ]
[((4520, 4561), 'six.add_metaclass', 'six.add_metaclass', (['MetaWithDynamicGetattr'], {}), '(MetaWithDynamicGetattr)\n', (4537, 4561), False, 'import six\n'), ((3731, 3780), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (3744, 3780), False, 'import socket\n')]
import importlib # import modules subset = importlib.import_module('.data.01_subset-data-GBP', 'src') plotwines = importlib.import_module('.visualization.02_visualize-wines', 'src') country_sub = importlib.import_module('.data.03_country-subset', 'src') raw_data = 'data/raw/winemag-data-130k-v2.csv' country = 'Chile' if __name__ == '__main__': subset_file = subset.process_data_GBP(raw_data) print(subset_file) plotwines.create_plots(subset_file) country_file = country_sub.get_country(subset_file, country) print(country_file)
[ "importlib.import_module" ]
[((44, 102), 'importlib.import_module', 'importlib.import_module', (['""".data.01_subset-data-GBP"""', '"""src"""'], {}), "('.data.01_subset-data-GBP', 'src')\n", (67, 102), False, 'import importlib\n'), ((115, 182), 'importlib.import_module', 'importlib.import_module', (['""".visualization.02_visualize-wines"""', '"""src"""'], {}), "('.visualization.02_visualize-wines', 'src')\n", (138, 182), False, 'import importlib\n'), ((197, 254), 'importlib.import_module', 'importlib.import_module', (['""".data.03_country-subset"""', '"""src"""'], {}), "('.data.03_country-subset', 'src')\n", (220, 254), False, 'import importlib\n')]
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### bl_info = { "name": "Geodesic Domes2", "author": "Noctumsolis, PKHG, Meta Androcto, <NAME>", "version": (0, 3, 2), "blender": (2, 7, 1), "location": "Toolshelf > Create Tab", "description": "Create geodesic dome type objects.", "warning": "", "wiki_url": "https://wiki.blender.org/index.php/Extensions:2.6/Py/Scripts/Modeling/Geodesic_Domes", "tracker_url": "", "category": "Mesh"} if "bpy" in locals(): import importlib importlib.reload(third_domes_panel_271) else: from . import third_domes_panel_271 import bpy def register(): bpy.utils.register_module(__name__) def unregister(): bpy.utils.unregister_module(__name__) if __name__ == "__main__": register()
[ "bpy.utils.register_module", "bpy.utils.unregister_module", "importlib.reload" ]
[((1265, 1304), 'importlib.reload', 'importlib.reload', (['third_domes_panel_271'], {}), '(third_domes_panel_271)\n', (1281, 1304), False, 'import importlib\n'), ((1386, 1421), 'bpy.utils.register_module', 'bpy.utils.register_module', (['__name__'], {}), '(__name__)\n', (1411, 1421), False, 'import bpy\n'), ((1446, 1483), 'bpy.utils.unregister_module', 'bpy.utils.unregister_module', (['__name__'], {}), '(__name__)\n', (1473, 1483), False, 'import bpy\n')]
from django.contrib import admin from .models import Idea @admin.register(Idea) class IdeaAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'projected_revenue', 'created', 'modified',) list_display_links = ('name',)
[ "django.contrib.admin.register" ]
[((61, 81), 'django.contrib.admin.register', 'admin.register', (['Idea'], {}), '(Idea)\n', (75, 81), False, 'from django.contrib import admin\n')]
# -- Setup Django -- from os import environ as env from os.path import dirname, join from sys import path path.insert(0, dirname(dirname(__file__))) path.insert(1, join(dirname(__file__), '_ext')) env['DJANGO_SETTINGS_MODULE'] = 'MangAdventure.tests.settings' __import__('django').setup() # -- Project information -- import MangAdventure as MA # noqa: E402 project = 'MangAdventure' author = MA.__author__ release = MA.__version__ copyright = f'2018-2021, {project}, {MA.__license__} license' # -- General configuration -- extensions = [ 'sphinx.ext.autodoc', 'mangadventure_patches', 'sphinx_autodoc_typehints', 'sphinx.ext.intersphinx', 'sphinx.ext.extlinks', 'sphinx.ext.viewcode', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' language = 'en' pygments_style = 'manni' needs_sphinx = '3.3' # -- InterSphinx & extlinks configuration -- _django = 'https://docs.djangoproject.com/en/3.2/' _mdn = 'https://developer.mozilla.org/en-US/docs/Web/' intersphinx_mapping = { 'django': (_django, f'{_django}_objects/'), 'python': ('https://docs.python.org/3.6/', None), } extlinks = { 'setting': (f'{_django}ref/settings/#std:setting-%s', ''), 'tag': (f'{_django}ref/templates/builtins/#%s', ''), 'auth': ('https://django-allauth.rtfd.io/en/latest/%s', ''), 'csp': (f'{_mdn}HTTP/Headers/Content-Security-Policy/%s', ''), 'status': (f'{_mdn}HTTP/Status/%s', ''), 'header': (f'{_mdn}HTTP/Headers/%s', ''), 'schema': ('https://schema.org/%s', ''), } # -- Autodoc configuration -- autodoc_default_options = { 'member-order': 'bysource', 'special-members': True, 'undoc-members': True, 'exclude-members': ','.join(( '__new__', '__dict__', '__repr__', '__init__', '__slots__', '__module__', '__weakref__', '__slotnames__', '__annotations__', )) } autodoc_mock_imports = ['pytest'] autodoc_inherit_docstrings = True always_document_param_types = True set_type_checking_flag = True typehints_fully_qualified = False typehints_document_rtype = True # disable sphinx.ext.autodoc.typehints autodoc_typehints = 'none' # -- Options for HTML output -- html_theme = 'sphinx_rtd_theme' html_theme_path = [__import__(html_theme).get_html_theme_path()] html_theme_options = { 'logo_only': True, 'display_version': False, 'collapse_navigation': True, } html_static_path = ['_static'] html_logo = '_static/logo.png' # html_sidebars = {} # -- Options for HTMLHelp output -- htmlhelp_basename = f'{project}Doc' # -- Options for LaTeX output -- latex_elements = {} latex_documents = [( master_doc, f'{project}.tex', f'{project} Documentation', author, 'manual' )] # -- Options for manual page output -- man_pages = [( master_doc, project.lower(), f'{project} Documentation', author.split(', '), 7 )] # -- Options for Texinfo output -- texinfo_documents = [( master_doc, project, f'{project} Documentation', author, project, MA.__doc__, 'Miscellaneous' )]
[ "os.path.dirname" ]
[((131, 148), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (138, 148), False, 'from os.path import dirname, join\n'), ((171, 188), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (178, 188), False, 'from os.path import dirname, join\n')]
# -*- encoding: utf-8 -*- # # # Copyright (C) 2002-2011 <NAME> <<EMAIL>> # Copyright (C) 2002-2011 <NAME> <<EMAIL>> # # This file is part of PyX (http://pyx.sourceforge.net/). # # PyX is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # PyX is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PyX; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import math import attr, canvasitem, deformer, unit import bbox as bboxmodule # global epsilon (used to judge whether a matrix is singular) _epsilon = (1e-5)**2 def set(epsilon=None): global _epsilon if epsilon is not None: _epsilon = epsilon # some helper routines def _rmatrix(angle): phi = math.pi*angle/180.0 return ((math.cos(phi), -math.sin(phi)), (math.sin(phi), math.cos(phi))) def _rvector(angle, x, y): phi = math.pi*angle/180.0 return ((1-math.cos(phi))*x + math.sin(phi) *y, -math.sin(phi) *x + (1-math.cos(phi))*y) def _mmatrix(angle): phi = math.pi*angle/180.0 return ( (math.cos(phi)*math.cos(phi)-math.sin(phi)*math.sin(phi), -2*math.sin(phi)*math.cos(phi) ), (-2*math.sin(phi)*math.cos(phi), math.sin(phi)*math.sin(phi)-math.cos(phi)*math.cos(phi) ) ) class _marker: pass # Exception class TrafoException(Exception): pass # trafo: affine transformations class trafo_pt(canvasitem.canvasitem, deformer.deformer): """affine transformation (coordinates in constructor in pts) Note that though the coordinates in the constructor are in pts (which is useful for internal purposes), all other methods only accept units in the standard user notation. """ def __init__(self, matrix=((1, 0), (0, 1)), vector=(0, 0), epsilon=_marker): """Return trafo with given transformation matrix and vector. If epsilon is passed it is used instead of the global epsilon defined in the module to check whether the matrix is singular or not. Use epsilon=None to turn of this checking. """ if epsilon is _marker: epsilon = _epsilon self.epsilon = epsilon if epsilon is not None and abs(matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]) < epsilon: raise TrafoException("transformation matrix must not be singular") else: self.matrix = matrix self.vector = vector def __mul__(self, other): if isinstance(other, trafo_pt): if self.epsilon is None or other.epsilon is None: epsilon = None elif self.epsilon <= other.epsilon: epsilon = self.epsilon else: epsilon = other.epsilon matrix = ( ( self.matrix[0][0]*other.matrix[0][0] + self.matrix[0][1]*other.matrix[1][0], self.matrix[0][0]*other.matrix[0][1] + self.matrix[0][1]*other.matrix[1][1] ), ( self.matrix[1][0]*other.matrix[0][0] + self.matrix[1][1]*other.matrix[1][0], self.matrix[1][0]*other.matrix[0][1] + self.matrix[1][1]*other.matrix[1][1] ) ) vector = ( self.matrix[0][0]*other.vector[0] + self.matrix[0][1]*other.vector[1] + self.vector[0], self.matrix[1][0]*other.vector[0] + self.matrix[1][1]*other.vector[1] + self.vector[1] ) return trafo_pt(matrix=matrix, vector=vector, epsilon=epsilon) else: raise NotImplementedError("can only multiply two transformations") def __str__(self): return "[%f %f %f %f %f %f]" % \ ( self.matrix[0][0], self.matrix[1][0], self.matrix[0][1], self.matrix[1][1], self.vector[0], self.vector[1] ) def processPS(self, file, writer, context, registry, bbox): file.write("[%f %f %f %f %f %f] concat\n" % \ ( self.matrix[0][0], self.matrix[1][0], self.matrix[0][1], self.matrix[1][1], self.vector[0], self.vector[1] ) ) def processPDF(self, file, writer, context, registry, bbox): file.write("%f %f %f %f %f %f cm\n" % \ ( self.matrix[0][0], self.matrix[1][0], self.matrix[0][1], self.matrix[1][1], self.vector[0], self.vector[1] ) ) def bbox(self): return bboxmodule.empty() def apply_pt(self, x_pt, y_pt): """apply transformation to point (x_pt, y_pt) in pts""" return ( self.matrix[0][0]*x_pt + self.matrix[0][1]*y_pt + self.vector[0], self.matrix[1][0]*x_pt + self.matrix[1][1]*y_pt + self.vector[1] ) def apply(self, x, y): # for the transformation we have to convert to points tx, ty = self.apply_pt(unit.topt(x), unit.topt(y)) return tx * unit.t_pt, ty * unit.t_pt def deform(self, path): return path.transformed(self) def inverse(self): det = 1.0*(self.matrix[0][0]*self.matrix[1][1] - self.matrix[0][1]*self.matrix[1][0]) matrix = ( ( self.matrix[1][1]/det, -self.matrix[0][1]/det), (-self.matrix[1][0]/det, self.matrix[0][0]/det) ) return ( trafo_pt(matrix=matrix, epsilon=self.epsilon) * trafo_pt(vector=(-self.vector[0], -self.vector[1]), epsilon=self.epsilon) ) def mirrored(self, angle): return mirror(angle, epsilon=self.epsilon) * self def rotated_pt(self, angle, x=None, y=None): return rotate_pt(angle, x, y, epsilon=self.epsilon) * self def rotated(self, angle, x=None, y=None): return rotate(angle, x, y, epsilon=self.epsilon) * self def scaled_pt(self, sx, sy=None, x=None, y=None): return scale_pt(sx, sy, x, y, epsilon=self.epsilon) * self def scaled(self, sx, sy=None, x=None, y=None): return scale(sx, sy, x, y, epsilon=self.epsilon) * self def slanted_pt(self, a, angle=0, x=None, y=None): return slant_pt(a, angle, x, y, epsilon=self.epsilon) * self def slanted(self, a, angle=0, x=None, y=None): return slant(a, angle, x, y, epsilon=self.epsilon) * self def translated_pt(self, x, y): return translate_pt(x, y, epsilon=self.epsilon) * self def translated(self, x, y): return translate(x, y, epsilon=self.epsilon) * self class trafo(trafo_pt): """affine transformation""" def __init__(self, matrix=((1,0), (0,1)), vector=(0, 0), epsilon=_marker): trafo_pt.__init__(self, matrix, (unit.topt(vector[0]), unit.topt(vector[1])), epsilon=epsilon) # # some standard transformations # class mirror(trafo): def __init__(self, angle=0, epsilon=_marker): trafo.__init__(self, matrix=_mmatrix(angle), epsilon=epsilon) class rotate_pt(trafo_pt): def __init__(self, angle, x=None, y=None, epsilon=_marker): vector = 0, 0 if x is not None or y is not None: if x is None or y is None: raise TrafoException("either specify both x and y or none of them") vector=_rvector(angle, x, y) trafo_pt.__init__(self, matrix=_rmatrix(angle), vector=vector, epsilon=epsilon) class rotate(trafo_pt): def __init__(self, angle, x=None, y=None, epsilon=_marker): vector = 0, 0 if x is not None or y is not None: if x is None or y is None: raise TrafoException("either specify both x and y or none of them") vector=_rvector(angle, unit.topt(x), unit.topt(y)) trafo_pt.__init__(self, matrix=_rmatrix(angle), vector=vector, epsilon=epsilon) class scale_pt(trafo_pt): def __init__(self, sx, sy=None, x=None, y=None, epsilon=_marker): if sy is None: sy = sx vector = 0, 0 if x is not None or y is not None: if x is None or y is None: raise TrafoException("either specify both x and y or none of them") vector = (1-sx)*x, (1-sy)*y trafo_pt.__init__(self, matrix=((sx, 0), (0, sy)), vector=vector, epsilon=epsilon) class scale(trafo): def __init__(self, sx, sy=None, x=None, y=None, epsilon=_marker): if sy is None: sy = sx vector = 0, 0 if x is not None or y is not None: if x is None or y is None: raise TrafoException("either specify both x and y or none of them") vector = (1-sx)*x, (1-sy)*y trafo.__init__(self, matrix=((sx, 0), (0, sy)), vector=vector, epsilon=epsilon) class slant_pt(trafo_pt): def __init__(self, a, angle=0, x=None, y=None, epsilon=_marker): t = ( rotate_pt(-angle, x, y, epsilon=epsilon) * trafo(matrix=((1, a), (0, 1)), epsilon=epsilon) * rotate_pt(angle, x, y, epsilon=epsilon) ) trafo_pt.__init__(self, t.matrix, t.vector, epsilon=epsilon) class slant(trafo): def __init__(self, a, angle=0, x=None, y=None, epsilon=_marker): t = ( rotate(-angle, x, y, epsilon=epsilon) * trafo(matrix=((1, a), (0, 1)), epsilon=epsilon) * rotate(angle, x, y, epsilon=epsilon) ) trafo.__init__(self, t.matrix, t.vector, epsilon=epsilon) class translate_pt(trafo_pt): def __init__(self, x, y, epsilon=_marker): trafo_pt.__init__(self, vector=(x, y), epsilon=epsilon) class translate(trafo): def __init__(self, x, y, epsilon=_marker): trafo.__init__(self, vector=(x, y), epsilon=epsilon)
[ "math.cos", "math.sin", "bbox.empty", "unit.topt" ]
[((5088, 5106), 'bbox.empty', 'bboxmodule.empty', ([], {}), '()\n', (5104, 5106), True, 'import bbox as bboxmodule\n'), ((1210, 1223), 'math.cos', 'math.cos', (['phi'], {}), '(phi)\n', (1218, 1223), False, 'import math\n'), ((1257, 1270), 'math.sin', 'math.sin', (['phi'], {}), '(phi)\n', (1265, 1270), False, 'import math\n'), ((1273, 1286), 'math.cos', 'math.cos', (['phi'], {}), '(phi)\n', (1281, 1286), False, 'import math\n'), ((5496, 5508), 'unit.topt', 'unit.topt', (['x'], {}), '(x)\n', (5505, 5508), False, 'import attr, canvasitem, deformer, unit\n'), ((5510, 5522), 'unit.topt', 'unit.topt', (['y'], {}), '(y)\n', (5519, 5522), False, 'import attr, canvasitem, deformer, unit\n'), ((1226, 1239), 'math.sin', 'math.sin', (['phi'], {}), '(phi)\n', (1234, 1239), False, 'import math\n'), ((1383, 1396), 'math.sin', 'math.sin', (['phi'], {}), '(phi)\n', (1391, 1396), False, 'import math\n'), ((1617, 1630), 'math.cos', 'math.cos', (['phi'], {}), '(phi)\n', (1625, 1630), False, 'import math\n'), ((1680, 1693), 'math.cos', 'math.cos', (['phi'], {}), '(phi)\n', (1688, 1693), False, 'import math\n'), ((7247, 7267), 'unit.topt', 'unit.topt', (['vector[0]'], {}), '(vector[0])\n', (7256, 7267), False, 'import attr, canvasitem, deformer, unit\n'), ((7269, 7289), 'unit.topt', 'unit.topt', (['vector[1]'], {}), '(vector[1])\n', (7278, 7289), False, 'import attr, canvasitem, deformer, unit\n'), ((8240, 8252), 'unit.topt', 'unit.topt', (['x'], {}), '(x)\n', (8249, 8252), False, 'import attr, canvasitem, deformer, unit\n'), ((8254, 8266), 'unit.topt', 'unit.topt', (['y'], {}), '(y)\n', (8263, 8266), False, 'import attr, canvasitem, deformer, unit\n'), ((1364, 1377), 'math.cos', 'math.cos', (['phi'], {}), '(phi)\n', (1372, 1377), False, 'import math\n'), ((1419, 1432), 'math.sin', 'math.sin', (['phi'], {}), '(phi)\n', (1427, 1432), False, 'import math\n'), ((1443, 1456), 'math.cos', 'math.cos', (['phi'], {}), '(phi)\n', (1451, 1456), False, 'import math\n'), ((1529, 1542), 'math.cos', 'math.cos', (['phi'], {}), '(phi)\n', (1537, 1542), False, 'import math\n'), ((1543, 1556), 'math.cos', 'math.cos', (['phi'], {}), '(phi)\n', (1551, 1556), False, 'import math\n'), ((1557, 1570), 'math.sin', 'math.sin', (['phi'], {}), '(phi)\n', (1565, 1570), False, 'import math\n'), ((1571, 1584), 'math.sin', 'math.sin', (['phi'], {}), '(phi)\n', (1579, 1584), False, 'import math\n'), ((1603, 1616), 'math.sin', 'math.sin', (['phi'], {}), '(phi)\n', (1611, 1616), False, 'import math\n'), ((1666, 1679), 'math.sin', 'math.sin', (['phi'], {}), '(phi)\n', (1674, 1679), False, 'import math\n'), ((1709, 1722), 'math.sin', 'math.sin', (['phi'], {}), '(phi)\n', (1717, 1722), False, 'import math\n'), ((1723, 1736), 'math.sin', 'math.sin', (['phi'], {}), '(phi)\n', (1731, 1736), False, 'import math\n'), ((1737, 1750), 'math.cos', 'math.cos', (['phi'], {}), '(phi)\n', (1745, 1750), False, 'import math\n'), ((1751, 1764), 'math.cos', 'math.cos', (['phi'], {}), '(phi)\n', (1759, 1764), False, 'import math\n')]
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-06-18 07:56 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('disturbance', '0005_auto_20180618_1123'), ] operations = [ migrations.RemoveField( model_name='proposalapprovergroup', name='activities', ), migrations.RemoveField( model_name='proposalapprovergroup', name='regions', ), migrations.RemoveField( model_name='proposalassessorgroup', name='activities', ), migrations.RemoveField( model_name='proposalassessorgroup', name='regions', ), ]
[ "django.db.migrations.RemoveField" ]
[((296, 373), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""proposalapprovergroup"""', 'name': '"""activities"""'}), "(model_name='proposalapprovergroup', name='activities')\n", (318, 373), False, 'from django.db import migrations\n'), ((418, 492), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""proposalapprovergroup"""', 'name': '"""regions"""'}), "(model_name='proposalapprovergroup', name='regions')\n", (440, 492), False, 'from django.db import migrations\n'), ((537, 614), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""proposalassessorgroup"""', 'name': '"""activities"""'}), "(model_name='proposalassessorgroup', name='activities')\n", (559, 614), False, 'from django.db import migrations\n'), ((659, 733), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""proposalassessorgroup"""', 'name': '"""regions"""'}), "(model_name='proposalassessorgroup', name='regions')\n", (681, 733), False, 'from django.db import migrations\n')]
# Copyright 2019 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. # ============================================================================== """Tests for MovingAverage optimizers.""" import numpy as np import pytest import tensorflow as tf from tensorflow_addons.optimizers import MovingAverage @pytest.mark.usefixtures("maybe_run_functions_eagerly") def test_run(): var0 = tf.Variable([1.0, 2.0]) var1 = tf.Variable([3.0, 4.0]) grads0 = tf.constant([0.1, 0.1]) grads1 = tf.constant([0.01, 0.01]) grads_and_vars = list(zip([grads0, grads1], [var0, var1])) opt = MovingAverage(tf.keras.optimizers.SGD(lr=2.0), average_decay=0.5,) opt.apply_gradients(grads_and_vars) opt.apply_gradients(grads_and_vars) np.testing.assert_allclose(var0.read_value(), [0.6, 1.6]) np.testing.assert_allclose(var1.read_value(), [2.96, 3.96]) ema_var0 = opt.get_slot(var0, "average") ema_var1 = opt.get_slot(var1, "average") np.testing.assert_allclose(ema_var0.read_value(), [0.75, 1.75]) np.testing.assert_allclose(ema_var1.read_value(), [2.975, 3.975]) _ = opt.assign_average_vars([var0, var1]) np.testing.assert_allclose(var0.read_value(), [0.75, 1.75]) np.testing.assert_allclose(var1.read_value(), [2.975, 3.975]) var0.assign_add([1.0, 1.0]), var1.assign_add([2.0, 2.0]), ema_var0.assign_add([3.0, 3.0]), ema_var1.assign_add([4.0, 4.0]), np.testing.assert_allclose(var0.read_value(), [1.75, 2.75]) np.testing.assert_allclose(var1.read_value(), [4.975, 5.975]) np.testing.assert_allclose(ema_var0.read_value(), [3.75, 4.75]) np.testing.assert_allclose(ema_var1.read_value(), [6.975, 7.975]) @pytest.mark.usefixtures("maybe_run_functions_eagerly") def test_opt_failure(): base_opt = None with pytest.raises(TypeError): MovingAverage(base_opt, 0.5) @pytest.mark.usefixtures("maybe_run_functions_eagerly") def test_model_weights_update(): grad = tf.Variable([[0.1]]) model = tf.keras.Sequential( [ tf.keras.layers.Dense( 1, kernel_initializer=tf.keras.initializers.Constant([[1.0]]), use_bias=False, ) ] ) model.build(input_shape=[1, 1]) opt = MovingAverage(tf.keras.optimizers.SGD(lr=2.0), average_decay=0.5) _ = opt.apply_gradients(list(zip([grad], model.variables))) np.testing.assert_allclose(model.variables[0].read_value(), [[0.8]]) _ = opt.assign_average_vars(model.variables) np.testing.assert_allclose(model.variables[0].read_value(), [[0.9]]) @pytest.mark.usefixtures("maybe_run_functions_eagerly") def test_model_dynamic_lr(): grad = tf.Variable([[0.1]]) model = tf.keras.Sequential( [ tf.keras.layers.Dense( 1, kernel_initializer=tf.keras.initializers.Constant([[1.0]]), use_bias=False, ) ] ) model.build(input_shape=[1, 1]) opt = MovingAverage(tf.keras.optimizers.SGD(lr=1e-3), average_decay=0.5) _ = opt.apply_gradients(list(zip([grad], model.variables))) np.testing.assert_allclose(opt.lr.read_value(), 1e-3) opt.lr = 1e-4 np.testing.assert_allclose(opt.lr.read_value(), 1e-4) @pytest.mark.usefixtures("maybe_run_functions_eagerly") def test_optimizer_string(): _ = MovingAverage("adam") def test_config(): sgd_opt = tf.keras.optimizers.SGD(lr=2.0, nesterov=True, momentum=0.3, decay=0.1) opt = MovingAverage( sgd_opt, average_decay=0.5, num_updates=None, start_step=5, dynamic_decay=True, ) config = opt.get_config() assert config["average_decay"] == 0.5 assert config["num_updates"] is None assert config["start_step"] == 5 assert config["dynamic_decay"] is True new_opt = MovingAverage.from_config(config) old_sgd_config = opt._optimizer.get_config() new_sgd_config = new_opt._optimizer.get_config() for k1, k2 in zip(old_sgd_config, new_sgd_config): assert old_sgd_config[k1] == new_sgd_config[k2] @pytest.mark.usefixtures("maybe_run_functions_eagerly") def test_fit_simple_linear_model(): seed = 0x2019 np.random.seed(seed) tf.random.set_seed(seed) num_examples = 5000 x = np.random.standard_normal((num_examples, 3)) w = np.random.standard_normal((3, 1)) y = np.dot(x, w) + np.random.standard_normal((num_examples, 1)) * 1e-4 model = tf.keras.models.Sequential() model.add(tf.keras.layers.Dense(input_shape=(3,), units=1)) opt = MovingAverage("sgd") model.compile(opt, loss="mse") model.fit(x, y, epochs=5) opt.assign_average_vars(model.variables) x = np.random.standard_normal((100, 3)) y = np.dot(x, w) predicted = model.predict(x) max_abs_diff = np.max(np.abs(predicted - y)) assert max_abs_diff < 5e-3 def test_serialization(): sgd_opt = tf.keras.optimizers.SGD(lr=2.0, nesterov=True, momentum=0.3, decay=0.1) optimizer = MovingAverage( sgd_opt, average_decay=0.5, num_updates=None, start_step=5, dynamic_decay=True, ) config = tf.keras.optimizers.serialize(optimizer) new_optimizer = tf.keras.optimizers.deserialize(config) assert new_optimizer.get_config() == optimizer.get_config() @pytest.mark.usefixtures("maybe_run_functions_eagerly") def test_start_step(): var0 = tf.Variable([1.0, 2.0]) grads0 = tf.constant([0.1, 0.1]) grads_and_vars = [(grads0, var0)] opt = MovingAverage( tf.keras.optimizers.SGD(lr=1.0), average_decay=0.5, start_step=1, ) opt.apply_gradients(grads_and_vars) np.testing.assert_allclose(var0.read_value(), [0.9, 1.9]) ema_var0 = opt.get_slot(var0, "average") opt.apply_gradients(grads_and_vars) np.testing.assert_allclose(var0.read_value(), [0.8, 1.8]) np.testing.assert_allclose(ema_var0.read_value(), [0.85, 1.85]) @pytest.mark.usefixtures("maybe_run_functions_eagerly") def test_dynamic_decay(): var0 = tf.Variable([1.0, 2.0]) grads0 = tf.constant([0.1, 0.1]) grads_and_vars = [(grads0, var0)] opt = MovingAverage( tf.keras.optimizers.SGD(lr=2.0), average_decay=0.5, dynamic_decay=True, ) opt.apply_gradients(grads_and_vars) opt.apply_gradients(grads_and_vars) np.testing.assert_allclose(var0.read_value(), [0.6, 1.6]) ema_var0 = opt.get_slot(var0, "average") np.testing.assert_allclose(ema_var0.read_value(), [0.64, 1.64]) @pytest.mark.usefixtures("maybe_run_functions_eagerly") @pytest.mark.with_device([tf.distribute.MirroredStrategy]) def test_swap_weights(device): with device.scope(): var = tf.Variable([1.0, 2.0]) grads = tf.constant([0.1, 0.1]) opt = MovingAverage(tf.keras.optimizers.SGD(lr=2.0), average_decay=0.5,) @tf.function def apply_gradients(): opt.apply_gradients([(grads, var)]) device.run(apply_gradients) np.testing.assert_allclose(var.read_value(), [0.8, 1.8]) ema_var = opt.get_slot(var, "average") np.testing.assert_allclose(ema_var.read_value(), [0.85, 1.85]) with device.scope(): opt.shadow_copy([var]) opt.swap_weights() np.testing.assert_allclose(ema_var.read_value(), [0.8, 1.8]) np.testing.assert_allclose(var.read_value(), [0.85, 1.85]) with device.scope(): opt.swap_weights() np.testing.assert_allclose(var.read_value(), [0.8, 1.8]) np.testing.assert_allclose(ema_var.read_value(), [0.85, 1.85])
[ "numpy.random.standard_normal", "numpy.abs", "tensorflow.keras.optimizers.deserialize", "tensorflow.random.set_seed", "tensorflow_addons.optimizers.MovingAverage", "tensorflow.Variable", "pytest.mark.with_device", "tensorflow.keras.optimizers.serialize", "tensorflow.keras.initializers.Constant", "...
[((848, 902), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""maybe_run_functions_eagerly"""'], {}), "('maybe_run_functions_eagerly')\n", (871, 902), False, 'import pytest\n'), ((2237, 2291), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""maybe_run_functions_eagerly"""'], {}), "('maybe_run_functions_eagerly')\n", (2260, 2291), False, 'import pytest\n'), ((2411, 2465), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""maybe_run_functions_eagerly"""'], {}), "('maybe_run_functions_eagerly')\n", (2434, 2465), False, 'import pytest\n'), ((3141, 3195), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""maybe_run_functions_eagerly"""'], {}), "('maybe_run_functions_eagerly')\n", (3164, 3195), False, 'import pytest\n'), ((3807, 3861), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""maybe_run_functions_eagerly"""'], {}), "('maybe_run_functions_eagerly')\n", (3830, 3861), False, 'import pytest\n'), ((4607, 4661), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""maybe_run_functions_eagerly"""'], {}), "('maybe_run_functions_eagerly')\n", (4630, 4661), False, 'import pytest\n'), ((5814, 5868), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""maybe_run_functions_eagerly"""'], {}), "('maybe_run_functions_eagerly')\n", (5837, 5868), False, 'import pytest\n'), ((6434, 6488), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""maybe_run_functions_eagerly"""'], {}), "('maybe_run_functions_eagerly')\n", (6457, 6488), False, 'import pytest\n'), ((6998, 7052), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""maybe_run_functions_eagerly"""'], {}), "('maybe_run_functions_eagerly')\n", (7021, 7052), False, 'import pytest\n'), ((7054, 7111), 'pytest.mark.with_device', 'pytest.mark.with_device', (['[tf.distribute.MirroredStrategy]'], {}), '([tf.distribute.MirroredStrategy])\n', (7077, 7111), False, 'import pytest\n'), ((930, 953), 'tensorflow.Variable', 'tf.Variable', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (941, 953), True, 'import tensorflow as tf\n'), ((965, 988), 'tensorflow.Variable', 'tf.Variable', (['[3.0, 4.0]'], {}), '([3.0, 4.0])\n', (976, 988), True, 'import tensorflow as tf\n'), ((1003, 1026), 'tensorflow.constant', 'tf.constant', (['[0.1, 0.1]'], {}), '([0.1, 0.1])\n', (1014, 1026), True, 'import tensorflow as tf\n'), ((1040, 1065), 'tensorflow.constant', 'tf.constant', (['[0.01, 0.01]'], {}), '([0.01, 0.01])\n', (1051, 1065), True, 'import tensorflow as tf\n'), ((2510, 2530), 'tensorflow.Variable', 'tf.Variable', (['[[0.1]]'], {}), '([[0.1]])\n', (2521, 2530), True, 'import tensorflow as tf\n'), ((3236, 3256), 'tensorflow.Variable', 'tf.Variable', (['[[0.1]]'], {}), '([[0.1]])\n', (3247, 3256), True, 'import tensorflow as tf\n'), ((3899, 3920), 'tensorflow_addons.optimizers.MovingAverage', 'MovingAverage', (['"""adam"""'], {}), "('adam')\n", (3912, 3920), False, 'from tensorflow_addons.optimizers import MovingAverage\n'), ((3956, 4027), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'lr': '(2.0)', 'nesterov': '(True)', 'momentum': '(0.3)', 'decay': '(0.1)'}), '(lr=2.0, nesterov=True, momentum=0.3, decay=0.1)\n', (3979, 4027), True, 'import tensorflow as tf\n'), ((4038, 4135), 'tensorflow_addons.optimizers.MovingAverage', 'MovingAverage', (['sgd_opt'], {'average_decay': '(0.5)', 'num_updates': 'None', 'start_step': '(5)', 'dynamic_decay': '(True)'}), '(sgd_opt, average_decay=0.5, num_updates=None, start_step=5,\n dynamic_decay=True)\n', (4051, 4135), False, 'from tensorflow_addons.optimizers import MovingAverage\n'), ((4356, 4389), 'tensorflow_addons.optimizers.MovingAverage.from_config', 'MovingAverage.from_config', (['config'], {}), '(config)\n', (4381, 4389), False, 'from tensorflow_addons.optimizers import MovingAverage\n'), ((4720, 4740), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (4734, 4740), True, 'import numpy as np\n'), ((4745, 4769), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['seed'], {}), '(seed)\n', (4763, 4769), True, 'import tensorflow as tf\n'), ((4802, 4846), 'numpy.random.standard_normal', 'np.random.standard_normal', (['(num_examples, 3)'], {}), '((num_examples, 3))\n', (4827, 4846), True, 'import numpy as np\n'), ((4855, 4888), 'numpy.random.standard_normal', 'np.random.standard_normal', (['(3, 1)'], {}), '((3, 1))\n', (4880, 4888), True, 'import numpy as np\n'), ((4977, 5005), 'tensorflow.keras.models.Sequential', 'tf.keras.models.Sequential', ([], {}), '()\n', (5003, 5005), True, 'import tensorflow as tf\n'), ((5081, 5101), 'tensorflow_addons.optimizers.MovingAverage', 'MovingAverage', (['"""sgd"""'], {}), "('sgd')\n", (5094, 5101), False, 'from tensorflow_addons.optimizers import MovingAverage\n'), ((5222, 5257), 'numpy.random.standard_normal', 'np.random.standard_normal', (['(100, 3)'], {}), '((100, 3))\n', (5247, 5257), True, 'import numpy as np\n'), ((5266, 5278), 'numpy.dot', 'np.dot', (['x', 'w'], {}), '(x, w)\n', (5272, 5278), True, 'import numpy as np\n'), ((5436, 5507), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'lr': '(2.0)', 'nesterov': '(True)', 'momentum': '(0.3)', 'decay': '(0.1)'}), '(lr=2.0, nesterov=True, momentum=0.3, decay=0.1)\n', (5459, 5507), True, 'import tensorflow as tf\n'), ((5524, 5621), 'tensorflow_addons.optimizers.MovingAverage', 'MovingAverage', (['sgd_opt'], {'average_decay': '(0.5)', 'num_updates': 'None', 'start_step': '(5)', 'dynamic_decay': '(True)'}), '(sgd_opt, average_decay=0.5, num_updates=None, start_step=5,\n dynamic_decay=True)\n', (5537, 5621), False, 'from tensorflow_addons.optimizers import MovingAverage\n'), ((5646, 5686), 'tensorflow.keras.optimizers.serialize', 'tf.keras.optimizers.serialize', (['optimizer'], {}), '(optimizer)\n', (5675, 5686), True, 'import tensorflow as tf\n'), ((5707, 5746), 'tensorflow.keras.optimizers.deserialize', 'tf.keras.optimizers.deserialize', (['config'], {}), '(config)\n', (5738, 5746), True, 'import tensorflow as tf\n'), ((5903, 5926), 'tensorflow.Variable', 'tf.Variable', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (5914, 5926), True, 'import tensorflow as tf\n'), ((5940, 5963), 'tensorflow.constant', 'tf.constant', (['[0.1, 0.1]'], {}), '([0.1, 0.1])\n', (5951, 5963), True, 'import tensorflow as tf\n'), ((6526, 6549), 'tensorflow.Variable', 'tf.Variable', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (6537, 6549), True, 'import tensorflow as tf\n'), ((6563, 6586), 'tensorflow.constant', 'tf.constant', (['[0.1, 0.1]'], {}), '([0.1, 0.1])\n', (6574, 6586), True, 'import tensorflow as tf\n'), ((1155, 1186), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'lr': '(2.0)'}), '(lr=2.0)\n', (1178, 1186), True, 'import tensorflow as tf\n'), ((2345, 2369), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2358, 2369), False, 'import pytest\n'), ((2379, 2407), 'tensorflow_addons.optimizers.MovingAverage', 'MovingAverage', (['base_opt', '(0.5)'], {}), '(base_opt, 0.5)\n', (2392, 2407), False, 'from tensorflow_addons.optimizers import MovingAverage\n'), ((2827, 2858), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'lr': '(2.0)'}), '(lr=2.0)\n', (2850, 2858), True, 'import tensorflow as tf\n'), ((3553, 3586), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'lr': '(0.001)'}), '(lr=0.001)\n', (3576, 3586), True, 'import tensorflow as tf\n'), ((4897, 4909), 'numpy.dot', 'np.dot', (['x', 'w'], {}), '(x, w)\n', (4903, 4909), True, 'import numpy as np\n'), ((5020, 5068), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', ([], {'input_shape': '(3,)', 'units': '(1)'}), '(input_shape=(3,), units=1)\n', (5041, 5068), True, 'import tensorflow as tf\n'), ((5340, 5361), 'numpy.abs', 'np.abs', (['(predicted - y)'], {}), '(predicted - y)\n', (5346, 5361), True, 'import numpy as np\n'), ((6036, 6067), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'lr': '(1.0)'}), '(lr=1.0)\n', (6059, 6067), True, 'import tensorflow as tf\n'), ((6659, 6690), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'lr': '(2.0)'}), '(lr=2.0)\n', (6682, 6690), True, 'import tensorflow as tf\n'), ((7182, 7205), 'tensorflow.Variable', 'tf.Variable', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (7193, 7205), True, 'import tensorflow as tf\n'), ((7222, 7245), 'tensorflow.constant', 'tf.constant', (['[0.1, 0.1]'], {}), '([0.1, 0.1])\n', (7233, 7245), True, 'import tensorflow as tf\n'), ((4912, 4956), 'numpy.random.standard_normal', 'np.random.standard_normal', (['(num_examples, 1)'], {}), '((num_examples, 1))\n', (4937, 4956), True, 'import numpy as np\n'), ((7275, 7306), 'tensorflow.keras.optimizers.SGD', 'tf.keras.optimizers.SGD', ([], {'lr': '(2.0)'}), '(lr=2.0)\n', (7298, 7306), True, 'import tensorflow as tf\n'), ((2663, 2702), 'tensorflow.keras.initializers.Constant', 'tf.keras.initializers.Constant', (['[[1.0]]'], {}), '([[1.0]])\n', (2693, 2702), True, 'import tensorflow as tf\n'), ((3389, 3428), 'tensorflow.keras.initializers.Constant', 'tf.keras.initializers.Constant', (['[[1.0]]'], {}), '([[1.0]])\n', (3419, 3428), True, 'import tensorflow as tf\n')]
# TEST STACK SCRIPT # <NAME>, July 2020 import stack # Create Stack object s = stack.Stack("\nMY COOL ELECTRONICS STACK") # Add elements to stack s.push("Raspberry Pi 3") s.push("Arduino") s.push("Arduino") s.push("LED red") s.push("LED green") s.push("LED yellow") s.push("PIC18F2550") s.push("Resistor") s.push("Multimeter") s.push("Capacitor") # See complete stack (first check) print("\nFIRST STACK CHECK:\n", s) # Remove some elements of stack s.pop() s.pop() s.pop() s.pop() # See complete stack (second check) print("\nSECOND STACK CHECK:\n", s) # See last stack item at this point print("\nLAST STACK ITEM NOW:\n", s.look_last_item()) # Clear all stack s.clear_stack() # Check stack now print("\nSTACK AFTER CLEAR METHOD:\n", s) # Add elements again s.push("Sensor HC-SR04") s.push("Sensor IR") s.push("Cables") s.push("Freescale microcontroller") # Check stack now print("\nNEW STACK:\n", s)
[ "stack.Stack" ]
[((81, 126), 'stack.Stack', 'stack.Stack', (['"""\nMY COOL ELECTRONICS STACK"""'], {}), '("""\nMY COOL ELECTRONICS STACK""")\n', (92, 126), False, 'import stack\n')]
# -*- coding: utf-8 -*- from django.conf.urls.defaults import patterns, url from django.http import HttpResponseRedirect from shop.util.decorators import on_method, shop_login_required class PayOnDeliveryBackend(object): backend_name = "Pay On Delivery" url_namespace = "pay-on-delivery" def __init__(self, shop): self.shop = shop # This is the shop reference, it allows this backend to interact with # it in a tidy way (look ma', no imports!) @on_method(shop_login_required) def simple_view(self, request): """ This simple view does nothing but record the "payment" as being complete since we trust the delivery guy to collect money, and redirect to the success page. This is the most simple case. """ # Get the order object the_order = self.shop.get_order(request) # Let's mark this as being complete for the full sum in our database # Set it as paid (it needs to be paid to the delivery guy, we assume # he does his job properly) self.shop.confirm_payment( the_order, self.shop.get_order_total(the_order), "None", self.backend_name) return HttpResponseRedirect(self.shop.get_finished_url()) def get_urls(self): urlpatterns = patterns('', url(r'^$', self.simple_view, name='pay-on-delivery'), ) return urlpatterns
[ "django.conf.urls.defaults.url", "shop.util.decorators.on_method" ]
[((490, 520), 'shop.util.decorators.on_method', 'on_method', (['shop_login_required'], {}), '(shop_login_required)\n', (499, 520), False, 'from shop.util.decorators import on_method, shop_login_required\n'), ((1335, 1386), 'django.conf.urls.defaults.url', 'url', (['"""^$"""', 'self.simple_view'], {'name': '"""pay-on-delivery"""'}), "('^$', self.simple_view, name='pay-on-delivery')\n", (1338, 1386), False, 'from django.conf.urls.defaults import patterns, url\n')]
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Base forecasting module.""" import logging import operator from collections import defaultdict from datetime import datetime from datetime import timedelta from decimal import Decimal from functools import reduce import numpy as np import statsmodels.api as sm from django.db.models import Q from statsmodels.sandbox.regression.predstd import wls_prediction_std from statsmodels.tools.sm_exceptions import ValueWarning from tenant_schemas.utils import tenant_context from api.models import Provider from api.query_filter import QueryFilter from api.query_filter import QueryFilterCollection from api.report.all.openshift.provider_map import OCPAllProviderMap from api.report.aws.openshift.provider_map import OCPAWSProviderMap from api.report.aws.provider_map import AWSProviderMap from api.report.azure.openshift.provider_map import OCPAzureProviderMap from api.report.azure.provider_map import AzureProviderMap from api.report.gcp.openshift.provider_map import OCPGCPProviderMap from api.report.gcp.provider_map import GCPProviderMap from api.report.ocp.provider_map import OCPProviderMap from api.utils import DateHelper from api.utils import get_cost_type from reporting.provider.aws.models import AWSOrganizationalUnit LOG = logging.getLogger(__name__) class Forecast: """Base forecasting class.""" # the minimum number of data points needed to use the current month's data. # if we have fewer than this many data points, fall back to using the previous month's data. # # this number is chosen in part because statsmodels.stats.stattools.omni_normtest() needs at least eight data # points to test for normal distribution. MINIMUM = 8 # the precision of the floats returned in the forecast response. PRECISION = 8 REPORT_TYPE = "costs" def __init__(self, query_params): # noqa: C901 """Class Constructor. Instance Attributes: - cost_summary_table (Model) - aggregates (dict) - filters (QueryFilterCollection) - query_range (tuple) """ self.dh = DateHelper() self.params = query_params if self.provider is Provider.PROVIDER_AWS: if query_params.get("cost_type"): self.cost_type = query_params.get("cost_type") else: self.cost_type = get_cost_type(self.request) # select appropriate model based on access access = query_params.get("access", {}) access_key = "default" self.cost_summary_table = self.provider_map.views.get("costs").get(access_key) if access: access_key = tuple(access.keys()) filter_fields = self.provider_map.provider_map.get("filters") materialized_view = self.provider_map.views.get("costs").get(access_key) if materialized_view: # We found a matching materialized view, use that self.cost_summary_table = materialized_view else: # We have access constraints, but no view to accomodate, default to daily summary table self.cost_summary_table = self.provider_map.query_table self.forecast_days_required = max((self.dh.this_month_end - self.dh.yesterday).days, 2) # forecasts use a rolling window self.query_range = (self.dh.n_days_ago(self.dh.yesterday, 30), self.dh.yesterday) self.filters = QueryFilterCollection() self.filters.add(field="usage_start", operation="gte", parameter=self.query_range[0]) self.filters.add(field="usage_end", operation="lte", parameter=self.query_range[1]) # filter queries based on access if access_key != "default": for q_param, filt in filter_fields.items(): access = query_params.get_access(q_param, list()) if access: self.set_access_filters(access, filt, self.filters) @property def provider_map(self): """Return the provider map instance.""" current_provider = self if current_provider.provider is Provider.PROVIDER_AWS: return self.provider_map_class(self.provider, self.REPORT_TYPE, self.cost_type) return self.provider_map_class(self.provider, self.REPORT_TYPE) @property def total_cost_term(self): """Return the provider map value for total cost.""" return self.provider_map.report_type_map.get("aggregates", {}).get("cost_total") @property def supplementary_cost_term(self): """Return the provider map value for total supplemenatry cost.""" return self.provider_map.report_type_map.get("aggregates", {}).get("sup_total") @property def infrastructure_cost_term(self): """Return the provider map value for total inftrastructure cost.""" return self.provider_map.report_type_map.get("aggregates", {}).get("infra_total") def predict(self): """Define ORM query to run forecast and return prediction.""" cost_predictions = {} with tenant_context(self.params.tenant): data = ( self.cost_summary_table.objects.filter(self.filters.compose()) .order_by("usage_start") .values("usage_start") .annotate( total_cost=self.total_cost_term, supplementary_cost=self.supplementary_cost_term, infrastructure_cost=self.infrastructure_cost_term, ) ) for fieldname in ["total_cost", "infrastructure_cost", "supplementary_cost"]: uniq_data = self._uniquify_qset(data.values("usage_start", fieldname), field=fieldname) cost_predictions[fieldname] = self._predict(uniq_data) cost_predictions = self._key_results_by_date(cost_predictions) return self.format_result(cost_predictions) def _predict(self, data): """Handle pre and post prediction work. This function handles arranging incoming data to conform with statsmodels requirements. Then after receiving the forecast output, this function handles formatting to conform to API reponse requirements. Args: data (list) a list of (datetime, float) tuples Returns: (LinearForecastResult) linear forecast results object """ LOG.debug("Forecast input data: %s", data) if len(data) < self.MINIMUM: LOG.warning( "Number of data elements (%s) is fewer than the minimum (%s). Unable to generate forecast.", len(data), self.MINIMUM, ) return [] dates, costs = zip(*data) X = self._enumerate_dates(dates) Y = [float(c) for c in costs] # difference in days between the first day to be predicted and the last day of data after outlier removal day_gap = ( datetime.combine(self.dh.today.date(), self.dh.midnight) - datetime.combine(dates[-1], self.dh.midnight) ).days # calculate x-values for the prediction range pred_x = [i for i in range(X[-1] + day_gap, X[-1] + day_gap + self.forecast_days_required)] # run the forecast results = self._run_forecast(X, Y, to_predict=pred_x) result_dict = {} for i, value in enumerate(results.prediction): # extrapolate confidence intervals to align with prediction. # this reduces the confidence interval below 95th percentile, but is a better UX. if i < len(results.confidence_lower): lower = results.confidence_lower[i] else: lower = results.confidence_lower[-1] + results.slope * (i - len(results.confidence_lower)) if i < len(results.confidence_upper): upper = results.confidence_upper[i] else: upper = results.confidence_upper[-1] + results.slope * (i - len(results.confidence_upper)) # ensure that there are no negative numbers. result_dict[self.dh.today.date() + timedelta(days=i)] = { "total_cost": max((value, 0)), "confidence_min": max((lower, 0)), "confidence_max": max((upper, 0)), } return (result_dict, results.rsquared, results.pvalues) def _enumerate_dates(self, date_list): """Given a list of dates, return a list of integers. This method works in conjunction with _remove_outliers(). This method works to preserve any gaps in the data created by _remove_outliers() so that the integers used for the X-axis are aligned appropriately. Example: If _remove_outliers() returns {"2000-01-01": 1.0, "2000-01-03": 1.5} then _enumerate_dates() returns [0, 2] """ days = self.dh.list_days( datetime.combine(date_list[0], self.dh.midnight), datetime.combine(date_list[-1], self.dh.midnight) ) out = [i for i, day in enumerate(days) if day.date() in date_list] return out def _remove_outliers(self, data): """Remove outliers from our dateset before predicting. We use a box plot method without plotting the box. """ values = list(data.values()) if values: third_quartile, first_quartile = np.percentile(values, [Decimal(75), Decimal(25)]) interquartile_range = third_quartile - first_quartile upper_boundary = third_quartile + (Decimal(1.5) * interquartile_range) lower_boundary = first_quartile - (Decimal(1.5) * interquartile_range) return {key: value for key, value in data.items() if (value >= lower_boundary and value <= upper_boundary)} return data def _key_results_by_date(self, results, check_term="total_cost"): """Take results formatted by cost type, and return results keyed by date.""" results_by_date = defaultdict(dict) date_based_dict = results[check_term][0] if results[check_term] else [] for date in date_based_dict: for cost_term in results: if results[cost_term][0].get(date): results_by_date[date][cost_term] = ( results[cost_term][0][date], {"rsquared": results[cost_term][1]}, {"pvalues": results[cost_term][2]}, ) return results_by_date def format_result(self, results): """Format results for API consumption.""" f_format = f"%.{self.PRECISION}f" # avoid converting floats to e-notation units = "USD" response = [] for key in results: if key > self.dh.this_month_end.date(): continue dikt = { "date": key, "values": [ { "date": key, "infrastructure": { "total": { "value": round(results[key]["infrastructure_cost"][0]["total_cost"], 3), "units": units, }, "confidence_max": { "value": round(results[key]["infrastructure_cost"][0]["confidence_max"], 3), "units": units, }, "confidence_min": { "value": round(max(results[key]["infrastructure_cost"][0]["confidence_min"], 0), 3), "units": units, }, "rsquared": { "value": f_format % results[key]["infrastructure_cost"][1]["rsquared"], "units": None, }, "pvalues": {"value": results[key]["infrastructure_cost"][2]["pvalues"], "units": None}, }, "supplementary": { "total": { "value": round(results[key]["supplementary_cost"][0]["total_cost"], 3), "units": units, }, "confidence_max": { "value": round(results[key]["supplementary_cost"][0]["confidence_max"], 3), "units": units, }, "confidence_min": { "value": round(max(results[key]["supplementary_cost"][0]["confidence_min"], 0), 3), "units": units, }, "rsquared": { "value": f_format % results[key]["supplementary_cost"][1]["rsquared"], "units": None, }, "pvalues": {"value": results[key]["supplementary_cost"][2]["pvalues"], "units": None}, }, "cost": { "total": {"value": round(results[key]["total_cost"][0]["total_cost"], 3), "units": units}, "confidence_max": { "value": round(results[key]["total_cost"][0]["confidence_max"], 3), "units": units, }, "confidence_min": { "value": round(max(results[key]["total_cost"][0]["confidence_min"], 0), 3), "units": units, }, "rsquared": {"value": f_format % results[key]["total_cost"][1]["rsquared"], "units": None}, "pvalues": {"value": results[key]["total_cost"][2]["pvalues"], "units": None}, }, } ], } response.append(dikt) return response def _run_forecast(self, x, y, to_predict=None): """Apply the forecast model. Args: x (list) a list of exogenous variables y (list) a list of endogenous variables to_predict (list) a list of exogenous variables used in the forecast results Note: both x and y MUST be the same number of elements Returns: (tuple) (numpy.ndarray) prediction values (numpy.ndarray) confidence interval lower bound (numpy.ndarray) confidence interval upper bound (float) R-squared value (list) P-values """ x = sm.add_constant(x) to_predict = sm.add_constant(to_predict) model = sm.OLS(y, x) results = model.fit() return LinearForecastResult(results, exog=to_predict) def _uniquify_qset(self, qset, field="total_cost"): """Take a QuerySet list, sum costs within the same day, and arrange it into a list of tuples. Args: qset (QuerySet) field (str) - field name in the QuerySet to be summed Returns: [(date, cost), ...] """ # FIXME: this QuerySet->dict->list conversion probably isn't ideal. # FIXME: there's probably a way to aggregate multiple sources by date using just the ORM. result = defaultdict(Decimal) for item in qset: result[item.get("usage_start")] += Decimal(item.get(field, 0.0)) result = self._remove_outliers(result) out = [(k, v) for k, v in result.items()] return out def set_access_filters(self, access, filt, filters): """Set access filters to ensure RBAC restrictions adhere to user's access and filters. Args: access (list) the list containing the users relevant access filt (list or dict) contains the filters to be updated filters (QueryFilterCollection) the filter collection to add the new filters to returns: None """ if isinstance(filt, list): for _filt in filt: _filt["operation"] = "in" q_filter = QueryFilter(parameter=access, **_filt) filters.add(q_filter) else: filt["operation"] = "in" q_filter = QueryFilter(parameter=access, **filt) filters.add(q_filter) class LinearForecastResult: """Container class for linear forecast results. Note: this class should be considered read-only """ def __init__(self, regression_result, exog=None): """Class constructor. Args: regression_result (RegressionResult) the results of a statsmodels regression exog (array-like) future exogenous variables; points to predict """ self._exog = exog self._regression_result = regression_result self._std_err, self._conf_lower, self._conf_upper = wls_prediction_std(regression_result, exog=exog) try: LOG.debug(regression_result.summary()) except (ValueWarning, UserWarning) as exc: LOG.warning(exc) LOG.debug("Forecast interval lower-bound: %s", self.confidence_lower) LOG.debug("Forecast interval upper-bound: %s", self.confidence_upper) @property def prediction(self): """Forecast prediction. Args: to_predict (array-like) - values to predict; uses model training values if not set. Returns: (array-like) - an nparray of prediction values or empty list """ # predict() returns the same number of elements as the number of input observations prediction = [] try: if self._exog is not None: prediction = self._regression_result.predict(sm.add_constant(self._exog)) else: prediction = self._regression_result.predict() except ValueError as exc: LOG.error(exc) LOG.debug("Forecast prediction: %s", prediction) return prediction @property def confidence_lower(self): """Confidence interval lower-bound.""" return self._conf_lower @property def confidence_upper(self): """Confidence interval upper-bound.""" return self._conf_upper @property def rsquared(self): """Forecast R-squared value.""" return self._regression_result.rsquared @property def pvalues(self): """Forecast P-values. The p-values use a two-tailed test. Depending on the prediction, there can be up to two values returned. Returns: (str) or [(str), (str)] """ f_format = f"%.{Forecast.PRECISION}f" # avoid converting floats to e-notation if len(self._regression_result.pvalues.tolist()) == 1: return f_format % self._regression_result.pvalues.tolist()[0] else: return [f_format % item for item in self._regression_result.pvalues.tolist()] @property def slope(self): """Slope estimate of linear regression. For a basic linear regression, params is always a list of two values - the slope and the Y-intercept. This assumption is not true for more advanced cases using other types of least-squares regressions. Returns: (float) the estimated slope param """ return self._regression_result.params[1] @property def intercept(self): """Y-intercept estimate of linear regression. For a basic linear regression, params is always a list of two values - the slope and the Y-intercept. This assumption is not true for more advanced cases using other types of least-squares regressions. Returns: (float) the estimated Y-intercept param """ return self._regression_result.params[0] class AWSForecast(Forecast): """AWS forecasting class.""" provider = Provider.PROVIDER_AWS provider_map_class = AWSProviderMap def set_access_filters(self, access, filt, filters): """Set access filters to ensure RBAC restrictions adhere to user's access and filters. Args: access (list) the list containing the users relevant access filt (list or dict) contains the filters to be updated filters (QueryFilterCollection) the filter collection to add the new filters to returns: None """ # Note that the RBAC access for organizational units should follow the hierarchical # structure of the tree. Therefore, as long as the user has access to the root nodes # passed in by group_by[org_unit_id] then the user automatically has access to all # the sub orgs. if access and "*" not in access: with tenant_context(self.params.tenant): allowed_ous = ( AWSOrganizationalUnit.objects.filter( reduce(operator.or_, (Q(org_unit_path__icontains=rbac) for rbac in access)) ) .filter(account_alias__isnull=True) .order_by("org_unit_id", "-created_timestamp") .distinct("org_unit_id") ) if allowed_ous: access = list(allowed_ous.values_list("org_unit_id", flat=True)) if not isinstance(filt, list) and filt["field"] == "organizational_unit__org_unit_path": filt["field"] = "organizational_unit__org_unit_id" super().set_access_filters(access, filt, filters) class AzureForecast(Forecast): """Azure forecasting class.""" provider = Provider.PROVIDER_AZURE provider_map_class = AzureProviderMap class OCPForecast(Forecast): """OCP forecasting class.""" provider = Provider.PROVIDER_OCP provider_map_class = OCPProviderMap class OCPAWSForecast(Forecast): """OCP+AWS forecasting class.""" provider = Provider.OCP_AWS provider_map_class = OCPAWSProviderMap class OCPAzureForecast(Forecast): """OCP+Azure forecasting class.""" provider = Provider.OCP_AZURE provider_map_class = OCPAzureProviderMap class OCPGCPForecast(Forecast): """OCP+GCP forecasting class.""" provider = Provider.OCP_GCP provider_map_class = OCPGCPProviderMap class OCPAllForecast(Forecast): """OCP+All forecasting class.""" provider = Provider.OCP_ALL provider_map_class = OCPAllProviderMap class GCPForecast(Forecast): """GCP forecasting class.""" provider = Provider.PROVIDER_GCP provider_map_class = GCPProviderMap
[ "logging.getLogger", "statsmodels.sandbox.regression.predstd.wls_prediction_std", "tenant_schemas.utils.tenant_context", "api.utils.get_cost_type", "api.query_filter.QueryFilter", "api.query_filter.QueryFilterCollection", "statsmodels.api.add_constant", "collections.defaultdict", "django.db.models.Q...
[((1309, 1336), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1326, 1336), False, 'import logging\n'), ((2160, 2172), 'api.utils.DateHelper', 'DateHelper', ([], {}), '()\n', (2170, 2172), False, 'from api.utils import DateHelper\n'), ((3497, 3520), 'api.query_filter.QueryFilterCollection', 'QueryFilterCollection', ([], {}), '()\n', (3518, 3520), False, 'from api.query_filter import QueryFilterCollection\n'), ((10099, 10116), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (10110, 10116), False, 'from collections import defaultdict\n'), ((14956, 14974), 'statsmodels.api.add_constant', 'sm.add_constant', (['x'], {}), '(x)\n', (14971, 14974), True, 'import statsmodels.api as sm\n'), ((14996, 15023), 'statsmodels.api.add_constant', 'sm.add_constant', (['to_predict'], {}), '(to_predict)\n', (15011, 15023), True, 'import statsmodels.api as sm\n'), ((15040, 15052), 'statsmodels.api.OLS', 'sm.OLS', (['y', 'x'], {}), '(y, x)\n', (15046, 15052), True, 'import statsmodels.api as sm\n'), ((15666, 15686), 'collections.defaultdict', 'defaultdict', (['Decimal'], {}), '(Decimal)\n', (15677, 15686), False, 'from collections import defaultdict\n'), ((17267, 17315), 'statsmodels.sandbox.regression.predstd.wls_prediction_std', 'wls_prediction_std', (['regression_result'], {'exog': 'exog'}), '(regression_result, exog=exog)\n', (17285, 17315), False, 'from statsmodels.sandbox.regression.predstd import wls_prediction_std\n'), ((5125, 5159), 'tenant_schemas.utils.tenant_context', 'tenant_context', (['self.params.tenant'], {}), '(self.params.tenant)\n', (5139, 5159), False, 'from tenant_schemas.utils import tenant_context\n'), ((9014, 9062), 'datetime.datetime.combine', 'datetime.combine', (['date_list[0]', 'self.dh.midnight'], {}), '(date_list[0], self.dh.midnight)\n', (9030, 9062), False, 'from datetime import datetime\n'), ((9064, 9113), 'datetime.datetime.combine', 'datetime.combine', (['date_list[-1]', 'self.dh.midnight'], {}), '(date_list[-1], self.dh.midnight)\n', (9080, 9113), False, 'from datetime import datetime\n'), ((16637, 16674), 'api.query_filter.QueryFilter', 'QueryFilter', ([], {'parameter': 'access'}), '(parameter=access, **filt)\n', (16648, 16674), False, 'from api.query_filter import QueryFilter\n'), ((2420, 2447), 'api.utils.get_cost_type', 'get_cost_type', (['self.request'], {}), '(self.request)\n', (2433, 2447), False, 'from api.utils import get_cost_type\n'), ((7105, 7150), 'datetime.datetime.combine', 'datetime.combine', (['dates[-1]', 'self.dh.midnight'], {}), '(dates[-1], self.dh.midnight)\n', (7121, 7150), False, 'from datetime import datetime\n'), ((16486, 16524), 'api.query_filter.QueryFilter', 'QueryFilter', ([], {'parameter': 'access'}), '(parameter=access, **_filt)\n', (16497, 16524), False, 'from api.query_filter import QueryFilter\n'), ((21160, 21194), 'tenant_schemas.utils.tenant_context', 'tenant_context', (['self.params.tenant'], {}), '(self.params.tenant)\n', (21174, 21194), False, 'from tenant_schemas.utils import tenant_context\n'), ((8218, 8235), 'datetime.timedelta', 'timedelta', ([], {'days': 'i'}), '(days=i)\n', (8227, 8235), False, 'from datetime import timedelta\n'), ((9516, 9527), 'decimal.Decimal', 'Decimal', (['(75)'], {}), '(75)\n', (9523, 9527), False, 'from decimal import Decimal\n'), ((9529, 9540), 'decimal.Decimal', 'Decimal', (['(25)'], {}), '(25)\n', (9536, 9540), False, 'from decimal import Decimal\n'), ((9657, 9669), 'decimal.Decimal', 'Decimal', (['(1.5)'], {}), '(1.5)\n', (9664, 9669), False, 'from decimal import Decimal\n'), ((9740, 9752), 'decimal.Decimal', 'Decimal', (['(1.5)'], {}), '(1.5)\n', (9747, 9752), False, 'from decimal import Decimal\n'), ((18134, 18161), 'statsmodels.api.add_constant', 'sm.add_constant', (['self._exog'], {}), '(self._exog)\n', (18149, 18161), True, 'import statsmodels.api as sm\n'), ((21332, 21364), 'django.db.models.Q', 'Q', ([], {'org_unit_path__icontains': 'rbac'}), '(org_unit_path__icontains=rbac)\n', (21333, 21364), False, 'from django.db.models import Q\n')]
import time from brainex.utils.gxe_utils import from_csv dataset_path = 'genex/experiments/data/ECGFiveDays.csv' mydb = from_csv(dataset_path, feature_num=0, num_worker=16, use_spark=True, driver_mem=64, max_result_mem=64, _rows_to_consider=400) mydb.build(st=0.1) for i in range(20): print('Running ' + str(i) + 'th query...') query = mydb.get_random_seq_of_len(sequence_len=68, seed=i) start = time.time() query_result = mydb.query_brute_force(query=query, best_k=5) duration = time.time() - start print('Done, it took ' + str(duration) + ' sec') print('result is ' + str(query_result))
[ "time.time", "brainex.utils.gxe_utils.from_csv" ]
[((122, 251), 'brainex.utils.gxe_utils.from_csv', 'from_csv', (['dataset_path'], {'feature_num': '(0)', 'num_worker': '(16)', 'use_spark': '(True)', 'driver_mem': '(64)', 'max_result_mem': '(64)', '_rows_to_consider': '(400)'}), '(dataset_path, feature_num=0, num_worker=16, use_spark=True,\n driver_mem=64, max_result_mem=64, _rows_to_consider=400)\n', (130, 251), False, 'from brainex.utils.gxe_utils import from_csv\n'), ((411, 422), 'time.time', 'time.time', ([], {}), '()\n', (420, 422), False, 'import time\n'), ((503, 514), 'time.time', 'time.time', ([], {}), '()\n', (512, 514), False, 'import time\n')]
#!/usr/bin/env python # Written against python 3.3.1 # Matasano Problem 4 # Detect single-character XOR # One of the 60-character strings at: # # https://gist.github.com/3132713 # has been encrypted by single-character XOR. Find it. (Your code from # problem 3 should help.) from prob3 import tryKey from prob1 import rawToHexLUT, hexToRaw cipher_strings = [ b'0e3647e8592d35514a081243582536ed3de6734059001e3f535ce6271032', b'334b041de124f73c18011a50e608097ac308ecee501337ec3e100854201d', b'40e127f51c10031d0133590b1e490f3514e05a54143d08222c2a4071e351', b'<KEY>', b'22015e420b07ef21164d5935e82338452f42282c1836e42536284c450de3', b'043b452e0268e7eb005a080b360f0642e6e342005217ef04a42f3e43113d', b'581e0829214202063d70030845e5301f5a5212ed0818e22f120b211b171b', b'<KEY>', b'<KEY>', b'550c3e13e80246320b0bec09362542243be42d1d5d060e203e1a0c66ef48', b'<KEY>', b'ec58ea200e3005090e1725005739eda7342aed311001383fff7c58ef1f11', b'<KEY>', b'05f12f380720ea2b19e24a07e53c142128354e2827f25a08fb401c3126a6', b'<KEY>', b'0b4f070f071fe92c200e1fa05e4b272e50201b5d493110e429482c100730', b'100a3148080f227fe60a132f0c10174fe3f63d1a5d38eb414ca8e82f2b05', b'0a19e83c58400a023b13234572e6e4272bf67434331631e63b5e0f00175c', b'54520c2ceb45530e0f78111d0b0707e01e4bf43b0606073854324421e6f9', b'09e7585353ee4a34190de1354e481c373a1b2b0a136127383e271212191f', b'<KEY>', b'371d39121605584f48217235ee1e0602445c162e4942254c071954321d29', b'4a0900e63e5f161e15554045f3594c2a6a77e4e52711602beaf53ae53bed', b'29011616565d2a372a605bee39eced31183fe068185c3b445b391fe53232', b'<KEY>', b'<KEY>', b'2c245155e8253708391a7ceb0d05005c3e080f3f0f0e5a16583b111f4448', b'493804044d262eec3759594f212d562420105d6a39e70a0f3957f347070c', b'e72d1d1f103807590f4339575e00381074485d2d580249f744052605e11d', b'<KEY>', b'<KEY>', b'e318164df80b043e5406296e5359271d152f552e155a43eda81f23231d1c', b'001de0413e174e18192c061e4b3d1b5626f90e3e1429544a20ee150d0c20', b'32e902193219033c58191302441a5c1b584825ea140c290927aaea53e23c', b'3a36363a732e32ea3f0e430508204b332c382a19292d5b291122e123446a', b'<KEY>', b'21f2fb250b2e55151e77253a3f0e5f4b2030370a4155e720e73914e35a4a', b'510a55583a3c491221397c123a2b14a8305b3b09e71b241d0e51202e1a32', b'1b51202f4917232b512a141d6812f03c455df05e5a1c2cee14390b3b593a', b'5f5731e5203116ee131a4a4b24112cef5d0822f035e6547d3a0014462f26', b'0028fb522104f771501a555d3f581e30e9ec3e49e3e63123432f07794145', b'1459f6312f000e5a1373e346e40f211e1b0b0e17000f391f170552150500', b'7e301e18325717e3412e022f087be30e5641080151357714e0e0eee15e11', b'533258e9360f513b083aa51d2824222f40200a470537ecec392d31070b38', b'<KEY>', b'2d3c230a1e5a300f6c3e26ed0d1709434950fd6f1e121335054129e4e4ec', b'ef22fa2112311b11584ce43434f46f521a215433f9514fe33d313a3e0838', b'34e7f336270c08010f2f544f0f1c1e235c0222644c2632efec061de2115f', b'<KEY>', b'e05d414dfa40222f0c382a03235f4d0d04372d4b7855105e26e44f2e0555', b'7f3a4f1351f85b0344223e1177e14707190c0e311f4ca633f5f3e9352372', b'01424d5d1a322a0d381717130e181d07240c2c19ecee750b1a37085d014c', b'<KEY>', b'0b1415512f38580e4e2a227def242643183c224f0ea146443403022fe9fd', b'43eb2b1078322a02192d5b5e0c360d584d0b5e2c13072912ee32f03f4155', b'002a52553e08361b0be0074b573e201c164c093a5c0f0159333b59770d5b', b'38e63c1c5244301a5a01f26930321256143e1ae05e1120a9eaf20a192d58', b'7d54140a152ef4035f09083ded531ee04df55848020656a1342e502649eb', b'0c211dfe101702015516341136252f3f06f73247133113f5642d083a3417', b'015e3d51433f3c003e5e28030b1d413eee186824504b241e0f0d32373e2b', b'2d465040ec130c5c0e2704aa17010c40095207223669110f22f45ea155f7', b'14552e2b341e5ce0195351066a23e3283e0ee935444b255a1c5c3cef7614', b'<KEY>', b'5658265f4c0ce4440a20322f591a413034292b312206a01be6453a512d21', b'1c585c19f31f785324f8583d1ee02620342b10a236263f105011ee5b0e14', b'<KEY>', b'<KEY>', b'<KEY>', b'550a20234202726341190311295254f4064205aa515ae0145a23071c4e18', b'3f2047024e3ce4555a1b39fa145455012c3afb0f2d11134846182e3c575b', b'e3e456571937762828065443153b51152e262f09c937024405284f236432', b'012f580c3536ec5c021574541d5c41123a4e661d5f0f5f344a083e3a5e4c', b'4216252d01eb0a2a4623621b48360d312c29f33e380650447617124b3e71', b'54141e59323606390204e95f1206520e5c084510034d30171c5e744f335d', b'1e30061401600b342e171059526d1949431a3f412f56594c183711ea4837', b'3131254f11e76f550e1e4d26f1391f44363b151c31281ff45259351da0e6', b'5def250d0f3505385f22e9f4112633005d272d092e0138275851f943e90e', b'0939165718303b445210095c16390cf04f19450e06f4545c0a0c320e3e23', b'<KEY>', b'0d3b2a5d271e463d2203765245065d5d684a051e5815265b52f3171d3004', b'<KEY>', b'4030544f3f51151e436e04203a5e3b287ee303490a43fb3b28042f36504e', b'1a2d5a03fc0e2c04384046242e2b5e1548101825eb2f285f1a210f022141', b'122355e90122281deeed3ba05636003826525d5551572d07030d4935201f', b'2a3c484a15410d3b16375d4665271b5c4ce7ee37083d3e512b45204f17f6', b'<KEY>', b'<KEY>', b'4a5209ef24e5f3225e503b143d0e5747323fe7ee3d5b1b5110395619e65a', b'1fee0a3945563d2b5703701817584b5f5b54702522f5031b561929ea2d1e', b'e7271935100e3c31211b23113a3a5524e02241181a251d521ff52f3c5a76', b'144a0efee02f0f5f1d353a1c112e1909234f032953ec591e0a58e55d2cf4', b'efee0cf00d0955500210015311467543544708eb590d113d30443d080c1e', b'1a562c1f7e2b0030094f051c03e30f4d501a0fe22a2817edfc5e470c3843', b'<KEY>', b'eb1d3f54ec0fea341a097c502ff1111524e24f5b553e49e8576b5b0e1e33', b'72413e2f5329e332ec563b5e65185efefd2c3b4e5f0b5133246d214a401d', b'352a0ae632183d200a162e5346110552131514e0553e51003e220d47424b', b'<KEY>', b'2d2457524a1e1204255934174d442a1a7d130f350a123c4a075f5be73e30', b'0c0518582d131f39575925e0231833370c482b270e183810415d5aec1900', b'<KEY>', b'010a4a2d0b0926082d2f1525562d1d070a7a08152f5b4438a4150b132e20', b'2b395d0d5d015d41335d21250de33e3d42152d3f557d1e44e4ee22255d2d', b'<KEY>', b'e7015f0215352030574b4108e44d0e1a204418e62325ff7f34052f234b2d', b'<KEY>', b'<KEY>', b'<KEY>', b'1e553809415efb1c460f2f0ffafaec491e4d4e49510452e8245a366a4106', b'e1f92cee0e10142514e7ec13155c412fe901092f1f0fa738280c5eee5e04', b'3526291e0b2a5f486a3051041f4c16372f5402e6f70b31a03525190b161a', b'260e5e1f0c2e4d7528ef11552fefe247201e4752085c1da903563c162a4b', b'2a14ff2e3265e604075e523b24455c364a7f284f3a43051d52152f1119e8', b'5f02e55a4b1300063640ef10151002565f0b0c010033a1cbef5d3634484a', b'<KEY>', b'1613400e1632435c0018482aa55b363d26290ae4405ded280f2b0c271536', b'4011250ce02119464a1de43113170356342c272d1d3355555e5706245e0a', b'16272d5e545953002e10020875e223010719555410f91ce518420e382456', b'0d4037320345f945241a1d090a545a310142442131464f4d10562ae4f05a', b'07ee4d4ae12e571e313c1636313134233e495459e548317708563c2c1b2f', b'<KEY>', b'5e63194411490c44494232237e1b323108573d3f391d1f3537e4165a2b35', b'51000a3a264c503b5852072a5636f04f5cea58a42838f5fca876415c3521', b'<KEY>', b'10f0370c5823115200e5015d083e2f1a5df91d68065c1b03f0080855e529', b'02ec00f1462d034123151ba6fc07eb3d5e54e85a3f3ee532fb41791a060b', b'<KEY>', b'5741235f051e080401a8013c065627e8ee5432205114243d54320e133f2d', b'4a4d181635411f5d084e31ed230c16506d5125415e060e4dcd0e5f3708e3', b'2d531c3e22065a5eee07310c145305131800063e4a20094b2006ea131240', b'e7335c1c4308160be6aa551a0f5a58243e0b10ee470047683c345e1c5b0c', b'5434505ee22a18110d20342e4b53062c4d79042a0a02422e225b2523e95a', b'3252212407115c07e15eee06391d0519e9271b641330011f383410281f0e', b'<KEY>', b'<KEY>', b'c32550ec3f132c0c2458503ae5241d3c0d7911480a073826315620403615', b'<KEY>', b'505746313d4d2e3455290a281ee81d50007e1148252528025237715a342a', b'1c0a13163e404e40242142061d34185421160220fa031f7a423a08f2e01a', b'101d303802f51b0c08ef461259315b553823e622a12d565509e23c624139', b'0a3d1309e4384c0eed383846545a035a41ee1771513b090a031e15f45159', b'2d4944092a1965542507003b23195758403e175a0a450c5c38114de21141', b'<KEY>', b'<KEY>', b'0e1d510556485e39557e044e2cf10457523016473f500b1e36370c17591c', b'7e5a19250a5e152b46f5130a094cef08e84704ef10197324464b0114017a', b'3b56f126390008343d3c400232ed201667211f0b1a1413080202530b08e2', b'4912321b61c90a0cf6ef0a0a0c0f17fa62eb385e2616194526701aff5fe6', b'2c57114b0400152d4f2aeb18ed41386c2e3a023a281d1a311eefe750ebab', b'3a4353282114593b3e36446d2c5e1e582e335337022930331f211604576a', b'<KEY>', b'074a122ee01b17131e4e124e2322a9560ce4120e37582b24e1036fe93f30', b'3c08290121090ef72f25e4f220323444532d3fe71f34553c7b2726131009', b'<KEY>', b'0e3d4fe03f56523cf40f29e4353455120e3a4f2f26f6a30a2b3e0c5b085a', b'57f3315c33e41c0f523426232d0651395c1525274e314d0219163b5f181f', b'53471622182739e9e25b473d74e1e7023d095a3134e62d1366563004120e', b'230a06431935391d5e0b5543223a3bed2b4358f555401e1b3b5c36470d11', b'22100330e03b4812e6120f163b1ef6abebe6f602545ef9a459e33d334c2a', b'463405faa655563a43532cfe154bec32fe3345eb2c2700340811213e5006', b'14241340112b2916017c270a0652732ee8121132385a6c020c040e2be15b', b'<KEY>', b'2e4c2e373b434b0d0b1b340c300e4b195614130ea03c234c292e14530c46', b'0d2c3f08560ee32e5a5b6413355215384442563e69ec294a0eef561e3053', b'193c100c0b24231c012273e10d2e12552723586120020b02e45632265e5f', b'2c175a11553d4b0b16025e2534180964245b125e5d6e595d1d2a0710580b', b'213a175ff30855e4001b305000263f5a5c3c5100163cee00114e3518f33a', b'10ed33e65b003012e7131e161d5e2e270b4645f358394118330f5a5b241b', b'33e80130f45708395457573406422a3b0d03e6e5053d0d2d151c083337a2', b'<KEY>', b'<KEY>', b'0864eb4935144c501103a71851370719301bec57093a0929ea3f18060e55', b'2d395e57143359e80efffb13330633ea19e323077b4814571e5a3de73a1f', b'<KEY>', b'2f3c2c28273a12520b482f18340d565d1fe84735474f4a012e1a13502523', b'23340f39064e306a08194d544647522e1443041d5ee81f5a18415e34a45f', b'475a392637565757730a0c4a517b2821040e1709e028071558021f164c54', b'100b2135190505264254005618f51152136125370eef27383e45350118ed', b'<KEY>', b'2c33141859392b04155e3d4e393b322526ee3e581d1b3d6817374d0c085b', b'c2ea5821200f1b755b2d13130f04e26625ea3a5b1e37144d3e473c24030d', b'ee15025d2019f757305e3f010e2a453a205f1919391e1a04e86d1a350119', b'1a5beb4946180fe0002a031a050b41e5164c58795021e1e45c59e2495c20', b'1121394f1e381c3647005b7326250514272b55250a49183be5454ba518eb', b'1ee55936102a465d5004371f2e382f1d03144f170d2b0eed042ee341eb19', b'ec1014ef3ff1272c3408220a41163708140b2e340e505c560c1e4cf82704', b'<KEY>', b'e259032c444b091e2e4920023f1a7ce40908255228e36f0f2424394b3c48', b'34130cf8223f23084813e745e006531a1e464b005e0e1ee405413fe22b4e', b'4af201080c0928420c2d491f6e5121e451223b070dee54244b3efc470a0e', b'<KEY>', b'2f3a142c4155073a200f04166c565634020a59ea04244ff7413c4bc10858', b'240d4752e5fa5a4e1ce255505602e55d4c575e2b59f52b4e0c0a0b464019', b'21341927f3380232396707232ae424ea123f5b371d4f65e2471dfbede611', b'<KEY>', b'<KEY>', b'<KEY>', b'4d59052e1f2242403d440a13263e1d2dea0612125e16033b180834030829', b'022917180d07474c295f793e42274b0e1e16581036225c1211e41e04042f', b'<KEY>', b'53085a3b34e75a1caa2e5d031f261f5f044350312f37455d493f131f3746', b'<KEY>', b'e42b315ce21f0def38144d20242845fa3f3b3b0ce8f4fb2d31ed1d54134b', b'2957023141335d35372813263b46581af6535a16404d0b4ff12a207648ec', b'e4421e301de25c43010c504e0f562f2018421ce137443b41134b5f542047', b'<KEY>', b'062d2e02267404241f4966e6e010052d3224e72856100b1d22f65a30e863', b'<KEY>', b'2a1be80e2013571522483b1e20321a4e03285d211a444d113924e8f41a1f', b'<KEY>', b'1b135d46eaef103e1d330a14337a2a4302441c1631ed07e7100c743a0e35', b'<KEY>', b'e7360e2b3846202a2926fa495e3302ed064d127a17343a1f11032b40e8f5', b'06e8f90a3118381c5414157d1434050210363e30500511a00a3d56e10438', b'30021931f7193e25a0540ef52658350929380974fb035b1a5d2c042959c7', b'<KEY>', b'2a2328120b2203320810134a0c0a0ef30b25460bec011c1e26e913575a51', b'e12d0948ed3c511416151d1c54082b3e385d14f838510bec4e4b5f585321', b'1559305c3a49192a010f04ec11001a3d5a5621e5535358353206521f013f', b'172c2c155a3a322009505c290516a2c4e4405a1e0a1e353b6e1a5a4e2f09', b'<KEY>', b'0931432e452d3aea1d02587d3a3e56ed2a3050e2f9363df366331e421947', b'<KEY>', b'4314380e264e2359e6a412504a424328e84434ff30236649353315344a00', b'25e33540550d3c15135b0eed451cfd1812eaf2063f085d6e214d121c342f', b'<KEY>', b'132f175e4c4af1120138e1f2085a3804471f5824555d083de6123f533123', b'0de11936062d3d2f12193e135f38ff5e1a531d1426523746004e2c063a27', b'49241aee1802311611a50de9592009e936270108214a0c4213a01f09545f', b'02e14d2babee204a5c4337135821360d021b7831305963ee0737072f0deb', b'1512371119050c0c1142245a004f033650481830230a1925085c1a172726', b'3be62f230a4b50526ec9345100252aa729eafa59221b3fa517304e500a15', b'5e57f231333c3d0c470a47551733511031362a3bed0f334a3f3136104230', b'eb24015d051a151f245905061a37ea273d2239fe02463a5e314d565f0457', b'23025f415d290a594e3b5940313347a11c5e41531ff15a385a183829780a', b'51e0035f2deb3b163eabe8550e2e0414491f573b5419234a28183044e112', b'1d54e8390b26585f3aef5f14206672240c4a5e5d31e01b4d406e351401fa', b'e555173e242c753b275d4ee50b2f26501402a71b1b5733ec19ee34284aed', b'<KEY>', b'3f4e024d4b161e144d5e3b140d1e2944465b491d265603a705373c231240', b'544f0d4ea6091e00e62d3e130d4f005139f339001a3b480c221b730be75e', b'5f1f4f3e0a0dec3b5128e32960e42d0fee02275528154b10e65c36555a2e', b'<KEY>', b'51203f1e01e5563851284013514a565e53125223052f47100e5011100201', b'3f5bee2305217838582be55958a00245265b0308ec56525b5c114c2d5407', b'e6e74818e53602160e45372029eb4de72754ec3f49290d2f5901014c0e7f', b'08e715e612380a5c1908285a1222073a023c562907384e4f470444483f34', b'1110382b5225343ba6092133483e2d683e1e280227084a1e405e3a341513', b'415f240f0c53e3f7196e2252fb0105347f345e531f535a344bf439220916', b'5722e7f7fa2f4c2e057e2a025e2dec31413439aa12265f5a3458f81a4b15', b'135839401856f337a72fec475a060de239a650163a55392a5b303f051415', b'56090f18023a2b16e2364407050d48e1541408281d3aa3e84c5b264c1f33', b'1725f9540aec5e10ed293e4e5a5a2d2125f053251a55395d1c2044022231', b'292d523ff86a180620075f325e02566659f30423525a053a01f0087f4b3b', b'17fe493808f25309251e1325596ce32b42311e5d0c2f58652640582a4b17', b'<KEY>', b'<KEY>', b'393a055f59060d454a235326e844243a30285c14e316272524f4f0444f51', b'<KEY>', b'2f1219430151e60f11150b101e295736361b1e053e4d08f83f230e2c383a', b'ef5b1d492610e834330f5cf3a2485d324f2822084f41111f582957191b19', b'1e3e223704fe1d2e1f592753e5550f15170b231b4234e945301f5605a670', b'300d322759ea0337015c662a0e073809543f2741104835512d0624551751', b'373727ef1f41084d0b5c0c0137283b1337026aea1c5ae115064ffa183402', b'09152b11e1233e5a0e302a521c5a33181e180026463744a82c024b4bf04e', b'<KEY>', b'e2000c405a01ede30c4c082e2537443c120f38fc57c43651423e5c3beb1d', b'1922182420191b293e163d58020b005f454a0621051a38e80b090a463ee9', b'<KEY>', b'<KEY>', b'775d1a345b483b35a02a4c3e17ee3a3d5a5b57153613264f23041922432f', b'35125b3e0a1d2257eb002a26455e1a2f042e1545e92f0b3408032c4f3551', b'2d4c392321300a18ed4f3e2c314d20500052aa3917e55d0d29500754282e', b'381b2e263758f63c474a1c23110c2d5f1c220412e91043580656080c0427', b'081ce1e5350b6a3535f0e6592e5b543432340e38f008e0324102e45a3f25', b'30040c181615362e4d1016160a4a5c006eeb1d2422355a3f1028ff192a07', b'<KEY>', b'1a2c06372d5b1419742150042d25003c2650512834ef16e51d183f0f0508', b'3d191107251100ee2e4125405a44174f061e0e1e5959e606530e06ed245e', b'3f592d47512dec5922500e460e1de7183b4c3c2e583942255a0c5d4d2305', b'3438001e482a002d56113a1fe13bed542d3508e22f4e22221431121c1539', b'ed445a5d28415073eb18022ef836274d573a48090f2a663058194901405d', b'<KEY>', b'5244102e1c3d304450ee01761924e62ff2173305e15809102b2125284dfc', b'171a3f010f3639056f2be71c2047581de32e05a20833e1221b0e25362459', b'2958280de238084f5a1c292e005be71f3b311e1f415809383d3862260238', b'361f56ecee120156375862eb3627185c2519545149e2e50b1f3b0c4e3352', b'<KEY>', b'10370656372e0236eb4f3303e216505f0e465228383729394faa2f205f34', b'<KEY>', b'<KEY>', b'59383ae11237e5450029162d2e1d3e09221a160e42ea06ea0ca7c7ecf4ea', b'3d3024f34d5c07464bea3b185e110d3a10395d3b2632343cf30ca2e6065a', b'262f111c0e15441a4825111b185f1e5756243206125f4603e97e79582d27', b'2d5801ee2654113e2da00b58e9260d643c10423e1d1f42093b0d0f7d5102', b'<KEY>', b'52053e3e152b5b2b4415580fec57ef5c08e5ed43cc2d2e5b40355d0d2017', b'<KEY>', b'1e313323324e5e177b171cf70c371541395c0e2b7726e42505483014362e', b'1910e4f7253f0a012057e03b1e3b4201362b224ff60e0b3a1d115b043957', b'200c1e0b242e5e3b4755f61e3be05c040908f1234358e55562711d2efa0f', b'0737e0160b1d13132044080d2325f1f0ee2f00354f2106471131020a5d0b', b'3f21060de62c052a17576e2ce729242b3e3621300627f01e52580a480050', b'1b381a11351f4f5d22040c3c4b3e7d263714e8e61a571d107a34260a4a51', b'edf52314e111207c0b23eb482f441d211f306137152407040e08530a783e', b'3c054e2d4e2905275e640220f74f1a193f54e1ed5b4e2a290eab27a55147', b'33522817335316ea2f3df957e25e02030601514f09f74c2fedee102d3114', b'5d05231d03313826164156110c44e4111f4658005e115e300f413b430300', b'380bf53a4331f74627492c133fe8eb3141ee39040def040c1a0ae914e3ed', b'5b00f0211f0a091e05582e22f05a5d262e0ce352251d25100b102b11e339', b'36053935f051f959093252411e2d5af81f360c0fa15d0b373b1d26323b77', b'<KEY>', b'0a5a114515536f553a352c513f0b12f700345fa51d5efb28222676e559ea', b'561b0557403f5f534a574638411e2d3b3c133f79555c333215e6f5f9e7ec', b'6658f7210218110f00062752e305f21601442c5310162445ed4d175630f3', b'0e2154253c4a22f02e1b0933351314071b521513235031250c18120024a1', b'e03555453d1e31775f37331823164c341c09e310463438481019fb0b12fa', b'37eee654410e4007501f2c0e42faf50125075b2b46164f165a1003097f08', b'<KEY>', b'<KEY>', b'<KEY>', b'5b2010060e2f5a4d045e0b36192f79181b0732183b4a261038340032f434', b'3a5557340be6f5315c35112912393503320f54065f0e275a3b5853352008', b'<KEY>', b'41053f5cef5f6f56e4f5410a5407281600200b2649460a2e3a3c38492a0c', b'4c071a57e9356ee415103c5c53e254063f2019340969e30a2e381d5b2555', b'32042f46431d2c44607934ed180c1028136a5f2b26092e3b2c4e2930585a',]; def findSingleCharXOR(ciphers): for cip in ciphers: for i in range(256): mg, plain = tryKey(cip, rawToHexLUT[i]); if (mg > .050): print("potential key: 0x" + rawToHexLUT[i]); print("potential hex(cipher): " + str(cip).lstrip("b'").rstrip("'")); print("potential hex(plain): " + str(plain).lstrip("b'").rstrip("'")); print("potential plaintext: " + str(hexToRaw(str(plain).lstrip("b'").rstrip("'"))).lstrip("b'").rstrip("'")); if __name__ == "__main__": findSingleCharXOR(cipher_strings); # Print the known answer, from having run this program once: #print("key: 0x58"); #print("plaintext: " + str(hexToRaw(hex_xor(cip, '58585858585858585858585858585858585858585858585858585858585858585858'))));
[ "prob3.tryKey" ]
[((17619, 17646), 'prob3.tryKey', 'tryKey', (['cip', 'rawToHexLUT[i]'], {}), '(cip, rawToHexLUT[i])\n', (17625, 17646), False, 'from prob3 import tryKey\n')]
import os from pathlib import Path class Paths: """Manages and configures the paths used by WaveRNN, Tacotron, and the data.""" def __init__(self, data_path, voc_id, tts_id): self.base = Path(__file__).parent.parent.expanduser().resolve()/'outdir' # Data Paths self.data = Path(data_path).expanduser().resolve() self.quant = self.data/'quant' self.mel = self.data/'mel' self.gta = self.data/'gta' # WaveRNN/Vocoder Paths self.voc_checkpoints = self.base/'checkpoints'/f'{voc_id}.wavernn' self.voc_latest_weights = self.voc_checkpoints/'latest_weights.pyt' self.voc_latest_optim = self.voc_checkpoints/'latest_optim.pyt' self.voc_output = self.base/'model_outputs'/f'{voc_id}.wavernn' self.voc_step = self.voc_checkpoints/'step.npy' self.voc_log = self.voc_checkpoints/'log.txt' # Tactron/TTS Paths self.tts_checkpoints = self.base/'checkpoints'/f'{tts_id}.tacotron' self.tts_latest_weights = self.tts_checkpoints/'latest_weights.pyt' self.tts_latest_optim = self.tts_checkpoints/'latest_optim.pyt' self.tts_output = self.base/'model_outputs'/f'{tts_id}.tacotron' self.tts_step = self.tts_checkpoints/'step.npy' self.tts_log = self.tts_checkpoints/'log.txt' self.tts_attention = self.tts_checkpoints/'attention' self.tts_mel_plot = self.tts_checkpoints/'mel_plots' self.create_paths() def create_paths(self): os.makedirs(self.data, exist_ok=True) os.makedirs(self.quant, exist_ok=True) os.makedirs(self.mel, exist_ok=True) os.makedirs(self.gta, exist_ok=True) os.makedirs(self.voc_checkpoints, exist_ok=True) os.makedirs(self.voc_output, exist_ok=True) os.makedirs(self.tts_checkpoints, exist_ok=True) os.makedirs(self.tts_output, exist_ok=True) os.makedirs(self.tts_attention, exist_ok=True) os.makedirs(self.tts_mel_plot, exist_ok=True) def get_tts_named_weights(self, name): """Gets the path for the weights in a named tts checkpoint.""" return self.tts_checkpoints/f'{name}_weights.pyt' def get_tts_named_optim(self, name): """Gets the path for the optimizer state in a named tts checkpoint.""" return self.tts_checkpoints/f'{name}_optim.pyt' def get_voc_named_weights(self, name): """Gets the path for the weights in a named voc checkpoint.""" return self.voc_checkpoints/f'{name}_weights.pyt' def get_voc_named_optim(self, name): """Gets the path for the optimizer state in a named voc checkpoint.""" return self.voc_checkpoints/f'{name}_optim.pyt'
[ "os.makedirs", "pathlib.Path" ]
[((1519, 1556), 'os.makedirs', 'os.makedirs', (['self.data'], {'exist_ok': '(True)'}), '(self.data, exist_ok=True)\n', (1530, 1556), False, 'import os\n'), ((1565, 1603), 'os.makedirs', 'os.makedirs', (['self.quant'], {'exist_ok': '(True)'}), '(self.quant, exist_ok=True)\n', (1576, 1603), False, 'import os\n'), ((1612, 1648), 'os.makedirs', 'os.makedirs', (['self.mel'], {'exist_ok': '(True)'}), '(self.mel, exist_ok=True)\n', (1623, 1648), False, 'import os\n'), ((1657, 1693), 'os.makedirs', 'os.makedirs', (['self.gta'], {'exist_ok': '(True)'}), '(self.gta, exist_ok=True)\n', (1668, 1693), False, 'import os\n'), ((1702, 1750), 'os.makedirs', 'os.makedirs', (['self.voc_checkpoints'], {'exist_ok': '(True)'}), '(self.voc_checkpoints, exist_ok=True)\n', (1713, 1750), False, 'import os\n'), ((1759, 1802), 'os.makedirs', 'os.makedirs', (['self.voc_output'], {'exist_ok': '(True)'}), '(self.voc_output, exist_ok=True)\n', (1770, 1802), False, 'import os\n'), ((1811, 1859), 'os.makedirs', 'os.makedirs', (['self.tts_checkpoints'], {'exist_ok': '(True)'}), '(self.tts_checkpoints, exist_ok=True)\n', (1822, 1859), False, 'import os\n'), ((1868, 1911), 'os.makedirs', 'os.makedirs', (['self.tts_output'], {'exist_ok': '(True)'}), '(self.tts_output, exist_ok=True)\n', (1879, 1911), False, 'import os\n'), ((1920, 1966), 'os.makedirs', 'os.makedirs', (['self.tts_attention'], {'exist_ok': '(True)'}), '(self.tts_attention, exist_ok=True)\n', (1931, 1966), False, 'import os\n'), ((1975, 2020), 'os.makedirs', 'os.makedirs', (['self.tts_mel_plot'], {'exist_ok': '(True)'}), '(self.tts_mel_plot, exist_ok=True)\n', (1986, 2020), False, 'import os\n'), ((308, 323), 'pathlib.Path', 'Path', (['data_path'], {}), '(data_path)\n', (312, 323), False, 'from pathlib import Path\n'), ((205, 219), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (209, 219), False, 'from pathlib import Path\n')]
#!/usr/bin/env python # import random import numpy as np from copy import copy from bart_utils import empty, Tree, logsumexp, softmax, check_if_zero, get_children_id #from itertools import izip, count from itertools import count class Particle(Tree): def __init__(self, train_ids=np.arange(0, dtype='int'), param=empty(), settings=empty(), cache_tmp={}): Tree.__init__(self, train_ids, param, settings, cache_tmp) self.ancestry = [] self.nodes_processed_itr = [] self.grow_nodes_itr = [] self.log_sis_ratio_d = {} if cache_tmp: self.do_not_grow = False self.grow_nodes = [0] def process_node_id(self, data, param, settings, cache, node_id): if self.do_not_split[node_id]: log_sis_ratio = 0.0 else: log_psplit = np.log(self.compute_psplit(node_id, param)) train_ids = self.train_ids[node_id] left, right = get_children_id(node_id) if settings.verbose >= 4: print('train_ids for this node = %s' % train_ids) (do_not_split_node_id, feat_id_chosen, split_chosen, idx_split_global, log_sis_ratio, logprior_nodeid, \ train_ids_left, train_ids_right, cache_tmp, loglik_left, loglik_right) \ = self.prior_proposal(data, param, settings, cache, node_id, train_ids, log_psplit) if do_not_split_node_id: self.do_not_split[node_id] = True else: self.update_left_right_statistics(cache_tmp, node_id, logprior_nodeid, train_ids_left,\ train_ids_right, loglik_left, loglik_right, feat_id_chosen, split_chosen, \ idx_split_global, settings, param, data, cache) self.grow_nodes.append(left) self.grow_nodes.append(right) return (log_sis_ratio) def grow_next(self, data, param, settings, cache): """ grows just one node at a time (nodewise expansion) breaks after processing the first non do_not_grow node or when grow_nodes is empty Note that multiple nodes could be killed in a single grow_next call """ # FIXME: refactor without the do_not_grow option; it made sense for SMC paper, but not for PG do_not_grow = True log_sis_ratio = 0.0 nodes_processed = [] if not self.grow_nodes: if settings.verbose >= 2: print('None of the leaves can be grown any further: Current ' \ 'depth = %3d, Skipping grow_next' % self.depth) else: while True: # loop through current leaf nodes, process first "non do_not_grow" node and break; # if none of the nodes can be processed, do_not_grow = True remove_position = 0 # just pop the oldest node node_id = self.grow_nodes.pop(remove_position) nodes_processed.append(node_id) do_not_grow = do_not_grow and self.do_not_split[node_id] if self.do_not_split[node_id]: if settings.verbose >= 3: print('Skipping split at node_id %3d' % node_id) if not self.grow_nodes: break else: log_sis_ratio += self.process_node_id(data, param, settings, cache, node_id) break # you have processed a non do_not_grow node, take a break! self.loglik_current = self.compute_loglik() self.log_sis_ratio = log_sis_ratio self.do_not_grow = do_not_grow if nodes_processed: self.nodes_processed_itr.append(nodes_processed) def check_nodes_processed_itr(self, settings): tmp = set([]) for nodes in self.nodes_processed_itr: for node in nodes: if node in tmp: print('node = %s present multiple times in nodes_processed_itr = %s' % \ (node, self.nodes_processed_itr)) raise Exception else: tmp.add(node) def update_particle_weights(particles, log_weights, settings): for n, p in enumerate(particles): if settings.verbose >= 2: print('pid = %5d, log_sis_ratio = %f' % (n, p.log_sis_ratio)) log_weights[n] += p.log_sis_ratio weights_norm = softmax(log_weights) # normalized weights ess = 1. / np.sum(weights_norm ** 2) / settings.n_particles log_pd = logsumexp(log_weights) return (log_pd, ess, log_weights, weights_norm) def resample(particles, log_weights, settings, log_pd, ess, weights_norm, tree_pg): if ess <= settings.ess_threshold: if tree_pg: pid_list = resample_pids_basic(settings, settings.n_particles-1, weights_norm) random.shuffle(pid_list) # shuffle so that particle is assigned randomly pid_list.insert(0, 0) else: pid_list = resample_pids_basic(settings, settings.n_particles, weights_norm) log_weights = np.ones(settings.n_particles) * (log_pd - np.log(settings.n_particles)) else: pid_list = range(settings.n_particles) if settings.verbose >= 2: print('ess = %s, ess_threshold = %s' % (ess, settings.ess_threshold)) print('new particle ids = ') print(pid_list) op = create_new_particles(particles, pid_list, settings) # update ancestry for pid, p in zip(pid_list, op): p.ancestry.append(pid) return (op, log_weights) def resample_pids_basic(settings, n_particles, prob): if settings.resample == 'multinomial': pid_list = sample_multinomial_numpy(n_particles, prob) elif settings.resample == 'systematic': pid_list = systematic_sample(n_particles, prob) return pid_list def sample_multinomial_numpy(n_particles, prob): indices = np.random.multinomial(n_particles, prob, size=1) pid_list = [pid for pid, cnt in enumerate(indices.flat) \ for n in range(cnt)] return pid_list def create_new_particles(particles, pid_list, settings): """ particles that occur just once after resampling are not 'copied' """ list_allocated = set([]) op = [] for i, pid in enumerate(pid_list): if pid not in list_allocated: op.append(particles[pid]) else: op.append(copy_particle(particles[pid], settings)) list_allocated.add(pid) return op def copy_particle(p, settings): # TODO: lots of unnecessary copying for PG; reduce memory requirement op = Particle() # lists op.leaf_nodes = p.leaf_nodes[:] op.non_leaf_nodes = p.non_leaf_nodes[:] op.ancestry = p.ancestry[:] op.nodes_processed_itr = [x[:] for x in p.nodes_processed_itr] op.grow_nodes = p.grow_nodes[:] op.grow_nodes_itr = [x[:] for x in p.grow_nodes_itr] # dictionaries op.do_not_split = p.do_not_split.copy() op.log_sis_ratio_d = p.log_sis_ratio_d.copy() op.sum_y = p.sum_y.copy() op.sum_y2 = p.sum_y2.copy() op.n_points = p.n_points.copy() op.param_n = p.param_n.copy() op.train_ids = p.train_ids.copy() op.node_info = p.node_info.copy() op.loglik = p.loglik.copy() op.logprior = p.logprior.copy() # other variables op.depth = copy(p.depth) op.do_not_grow = copy(p.do_not_grow) op.loglik_current = copy(p.loglik_current) return op def systematic_sample(n, prob): """ systematic re-sampling algorithm. Note: objects with > 1/n probability (better than average) are guaranteed to occur atleast once. see section 2.4 of 'Comparison of Resampling Schemes for Particle Filtering' by Douc et. al for more info. """ assert(n == len(prob)) assert(abs(np.sum(prob) - 1) < 1e-10) cum_prob = np.cumsum(prob) u = np.random.rand(1) / float(n) i = 0 indices = [] while True: while u > cum_prob[i]: i += 1 indices.append(i) u += 1/float(n) if u > 1: break return indices def init_particles(data, settings, param, cache_tmp): particles = [Particle(np.arange(data['n_train']), param, settings, cache_tmp) \ for n in range(settings.n_particles)] log_weights = np.array([p.loglik[0] for p in particles]) - np.log(settings.n_particles) return (particles, log_weights) def grow_next_pg(p, tree_pg, itr, settings): p.log_sis_ratio = 0. p.do_not_grow = False p.grow_nodes = [] try: nodes_processed = tree_pg.nodes_processed_itr[itr] p.nodes_processed_itr.append(nodes_processed[:]) for node_id in nodes_processed[:-1]: assert(tree_pg.do_not_split[node_id]) p.do_not_split[node_id] = True node_id = nodes_processed[-1] if node_id in tree_pg.node_info: left, right = get_children_id(node_id) log_sis_ratio_loglik_new = tree_pg.loglik[left] + tree_pg.loglik[right] - tree_pg.loglik[node_id] try: log_sis_ratio_loglik_old, log_sis_ratio_prior = tree_pg.log_sis_ratio_d[node_id] except KeyError: print('tree_pg: node_info = %s, log_sis_ratio_d = %s' % (tree_pg.node_info, tree_pg.log_sis_ratio_d)) raise KeyError if settings.verbose >= 2: print('log_sis_ratio_loglik_old = %s' % log_sis_ratio_loglik_old) print('log_sis_ratio_loglik_new = %s' % log_sis_ratio_loglik_new) p.log_sis_ratio = log_sis_ratio_loglik_new + log_sis_ratio_prior tree_pg.log_sis_ratio_d[node_id] = (log_sis_ratio_loglik_new, log_sis_ratio_prior) p.log_sis_ratio_d[node_id] = tree_pg.log_sis_ratio_d[node_id] p.non_leaf_nodes.append(node_id) try: p.leaf_nodes.remove(node_id) except ValueError: print('warning: unable to remove node_id = %s from leaf_nodes = %s' % (node_id, p.leaf_nodes)) pass p.leaf_nodes.append(left) p.leaf_nodes.append(right) # copying relevant bits p.node_info[node_id] = tree_pg.node_info[node_id] p.logprior[node_id] = tree_pg.logprior[node_id] for node_id_child in [left, right]: p.do_not_split[node_id_child] = False # can look up where node_id_child occurred in nodes_processed_itr p.loglik[node_id_child] = tree_pg.loglik[node_id_child] p.logprior[node_id_child] = tree_pg.logprior[node_id_child] p.train_ids[node_id_child] = tree_pg.train_ids[node_id_child] p.sum_y[node_id_child] = tree_pg.sum_y[node_id_child] p.sum_y2[node_id_child] = tree_pg.sum_y2[node_id_child] p.param_n[node_id_child] = tree_pg.param_n[node_id_child] p.n_points[node_id_child] = tree_pg.n_points[node_id_child] if settings.verbose >= 2: print('p.leaf_nodes = %s' % p.leaf_nodes) print('p.non_leaf_nodes = %s' % p.non_leaf_nodes) print('p.node_info.keys() = %s' % sorted(p.node_info.keys())) try: p.grow_nodes = tree_pg.grow_nodes_itr[itr+1] p.log_sis_ratio_d = tree_pg.log_sis_ratio_d p.depth = tree_pg.depth except IndexError: p.do_not_grow = True except IndexError: p.do_not_grow = True def run_smc(particles, data, settings, param, log_weights, cache, tree_pg=None): if settings.verbose >= 2: print('Conditioned tree:') tree_pg.print_tree() itr = 0 while True: if settings.verbose >= 2: print('\n') print('*'*80) print('Current iteration = %3d' % itr) print('*'*80) if itr != 0: # no resampling required when itr == 0 since weights haven't been updated yet if settings.verbose >= 1: print('iteration = %3d, log p(y|x) = %.2f, ess/n_particles = %f' % (itr, log_pd, ess)) (particles, log_weights) = resample(particles, log_weights, settings, log_pd, \ ess, weights_norm, tree_pg) for pid, p in enumerate(particles): if settings.verbose >= 2: print('Current particle = %3d' % pid) print('grow_nodes = %s' % p.grow_nodes) print('leaf_nodes = %s, non_leaf_nodes = %s' % (p.leaf_nodes, p.non_leaf_nodes)) if p.grow_nodes: p.grow_nodes_itr.append(p.grow_nodes[:]) if tree_pg and (pid == 0): if settings.verbose >= 2 and itr == 0: for s in ['leaf_nodes', 'non_leaf_nodes', 'grow_nodes_itr', 'ancestry', 'nodes_processed_itr']: print('p.%s = %s' % (s, getattr(p, s))) grow_next_pg(p, tree_pg, itr, settings) else: p.grow_next(data, param, settings, cache) p.update_depth() if settings.verbose >= 2: print('nodes_processed_itr for particle = %s' % p.nodes_processed_itr) print('grow_nodes (after running grow_next) (NOT updated for conditioned tree_pg) = %s' % p.grow_nodes) print('leaf_nodes = %s, non_leaf_nodes = %s' % (p.leaf_nodes, p.non_leaf_nodes)) print('nodes_processed_itr for particle (after running update_particle weights) = %s' % p.nodes_processed_itr) print('checking nodes_processed_itr') (log_pd, ess, log_weights, weights_norm) = \ update_particle_weights(particles, log_weights, settings) # in place update of log_weights if settings.verbose >= 2: print('log_weights = %s' % log_weights) if check_do_not_grow(particles): if settings.verbose >= 1: print('None of the particles can be grown any further; breaking out') break itr += 1 if (settings.debug == 1) and tree_pg: for pid, p in enumerate(particles): if settings.verbose >=2 : print('checking pid = %s' % pid) p.check_nodes_processed_itr(settings) if settings.verbose >= 2: print('check if tree_pg did the right thing:') print('nodes_processed_itr (orig, new):\n%s\n%s' % (tree_pg.nodes_processed_itr, particles[0].nodes_processed_itr)) print('leaf_nodes (orig, new):\n%s\n%s' % (tree_pg.leaf_nodes, particles[0].leaf_nodes)) print('non_leaf_nodes (orig, new):\n%s\n%s' % (tree_pg.non_leaf_nodes, particles[0].non_leaf_nodes)) print('grow_nodes_itr (orig, new):\n%s\n%s' % (tree_pg.grow_nodes_itr, particles[0].grow_nodes_itr)) assert particles[0].leaf_nodes == tree_pg.leaf_nodes assert particles[0].non_leaf_nodes == tree_pg.non_leaf_nodes assert particles[0].grow_nodes_itr == tree_pg.grow_nodes_itr return (particles, ess, log_weights, log_pd) def init_run_smc(data, settings, param, cache, cache_tmp, tree_pg=None): particles, log_weights = init_particles(data, settings, param, cache_tmp) (particles, ess, log_weights, log_pd) = \ run_smc(particles, data, settings, param, log_weights, cache, tree_pg) return (particles, log_pd, log_weights) def check_do_not_grow(particles): """ Test if all particles have grown fully """ do_not_grow = True for p in particles: do_not_grow = do_not_grow and p.do_not_grow return do_not_grow
[ "bart_utils.softmax", "numpy.random.rand", "random.shuffle", "numpy.ones", "bart_utils.get_children_id", "numpy.log", "numpy.random.multinomial", "bart_utils.Tree.__init__", "numpy.array", "numpy.sum", "bart_utils.empty", "numpy.cumsum", "copy.copy", "numpy.arange", "bart_utils.logsumexp...
[((4471, 4491), 'bart_utils.softmax', 'softmax', (['log_weights'], {}), '(log_weights)\n', (4478, 4491), False, 'from bart_utils import empty, Tree, logsumexp, softmax, check_if_zero, get_children_id\n'), ((4594, 4616), 'bart_utils.logsumexp', 'logsumexp', (['log_weights'], {}), '(log_weights)\n', (4603, 4616), False, 'from bart_utils import empty, Tree, logsumexp, softmax, check_if_zero, get_children_id\n'), ((5981, 6029), 'numpy.random.multinomial', 'np.random.multinomial', (['n_particles', 'prob'], {'size': '(1)'}), '(n_particles, prob, size=1)\n', (6002, 6029), True, 'import numpy as np\n'), ((7415, 7428), 'copy.copy', 'copy', (['p.depth'], {}), '(p.depth)\n', (7419, 7428), False, 'from copy import copy\n'), ((7450, 7469), 'copy.copy', 'copy', (['p.do_not_grow'], {}), '(p.do_not_grow)\n', (7454, 7469), False, 'from copy import copy\n'), ((7494, 7516), 'copy.copy', 'copy', (['p.loglik_current'], {}), '(p.loglik_current)\n', (7498, 7516), False, 'from copy import copy\n'), ((7911, 7926), 'numpy.cumsum', 'np.cumsum', (['prob'], {}), '(prob)\n', (7920, 7926), True, 'import numpy as np\n'), ((287, 312), 'numpy.arange', 'np.arange', (['(0)'], {'dtype': '"""int"""'}), "(0, dtype='int')\n", (296, 312), True, 'import numpy as np\n'), ((320, 327), 'bart_utils.empty', 'empty', ([], {}), '()\n', (325, 327), False, 'from bart_utils import empty, Tree, logsumexp, softmax, check_if_zero, get_children_id\n'), ((338, 345), 'bart_utils.empty', 'empty', ([], {}), '()\n', (343, 345), False, 'from bart_utils import empty, Tree, logsumexp, softmax, check_if_zero, get_children_id\n'), ((370, 428), 'bart_utils.Tree.__init__', 'Tree.__init__', (['self', 'train_ids', 'param', 'settings', 'cache_tmp'], {}), '(self, train_ids, param, settings, cache_tmp)\n', (383, 428), False, 'from bart_utils import empty, Tree, logsumexp, softmax, check_if_zero, get_children_id\n'), ((7935, 7952), 'numpy.random.rand', 'np.random.rand', (['(1)'], {}), '(1)\n', (7949, 7952), True, 'import numpy as np\n'), ((8370, 8412), 'numpy.array', 'np.array', (['[p.loglik[0] for p in particles]'], {}), '([p.loglik[0] for p in particles])\n', (8378, 8412), True, 'import numpy as np\n'), ((8415, 8443), 'numpy.log', 'np.log', (['settings.n_particles'], {}), '(settings.n_particles)\n', (8421, 8443), True, 'import numpy as np\n'), ((953, 977), 'bart_utils.get_children_id', 'get_children_id', (['node_id'], {}), '(node_id)\n', (968, 977), False, 'from bart_utils import empty, Tree, logsumexp, softmax, check_if_zero, get_children_id\n'), ((4532, 4557), 'numpy.sum', 'np.sum', (['(weights_norm ** 2)'], {}), '(weights_norm ** 2)\n', (4538, 4557), True, 'import numpy as np\n'), ((4916, 4940), 'random.shuffle', 'random.shuffle', (['pid_list'], {}), '(pid_list)\n', (4930, 4940), False, 'import random\n'), ((5151, 5180), 'numpy.ones', 'np.ones', (['settings.n_particles'], {}), '(settings.n_particles)\n', (5158, 5180), True, 'import numpy as np\n'), ((8244, 8270), 'numpy.arange', 'np.arange', (["data['n_train']"], {}), "(data['n_train'])\n", (8253, 8270), True, 'import numpy as np\n'), ((8968, 8992), 'bart_utils.get_children_id', 'get_children_id', (['node_id'], {}), '(node_id)\n', (8983, 8992), False, 'from bart_utils import empty, Tree, logsumexp, softmax, check_if_zero, get_children_id\n'), ((5193, 5221), 'numpy.log', 'np.log', (['settings.n_particles'], {}), '(settings.n_particles)\n', (5199, 5221), True, 'import numpy as np\n'), ((7869, 7881), 'numpy.sum', 'np.sum', (['prob'], {}), '(prob)\n', (7875, 7881), True, 'import numpy as np\n')]