repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
AustralianSynchrotron/lightflow
lightflow/models/parameters.py
Parameters.check_missing
def check_missing(self, args): """ Returns the names of all options that are required but were not specified. All options that don't have a default value are required in order to run the workflow. Args: args (dict): A dictionary of the provided arguments that is checked for missing options. Returns: list: A list with the names of the options that are missing from the provided arguments. """ return [opt.name for opt in self if (opt.name not in args) and (opt.default is None)]
python
def check_missing(self, args): """ Returns the names of all options that are required but were not specified. All options that don't have a default value are required in order to run the workflow. Args: args (dict): A dictionary of the provided arguments that is checked for missing options. Returns: list: A list with the names of the options that are missing from the provided arguments. """ return [opt.name for opt in self if (opt.name not in args) and (opt.default is None)]
[ "def", "check_missing", "(", "self", ",", "args", ")", ":", "return", "[", "opt", ".", "name", "for", "opt", "in", "self", "if", "(", "opt", ".", "name", "not", "in", "args", ")", "and", "(", "opt", ".", "default", "is", "None", ")", "]" ]
Returns the names of all options that are required but were not specified. All options that don't have a default value are required in order to run the workflow. Args: args (dict): A dictionary of the provided arguments that is checked for missing options. Returns: list: A list with the names of the options that are missing from the provided arguments.
[ "Returns", "the", "names", "of", "all", "options", "that", "are", "required", "but", "were", "not", "specified", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/parameters.py#L99-L114
train
AustralianSynchrotron/lightflow
lightflow/models/parameters.py
Parameters.consolidate
def consolidate(self, args): """ Consolidate the provided arguments. If the provided arguments have matching options, this performs a type conversion. For any option that has a default value and is not present in the provided arguments, the default value is added. Args: args (dict): A dictionary of the provided arguments. Returns: dict: A dictionary with the type converted and with default options enriched arguments. """ result = dict(args) for opt in self: if opt.name in result: result[opt.name] = opt.convert(result[opt.name]) else: if opt.default is not None: result[opt.name] = opt.convert(opt.default) return result
python
def consolidate(self, args): """ Consolidate the provided arguments. If the provided arguments have matching options, this performs a type conversion. For any option that has a default value and is not present in the provided arguments, the default value is added. Args: args (dict): A dictionary of the provided arguments. Returns: dict: A dictionary with the type converted and with default options enriched arguments. """ result = dict(args) for opt in self: if opt.name in result: result[opt.name] = opt.convert(result[opt.name]) else: if opt.default is not None: result[opt.name] = opt.convert(opt.default) return result
[ "def", "consolidate", "(", "self", ",", "args", ")", ":", "result", "=", "dict", "(", "args", ")", "for", "opt", "in", "self", ":", "if", "opt", ".", "name", "in", "result", ":", "result", "[", "opt", ".", "name", "]", "=", "opt", ".", "convert",...
Consolidate the provided arguments. If the provided arguments have matching options, this performs a type conversion. For any option that has a default value and is not present in the provided arguments, the default value is added. Args: args (dict): A dictionary of the provided arguments. Returns: dict: A dictionary with the type converted and with default options enriched arguments.
[ "Consolidate", "the", "provided", "arguments", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/parameters.py#L116-L139
train
AustralianSynchrotron/lightflow
lightflow/models/dag.py
Dag.define
def define(self, schema, *, validate=True): """ Store the task graph definition (schema). The schema has to adhere to the following rules: A key in the schema dict represents a parent task and the value one or more children: {parent: [child]} or {parent: [child1, child2]} The data output of one task can be routed to a labelled input slot of successor tasks using a dictionary instead of a list for the children: {parent: {child1: 'positive', child2: 'negative'}} An empty slot name or None skips the creation of a labelled slot: {parent: {child1: '', child2: None}} Args: schema (dict): A dictionary with the schema definition. validate (bool): Set to True to validate the graph by checking whether it is a directed acyclic graph. """ self._schema = schema if validate: self.validate(self.make_graph(self._schema))
python
def define(self, schema, *, validate=True): """ Store the task graph definition (schema). The schema has to adhere to the following rules: A key in the schema dict represents a parent task and the value one or more children: {parent: [child]} or {parent: [child1, child2]} The data output of one task can be routed to a labelled input slot of successor tasks using a dictionary instead of a list for the children: {parent: {child1: 'positive', child2: 'negative'}} An empty slot name or None skips the creation of a labelled slot: {parent: {child1: '', child2: None}} Args: schema (dict): A dictionary with the schema definition. validate (bool): Set to True to validate the graph by checking whether it is a directed acyclic graph. """ self._schema = schema if validate: self.validate(self.make_graph(self._schema))
[ "def", "define", "(", "self", ",", "schema", ",", "*", ",", "validate", "=", "True", ")", ":", "self", ".", "_schema", "=", "schema", "if", "validate", ":", "self", ".", "validate", "(", "self", ".", "make_graph", "(", "self", ".", "_schema", ")", ...
Store the task graph definition (schema). The schema has to adhere to the following rules: A key in the schema dict represents a parent task and the value one or more children: {parent: [child]} or {parent: [child1, child2]} The data output of one task can be routed to a labelled input slot of successor tasks using a dictionary instead of a list for the children: {parent: {child1: 'positive', child2: 'negative'}} An empty slot name or None skips the creation of a labelled slot: {parent: {child1: '', child2: None}} Args: schema (dict): A dictionary with the schema definition. validate (bool): Set to True to validate the graph by checking whether it is a directed acyclic graph.
[ "Store", "the", "task", "graph", "definition", "(", "schema", ")", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/dag.py#L77-L100
train
AustralianSynchrotron/lightflow
lightflow/models/dag.py
Dag.run
def run(self, config, workflow_id, signal, *, data=None): """ Run the dag by calling the tasks in the correct order. Args: config (Config): Reference to the configuration object from which the settings for the dag are retrieved. workflow_id (str): The unique ID of the workflow that runs this dag. signal (DagSignal): The signal object for dags. It wraps the construction and sending of signals into easy to use methods. data (MultiTaskData): The initial data that is passed on to the start tasks. Raises: DirectedAcyclicGraphInvalid: If the graph is not a dag (e.g. contains loops). ConfigNotDefinedError: If the configuration for the dag is empty. """ graph = self.make_graph(self._schema) # pre-checks self.validate(graph) if config is None: raise ConfigNotDefinedError() # create the celery app for submitting tasks celery_app = create_app(config) # the task queue for managing the current state of the tasks tasks = [] stopped = False # add all tasks without predecessors to the task list for task in nx.topological_sort(graph): task.workflow_name = self.workflow_name task.dag_name = self.name if len(list(graph.predecessors(task))) == 0: task.state = TaskState.Waiting tasks.append(task) def set_task_completed(completed_task): """ For each completed task, add all successor tasks to the task list. If they are not in the task list yet, flag them as 'waiting'. """ completed_task.state = TaskState.Completed for successor in graph.successors(completed_task): if successor not in tasks: successor.state = TaskState.Waiting tasks.append(successor) # process the task queue as long as there are tasks in it while tasks: if not stopped: stopped = signal.is_stopped # delay the execution by the polling time if config.dag_polling_time > 0.0: sleep(config.dag_polling_time) for i in range(len(tasks) - 1, -1, -1): task = tasks[i] # for each waiting task, wait for all predecessor tasks to be # completed. Then check whether the task should be skipped by # interrogating the predecessor tasks. if task.is_waiting: if stopped: task.state = TaskState.Stopped else: pre_tasks = list(graph.predecessors(task)) if all([p.is_completed for p in pre_tasks]): # check whether the task should be skipped run_task = task.has_to_run or len(pre_tasks) == 0 for pre in pre_tasks: if run_task: break # predecessor task is skipped and flag should # not be propagated if pre.is_skipped and not pre.propagate_skip: run_task = True # limits of a non-skipped predecessor task if not pre.is_skipped: if pre.celery_result.result.limit is not None: if task.name in [ n.name if isinstance(n, BaseTask) else n for n in pre.celery_result.result.limit]: run_task = True else: run_task = True task.is_skipped = not run_task # send the task to celery or, if skipped, mark it as completed if task.is_skipped: set_task_completed(task) else: # compose the input data from the predecessor tasks # output. Data from skipped predecessor tasks do not # contribute to the input data if len(pre_tasks) == 0: input_data = data else: input_data = MultiTaskData() for pt in [p for p in pre_tasks if not p.is_skipped]: slot = graph[pt][task]['slot'] input_data.add_dataset( pt.name, pt.celery_result.result.data.default_dataset, aliases=[slot] if slot is not None else None) task.state = TaskState.Running task.celery_result = celery_app.send_task( JobExecPath.Task, args=(task, workflow_id, input_data), queue=task.queue, routing_key=task.queue ) # flag task as completed elif task.is_running: if task.celery_completed: set_task_completed(task) elif task.celery_failed: task.state = TaskState.Aborted signal.stop_workflow() # cleanup task results that are not required anymore elif task.is_completed: if all([s.is_completed or s.is_stopped or s.is_aborted for s in graph.successors(task)]): if celery_app.conf.result_expires == 0: task.clear_celery_result() tasks.remove(task) # cleanup and remove stopped and aborted tasks elif task.is_stopped or task.is_aborted: if celery_app.conf.result_expires == 0: task.clear_celery_result() tasks.remove(task)
python
def run(self, config, workflow_id, signal, *, data=None): """ Run the dag by calling the tasks in the correct order. Args: config (Config): Reference to the configuration object from which the settings for the dag are retrieved. workflow_id (str): The unique ID of the workflow that runs this dag. signal (DagSignal): The signal object for dags. It wraps the construction and sending of signals into easy to use methods. data (MultiTaskData): The initial data that is passed on to the start tasks. Raises: DirectedAcyclicGraphInvalid: If the graph is not a dag (e.g. contains loops). ConfigNotDefinedError: If the configuration for the dag is empty. """ graph = self.make_graph(self._schema) # pre-checks self.validate(graph) if config is None: raise ConfigNotDefinedError() # create the celery app for submitting tasks celery_app = create_app(config) # the task queue for managing the current state of the tasks tasks = [] stopped = False # add all tasks without predecessors to the task list for task in nx.topological_sort(graph): task.workflow_name = self.workflow_name task.dag_name = self.name if len(list(graph.predecessors(task))) == 0: task.state = TaskState.Waiting tasks.append(task) def set_task_completed(completed_task): """ For each completed task, add all successor tasks to the task list. If they are not in the task list yet, flag them as 'waiting'. """ completed_task.state = TaskState.Completed for successor in graph.successors(completed_task): if successor not in tasks: successor.state = TaskState.Waiting tasks.append(successor) # process the task queue as long as there are tasks in it while tasks: if not stopped: stopped = signal.is_stopped # delay the execution by the polling time if config.dag_polling_time > 0.0: sleep(config.dag_polling_time) for i in range(len(tasks) - 1, -1, -1): task = tasks[i] # for each waiting task, wait for all predecessor tasks to be # completed. Then check whether the task should be skipped by # interrogating the predecessor tasks. if task.is_waiting: if stopped: task.state = TaskState.Stopped else: pre_tasks = list(graph.predecessors(task)) if all([p.is_completed for p in pre_tasks]): # check whether the task should be skipped run_task = task.has_to_run or len(pre_tasks) == 0 for pre in pre_tasks: if run_task: break # predecessor task is skipped and flag should # not be propagated if pre.is_skipped and not pre.propagate_skip: run_task = True # limits of a non-skipped predecessor task if not pre.is_skipped: if pre.celery_result.result.limit is not None: if task.name in [ n.name if isinstance(n, BaseTask) else n for n in pre.celery_result.result.limit]: run_task = True else: run_task = True task.is_skipped = not run_task # send the task to celery or, if skipped, mark it as completed if task.is_skipped: set_task_completed(task) else: # compose the input data from the predecessor tasks # output. Data from skipped predecessor tasks do not # contribute to the input data if len(pre_tasks) == 0: input_data = data else: input_data = MultiTaskData() for pt in [p for p in pre_tasks if not p.is_skipped]: slot = graph[pt][task]['slot'] input_data.add_dataset( pt.name, pt.celery_result.result.data.default_dataset, aliases=[slot] if slot is not None else None) task.state = TaskState.Running task.celery_result = celery_app.send_task( JobExecPath.Task, args=(task, workflow_id, input_data), queue=task.queue, routing_key=task.queue ) # flag task as completed elif task.is_running: if task.celery_completed: set_task_completed(task) elif task.celery_failed: task.state = TaskState.Aborted signal.stop_workflow() # cleanup task results that are not required anymore elif task.is_completed: if all([s.is_completed or s.is_stopped or s.is_aborted for s in graph.successors(task)]): if celery_app.conf.result_expires == 0: task.clear_celery_result() tasks.remove(task) # cleanup and remove stopped and aborted tasks elif task.is_stopped or task.is_aborted: if celery_app.conf.result_expires == 0: task.clear_celery_result() tasks.remove(task)
[ "def", "run", "(", "self", ",", "config", ",", "workflow_id", ",", "signal", ",", "*", ",", "data", "=", "None", ")", ":", "graph", "=", "self", ".", "make_graph", "(", "self", ".", "_schema", ")", "# pre-checks", "self", ".", "validate", "(", "graph...
Run the dag by calling the tasks in the correct order. Args: config (Config): Reference to the configuration object from which the settings for the dag are retrieved. workflow_id (str): The unique ID of the workflow that runs this dag. signal (DagSignal): The signal object for dags. It wraps the construction and sending of signals into easy to use methods. data (MultiTaskData): The initial data that is passed on to the start tasks. Raises: DirectedAcyclicGraphInvalid: If the graph is not a dag (e.g. contains loops). ConfigNotDefinedError: If the configuration for the dag is empty.
[ "Run", "the", "dag", "by", "calling", "the", "tasks", "in", "the", "correct", "order", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/dag.py#L102-L241
train
AustralianSynchrotron/lightflow
lightflow/models/dag.py
Dag.validate
def validate(self, graph): """ Validate the graph by checking whether it is a directed acyclic graph. Args: graph (DiGraph): Reference to a DiGraph object from NetworkX. Raises: DirectedAcyclicGraphInvalid: If the graph is not a valid dag. """ if not nx.is_directed_acyclic_graph(graph): raise DirectedAcyclicGraphInvalid(graph_name=self._name)
python
def validate(self, graph): """ Validate the graph by checking whether it is a directed acyclic graph. Args: graph (DiGraph): Reference to a DiGraph object from NetworkX. Raises: DirectedAcyclicGraphInvalid: If the graph is not a valid dag. """ if not nx.is_directed_acyclic_graph(graph): raise DirectedAcyclicGraphInvalid(graph_name=self._name)
[ "def", "validate", "(", "self", ",", "graph", ")", ":", "if", "not", "nx", ".", "is_directed_acyclic_graph", "(", "graph", ")", ":", "raise", "DirectedAcyclicGraphInvalid", "(", "graph_name", "=", "self", ".", "_name", ")" ]
Validate the graph by checking whether it is a directed acyclic graph. Args: graph (DiGraph): Reference to a DiGraph object from NetworkX. Raises: DirectedAcyclicGraphInvalid: If the graph is not a valid dag.
[ "Validate", "the", "graph", "by", "checking", "whether", "it", "is", "a", "directed", "acyclic", "graph", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/dag.py#L243-L253
train
AustralianSynchrotron/lightflow
lightflow/models/dag.py
Dag.make_graph
def make_graph(schema): """ Construct the task graph (dag) from a given schema. Parses the graph schema definition and creates the task graph. Tasks are the vertices of the graph and the connections defined in the schema become the edges. A key in the schema dict represents a parent task and the value one or more children: {parent: [child]} or {parent: [child1, child2]} The data output of one task can be routed to a labelled input slot of successor tasks using a dictionary instead of a list for the children: {parent: {child1: 'positive', child2: 'negative'}} An empty slot name or None skips the creation of a labelled slot: {parent: {child1: '', child2: None}} The underlying graph library creates nodes automatically, when an edge between non-existing nodes is created. Args: schema (dict): A dictionary with the schema definition. Returns: DiGraph: A reference to the fully constructed graph object. Raises: DirectedAcyclicGraphUndefined: If the schema is not defined. """ if schema is None: raise DirectedAcyclicGraphUndefined() # sanitize the input schema such that it follows the structure: # {parent: {child_1: slot_1, child_2: slot_2, ...}, ...} sanitized_schema = {} for parent, children in schema.items(): child_dict = {} if children is not None: if isinstance(children, list): if len(children) > 0: child_dict = {child: None for child in children} else: child_dict = {None: None} elif isinstance(children, dict): for child, slot in children.items(): child_dict[child] = slot if slot != '' else None else: child_dict = {children: None} else: child_dict = {None: None} sanitized_schema[parent] = child_dict # build the graph from the sanitized schema graph = nx.DiGraph() for parent, children in sanitized_schema.items(): for child, slot in children.items(): if child is not None: graph.add_edge(parent, child, slot=slot) else: graph.add_node(parent) return graph
python
def make_graph(schema): """ Construct the task graph (dag) from a given schema. Parses the graph schema definition and creates the task graph. Tasks are the vertices of the graph and the connections defined in the schema become the edges. A key in the schema dict represents a parent task and the value one or more children: {parent: [child]} or {parent: [child1, child2]} The data output of one task can be routed to a labelled input slot of successor tasks using a dictionary instead of a list for the children: {parent: {child1: 'positive', child2: 'negative'}} An empty slot name or None skips the creation of a labelled slot: {parent: {child1: '', child2: None}} The underlying graph library creates nodes automatically, when an edge between non-existing nodes is created. Args: schema (dict): A dictionary with the schema definition. Returns: DiGraph: A reference to the fully constructed graph object. Raises: DirectedAcyclicGraphUndefined: If the schema is not defined. """ if schema is None: raise DirectedAcyclicGraphUndefined() # sanitize the input schema such that it follows the structure: # {parent: {child_1: slot_1, child_2: slot_2, ...}, ...} sanitized_schema = {} for parent, children in schema.items(): child_dict = {} if children is not None: if isinstance(children, list): if len(children) > 0: child_dict = {child: None for child in children} else: child_dict = {None: None} elif isinstance(children, dict): for child, slot in children.items(): child_dict[child] = slot if slot != '' else None else: child_dict = {children: None} else: child_dict = {None: None} sanitized_schema[parent] = child_dict # build the graph from the sanitized schema graph = nx.DiGraph() for parent, children in sanitized_schema.items(): for child, slot in children.items(): if child is not None: graph.add_edge(parent, child, slot=slot) else: graph.add_node(parent) return graph
[ "def", "make_graph", "(", "schema", ")", ":", "if", "schema", "is", "None", ":", "raise", "DirectedAcyclicGraphUndefined", "(", ")", "# sanitize the input schema such that it follows the structure:", "# {parent: {child_1: slot_1, child_2: slot_2, ...}, ...}", "sanitized_schema",...
Construct the task graph (dag) from a given schema. Parses the graph schema definition and creates the task graph. Tasks are the vertices of the graph and the connections defined in the schema become the edges. A key in the schema dict represents a parent task and the value one or more children: {parent: [child]} or {parent: [child1, child2]} The data output of one task can be routed to a labelled input slot of successor tasks using a dictionary instead of a list for the children: {parent: {child1: 'positive', child2: 'negative'}} An empty slot name or None skips the creation of a labelled slot: {parent: {child1: '', child2: None}} The underlying graph library creates nodes automatically, when an edge between non-existing nodes is created. Args: schema (dict): A dictionary with the schema definition. Returns: DiGraph: A reference to the fully constructed graph object. Raises: DirectedAcyclicGraphUndefined: If the schema is not defined.
[ "Construct", "the", "task", "graph", "(", "dag", ")", "from", "a", "given", "schema", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/dag.py#L256-L318
train
AustralianSynchrotron/lightflow
lightflow/models/task_data.py
TaskData.merge
def merge(self, dataset): """ Merge the specified dataset on top of the existing data. This replaces all values in the existing dataset with the values from the given dataset. Args: dataset (TaskData): A reference to the TaskData object that should be merged on top of the existing object. """ def merge_data(source, dest): for key, value in source.items(): if isinstance(value, dict): merge_data(value, dest.setdefault(key, {})) else: dest[key] = value return dest merge_data(dataset.data, self._data) for h in dataset.task_history: if h not in self._task_history: self._task_history.append(h)
python
def merge(self, dataset): """ Merge the specified dataset on top of the existing data. This replaces all values in the existing dataset with the values from the given dataset. Args: dataset (TaskData): A reference to the TaskData object that should be merged on top of the existing object. """ def merge_data(source, dest): for key, value in source.items(): if isinstance(value, dict): merge_data(value, dest.setdefault(key, {})) else: dest[key] = value return dest merge_data(dataset.data, self._data) for h in dataset.task_history: if h not in self._task_history: self._task_history.append(h)
[ "def", "merge", "(", "self", ",", "dataset", ")", ":", "def", "merge_data", "(", "source", ",", "dest", ")", ":", "for", "key", ",", "value", "in", "source", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "m...
Merge the specified dataset on top of the existing data. This replaces all values in the existing dataset with the values from the given dataset. Args: dataset (TaskData): A reference to the TaskData object that should be merged on top of the existing object.
[ "Merge", "the", "specified", "dataset", "on", "top", "of", "the", "existing", "data", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_data.py#L59-L81
train
AustralianSynchrotron/lightflow
lightflow/models/task_data.py
MultiTaskData.add_dataset
def add_dataset(self, task_name, dataset=None, *, aliases=None): """ Add a new dataset to the MultiTaskData. Args: task_name (str): The name of the task from which the dataset was received. dataset (TaskData): The dataset that should be added. aliases (list): A list of aliases that should be registered with the dataset. """ self._datasets.append(dataset if dataset is not None else TaskData()) last_index = len(self._datasets) - 1 self._aliases[task_name] = last_index if aliases is not None: for alias in aliases: self._aliases[alias] = last_index if len(self._datasets) == 1: self._default_index = 0
python
def add_dataset(self, task_name, dataset=None, *, aliases=None): """ Add a new dataset to the MultiTaskData. Args: task_name (str): The name of the task from which the dataset was received. dataset (TaskData): The dataset that should be added. aliases (list): A list of aliases that should be registered with the dataset. """ self._datasets.append(dataset if dataset is not None else TaskData()) last_index = len(self._datasets) - 1 self._aliases[task_name] = last_index if aliases is not None: for alias in aliases: self._aliases[alias] = last_index if len(self._datasets) == 1: self._default_index = 0
[ "def", "add_dataset", "(", "self", ",", "task_name", ",", "dataset", "=", "None", ",", "*", ",", "aliases", "=", "None", ")", ":", "self", ".", "_datasets", ".", "append", "(", "dataset", "if", "dataset", "is", "not", "None", "else", "TaskData", "(", ...
Add a new dataset to the MultiTaskData. Args: task_name (str): The name of the task from which the dataset was received. dataset (TaskData): The dataset that should be added. aliases (list): A list of aliases that should be registered with the dataset.
[ "Add", "a", "new", "dataset", "to", "the", "MultiTaskData", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_data.py#L146-L163
train
AustralianSynchrotron/lightflow
lightflow/models/task_data.py
MultiTaskData.add_alias
def add_alias(self, alias, index): """ Add an alias pointing to the specified index. Args: alias (str): The alias that should point to the given index. index (int): The index of the dataset for which an alias should be added. Raises: DataInvalidIndex: If the index does not represent a valid dataset. """ if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) self._aliases[alias] = index
python
def add_alias(self, alias, index): """ Add an alias pointing to the specified index. Args: alias (str): The alias that should point to the given index. index (int): The index of the dataset for which an alias should be added. Raises: DataInvalidIndex: If the index does not represent a valid dataset. """ if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) self._aliases[alias] = index
[ "def", "add_alias", "(", "self", ",", "alias", ",", "index", ")", ":", "if", "index", ">=", "len", "(", "self", ".", "_datasets", ")", ":", "raise", "DataInvalidIndex", "(", "'A dataset with index {} does not exist'", ".", "format", "(", "index", ")", ")", ...
Add an alias pointing to the specified index. Args: alias (str): The alias that should point to the given index. index (int): The index of the dataset for which an alias should be added. Raises: DataInvalidIndex: If the index does not represent a valid dataset.
[ "Add", "an", "alias", "pointing", "to", "the", "specified", "index", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_data.py#L165-L177
train
AustralianSynchrotron/lightflow
lightflow/models/task_data.py
MultiTaskData.flatten
def flatten(self, in_place=True): """ Merge all datasets into a single dataset. The default dataset is the last dataset to be merged, as it is considered to be the primary source of information and should overwrite all existing fields with the same key. Args: in_place (bool): Set to ``True`` to replace the existing datasets with the merged one. If set to ``False``, will return a new MultiTaskData object containing the merged dataset. Returns: MultiTaskData: If the in_place flag is set to False. """ new_dataset = TaskData() for i, dataset in enumerate(self._datasets): if i != self._default_index: new_dataset.merge(dataset) new_dataset.merge(self.default_dataset) # point all aliases to the new, single dataset new_aliases = {alias: 0 for alias, _ in self._aliases.items()} # replace existing datasets or return a new MultiTaskData object if in_place: self._datasets = [new_dataset] self._aliases = new_aliases self._default_index = 0 else: return MultiTaskData(dataset=new_dataset, aliases=list(new_aliases.keys()))
python
def flatten(self, in_place=True): """ Merge all datasets into a single dataset. The default dataset is the last dataset to be merged, as it is considered to be the primary source of information and should overwrite all existing fields with the same key. Args: in_place (bool): Set to ``True`` to replace the existing datasets with the merged one. If set to ``False``, will return a new MultiTaskData object containing the merged dataset. Returns: MultiTaskData: If the in_place flag is set to False. """ new_dataset = TaskData() for i, dataset in enumerate(self._datasets): if i != self._default_index: new_dataset.merge(dataset) new_dataset.merge(self.default_dataset) # point all aliases to the new, single dataset new_aliases = {alias: 0 for alias, _ in self._aliases.items()} # replace existing datasets or return a new MultiTaskData object if in_place: self._datasets = [new_dataset] self._aliases = new_aliases self._default_index = 0 else: return MultiTaskData(dataset=new_dataset, aliases=list(new_aliases.keys()))
[ "def", "flatten", "(", "self", ",", "in_place", "=", "True", ")", ":", "new_dataset", "=", "TaskData", "(", ")", "for", "i", ",", "dataset", "in", "enumerate", "(", "self", ".", "_datasets", ")", ":", "if", "i", "!=", "self", ".", "_default_index", "...
Merge all datasets into a single dataset. The default dataset is the last dataset to be merged, as it is considered to be the primary source of information and should overwrite all existing fields with the same key. Args: in_place (bool): Set to ``True`` to replace the existing datasets with the merged one. If set to ``False``, will return a new MultiTaskData object containing the merged dataset. Returns: MultiTaskData: If the in_place flag is set to False.
[ "Merge", "all", "datasets", "into", "a", "single", "dataset", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_data.py#L179-L211
train
AustralianSynchrotron/lightflow
lightflow/models/task_data.py
MultiTaskData.set_default_by_alias
def set_default_by_alias(self, alias): """ Set the default dataset by its alias. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: alias (str): The alias of the dataset that should be made the default. Raises: DataInvalidAlias: If the alias does not represent a valid dataset. """ if alias not in self._aliases: raise DataInvalidAlias('A dataset with alias {} does not exist'.format(alias)) self._default_index = self._aliases[alias]
python
def set_default_by_alias(self, alias): """ Set the default dataset by its alias. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: alias (str): The alias of the dataset that should be made the default. Raises: DataInvalidAlias: If the alias does not represent a valid dataset. """ if alias not in self._aliases: raise DataInvalidAlias('A dataset with alias {} does not exist'.format(alias)) self._default_index = self._aliases[alias]
[ "def", "set_default_by_alias", "(", "self", ",", "alias", ")", ":", "if", "alias", "not", "in", "self", ".", "_aliases", ":", "raise", "DataInvalidAlias", "(", "'A dataset with alias {} does not exist'", ".", "format", "(", "alias", ")", ")", "self", ".", "_de...
Set the default dataset by its alias. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: alias (str): The alias of the dataset that should be made the default. Raises: DataInvalidAlias: If the alias does not represent a valid dataset.
[ "Set", "the", "default", "dataset", "by", "its", "alias", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_data.py#L213-L228
train
AustralianSynchrotron/lightflow
lightflow/models/task_data.py
MultiTaskData.set_default_by_index
def set_default_by_index(self, index): """ Set the default dataset by its index. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: index (int): The index of the dataset that should be made the default. Raises: DataInvalidIndex: If the index does not represent a valid dataset. """ if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) self._default_index = index
python
def set_default_by_index(self, index): """ Set the default dataset by its index. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: index (int): The index of the dataset that should be made the default. Raises: DataInvalidIndex: If the index does not represent a valid dataset. """ if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) self._default_index = index
[ "def", "set_default_by_index", "(", "self", ",", "index", ")", ":", "if", "index", ">=", "len", "(", "self", ".", "_datasets", ")", ":", "raise", "DataInvalidIndex", "(", "'A dataset with index {} does not exist'", ".", "format", "(", "index", ")", ")", "self"...
Set the default dataset by its index. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: index (int): The index of the dataset that should be made the default. Raises: DataInvalidIndex: If the index does not represent a valid dataset.
[ "Set", "the", "default", "dataset", "by", "its", "index", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_data.py#L230-L245
train
AustralianSynchrotron/lightflow
lightflow/models/task_data.py
MultiTaskData.get_by_alias
def get_by_alias(self, alias): """ Return a dataset by its alias. Args: alias (str): The alias of the dataset that should be returned. Raises: DataInvalidAlias: If the alias does not represent a valid dataset. """ if alias not in self._aliases: raise DataInvalidAlias('A dataset with alias {} does not exist'.format(alias)) return self.get_by_index(self._aliases[alias])
python
def get_by_alias(self, alias): """ Return a dataset by its alias. Args: alias (str): The alias of the dataset that should be returned. Raises: DataInvalidAlias: If the alias does not represent a valid dataset. """ if alias not in self._aliases: raise DataInvalidAlias('A dataset with alias {} does not exist'.format(alias)) return self.get_by_index(self._aliases[alias])
[ "def", "get_by_alias", "(", "self", ",", "alias", ")", ":", "if", "alias", "not", "in", "self", ".", "_aliases", ":", "raise", "DataInvalidAlias", "(", "'A dataset with alias {} does not exist'", ".", "format", "(", "alias", ")", ")", "return", "self", ".", ...
Return a dataset by its alias. Args: alias (str): The alias of the dataset that should be returned. Raises: DataInvalidAlias: If the alias does not represent a valid dataset.
[ "Return", "a", "dataset", "by", "its", "alias", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_data.py#L247-L259
train
AustralianSynchrotron/lightflow
lightflow/models/task_data.py
MultiTaskData.get_by_index
def get_by_index(self, index): """ Return a dataset by its index. Args: index (int): The index of the dataset that should be returned. Raises: DataInvalidIndex: If the index does not represent a valid dataset. """ if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) return self._datasets[index]
python
def get_by_index(self, index): """ Return a dataset by its index. Args: index (int): The index of the dataset that should be returned. Raises: DataInvalidIndex: If the index does not represent a valid dataset. """ if index >= len(self._datasets): raise DataInvalidIndex('A dataset with index {} does not exist'.format(index)) return self._datasets[index]
[ "def", "get_by_index", "(", "self", ",", "index", ")", ":", "if", "index", ">=", "len", "(", "self", ".", "_datasets", ")", ":", "raise", "DataInvalidIndex", "(", "'A dataset with index {} does not exist'", ".", "format", "(", "index", ")", ")", "return", "s...
Return a dataset by its index. Args: index (int): The index of the dataset that should be returned. Raises: DataInvalidIndex: If the index does not represent a valid dataset.
[ "Return", "a", "dataset", "by", "its", "index", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_data.py#L261-L273
train
AustralianSynchrotron/lightflow
lightflow/tasks/python_task.py
PythonTask.run
def run(self, data, store, signal, context, **kwargs): """ The main run method of the Python task. Args: data (:class:`.MultiTaskData`): The data object that has been passed from the predecessor task. store (:class:`.DataStoreDocument`): The persistent data store object that allows the task to store data for access across the current workflow run. signal (TaskSignal): The signal object for tasks. It wraps the construction and sending of signals into easy to use methods. context (TaskContext): The context in which the tasks runs. Returns: Action: An Action object containing the data that should be passed on to the next task and optionally a list of successor tasks that should be executed. """ if self._callback is not None: result = self._callback(data, store, signal, context, **kwargs) return result if result is not None else Action(data)
python
def run(self, data, store, signal, context, **kwargs): """ The main run method of the Python task. Args: data (:class:`.MultiTaskData`): The data object that has been passed from the predecessor task. store (:class:`.DataStoreDocument`): The persistent data store object that allows the task to store data for access across the current workflow run. signal (TaskSignal): The signal object for tasks. It wraps the construction and sending of signals into easy to use methods. context (TaskContext): The context in which the tasks runs. Returns: Action: An Action object containing the data that should be passed on to the next task and optionally a list of successor tasks that should be executed. """ if self._callback is not None: result = self._callback(data, store, signal, context, **kwargs) return result if result is not None else Action(data)
[ "def", "run", "(", "self", ",", "data", ",", "store", ",", "signal", ",", "context", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_callback", "is", "not", "None", ":", "result", "=", "self", ".", "_callback", "(", "data", ",", "store", ...
The main run method of the Python task. Args: data (:class:`.MultiTaskData`): The data object that has been passed from the predecessor task. store (:class:`.DataStoreDocument`): The persistent data store object that allows the task to store data for access across the current workflow run. signal (TaskSignal): The signal object for tasks. It wraps the construction and sending of signals into easy to use methods. context (TaskContext): The context in which the tasks runs. Returns: Action: An Action object containing the data that should be passed on to the next task and optionally a list of successor tasks that should be executed.
[ "The", "main", "run", "method", "of", "the", "Python", "task", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/tasks/python_task.py#L80-L99
train
AustralianSynchrotron/lightflow
lightflow/models/task_context.py
TaskContext.to_dict
def to_dict(self): """ Return the task context content as a dictionary. """ return { 'task_name': self.task_name, 'dag_name': self.dag_name, 'workflow_name': self.workflow_name, 'workflow_id': self.workflow_id, 'worker_hostname': self.worker_hostname }
python
def to_dict(self): """ Return the task context content as a dictionary. """ return { 'task_name': self.task_name, 'dag_name': self.dag_name, 'workflow_name': self.workflow_name, 'workflow_id': self.workflow_id, 'worker_hostname': self.worker_hostname }
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "'task_name'", ":", "self", ".", "task_name", ",", "'dag_name'", ":", "self", ".", "dag_name", ",", "'workflow_name'", ":", "self", ".", "workflow_name", ",", "'workflow_id'", ":", "self", ".", "workf...
Return the task context content as a dictionary.
[ "Return", "the", "task", "context", "content", "as", "a", "dictionary", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_context.py#L21-L29
train
AustralianSynchrotron/lightflow
lightflow/workers.py
start_worker
def start_worker(queues, config, *, name=None, celery_args=None, check_datastore=True): """ Start a worker process. Args: queues (list): List of queue names this worker accepts jobs from. config (Config): Reference to the configuration object from which the settings for the worker are retrieved. name (string): Unique name for the worker. The hostname template variables from Celery can be used. If not given, a unique name is created. celery_args (list): List of additional Celery worker command line arguments. Please note that this depends on the version of Celery used and might change. Use with caution. check_datastore (bool): Set to True to check whether the data store is available prior to starting the worker. """ celery_app = create_app(config) if check_datastore: with DataStore(**config.data_store, auto_connect=True, handle_reconnect=False) as ds: celery_app.user_options['datastore_info'] = ds.server_info argv = [ 'worker', '-n={}'.format(uuid4() if name is None else name), '--queues={}'.format(','.join(queues)) ] argv.extend(celery_args or []) celery_app.steps['consumer'].add(WorkerLifecycle) celery_app.user_options['config'] = config celery_app.worker_main(argv)
python
def start_worker(queues, config, *, name=None, celery_args=None, check_datastore=True): """ Start a worker process. Args: queues (list): List of queue names this worker accepts jobs from. config (Config): Reference to the configuration object from which the settings for the worker are retrieved. name (string): Unique name for the worker. The hostname template variables from Celery can be used. If not given, a unique name is created. celery_args (list): List of additional Celery worker command line arguments. Please note that this depends on the version of Celery used and might change. Use with caution. check_datastore (bool): Set to True to check whether the data store is available prior to starting the worker. """ celery_app = create_app(config) if check_datastore: with DataStore(**config.data_store, auto_connect=True, handle_reconnect=False) as ds: celery_app.user_options['datastore_info'] = ds.server_info argv = [ 'worker', '-n={}'.format(uuid4() if name is None else name), '--queues={}'.format(','.join(queues)) ] argv.extend(celery_args or []) celery_app.steps['consumer'].add(WorkerLifecycle) celery_app.user_options['config'] = config celery_app.worker_main(argv)
[ "def", "start_worker", "(", "queues", ",", "config", ",", "*", ",", "name", "=", "None", ",", "celery_args", "=", "None", ",", "check_datastore", "=", "True", ")", ":", "celery_app", "=", "create_app", "(", "config", ")", "if", "check_datastore", ":", "w...
Start a worker process. Args: queues (list): List of queue names this worker accepts jobs from. config (Config): Reference to the configuration object from which the settings for the worker are retrieved. name (string): Unique name for the worker. The hostname template variables from Celery can be used. If not given, a unique name is created. celery_args (list): List of additional Celery worker command line arguments. Please note that this depends on the version of Celery used and might change. Use with caution. check_datastore (bool): Set to True to check whether the data store is available prior to starting the worker.
[ "Start", "a", "worker", "process", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/workers.py#L10-L42
train
AustralianSynchrotron/lightflow
lightflow/workers.py
stop_worker
def stop_worker(config, *, worker_ids=None): """ Stop a worker process. Args: config (Config): Reference to the configuration object from which the settings for the worker are retrieved. worker_ids (list): An optional list of ids for the worker that should be stopped. """ if worker_ids is not None and not isinstance(worker_ids, list): worker_ids = [worker_ids] celery_app = create_app(config) celery_app.control.shutdown(destination=worker_ids)
python
def stop_worker(config, *, worker_ids=None): """ Stop a worker process. Args: config (Config): Reference to the configuration object from which the settings for the worker are retrieved. worker_ids (list): An optional list of ids for the worker that should be stopped. """ if worker_ids is not None and not isinstance(worker_ids, list): worker_ids = [worker_ids] celery_app = create_app(config) celery_app.control.shutdown(destination=worker_ids)
[ "def", "stop_worker", "(", "config", ",", "*", ",", "worker_ids", "=", "None", ")", ":", "if", "worker_ids", "is", "not", "None", "and", "not", "isinstance", "(", "worker_ids", ",", "list", ")", ":", "worker_ids", "=", "[", "worker_ids", "]", "celery_app...
Stop a worker process. Args: config (Config): Reference to the configuration object from which the settings for the worker are retrieved. worker_ids (list): An optional list of ids for the worker that should be stopped.
[ "Stop", "a", "worker", "process", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/workers.py#L45-L57
train
AustralianSynchrotron/lightflow
lightflow/workers.py
list_workers
def list_workers(config, *, filter_by_queues=None): """ Return a list of all available workers. Args: config (Config): Reference to the configuration object from which the settings are retrieved. filter_by_queues (list): Restrict the returned workers to workers that listen to at least one of the queue names in this list. Returns: list: A list of WorkerStats objects. """ celery_app = create_app(config) worker_stats = celery_app.control.inspect().stats() queue_stats = celery_app.control.inspect().active_queues() if worker_stats is None: return [] workers = [] for name, w_stat in worker_stats.items(): queues = [QueueStats.from_celery(q_stat) for q_stat in queue_stats[name]] add_worker = filter_by_queues is None if not add_worker: for queue in queues: if queue.name in filter_by_queues: add_worker = True break if add_worker: workers.append(WorkerStats.from_celery(name, w_stat, queues)) return workers
python
def list_workers(config, *, filter_by_queues=None): """ Return a list of all available workers. Args: config (Config): Reference to the configuration object from which the settings are retrieved. filter_by_queues (list): Restrict the returned workers to workers that listen to at least one of the queue names in this list. Returns: list: A list of WorkerStats objects. """ celery_app = create_app(config) worker_stats = celery_app.control.inspect().stats() queue_stats = celery_app.control.inspect().active_queues() if worker_stats is None: return [] workers = [] for name, w_stat in worker_stats.items(): queues = [QueueStats.from_celery(q_stat) for q_stat in queue_stats[name]] add_worker = filter_by_queues is None if not add_worker: for queue in queues: if queue.name in filter_by_queues: add_worker = True break if add_worker: workers.append(WorkerStats.from_celery(name, w_stat, queues)) return workers
[ "def", "list_workers", "(", "config", ",", "*", ",", "filter_by_queues", "=", "None", ")", ":", "celery_app", "=", "create_app", "(", "config", ")", "worker_stats", "=", "celery_app", ".", "control", ".", "inspect", "(", ")", ".", "stats", "(", ")", "que...
Return a list of all available workers. Args: config (Config): Reference to the configuration object from which the settings are retrieved. filter_by_queues (list): Restrict the returned workers to workers that listen to at least one of the queue names in this list. Returns: list: A list of WorkerStats objects.
[ "Return", "a", "list", "of", "all", "available", "workers", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/workers.py#L60-L93
train
AustralianSynchrotron/lightflow
lightflow/models/task_parameters.py
TaskParameters.eval
def eval(self, data, data_store, *, exclude=None): """ Return a new object in which callable parameters have been evaluated. Native types are not touched and simply returned, while callable methods are executed and their return value is returned. Args: data (MultiTaskData): The data object that has been passed from the predecessor task. data_store (DataStore): The persistent data store object that allows the task to store data for access across the current workflow run. exclude (list): List of key names as strings that should be excluded from the evaluation. Returns: TaskParameters: A new TaskParameters object with the callable parameters replaced by their return value. """ exclude = [] if exclude is None else exclude result = {} for key, value in self.items(): if key in exclude: continue if value is not None and callable(value): result[key] = value(data, data_store) else: result[key] = value return TaskParameters(result)
python
def eval(self, data, data_store, *, exclude=None): """ Return a new object in which callable parameters have been evaluated. Native types are not touched and simply returned, while callable methods are executed and their return value is returned. Args: data (MultiTaskData): The data object that has been passed from the predecessor task. data_store (DataStore): The persistent data store object that allows the task to store data for access across the current workflow run. exclude (list): List of key names as strings that should be excluded from the evaluation. Returns: TaskParameters: A new TaskParameters object with the callable parameters replaced by their return value. """ exclude = [] if exclude is None else exclude result = {} for key, value in self.items(): if key in exclude: continue if value is not None and callable(value): result[key] = value(data, data_store) else: result[key] = value return TaskParameters(result)
[ "def", "eval", "(", "self", ",", "data", ",", "data_store", ",", "*", ",", "exclude", "=", "None", ")", ":", "exclude", "=", "[", "]", "if", "exclude", "is", "None", "else", "exclude", "result", "=", "{", "}", "for", "key", ",", "value", "in", "s...
Return a new object in which callable parameters have been evaluated. Native types are not touched and simply returned, while callable methods are executed and their return value is returned. Args: data (MultiTaskData): The data object that has been passed from the predecessor task. data_store (DataStore): The persistent data store object that allows the task to store data for access across the current workflow run. exclude (list): List of key names as strings that should be excluded from the evaluation. Returns: TaskParameters: A new TaskParameters object with the callable parameters replaced by their return value.
[ "Return", "a", "new", "object", "in", "which", "callable", "parameters", "have", "been", "evaluated", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_parameters.py#L60-L90
train
AustralianSynchrotron/lightflow
lightflow/models/task_parameters.py
TaskParameters.eval_single
def eval_single(self, key, data, data_store): """ Evaluate the value of a single parameter taking into account callables . Native types are not touched and simply returned, while callable methods are executed and their return value is returned. Args: key (str): The name of the parameter that should be evaluated. data (MultiTaskData): The data object that has been passed from the predecessor task. data_store (DataStore): The persistent data store object that allows the task to store data for access across the current workflow run. """ if key in self: value = self[key] if value is not None and callable(value): return value(data, data_store) else: return value else: raise AttributeError()
python
def eval_single(self, key, data, data_store): """ Evaluate the value of a single parameter taking into account callables . Native types are not touched and simply returned, while callable methods are executed and their return value is returned. Args: key (str): The name of the parameter that should be evaluated. data (MultiTaskData): The data object that has been passed from the predecessor task. data_store (DataStore): The persistent data store object that allows the task to store data for access across the current workflow run. """ if key in self: value = self[key] if value is not None and callable(value): return value(data, data_store) else: return value else: raise AttributeError()
[ "def", "eval_single", "(", "self", ",", "key", ",", "data", ",", "data_store", ")", ":", "if", "key", "in", "self", ":", "value", "=", "self", "[", "key", "]", "if", "value", "is", "not", "None", "and", "callable", "(", "value", ")", ":", "return",...
Evaluate the value of a single parameter taking into account callables . Native types are not touched and simply returned, while callable methods are executed and their return value is returned. Args: key (str): The name of the parameter that should be evaluated. data (MultiTaskData): The data object that has been passed from the predecessor task. data_store (DataStore): The persistent data store object that allows the task to store data for access across the current workflow run.
[ "Evaluate", "the", "value", "of", "a", "single", "parameter", "taking", "into", "account", "callables", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task_parameters.py#L92-L114
train
dh1tw/pyhamtools
pyhamtools/qsl.py
get_lotw_users
def get_lotw_users(**kwargs): """Download the latest offical list of `ARRL Logbook of the World (LOTW)`__ users. Args: url (str, optional): Download URL Returns: dict: Dictionary containing the callsign (unicode) date of the last LOTW upload (datetime) Raises: IOError: When network is unavailable, file can't be downloaded or processed ValueError: Raised when data from file can't be read Example: The following example downloads the LOTW user list and check when DH1TW has made his last LOTW upload: >>> from pyhamtools.qsl import get_lotw_users >>> mydict = get_lotw_users() >>> mydict['DH1TW'] datetime.datetime(2014, 9, 7, 0, 0) .. _ARRL: http://www.arrl.org/logbook-of-the-world __ ARRL_ """ url = "" lotw = {} try: url = kwargs['url'] except KeyError: # url = "http://wd5eae.org/LoTW_Data.txt" url = "https://lotw.arrl.org/lotw-user-activity.csv" try: result = requests.get(url) except (ConnectionError, HTTPError, Timeout) as e: raise IOError(e) error_count = 0 if result.status_code == requests.codes.ok: for el in result.text.split(): data = el.split(",") try: lotw[data[0]] = datetime.strptime(data[1], '%Y-%m-%d') except ValueError as e: error_count += 1 if error_count > 10: raise ValueError("more than 10 wrongly formatted datasets " + str(e)) else: raise IOError("HTTP Error: " + str(result.status_code)) return lotw
python
def get_lotw_users(**kwargs): """Download the latest offical list of `ARRL Logbook of the World (LOTW)`__ users. Args: url (str, optional): Download URL Returns: dict: Dictionary containing the callsign (unicode) date of the last LOTW upload (datetime) Raises: IOError: When network is unavailable, file can't be downloaded or processed ValueError: Raised when data from file can't be read Example: The following example downloads the LOTW user list and check when DH1TW has made his last LOTW upload: >>> from pyhamtools.qsl import get_lotw_users >>> mydict = get_lotw_users() >>> mydict['DH1TW'] datetime.datetime(2014, 9, 7, 0, 0) .. _ARRL: http://www.arrl.org/logbook-of-the-world __ ARRL_ """ url = "" lotw = {} try: url = kwargs['url'] except KeyError: # url = "http://wd5eae.org/LoTW_Data.txt" url = "https://lotw.arrl.org/lotw-user-activity.csv" try: result = requests.get(url) except (ConnectionError, HTTPError, Timeout) as e: raise IOError(e) error_count = 0 if result.status_code == requests.codes.ok: for el in result.text.split(): data = el.split(",") try: lotw[data[0]] = datetime.strptime(data[1], '%Y-%m-%d') except ValueError as e: error_count += 1 if error_count > 10: raise ValueError("more than 10 wrongly formatted datasets " + str(e)) else: raise IOError("HTTP Error: " + str(result.status_code)) return lotw
[ "def", "get_lotw_users", "(", "*", "*", "kwargs", ")", ":", "url", "=", "\"\"", "lotw", "=", "{", "}", "try", ":", "url", "=", "kwargs", "[", "'url'", "]", "except", "KeyError", ":", "# url = \"http://wd5eae.org/LoTW_Data.txt\"", "url", "=", "\"https://lotw....
Download the latest offical list of `ARRL Logbook of the World (LOTW)`__ users. Args: url (str, optional): Download URL Returns: dict: Dictionary containing the callsign (unicode) date of the last LOTW upload (datetime) Raises: IOError: When network is unavailable, file can't be downloaded or processed ValueError: Raised when data from file can't be read Example: The following example downloads the LOTW user list and check when DH1TW has made his last LOTW upload: >>> from pyhamtools.qsl import get_lotw_users >>> mydict = get_lotw_users() >>> mydict['DH1TW'] datetime.datetime(2014, 9, 7, 0, 0) .. _ARRL: http://www.arrl.org/logbook-of-the-world __ ARRL_
[ "Download", "the", "latest", "offical", "list", "of", "ARRL", "Logbook", "of", "the", "World", "(", "LOTW", ")", "__", "users", "." ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/qsl.py#L12-L69
train
dh1tw/pyhamtools
pyhamtools/qsl.py
get_clublog_users
def get_clublog_users(**kwargs): """Download the latest offical list of `Clublog`__ users. Args: url (str, optional): Download URL Returns: dict: Dictionary containing (if data available) the fields: firstqso, lastqso, last-lotw, lastupload (datetime), locator (string) and oqrs (boolean) Raises: IOError: When network is unavailable, file can't be downloaded or processed Example: The following example downloads the Clublog user list and returns a dictionary with the data of HC2/AL1O: >>> from pyhamtools.qsl import get_clublog_users >>> clublog = get_lotw_users() >>> clublog['HC2/AL1O'] {'firstqso': datetime.datetime(2012, 1, 1, 19, 59, 27), 'last-lotw': datetime.datetime(2013, 5, 9, 1, 56, 23), 'lastqso': datetime.datetime(2013, 5, 5, 6, 39, 3), 'lastupload': datetime.datetime(2013, 5, 8, 15, 0, 6), 'oqrs': True} .. _CLUBLOG: https://secure.clublog.org __ CLUBLOG_ """ url = "" clublog = {} try: url = kwargs['url'] except KeyError: url = "https://secure.clublog.org/clublog-users.json.zip" try: result = requests.get(url) except (ConnectionError, HTTPError, Timeout) as e: raise IOError(e) if result.status_code != requests.codes.ok: raise IOError("HTTP Error: " + str(result.status_code)) zip_file = zipfile.ZipFile(BytesIO(result.content)) files = zip_file.namelist() cl_json_unzipped = zip_file.read(files[0]).decode('utf8').replace("'", '"') cl_data = json.loads(cl_json_unzipped, encoding='UTF-8') error_count = 0 for call, call_data in iteritems(cl_data): try: data = {} if "firstqso" in call_data: if call_data["firstqso"] != None: data["firstqso"] = datetime.strptime(call_data["firstqso"], '%Y-%m-%d %H:%M:%S') if "lastqso" in call_data: if call_data["lastqso"] != None: data["lastqso"] = datetime.strptime(call_data["lastqso"], '%Y-%m-%d %H:%M:%S') if "last-lotw" in call_data: if call_data["last-lotw"] != None: data["last-lotw"] = datetime.strptime(call_data["last-lotw"], '%Y-%m-%d %H:%M:%S') if "lastupload" in call_data: if call_data["lastupload"] != None: data["lastupload"] = datetime.strptime(call_data["lastupload"], '%Y-%m-%d %H:%M:%S') if "locator" in call_data: if call_data["locator"] != None: data["locator"] = call_data["locator"] if "oqrs" in call_data: if call_data["oqrs"] != None: data["oqrs"] = call_data["oqrs"] clublog[call] = data except TypeError: #some date fields contain null instead of a valid datetime string - we ignore them print("Ignoring invalid type in data:", call, call_data) pass except ValueError: #some date fiels are invalid. we ignore them for the moment print("Ignoring invalid data:", call, call_data) pass return clublog
python
def get_clublog_users(**kwargs): """Download the latest offical list of `Clublog`__ users. Args: url (str, optional): Download URL Returns: dict: Dictionary containing (if data available) the fields: firstqso, lastqso, last-lotw, lastupload (datetime), locator (string) and oqrs (boolean) Raises: IOError: When network is unavailable, file can't be downloaded or processed Example: The following example downloads the Clublog user list and returns a dictionary with the data of HC2/AL1O: >>> from pyhamtools.qsl import get_clublog_users >>> clublog = get_lotw_users() >>> clublog['HC2/AL1O'] {'firstqso': datetime.datetime(2012, 1, 1, 19, 59, 27), 'last-lotw': datetime.datetime(2013, 5, 9, 1, 56, 23), 'lastqso': datetime.datetime(2013, 5, 5, 6, 39, 3), 'lastupload': datetime.datetime(2013, 5, 8, 15, 0, 6), 'oqrs': True} .. _CLUBLOG: https://secure.clublog.org __ CLUBLOG_ """ url = "" clublog = {} try: url = kwargs['url'] except KeyError: url = "https://secure.clublog.org/clublog-users.json.zip" try: result = requests.get(url) except (ConnectionError, HTTPError, Timeout) as e: raise IOError(e) if result.status_code != requests.codes.ok: raise IOError("HTTP Error: " + str(result.status_code)) zip_file = zipfile.ZipFile(BytesIO(result.content)) files = zip_file.namelist() cl_json_unzipped = zip_file.read(files[0]).decode('utf8').replace("'", '"') cl_data = json.loads(cl_json_unzipped, encoding='UTF-8') error_count = 0 for call, call_data in iteritems(cl_data): try: data = {} if "firstqso" in call_data: if call_data["firstqso"] != None: data["firstqso"] = datetime.strptime(call_data["firstqso"], '%Y-%m-%d %H:%M:%S') if "lastqso" in call_data: if call_data["lastqso"] != None: data["lastqso"] = datetime.strptime(call_data["lastqso"], '%Y-%m-%d %H:%M:%S') if "last-lotw" in call_data: if call_data["last-lotw"] != None: data["last-lotw"] = datetime.strptime(call_data["last-lotw"], '%Y-%m-%d %H:%M:%S') if "lastupload" in call_data: if call_data["lastupload"] != None: data["lastupload"] = datetime.strptime(call_data["lastupload"], '%Y-%m-%d %H:%M:%S') if "locator" in call_data: if call_data["locator"] != None: data["locator"] = call_data["locator"] if "oqrs" in call_data: if call_data["oqrs"] != None: data["oqrs"] = call_data["oqrs"] clublog[call] = data except TypeError: #some date fields contain null instead of a valid datetime string - we ignore them print("Ignoring invalid type in data:", call, call_data) pass except ValueError: #some date fiels are invalid. we ignore them for the moment print("Ignoring invalid data:", call, call_data) pass return clublog
[ "def", "get_clublog_users", "(", "*", "*", "kwargs", ")", ":", "url", "=", "\"\"", "clublog", "=", "{", "}", "try", ":", "url", "=", "kwargs", "[", "'url'", "]", "except", "KeyError", ":", "url", "=", "\"https://secure.clublog.org/clublog-users.json.zip\"", ...
Download the latest offical list of `Clublog`__ users. Args: url (str, optional): Download URL Returns: dict: Dictionary containing (if data available) the fields: firstqso, lastqso, last-lotw, lastupload (datetime), locator (string) and oqrs (boolean) Raises: IOError: When network is unavailable, file can't be downloaded or processed Example: The following example downloads the Clublog user list and returns a dictionary with the data of HC2/AL1O: >>> from pyhamtools.qsl import get_clublog_users >>> clublog = get_lotw_users() >>> clublog['HC2/AL1O'] {'firstqso': datetime.datetime(2012, 1, 1, 19, 59, 27), 'last-lotw': datetime.datetime(2013, 5, 9, 1, 56, 23), 'lastqso': datetime.datetime(2013, 5, 5, 6, 39, 3), 'lastupload': datetime.datetime(2013, 5, 8, 15, 0, 6), 'oqrs': True} .. _CLUBLOG: https://secure.clublog.org __ CLUBLOG_
[ "Download", "the", "latest", "offical", "list", "of", "Clublog", "__", "users", "." ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/qsl.py#L71-L157
train
dh1tw/pyhamtools
pyhamtools/qsl.py
get_eqsl_users
def get_eqsl_users(**kwargs): """Download the latest official list of `EQSL.cc`__ users. The list of users can be found here_. Args: url (str, optional): Download URL Returns: list: List containing the callsigns of EQSL users (unicode) Raises: IOError: When network is unavailable, file can't be downloaded or processed Example: The following example downloads the EQSL user list and checks if DH1TW is a user: >>> from pyhamtools.qsl import get_eqsl_users >>> mylist = get_eqsl_users() >>> try: >>> mylist.index('DH1TW') >>> except ValueError as e: >>> print e 'DH1TW' is not in list .. _here: http://www.eqsl.cc/QSLCard/DownloadedFiles/AGMemberlist.txt """ url = "" eqsl = [] try: url = kwargs['url'] except KeyError: url = "http://www.eqsl.cc/QSLCard/DownloadedFiles/AGMemberlist.txt" try: result = requests.get(url) except (ConnectionError, HTTPError, Timeout) as e: raise IOError(e) if result.status_code == requests.codes.ok: eqsl = re.sub("^List.+UTC", "", result.text) eqsl = eqsl.upper().split() else: raise IOError("HTTP Error: " + str(result.status_code)) return eqsl
python
def get_eqsl_users(**kwargs): """Download the latest official list of `EQSL.cc`__ users. The list of users can be found here_. Args: url (str, optional): Download URL Returns: list: List containing the callsigns of EQSL users (unicode) Raises: IOError: When network is unavailable, file can't be downloaded or processed Example: The following example downloads the EQSL user list and checks if DH1TW is a user: >>> from pyhamtools.qsl import get_eqsl_users >>> mylist = get_eqsl_users() >>> try: >>> mylist.index('DH1TW') >>> except ValueError as e: >>> print e 'DH1TW' is not in list .. _here: http://www.eqsl.cc/QSLCard/DownloadedFiles/AGMemberlist.txt """ url = "" eqsl = [] try: url = kwargs['url'] except KeyError: url = "http://www.eqsl.cc/QSLCard/DownloadedFiles/AGMemberlist.txt" try: result = requests.get(url) except (ConnectionError, HTTPError, Timeout) as e: raise IOError(e) if result.status_code == requests.codes.ok: eqsl = re.sub("^List.+UTC", "", result.text) eqsl = eqsl.upper().split() else: raise IOError("HTTP Error: " + str(result.status_code)) return eqsl
[ "def", "get_eqsl_users", "(", "*", "*", "kwargs", ")", ":", "url", "=", "\"\"", "eqsl", "=", "[", "]", "try", ":", "url", "=", "kwargs", "[", "'url'", "]", "except", "KeyError", ":", "url", "=", "\"http://www.eqsl.cc/QSLCard/DownloadedFiles/AGMemberlist.txt\""...
Download the latest official list of `EQSL.cc`__ users. The list of users can be found here_. Args: url (str, optional): Download URL Returns: list: List containing the callsigns of EQSL users (unicode) Raises: IOError: When network is unavailable, file can't be downloaded or processed Example: The following example downloads the EQSL user list and checks if DH1TW is a user: >>> from pyhamtools.qsl import get_eqsl_users >>> mylist = get_eqsl_users() >>> try: >>> mylist.index('DH1TW') >>> except ValueError as e: >>> print e 'DH1TW' is not in list .. _here: http://www.eqsl.cc/QSLCard/DownloadedFiles/AGMemberlist.txt
[ "Download", "the", "latest", "official", "list", "of", "EQSL", ".", "cc", "__", "users", ".", "The", "list", "of", "users", "can", "be", "found", "here_", "." ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/qsl.py#L159-L206
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib.copy_data_in_redis
def copy_data_in_redis(self, redis_prefix, redis_instance): """ Copy the complete lookup data into redis. Old data will be overwritten. Args: redis_prefix (str): Prefix to distinguish the data in redis for the different looktypes redis_instance (str): an Instance of Redis Returns: bool: returns True when the data has been copied successfully into Redis Example: Copy the entire lookup data from the Country-files.com PLIST File into Redis. This example requires a running instance of Redis, as well the python Redis connector (pip install redis-py). >>> from pyhamtools import LookupLib >>> import redis >>> r = redis.Redis() >>> my_lookuplib = LookupLib(lookuptype="countryfile") >>> print my_lookuplib.copy_data_in_redis(redis_prefix="CF", redis_instance=r) True Now let's create an instance of LookupLib, using Redis to query the data >>> from pyhamtools import LookupLib >>> import redis >>> r = redis.Redis() >>> my_lookuplib = LookupLib(lookuptype="countryfile", redis_instance=r, redis_prefix="CF") >>> my_lookuplib.lookup_callsign("3D2RI") { u'adif': 460, u'continent': u'OC', u'country': u'Rotuma Island', u'cqz': 32, u'ituz': 56, u'latitude': -12.48, u'longitude': 177.08 } Note: This method is available for the following lookup type - clublogxml - countryfile """ if redis_instance is not None: self._redis = redis_instance if self._redis is None: raise AttributeError("redis_instance is missing") if redis_prefix is None: raise KeyError("redis_prefix is missing") if self._lookuptype == "clublogxml" or self._lookuptype == "countryfile": self._push_dict_to_redis(self._entities, redis_prefix, "_entity_") self._push_dict_index_to_redis(self._callsign_exceptions_index, redis_prefix, "_call_ex_index_") self._push_dict_to_redis(self._callsign_exceptions, redis_prefix, "_call_ex_") self._push_dict_index_to_redis(self._prefixes_index, redis_prefix, "_prefix_index_") self._push_dict_to_redis(self._prefixes, redis_prefix, "_prefix_") self._push_dict_index_to_redis(self._invalid_operations_index, redis_prefix, "_inv_op_index_") self._push_dict_to_redis(self._invalid_operations, redis_prefix, "_inv_op_") self._push_dict_index_to_redis(self._zone_exceptions_index, redis_prefix, "_zone_ex_index_") self._push_dict_to_redis(self._zone_exceptions, redis_prefix, "_zone_ex_") return True
python
def copy_data_in_redis(self, redis_prefix, redis_instance): """ Copy the complete lookup data into redis. Old data will be overwritten. Args: redis_prefix (str): Prefix to distinguish the data in redis for the different looktypes redis_instance (str): an Instance of Redis Returns: bool: returns True when the data has been copied successfully into Redis Example: Copy the entire lookup data from the Country-files.com PLIST File into Redis. This example requires a running instance of Redis, as well the python Redis connector (pip install redis-py). >>> from pyhamtools import LookupLib >>> import redis >>> r = redis.Redis() >>> my_lookuplib = LookupLib(lookuptype="countryfile") >>> print my_lookuplib.copy_data_in_redis(redis_prefix="CF", redis_instance=r) True Now let's create an instance of LookupLib, using Redis to query the data >>> from pyhamtools import LookupLib >>> import redis >>> r = redis.Redis() >>> my_lookuplib = LookupLib(lookuptype="countryfile", redis_instance=r, redis_prefix="CF") >>> my_lookuplib.lookup_callsign("3D2RI") { u'adif': 460, u'continent': u'OC', u'country': u'Rotuma Island', u'cqz': 32, u'ituz': 56, u'latitude': -12.48, u'longitude': 177.08 } Note: This method is available for the following lookup type - clublogxml - countryfile """ if redis_instance is not None: self._redis = redis_instance if self._redis is None: raise AttributeError("redis_instance is missing") if redis_prefix is None: raise KeyError("redis_prefix is missing") if self._lookuptype == "clublogxml" or self._lookuptype == "countryfile": self._push_dict_to_redis(self._entities, redis_prefix, "_entity_") self._push_dict_index_to_redis(self._callsign_exceptions_index, redis_prefix, "_call_ex_index_") self._push_dict_to_redis(self._callsign_exceptions, redis_prefix, "_call_ex_") self._push_dict_index_to_redis(self._prefixes_index, redis_prefix, "_prefix_index_") self._push_dict_to_redis(self._prefixes, redis_prefix, "_prefix_") self._push_dict_index_to_redis(self._invalid_operations_index, redis_prefix, "_inv_op_index_") self._push_dict_to_redis(self._invalid_operations, redis_prefix, "_inv_op_") self._push_dict_index_to_redis(self._zone_exceptions_index, redis_prefix, "_zone_ex_index_") self._push_dict_to_redis(self._zone_exceptions, redis_prefix, "_zone_ex_") return True
[ "def", "copy_data_in_redis", "(", "self", ",", "redis_prefix", ",", "redis_instance", ")", ":", "if", "redis_instance", "is", "not", "None", ":", "self", ".", "_redis", "=", "redis_instance", "if", "self", ".", "_redis", "is", "None", ":", "raise", "Attribut...
Copy the complete lookup data into redis. Old data will be overwritten. Args: redis_prefix (str): Prefix to distinguish the data in redis for the different looktypes redis_instance (str): an Instance of Redis Returns: bool: returns True when the data has been copied successfully into Redis Example: Copy the entire lookup data from the Country-files.com PLIST File into Redis. This example requires a running instance of Redis, as well the python Redis connector (pip install redis-py). >>> from pyhamtools import LookupLib >>> import redis >>> r = redis.Redis() >>> my_lookuplib = LookupLib(lookuptype="countryfile") >>> print my_lookuplib.copy_data_in_redis(redis_prefix="CF", redis_instance=r) True Now let's create an instance of LookupLib, using Redis to query the data >>> from pyhamtools import LookupLib >>> import redis >>> r = redis.Redis() >>> my_lookuplib = LookupLib(lookuptype="countryfile", redis_instance=r, redis_prefix="CF") >>> my_lookuplib.lookup_callsign("3D2RI") { u'adif': 460, u'continent': u'OC', u'country': u'Rotuma Island', u'cqz': 32, u'ituz': 56, u'latitude': -12.48, u'longitude': 177.08 } Note: This method is available for the following lookup type - clublogxml - countryfile
[ "Copy", "the", "complete", "lookup", "data", "into", "redis", ".", "Old", "data", "will", "be", "overwritten", "." ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L151-L223
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib.lookup_entity
def lookup_entity(self, entity=None): """Returns lookup data of an ADIF Entity Args: entity (int): ADIF identifier of country Returns: dict: Dictionary containing the country specific data Raises: KeyError: No matching entity found Example: The following code queries the the Clublog XML database for the ADIF entity Turkmenistan, which has the id 273. >>> from pyhamtools import LookupLib >>> my_lookuplib = LookupLib(lookuptype="clublogapi", apikey="myapikey") >>> print my_lookuplib.lookup_entity(273) { 'deleted': False, 'country': u'TURKMENISTAN', 'longitude': 58.4, 'cqz': 17, 'prefix': u'EZ', 'latitude': 38.0, 'continent': u'AS' } Note: This method is available for the following lookup type - clublogxml - redis - qrz.com """ if self._lookuptype == "clublogxml": entity = int(entity) if entity in self._entities: return self._strip_metadata(self._entities[entity]) else: raise KeyError elif self._lookuptype == "redis": if self._redis_prefix is None: raise KeyError ("redis_prefix is missing") #entity = str(entity) json_data = self._redis.get(self._redis_prefix + "_entity_" + str(entity)) if json_data is not None: my_dict = self._deserialize_data(json_data) return self._strip_metadata(my_dict) elif self._lookuptype == "qrz": result = self._lookup_qrz_dxcc(entity, self._apikey) return result # no matching case raise KeyError
python
def lookup_entity(self, entity=None): """Returns lookup data of an ADIF Entity Args: entity (int): ADIF identifier of country Returns: dict: Dictionary containing the country specific data Raises: KeyError: No matching entity found Example: The following code queries the the Clublog XML database for the ADIF entity Turkmenistan, which has the id 273. >>> from pyhamtools import LookupLib >>> my_lookuplib = LookupLib(lookuptype="clublogapi", apikey="myapikey") >>> print my_lookuplib.lookup_entity(273) { 'deleted': False, 'country': u'TURKMENISTAN', 'longitude': 58.4, 'cqz': 17, 'prefix': u'EZ', 'latitude': 38.0, 'continent': u'AS' } Note: This method is available for the following lookup type - clublogxml - redis - qrz.com """ if self._lookuptype == "clublogxml": entity = int(entity) if entity in self._entities: return self._strip_metadata(self._entities[entity]) else: raise KeyError elif self._lookuptype == "redis": if self._redis_prefix is None: raise KeyError ("redis_prefix is missing") #entity = str(entity) json_data = self._redis.get(self._redis_prefix + "_entity_" + str(entity)) if json_data is not None: my_dict = self._deserialize_data(json_data) return self._strip_metadata(my_dict) elif self._lookuptype == "qrz": result = self._lookup_qrz_dxcc(entity, self._apikey) return result # no matching case raise KeyError
[ "def", "lookup_entity", "(", "self", ",", "entity", "=", "None", ")", ":", "if", "self", ".", "_lookuptype", "==", "\"clublogxml\"", ":", "entity", "=", "int", "(", "entity", ")", "if", "entity", "in", "self", ".", "_entities", ":", "return", "self", "...
Returns lookup data of an ADIF Entity Args: entity (int): ADIF identifier of country Returns: dict: Dictionary containing the country specific data Raises: KeyError: No matching entity found Example: The following code queries the the Clublog XML database for the ADIF entity Turkmenistan, which has the id 273. >>> from pyhamtools import LookupLib >>> my_lookuplib = LookupLib(lookuptype="clublogapi", apikey="myapikey") >>> print my_lookuplib.lookup_entity(273) { 'deleted': False, 'country': u'TURKMENISTAN', 'longitude': 58.4, 'cqz': 17, 'prefix': u'EZ', 'latitude': 38.0, 'continent': u'AS' } Note: This method is available for the following lookup type - clublogxml - redis - qrz.com
[ "Returns", "lookup", "data", "of", "an", "ADIF", "Entity" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L243-L302
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._strip_metadata
def _strip_metadata(self, my_dict): """ Create a copy of dict and remove not needed data """ new_dict = copy.deepcopy(my_dict) if const.START in new_dict: del new_dict[const.START] if const.END in new_dict: del new_dict[const.END] if const.WHITELIST in new_dict: del new_dict[const.WHITELIST] if const.WHITELIST_START in new_dict: del new_dict[const.WHITELIST_START] if const.WHITELIST_END in new_dict: del new_dict[const.WHITELIST_END] return new_dict
python
def _strip_metadata(self, my_dict): """ Create a copy of dict and remove not needed data """ new_dict = copy.deepcopy(my_dict) if const.START in new_dict: del new_dict[const.START] if const.END in new_dict: del new_dict[const.END] if const.WHITELIST in new_dict: del new_dict[const.WHITELIST] if const.WHITELIST_START in new_dict: del new_dict[const.WHITELIST_START] if const.WHITELIST_END in new_dict: del new_dict[const.WHITELIST_END] return new_dict
[ "def", "_strip_metadata", "(", "self", ",", "my_dict", ")", ":", "new_dict", "=", "copy", ".", "deepcopy", "(", "my_dict", ")", "if", "const", ".", "START", "in", "new_dict", ":", "del", "new_dict", "[", "const", ".", "START", "]", "if", "const", ".", ...
Create a copy of dict and remove not needed data
[ "Create", "a", "copy", "of", "dict", "and", "remove", "not", "needed", "data" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L304-L319
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib.lookup_callsign
def lookup_callsign(self, callsign=None, timestamp=timestamp_now): """ Returns lookup data if an exception exists for a callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary containing the country specific data of the callsign Raises: KeyError: No matching callsign found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code queries the the online Clublog API for the callsign "VK9XO" on a specific date. >>> from pyhamtools import LookupLib >>> from datetime import datetime >>> import pytz >>> my_lookuplib = LookupLib(lookuptype="clublogapi", apikey="myapikey") >>> timestamp = datetime(year=1962, month=7, day=7, tzinfo=pytz.UTC) >>> print my_lookuplib.lookup_callsign("VK9XO", timestamp) { 'country': u'CHRISTMAS ISLAND', 'longitude': 105.7, 'cqz': 29, 'adif': 35, 'latitude': -10.5, 'continent': u'OC' } Note: This method is available for - clublogxml - clublogapi - countryfile - qrz.com - redis """ callsign = callsign.strip().upper() if self._lookuptype == "clublogapi": callsign_data = self._lookup_clublogAPI(callsign=callsign, timestamp=timestamp, apikey=self._apikey) if callsign_data[const.ADIF]==1000: raise KeyError else: return callsign_data elif self._lookuptype == "clublogxml" or self._lookuptype == "countryfile": return self._check_data_for_date(callsign, timestamp, self._callsign_exceptions, self._callsign_exceptions_index) elif self._lookuptype == "redis": data_dict, index = self._get_dicts_from_redis("_call_ex_", "_call_ex_index_", self._redis_prefix, callsign) return self._check_data_for_date(callsign, timestamp, data_dict, index) # no matching case elif self._lookuptype == "qrz": return self._lookup_qrz_callsign(callsign, self._apikey, self._apiv) raise KeyError("unknown Callsign")
python
def lookup_callsign(self, callsign=None, timestamp=timestamp_now): """ Returns lookup data if an exception exists for a callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary containing the country specific data of the callsign Raises: KeyError: No matching callsign found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code queries the the online Clublog API for the callsign "VK9XO" on a specific date. >>> from pyhamtools import LookupLib >>> from datetime import datetime >>> import pytz >>> my_lookuplib = LookupLib(lookuptype="clublogapi", apikey="myapikey") >>> timestamp = datetime(year=1962, month=7, day=7, tzinfo=pytz.UTC) >>> print my_lookuplib.lookup_callsign("VK9XO", timestamp) { 'country': u'CHRISTMAS ISLAND', 'longitude': 105.7, 'cqz': 29, 'adif': 35, 'latitude': -10.5, 'continent': u'OC' } Note: This method is available for - clublogxml - clublogapi - countryfile - qrz.com - redis """ callsign = callsign.strip().upper() if self._lookuptype == "clublogapi": callsign_data = self._lookup_clublogAPI(callsign=callsign, timestamp=timestamp, apikey=self._apikey) if callsign_data[const.ADIF]==1000: raise KeyError else: return callsign_data elif self._lookuptype == "clublogxml" or self._lookuptype == "countryfile": return self._check_data_for_date(callsign, timestamp, self._callsign_exceptions, self._callsign_exceptions_index) elif self._lookuptype == "redis": data_dict, index = self._get_dicts_from_redis("_call_ex_", "_call_ex_index_", self._redis_prefix, callsign) return self._check_data_for_date(callsign, timestamp, data_dict, index) # no matching case elif self._lookuptype == "qrz": return self._lookup_qrz_callsign(callsign, self._apikey, self._apiv) raise KeyError("unknown Callsign")
[ "def", "lookup_callsign", "(", "self", ",", "callsign", "=", "None", ",", "timestamp", "=", "timestamp_now", ")", ":", "callsign", "=", "callsign", ".", "strip", "(", ")", ".", "upper", "(", ")", "if", "self", ".", "_lookuptype", "==", "\"clublogapi\"", ...
Returns lookup data if an exception exists for a callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary containing the country specific data of the callsign Raises: KeyError: No matching callsign found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code queries the the online Clublog API for the callsign "VK9XO" on a specific date. >>> from pyhamtools import LookupLib >>> from datetime import datetime >>> import pytz >>> my_lookuplib = LookupLib(lookuptype="clublogapi", apikey="myapikey") >>> timestamp = datetime(year=1962, month=7, day=7, tzinfo=pytz.UTC) >>> print my_lookuplib.lookup_callsign("VK9XO", timestamp) { 'country': u'CHRISTMAS ISLAND', 'longitude': 105.7, 'cqz': 29, 'adif': 35, 'latitude': -10.5, 'continent': u'OC' } Note: This method is available for - clublogxml - clublogapi - countryfile - qrz.com - redis
[ "Returns", "lookup", "data", "if", "an", "exception", "exists", "for", "a", "callsign" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L322-L388
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._get_dicts_from_redis
def _get_dicts_from_redis(self, name, index_name, redis_prefix, item): """ Retrieve the data of an item from redis and put it in an index and data dictionary to match the common query interface. """ r = self._redis data_dict = {} data_index_dict = {} if redis_prefix is None: raise KeyError ("redis_prefix is missing") if r.scard(redis_prefix + index_name + str(item)) > 0: data_index_dict[str(item)] = r.smembers(redis_prefix + index_name + str(item)) for i in data_index_dict[item]: json_data = r.get(redis_prefix + name + str(int(i))) data_dict[i] = self._deserialize_data(json_data) return (data_dict, data_index_dict) raise KeyError ("No Data found in Redis for "+ item)
python
def _get_dicts_from_redis(self, name, index_name, redis_prefix, item): """ Retrieve the data of an item from redis and put it in an index and data dictionary to match the common query interface. """ r = self._redis data_dict = {} data_index_dict = {} if redis_prefix is None: raise KeyError ("redis_prefix is missing") if r.scard(redis_prefix + index_name + str(item)) > 0: data_index_dict[str(item)] = r.smembers(redis_prefix + index_name + str(item)) for i in data_index_dict[item]: json_data = r.get(redis_prefix + name + str(int(i))) data_dict[i] = self._deserialize_data(json_data) return (data_dict, data_index_dict) raise KeyError ("No Data found in Redis for "+ item)
[ "def", "_get_dicts_from_redis", "(", "self", ",", "name", ",", "index_name", ",", "redis_prefix", ",", "item", ")", ":", "r", "=", "self", ".", "_redis", "data_dict", "=", "{", "}", "data_index_dict", "=", "{", "}", "if", "redis_prefix", "is", "None", ":...
Retrieve the data of an item from redis and put it in an index and data dictionary to match the common query interface.
[ "Retrieve", "the", "data", "of", "an", "item", "from", "redis", "and", "put", "it", "in", "an", "index", "and", "data", "dictionary", "to", "match", "the", "common", "query", "interface", "." ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L390-L411
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._check_data_for_date
def _check_data_for_date(self, item, timestamp, data_dict, data_index_dict): """ Checks if the item is found in the index. An entry in the index points to the data in the data_dict. This is mainly used retrieve callsigns and prefixes. In case data is found for item, a dict containing the data is returned. Otherwise a KeyError is raised. """ if item in data_index_dict: for item in data_index_dict[item]: # startdate < timestamp if const.START in data_dict[item] and not const.END in data_dict[item]: if data_dict[item][const.START] < timestamp: item_data = copy.deepcopy(data_dict[item]) del item_data[const.START] return item_data # enddate > timestamp elif not const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.END] > timestamp: item_data = copy.deepcopy(data_dict[item]) del item_data[const.END] return item_data # startdate > timestamp > enddate elif const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.START] < timestamp \ and data_dict[item][const.END] > timestamp: item_data = copy.deepcopy(data_dict[item]) del item_data[const.START] del item_data[const.END] return item_data # no startdate or enddate available elif not const.START in data_dict[item] and not const.END in data_dict[item]: return data_dict[item] raise KeyError
python
def _check_data_for_date(self, item, timestamp, data_dict, data_index_dict): """ Checks if the item is found in the index. An entry in the index points to the data in the data_dict. This is mainly used retrieve callsigns and prefixes. In case data is found for item, a dict containing the data is returned. Otherwise a KeyError is raised. """ if item in data_index_dict: for item in data_index_dict[item]: # startdate < timestamp if const.START in data_dict[item] and not const.END in data_dict[item]: if data_dict[item][const.START] < timestamp: item_data = copy.deepcopy(data_dict[item]) del item_data[const.START] return item_data # enddate > timestamp elif not const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.END] > timestamp: item_data = copy.deepcopy(data_dict[item]) del item_data[const.END] return item_data # startdate > timestamp > enddate elif const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.START] < timestamp \ and data_dict[item][const.END] > timestamp: item_data = copy.deepcopy(data_dict[item]) del item_data[const.START] del item_data[const.END] return item_data # no startdate or enddate available elif not const.START in data_dict[item] and not const.END in data_dict[item]: return data_dict[item] raise KeyError
[ "def", "_check_data_for_date", "(", "self", ",", "item", ",", "timestamp", ",", "data_dict", ",", "data_index_dict", ")", ":", "if", "item", "in", "data_index_dict", ":", "for", "item", "in", "data_index_dict", "[", "item", "]", ":", "# startdate < timestamp", ...
Checks if the item is found in the index. An entry in the index points to the data in the data_dict. This is mainly used retrieve callsigns and prefixes. In case data is found for item, a dict containing the data is returned. Otherwise a KeyError is raised.
[ "Checks", "if", "the", "item", "is", "found", "in", "the", "index", ".", "An", "entry", "in", "the", "index", "points", "to", "the", "data", "in", "the", "data_dict", ".", "This", "is", "mainly", "used", "retrieve", "callsigns", "and", "prefixes", ".", ...
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L413-L450
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._check_inv_operation_for_date
def _check_inv_operation_for_date(self, item, timestamp, data_dict, data_index_dict): """ Checks if the callsign is marked as an invalid operation for a given timestamp. In case the operation is invalid, True is returned. Otherwise a KeyError is raised. """ if item in data_index_dict: for item in data_index_dict[item]: # startdate < timestamp if const.START in data_dict[item] and not const.END in data_dict[item]: if data_dict[item][const.START] < timestamp: return True # enddate > timestamp elif not const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.END] > timestamp: return True # startdate > timestamp > enddate elif const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.START] < timestamp \ and data_dict[item][const.END] > timestamp: return True # no startdate or enddate available elif not const.START in data_dict[item] and not const.END in data_dict[item]: return True raise KeyError
python
def _check_inv_operation_for_date(self, item, timestamp, data_dict, data_index_dict): """ Checks if the callsign is marked as an invalid operation for a given timestamp. In case the operation is invalid, True is returned. Otherwise a KeyError is raised. """ if item in data_index_dict: for item in data_index_dict[item]: # startdate < timestamp if const.START in data_dict[item] and not const.END in data_dict[item]: if data_dict[item][const.START] < timestamp: return True # enddate > timestamp elif not const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.END] > timestamp: return True # startdate > timestamp > enddate elif const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.START] < timestamp \ and data_dict[item][const.END] > timestamp: return True # no startdate or enddate available elif not const.START in data_dict[item] and not const.END in data_dict[item]: return True raise KeyError
[ "def", "_check_inv_operation_for_date", "(", "self", ",", "item", ",", "timestamp", ",", "data_dict", ",", "data_index_dict", ")", ":", "if", "item", "in", "data_index_dict", ":", "for", "item", "in", "data_index_dict", "[", "item", "]", ":", "# startdate < time...
Checks if the callsign is marked as an invalid operation for a given timestamp. In case the operation is invalid, True is returned. Otherwise a KeyError is raised.
[ "Checks", "if", "the", "callsign", "is", "marked", "as", "an", "invalid", "operation", "for", "a", "given", "timestamp", ".", "In", "case", "the", "operation", "is", "invalid", "True", "is", "returned", ".", "Otherwise", "a", "KeyError", "is", "raised", "....
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L453-L482
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib.lookup_prefix
def lookup_prefix(self, prefix, timestamp=timestamp_now): """ Returns lookup data of a Prefix Args: prefix (string): Prefix of a Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary containing the country specific data of the Prefix Raises: KeyError: No matching Prefix found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code shows how to obtain the information for the prefix "DH" from the countryfile.com database (default database). >>> from pyhamtools import LookupLib >>> myLookupLib = LookupLib() >>> print myLookupLib.lookup_prefix("DH") { 'adif': 230, 'country': u'Fed. Rep. of Germany', 'longitude': 10.0, 'cqz': 14, 'ituz': 28, 'latitude': 51.0, 'continent': u'EU' } Note: This method is available for - clublogxml - countryfile - redis """ prefix = prefix.strip().upper() if self._lookuptype == "clublogxml" or self._lookuptype == "countryfile": return self._check_data_for_date(prefix, timestamp, self._prefixes, self._prefixes_index) elif self._lookuptype == "redis": data_dict, index = self._get_dicts_from_redis("_prefix_", "_prefix_index_", self._redis_prefix, prefix) return self._check_data_for_date(prefix, timestamp, data_dict, index) # no matching case raise KeyError
python
def lookup_prefix(self, prefix, timestamp=timestamp_now): """ Returns lookup data of a Prefix Args: prefix (string): Prefix of a Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary containing the country specific data of the Prefix Raises: KeyError: No matching Prefix found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code shows how to obtain the information for the prefix "DH" from the countryfile.com database (default database). >>> from pyhamtools import LookupLib >>> myLookupLib = LookupLib() >>> print myLookupLib.lookup_prefix("DH") { 'adif': 230, 'country': u'Fed. Rep. of Germany', 'longitude': 10.0, 'cqz': 14, 'ituz': 28, 'latitude': 51.0, 'continent': u'EU' } Note: This method is available for - clublogxml - countryfile - redis """ prefix = prefix.strip().upper() if self._lookuptype == "clublogxml" or self._lookuptype == "countryfile": return self._check_data_for_date(prefix, timestamp, self._prefixes, self._prefixes_index) elif self._lookuptype == "redis": data_dict, index = self._get_dicts_from_redis("_prefix_", "_prefix_index_", self._redis_prefix, prefix) return self._check_data_for_date(prefix, timestamp, data_dict, index) # no matching case raise KeyError
[ "def", "lookup_prefix", "(", "self", ",", "prefix", ",", "timestamp", "=", "timestamp_now", ")", ":", "prefix", "=", "prefix", ".", "strip", "(", ")", ".", "upper", "(", ")", "if", "self", ".", "_lookuptype", "==", "\"clublogxml\"", "or", "self", ".", ...
Returns lookup data of a Prefix Args: prefix (string): Prefix of a Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary containing the country specific data of the Prefix Raises: KeyError: No matching Prefix found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code shows how to obtain the information for the prefix "DH" from the countryfile.com database (default database). >>> from pyhamtools import LookupLib >>> myLookupLib = LookupLib() >>> print myLookupLib.lookup_prefix("DH") { 'adif': 230, 'country': u'Fed. Rep. of Germany', 'longitude': 10.0, 'cqz': 14, 'ituz': 28, 'latitude': 51.0, 'continent': u'EU' } Note: This method is available for - clublogxml - countryfile - redis
[ "Returns", "lookup", "data", "of", "a", "Prefix" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L485-L538
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib.is_invalid_operation
def is_invalid_operation(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)): """ Returns True if an operations is known as invalid Args: callsign (string): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: bool: True if a record exists for this callsign (at the given time) Raises: KeyError: No matching callsign found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code checks the Clublog XML database if the operation is valid for two dates. >>> from pyhamtools import LookupLib >>> from datetime import datetime >>> import pytz >>> my_lookuplib = LookupLib(lookuptype="clublogxml", apikey="myapikey") >>> print my_lookuplib.is_invalid_operation("5W1CFN") True >>> try: >>> timestamp = datetime(year=2012, month=1, day=31).replace(tzinfo=pytz.UTC) >>> my_lookuplib.is_invalid_operation("5W1CFN", timestamp) >>> except KeyError: >>> print "Seems to be invalid operation before 31.1.2012" Seems to be an invalid operation before 31.1.2012 Note: This method is available for - clublogxml - redis """ callsign = callsign.strip().upper() if self._lookuptype == "clublogxml": return self._check_inv_operation_for_date(callsign, timestamp, self._invalid_operations, self._invalid_operations_index) elif self._lookuptype == "redis": data_dict, index = self._get_dicts_from_redis("_inv_op_", "_inv_op_index_", self._redis_prefix, callsign) return self._check_inv_operation_for_date(callsign, timestamp, data_dict, index) #no matching case raise KeyError
python
def is_invalid_operation(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)): """ Returns True if an operations is known as invalid Args: callsign (string): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: bool: True if a record exists for this callsign (at the given time) Raises: KeyError: No matching callsign found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code checks the Clublog XML database if the operation is valid for two dates. >>> from pyhamtools import LookupLib >>> from datetime import datetime >>> import pytz >>> my_lookuplib = LookupLib(lookuptype="clublogxml", apikey="myapikey") >>> print my_lookuplib.is_invalid_operation("5W1CFN") True >>> try: >>> timestamp = datetime(year=2012, month=1, day=31).replace(tzinfo=pytz.UTC) >>> my_lookuplib.is_invalid_operation("5W1CFN", timestamp) >>> except KeyError: >>> print "Seems to be invalid operation before 31.1.2012" Seems to be an invalid operation before 31.1.2012 Note: This method is available for - clublogxml - redis """ callsign = callsign.strip().upper() if self._lookuptype == "clublogxml": return self._check_inv_operation_for_date(callsign, timestamp, self._invalid_operations, self._invalid_operations_index) elif self._lookuptype == "redis": data_dict, index = self._get_dicts_from_redis("_inv_op_", "_inv_op_index_", self._redis_prefix, callsign) return self._check_inv_operation_for_date(callsign, timestamp, data_dict, index) #no matching case raise KeyError
[ "def", "is_invalid_operation", "(", "self", ",", "callsign", ",", "timestamp", "=", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo", "=", "UTC", ")", ")", ":", "callsign", "=", "callsign", ".", "strip", "(", ")", ".", "upper", "(", ...
Returns True if an operations is known as invalid Args: callsign (string): Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: bool: True if a record exists for this callsign (at the given time) Raises: KeyError: No matching callsign found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code checks the Clublog XML database if the operation is valid for two dates. >>> from pyhamtools import LookupLib >>> from datetime import datetime >>> import pytz >>> my_lookuplib = LookupLib(lookuptype="clublogxml", apikey="myapikey") >>> print my_lookuplib.is_invalid_operation("5W1CFN") True >>> try: >>> timestamp = datetime(year=2012, month=1, day=31).replace(tzinfo=pytz.UTC) >>> my_lookuplib.is_invalid_operation("5W1CFN", timestamp) >>> except KeyError: >>> print "Seems to be invalid operation before 31.1.2012" Seems to be an invalid operation before 31.1.2012 Note: This method is available for - clublogxml - redis
[ "Returns", "True", "if", "an", "operations", "is", "known", "as", "invalid" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L540-L591
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._check_zone_exception_for_date
def _check_zone_exception_for_date(self, item, timestamp, data_dict, data_index_dict): """ Checks the index and data if a cq-zone exception exists for the callsign When a zone exception is found, the zone is returned. If no exception is found a KeyError is raised """ if item in data_index_dict: for item in data_index_dict[item]: # startdate < timestamp if const.START in data_dict[item] and not const.END in data_dict[item]: if data_dict[item][const.START] < timestamp: return data_dict[item][const.CQZ] # enddate > timestamp elif not const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.END] > timestamp: return data_dict[item][const.CQZ] # startdate > timestamp > enddate elif const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.START] < timestamp \ and data_dict[item][const.END] > timestamp: return data_dict[item][const.CQZ] # no startdate or enddate available elif not const.START in data_dict[item] and not const.END in data_dict[item]: return data_dict[item][const.CQZ] raise KeyError
python
def _check_zone_exception_for_date(self, item, timestamp, data_dict, data_index_dict): """ Checks the index and data if a cq-zone exception exists for the callsign When a zone exception is found, the zone is returned. If no exception is found a KeyError is raised """ if item in data_index_dict: for item in data_index_dict[item]: # startdate < timestamp if const.START in data_dict[item] and not const.END in data_dict[item]: if data_dict[item][const.START] < timestamp: return data_dict[item][const.CQZ] # enddate > timestamp elif not const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.END] > timestamp: return data_dict[item][const.CQZ] # startdate > timestamp > enddate elif const.START in data_dict[item] and const.END in data_dict[item]: if data_dict[item][const.START] < timestamp \ and data_dict[item][const.END] > timestamp: return data_dict[item][const.CQZ] # no startdate or enddate available elif not const.START in data_dict[item] and not const.END in data_dict[item]: return data_dict[item][const.CQZ] raise KeyError
[ "def", "_check_zone_exception_for_date", "(", "self", ",", "item", ",", "timestamp", ",", "data_dict", ",", "data_index_dict", ")", ":", "if", "item", "in", "data_index_dict", ":", "for", "item", "in", "data_index_dict", "[", "item", "]", ":", "# startdate < tim...
Checks the index and data if a cq-zone exception exists for the callsign When a zone exception is found, the zone is returned. If no exception is found a KeyError is raised
[ "Checks", "the", "index", "and", "data", "if", "a", "cq", "-", "zone", "exception", "exists", "for", "the", "callsign", "When", "a", "zone", "exception", "is", "found", "the", "zone", "is", "returned", ".", "If", "no", "exception", "is", "found", "a", ...
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L594-L624
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib.lookup_zone_exception
def lookup_zone_exception(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)): """ Returns a CQ Zone if an exception exists for the given callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: int: Value of the the CQ Zone exception which exists for this callsign (at the given time) Raises: KeyError: No matching callsign found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code checks the Clublog XML database if a CQ Zone exception exists for the callsign DP0GVN. >>> from pyhamtools import LookupLib >>> my_lookuplib = LookupLib(lookuptype="clublogxml", apikey="myapikey") >>> print my_lookuplib.lookup_zone_exception("DP0GVN") 38 The prefix "DP" It is assigned to Germany, but the station is located in Antarctica, and therefore in CQ Zone 38 Note: This method is available for - clublogxml - redis """ callsign = callsign.strip().upper() if self._lookuptype == "clublogxml": return self._check_zone_exception_for_date(callsign, timestamp, self._zone_exceptions, self._zone_exceptions_index) elif self._lookuptype == "redis": data_dict, index = self._get_dicts_from_redis("_zone_ex_", "_zone_ex_index_", self._redis_prefix, callsign) return self._check_zone_exception_for_date(callsign, timestamp, data_dict, index) #no matching case raise KeyError
python
def lookup_zone_exception(self, callsign, timestamp=datetime.utcnow().replace(tzinfo=UTC)): """ Returns a CQ Zone if an exception exists for the given callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: int: Value of the the CQ Zone exception which exists for this callsign (at the given time) Raises: KeyError: No matching callsign found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code checks the Clublog XML database if a CQ Zone exception exists for the callsign DP0GVN. >>> from pyhamtools import LookupLib >>> my_lookuplib = LookupLib(lookuptype="clublogxml", apikey="myapikey") >>> print my_lookuplib.lookup_zone_exception("DP0GVN") 38 The prefix "DP" It is assigned to Germany, but the station is located in Antarctica, and therefore in CQ Zone 38 Note: This method is available for - clublogxml - redis """ callsign = callsign.strip().upper() if self._lookuptype == "clublogxml": return self._check_zone_exception_for_date(callsign, timestamp, self._zone_exceptions, self._zone_exceptions_index) elif self._lookuptype == "redis": data_dict, index = self._get_dicts_from_redis("_zone_ex_", "_zone_ex_index_", self._redis_prefix, callsign) return self._check_zone_exception_for_date(callsign, timestamp, data_dict, index) #no matching case raise KeyError
[ "def", "lookup_zone_exception", "(", "self", ",", "callsign", ",", "timestamp", "=", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo", "=", "UTC", ")", ")", ":", "callsign", "=", "callsign", ".", "strip", "(", ")", ".", "upper", "(", ...
Returns a CQ Zone if an exception exists for the given callsign Args: callsign (string): Amateur radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: int: Value of the the CQ Zone exception which exists for this callsign (at the given time) Raises: KeyError: No matching callsign found APIKeyMissingError: API Key for Clublog missing or incorrect Example: The following code checks the Clublog XML database if a CQ Zone exception exists for the callsign DP0GVN. >>> from pyhamtools import LookupLib >>> my_lookuplib = LookupLib(lookuptype="clublogxml", apikey="myapikey") >>> print my_lookuplib.lookup_zone_exception("DP0GVN") 38 The prefix "DP" It is assigned to Germany, but the station is located in Antarctica, and therefore in CQ Zone 38 Note: This method is available for - clublogxml - redis
[ "Returns", "a", "CQ", "Zone", "if", "an", "exception", "exists", "for", "the", "given", "callsign" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L627-L673
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._lookup_clublogAPI
def _lookup_clublogAPI(self, callsign=None, timestamp=timestamp_now, url="https://secure.clublog.org/dxcc", apikey=None): """ Set up the Lookup object for Clublog Online API """ params = {"year" : timestamp.strftime("%Y"), "month" : timestamp.strftime("%m"), "day" : timestamp.strftime("%d"), "hour" : timestamp.strftime("%H"), "minute" : timestamp.strftime("%M"), "api" : apikey, "full" : "1", "call" : callsign } if sys.version_info.major == 3: encodeurl = url + "?" + urllib.parse.urlencode(params) else: encodeurl = url + "?" + urllib.urlencode(params) response = requests.get(encodeurl, timeout=5) if not self._check_html_response(response): raise LookupError jsonLookup = response.json() lookup = {} for item in jsonLookup: if item == "Name": lookup[const.COUNTRY] = jsonLookup["Name"] elif item == "DXCC": lookup[const.ADIF] = int(jsonLookup["DXCC"]) elif item == "Lon": lookup[const.LONGITUDE] = float(jsonLookup["Lon"])*(-1) elif item == "Lat": lookup[const.LATITUDE] = float(jsonLookup["Lat"]) elif item == "CQZ": lookup[const.CQZ] = int(jsonLookup["CQZ"]) elif item == "Continent": lookup[const.CONTINENT] = jsonLookup["Continent"] if lookup[const.ADIF] == 0: raise KeyError else: return lookup
python
def _lookup_clublogAPI(self, callsign=None, timestamp=timestamp_now, url="https://secure.clublog.org/dxcc", apikey=None): """ Set up the Lookup object for Clublog Online API """ params = {"year" : timestamp.strftime("%Y"), "month" : timestamp.strftime("%m"), "day" : timestamp.strftime("%d"), "hour" : timestamp.strftime("%H"), "minute" : timestamp.strftime("%M"), "api" : apikey, "full" : "1", "call" : callsign } if sys.version_info.major == 3: encodeurl = url + "?" + urllib.parse.urlencode(params) else: encodeurl = url + "?" + urllib.urlencode(params) response = requests.get(encodeurl, timeout=5) if not self._check_html_response(response): raise LookupError jsonLookup = response.json() lookup = {} for item in jsonLookup: if item == "Name": lookup[const.COUNTRY] = jsonLookup["Name"] elif item == "DXCC": lookup[const.ADIF] = int(jsonLookup["DXCC"]) elif item == "Lon": lookup[const.LONGITUDE] = float(jsonLookup["Lon"])*(-1) elif item == "Lat": lookup[const.LATITUDE] = float(jsonLookup["Lat"]) elif item == "CQZ": lookup[const.CQZ] = int(jsonLookup["CQZ"]) elif item == "Continent": lookup[const.CONTINENT] = jsonLookup["Continent"] if lookup[const.ADIF] == 0: raise KeyError else: return lookup
[ "def", "_lookup_clublogAPI", "(", "self", ",", "callsign", "=", "None", ",", "timestamp", "=", "timestamp_now", ",", "url", "=", "\"https://secure.clublog.org/dxcc\"", ",", "apikey", "=", "None", ")", ":", "params", "=", "{", "\"year\"", ":", "timestamp", ".",...
Set up the Lookup object for Clublog Online API
[ "Set", "up", "the", "Lookup", "object", "for", "Clublog", "Online", "API" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L675-L712
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._lookup_qrz_dxcc
def _lookup_qrz_dxcc(self, dxcc_or_callsign, apikey, apiv="1.3.3"): """ Performs the dxcc lookup against the QRZ.com XML API: """ response = self._request_dxcc_info_from_qrz(dxcc_or_callsign, apikey, apiv=apiv) root = BeautifulSoup(response.text, "html.parser") lookup = {} if root.error: #try to get a new session key and try to request again if re.search('No DXCC Information for', root.error.text, re.I): #No data available for callsign raise KeyError(root.error.text) elif re.search('Session Timeout', root.error.text, re.I): # Get new session key self._apikey = apikey = self._get_qrz_session_key(self._username, self._pwd) response = self._request_dxcc_info_from_qrz(dxcc_or_callsign, apikey) root = BeautifulSoup(response.text, "html.parser") else: raise AttributeError("Session Key Missing") #most likely session key missing or invalid if root.dxcc is None: raise ValueError if root.dxcc.dxcc: lookup[const.ADIF] = int(root.dxcc.dxcc.text) if root.dxcc.cc: lookup['cc'] = root.dxcc.cc.text if root.dxcc.cc: lookup['ccc'] = root.dxcc.ccc.text if root.find('name'): lookup[const.COUNTRY] = root.find('name').get_text() if root.dxcc.continent: lookup[const.CONTINENT] = root.dxcc.continent.text if root.dxcc.ituzone: lookup[const.ITUZ] = int(root.dxcc.ituzone.text) if root.dxcc.cqzone: lookup[const.CQZ] = int(root.dxcc.cqzone.text) if root.dxcc.timezone: lookup['timezone'] = float(root.dxcc.timezone.text) if root.dxcc.lat: lookup[const.LATITUDE] = float(root.dxcc.lat.text) if root.dxcc.lon: lookup[const.LONGITUDE] = float(root.dxcc.lon.text) return lookup
python
def _lookup_qrz_dxcc(self, dxcc_or_callsign, apikey, apiv="1.3.3"): """ Performs the dxcc lookup against the QRZ.com XML API: """ response = self._request_dxcc_info_from_qrz(dxcc_or_callsign, apikey, apiv=apiv) root = BeautifulSoup(response.text, "html.parser") lookup = {} if root.error: #try to get a new session key and try to request again if re.search('No DXCC Information for', root.error.text, re.I): #No data available for callsign raise KeyError(root.error.text) elif re.search('Session Timeout', root.error.text, re.I): # Get new session key self._apikey = apikey = self._get_qrz_session_key(self._username, self._pwd) response = self._request_dxcc_info_from_qrz(dxcc_or_callsign, apikey) root = BeautifulSoup(response.text, "html.parser") else: raise AttributeError("Session Key Missing") #most likely session key missing or invalid if root.dxcc is None: raise ValueError if root.dxcc.dxcc: lookup[const.ADIF] = int(root.dxcc.dxcc.text) if root.dxcc.cc: lookup['cc'] = root.dxcc.cc.text if root.dxcc.cc: lookup['ccc'] = root.dxcc.ccc.text if root.find('name'): lookup[const.COUNTRY] = root.find('name').get_text() if root.dxcc.continent: lookup[const.CONTINENT] = root.dxcc.continent.text if root.dxcc.ituzone: lookup[const.ITUZ] = int(root.dxcc.ituzone.text) if root.dxcc.cqzone: lookup[const.CQZ] = int(root.dxcc.cqzone.text) if root.dxcc.timezone: lookup['timezone'] = float(root.dxcc.timezone.text) if root.dxcc.lat: lookup[const.LATITUDE] = float(root.dxcc.lat.text) if root.dxcc.lon: lookup[const.LONGITUDE] = float(root.dxcc.lon.text) return lookup
[ "def", "_lookup_qrz_dxcc", "(", "self", ",", "dxcc_or_callsign", ",", "apikey", ",", "apiv", "=", "\"1.3.3\"", ")", ":", "response", "=", "self", ".", "_request_dxcc_info_from_qrz", "(", "dxcc_or_callsign", ",", "apikey", ",", "apiv", "=", "apiv", ")", "root",...
Performs the dxcc lookup against the QRZ.com XML API:
[ "Performs", "the", "dxcc", "lookup", "against", "the", "QRZ", ".", "com", "XML", "API", ":" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L746-L790
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._lookup_qrz_callsign
def _lookup_qrz_callsign(self, callsign=None, apikey=None, apiv="1.3.3"): """ Performs the callsign lookup against the QRZ.com XML API: """ if apikey is None: raise AttributeError("Session Key Missing") callsign = callsign.upper() response = self._request_callsign_info_from_qrz(callsign, apikey, apiv) root = BeautifulSoup(response.text, "html.parser") lookup = {} if root.error: if re.search('Not found', root.error.text, re.I): #No data available for callsign raise KeyError(root.error.text) #try to get a new session key and try to request again elif re.search('Session Timeout', root.error.text, re.I) or re.search('Invalid session key', root.error.text, re.I): apikey = self._get_qrz_session_key(self._username, self._pwd) response = self._request_callsign_info_from_qrz(callsign, apikey, apiv) root = BeautifulSoup(response.text, "html.parser") #if this fails again, raise error if root.error: if re.search('Not found', root.error.text, re.I): #No data available for callsign raise KeyError(root.error.text) else: raise AttributeError(root.error.text) #most likely session key invalid else: #update API Key ob Lookup object self._apikey = apikey else: raise AttributeError(root.error.text) #most likely session key missing if root.callsign is None: raise ValueError if root.callsign.call: lookup[const.CALLSIGN] = root.callsign.call.text if root.callsign.xref: lookup[const.XREF] = root.callsign.xref.text if root.callsign.aliases: lookup[const.ALIASES] = root.callsign.aliases.text.split(',') if root.callsign.dxcc: lookup[const.ADIF] = int(root.callsign.dxcc.text) if root.callsign.fname: lookup[const.FNAME] = root.callsign.fname.text if root.callsign.find("name"): lookup[const.NAME] = root.callsign.find('name').get_text() if root.callsign.addr1: lookup[const.ADDR1] = root.callsign.addr1.text if root.callsign.addr2: lookup[const.ADDR2] = root.callsign.addr2.text if root.callsign.state: lookup[const.STATE] = root.callsign.state.text if root.callsign.zip: lookup[const.ZIPCODE] = root.callsign.zip.text if root.callsign.country: lookup[const.COUNTRY] = root.callsign.country.text if root.callsign.ccode: lookup[const.CCODE] = int(root.callsign.ccode.text) if root.callsign.lat: lookup[const.LATITUDE] = float(root.callsign.lat.text) if root.callsign.lon: lookup[const.LONGITUDE] = float(root.callsign.lon.text) if root.callsign.grid: lookup[const.LOCATOR] = root.callsign.grid.text if root.callsign.county: lookup[const.COUNTY] = root.callsign.county.text if root.callsign.fips: lookup[const.FIPS] = int(root.callsign.fips.text) # check type if root.callsign.land: lookup[const.LAND] = root.callsign.land.text if root.callsign.efdate: try: lookup[const.EFDATE] = datetime.strptime(root.callsign.efdate.text, '%Y-%m-%d').replace(tzinfo=UTC) except ValueError: self._logger.debug("[QRZ.com] efdate: Invalid DateTime; " + callsign + " " + root.callsign.efdate.text) if root.callsign.expdate: try: lookup[const.EXPDATE] = datetime.strptime(root.callsign.expdate.text, '%Y-%m-%d').replace(tzinfo=UTC) except ValueError: self._logger.debug("[QRZ.com] expdate: Invalid DateTime; " + callsign + " " + root.callsign.expdate.text) if root.callsign.p_call: lookup[const.P_CALL] = root.callsign.p_call.text if root.callsign.find('class'): lookup[const.LICENSE_CLASS] = root.callsign.find('class').get_text() if root.callsign.codes: lookup[const.CODES] = root.callsign.codes.text if root.callsign.qslmgr: lookup[const.QSLMGR] = root.callsign.qslmgr.text if root.callsign.email: lookup[const.EMAIL] = root.callsign.email.text if root.callsign.url: lookup[const.URL] = root.callsign.url.text if root.callsign.u_views: lookup[const.U_VIEWS] = int(root.callsign.u_views.text) if root.callsign.bio: lookup[const.BIO] = root.callsign.bio.text if root.callsign.biodate: try: lookup[const.BIODATE] = datetime.strptime(root.callsign.biodate.text, '%Y-%m-%d %H:%M:%S').replace(tzinfo=UTC) except ValueError: self._logger.warning("[QRZ.com] biodate: Invalid DateTime; " + callsign) if root.callsign.image: lookup[const.IMAGE] = root.callsign.image.text if root.callsign.imageinfo: lookup[const.IMAGE_INFO] = root.callsign.imageinfo.text if root.callsign.serial: lookup[const.SERIAL] = long(root.callsign.serial.text) if root.callsign.moddate: try: lookup[const.MODDATE] = datetime.strptime(root.callsign.moddate.text, '%Y-%m-%d %H:%M:%S').replace(tzinfo=UTC) except ValueError: self._logger.warning("[QRZ.com] moddate: Invalid DateTime; " + callsign) if root.callsign.MSA: lookup[const.MSA] = int(root.callsign.MSA.text) if root.callsign.AreaCode: lookup[const.AREACODE] = int(root.callsign.AreaCode.text) if root.callsign.TimeZone: lookup[const.TIMEZONE] = int(root.callsign.TimeZone.text) if root.callsign.GMTOffset: lookup[const.GMTOFFSET] = float(root.callsign.GMTOffset.text) if root.callsign.DST: if root.callsign.DST.text == "Y": lookup[const.DST] = True else: lookup[const.DST] = False if root.callsign.eqsl: if root.callsign.eqsl.text == "1": lookup[const.EQSL] = True else: lookup[const.EQSL] = False if root.callsign.mqsl: if root.callsign.mqsl.text == "1": lookup[const.MQSL] = True else: lookup[const.MQSL] = False if root.callsign.cqzone: lookup[const.CQZ] = int(root.callsign.cqzone.text) if root.callsign.ituzone: lookup[const.ITUZ] = int(root.callsign.ituzone.text) if root.callsign.born: lookup[const.BORN] = int(root.callsign.born.text) if root.callsign.user: lookup[const.USER_MGR] = root.callsign.user.text if root.callsign.lotw: if root.callsign.lotw.text == "1": lookup[const.LOTW] = True else: lookup[const.LOTW] = False if root.callsign.iota: lookup[const.IOTA] = root.callsign.iota.text if root.callsign.geoloc: lookup[const.GEOLOC] = root.callsign.geoloc.text # if sys.version_info >= (2,): # for item in lookup: # if isinstance(lookup[item], unicode): # print item, repr(lookup[item]) return lookup
python
def _lookup_qrz_callsign(self, callsign=None, apikey=None, apiv="1.3.3"): """ Performs the callsign lookup against the QRZ.com XML API: """ if apikey is None: raise AttributeError("Session Key Missing") callsign = callsign.upper() response = self._request_callsign_info_from_qrz(callsign, apikey, apiv) root = BeautifulSoup(response.text, "html.parser") lookup = {} if root.error: if re.search('Not found', root.error.text, re.I): #No data available for callsign raise KeyError(root.error.text) #try to get a new session key and try to request again elif re.search('Session Timeout', root.error.text, re.I) or re.search('Invalid session key', root.error.text, re.I): apikey = self._get_qrz_session_key(self._username, self._pwd) response = self._request_callsign_info_from_qrz(callsign, apikey, apiv) root = BeautifulSoup(response.text, "html.parser") #if this fails again, raise error if root.error: if re.search('Not found', root.error.text, re.I): #No data available for callsign raise KeyError(root.error.text) else: raise AttributeError(root.error.text) #most likely session key invalid else: #update API Key ob Lookup object self._apikey = apikey else: raise AttributeError(root.error.text) #most likely session key missing if root.callsign is None: raise ValueError if root.callsign.call: lookup[const.CALLSIGN] = root.callsign.call.text if root.callsign.xref: lookup[const.XREF] = root.callsign.xref.text if root.callsign.aliases: lookup[const.ALIASES] = root.callsign.aliases.text.split(',') if root.callsign.dxcc: lookup[const.ADIF] = int(root.callsign.dxcc.text) if root.callsign.fname: lookup[const.FNAME] = root.callsign.fname.text if root.callsign.find("name"): lookup[const.NAME] = root.callsign.find('name').get_text() if root.callsign.addr1: lookup[const.ADDR1] = root.callsign.addr1.text if root.callsign.addr2: lookup[const.ADDR2] = root.callsign.addr2.text if root.callsign.state: lookup[const.STATE] = root.callsign.state.text if root.callsign.zip: lookup[const.ZIPCODE] = root.callsign.zip.text if root.callsign.country: lookup[const.COUNTRY] = root.callsign.country.text if root.callsign.ccode: lookup[const.CCODE] = int(root.callsign.ccode.text) if root.callsign.lat: lookup[const.LATITUDE] = float(root.callsign.lat.text) if root.callsign.lon: lookup[const.LONGITUDE] = float(root.callsign.lon.text) if root.callsign.grid: lookup[const.LOCATOR] = root.callsign.grid.text if root.callsign.county: lookup[const.COUNTY] = root.callsign.county.text if root.callsign.fips: lookup[const.FIPS] = int(root.callsign.fips.text) # check type if root.callsign.land: lookup[const.LAND] = root.callsign.land.text if root.callsign.efdate: try: lookup[const.EFDATE] = datetime.strptime(root.callsign.efdate.text, '%Y-%m-%d').replace(tzinfo=UTC) except ValueError: self._logger.debug("[QRZ.com] efdate: Invalid DateTime; " + callsign + " " + root.callsign.efdate.text) if root.callsign.expdate: try: lookup[const.EXPDATE] = datetime.strptime(root.callsign.expdate.text, '%Y-%m-%d').replace(tzinfo=UTC) except ValueError: self._logger.debug("[QRZ.com] expdate: Invalid DateTime; " + callsign + " " + root.callsign.expdate.text) if root.callsign.p_call: lookup[const.P_CALL] = root.callsign.p_call.text if root.callsign.find('class'): lookup[const.LICENSE_CLASS] = root.callsign.find('class').get_text() if root.callsign.codes: lookup[const.CODES] = root.callsign.codes.text if root.callsign.qslmgr: lookup[const.QSLMGR] = root.callsign.qslmgr.text if root.callsign.email: lookup[const.EMAIL] = root.callsign.email.text if root.callsign.url: lookup[const.URL] = root.callsign.url.text if root.callsign.u_views: lookup[const.U_VIEWS] = int(root.callsign.u_views.text) if root.callsign.bio: lookup[const.BIO] = root.callsign.bio.text if root.callsign.biodate: try: lookup[const.BIODATE] = datetime.strptime(root.callsign.biodate.text, '%Y-%m-%d %H:%M:%S').replace(tzinfo=UTC) except ValueError: self._logger.warning("[QRZ.com] biodate: Invalid DateTime; " + callsign) if root.callsign.image: lookup[const.IMAGE] = root.callsign.image.text if root.callsign.imageinfo: lookup[const.IMAGE_INFO] = root.callsign.imageinfo.text if root.callsign.serial: lookup[const.SERIAL] = long(root.callsign.serial.text) if root.callsign.moddate: try: lookup[const.MODDATE] = datetime.strptime(root.callsign.moddate.text, '%Y-%m-%d %H:%M:%S').replace(tzinfo=UTC) except ValueError: self._logger.warning("[QRZ.com] moddate: Invalid DateTime; " + callsign) if root.callsign.MSA: lookup[const.MSA] = int(root.callsign.MSA.text) if root.callsign.AreaCode: lookup[const.AREACODE] = int(root.callsign.AreaCode.text) if root.callsign.TimeZone: lookup[const.TIMEZONE] = int(root.callsign.TimeZone.text) if root.callsign.GMTOffset: lookup[const.GMTOFFSET] = float(root.callsign.GMTOffset.text) if root.callsign.DST: if root.callsign.DST.text == "Y": lookup[const.DST] = True else: lookup[const.DST] = False if root.callsign.eqsl: if root.callsign.eqsl.text == "1": lookup[const.EQSL] = True else: lookup[const.EQSL] = False if root.callsign.mqsl: if root.callsign.mqsl.text == "1": lookup[const.MQSL] = True else: lookup[const.MQSL] = False if root.callsign.cqzone: lookup[const.CQZ] = int(root.callsign.cqzone.text) if root.callsign.ituzone: lookup[const.ITUZ] = int(root.callsign.ituzone.text) if root.callsign.born: lookup[const.BORN] = int(root.callsign.born.text) if root.callsign.user: lookup[const.USER_MGR] = root.callsign.user.text if root.callsign.lotw: if root.callsign.lotw.text == "1": lookup[const.LOTW] = True else: lookup[const.LOTW] = False if root.callsign.iota: lookup[const.IOTA] = root.callsign.iota.text if root.callsign.geoloc: lookup[const.GEOLOC] = root.callsign.geoloc.text # if sys.version_info >= (2,): # for item in lookup: # if isinstance(lookup[item], unicode): # print item, repr(lookup[item]) return lookup
[ "def", "_lookup_qrz_callsign", "(", "self", ",", "callsign", "=", "None", ",", "apikey", "=", "None", ",", "apiv", "=", "\"1.3.3\"", ")", ":", "if", "apikey", "is", "None", ":", "raise", "AttributeError", "(", "\"Session Key Missing\"", ")", "callsign", "=",...
Performs the callsign lookup against the QRZ.com XML API:
[ "Performs", "the", "callsign", "lookup", "against", "the", "QRZ", ".", "com", "XML", "API", ":" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L793-L958
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._load_clublogXML
def _load_clublogXML(self, url="https://secure.clublog.org/cty.php", apikey=None, cty_file=None): """ Load and process the ClublogXML file either as a download or from file """ if self._download: cty_file = self._download_file( url = url, apikey = apikey) else: cty_file = self._lib_filename header = self._extract_clublog_header(cty_file) cty_file = self._remove_clublog_xml_header(cty_file) cty_dict = self._parse_clublog_xml(cty_file) self._entities = cty_dict["entities"] self._callsign_exceptions = cty_dict["call_exceptions"] self._prefixes = cty_dict["prefixes"] self._invalid_operations = cty_dict["invalid_operations"] self._zone_exceptions = cty_dict["zone_exceptions"] self._callsign_exceptions_index = cty_dict["call_exceptions_index"] self._prefixes_index = cty_dict["prefixes_index"] self._invalid_operations_index = cty_dict["invalid_operations_index"] self._zone_exceptions_index = cty_dict["zone_exceptions_index"] return True
python
def _load_clublogXML(self, url="https://secure.clublog.org/cty.php", apikey=None, cty_file=None): """ Load and process the ClublogXML file either as a download or from file """ if self._download: cty_file = self._download_file( url = url, apikey = apikey) else: cty_file = self._lib_filename header = self._extract_clublog_header(cty_file) cty_file = self._remove_clublog_xml_header(cty_file) cty_dict = self._parse_clublog_xml(cty_file) self._entities = cty_dict["entities"] self._callsign_exceptions = cty_dict["call_exceptions"] self._prefixes = cty_dict["prefixes"] self._invalid_operations = cty_dict["invalid_operations"] self._zone_exceptions = cty_dict["zone_exceptions"] self._callsign_exceptions_index = cty_dict["call_exceptions_index"] self._prefixes_index = cty_dict["prefixes_index"] self._invalid_operations_index = cty_dict["invalid_operations_index"] self._zone_exceptions_index = cty_dict["zone_exceptions_index"] return True
[ "def", "_load_clublogXML", "(", "self", ",", "url", "=", "\"https://secure.clublog.org/cty.php\"", ",", "apikey", "=", "None", ",", "cty_file", "=", "None", ")", ":", "if", "self", ".", "_download", ":", "cty_file", "=", "self", ".", "_download_file", "(", "...
Load and process the ClublogXML file either as a download or from file
[ "Load", "and", "process", "the", "ClublogXML", "file", "either", "as", "a", "download", "or", "from", "file" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L960-L989
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._load_countryfile
def _load_countryfile(self, url="https://www.country-files.com/cty/cty.plist", country_mapping_filename="countryfilemapping.json", cty_file=None): """ Load and process the ClublogXML file either as a download or from file """ cwdFile = os.path.abspath(os.path.join(os.getcwd(), country_mapping_filename)) pkgFile = os.path.abspath(os.path.join(os.path.dirname(__file__), country_mapping_filename)) # from cwd if os.path.exists(cwdFile): # country mapping files contains the ADIF identifiers of a particular # country since the country-files do not provide this information (only DXCC id) country_mapping_filename = cwdFile # from package elif os.path.exists(pkgFile): country_mapping_filename = pkgFile else: country_mapping_filename = None if self._download: cty_file = self._download_file(url=url) else: cty_file = os.path.abspath(cty_file) cty_dict = self._parse_country_file(cty_file, country_mapping_filename) self._callsign_exceptions = cty_dict["exceptions"] self._prefixes = cty_dict["prefixes"] self._callsign_exceptions_index = cty_dict["exceptions_index"] self._prefixes_index = cty_dict["prefixes_index"] return True
python
def _load_countryfile(self, url="https://www.country-files.com/cty/cty.plist", country_mapping_filename="countryfilemapping.json", cty_file=None): """ Load and process the ClublogXML file either as a download or from file """ cwdFile = os.path.abspath(os.path.join(os.getcwd(), country_mapping_filename)) pkgFile = os.path.abspath(os.path.join(os.path.dirname(__file__), country_mapping_filename)) # from cwd if os.path.exists(cwdFile): # country mapping files contains the ADIF identifiers of a particular # country since the country-files do not provide this information (only DXCC id) country_mapping_filename = cwdFile # from package elif os.path.exists(pkgFile): country_mapping_filename = pkgFile else: country_mapping_filename = None if self._download: cty_file = self._download_file(url=url) else: cty_file = os.path.abspath(cty_file) cty_dict = self._parse_country_file(cty_file, country_mapping_filename) self._callsign_exceptions = cty_dict["exceptions"] self._prefixes = cty_dict["prefixes"] self._callsign_exceptions_index = cty_dict["exceptions_index"] self._prefixes_index = cty_dict["prefixes_index"] return True
[ "def", "_load_countryfile", "(", "self", ",", "url", "=", "\"https://www.country-files.com/cty/cty.plist\"", ",", "country_mapping_filename", "=", "\"countryfilemapping.json\"", ",", "cty_file", "=", "None", ")", ":", "cwdFile", "=", "os", ".", "path", ".", "abspath",...
Load and process the ClublogXML file either as a download or from file
[ "Load", "and", "process", "the", "ClublogXML", "file", "either", "as", "a", "download", "or", "from", "file" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L991-L1023
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._download_file
def _download_file(self, url, apikey=None): """ Download lookup files either from Clublog or Country-files.com """ import gzip import tempfile cty = {} cty_date = "" cty_file_path = None filename = None # download file if apikey: # clublog response = requests.get(url+"?api="+apikey, timeout=10) else: # country-files.com response = requests.get(url, timeout=10) if not self._check_html_response(response): raise LookupError #Clublog Webserver Header if "Content-Disposition" in response.headers: f = re.search('filename=".+"', response.headers["Content-Disposition"]) if f: f = f.group(0) filename = re.search('".+"', f).group(0).replace('"', '') #Country-files.org webserver header else: f = re.search('/.{4}plist$', url) if f: f = f.group(0) filename = f[1:] if not filename: filename = "cty_" + self._generate_random_word(5) download_file_path = os.path.join(tempfile.gettempdir(), filename) with open(download_file_path, "wb") as download_file: download_file.write(response.content) self._logger.debug(str(download_file_path) + " successfully downloaded") # unzip file, if gz if os.path.splitext(download_file_path)[1][1:] == "gz": download_file = gzip.open(download_file_path, "r") try: cty_file_path = os.path.join(os.path.splitext(download_file_path)[0]) with open(cty_file_path, "wb") as cty_file: cty_file.write(download_file.read()) self._logger.debug(str(cty_file_path) + " successfully extracted") finally: download_file.close() else: cty_file_path = download_file_path return cty_file_path
python
def _download_file(self, url, apikey=None): """ Download lookup files either from Clublog or Country-files.com """ import gzip import tempfile cty = {} cty_date = "" cty_file_path = None filename = None # download file if apikey: # clublog response = requests.get(url+"?api="+apikey, timeout=10) else: # country-files.com response = requests.get(url, timeout=10) if not self._check_html_response(response): raise LookupError #Clublog Webserver Header if "Content-Disposition" in response.headers: f = re.search('filename=".+"', response.headers["Content-Disposition"]) if f: f = f.group(0) filename = re.search('".+"', f).group(0).replace('"', '') #Country-files.org webserver header else: f = re.search('/.{4}plist$', url) if f: f = f.group(0) filename = f[1:] if not filename: filename = "cty_" + self._generate_random_word(5) download_file_path = os.path.join(tempfile.gettempdir(), filename) with open(download_file_path, "wb") as download_file: download_file.write(response.content) self._logger.debug(str(download_file_path) + " successfully downloaded") # unzip file, if gz if os.path.splitext(download_file_path)[1][1:] == "gz": download_file = gzip.open(download_file_path, "r") try: cty_file_path = os.path.join(os.path.splitext(download_file_path)[0]) with open(cty_file_path, "wb") as cty_file: cty_file.write(download_file.read()) self._logger.debug(str(cty_file_path) + " successfully extracted") finally: download_file.close() else: cty_file_path = download_file_path return cty_file_path
[ "def", "_download_file", "(", "self", ",", "url", ",", "apikey", "=", "None", ")", ":", "import", "gzip", "import", "tempfile", "cty", "=", "{", "}", "cty_date", "=", "\"\"", "cty_file_path", "=", "None", "filename", "=", "None", "# download file", "if", ...
Download lookup files either from Clublog or Country-files.com
[ "Download", "lookup", "files", "either", "from", "Clublog", "or", "Country", "-", "files", ".", "com" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L1025-L1082
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._extract_clublog_header
def _extract_clublog_header(self, cty_xml_filename): """ Extract the header of the Clublog XML File """ cty_header = {} try: with open(cty_xml_filename, "r") as cty: raw_header = cty.readline() cty_date = re.search("date='.+'", raw_header) if cty_date: cty_date = cty_date.group(0).replace("date=", "").replace("'", "") cty_date = datetime.strptime(cty_date[:19], '%Y-%m-%dT%H:%M:%S') cty_date.replace(tzinfo=UTC) cty_header["Date"] = cty_date cty_ns = re.search("xmlns='.+[']", raw_header) if cty_ns: cty_ns = cty_ns.group(0).replace("xmlns=", "").replace("'", "") cty_header['NameSpace'] = cty_ns if len(cty_header) == 2: self._logger.debug("Header successfully retrieved from CTY File") elif len(cty_header) < 2: self._logger.warning("Header could only be partically retrieved from CTY File") self._logger.warning("Content of Header: ") for key in cty_header: self._logger.warning(str(key)+": "+str(cty_header[key])) return cty_header except Exception as e: self._logger.error("Clublog CTY File could not be opened / modified") self._logger.error("Error Message: " + str(e)) return
python
def _extract_clublog_header(self, cty_xml_filename): """ Extract the header of the Clublog XML File """ cty_header = {} try: with open(cty_xml_filename, "r") as cty: raw_header = cty.readline() cty_date = re.search("date='.+'", raw_header) if cty_date: cty_date = cty_date.group(0).replace("date=", "").replace("'", "") cty_date = datetime.strptime(cty_date[:19], '%Y-%m-%dT%H:%M:%S') cty_date.replace(tzinfo=UTC) cty_header["Date"] = cty_date cty_ns = re.search("xmlns='.+[']", raw_header) if cty_ns: cty_ns = cty_ns.group(0).replace("xmlns=", "").replace("'", "") cty_header['NameSpace'] = cty_ns if len(cty_header) == 2: self._logger.debug("Header successfully retrieved from CTY File") elif len(cty_header) < 2: self._logger.warning("Header could only be partically retrieved from CTY File") self._logger.warning("Content of Header: ") for key in cty_header: self._logger.warning(str(key)+": "+str(cty_header[key])) return cty_header except Exception as e: self._logger.error("Clublog CTY File could not be opened / modified") self._logger.error("Error Message: " + str(e)) return
[ "def", "_extract_clublog_header", "(", "self", ",", "cty_xml_filename", ")", ":", "cty_header", "=", "{", "}", "try", ":", "with", "open", "(", "cty_xml_filename", ",", "\"r\"", ")", "as", "cty", ":", "raw_header", "=", "cty", ".", "readline", "(", ")", ...
Extract the header of the Clublog XML File
[ "Extract", "the", "header", "of", "the", "Clublog", "XML", "File" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L1084-L1119
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._remove_clublog_xml_header
def _remove_clublog_xml_header(self, cty_xml_filename): """ remove the header of the Clublog XML File to make it properly parseable for the python ElementTree XML parser """ import tempfile try: with open(cty_xml_filename, "r") as f: content = f.readlines() cty_dir = tempfile.gettempdir() cty_name = os.path.split(cty_xml_filename)[1] cty_xml_filename_no_header = os.path.join(cty_dir, "NoHeader_"+cty_name) with open(cty_xml_filename_no_header, "w") as f: f.writelines("<clublog>\n\r") f.writelines(content[1:]) self._logger.debug("Header successfully modified for XML Parsing") return cty_xml_filename_no_header except Exception as e: self._logger.error("Clublog CTY could not be opened / modified") self._logger.error("Error Message: " + str(e)) return
python
def _remove_clublog_xml_header(self, cty_xml_filename): """ remove the header of the Clublog XML File to make it properly parseable for the python ElementTree XML parser """ import tempfile try: with open(cty_xml_filename, "r") as f: content = f.readlines() cty_dir = tempfile.gettempdir() cty_name = os.path.split(cty_xml_filename)[1] cty_xml_filename_no_header = os.path.join(cty_dir, "NoHeader_"+cty_name) with open(cty_xml_filename_no_header, "w") as f: f.writelines("<clublog>\n\r") f.writelines(content[1:]) self._logger.debug("Header successfully modified for XML Parsing") return cty_xml_filename_no_header except Exception as e: self._logger.error("Clublog CTY could not be opened / modified") self._logger.error("Error Message: " + str(e)) return
[ "def", "_remove_clublog_xml_header", "(", "self", ",", "cty_xml_filename", ")", ":", "import", "tempfile", "try", ":", "with", "open", "(", "cty_xml_filename", ",", "\"r\"", ")", "as", "f", ":", "content", "=", "f", ".", "readlines", "(", ")", "cty_dir", "...
remove the header of the Clublog XML File to make it properly parseable for the python ElementTree XML parser
[ "remove", "the", "header", "of", "the", "Clublog", "XML", "File", "to", "make", "it", "properly", "parseable", "for", "the", "python", "ElementTree", "XML", "parser" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L1122-L1147
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._parse_clublog_xml
def _parse_clublog_xml(self, cty_xml_filename): """ parse the content of a clublog XML file and return the parsed values in dictionaries """ entities = {} call_exceptions = {} prefixes = {} invalid_operations = {} zone_exceptions = {} call_exceptions_index = {} prefixes_index = {} invalid_operations_index = {} zone_exceptions_index = {} cty_tree = ET.parse(cty_xml_filename) root = cty_tree.getroot() #retrieve ADIF Country Entities cty_entities = cty_tree.find("entities") self._logger.debug("total entities: " + str(len(cty_entities))) if len(cty_entities) > 1: for cty_entity in cty_entities: try: entity = {} for item in cty_entity: if item.tag == "name": entity[const.COUNTRY] = unicode(item.text) self._logger.debug(unicode(item.text)) elif item.tag == "prefix": entity[const.PREFIX] = unicode(item.text) elif item.tag == "deleted": if item.text == "TRUE": entity[const.DELETED] = True else: entity[const.DELETED] = False elif item.tag == "cqz": entity[const.CQZ] = int(item.text) elif item.tag == "cont": entity[const.CONTINENT] = unicode(item.text) elif item.tag == "long": entity[const.LONGITUDE] = float(item.text) elif item.tag == "lat": entity[const.LATITUDE] = float(item.text) elif item.tag == "start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') entity[const.START] = dt.replace(tzinfo=UTC) elif item.tag == "end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') entity[const.END] = dt.replace(tzinfo=UTC) elif item.tag == "whitelist": if item.text == "TRUE": entity[const.WHITELIST] = True else: entity[const.WHITELIST] = False elif item.tag == "whitelist_start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') entity[const.WHITELIST_START] = dt.replace(tzinfo=UTC) elif item.tag == "whitelist_end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') entity[const.WHITELIST_END] = dt.replace(tzinfo=UTC) except AttributeError: self._logger.error("Error while processing: ") entities[int(cty_entity[0].text)] = entity self._logger.debug(str(len(entities))+" Entities added") else: raise Exception("No Country Entities detected in XML File") cty_exceptions = cty_tree.find("exceptions") if len(cty_exceptions) > 1: for cty_exception in cty_exceptions: call_exception = {} for item in cty_exception: if item.tag == "call": call = str(item.text) if call in call_exceptions_index.keys(): call_exceptions_index[call].append(int(cty_exception.attrib["record"])) else: call_exceptions_index[call] = [int(cty_exception.attrib["record"])] elif item.tag == "entity": call_exception[const.COUNTRY] = unicode(item.text) elif item.tag == "adif": call_exception[const.ADIF] = int(item.text) elif item.tag == "cqz": call_exception[const.CQZ] = int(item.text) elif item.tag == "cont": call_exception[const.CONTINENT] = unicode(item.text) elif item.tag == "long": call_exception[const.LONGITUDE] = float(item.text) elif item.tag == "lat": call_exception[const.LATITUDE] = float(item.text) elif item.tag == "start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') call_exception[const.START] = dt.replace(tzinfo=UTC) elif item.tag == "end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') call_exception[const.END] = dt.replace(tzinfo=UTC) call_exceptions[int(cty_exception.attrib["record"])] = call_exception self._logger.debug(str(len(call_exceptions))+" Exceptions added") self._logger.debug(str(len(call_exceptions_index))+" unique Calls in Index ") else: raise Exception("No Exceptions detected in XML File") cty_prefixes = cty_tree.find("prefixes") if len(cty_prefixes) > 1: for cty_prefix in cty_prefixes: prefix = {} for item in cty_prefix: pref = None if item.tag == "call": #create index for this prefix call = str(item.text) if call in prefixes_index.keys(): prefixes_index[call].append(int(cty_prefix.attrib["record"])) else: prefixes_index[call] = [int(cty_prefix.attrib["record"])] if item.tag == "entity": prefix[const.COUNTRY] = unicode(item.text) elif item.tag == "adif": prefix[const.ADIF] = int(item.text) elif item.tag == "cqz": prefix[const.CQZ] = int(item.text) elif item.tag == "cont": prefix[const.CONTINENT] = unicode(item.text) elif item.tag == "long": prefix[const.LONGITUDE] = float(item.text) elif item.tag == "lat": prefix[const.LATITUDE] = float(item.text) elif item.tag == "start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') prefix[const.START] = dt.replace(tzinfo=UTC) elif item.tag == "end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') prefix[const.END] = dt.replace(tzinfo=UTC) prefixes[int(cty_prefix.attrib["record"])] = prefix self._logger.debug(str(len(prefixes))+" Prefixes added") self._logger.debug(str(len(prefixes_index))+" unique Prefixes in Index") else: raise Exception("No Prefixes detected in XML File") cty_inv_operations = cty_tree.find("invalid_operations") if len(cty_inv_operations) > 1: for cty_inv_operation in cty_inv_operations: invalid_operation = {} for item in cty_inv_operation: call = None if item.tag == "call": call = str(item.text) if call in invalid_operations_index.keys(): invalid_operations_index[call].append(int(cty_inv_operation.attrib["record"])) else: invalid_operations_index[call] = [int(cty_inv_operation.attrib["record"])] elif item.tag == "start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') invalid_operation[const.START] = dt.replace(tzinfo=UTC) elif item.tag == "end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') invalid_operation[const.END] = dt.replace(tzinfo=UTC) invalid_operations[int(cty_inv_operation.attrib["record"])] = invalid_operation self._logger.debug(str(len(invalid_operations))+" Invalid Operations added") self._logger.debug(str(len(invalid_operations_index))+" unique Calls in Index") else: raise Exception("No records for invalid operations detected in XML File") cty_zone_exceptions = cty_tree.find("zone_exceptions") if len(cty_zone_exceptions) > 1: for cty_zone_exception in cty_zone_exceptions: zoneException = {} for item in cty_zone_exception: call = None if item.tag == "call": call = str(item.text) if call in zone_exceptions_index.keys(): zone_exceptions_index[call].append(int(cty_zone_exception.attrib["record"])) else: zone_exceptions_index[call] = [int(cty_zone_exception.attrib["record"])] elif item.tag == "zone": zoneException[const.CQZ] = int(item.text) elif item.tag == "start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') zoneException[const.START] = dt.replace(tzinfo=UTC) elif item.tag == "end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') zoneException[const.END] = dt.replace(tzinfo=UTC) zone_exceptions[int(cty_zone_exception.attrib["record"])] = zoneException self._logger.debug(str(len(zone_exceptions))+" Zone Exceptions added") self._logger.debug(str(len(zone_exceptions_index))+" unique Calls in Index") else: raise Exception("No records for zone exceptions detected in XML File") result = { "entities" : entities, "call_exceptions" : call_exceptions, "prefixes" : prefixes, "invalid_operations" : invalid_operations, "zone_exceptions" : zone_exceptions, "prefixes_index" : prefixes_index, "call_exceptions_index" : call_exceptions_index, "invalid_operations_index" : invalid_operations_index, "zone_exceptions_index" : zone_exceptions_index, } return result
python
def _parse_clublog_xml(self, cty_xml_filename): """ parse the content of a clublog XML file and return the parsed values in dictionaries """ entities = {} call_exceptions = {} prefixes = {} invalid_operations = {} zone_exceptions = {} call_exceptions_index = {} prefixes_index = {} invalid_operations_index = {} zone_exceptions_index = {} cty_tree = ET.parse(cty_xml_filename) root = cty_tree.getroot() #retrieve ADIF Country Entities cty_entities = cty_tree.find("entities") self._logger.debug("total entities: " + str(len(cty_entities))) if len(cty_entities) > 1: for cty_entity in cty_entities: try: entity = {} for item in cty_entity: if item.tag == "name": entity[const.COUNTRY] = unicode(item.text) self._logger.debug(unicode(item.text)) elif item.tag == "prefix": entity[const.PREFIX] = unicode(item.text) elif item.tag == "deleted": if item.text == "TRUE": entity[const.DELETED] = True else: entity[const.DELETED] = False elif item.tag == "cqz": entity[const.CQZ] = int(item.text) elif item.tag == "cont": entity[const.CONTINENT] = unicode(item.text) elif item.tag == "long": entity[const.LONGITUDE] = float(item.text) elif item.tag == "lat": entity[const.LATITUDE] = float(item.text) elif item.tag == "start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') entity[const.START] = dt.replace(tzinfo=UTC) elif item.tag == "end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') entity[const.END] = dt.replace(tzinfo=UTC) elif item.tag == "whitelist": if item.text == "TRUE": entity[const.WHITELIST] = True else: entity[const.WHITELIST] = False elif item.tag == "whitelist_start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') entity[const.WHITELIST_START] = dt.replace(tzinfo=UTC) elif item.tag == "whitelist_end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') entity[const.WHITELIST_END] = dt.replace(tzinfo=UTC) except AttributeError: self._logger.error("Error while processing: ") entities[int(cty_entity[0].text)] = entity self._logger.debug(str(len(entities))+" Entities added") else: raise Exception("No Country Entities detected in XML File") cty_exceptions = cty_tree.find("exceptions") if len(cty_exceptions) > 1: for cty_exception in cty_exceptions: call_exception = {} for item in cty_exception: if item.tag == "call": call = str(item.text) if call in call_exceptions_index.keys(): call_exceptions_index[call].append(int(cty_exception.attrib["record"])) else: call_exceptions_index[call] = [int(cty_exception.attrib["record"])] elif item.tag == "entity": call_exception[const.COUNTRY] = unicode(item.text) elif item.tag == "adif": call_exception[const.ADIF] = int(item.text) elif item.tag == "cqz": call_exception[const.CQZ] = int(item.text) elif item.tag == "cont": call_exception[const.CONTINENT] = unicode(item.text) elif item.tag == "long": call_exception[const.LONGITUDE] = float(item.text) elif item.tag == "lat": call_exception[const.LATITUDE] = float(item.text) elif item.tag == "start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') call_exception[const.START] = dt.replace(tzinfo=UTC) elif item.tag == "end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') call_exception[const.END] = dt.replace(tzinfo=UTC) call_exceptions[int(cty_exception.attrib["record"])] = call_exception self._logger.debug(str(len(call_exceptions))+" Exceptions added") self._logger.debug(str(len(call_exceptions_index))+" unique Calls in Index ") else: raise Exception("No Exceptions detected in XML File") cty_prefixes = cty_tree.find("prefixes") if len(cty_prefixes) > 1: for cty_prefix in cty_prefixes: prefix = {} for item in cty_prefix: pref = None if item.tag == "call": #create index for this prefix call = str(item.text) if call in prefixes_index.keys(): prefixes_index[call].append(int(cty_prefix.attrib["record"])) else: prefixes_index[call] = [int(cty_prefix.attrib["record"])] if item.tag == "entity": prefix[const.COUNTRY] = unicode(item.text) elif item.tag == "adif": prefix[const.ADIF] = int(item.text) elif item.tag == "cqz": prefix[const.CQZ] = int(item.text) elif item.tag == "cont": prefix[const.CONTINENT] = unicode(item.text) elif item.tag == "long": prefix[const.LONGITUDE] = float(item.text) elif item.tag == "lat": prefix[const.LATITUDE] = float(item.text) elif item.tag == "start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') prefix[const.START] = dt.replace(tzinfo=UTC) elif item.tag == "end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') prefix[const.END] = dt.replace(tzinfo=UTC) prefixes[int(cty_prefix.attrib["record"])] = prefix self._logger.debug(str(len(prefixes))+" Prefixes added") self._logger.debug(str(len(prefixes_index))+" unique Prefixes in Index") else: raise Exception("No Prefixes detected in XML File") cty_inv_operations = cty_tree.find("invalid_operations") if len(cty_inv_operations) > 1: for cty_inv_operation in cty_inv_operations: invalid_operation = {} for item in cty_inv_operation: call = None if item.tag == "call": call = str(item.text) if call in invalid_operations_index.keys(): invalid_operations_index[call].append(int(cty_inv_operation.attrib["record"])) else: invalid_operations_index[call] = [int(cty_inv_operation.attrib["record"])] elif item.tag == "start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') invalid_operation[const.START] = dt.replace(tzinfo=UTC) elif item.tag == "end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') invalid_operation[const.END] = dt.replace(tzinfo=UTC) invalid_operations[int(cty_inv_operation.attrib["record"])] = invalid_operation self._logger.debug(str(len(invalid_operations))+" Invalid Operations added") self._logger.debug(str(len(invalid_operations_index))+" unique Calls in Index") else: raise Exception("No records for invalid operations detected in XML File") cty_zone_exceptions = cty_tree.find("zone_exceptions") if len(cty_zone_exceptions) > 1: for cty_zone_exception in cty_zone_exceptions: zoneException = {} for item in cty_zone_exception: call = None if item.tag == "call": call = str(item.text) if call in zone_exceptions_index.keys(): zone_exceptions_index[call].append(int(cty_zone_exception.attrib["record"])) else: zone_exceptions_index[call] = [int(cty_zone_exception.attrib["record"])] elif item.tag == "zone": zoneException[const.CQZ] = int(item.text) elif item.tag == "start": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') zoneException[const.START] = dt.replace(tzinfo=UTC) elif item.tag == "end": dt = datetime.strptime(item.text[:19], '%Y-%m-%dT%H:%M:%S') zoneException[const.END] = dt.replace(tzinfo=UTC) zone_exceptions[int(cty_zone_exception.attrib["record"])] = zoneException self._logger.debug(str(len(zone_exceptions))+" Zone Exceptions added") self._logger.debug(str(len(zone_exceptions_index))+" unique Calls in Index") else: raise Exception("No records for zone exceptions detected in XML File") result = { "entities" : entities, "call_exceptions" : call_exceptions, "prefixes" : prefixes, "invalid_operations" : invalid_operations, "zone_exceptions" : zone_exceptions, "prefixes_index" : prefixes_index, "call_exceptions_index" : call_exceptions_index, "invalid_operations_index" : invalid_operations_index, "zone_exceptions_index" : zone_exceptions_index, } return result
[ "def", "_parse_clublog_xml", "(", "self", ",", "cty_xml_filename", ")", ":", "entities", "=", "{", "}", "call_exceptions", "=", "{", "}", "prefixes", "=", "{", "}", "invalid_operations", "=", "{", "}", "zone_exceptions", "=", "{", "}", "call_exceptions_index",...
parse the content of a clublog XML file and return the parsed values in dictionaries
[ "parse", "the", "content", "of", "a", "clublog", "XML", "file", "and", "return", "the", "parsed", "values", "in", "dictionaries" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L1149-L1364
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._parse_country_file
def _parse_country_file(self, cty_file, country_mapping_filename=None): """ Parse the content of a PLIST file from country-files.com return the parsed values in dictionaries. Country-files.com provides Prefixes and Exceptions """ import plistlib cty_list = None entities = {} exceptions = {} prefixes = {} exceptions_index = {} prefixes_index = {} exceptions_counter = 0 prefixes_counter = 0 mapping = None with open(country_mapping_filename, "r") as f: mapping = json.loads(f.read(),encoding='UTF-8') cty_list = plistlib.readPlist(cty_file) for item in cty_list: entry = {} call = str(item) entry[const.COUNTRY] = unicode(cty_list[item]["Country"]) if mapping: entry[const.ADIF] = int(mapping[cty_list[item]["Country"]]) entry[const.CQZ] = int(cty_list[item]["CQZone"]) entry[const.ITUZ] = int(cty_list[item]["ITUZone"]) entry[const.CONTINENT] = unicode(cty_list[item]["Continent"]) entry[const.LATITUDE] = float(cty_list[item]["Latitude"]) entry[const.LONGITUDE] = float(cty_list[item]["Longitude"])*(-1) if cty_list[item]["ExactCallsign"]: if call in exceptions_index.keys(): exceptions_index[call].append(exceptions_counter) else: exceptions_index[call] = [exceptions_counter] exceptions[exceptions_counter] = entry exceptions_counter += 1 else: if call in prefixes_index.keys(): prefixes_index[call].append(prefixes_counter) else: prefixes_index[call] = [prefixes_counter] prefixes[prefixes_counter] = entry prefixes_counter += 1 self._logger.debug(str(len(prefixes))+" Prefixes added") self._logger.debug(str(len(prefixes_index))+" Prefixes in Index") self._logger.debug(str(len(exceptions))+" Exceptions added") self._logger.debug(str(len(exceptions_index))+" Exceptions in Index") result = { "prefixes" : prefixes, "exceptions" : exceptions, "prefixes_index" : prefixes_index, "exceptions_index" : exceptions_index, } return result
python
def _parse_country_file(self, cty_file, country_mapping_filename=None): """ Parse the content of a PLIST file from country-files.com return the parsed values in dictionaries. Country-files.com provides Prefixes and Exceptions """ import plistlib cty_list = None entities = {} exceptions = {} prefixes = {} exceptions_index = {} prefixes_index = {} exceptions_counter = 0 prefixes_counter = 0 mapping = None with open(country_mapping_filename, "r") as f: mapping = json.loads(f.read(),encoding='UTF-8') cty_list = plistlib.readPlist(cty_file) for item in cty_list: entry = {} call = str(item) entry[const.COUNTRY] = unicode(cty_list[item]["Country"]) if mapping: entry[const.ADIF] = int(mapping[cty_list[item]["Country"]]) entry[const.CQZ] = int(cty_list[item]["CQZone"]) entry[const.ITUZ] = int(cty_list[item]["ITUZone"]) entry[const.CONTINENT] = unicode(cty_list[item]["Continent"]) entry[const.LATITUDE] = float(cty_list[item]["Latitude"]) entry[const.LONGITUDE] = float(cty_list[item]["Longitude"])*(-1) if cty_list[item]["ExactCallsign"]: if call in exceptions_index.keys(): exceptions_index[call].append(exceptions_counter) else: exceptions_index[call] = [exceptions_counter] exceptions[exceptions_counter] = entry exceptions_counter += 1 else: if call in prefixes_index.keys(): prefixes_index[call].append(prefixes_counter) else: prefixes_index[call] = [prefixes_counter] prefixes[prefixes_counter] = entry prefixes_counter += 1 self._logger.debug(str(len(prefixes))+" Prefixes added") self._logger.debug(str(len(prefixes_index))+" Prefixes in Index") self._logger.debug(str(len(exceptions))+" Exceptions added") self._logger.debug(str(len(exceptions_index))+" Exceptions in Index") result = { "prefixes" : prefixes, "exceptions" : exceptions, "prefixes_index" : prefixes_index, "exceptions_index" : exceptions_index, } return result
[ "def", "_parse_country_file", "(", "self", ",", "cty_file", ",", "country_mapping_filename", "=", "None", ")", ":", "import", "plistlib", "cty_list", "=", "None", "entities", "=", "{", "}", "exceptions", "=", "{", "}", "prefixes", "=", "{", "}", "exceptions_...
Parse the content of a PLIST file from country-files.com return the parsed values in dictionaries. Country-files.com provides Prefixes and Exceptions
[ "Parse", "the", "content", "of", "a", "PLIST", "file", "from", "country", "-", "files", ".", "com", "return", "the", "parsed", "values", "in", "dictionaries", ".", "Country", "-", "files", ".", "com", "provides", "Prefixes", "and", "Exceptions" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L1366-L1433
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._generate_random_word
def _generate_random_word(self, length): """ Generates a random word """ return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))
python
def _generate_random_word(self, length): """ Generates a random word """ return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))
[ "def", "_generate_random_word", "(", "self", ",", "length", ")", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_lowercase", ")", "for", "_", "in", "range", "(", "length", ")", ")" ]
Generates a random word
[ "Generates", "a", "random", "word" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L1435-L1439
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._check_html_response
def _check_html_response(self, response): """ Checks if the API Key is valid and if the request returned a 200 status (ok) """ error1 = "Access to this form requires a valid API key. For more info see: http://www.clublog.org/need_api.php" error2 = "Invalid or missing API Key" if response.status_code == requests.codes.ok: return True else: err_str = "HTTP Status Code: " + str(response.status_code) + " HTTP Response: " + str(response.text) self._logger.error(err_str) if response.status_code == 403: raise APIKeyMissingError else: raise LookupError(err_str)
python
def _check_html_response(self, response): """ Checks if the API Key is valid and if the request returned a 200 status (ok) """ error1 = "Access to this form requires a valid API key. For more info see: http://www.clublog.org/need_api.php" error2 = "Invalid or missing API Key" if response.status_code == requests.codes.ok: return True else: err_str = "HTTP Status Code: " + str(response.status_code) + " HTTP Response: " + str(response.text) self._logger.error(err_str) if response.status_code == 403: raise APIKeyMissingError else: raise LookupError(err_str)
[ "def", "_check_html_response", "(", "self", ",", "response", ")", ":", "error1", "=", "\"Access to this form requires a valid API key. For more info see: http://www.clublog.org/need_api.php\"", "error2", "=", "\"Invalid or missing API Key\"", "if", "response", ".", "status_code", ...
Checks if the API Key is valid and if the request returned a 200 status (ok)
[ "Checks", "if", "the", "API", "Key", "is", "valid", "and", "if", "the", "request", "returned", "a", "200", "status", "(", "ok", ")" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L1441-L1457
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._serialize_data
def _serialize_data(self, my_dict): """ Serialize a Dictionary into JSON """ new_dict = {} for item in my_dict: if isinstance(my_dict[item], datetime): new_dict[item] = my_dict[item].strftime('%Y-%m-%d%H:%M:%S') else: new_dict[item] = str(my_dict[item]) return json.dumps(new_dict)
python
def _serialize_data(self, my_dict): """ Serialize a Dictionary into JSON """ new_dict = {} for item in my_dict: if isinstance(my_dict[item], datetime): new_dict[item] = my_dict[item].strftime('%Y-%m-%d%H:%M:%S') else: new_dict[item] = str(my_dict[item]) return json.dumps(new_dict)
[ "def", "_serialize_data", "(", "self", ",", "my_dict", ")", ":", "new_dict", "=", "{", "}", "for", "item", "in", "my_dict", ":", "if", "isinstance", "(", "my_dict", "[", "item", "]", ",", "datetime", ")", ":", "new_dict", "[", "item", "]", "=", "my_d...
Serialize a Dictionary into JSON
[ "Serialize", "a", "Dictionary", "into", "JSON" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L1460-L1471
train
dh1tw/pyhamtools
pyhamtools/lookuplib.py
LookupLib._deserialize_data
def _deserialize_data(self, json_data): """ Deserialize a JSON into a dictionary """ my_dict = json.loads(json_data.decode('utf8').replace("'", '"'), encoding='UTF-8') for item in my_dict: if item == const.ADIF: my_dict[item] = int(my_dict[item]) elif item == const.DELETED: my_dict[item] = self._str_to_bool(my_dict[item]) elif item == const.CQZ: my_dict[item] = int(my_dict[item]) elif item == const.ITUZ: my_dict[item] = int(my_dict[item]) elif item == const.LATITUDE: my_dict[item] = float(my_dict[item]) elif item == const.LONGITUDE: my_dict[item] = float(my_dict[item]) elif item == const.START: my_dict[item] = datetime.strptime(my_dict[item], '%Y-%m-%d%H:%M:%S').replace(tzinfo=UTC) elif item == const.END: my_dict[item] = datetime.strptime(my_dict[item], '%Y-%m-%d%H:%M:%S').replace(tzinfo=UTC) elif item == const.WHITELIST_START: my_dict[item] = datetime.strptime(my_dict[item], '%Y-%m-%d%H:%M:%S').replace(tzinfo=UTC) elif item == const.WHITELIST_END: my_dict[item] = datetime.strptime(my_dict[item], '%Y-%m-%d%H:%M:%S').replace(tzinfo=UTC) elif item == const.WHITELIST: my_dict[item] = self._str_to_bool(my_dict[item]) else: my_dict[item] = unicode(my_dict[item]) return my_dict
python
def _deserialize_data(self, json_data): """ Deserialize a JSON into a dictionary """ my_dict = json.loads(json_data.decode('utf8').replace("'", '"'), encoding='UTF-8') for item in my_dict: if item == const.ADIF: my_dict[item] = int(my_dict[item]) elif item == const.DELETED: my_dict[item] = self._str_to_bool(my_dict[item]) elif item == const.CQZ: my_dict[item] = int(my_dict[item]) elif item == const.ITUZ: my_dict[item] = int(my_dict[item]) elif item == const.LATITUDE: my_dict[item] = float(my_dict[item]) elif item == const.LONGITUDE: my_dict[item] = float(my_dict[item]) elif item == const.START: my_dict[item] = datetime.strptime(my_dict[item], '%Y-%m-%d%H:%M:%S').replace(tzinfo=UTC) elif item == const.END: my_dict[item] = datetime.strptime(my_dict[item], '%Y-%m-%d%H:%M:%S').replace(tzinfo=UTC) elif item == const.WHITELIST_START: my_dict[item] = datetime.strptime(my_dict[item], '%Y-%m-%d%H:%M:%S').replace(tzinfo=UTC) elif item == const.WHITELIST_END: my_dict[item] = datetime.strptime(my_dict[item], '%Y-%m-%d%H:%M:%S').replace(tzinfo=UTC) elif item == const.WHITELIST: my_dict[item] = self._str_to_bool(my_dict[item]) else: my_dict[item] = unicode(my_dict[item]) return my_dict
[ "def", "_deserialize_data", "(", "self", ",", "json_data", ")", ":", "my_dict", "=", "json", ".", "loads", "(", "json_data", ".", "decode", "(", "'utf8'", ")", ".", "replace", "(", "\"'\"", ",", "'\"'", ")", ",", "encoding", "=", "'UTF-8'", ")", "for",...
Deserialize a JSON into a dictionary
[ "Deserialize", "a", "JSON", "into", "a", "dictionary" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/lookuplib.py#L1473-L1507
train
AustralianSynchrotron/lightflow
lightflow/models/mongo_proxy.py
get_methods
def get_methods(*objs): """ Return the names of all callable attributes of an object""" return set( attr for obj in objs for attr in dir(obj) if not attr.startswith('_') and callable(getattr(obj, attr)) )
python
def get_methods(*objs): """ Return the names of all callable attributes of an object""" return set( attr for obj in objs for attr in dir(obj) if not attr.startswith('_') and callable(getattr(obj, attr)) )
[ "def", "get_methods", "(", "*", "objs", ")", ":", "return", "set", "(", "attr", "for", "obj", "in", "objs", "for", "attr", "in", "dir", "(", "obj", ")", "if", "not", "attr", ".", "startswith", "(", "'_'", ")", "and", "callable", "(", "getattr", "("...
Return the names of all callable attributes of an object
[ "Return", "the", "names", "of", "all", "callable", "attributes", "of", "an", "object" ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/mongo_proxy.py#L18-L25
train
AustralianSynchrotron/lightflow
lightflow/config.py
Config.from_file
def from_file(cls, filename, *, strict=True): """ Create a new Config object from a configuration file. Args: filename (str): The location and name of the configuration file. strict (bool): If true raises a ConfigLoadError when the configuration cannot be found. Returns: An instance of the Config class. Raises: ConfigLoadError: If the configuration cannot be found. """ config = cls() config.load_from_file(filename, strict=strict) return config
python
def from_file(cls, filename, *, strict=True): """ Create a new Config object from a configuration file. Args: filename (str): The location and name of the configuration file. strict (bool): If true raises a ConfigLoadError when the configuration cannot be found. Returns: An instance of the Config class. Raises: ConfigLoadError: If the configuration cannot be found. """ config = cls() config.load_from_file(filename, strict=strict) return config
[ "def", "from_file", "(", "cls", ",", "filename", ",", "*", ",", "strict", "=", "True", ")", ":", "config", "=", "cls", "(", ")", "config", ".", "load_from_file", "(", "filename", ",", "strict", "=", "strict", ")", "return", "config" ]
Create a new Config object from a configuration file. Args: filename (str): The location and name of the configuration file. strict (bool): If true raises a ConfigLoadError when the configuration cannot be found. Returns: An instance of the Config class. Raises: ConfigLoadError: If the configuration cannot be found.
[ "Create", "a", "new", "Config", "object", "from", "a", "configuration", "file", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/config.py#L43-L59
train
AustralianSynchrotron/lightflow
lightflow/config.py
Config.load_from_file
def load_from_file(self, filename=None, *, strict=True): """ Load the configuration from a file. The location of the configuration file can either be specified directly in the parameter filename or is searched for in the following order: 1. In the environment variable given by LIGHTFLOW_CONFIG_ENV 2. In the current execution directory 3. In the user's home directory Args: filename (str): The location and name of the configuration file. strict (bool): If true raises a ConfigLoadError when the configuration cannot be found. Raises: ConfigLoadError: If the configuration cannot be found. """ self.set_to_default() if filename: self._update_from_file(filename) else: if LIGHTFLOW_CONFIG_ENV not in os.environ: if os.path.isfile(os.path.join(os.getcwd(), LIGHTFLOW_CONFIG_NAME)): self._update_from_file( os.path.join(os.getcwd(), LIGHTFLOW_CONFIG_NAME)) elif os.path.isfile(expand_env_var('~/{}'.format(LIGHTFLOW_CONFIG_NAME))): self._update_from_file( expand_env_var('~/{}'.format(LIGHTFLOW_CONFIG_NAME))) else: if strict: raise ConfigLoadError('Could not find the configuration file.') else: self._update_from_file(expand_env_var(os.environ[LIGHTFLOW_CONFIG_ENV])) self._update_python_paths()
python
def load_from_file(self, filename=None, *, strict=True): """ Load the configuration from a file. The location of the configuration file can either be specified directly in the parameter filename or is searched for in the following order: 1. In the environment variable given by LIGHTFLOW_CONFIG_ENV 2. In the current execution directory 3. In the user's home directory Args: filename (str): The location and name of the configuration file. strict (bool): If true raises a ConfigLoadError when the configuration cannot be found. Raises: ConfigLoadError: If the configuration cannot be found. """ self.set_to_default() if filename: self._update_from_file(filename) else: if LIGHTFLOW_CONFIG_ENV not in os.environ: if os.path.isfile(os.path.join(os.getcwd(), LIGHTFLOW_CONFIG_NAME)): self._update_from_file( os.path.join(os.getcwd(), LIGHTFLOW_CONFIG_NAME)) elif os.path.isfile(expand_env_var('~/{}'.format(LIGHTFLOW_CONFIG_NAME))): self._update_from_file( expand_env_var('~/{}'.format(LIGHTFLOW_CONFIG_NAME))) else: if strict: raise ConfigLoadError('Could not find the configuration file.') else: self._update_from_file(expand_env_var(os.environ[LIGHTFLOW_CONFIG_ENV])) self._update_python_paths()
[ "def", "load_from_file", "(", "self", ",", "filename", "=", "None", ",", "*", ",", "strict", "=", "True", ")", ":", "self", ".", "set_to_default", "(", ")", "if", "filename", ":", "self", ".", "_update_from_file", "(", "filename", ")", "else", ":", "if...
Load the configuration from a file. The location of the configuration file can either be specified directly in the parameter filename or is searched for in the following order: 1. In the environment variable given by LIGHTFLOW_CONFIG_ENV 2. In the current execution directory 3. In the user's home directory Args: filename (str): The location and name of the configuration file. strict (bool): If true raises a ConfigLoadError when the configuration cannot be found. Raises: ConfigLoadError: If the configuration cannot be found.
[ "Load", "the", "configuration", "from", "a", "file", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/config.py#L61-L97
train
AustralianSynchrotron/lightflow
lightflow/config.py
Config.load_from_dict
def load_from_dict(self, conf_dict=None): """ Load the configuration from a dictionary. Args: conf_dict (dict): Dictionary with the configuration. """ self.set_to_default() self._update_dict(self._config, conf_dict) self._update_python_paths()
python
def load_from_dict(self, conf_dict=None): """ Load the configuration from a dictionary. Args: conf_dict (dict): Dictionary with the configuration. """ self.set_to_default() self._update_dict(self._config, conf_dict) self._update_python_paths()
[ "def", "load_from_dict", "(", "self", ",", "conf_dict", "=", "None", ")", ":", "self", ".", "set_to_default", "(", ")", "self", ".", "_update_dict", "(", "self", ".", "_config", ",", "conf_dict", ")", "self", ".", "_update_python_paths", "(", ")" ]
Load the configuration from a dictionary. Args: conf_dict (dict): Dictionary with the configuration.
[ "Load", "the", "configuration", "from", "a", "dictionary", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/config.py#L99-L107
train
AustralianSynchrotron/lightflow
lightflow/config.py
Config._update_from_file
def _update_from_file(self, filename): """ Helper method to update an existing configuration with the values from a file. Loads a configuration file and replaces all values in the existing configuration dictionary with the values from the file. Args: filename (str): The path and name to the configuration file. """ if os.path.exists(filename): try: with open(filename, 'r') as config_file: yaml_dict = yaml.safe_load(config_file.read()) if yaml_dict is not None: self._update_dict(self._config, yaml_dict) except IsADirectoryError: raise ConfigLoadError( 'The specified configuration file is a directory not a file') else: raise ConfigLoadError('The config file {} does not exist'.format(filename))
python
def _update_from_file(self, filename): """ Helper method to update an existing configuration with the values from a file. Loads a configuration file and replaces all values in the existing configuration dictionary with the values from the file. Args: filename (str): The path and name to the configuration file. """ if os.path.exists(filename): try: with open(filename, 'r') as config_file: yaml_dict = yaml.safe_load(config_file.read()) if yaml_dict is not None: self._update_dict(self._config, yaml_dict) except IsADirectoryError: raise ConfigLoadError( 'The specified configuration file is a directory not a file') else: raise ConfigLoadError('The config file {} does not exist'.format(filename))
[ "def", "_update_from_file", "(", "self", ",", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "config_file", ":", "yaml_dict", "=", "yaml", "...
Helper method to update an existing configuration with the values from a file. Loads a configuration file and replaces all values in the existing configuration dictionary with the values from the file. Args: filename (str): The path and name to the configuration file.
[ "Helper", "method", "to", "update", "an", "existing", "configuration", "with", "the", "values", "from", "a", "file", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/config.py#L169-L188
train
AustralianSynchrotron/lightflow
lightflow/config.py
Config._update_dict
def _update_dict(self, to_dict, from_dict): """ Recursively merges the fields for two dictionaries. Args: to_dict (dict): The dictionary onto which the merge is executed. from_dict (dict): The dictionary merged into to_dict """ for key, value in from_dict.items(): if key in to_dict and isinstance(to_dict[key], dict) and \ isinstance(from_dict[key], dict): self._update_dict(to_dict[key], from_dict[key]) else: to_dict[key] = from_dict[key]
python
def _update_dict(self, to_dict, from_dict): """ Recursively merges the fields for two dictionaries. Args: to_dict (dict): The dictionary onto which the merge is executed. from_dict (dict): The dictionary merged into to_dict """ for key, value in from_dict.items(): if key in to_dict and isinstance(to_dict[key], dict) and \ isinstance(from_dict[key], dict): self._update_dict(to_dict[key], from_dict[key]) else: to_dict[key] = from_dict[key]
[ "def", "_update_dict", "(", "self", ",", "to_dict", ",", "from_dict", ")", ":", "for", "key", ",", "value", "in", "from_dict", ".", "items", "(", ")", ":", "if", "key", "in", "to_dict", "and", "isinstance", "(", "to_dict", "[", "key", "]", ",", "dict...
Recursively merges the fields for two dictionaries. Args: to_dict (dict): The dictionary onto which the merge is executed. from_dict (dict): The dictionary merged into to_dict
[ "Recursively", "merges", "the", "fields", "for", "two", "dictionaries", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/config.py#L190-L202
train
AustralianSynchrotron/lightflow
lightflow/config.py
Config._update_python_paths
def _update_python_paths(self): """ Append the workflow and libraries paths to the PYTHONPATH. """ for path in self._config['workflows'] + self._config['libraries']: if os.path.isdir(os.path.abspath(path)): if path not in sys.path: sys.path.append(path) else: raise ConfigLoadError( 'Workflow directory {} does not exist'.format(path))
python
def _update_python_paths(self): """ Append the workflow and libraries paths to the PYTHONPATH. """ for path in self._config['workflows'] + self._config['libraries']: if os.path.isdir(os.path.abspath(path)): if path not in sys.path: sys.path.append(path) else: raise ConfigLoadError( 'Workflow directory {} does not exist'.format(path))
[ "def", "_update_python_paths", "(", "self", ")", ":", "for", "path", "in", "self", ".", "_config", "[", "'workflows'", "]", "+", "self", ".", "_config", "[", "'libraries'", "]", ":", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".",...
Append the workflow and libraries paths to the PYTHONPATH.
[ "Append", "the", "workflow", "and", "libraries", "paths", "to", "the", "PYTHONPATH", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/config.py#L204-L212
train
dh1tw/pyhamtools
pyhamtools/dxcluster.py
decode_char_spot
def decode_char_spot(raw_string): """Chop Line from DX-Cluster into pieces and return a dict with the spot data""" data = {} # Spotter callsign if re.match('[A-Za-z0-9\/]+[:$]', raw_string[6:15]): data[const.SPOTTER] = re.sub(':', '', re.match('[A-Za-z0-9\/]+[:$]', raw_string[6:15]).group(0)) else: raise ValueError if re.search('[0-9\.]{5,12}', raw_string[10:25]): data[const.FREQUENCY] = float(re.search('[0-9\.]{5,12}', raw_string[10:25]).group(0)) else: raise ValueError data[const.DX] = re.sub('[^A-Za-z0-9\/]+', '', raw_string[26:38]) data[const.COMMENT] = re.sub('[^\sA-Za-z0-9\.,;\#\+\-!\?\$\(\)@\/]+', ' ', raw_string[39:69]).strip() data[const.TIME] = datetime.now().replace(tzinfo=UTC) return data
python
def decode_char_spot(raw_string): """Chop Line from DX-Cluster into pieces and return a dict with the spot data""" data = {} # Spotter callsign if re.match('[A-Za-z0-9\/]+[:$]', raw_string[6:15]): data[const.SPOTTER] = re.sub(':', '', re.match('[A-Za-z0-9\/]+[:$]', raw_string[6:15]).group(0)) else: raise ValueError if re.search('[0-9\.]{5,12}', raw_string[10:25]): data[const.FREQUENCY] = float(re.search('[0-9\.]{5,12}', raw_string[10:25]).group(0)) else: raise ValueError data[const.DX] = re.sub('[^A-Za-z0-9\/]+', '', raw_string[26:38]) data[const.COMMENT] = re.sub('[^\sA-Za-z0-9\.,;\#\+\-!\?\$\(\)@\/]+', ' ', raw_string[39:69]).strip() data[const.TIME] = datetime.now().replace(tzinfo=UTC) return data
[ "def", "decode_char_spot", "(", "raw_string", ")", ":", "data", "=", "{", "}", "# Spotter callsign", "if", "re", ".", "match", "(", "'[A-Za-z0-9\\/]+[:$]'", ",", "raw_string", "[", "6", ":", "15", "]", ")", ":", "data", "[", "const", ".", "SPOTTER", "]",...
Chop Line from DX-Cluster into pieces and return a dict with the spot data
[ "Chop", "Line", "from", "DX", "-", "Cluster", "into", "pieces", "and", "return", "a", "dict", "with", "the", "spot", "data" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/dxcluster.py#L16-L36
train
dh1tw/pyhamtools
pyhamtools/dxcluster.py
decode_pc11_message
def decode_pc11_message(raw_string): """Decode PC11 message, which usually contains DX Spots""" data = {} spot = raw_string.split("^") data[const.FREQUENCY] = float(spot[1]) data[const.DX] = spot[2] data[const.TIME] = datetime.fromtimestamp(mktime(strptime(spot[3]+" "+spot[4][:-1], "%d-%b-%Y %H%M"))) data[const.COMMENT] = spot[5] data[const.SPOTTER] = spot[6] data["node"] = spot[7] data["raw_spot"] = raw_string return data
python
def decode_pc11_message(raw_string): """Decode PC11 message, which usually contains DX Spots""" data = {} spot = raw_string.split("^") data[const.FREQUENCY] = float(spot[1]) data[const.DX] = spot[2] data[const.TIME] = datetime.fromtimestamp(mktime(strptime(spot[3]+" "+spot[4][:-1], "%d-%b-%Y %H%M"))) data[const.COMMENT] = spot[5] data[const.SPOTTER] = spot[6] data["node"] = spot[7] data["raw_spot"] = raw_string return data
[ "def", "decode_pc11_message", "(", "raw_string", ")", ":", "data", "=", "{", "}", "spot", "=", "raw_string", ".", "split", "(", "\"^\"", ")", "data", "[", "const", ".", "FREQUENCY", "]", "=", "float", "(", "spot", "[", "1", "]", ")", "data", "[", "...
Decode PC11 message, which usually contains DX Spots
[ "Decode", "PC11", "message", "which", "usually", "contains", "DX", "Spots" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/dxcluster.py#L38-L50
train
dh1tw/pyhamtools
pyhamtools/dxcluster.py
decode_pc23_message
def decode_pc23_message(raw_string): """ Decode PC23 Message which usually contains WCY """ data = {} wcy = raw_string.split("^") data[const.R] = int(wcy[1]) data[const.expk] = int(wcy[2]) data[const.CALLSIGN] = wcy[3] data[const.A] = wcy[4] data[const.SFI] = wcy[5] data[const.K] = wcy[6] data[const.AURORA] = wcy[7] data["node"] = wcy[7] data["ip"] = wcy[8] data["raw_data"] = raw_string return data
python
def decode_pc23_message(raw_string): """ Decode PC23 Message which usually contains WCY """ data = {} wcy = raw_string.split("^") data[const.R] = int(wcy[1]) data[const.expk] = int(wcy[2]) data[const.CALLSIGN] = wcy[3] data[const.A] = wcy[4] data[const.SFI] = wcy[5] data[const.K] = wcy[6] data[const.AURORA] = wcy[7] data["node"] = wcy[7] data["ip"] = wcy[8] data["raw_data"] = raw_string return data
[ "def", "decode_pc23_message", "(", "raw_string", ")", ":", "data", "=", "{", "}", "wcy", "=", "raw_string", ".", "split", "(", "\"^\"", ")", "data", "[", "const", ".", "R", "]", "=", "int", "(", "wcy", "[", "1", "]", ")", "data", "[", "const", "....
Decode PC23 Message which usually contains WCY
[ "Decode", "PC23", "Message", "which", "usually", "contains", "WCY" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/dxcluster.py#L68-L83
train
AustralianSynchrotron/lightflow
lightflow/models/task.py
BaseTask._run
def _run(self, data, store, signal, context, *, success_callback=None, stop_callback=None, abort_callback=None): """ The internal run method that decorates the public run method. This method makes sure data is being passed to and from the task. Args: data (MultiTaskData): The data object that has been passed from the predecessor task. store (DataStoreDocument): The persistent data store object that allows the task to store data for access across the current workflow run. signal (TaskSignal): The signal object for tasks. It wraps the construction and sending of signals into easy to use methods. context (TaskContext): The context in which the tasks runs. success_callback: This function is called when the task completed successfully stop_callback: This function is called when a StopTask exception was raised. abort_callback: This function is called when an AbortWorkflow exception was raised. Raises: TaskReturnActionInvalid: If the return value of the task is not an Action object. Returns: Action: An Action object containing the data that should be passed on to the next task and optionally a list of successor tasks that should be executed. """ if data is None: data = MultiTaskData() data.add_dataset(self._name) try: if self._callback_init is not None: self._callback_init(data, store, signal, context) result = self.run(data, store, signal, context) if self._callback_finally is not None: self._callback_finally(TaskStatus.Success, data, store, signal, context) if success_callback is not None: success_callback() # the task should be stopped and optionally all successor tasks skipped except StopTask as err: if self._callback_finally is not None: self._callback_finally(TaskStatus.Stopped, data, store, signal, context) if stop_callback is not None: stop_callback(exc=err) result = Action(data, limit=[]) if err.skip_successors else None # the workflow should be stopped immediately except AbortWorkflow as err: if self._callback_finally is not None: self._callback_finally(TaskStatus.Aborted, data, store, signal, context) if abort_callback is not None: abort_callback(exc=err) result = None signal.stop_workflow() # catch any other exception, call the finally callback, then re-raise except: if self._callback_finally is not None: self._callback_finally(TaskStatus.Error, data, store, signal, context) signal.stop_workflow() raise # handle the returned data (either implicitly or as an returned Action object) by # flattening all, possibly modified, input datasets in the MultiTask data down to # a single output dataset. if result is None: data.flatten(in_place=True) data.add_task_history(self.name) return Action(data) else: if not isinstance(result, Action): raise TaskReturnActionInvalid() result.data.flatten(in_place=True) result.data.add_task_history(self.name) return result
python
def _run(self, data, store, signal, context, *, success_callback=None, stop_callback=None, abort_callback=None): """ The internal run method that decorates the public run method. This method makes sure data is being passed to and from the task. Args: data (MultiTaskData): The data object that has been passed from the predecessor task. store (DataStoreDocument): The persistent data store object that allows the task to store data for access across the current workflow run. signal (TaskSignal): The signal object for tasks. It wraps the construction and sending of signals into easy to use methods. context (TaskContext): The context in which the tasks runs. success_callback: This function is called when the task completed successfully stop_callback: This function is called when a StopTask exception was raised. abort_callback: This function is called when an AbortWorkflow exception was raised. Raises: TaskReturnActionInvalid: If the return value of the task is not an Action object. Returns: Action: An Action object containing the data that should be passed on to the next task and optionally a list of successor tasks that should be executed. """ if data is None: data = MultiTaskData() data.add_dataset(self._name) try: if self._callback_init is not None: self._callback_init(data, store, signal, context) result = self.run(data, store, signal, context) if self._callback_finally is not None: self._callback_finally(TaskStatus.Success, data, store, signal, context) if success_callback is not None: success_callback() # the task should be stopped and optionally all successor tasks skipped except StopTask as err: if self._callback_finally is not None: self._callback_finally(TaskStatus.Stopped, data, store, signal, context) if stop_callback is not None: stop_callback(exc=err) result = Action(data, limit=[]) if err.skip_successors else None # the workflow should be stopped immediately except AbortWorkflow as err: if self._callback_finally is not None: self._callback_finally(TaskStatus.Aborted, data, store, signal, context) if abort_callback is not None: abort_callback(exc=err) result = None signal.stop_workflow() # catch any other exception, call the finally callback, then re-raise except: if self._callback_finally is not None: self._callback_finally(TaskStatus.Error, data, store, signal, context) signal.stop_workflow() raise # handle the returned data (either implicitly or as an returned Action object) by # flattening all, possibly modified, input datasets in the MultiTask data down to # a single output dataset. if result is None: data.flatten(in_place=True) data.add_task_history(self.name) return Action(data) else: if not isinstance(result, Action): raise TaskReturnActionInvalid() result.data.flatten(in_place=True) result.data.add_task_history(self.name) return result
[ "def", "_run", "(", "self", ",", "data", ",", "store", ",", "signal", ",", "context", ",", "*", ",", "success_callback", "=", "None", ",", "stop_callback", "=", "None", ",", "abort_callback", "=", "None", ")", ":", "if", "data", "is", "None", ":", "d...
The internal run method that decorates the public run method. This method makes sure data is being passed to and from the task. Args: data (MultiTaskData): The data object that has been passed from the predecessor task. store (DataStoreDocument): The persistent data store object that allows the task to store data for access across the current workflow run. signal (TaskSignal): The signal object for tasks. It wraps the construction and sending of signals into easy to use methods. context (TaskContext): The context in which the tasks runs. success_callback: This function is called when the task completed successfully stop_callback: This function is called when a StopTask exception was raised. abort_callback: This function is called when an AbortWorkflow exception was raised. Raises: TaskReturnActionInvalid: If the return value of the task is not an Action object. Returns: Action: An Action object containing the data that should be passed on to the next task and optionally a list of successor tasks that should be executed.
[ "The", "internal", "run", "method", "that", "decorates", "the", "public", "run", "method", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task.py#L208-L295
train
dh1tw/pyhamtools
pyhamtools/locator.py
latlong_to_locator
def latlong_to_locator (latitude, longitude): """converts WGS84 coordinates into the corresponding Maidenhead Locator Args: latitude (float): Latitude longitude (float): Longitude Returns: string: Maidenhead locator Raises: ValueError: When called with wrong or invalid input args TypeError: When args are non float values Example: The following example converts latitude and longitude into the Maidenhead locator >>> from pyhamtools.locator import latlong_to_locator >>> latitude = 48.5208333 >>> longitude = 9.375 >>> latlong_to_locator(latitude, longitude) 'JN48QM' Note: Latitude (negative = West, positive = East) Longitude (negative = South, positive = North) """ if longitude >= 180 or longitude <= -180: raise ValueError if latitude >= 90 or latitude <= -90: raise ValueError longitude += 180; latitude +=90; locator = chr(ord('A') + int(longitude / 20)) locator += chr(ord('A') + int(latitude / 10)) locator += chr(ord('0') + int((longitude % 20) / 2)) locator += chr(ord('0') + int(latitude % 10)) locator += chr(ord('A') + int((longitude - int(longitude / 2) * 2) / (2 / 24))) locator += chr(ord('A') + int((latitude - int(latitude / 1) * 1 ) / (1 / 24))) return locator
python
def latlong_to_locator (latitude, longitude): """converts WGS84 coordinates into the corresponding Maidenhead Locator Args: latitude (float): Latitude longitude (float): Longitude Returns: string: Maidenhead locator Raises: ValueError: When called with wrong or invalid input args TypeError: When args are non float values Example: The following example converts latitude and longitude into the Maidenhead locator >>> from pyhamtools.locator import latlong_to_locator >>> latitude = 48.5208333 >>> longitude = 9.375 >>> latlong_to_locator(latitude, longitude) 'JN48QM' Note: Latitude (negative = West, positive = East) Longitude (negative = South, positive = North) """ if longitude >= 180 or longitude <= -180: raise ValueError if latitude >= 90 or latitude <= -90: raise ValueError longitude += 180; latitude +=90; locator = chr(ord('A') + int(longitude / 20)) locator += chr(ord('A') + int(latitude / 10)) locator += chr(ord('0') + int((longitude % 20) / 2)) locator += chr(ord('0') + int(latitude % 10)) locator += chr(ord('A') + int((longitude - int(longitude / 2) * 2) / (2 / 24))) locator += chr(ord('A') + int((latitude - int(latitude / 1) * 1 ) / (1 / 24))) return locator
[ "def", "latlong_to_locator", "(", "latitude", ",", "longitude", ")", ":", "if", "longitude", ">=", "180", "or", "longitude", "<=", "-", "180", ":", "raise", "ValueError", "if", "latitude", ">=", "90", "or", "latitude", "<=", "-", "90", ":", "raise", "Val...
converts WGS84 coordinates into the corresponding Maidenhead Locator Args: latitude (float): Latitude longitude (float): Longitude Returns: string: Maidenhead locator Raises: ValueError: When called with wrong or invalid input args TypeError: When args are non float values Example: The following example converts latitude and longitude into the Maidenhead locator >>> from pyhamtools.locator import latlong_to_locator >>> latitude = 48.5208333 >>> longitude = 9.375 >>> latlong_to_locator(latitude, longitude) 'JN48QM' Note: Latitude (negative = West, positive = East) Longitude (negative = South, positive = North)
[ "converts", "WGS84", "coordinates", "into", "the", "corresponding", "Maidenhead", "Locator" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/locator.py#L10-L55
train
dh1tw/pyhamtools
pyhamtools/locator.py
locator_to_latlong
def locator_to_latlong (locator): """converts Maidenhead locator in the corresponding WGS84 coordinates Args: locator (string): Locator, either 4 or 6 characters Returns: tuple (float, float): Latitude, Longitude Raises: ValueError: When called with wrong or invalid input arg TypeError: When arg is not a string Example: The following example converts a Maidenhead locator into Latitude and Longitude >>> from pyhamtools.locator import locator_to_latlong >>> latitude, longitude = locator_to_latlong("JN48QM") >>> print latitude, longitude 48.5208333333 9.375 Note: Latitude (negative = West, positive = East) Longitude (negative = South, positive = North) """ locator = locator.upper() if len(locator) == 5 or len(locator) < 4: raise ValueError if ord(locator[0]) > ord('R') or ord(locator[0]) < ord('A'): raise ValueError if ord(locator[1]) > ord('R') or ord(locator[1]) < ord('A'): raise ValueError if ord(locator[2]) > ord('9') or ord(locator[2]) < ord('0'): raise ValueError if ord(locator[3]) > ord('9') or ord(locator[3]) < ord('0'): raise ValueError if len(locator) == 6: if ord(locator[4]) > ord('X') or ord(locator[4]) < ord('A'): raise ValueError if ord (locator[5]) > ord('X') or ord(locator[5]) < ord('A'): raise ValueError longitude = (ord(locator[0]) - ord('A')) * 20 - 180 latitude = (ord(locator[1]) - ord('A')) * 10 - 90 longitude += (ord(locator[2]) - ord('0')) * 2 latitude += (ord(locator[3]) - ord('0')) if len(locator) == 6: longitude += ((ord(locator[4])) - ord('A')) * (2 / 24) latitude += ((ord(locator[5])) - ord('A')) * (1 / 24) # move to center of subsquare longitude += 1 / 24 latitude += 0.5 / 24 else: # move to center of square longitude += 1; latitude += 0.5; return latitude, longitude
python
def locator_to_latlong (locator): """converts Maidenhead locator in the corresponding WGS84 coordinates Args: locator (string): Locator, either 4 or 6 characters Returns: tuple (float, float): Latitude, Longitude Raises: ValueError: When called with wrong or invalid input arg TypeError: When arg is not a string Example: The following example converts a Maidenhead locator into Latitude and Longitude >>> from pyhamtools.locator import locator_to_latlong >>> latitude, longitude = locator_to_latlong("JN48QM") >>> print latitude, longitude 48.5208333333 9.375 Note: Latitude (negative = West, positive = East) Longitude (negative = South, positive = North) """ locator = locator.upper() if len(locator) == 5 or len(locator) < 4: raise ValueError if ord(locator[0]) > ord('R') or ord(locator[0]) < ord('A'): raise ValueError if ord(locator[1]) > ord('R') or ord(locator[1]) < ord('A'): raise ValueError if ord(locator[2]) > ord('9') or ord(locator[2]) < ord('0'): raise ValueError if ord(locator[3]) > ord('9') or ord(locator[3]) < ord('0'): raise ValueError if len(locator) == 6: if ord(locator[4]) > ord('X') or ord(locator[4]) < ord('A'): raise ValueError if ord (locator[5]) > ord('X') or ord(locator[5]) < ord('A'): raise ValueError longitude = (ord(locator[0]) - ord('A')) * 20 - 180 latitude = (ord(locator[1]) - ord('A')) * 10 - 90 longitude += (ord(locator[2]) - ord('0')) * 2 latitude += (ord(locator[3]) - ord('0')) if len(locator) == 6: longitude += ((ord(locator[4])) - ord('A')) * (2 / 24) latitude += ((ord(locator[5])) - ord('A')) * (1 / 24) # move to center of subsquare longitude += 1 / 24 latitude += 0.5 / 24 else: # move to center of square longitude += 1; latitude += 0.5; return latitude, longitude
[ "def", "locator_to_latlong", "(", "locator", ")", ":", "locator", "=", "locator", ".", "upper", "(", ")", "if", "len", "(", "locator", ")", "==", "5", "or", "len", "(", "locator", ")", "<", "4", ":", "raise", "ValueError", "if", "ord", "(", "locator"...
converts Maidenhead locator in the corresponding WGS84 coordinates Args: locator (string): Locator, either 4 or 6 characters Returns: tuple (float, float): Latitude, Longitude Raises: ValueError: When called with wrong or invalid input arg TypeError: When arg is not a string Example: The following example converts a Maidenhead locator into Latitude and Longitude >>> from pyhamtools.locator import locator_to_latlong >>> latitude, longitude = locator_to_latlong("JN48QM") >>> print latitude, longitude 48.5208333333 9.375 Note: Latitude (negative = West, positive = East) Longitude (negative = South, positive = North)
[ "converts", "Maidenhead", "locator", "in", "the", "corresponding", "WGS84", "coordinates" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/locator.py#L57-L125
train
dh1tw/pyhamtools
pyhamtools/locator.py
calculate_distance
def calculate_distance(locator1, locator2): """calculates the (shortpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in km Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the distance between two Maidenhead locators in km >>> from pyhamtools.locator import calculate_distance >>> calculate_distance("JN48QM", "QF67bf") 16466.413 """ R = 6371 #earh radius lat1, long1 = locator_to_latlong(locator1) lat2, long2 = locator_to_latlong(locator2) d_lat = radians(lat2) - radians(lat1) d_long = radians(long2) - radians(long1) r_lat1 = radians(lat1) r_long1 = radians(long1) r_lat2 = radians(lat2) r_long2 = radians(long2) a = sin(d_lat/2) * sin(d_lat/2) + cos(r_lat1) * cos(r_lat2) * sin(d_long/2) * sin(d_long/2) c = 2 * atan2(sqrt(a), sqrt(1-a)) d = R * c #distance in km return d;
python
def calculate_distance(locator1, locator2): """calculates the (shortpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in km Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the distance between two Maidenhead locators in km >>> from pyhamtools.locator import calculate_distance >>> calculate_distance("JN48QM", "QF67bf") 16466.413 """ R = 6371 #earh radius lat1, long1 = locator_to_latlong(locator1) lat2, long2 = locator_to_latlong(locator2) d_lat = radians(lat2) - radians(lat1) d_long = radians(long2) - radians(long1) r_lat1 = radians(lat1) r_long1 = radians(long1) r_lat2 = radians(lat2) r_long2 = radians(long2) a = sin(d_lat/2) * sin(d_lat/2) + cos(r_lat1) * cos(r_lat2) * sin(d_long/2) * sin(d_long/2) c = 2 * atan2(sqrt(a), sqrt(1-a)) d = R * c #distance in km return d;
[ "def", "calculate_distance", "(", "locator1", ",", "locator2", ")", ":", "R", "=", "6371", "#earh radius", "lat1", ",", "long1", "=", "locator_to_latlong", "(", "locator1", ")", "lat2", ",", "long2", "=", "locator_to_latlong", "(", "locator2", ")", "d_lat", ...
calculates the (shortpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in km Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the distance between two Maidenhead locators in km >>> from pyhamtools.locator import calculate_distance >>> calculate_distance("JN48QM", "QF67bf") 16466.413
[ "calculates", "the", "(", "shortpath", ")", "distance", "between", "two", "Maidenhead", "locators" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/locator.py#L128-L167
train
dh1tw/pyhamtools
pyhamtools/locator.py
calculate_distance_longpath
def calculate_distance_longpath(locator1, locator2): """calculates the (longpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in km Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the longpath distance between two Maidenhead locators in km >>> from pyhamtools.locator import calculate_distance_longpath >>> calculate_distance_longpath("JN48QM", "QF67bf") 23541.5867 """ c = 40008 #[km] earth circumference sp = calculate_distance(locator1, locator2) return c - sp
python
def calculate_distance_longpath(locator1, locator2): """calculates the (longpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in km Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the longpath distance between two Maidenhead locators in km >>> from pyhamtools.locator import calculate_distance_longpath >>> calculate_distance_longpath("JN48QM", "QF67bf") 23541.5867 """ c = 40008 #[km] earth circumference sp = calculate_distance(locator1, locator2) return c - sp
[ "def", "calculate_distance_longpath", "(", "locator1", ",", "locator2", ")", ":", "c", "=", "40008", "#[km] earth circumference", "sp", "=", "calculate_distance", "(", "locator1", ",", "locator2", ")", "return", "c", "-", "sp" ]
calculates the (longpath) distance between two Maidenhead locators Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Distance in km Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the longpath distance between two Maidenhead locators in km >>> from pyhamtools.locator import calculate_distance_longpath >>> calculate_distance_longpath("JN48QM", "QF67bf") 23541.5867
[ "calculates", "the", "(", "longpath", ")", "distance", "between", "two", "Maidenhead", "locators" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/locator.py#L170-L196
train
dh1tw/pyhamtools
pyhamtools/locator.py
calculate_heading
def calculate_heading(locator1, locator2): """calculates the heading from the first to the second locator Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Heading in deg Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the heading from locator1 to locator2 >>> from pyhamtools.locator import calculate_heading >>> calculate_heading("JN48QM", "QF67bf") 74.3136 """ lat1, long1 = locator_to_latlong(locator1) lat2, long2 = locator_to_latlong(locator2) r_lat1 = radians(lat1) r_lon1 = radians(long1) r_lat2 = radians(lat2) r_lon2 = radians(long2) d_lon = radians(long2 - long1) b = atan2(sin(d_lon)*cos(r_lat2),cos(r_lat1)*sin(r_lat2)-sin(r_lat1)*cos(r_lat2)*cos(d_lon)) # bearing calc bd = degrees(b) br,bn = divmod(bd+360,360) # the bearing remainder and final bearing return bn
python
def calculate_heading(locator1, locator2): """calculates the heading from the first to the second locator Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Heading in deg Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the heading from locator1 to locator2 >>> from pyhamtools.locator import calculate_heading >>> calculate_heading("JN48QM", "QF67bf") 74.3136 """ lat1, long1 = locator_to_latlong(locator1) lat2, long2 = locator_to_latlong(locator2) r_lat1 = radians(lat1) r_lon1 = radians(long1) r_lat2 = radians(lat2) r_lon2 = radians(long2) d_lon = radians(long2 - long1) b = atan2(sin(d_lon)*cos(r_lat2),cos(r_lat1)*sin(r_lat2)-sin(r_lat1)*cos(r_lat2)*cos(d_lon)) # bearing calc bd = degrees(b) br,bn = divmod(bd+360,360) # the bearing remainder and final bearing return bn
[ "def", "calculate_heading", "(", "locator1", ",", "locator2", ")", ":", "lat1", ",", "long1", "=", "locator_to_latlong", "(", "locator1", ")", "lat2", ",", "long2", "=", "locator_to_latlong", "(", "locator2", ")", "r_lat1", "=", "radians", "(", "lat1", ")", ...
calculates the heading from the first to the second locator Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Heading in deg Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the heading from locator1 to locator2 >>> from pyhamtools.locator import calculate_heading >>> calculate_heading("JN48QM", "QF67bf") 74.3136
[ "calculates", "the", "heading", "from", "the", "first", "to", "the", "second", "locator" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/locator.py#L199-L237
train
dh1tw/pyhamtools
pyhamtools/locator.py
calculate_heading_longpath
def calculate_heading_longpath(locator1, locator2): """calculates the heading from the first to the second locator (long path) Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Long path heading in deg Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the long path heading from locator1 to locator2 >>> from pyhamtools.locator import calculate_heading_longpath >>> calculate_heading_longpath("JN48QM", "QF67bf") 254.3136 """ heading = calculate_heading(locator1, locator2) lp = (heading + 180)%360 return lp
python
def calculate_heading_longpath(locator1, locator2): """calculates the heading from the first to the second locator (long path) Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Long path heading in deg Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the long path heading from locator1 to locator2 >>> from pyhamtools.locator import calculate_heading_longpath >>> calculate_heading_longpath("JN48QM", "QF67bf") 254.3136 """ heading = calculate_heading(locator1, locator2) lp = (heading + 180)%360 return lp
[ "def", "calculate_heading_longpath", "(", "locator1", ",", "locator2", ")", ":", "heading", "=", "calculate_heading", "(", "locator1", ",", "locator2", ")", "lp", "=", "(", "heading", "+", "180", ")", "%", "360", "return", "lp" ]
calculates the heading from the first to the second locator (long path) Args: locator1 (string): Locator, either 4 or 6 characters locator2 (string): Locator, either 4 or 6 characters Returns: float: Long path heading in deg Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the long path heading from locator1 to locator2 >>> from pyhamtools.locator import calculate_heading_longpath >>> calculate_heading_longpath("JN48QM", "QF67bf") 254.3136
[ "calculates", "the", "heading", "from", "the", "first", "to", "the", "second", "locator", "(", "long", "path", ")" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/locator.py#L239-L266
train
dh1tw/pyhamtools
pyhamtools/locator.py
calculate_sunrise_sunset
def calculate_sunrise_sunset(locator, calc_date=datetime.utcnow()): """calculates the next sunset and sunrise for a Maidenhead locator at a give date & time Args: locator1 (string): Maidenhead Locator, either 4 or 6 characters calc_date (datetime, optional): Starting datetime for the calculations (UTC) Returns: dict: Containing datetimes for morning_dawn, sunrise, evening_dawn, sunset Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the next sunrise & sunset for JN48QM on the 1./Jan/2014 >>> from pyhamtools.locator import calculate_sunrise_sunset >>> from datetime import datetime >>> import pytz >>> UTC = pytz.UTC >>> myDate = datetime(year=2014, month=1, day=1, tzinfo=UTC) >>> calculate_sunrise_sunset("JN48QM", myDate) { 'morning_dawn': datetime.datetime(2014, 1, 1, 6, 36, 51, 710524, tzinfo=<UTC>), 'sunset': datetime.datetime(2014, 1, 1, 16, 15, 23, 31016, tzinfo=<UTC>), 'evening_dawn': datetime.datetime(2014, 1, 1, 15, 38, 8, 355315, tzinfo=<UTC>), 'sunrise': datetime.datetime(2014, 1, 1, 7, 14, 6, 162063, tzinfo=<UTC>) } """ morning_dawn = None sunrise = None evening_dawn = None sunset = None latitude, longitude = locator_to_latlong(locator) if type(calc_date) != datetime: raise ValueError sun = ephem.Sun() home = ephem.Observer() home.lat = str(latitude) home.long = str(longitude) home.date = calc_date sun.compute(home) try: nextrise = home.next_rising(sun) nextset = home.next_setting(sun) home.horizon = '-6' beg_twilight = home.next_rising(sun, use_center=True) end_twilight = home.next_setting(sun, use_center=True) morning_dawn = beg_twilight.datetime() sunrise = nextrise.datetime() evening_dawn = nextset.datetime() sunset = end_twilight.datetime() #if sun never sets or rises (e.g. at polar circles) except ephem.AlwaysUpError as e: morning_dawn = None sunrise = None evening_dawn = None sunset = None except ephem.NeverUpError as e: morning_dawn = None sunrise = None evening_dawn = None sunset = None result = {} result['morning_dawn'] = morning_dawn result['sunrise'] = sunrise result['evening_dawn'] = evening_dawn result['sunset'] = sunset if morning_dawn: result['morning_dawn'] = morning_dawn.replace(tzinfo=UTC) if sunrise: result['sunrise'] = sunrise.replace(tzinfo=UTC) if evening_dawn: result['evening_dawn'] = evening_dawn.replace(tzinfo=UTC) if sunset: result['sunset'] = sunset.replace(tzinfo=UTC) return result
python
def calculate_sunrise_sunset(locator, calc_date=datetime.utcnow()): """calculates the next sunset and sunrise for a Maidenhead locator at a give date & time Args: locator1 (string): Maidenhead Locator, either 4 or 6 characters calc_date (datetime, optional): Starting datetime for the calculations (UTC) Returns: dict: Containing datetimes for morning_dawn, sunrise, evening_dawn, sunset Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the next sunrise & sunset for JN48QM on the 1./Jan/2014 >>> from pyhamtools.locator import calculate_sunrise_sunset >>> from datetime import datetime >>> import pytz >>> UTC = pytz.UTC >>> myDate = datetime(year=2014, month=1, day=1, tzinfo=UTC) >>> calculate_sunrise_sunset("JN48QM", myDate) { 'morning_dawn': datetime.datetime(2014, 1, 1, 6, 36, 51, 710524, tzinfo=<UTC>), 'sunset': datetime.datetime(2014, 1, 1, 16, 15, 23, 31016, tzinfo=<UTC>), 'evening_dawn': datetime.datetime(2014, 1, 1, 15, 38, 8, 355315, tzinfo=<UTC>), 'sunrise': datetime.datetime(2014, 1, 1, 7, 14, 6, 162063, tzinfo=<UTC>) } """ morning_dawn = None sunrise = None evening_dawn = None sunset = None latitude, longitude = locator_to_latlong(locator) if type(calc_date) != datetime: raise ValueError sun = ephem.Sun() home = ephem.Observer() home.lat = str(latitude) home.long = str(longitude) home.date = calc_date sun.compute(home) try: nextrise = home.next_rising(sun) nextset = home.next_setting(sun) home.horizon = '-6' beg_twilight = home.next_rising(sun, use_center=True) end_twilight = home.next_setting(sun, use_center=True) morning_dawn = beg_twilight.datetime() sunrise = nextrise.datetime() evening_dawn = nextset.datetime() sunset = end_twilight.datetime() #if sun never sets or rises (e.g. at polar circles) except ephem.AlwaysUpError as e: morning_dawn = None sunrise = None evening_dawn = None sunset = None except ephem.NeverUpError as e: morning_dawn = None sunrise = None evening_dawn = None sunset = None result = {} result['morning_dawn'] = morning_dawn result['sunrise'] = sunrise result['evening_dawn'] = evening_dawn result['sunset'] = sunset if morning_dawn: result['morning_dawn'] = morning_dawn.replace(tzinfo=UTC) if sunrise: result['sunrise'] = sunrise.replace(tzinfo=UTC) if evening_dawn: result['evening_dawn'] = evening_dawn.replace(tzinfo=UTC) if sunset: result['sunset'] = sunset.replace(tzinfo=UTC) return result
[ "def", "calculate_sunrise_sunset", "(", "locator", ",", "calc_date", "=", "datetime", ".", "utcnow", "(", ")", ")", ":", "morning_dawn", "=", "None", "sunrise", "=", "None", "evening_dawn", "=", "None", "sunset", "=", "None", "latitude", ",", "longitude", "=...
calculates the next sunset and sunrise for a Maidenhead locator at a give date & time Args: locator1 (string): Maidenhead Locator, either 4 or 6 characters calc_date (datetime, optional): Starting datetime for the calculations (UTC) Returns: dict: Containing datetimes for morning_dawn, sunrise, evening_dawn, sunset Raises: ValueError: When called with wrong or invalid input arg AttributeError: When args are not a string Example: The following calculates the next sunrise & sunset for JN48QM on the 1./Jan/2014 >>> from pyhamtools.locator import calculate_sunrise_sunset >>> from datetime import datetime >>> import pytz >>> UTC = pytz.UTC >>> myDate = datetime(year=2014, month=1, day=1, tzinfo=UTC) >>> calculate_sunrise_sunset("JN48QM", myDate) { 'morning_dawn': datetime.datetime(2014, 1, 1, 6, 36, 51, 710524, tzinfo=<UTC>), 'sunset': datetime.datetime(2014, 1, 1, 16, 15, 23, 31016, tzinfo=<UTC>), 'evening_dawn': datetime.datetime(2014, 1, 1, 15, 38, 8, 355315, tzinfo=<UTC>), 'sunrise': datetime.datetime(2014, 1, 1, 7, 14, 6, 162063, tzinfo=<UTC>) }
[ "calculates", "the", "next", "sunset", "and", "sunrise", "for", "a", "Maidenhead", "locator", "at", "a", "give", "date", "&", "time" ]
ee7e4b8732e23c298da10e07163748156c16d0fa
https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/locator.py#L268-L358
train
AustralianSynchrotron/lightflow
lightflow/queue/pickle.py
cloudpickle_dumps
def cloudpickle_dumps(obj, dumper=cloudpickle.dumps): """ Encode Python objects into a byte stream using cloudpickle. """ return dumper(obj, protocol=serialization.pickle_protocol)
python
def cloudpickle_dumps(obj, dumper=cloudpickle.dumps): """ Encode Python objects into a byte stream using cloudpickle. """ return dumper(obj, protocol=serialization.pickle_protocol)
[ "def", "cloudpickle_dumps", "(", "obj", ",", "dumper", "=", "cloudpickle", ".", "dumps", ")", ":", "return", "dumper", "(", "obj", ",", "protocol", "=", "serialization", ".", "pickle_protocol", ")" ]
Encode Python objects into a byte stream using cloudpickle.
[ "Encode", "Python", "objects", "into", "a", "byte", "stream", "using", "cloudpickle", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/pickle.py#L18-L20
train
AustralianSynchrotron/lightflow
lightflow/queue/pickle.py
patch_celery
def patch_celery(): """ Monkey patch Celery to use cloudpickle instead of pickle. """ registry = serialization.registry serialization.pickle = cloudpickle registry.unregister('pickle') registry.register('pickle', cloudpickle_dumps, cloudpickle_loads, content_type='application/x-python-serialize', content_encoding='binary') import celery.worker as worker import celery.concurrency.asynpool as asynpool worker.state.pickle = cloudpickle asynpool._pickle = cloudpickle import billiard.common billiard.common.pickle = cloudpickle billiard.common.pickle_dumps = cloudpickle_dumps billiard.common.pickle_loads = cloudpickle_loads
python
def patch_celery(): """ Monkey patch Celery to use cloudpickle instead of pickle. """ registry = serialization.registry serialization.pickle = cloudpickle registry.unregister('pickle') registry.register('pickle', cloudpickle_dumps, cloudpickle_loads, content_type='application/x-python-serialize', content_encoding='binary') import celery.worker as worker import celery.concurrency.asynpool as asynpool worker.state.pickle = cloudpickle asynpool._pickle = cloudpickle import billiard.common billiard.common.pickle = cloudpickle billiard.common.pickle_dumps = cloudpickle_dumps billiard.common.pickle_loads = cloudpickle_loads
[ "def", "patch_celery", "(", ")", ":", "registry", "=", "serialization", ".", "registry", "serialization", ".", "pickle", "=", "cloudpickle", "registry", ".", "unregister", "(", "'pickle'", ")", "registry", ".", "register", "(", "'pickle'", ",", "cloudpickle_dump...
Monkey patch Celery to use cloudpickle instead of pickle.
[ "Monkey", "patch", "Celery", "to", "use", "cloudpickle", "instead", "of", "pickle", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/queue/pickle.py#L23-L40
train
AustralianSynchrotron/lightflow
lightflow/models/signal.py
SignalConnection.connect
def connect(self): """ Connects to the redis database. """ self._connection = StrictRedis( host=self._host, port=self._port, db=self._database, password=self._password)
python
def connect(self): """ Connects to the redis database. """ self._connection = StrictRedis( host=self._host, port=self._port, db=self._database, password=self._password)
[ "def", "connect", "(", "self", ")", ":", "self", ".", "_connection", "=", "StrictRedis", "(", "host", "=", "self", ".", "_host", ",", "port", "=", "self", ".", "_port", ",", "db", "=", "self", ".", "_database", ",", "password", "=", "self", ".", "_...
Connects to the redis database.
[ "Connects", "to", "the", "redis", "database", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/signal.py#L47-L53
train
AustralianSynchrotron/lightflow
lightflow/models/signal.py
Server.receive
def receive(self): """ Returns a single request. Takes the first request from the list of requests and returns it. If the list is empty, None is returned. Returns: Response: If a new request is available a Request object is returned, otherwise None is returned. """ pickled_request = self._connection.connection.lpop(self._request_key) return pickle.loads(pickled_request) if pickled_request is not None else None
python
def receive(self): """ Returns a single request. Takes the first request from the list of requests and returns it. If the list is empty, None is returned. Returns: Response: If a new request is available a Request object is returned, otherwise None is returned. """ pickled_request = self._connection.connection.lpop(self._request_key) return pickle.loads(pickled_request) if pickled_request is not None else None
[ "def", "receive", "(", "self", ")", ":", "pickled_request", "=", "self", ".", "_connection", ".", "connection", ".", "lpop", "(", "self", ".", "_request_key", ")", "return", "pickle", ".", "loads", "(", "pickled_request", ")", "if", "pickled_request", "is", ...
Returns a single request. Takes the first request from the list of requests and returns it. If the list is empty, None is returned. Returns: Response: If a new request is available a Request object is returned, otherwise None is returned.
[ "Returns", "a", "single", "request", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/signal.py#L118-L129
train
AustralianSynchrotron/lightflow
lightflow/models/signal.py
Server.send
def send(self, response): """ Send a response back to the client that issued a request. Args: response (Response): Reference to the response object that should be sent. """ self._connection.connection.set('{}:{}'.format(SIGNAL_REDIS_PREFIX, response.uid), pickle.dumps(response))
python
def send(self, response): """ Send a response back to the client that issued a request. Args: response (Response): Reference to the response object that should be sent. """ self._connection.connection.set('{}:{}'.format(SIGNAL_REDIS_PREFIX, response.uid), pickle.dumps(response))
[ "def", "send", "(", "self", ",", "response", ")", ":", "self", ".", "_connection", ".", "connection", ".", "set", "(", "'{}:{}'", ".", "format", "(", "SIGNAL_REDIS_PREFIX", ",", "response", ".", "uid", ")", ",", "pickle", ".", "dumps", "(", "response", ...
Send a response back to the client that issued a request. Args: response (Response): Reference to the response object that should be sent.
[ "Send", "a", "response", "back", "to", "the", "client", "that", "issued", "a", "request", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/signal.py#L131-L138
train
AustralianSynchrotron/lightflow
lightflow/models/signal.py
Server.restore
def restore(self, request): """ Push the request back onto the queue. Args: request (Request): Reference to a request object that should be pushed back onto the request queue. """ self._connection.connection.rpush(self._request_key, pickle.dumps(request))
python
def restore(self, request): """ Push the request back onto the queue. Args: request (Request): Reference to a request object that should be pushed back onto the request queue. """ self._connection.connection.rpush(self._request_key, pickle.dumps(request))
[ "def", "restore", "(", "self", ",", "request", ")", ":", "self", ".", "_connection", ".", "connection", ".", "rpush", "(", "self", ".", "_request_key", ",", "pickle", ".", "dumps", "(", "request", ")", ")" ]
Push the request back onto the queue. Args: request (Request): Reference to a request object that should be pushed back onto the request queue.
[ "Push", "the", "request", "back", "onto", "the", "queue", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/signal.py#L140-L147
train
AustralianSynchrotron/lightflow
lightflow/models/signal.py
Client.send
def send(self, request): """ Send a request to the server and wait for its response. Args: request (Request): Reference to a request object that is sent to the server. Returns: Response: The response from the server to the request. """ self._connection.connection.rpush(self._request_key, pickle.dumps(request)) resp_key = '{}:{}'.format(SIGNAL_REDIS_PREFIX, request.uid) while True: if self._connection.polling_time > 0.0: sleep(self._connection.polling_time) response_data = self._connection.connection.get(resp_key) if response_data is not None: self._connection.connection.delete(resp_key) break return pickle.loads(response_data)
python
def send(self, request): """ Send a request to the server and wait for its response. Args: request (Request): Reference to a request object that is sent to the server. Returns: Response: The response from the server to the request. """ self._connection.connection.rpush(self._request_key, pickle.dumps(request)) resp_key = '{}:{}'.format(SIGNAL_REDIS_PREFIX, request.uid) while True: if self._connection.polling_time > 0.0: sleep(self._connection.polling_time) response_data = self._connection.connection.get(resp_key) if response_data is not None: self._connection.connection.delete(resp_key) break return pickle.loads(response_data)
[ "def", "send", "(", "self", ",", "request", ")", ":", "self", ".", "_connection", ".", "connection", ".", "rpush", "(", "self", ".", "_request_key", ",", "pickle", ".", "dumps", "(", "request", ")", ")", "resp_key", "=", "'{}:{}'", ".", "format", "(", ...
Send a request to the server and wait for its response. Args: request (Request): Reference to a request object that is sent to the server. Returns: Response: The response from the server to the request.
[ "Send", "a", "request", "to", "the", "server", "and", "wait", "for", "its", "response", "." ]
dc53dbc1d961e20fb144273baca258060705c03e
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/signal.py#L171-L192
train
krzysiekfonal/grammaregex
grammaregex/grammaregex.py
verify_pattern
def verify_pattern(pattern): """Verifies if pattern for matching and finding fulfill expected structure. :param pattern: string pattern to verify :return: True if pattern has proper syntax, False otherwise """ regex = re.compile("^!?[a-zA-Z]+$|[*]{1,2}$") def __verify_pattern__(__pattern__): if not __pattern__: return False elif __pattern__[0] == "!": return __verify_pattern__(__pattern__[1:]) elif __pattern__[0] == "[" and __pattern__[-1] == "]": return all(__verify_pattern__(p) for p in __pattern__[1:-1].split(",")) else: return regex.match(__pattern__) return all(__verify_pattern__(p) for p in pattern.split("/"))
python
def verify_pattern(pattern): """Verifies if pattern for matching and finding fulfill expected structure. :param pattern: string pattern to verify :return: True if pattern has proper syntax, False otherwise """ regex = re.compile("^!?[a-zA-Z]+$|[*]{1,2}$") def __verify_pattern__(__pattern__): if not __pattern__: return False elif __pattern__[0] == "!": return __verify_pattern__(__pattern__[1:]) elif __pattern__[0] == "[" and __pattern__[-1] == "]": return all(__verify_pattern__(p) for p in __pattern__[1:-1].split(",")) else: return regex.match(__pattern__) return all(__verify_pattern__(p) for p in pattern.split("/"))
[ "def", "verify_pattern", "(", "pattern", ")", ":", "regex", "=", "re", ".", "compile", "(", "\"^!?[a-zA-Z]+$|[*]{1,2}$\"", ")", "def", "__verify_pattern__", "(", "__pattern__", ")", ":", "if", "not", "__pattern__", ":", "return", "False", "elif", "__pattern__", ...
Verifies if pattern for matching and finding fulfill expected structure. :param pattern: string pattern to verify :return: True if pattern has proper syntax, False otherwise
[ "Verifies", "if", "pattern", "for", "matching", "and", "finding", "fulfill", "expected", "structure", "." ]
5212075433fc5201da628acf09cdf5bf73aa1ad0
https://github.com/krzysiekfonal/grammaregex/blob/5212075433fc5201da628acf09cdf5bf73aa1ad0/grammaregex/grammaregex.py#L40-L60
train
krzysiekfonal/grammaregex
grammaregex/grammaregex.py
print_tree
def print_tree(sent, token_attr): """Prints sentences tree as string using token_attr from token(like pos_, tag_ etc.) :param sent: sentence to print :param token_attr: choosen attr to present for tokens(e.g. dep_, pos_, tag_, ...) """ def __print_sent__(token, attr): print("{", end=" ") [__print_sent__(t, attr) for t in token.lefts] print(u"%s->%s(%s)" % (token,token.dep_,token.tag_ if not attr else getattr(token, attr)), end="") [__print_sent__(t, attr) for t in token.rights] print("}", end=" ") return __print_sent__(sent.root, token_attr)
python
def print_tree(sent, token_attr): """Prints sentences tree as string using token_attr from token(like pos_, tag_ etc.) :param sent: sentence to print :param token_attr: choosen attr to present for tokens(e.g. dep_, pos_, tag_, ...) """ def __print_sent__(token, attr): print("{", end=" ") [__print_sent__(t, attr) for t in token.lefts] print(u"%s->%s(%s)" % (token,token.dep_,token.tag_ if not attr else getattr(token, attr)), end="") [__print_sent__(t, attr) for t in token.rights] print("}", end=" ") return __print_sent__(sent.root, token_attr)
[ "def", "print_tree", "(", "sent", ",", "token_attr", ")", ":", "def", "__print_sent__", "(", "token", ",", "attr", ")", ":", "print", "(", "\"{\"", ",", "end", "=", "\" \"", ")", "[", "__print_sent__", "(", "t", ",", "attr", ")", "for", "t", "in", ...
Prints sentences tree as string using token_attr from token(like pos_, tag_ etc.) :param sent: sentence to print :param token_attr: choosen attr to present for tokens(e.g. dep_, pos_, tag_, ...)
[ "Prints", "sentences", "tree", "as", "string", "using", "token_attr", "from", "token", "(", "like", "pos_", "tag_", "etc", ".", ")" ]
5212075433fc5201da628acf09cdf5bf73aa1ad0
https://github.com/krzysiekfonal/grammaregex/blob/5212075433fc5201da628acf09cdf5bf73aa1ad0/grammaregex/grammaregex.py#L63-L76
train
krzysiekfonal/grammaregex
grammaregex/grammaregex.py
match_tree
def match_tree(sentence, pattern): """Matches given sentence with provided pattern. :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which sentence will be compared :return: True if sentence match to pattern, False otherwise :raises: PatternSyntaxException: if pattern has wrong syntax """ if not verify_pattern(pattern): raise PatternSyntaxException(pattern) def _match_node(t, p): pat_node = p.pop(0) if p else "" return not pat_node or (_match_token(t, pat_node, False) and _match_edge(t.children,p)) def _match_edge(edges,p): pat_edge = p.pop(0) if p else "" if not pat_edge: return True elif not edges: return False else: for (t) in edges: if (_match_token(t, pat_edge, True)) and _match_node(t, list(p)): return True elif pat_edge == "**" and _match_edge(t.children, ["**"] + p): return True return False return _match_node(sentence.root, pattern.split("/"))
python
def match_tree(sentence, pattern): """Matches given sentence with provided pattern. :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which sentence will be compared :return: True if sentence match to pattern, False otherwise :raises: PatternSyntaxException: if pattern has wrong syntax """ if not verify_pattern(pattern): raise PatternSyntaxException(pattern) def _match_node(t, p): pat_node = p.pop(0) if p else "" return not pat_node or (_match_token(t, pat_node, False) and _match_edge(t.children,p)) def _match_edge(edges,p): pat_edge = p.pop(0) if p else "" if not pat_edge: return True elif not edges: return False else: for (t) in edges: if (_match_token(t, pat_edge, True)) and _match_node(t, list(p)): return True elif pat_edge == "**" and _match_edge(t.children, ["**"] + p): return True return False return _match_node(sentence.root, pattern.split("/"))
[ "def", "match_tree", "(", "sentence", ",", "pattern", ")", ":", "if", "not", "verify_pattern", "(", "pattern", ")", ":", "raise", "PatternSyntaxException", "(", "pattern", ")", "def", "_match_node", "(", "t", ",", "p", ")", ":", "pat_node", "=", "p", "."...
Matches given sentence with provided pattern. :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which sentence will be compared :return: True if sentence match to pattern, False otherwise :raises: PatternSyntaxException: if pattern has wrong syntax
[ "Matches", "given", "sentence", "with", "provided", "pattern", "." ]
5212075433fc5201da628acf09cdf5bf73aa1ad0
https://github.com/krzysiekfonal/grammaregex/blob/5212075433fc5201da628acf09cdf5bf73aa1ad0/grammaregex/grammaregex.py#L79-L111
train
krzysiekfonal/grammaregex
grammaregex/grammaregex.py
find_tokens
def find_tokens(sentence, pattern): """Find all tokens from parts of sentence fitted to pattern, being on the end of matched sub-tree(of sentence) :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which sentence will be compared :return: Spacy tokens(see: http://spacy.io/docs/#token) found at the end of pattern if whole pattern match :raises: PatternSyntaxException: if pattern has wrong syntax """ if not verify_pattern(pattern): raise PatternSyntaxException(pattern) def _match_node(t, p, tokens): pat_node = p.pop(0) if p else "" res = not pat_node or (_match_token(t, pat_node, False) and (not p or _match_edge(t.children, p, tokens))) if res and not p: tokens.append(t) return res def _match_edge(edges,p, tokens): pat_edge = p.pop(0) if p else "" if pat_edge: for (t) in edges: if _match_token(t, pat_edge, True): _match_node(t, list(p), tokens) if pat_edge == "**": _match_edge(t.children, ["**"] + p, tokens) result_tokens = [] _match_node(sentence.root, pattern.split("/"), result_tokens) return result_tokens
python
def find_tokens(sentence, pattern): """Find all tokens from parts of sentence fitted to pattern, being on the end of matched sub-tree(of sentence) :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which sentence will be compared :return: Spacy tokens(see: http://spacy.io/docs/#token) found at the end of pattern if whole pattern match :raises: PatternSyntaxException: if pattern has wrong syntax """ if not verify_pattern(pattern): raise PatternSyntaxException(pattern) def _match_node(t, p, tokens): pat_node = p.pop(0) if p else "" res = not pat_node or (_match_token(t, pat_node, False) and (not p or _match_edge(t.children, p, tokens))) if res and not p: tokens.append(t) return res def _match_edge(edges,p, tokens): pat_edge = p.pop(0) if p else "" if pat_edge: for (t) in edges: if _match_token(t, pat_edge, True): _match_node(t, list(p), tokens) if pat_edge == "**": _match_edge(t.children, ["**"] + p, tokens) result_tokens = [] _match_node(sentence.root, pattern.split("/"), result_tokens) return result_tokens
[ "def", "find_tokens", "(", "sentence", ",", "pattern", ")", ":", "if", "not", "verify_pattern", "(", "pattern", ")", ":", "raise", "PatternSyntaxException", "(", "pattern", ")", "def", "_match_node", "(", "t", ",", "p", ",", "tokens", ")", ":", "pat_node",...
Find all tokens from parts of sentence fitted to pattern, being on the end of matched sub-tree(of sentence) :param sentence: sentence from Spacy(see: http://spacy.io/docs/#doc-spans-sents) representing complete statement :param pattern: pattern to which sentence will be compared :return: Spacy tokens(see: http://spacy.io/docs/#token) found at the end of pattern if whole pattern match :raises: PatternSyntaxException: if pattern has wrong syntax
[ "Find", "all", "tokens", "from", "parts", "of", "sentence", "fitted", "to", "pattern", "being", "on", "the", "end", "of", "matched", "sub", "-", "tree", "(", "of", "sentence", ")" ]
5212075433fc5201da628acf09cdf5bf73aa1ad0
https://github.com/krzysiekfonal/grammaregex/blob/5212075433fc5201da628acf09cdf5bf73aa1ad0/grammaregex/grammaregex.py#L114-L146
train
pwwang/liquidpy
liquid/__init__.py
Liquid.split
def split (s, delimter, trim = True, limit = 0): # pragma: no cover """ Split a string using a single-character delimter @params: `s`: the string `delimter`: the single-character delimter `trim`: whether to trim each part. Default: True @examples: ```python ret = split("'a,b',c", ",") # ret == ["'a,b'", "c"] # ',' inside quotes will be recognized. ``` @returns: The list of substrings """ ret = [] special1 = ['(', ')', '[', ']', '{', '}'] special2 = ['\'', '"'] special3 = '\\' flags1 = [0, 0, 0] flags2 = [False, False] flags3 = False start = 0 nlim = 0 for i, c in enumerate(s): if c == special3: # next char is escaped flags3 = not flags3 elif not flags3: # no escape if c in special1: index = special1.index(c) if index % 2 == 0: flags1[int(index/2)] += 1 else: flags1[int(index/2)] -= 1 elif c in special2: index = special2.index(c) flags2[index] = not flags2[index] elif c == delimter and not any(flags1) and not any(flags2): r = s[start:i] if trim: r = r.strip() ret.append(r) start = i + 1 nlim = nlim + 1 if limit and nlim >= limit: break else: # escaping closed flags3 = False r = s[start:] if trim: r = r.strip() ret.append(r) return ret
python
def split (s, delimter, trim = True, limit = 0): # pragma: no cover """ Split a string using a single-character delimter @params: `s`: the string `delimter`: the single-character delimter `trim`: whether to trim each part. Default: True @examples: ```python ret = split("'a,b',c", ",") # ret == ["'a,b'", "c"] # ',' inside quotes will be recognized. ``` @returns: The list of substrings """ ret = [] special1 = ['(', ')', '[', ']', '{', '}'] special2 = ['\'', '"'] special3 = '\\' flags1 = [0, 0, 0] flags2 = [False, False] flags3 = False start = 0 nlim = 0 for i, c in enumerate(s): if c == special3: # next char is escaped flags3 = not flags3 elif not flags3: # no escape if c in special1: index = special1.index(c) if index % 2 == 0: flags1[int(index/2)] += 1 else: flags1[int(index/2)] -= 1 elif c in special2: index = special2.index(c) flags2[index] = not flags2[index] elif c == delimter and not any(flags1) and not any(flags2): r = s[start:i] if trim: r = r.strip() ret.append(r) start = i + 1 nlim = nlim + 1 if limit and nlim >= limit: break else: # escaping closed flags3 = False r = s[start:] if trim: r = r.strip() ret.append(r) return ret
[ "def", "split", "(", "s", ",", "delimter", ",", "trim", "=", "True", ",", "limit", "=", "0", ")", ":", "# pragma: no cover", "ret", "=", "[", "]", "special1", "=", "[", "'('", ",", "')'", ",", "'['", ",", "']'", ",", "'{'", ",", "'}'", "]", "sp...
Split a string using a single-character delimter @params: `s`: the string `delimter`: the single-character delimter `trim`: whether to trim each part. Default: True @examples: ```python ret = split("'a,b',c", ",") # ret == ["'a,b'", "c"] # ',' inside quotes will be recognized. ``` @returns: The list of substrings
[ "Split", "a", "string", "using", "a", "single", "-", "character", "delimter" ]
f422af836740b7facfbc6b89e5162a17d619dd07
https://github.com/pwwang/liquidpy/blob/f422af836740b7facfbc6b89e5162a17d619dd07/liquid/__init__.py#L367-L421
train
pwwang/liquidpy
liquid/__init__.py
Liquid.render
def render(self, **context): """ Render this template by applying it to `context`. @params: `context`: a dictionary of values to use in this rendering. @returns: The rendered string """ # Make the complete context we'll use. localns = self.envs.copy() localns.update(context) try: exec(str(self.code), None, localns) return localns[Liquid.COMPLIED_RENDERED_STR] except Exception: stacks = list(reversed(traceback.format_exc().splitlines())) for stack in stacks: stack = stack.strip() if stack.startswith('File "<string>"'): lineno = int(stack.split(', ')[1].split()[-1]) source = [] if 'NameError:' in stacks[0]: source.append('Do you forget to provide the data?') import math source.append('\nCompiled source (use debug mode to see full source):') source.append('---------------------------------------------------') nlines = len(self.code.codes) nbit = int(math.log(nlines, 10)) + 3 for i, line in enumerate(self.code.codes): if i - 7 > lineno or i + 9 < lineno: continue if i + 1 != lineno: source.append(' ' + (str(i+1) + '.').ljust(nbit) + str(line).rstrip()) else: source.append('* ' + (str(i+1) + '.').ljust(nbit) + str(line).rstrip()) raise LiquidRenderError( stacks[0], repr(self.code.codes[lineno - 1]) + '\n' + '\n'.join(source) + '\n\nPREVIOUS EXCEPTION:\n------------------\n' + '\n'.join(stacks) + '\n' + '\nCONTEXT:\n------------------\n' + '\n'.join( ' ' + key + ': ' + str(val) for key, val in localns.items() if not key.startswith('_liquid_') and not key.startswith('__') ) + '\n' ) raise
python
def render(self, **context): """ Render this template by applying it to `context`. @params: `context`: a dictionary of values to use in this rendering. @returns: The rendered string """ # Make the complete context we'll use. localns = self.envs.copy() localns.update(context) try: exec(str(self.code), None, localns) return localns[Liquid.COMPLIED_RENDERED_STR] except Exception: stacks = list(reversed(traceback.format_exc().splitlines())) for stack in stacks: stack = stack.strip() if stack.startswith('File "<string>"'): lineno = int(stack.split(', ')[1].split()[-1]) source = [] if 'NameError:' in stacks[0]: source.append('Do you forget to provide the data?') import math source.append('\nCompiled source (use debug mode to see full source):') source.append('---------------------------------------------------') nlines = len(self.code.codes) nbit = int(math.log(nlines, 10)) + 3 for i, line in enumerate(self.code.codes): if i - 7 > lineno or i + 9 < lineno: continue if i + 1 != lineno: source.append(' ' + (str(i+1) + '.').ljust(nbit) + str(line).rstrip()) else: source.append('* ' + (str(i+1) + '.').ljust(nbit) + str(line).rstrip()) raise LiquidRenderError( stacks[0], repr(self.code.codes[lineno - 1]) + '\n' + '\n'.join(source) + '\n\nPREVIOUS EXCEPTION:\n------------------\n' + '\n'.join(stacks) + '\n' + '\nCONTEXT:\n------------------\n' + '\n'.join( ' ' + key + ': ' + str(val) for key, val in localns.items() if not key.startswith('_liquid_') and not key.startswith('__') ) + '\n' ) raise
[ "def", "render", "(", "self", ",", "*", "*", "context", ")", ":", "# Make the complete context we'll use.", "localns", "=", "self", ".", "envs", ".", "copy", "(", ")", "localns", ".", "update", "(", "context", ")", "try", ":", "exec", "(", "str", "(", ...
Render this template by applying it to `context`. @params: `context`: a dictionary of values to use in this rendering. @returns: The rendered string
[ "Render", "this", "template", "by", "applying", "it", "to", "context", "." ]
f422af836740b7facfbc6b89e5162a17d619dd07
https://github.com/pwwang/liquidpy/blob/f422af836740b7facfbc6b89e5162a17d619dd07/liquid/__init__.py#L575-L624
train
pwwang/liquidpy
liquid/builder.py
LiquidCode.addLine
def addLine(self, line): """ Add a line of source to the code. Indentation and newline will be added for you, don't provide them. @params: `line`: The line to add """ if not isinstance(line, LiquidLine): line = LiquidLine(line) line.ndent = self.ndent self.codes.append(line)
python
def addLine(self, line): """ Add a line of source to the code. Indentation and newline will be added for you, don't provide them. @params: `line`: The line to add """ if not isinstance(line, LiquidLine): line = LiquidLine(line) line.ndent = self.ndent self.codes.append(line)
[ "def", "addLine", "(", "self", ",", "line", ")", ":", "if", "not", "isinstance", "(", "line", ",", "LiquidLine", ")", ":", "line", "=", "LiquidLine", "(", "line", ")", "line", ".", "ndent", "=", "self", ".", "ndent", "self", ".", "codes", ".", "app...
Add a line of source to the code. Indentation and newline will be added for you, don't provide them. @params: `line`: The line to add
[ "Add", "a", "line", "of", "source", "to", "the", "code", ".", "Indentation", "and", "newline", "will", "be", "added", "for", "you", "don", "t", "provide", "them", "." ]
f422af836740b7facfbc6b89e5162a17d619dd07
https://github.com/pwwang/liquidpy/blob/f422af836740b7facfbc6b89e5162a17d619dd07/liquid/builder.py#L57-L67
train
ManufacturaInd/python-zenlog
zenlog/__init__.py
Log.level
def level(self, lvl=None): '''Get or set the logging level.''' if not lvl: return self._lvl self._lvl = self._parse_level(lvl) self.stream.setLevel(self._lvl) logging.root.setLevel(self._lvl)
python
def level(self, lvl=None): '''Get or set the logging level.''' if not lvl: return self._lvl self._lvl = self._parse_level(lvl) self.stream.setLevel(self._lvl) logging.root.setLevel(self._lvl)
[ "def", "level", "(", "self", ",", "lvl", "=", "None", ")", ":", "if", "not", "lvl", ":", "return", "self", ".", "_lvl", "self", ".", "_lvl", "=", "self", ".", "_parse_level", "(", "lvl", ")", "self", ".", "stream", ".", "setLevel", "(", "self", "...
Get or set the logging level.
[ "Get", "or", "set", "the", "logging", "level", "." ]
8f4ddf281287c99e286b78ef2d0d949a7172ba4c
https://github.com/ManufacturaInd/python-zenlog/blob/8f4ddf281287c99e286b78ef2d0d949a7172ba4c/zenlog/__init__.py#L90-L96
train
mirumee/django-prices-openexchangerates
django_prices_openexchangerates/__init__.py
get_rate_from_db
def get_rate_from_db(currency: str) -> Decimal: """ Fetch currency conversion rate from the database """ from .models import ConversionRate try: rate = ConversionRate.objects.get_rate(currency) except ConversionRate.DoesNotExist: # noqa raise ValueError('No conversion rate for %s' % (currency, )) return rate.rate
python
def get_rate_from_db(currency: str) -> Decimal: """ Fetch currency conversion rate from the database """ from .models import ConversionRate try: rate = ConversionRate.objects.get_rate(currency) except ConversionRate.DoesNotExist: # noqa raise ValueError('No conversion rate for %s' % (currency, )) return rate.rate
[ "def", "get_rate_from_db", "(", "currency", ":", "str", ")", "->", "Decimal", ":", "from", ".", "models", "import", "ConversionRate", "try", ":", "rate", "=", "ConversionRate", ".", "objects", ".", "get_rate", "(", "currency", ")", "except", "ConversionRate", ...
Fetch currency conversion rate from the database
[ "Fetch", "currency", "conversion", "rate", "from", "the", "database" ]
3f633ad20f62dce03c526e9af93335f2b6b1a950
https://github.com/mirumee/django-prices-openexchangerates/blob/3f633ad20f62dce03c526e9af93335f2b6b1a950/django_prices_openexchangerates/__init__.py#L15-L24
train
mirumee/django-prices-openexchangerates
django_prices_openexchangerates/__init__.py
get_conversion_rate
def get_conversion_rate(from_currency: str, to_currency: str) -> Decimal: """ Get conversion rate to use in exchange """ reverse_rate = False if to_currency == BASE_CURRENCY: # Fetch exchange rate for base currency and use 1 / rate for conversion rate_currency = from_currency reverse_rate = True else: rate_currency = to_currency rate = get_rate_from_db(rate_currency) if reverse_rate: conversion_rate = Decimal(1) / rate else: conversion_rate = rate return conversion_rate
python
def get_conversion_rate(from_currency: str, to_currency: str) -> Decimal: """ Get conversion rate to use in exchange """ reverse_rate = False if to_currency == BASE_CURRENCY: # Fetch exchange rate for base currency and use 1 / rate for conversion rate_currency = from_currency reverse_rate = True else: rate_currency = to_currency rate = get_rate_from_db(rate_currency) if reverse_rate: conversion_rate = Decimal(1) / rate else: conversion_rate = rate return conversion_rate
[ "def", "get_conversion_rate", "(", "from_currency", ":", "str", ",", "to_currency", ":", "str", ")", "->", "Decimal", ":", "reverse_rate", "=", "False", "if", "to_currency", "==", "BASE_CURRENCY", ":", "# Fetch exchange rate for base currency and use 1 / rate for conversi...
Get conversion rate to use in exchange
[ "Get", "conversion", "rate", "to", "use", "in", "exchange" ]
3f633ad20f62dce03c526e9af93335f2b6b1a950
https://github.com/mirumee/django-prices-openexchangerates/blob/3f633ad20f62dce03c526e9af93335f2b6b1a950/django_prices_openexchangerates/__init__.py#L27-L44
train
mirumee/django-prices-openexchangerates
django_prices_openexchangerates/__init__.py
exchange_currency
def exchange_currency( base: T, to_currency: str, *, conversion_rate: Decimal=None) -> T: """ Exchanges Money, TaxedMoney and their ranges to the specified currency. get_rate parameter is a callable taking single argument (target currency) that returns proper conversion rate """ if base.currency == to_currency: return base if base.currency != BASE_CURRENCY and to_currency != BASE_CURRENCY: # Exchange to base currency first base = exchange_currency(base, BASE_CURRENCY) if conversion_rate is None: conversion_rate = get_conversion_rate(base.currency, to_currency) if isinstance(base, Money): return Money(base.amount * conversion_rate, currency=to_currency) if isinstance(base, MoneyRange): return MoneyRange( exchange_currency( base.start, to_currency, conversion_rate=conversion_rate), exchange_currency( base.stop, to_currency, conversion_rate=conversion_rate)) if isinstance(base, TaxedMoney): return TaxedMoney( exchange_currency( base.net, to_currency, conversion_rate=conversion_rate), exchange_currency( base.gross, to_currency, conversion_rate=conversion_rate)) if isinstance(base, TaxedMoneyRange): return TaxedMoneyRange( exchange_currency( base.start, to_currency, conversion_rate=conversion_rate), exchange_currency( base.stop, to_currency, conversion_rate=conversion_rate)) # base.currency was set but we don't know how to exchange given type raise TypeError('Unknown base for exchange_currency: %r' % (base,))
python
def exchange_currency( base: T, to_currency: str, *, conversion_rate: Decimal=None) -> T: """ Exchanges Money, TaxedMoney and their ranges to the specified currency. get_rate parameter is a callable taking single argument (target currency) that returns proper conversion rate """ if base.currency == to_currency: return base if base.currency != BASE_CURRENCY and to_currency != BASE_CURRENCY: # Exchange to base currency first base = exchange_currency(base, BASE_CURRENCY) if conversion_rate is None: conversion_rate = get_conversion_rate(base.currency, to_currency) if isinstance(base, Money): return Money(base.amount * conversion_rate, currency=to_currency) if isinstance(base, MoneyRange): return MoneyRange( exchange_currency( base.start, to_currency, conversion_rate=conversion_rate), exchange_currency( base.stop, to_currency, conversion_rate=conversion_rate)) if isinstance(base, TaxedMoney): return TaxedMoney( exchange_currency( base.net, to_currency, conversion_rate=conversion_rate), exchange_currency( base.gross, to_currency, conversion_rate=conversion_rate)) if isinstance(base, TaxedMoneyRange): return TaxedMoneyRange( exchange_currency( base.start, to_currency, conversion_rate=conversion_rate), exchange_currency( base.stop, to_currency, conversion_rate=conversion_rate)) # base.currency was set but we don't know how to exchange given type raise TypeError('Unknown base for exchange_currency: %r' % (base,))
[ "def", "exchange_currency", "(", "base", ":", "T", ",", "to_currency", ":", "str", ",", "*", ",", "conversion_rate", ":", "Decimal", "=", "None", ")", "->", "T", ":", "if", "base", ".", "currency", "==", "to_currency", ":", "return", "base", "if", "bas...
Exchanges Money, TaxedMoney and their ranges to the specified currency. get_rate parameter is a callable taking single argument (target currency) that returns proper conversion rate
[ "Exchanges", "Money", "TaxedMoney", "and", "their", "ranges", "to", "the", "specified", "currency", ".", "get_rate", "parameter", "is", "a", "callable", "taking", "single", "argument", "(", "target", "currency", ")", "that", "returns", "proper", "conversion", "r...
3f633ad20f62dce03c526e9af93335f2b6b1a950
https://github.com/mirumee/django-prices-openexchangerates/blob/3f633ad20f62dce03c526e9af93335f2b6b1a950/django_prices_openexchangerates/__init__.py#L47-L85
train
mdredze/carmen-python
carmen/resolvers/profile.py
normalize
def normalize(location_name, preserve_commas=False): """Normalize *location_name* by stripping punctuation and collapsing runs of whitespace, and return the normalized name.""" def replace(match): if preserve_commas and ',' in match.group(0): return ',' return ' ' return NORMALIZATION_RE.sub(replace, location_name).strip().lower()
python
def normalize(location_name, preserve_commas=False): """Normalize *location_name* by stripping punctuation and collapsing runs of whitespace, and return the normalized name.""" def replace(match): if preserve_commas and ',' in match.group(0): return ',' return ' ' return NORMALIZATION_RE.sub(replace, location_name).strip().lower()
[ "def", "normalize", "(", "location_name", ",", "preserve_commas", "=", "False", ")", ":", "def", "replace", "(", "match", ")", ":", "if", "preserve_commas", "and", "','", "in", "match", ".", "group", "(", "0", ")", ":", "return", "','", "return", "' '", ...
Normalize *location_name* by stripping punctuation and collapsing runs of whitespace, and return the normalized name.
[ "Normalize", "*", "location_name", "*", "by", "stripping", "punctuation", "and", "collapsing", "runs", "of", "whitespace", "and", "return", "the", "normalized", "name", "." ]
070b974222b5407f7aae2518ffbdf9df198b8e96
https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/resolvers/profile.py#L15-L22
train
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.calc_precipitation_stats
def calc_precipitation_stats(self, months=None, avg_stats=True, percentile=50): """ Calculates precipitation statistics for the cascade model while aggregating hourly observations Parameters ---------- months : Months for each seasons to be used for statistics (array of numpy array, default=1-12, e.g., [np.arange(12) + 1]) avg_stats : average statistics for all levels True/False (default=True) percentile : percentil for splitting the dataset in small and high intensities (default=50) """ if months is None: months = [np.arange(12) + 1] self.precip.months = months self.precip.stats = melodist.build_casc(self.data, months=months, avg_stats=avg_stats, percentile=percentile)
python
def calc_precipitation_stats(self, months=None, avg_stats=True, percentile=50): """ Calculates precipitation statistics for the cascade model while aggregating hourly observations Parameters ---------- months : Months for each seasons to be used for statistics (array of numpy array, default=1-12, e.g., [np.arange(12) + 1]) avg_stats : average statistics for all levels True/False (default=True) percentile : percentil for splitting the dataset in small and high intensities (default=50) """ if months is None: months = [np.arange(12) + 1] self.precip.months = months self.precip.stats = melodist.build_casc(self.data, months=months, avg_stats=avg_stats, percentile=percentile)
[ "def", "calc_precipitation_stats", "(", "self", ",", "months", "=", "None", ",", "avg_stats", "=", "True", ",", "percentile", "=", "50", ")", ":", "if", "months", "is", "None", ":", "months", "=", "[", "np", ".", "arange", "(", "12", ")", "+", "1", ...
Calculates precipitation statistics for the cascade model while aggregating hourly observations Parameters ---------- months : Months for each seasons to be used for statistics (array of numpy array, default=1-12, e.g., [np.arange(12) + 1]) avg_stats : average statistics for all levels True/False (default=True) percentile : percentil for splitting the dataset in small and high intensities (default=50)
[ "Calculates", "precipitation", "statistics", "for", "the", "cascade", "model", "while", "aggregating", "hourly", "observations" ]
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L77-L92
train
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.calc_wind_stats
def calc_wind_stats(self): """ Calculates statistics in order to derive diurnal patterns of wind speed """ a, b, t_shift = melodist.fit_cosine_function(self.data.wind) self.wind.update(a=a, b=b, t_shift=t_shift)
python
def calc_wind_stats(self): """ Calculates statistics in order to derive diurnal patterns of wind speed """ a, b, t_shift = melodist.fit_cosine_function(self.data.wind) self.wind.update(a=a, b=b, t_shift=t_shift)
[ "def", "calc_wind_stats", "(", "self", ")", ":", "a", ",", "b", ",", "t_shift", "=", "melodist", ".", "fit_cosine_function", "(", "self", ".", "data", ".", "wind", ")", "self", ".", "wind", ".", "update", "(", "a", "=", "a", ",", "b", "=", "b", "...
Calculates statistics in order to derive diurnal patterns of wind speed
[ "Calculates", "statistics", "in", "order", "to", "derive", "diurnal", "patterns", "of", "wind", "speed" ]
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L94-L99
train
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.calc_humidity_stats
def calc_humidity_stats(self): """ Calculates statistics in order to derive diurnal patterns of relative humidity. """ a1, a0 = melodist.calculate_dewpoint_regression(self.data, return_stats=False) self.hum.update(a0=a0, a1=a1) self.hum.kr = 12 self.hum.month_hour_precip_mean = melodist.calculate_month_hour_precip_mean(self.data)
python
def calc_humidity_stats(self): """ Calculates statistics in order to derive diurnal patterns of relative humidity. """ a1, a0 = melodist.calculate_dewpoint_regression(self.data, return_stats=False) self.hum.update(a0=a0, a1=a1) self.hum.kr = 12 self.hum.month_hour_precip_mean = melodist.calculate_month_hour_precip_mean(self.data)
[ "def", "calc_humidity_stats", "(", "self", ")", ":", "a1", ",", "a0", "=", "melodist", ".", "calculate_dewpoint_regression", "(", "self", ".", "data", ",", "return_stats", "=", "False", ")", "self", ".", "hum", ".", "update", "(", "a0", "=", "a0", ",", ...
Calculates statistics in order to derive diurnal patterns of relative humidity.
[ "Calculates", "statistics", "in", "order", "to", "derive", "diurnal", "patterns", "of", "relative", "humidity", "." ]
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L101-L109
train
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.calc_temperature_stats
def calc_temperature_stats(self): """ Calculates statistics in order to derive diurnal patterns of temperature """ self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_course_by_month(self.data.temp, normalize=True)
python
def calc_temperature_stats(self): """ Calculates statistics in order to derive diurnal patterns of temperature """ self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_course_by_month(self.data.temp, normalize=True)
[ "def", "calc_temperature_stats", "(", "self", ")", ":", "self", ".", "temp", ".", "max_delta", "=", "melodist", ".", "get_shift_by_data", "(", "self", ".", "data", ".", "temp", ",", "self", ".", "_lon", ",", "self", ".", "_lat", ",", "self", ".", "_tim...
Calculates statistics in order to derive diurnal patterns of temperature
[ "Calculates", "statistics", "in", "order", "to", "derive", "diurnal", "patterns", "of", "temperature" ]
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L111-L116
train
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.calc_radiation_stats
def calc_radiation_stats(self, data_daily=None, day_length=None, how='all'): """ Calculates statistics in order to derive solar radiation from sunshine duration or minimum/maximum temperature. Parameters ---------- data_daily : DataFrame, optional Daily data from the associated ``Station`` object. day_length : Series, optional Day lengths as calculated by ``calc_sun_times``. """ assert how in ('all', 'seasonal', 'monthly') self.glob.mean_course = melodist.util.calculate_mean_daily_course_by_month(self.data.glob) if data_daily is not None: pot_rad = melodist.potential_radiation( melodist.util.hourly_index(data_daily.index), self._lon, self._lat, self._timezone) pot_rad_daily = pot_rad.resample('D').mean() obs_rad_daily = self.data.glob.resample('D').mean() if how == 'all': month_ranges = [np.arange(12) + 1] elif how == 'seasonal': month_ranges = [[3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 1, 2]] elif how == 'monthly': month_ranges = zip(np.arange(12) + 1) def myisin(s, v): return pd.Series(s).isin(v).values def extract_months(s, months): return s[myisin(s.index.month, months)] if 'ssd' in data_daily and day_length is not None: for months in month_ranges: a, b = melodist.fit_angstroem_params( extract_months(data_daily.ssd, months), extract_months(day_length, months), extract_months(pot_rad_daily, months), extract_months(obs_rad_daily, months), ) for month in months: self.glob.angstroem.loc[month] = a, b if 'tmin' in data_daily and 'tmax' in data_daily: df = pd.DataFrame( data=dict( tmin=data_daily.tmin, tmax=data_daily.tmax, pot_rad=pot_rad_daily, obs_rad=obs_rad_daily, ) ).dropna(how='any') for months in month_ranges: a, c = melodist.fit_bristow_campbell_params( extract_months(df.tmin, months), extract_months(df.tmax, months), extract_months(df.pot_rad, months), extract_months(df.obs_rad, months), ) for month in months: self.glob.bristcamp.loc[month] = a, c
python
def calc_radiation_stats(self, data_daily=None, day_length=None, how='all'): """ Calculates statistics in order to derive solar radiation from sunshine duration or minimum/maximum temperature. Parameters ---------- data_daily : DataFrame, optional Daily data from the associated ``Station`` object. day_length : Series, optional Day lengths as calculated by ``calc_sun_times``. """ assert how in ('all', 'seasonal', 'monthly') self.glob.mean_course = melodist.util.calculate_mean_daily_course_by_month(self.data.glob) if data_daily is not None: pot_rad = melodist.potential_radiation( melodist.util.hourly_index(data_daily.index), self._lon, self._lat, self._timezone) pot_rad_daily = pot_rad.resample('D').mean() obs_rad_daily = self.data.glob.resample('D').mean() if how == 'all': month_ranges = [np.arange(12) + 1] elif how == 'seasonal': month_ranges = [[3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 1, 2]] elif how == 'monthly': month_ranges = zip(np.arange(12) + 1) def myisin(s, v): return pd.Series(s).isin(v).values def extract_months(s, months): return s[myisin(s.index.month, months)] if 'ssd' in data_daily and day_length is not None: for months in month_ranges: a, b = melodist.fit_angstroem_params( extract_months(data_daily.ssd, months), extract_months(day_length, months), extract_months(pot_rad_daily, months), extract_months(obs_rad_daily, months), ) for month in months: self.glob.angstroem.loc[month] = a, b if 'tmin' in data_daily and 'tmax' in data_daily: df = pd.DataFrame( data=dict( tmin=data_daily.tmin, tmax=data_daily.tmax, pot_rad=pot_rad_daily, obs_rad=obs_rad_daily, ) ).dropna(how='any') for months in month_ranges: a, c = melodist.fit_bristow_campbell_params( extract_months(df.tmin, months), extract_months(df.tmax, months), extract_months(df.pot_rad, months), extract_months(df.obs_rad, months), ) for month in months: self.glob.bristcamp.loc[month] = a, c
[ "def", "calc_radiation_stats", "(", "self", ",", "data_daily", "=", "None", ",", "day_length", "=", "None", ",", "how", "=", "'all'", ")", ":", "assert", "how", "in", "(", "'all'", ",", "'seasonal'", ",", "'monthly'", ")", "self", ".", "glob", ".", "me...
Calculates statistics in order to derive solar radiation from sunshine duration or minimum/maximum temperature. Parameters ---------- data_daily : DataFrame, optional Daily data from the associated ``Station`` object. day_length : Series, optional Day lengths as calculated by ``calc_sun_times``.
[ "Calculates", "statistics", "in", "order", "to", "derive", "solar", "radiation", "from", "sunshine", "duration", "or", "minimum", "/", "maximum", "temperature", "." ]
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L118-L186
train
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.to_json
def to_json(self, filename=None): """ Exports statistical data to a JSON formatted file Parameters ---------- filename: output file that holds statistics data """ def json_encoder(obj): if isinstance(obj, pd.DataFrame) or isinstance(obj, pd.Series): if isinstance(obj.index, pd.core.index.MultiIndex): obj = obj.reset_index() # convert MultiIndex to columns return json.loads(obj.to_json(date_format='iso')) elif isinstance(obj, melodist.cascade.CascadeStatistics): return obj.__dict__ elif isinstance(obj, np.ndarray): return obj.tolist() else: raise TypeError('%s not supported' % type(obj)) d = dict( temp=self.temp, wind=self.wind, precip=self.precip, hum=self.hum, glob=self.glob ) j = json.dumps(d, default=json_encoder, indent=4) if filename is None: return j else: with open(filename, 'w') as f: f.write(j)
python
def to_json(self, filename=None): """ Exports statistical data to a JSON formatted file Parameters ---------- filename: output file that holds statistics data """ def json_encoder(obj): if isinstance(obj, pd.DataFrame) or isinstance(obj, pd.Series): if isinstance(obj.index, pd.core.index.MultiIndex): obj = obj.reset_index() # convert MultiIndex to columns return json.loads(obj.to_json(date_format='iso')) elif isinstance(obj, melodist.cascade.CascadeStatistics): return obj.__dict__ elif isinstance(obj, np.ndarray): return obj.tolist() else: raise TypeError('%s not supported' % type(obj)) d = dict( temp=self.temp, wind=self.wind, precip=self.precip, hum=self.hum, glob=self.glob ) j = json.dumps(d, default=json_encoder, indent=4) if filename is None: return j else: with open(filename, 'w') as f: f.write(j)
[ "def", "to_json", "(", "self", ",", "filename", "=", "None", ")", ":", "def", "json_encoder", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "pd", ".", "DataFrame", ")", "or", "isinstance", "(", "obj", ",", "pd", ".", "Series", ")", ":"...
Exports statistical data to a JSON formatted file Parameters ---------- filename: output file that holds statistics data
[ "Exports", "statistical", "data", "to", "a", "JSON", "formatted", "file" ]
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L188-L223
train
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.from_json
def from_json(cls, filename): """ Imports statistical data from a JSON formatted file Parameters ---------- filename: input file that holds statistics data """ def json_decoder(d): if 'p01' in d and 'pxx' in d: # we assume this is a CascadeStatistics object return melodist.cascade.CascadeStatistics.from_dict(d) return d with open(filename) as f: d = json.load(f, object_hook=json_decoder) stats = cls() stats.temp.update(d['temp']) stats.hum.update(d['hum']) stats.precip.update(d['precip']) stats.wind.update(d['wind']) stats.glob.update(d['glob']) if stats.temp.max_delta is not None: stats.temp.max_delta = pd.read_json(json.dumps(stats.temp.max_delta), typ='series').sort_index() if stats.temp.mean_course is not None: mc = pd.read_json(json.dumps(stats.temp.mean_course), typ='frame').sort_index()[np.arange(1, 12 + 1)] stats.temp.mean_course = mc.sort_index()[np.arange(1, 12 + 1)] if stats.hum.month_hour_precip_mean is not None: mhpm = pd.read_json(json.dumps(stats.hum.month_hour_precip_mean), typ='frame').sort_index() mhpm = mhpm.set_index(['level_0', 'level_1', 'level_2']) # convert to MultiIndex mhpm = mhpm.squeeze() # convert to Series mhpm = mhpm.rename_axis([None, None, None]) # remove index labels stats.hum.month_hour_precip_mean = mhpm for var in ('angstroem', 'bristcamp', 'mean_course'): if stats.glob[var] is not None: stats.glob[var] = pd.read_json(json.dumps(stats.glob[var])).sort_index() if stats.glob.mean_course is not None: stats.glob.mean_course = stats.glob.mean_course[np.arange(1, 12 + 1)] return stats
python
def from_json(cls, filename): """ Imports statistical data from a JSON formatted file Parameters ---------- filename: input file that holds statistics data """ def json_decoder(d): if 'p01' in d and 'pxx' in d: # we assume this is a CascadeStatistics object return melodist.cascade.CascadeStatistics.from_dict(d) return d with open(filename) as f: d = json.load(f, object_hook=json_decoder) stats = cls() stats.temp.update(d['temp']) stats.hum.update(d['hum']) stats.precip.update(d['precip']) stats.wind.update(d['wind']) stats.glob.update(d['glob']) if stats.temp.max_delta is not None: stats.temp.max_delta = pd.read_json(json.dumps(stats.temp.max_delta), typ='series').sort_index() if stats.temp.mean_course is not None: mc = pd.read_json(json.dumps(stats.temp.mean_course), typ='frame').sort_index()[np.arange(1, 12 + 1)] stats.temp.mean_course = mc.sort_index()[np.arange(1, 12 + 1)] if stats.hum.month_hour_precip_mean is not None: mhpm = pd.read_json(json.dumps(stats.hum.month_hour_precip_mean), typ='frame').sort_index() mhpm = mhpm.set_index(['level_0', 'level_1', 'level_2']) # convert to MultiIndex mhpm = mhpm.squeeze() # convert to Series mhpm = mhpm.rename_axis([None, None, None]) # remove index labels stats.hum.month_hour_precip_mean = mhpm for var in ('angstroem', 'bristcamp', 'mean_course'): if stats.glob[var] is not None: stats.glob[var] = pd.read_json(json.dumps(stats.glob[var])).sort_index() if stats.glob.mean_course is not None: stats.glob.mean_course = stats.glob.mean_course[np.arange(1, 12 + 1)] return stats
[ "def", "from_json", "(", "cls", ",", "filename", ")", ":", "def", "json_decoder", "(", "d", ")", ":", "if", "'p01'", "in", "d", "and", "'pxx'", "in", "d", ":", "# we assume this is a CascadeStatistics object", "return", "melodist", ".", "cascade", ".", "Casc...
Imports statistical data from a JSON formatted file Parameters ---------- filename: input file that holds statistics data
[ "Imports", "statistical", "data", "from", "a", "JSON", "formatted", "file" ]
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L226-L272
train
kristianfoerster/melodist
melodist/radiation.py
disaggregate_radiation
def disaggregate_radiation(data_daily, sun_times=None, pot_rad=None, method='pot_rad', angstr_a=0.25, angstr_b=0.5, bristcamp_a=0.75, bristcamp_c=2.4, mean_course=None): """general function for radiation disaggregation Args: daily_data: daily values sun_times: daily dataframe including results of the util.sun_times function pot_rad: hourly dataframe including potential radiation method: keyword specifying the disaggregation method to be used angstr_a: parameter a of the Angstrom model (intercept) angstr_b: parameter b of the Angstrom model (slope) mean_course: monthly values of the mean hourly radiation course Returns: Disaggregated hourly values of shortwave radiation. """ # check if disaggregation method has a valid value if method not in ('pot_rad', 'pot_rad_via_ssd', 'pot_rad_via_bc', 'mean_course'): raise ValueError('Invalid option') glob_disagg = pd.Series(index=melodist.util.hourly_index(data_daily.index)) if method == 'mean_course': assert mean_course is not None pot_rad = pd.Series(index=glob_disagg.index) pot_rad[:] = mean_course.unstack().loc[list(zip(pot_rad.index.month, pot_rad.index.hour))].values else: assert pot_rad is not None pot_rad_daily = pot_rad.resample('D').mean() if method in ('pot_rad', 'mean_course'): globalrad = data_daily.glob elif method == 'pot_rad_via_ssd': # in this case use the Angstrom model globalrad = pd.Series(index=data_daily.index, data=0.) dates = sun_times.index[sun_times.daylength > 0] # account for polar nights globalrad[dates] = angstroem(data_daily.ssd[dates], sun_times.daylength[dates], pot_rad_daily[dates], angstr_a, angstr_b) elif method == 'pot_rad_via_bc': # using data from Bristow-Campbell model globalrad = bristow_campbell(data_daily.tmin, data_daily.tmax, pot_rad_daily, bristcamp_a, bristcamp_c) globalrad_equal = globalrad.reindex(pot_rad.index, method='ffill') # hourly values (replicate daily mean value for each hour) pot_rad_daily_equal = pot_rad_daily.reindex(pot_rad.index, method='ffill') glob_disagg = pot_rad / pot_rad_daily_equal * globalrad_equal glob_disagg[glob_disagg < 1e-2] = 0. return glob_disagg
python
def disaggregate_radiation(data_daily, sun_times=None, pot_rad=None, method='pot_rad', angstr_a=0.25, angstr_b=0.5, bristcamp_a=0.75, bristcamp_c=2.4, mean_course=None): """general function for radiation disaggregation Args: daily_data: daily values sun_times: daily dataframe including results of the util.sun_times function pot_rad: hourly dataframe including potential radiation method: keyword specifying the disaggregation method to be used angstr_a: parameter a of the Angstrom model (intercept) angstr_b: parameter b of the Angstrom model (slope) mean_course: monthly values of the mean hourly radiation course Returns: Disaggregated hourly values of shortwave radiation. """ # check if disaggregation method has a valid value if method not in ('pot_rad', 'pot_rad_via_ssd', 'pot_rad_via_bc', 'mean_course'): raise ValueError('Invalid option') glob_disagg = pd.Series(index=melodist.util.hourly_index(data_daily.index)) if method == 'mean_course': assert mean_course is not None pot_rad = pd.Series(index=glob_disagg.index) pot_rad[:] = mean_course.unstack().loc[list(zip(pot_rad.index.month, pot_rad.index.hour))].values else: assert pot_rad is not None pot_rad_daily = pot_rad.resample('D').mean() if method in ('pot_rad', 'mean_course'): globalrad = data_daily.glob elif method == 'pot_rad_via_ssd': # in this case use the Angstrom model globalrad = pd.Series(index=data_daily.index, data=0.) dates = sun_times.index[sun_times.daylength > 0] # account for polar nights globalrad[dates] = angstroem(data_daily.ssd[dates], sun_times.daylength[dates], pot_rad_daily[dates], angstr_a, angstr_b) elif method == 'pot_rad_via_bc': # using data from Bristow-Campbell model globalrad = bristow_campbell(data_daily.tmin, data_daily.tmax, pot_rad_daily, bristcamp_a, bristcamp_c) globalrad_equal = globalrad.reindex(pot_rad.index, method='ffill') # hourly values (replicate daily mean value for each hour) pot_rad_daily_equal = pot_rad_daily.reindex(pot_rad.index, method='ffill') glob_disagg = pot_rad / pot_rad_daily_equal * globalrad_equal glob_disagg[glob_disagg < 1e-2] = 0. return glob_disagg
[ "def", "disaggregate_radiation", "(", "data_daily", ",", "sun_times", "=", "None", ",", "pot_rad", "=", "None", ",", "method", "=", "'pot_rad'", ",", "angstr_a", "=", "0.25", ",", "angstr_b", "=", "0.5", ",", "bristcamp_a", "=", "0.75", ",", "bristcamp_c", ...
general function for radiation disaggregation Args: daily_data: daily values sun_times: daily dataframe including results of the util.sun_times function pot_rad: hourly dataframe including potential radiation method: keyword specifying the disaggregation method to be used angstr_a: parameter a of the Angstrom model (intercept) angstr_b: parameter b of the Angstrom model (slope) mean_course: monthly values of the mean hourly radiation course Returns: Disaggregated hourly values of shortwave radiation.
[ "general", "function", "for", "radiation", "disaggregation", "Args", ":", "daily_data", ":", "daily", "values", "sun_times", ":", "daily", "dataframe", "including", "results", "of", "the", "util", ".", "sun_times", "function", "pot_rad", ":", "hourly", "dataframe"...
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L37-L93
train
kristianfoerster/melodist
melodist/radiation.py
potential_radiation
def potential_radiation(dates, lon, lat, timezone, terrain_slope=0, terrain_slope_azimuth=0, cloud_fraction=0, split=False): """ Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E. and Elder, K. (2006): A Meteorological Distribution System for High-Resolution Terrestrial Modeling (MicroMet), J. Hydrometeorol., 7, 217–234. Corrections for eccentricity are carried out following: Paltridge, G.W., Platt, C.M.R., 1976. Radiative processes in Meteorology and Climatology. Elsevier Scientific Publishing Company, Amsterdam, Oxford, New York. Parameters ---------- dates : DatetimeIndex or array-like The dates for which potential radiation shall be calculated lon : float Longitude (degrees) lat : float Latitude (degrees) timezone : float Time zone terrain_slope : float, default 0 Terrain slope as defined in Liston & Elder (2006) (eq. 12) terrain_slope_azimuth : float, default 0 Terrain slope azimuth as defined in Liston & Elder (2006) (eq. 13) cloud_fraction : float, default 0 Cloud fraction between 0 and 1 split : boolean, default False If True, return a DataFrame containing direct and diffuse radiation, otherwise return a Series containing total radiation """ solar_constant = 1367. days_per_year = 365.25 tropic_of_cancer = np.deg2rad(23.43697) solstice = 173.0 dates = pd.DatetimeIndex(dates) dates_hour = np.array(dates.hour) dates_minute = np.array(dates.minute) day_of_year = np.array(dates.dayofyear) # compute solar decline in rad solar_decline = tropic_of_cancer * np.cos(2.0 * np.pi * (day_of_year - solstice) / days_per_year) # compute the sun hour angle in rad standard_meridian = timezone * 15. delta_lat_time = (lon - standard_meridian) * 24. / 360. hour_angle = np.pi * (((dates_hour + dates_minute / 60. + delta_lat_time) / 12.) - 1.) # get solar zenith angle cos_solar_zenith = (np.sin(solar_decline) * np.sin(np.deg2rad(lat)) + np.cos(solar_decline) * np.cos(np.deg2rad(lat)) * np.cos(hour_angle)) cos_solar_zenith = cos_solar_zenith.clip(min=0) solar_zenith_angle = np.arccos(cos_solar_zenith) # compute transmissivities for direct and diffus radiation using cloud fraction transmissivity_direct = (0.6 + 0.2 * cos_solar_zenith) * (1.0 - cloud_fraction) transmissivity_diffuse = (0.3 + 0.1 * cos_solar_zenith) * cloud_fraction # modify solar constant for eccentricity beta = 2. * np.pi * (day_of_year / days_per_year) radius_ratio = (1.00011 + 0.034221 * np.cos(beta) + 0.00128 * np.sin(beta) + 0.000719 * np.cos(2. * beta) + 0.000077 * np.sin(2 * beta)) solar_constant_times_radius_ratio = solar_constant * radius_ratio mu = np.arcsin(np.cos(solar_decline) * np.sin(hour_angle) / np.sin(solar_zenith_angle)) cosi = (np.cos(terrain_slope) * cos_solar_zenith + np.sin(terrain_slope) * np.sin(solar_zenith_angle) * np.cos(mu - terrain_slope_azimuth)) # get total shortwave radiation direct_radiation = solar_constant_times_radius_ratio * transmissivity_direct * cosi diffuse_radiation = solar_constant_times_radius_ratio * transmissivity_diffuse * cos_solar_zenith direct_radiation = direct_radiation.clip(min=0) df = pd.DataFrame(index=dates, data=dict(direct=direct_radiation, diffuse=diffuse_radiation)) if split: return df else: return df.direct + df.diffuse
python
def potential_radiation(dates, lon, lat, timezone, terrain_slope=0, terrain_slope_azimuth=0, cloud_fraction=0, split=False): """ Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E. and Elder, K. (2006): A Meteorological Distribution System for High-Resolution Terrestrial Modeling (MicroMet), J. Hydrometeorol., 7, 217–234. Corrections for eccentricity are carried out following: Paltridge, G.W., Platt, C.M.R., 1976. Radiative processes in Meteorology and Climatology. Elsevier Scientific Publishing Company, Amsterdam, Oxford, New York. Parameters ---------- dates : DatetimeIndex or array-like The dates for which potential radiation shall be calculated lon : float Longitude (degrees) lat : float Latitude (degrees) timezone : float Time zone terrain_slope : float, default 0 Terrain slope as defined in Liston & Elder (2006) (eq. 12) terrain_slope_azimuth : float, default 0 Terrain slope azimuth as defined in Liston & Elder (2006) (eq. 13) cloud_fraction : float, default 0 Cloud fraction between 0 and 1 split : boolean, default False If True, return a DataFrame containing direct and diffuse radiation, otherwise return a Series containing total radiation """ solar_constant = 1367. days_per_year = 365.25 tropic_of_cancer = np.deg2rad(23.43697) solstice = 173.0 dates = pd.DatetimeIndex(dates) dates_hour = np.array(dates.hour) dates_minute = np.array(dates.minute) day_of_year = np.array(dates.dayofyear) # compute solar decline in rad solar_decline = tropic_of_cancer * np.cos(2.0 * np.pi * (day_of_year - solstice) / days_per_year) # compute the sun hour angle in rad standard_meridian = timezone * 15. delta_lat_time = (lon - standard_meridian) * 24. / 360. hour_angle = np.pi * (((dates_hour + dates_minute / 60. + delta_lat_time) / 12.) - 1.) # get solar zenith angle cos_solar_zenith = (np.sin(solar_decline) * np.sin(np.deg2rad(lat)) + np.cos(solar_decline) * np.cos(np.deg2rad(lat)) * np.cos(hour_angle)) cos_solar_zenith = cos_solar_zenith.clip(min=0) solar_zenith_angle = np.arccos(cos_solar_zenith) # compute transmissivities for direct and diffus radiation using cloud fraction transmissivity_direct = (0.6 + 0.2 * cos_solar_zenith) * (1.0 - cloud_fraction) transmissivity_diffuse = (0.3 + 0.1 * cos_solar_zenith) * cloud_fraction # modify solar constant for eccentricity beta = 2. * np.pi * (day_of_year / days_per_year) radius_ratio = (1.00011 + 0.034221 * np.cos(beta) + 0.00128 * np.sin(beta) + 0.000719 * np.cos(2. * beta) + 0.000077 * np.sin(2 * beta)) solar_constant_times_radius_ratio = solar_constant * radius_ratio mu = np.arcsin(np.cos(solar_decline) * np.sin(hour_angle) / np.sin(solar_zenith_angle)) cosi = (np.cos(terrain_slope) * cos_solar_zenith + np.sin(terrain_slope) * np.sin(solar_zenith_angle) * np.cos(mu - terrain_slope_azimuth)) # get total shortwave radiation direct_radiation = solar_constant_times_radius_ratio * transmissivity_direct * cosi diffuse_radiation = solar_constant_times_radius_ratio * transmissivity_diffuse * cos_solar_zenith direct_radiation = direct_radiation.clip(min=0) df = pd.DataFrame(index=dates, data=dict(direct=direct_radiation, diffuse=diffuse_radiation)) if split: return df else: return df.direct + df.diffuse
[ "def", "potential_radiation", "(", "dates", ",", "lon", ",", "lat", ",", "timezone", ",", "terrain_slope", "=", "0", ",", "terrain_slope_azimuth", "=", "0", ",", "cloud_fraction", "=", "0", ",", "split", "=", "False", ")", ":", "solar_constant", "=", "1367...
Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E. and Elder, K. (2006): A Meteorological Distribution System for High-Resolution Terrestrial Modeling (MicroMet), J. Hydrometeorol., 7, 217–234. Corrections for eccentricity are carried out following: Paltridge, G.W., Platt, C.M.R., 1976. Radiative processes in Meteorology and Climatology. Elsevier Scientific Publishing Company, Amsterdam, Oxford, New York. Parameters ---------- dates : DatetimeIndex or array-like The dates for which potential radiation shall be calculated lon : float Longitude (degrees) lat : float Latitude (degrees) timezone : float Time zone terrain_slope : float, default 0 Terrain slope as defined in Liston & Elder (2006) (eq. 12) terrain_slope_azimuth : float, default 0 Terrain slope azimuth as defined in Liston & Elder (2006) (eq. 13) cloud_fraction : float, default 0 Cloud fraction between 0 and 1 split : boolean, default False If True, return a DataFrame containing direct and diffuse radiation, otherwise return a Series containing total radiation
[ "Calculate", "potential", "shortwave", "radiation", "for", "a", "specific", "location", "and", "time", ".", "This", "routine", "calculates", "global", "radiation", "as", "described", "in", ":", "Liston", "G", ".", "E", ".", "and", "Elder", "K", ".", "(", "...
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L96-L177
train
kristianfoerster/melodist
melodist/radiation.py
bristow_campbell
def bristow_campbell(tmin, tmax, pot_rad_daily, A, C): """calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and daily maximum and minimum temperature. Agricultural and forest meteorology 31.2 (1984): 159-166. Args: daily_data: time series (daily data) including at least minimum and maximum temeprature pot_rad_daily: mean potential daily radiation A: parameter A of the Bristow-Campbell model C: parameter C of the Bristow-Campbell model Returns: series of potential shortwave radiation """ assert tmin.index.equals(tmax.index) temp = pd.DataFrame(data=dict(tmin=tmin, tmax=tmax)) temp = temp.reindex(pd.DatetimeIndex(start=temp.index[0], end=temp.index[-1], freq='D')) temp['tmin_nextday'] = temp.tmin temp.tmin_nextday.iloc[:-1] = temp.tmin.iloc[1:].values temp = temp.loc[tmin.index] pot_rad_daily = pot_rad_daily.loc[tmin.index] dT = temp.tmax - (temp.tmin + temp.tmin_nextday) / 2 dT_m_avg = dT.groupby(dT.index.month).mean() B = 0.036 * np.exp(-0.154 * dT_m_avg[temp.index.month]) B.index = temp.index if isinstance(A, pd.Series): months = temp.index.month A = A.loc[months].values C = C.loc[months].values transmissivity = A * (1 - np.exp(-B * dT**C)) R0 = transmissivity * pot_rad_daily return R0
python
def bristow_campbell(tmin, tmax, pot_rad_daily, A, C): """calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and daily maximum and minimum temperature. Agricultural and forest meteorology 31.2 (1984): 159-166. Args: daily_data: time series (daily data) including at least minimum and maximum temeprature pot_rad_daily: mean potential daily radiation A: parameter A of the Bristow-Campbell model C: parameter C of the Bristow-Campbell model Returns: series of potential shortwave radiation """ assert tmin.index.equals(tmax.index) temp = pd.DataFrame(data=dict(tmin=tmin, tmax=tmax)) temp = temp.reindex(pd.DatetimeIndex(start=temp.index[0], end=temp.index[-1], freq='D')) temp['tmin_nextday'] = temp.tmin temp.tmin_nextday.iloc[:-1] = temp.tmin.iloc[1:].values temp = temp.loc[tmin.index] pot_rad_daily = pot_rad_daily.loc[tmin.index] dT = temp.tmax - (temp.tmin + temp.tmin_nextday) / 2 dT_m_avg = dT.groupby(dT.index.month).mean() B = 0.036 * np.exp(-0.154 * dT_m_avg[temp.index.month]) B.index = temp.index if isinstance(A, pd.Series): months = temp.index.month A = A.loc[months].values C = C.loc[months].values transmissivity = A * (1 - np.exp(-B * dT**C)) R0 = transmissivity * pot_rad_daily return R0
[ "def", "bristow_campbell", "(", "tmin", ",", "tmax", ",", "pot_rad_daily", ",", "A", ",", "C", ")", ":", "assert", "tmin", ".", "index", ".", "equals", "(", "tmax", ".", "index", ")", "temp", "=", "pd", ".", "DataFrame", "(", "data", "=", "dict", "...
calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and daily maximum and minimum temperature. Agricultural and forest meteorology 31.2 (1984): 159-166. Args: daily_data: time series (daily data) including at least minimum and maximum temeprature pot_rad_daily: mean potential daily radiation A: parameter A of the Bristow-Campbell model C: parameter C of the Bristow-Campbell model Returns: series of potential shortwave radiation
[ "calculates", "potential", "shortwave", "radiation", "based", "on", "minimum", "and", "maximum", "temperature", "This", "routine", "calculates", "global", "radiation", "as", "described", "in", ":", "Bristow", "Keith", "L", ".", "and", "Gaylon", "S", ".", "Campbe...
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L180-L221
train
kristianfoerster/melodist
melodist/radiation.py
fit_bristow_campbell_params
def fit_bristow_campbell_params(tmin, tmax, pot_rad_daily, obs_rad_daily): """ Fit the A and C parameters for the Bristow & Campbell (1984) model using observed daily minimum and maximum temperature and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- tmin : Series Observed daily minimum temperature. tmax : Series Observed daily maximum temperature. pot_rad_daily : Series Mean potential daily solar radiation. obs_rad_daily : Series Mean observed daily solar radiation. """ def bc_absbias(ac): return np.abs(np.mean(bristow_campbell(df.tmin, df.tmax, df.pot, ac[0], ac[1]) - df.obs)) df = pd.DataFrame(data=dict(tmin=tmin, tmax=tmax, pot=pot_rad_daily, obs=obs_rad_daily)).dropna(how='any') res = scipy.optimize.minimize(bc_absbias, [0.75, 2.4]) # i.e. we minimize the absolute bias return res.x
python
def fit_bristow_campbell_params(tmin, tmax, pot_rad_daily, obs_rad_daily): """ Fit the A and C parameters for the Bristow & Campbell (1984) model using observed daily minimum and maximum temperature and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- tmin : Series Observed daily minimum temperature. tmax : Series Observed daily maximum temperature. pot_rad_daily : Series Mean potential daily solar radiation. obs_rad_daily : Series Mean observed daily solar radiation. """ def bc_absbias(ac): return np.abs(np.mean(bristow_campbell(df.tmin, df.tmax, df.pot, ac[0], ac[1]) - df.obs)) df = pd.DataFrame(data=dict(tmin=tmin, tmax=tmax, pot=pot_rad_daily, obs=obs_rad_daily)).dropna(how='any') res = scipy.optimize.minimize(bc_absbias, [0.75, 2.4]) # i.e. we minimize the absolute bias return res.x
[ "def", "fit_bristow_campbell_params", "(", "tmin", ",", "tmax", ",", "pot_rad_daily", ",", "obs_rad_daily", ")", ":", "def", "bc_absbias", "(", "ac", ")", ":", "return", "np", ".", "abs", "(", "np", ".", "mean", "(", "bristow_campbell", "(", "df", ".", "...
Fit the A and C parameters for the Bristow & Campbell (1984) model using observed daily minimum and maximum temperature and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- tmin : Series Observed daily minimum temperature. tmax : Series Observed daily maximum temperature. pot_rad_daily : Series Mean potential daily solar radiation. obs_rad_daily : Series Mean observed daily solar radiation.
[ "Fit", "the", "A", "and", "C", "parameters", "for", "the", "Bristow", "&", "Campbell", "(", "1984", ")", "model", "using", "observed", "daily", "minimum", "and", "maximum", "temperature", "and", "mean", "daily", "(", "e", ".", "g", ".", "aggregated", "fr...
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L224-L250
train
kristianfoerster/melodist
melodist/radiation.py
angstroem
def angstroem(ssd, day_length, pot_rad_daily, a, b): """ Calculate mean daily radiation from observed sunshine duration according to Angstroem (1924). Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths as calculated by ``calc_sun_times``. pot_rad_daily : Series Mean potential daily solar radiation. a : float First parameter for the Angstroem model (originally 0.25). b : float Second parameter for the Angstroem model (originally 0.75). """ if isinstance(a, pd.Series): months = ssd.index.month a = a.loc[months].values b = b.loc[months].values glob_day = (a + b * ssd / day_length) * pot_rad_daily return glob_day
python
def angstroem(ssd, day_length, pot_rad_daily, a, b): """ Calculate mean daily radiation from observed sunshine duration according to Angstroem (1924). Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths as calculated by ``calc_sun_times``. pot_rad_daily : Series Mean potential daily solar radiation. a : float First parameter for the Angstroem model (originally 0.25). b : float Second parameter for the Angstroem model (originally 0.75). """ if isinstance(a, pd.Series): months = ssd.index.month a = a.loc[months].values b = b.loc[months].values glob_day = (a + b * ssd / day_length) * pot_rad_daily return glob_day
[ "def", "angstroem", "(", "ssd", ",", "day_length", ",", "pot_rad_daily", ",", "a", ",", "b", ")", ":", "if", "isinstance", "(", "a", ",", "pd", ".", "Series", ")", ":", "months", "=", "ssd", ".", "index", ".", "month", "a", "=", "a", ".", "loc", ...
Calculate mean daily radiation from observed sunshine duration according to Angstroem (1924). Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths as calculated by ``calc_sun_times``. pot_rad_daily : Series Mean potential daily solar radiation. a : float First parameter for the Angstroem model (originally 0.25). b : float Second parameter for the Angstroem model (originally 0.75).
[ "Calculate", "mean", "daily", "radiation", "from", "observed", "sunshine", "duration", "according", "to", "Angstroem", "(", "1924", ")", ".", "Parameters", "----------", "ssd", ":", "Series", "Observed", "daily", "sunshine", "duration", ".", "day_length", ":", "...
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L253-L281
train
kristianfoerster/melodist
melodist/radiation.py
fit_angstroem_params
def fit_angstroem_params(ssd, day_length, pot_rad_daily, obs_rad_daily): """ Fit the a and b parameters for the Angstroem (1924) model using observed daily sunshine duration and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths as calculated by ``calc_sun_times``. pot_rad_daily : Series Mean potential daily solar radiation. obs_rad_daily : Series Mean observed daily solar radiation. """ df = pd.DataFrame(data=dict(ssd=ssd, day_length=day_length, pot=pot_rad_daily, obs=obs_rad_daily)).dropna(how='any') def angstroem_opt(x, a, b): return angstroem(x[0], x[1], x[2], a, b) x = np.array([df.ssd, df.day_length, df.pot]) popt, pcov = scipy.optimize.curve_fit(angstroem_opt, x, df.obs, p0=[0.25, 0.75]) return popt
python
def fit_angstroem_params(ssd, day_length, pot_rad_daily, obs_rad_daily): """ Fit the a and b parameters for the Angstroem (1924) model using observed daily sunshine duration and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths as calculated by ``calc_sun_times``. pot_rad_daily : Series Mean potential daily solar radiation. obs_rad_daily : Series Mean observed daily solar radiation. """ df = pd.DataFrame(data=dict(ssd=ssd, day_length=day_length, pot=pot_rad_daily, obs=obs_rad_daily)).dropna(how='any') def angstroem_opt(x, a, b): return angstroem(x[0], x[1], x[2], a, b) x = np.array([df.ssd, df.day_length, df.pot]) popt, pcov = scipy.optimize.curve_fit(angstroem_opt, x, df.obs, p0=[0.25, 0.75]) return popt
[ "def", "fit_angstroem_params", "(", "ssd", ",", "day_length", ",", "pot_rad_daily", ",", "obs_rad_daily", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "data", "=", "dict", "(", "ssd", "=", "ssd", ",", "day_length", "=", "day_length", ",", "pot", "="...
Fit the a and b parameters for the Angstroem (1924) model using observed daily sunshine duration and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths as calculated by ``calc_sun_times``. pot_rad_daily : Series Mean potential daily solar radiation. obs_rad_daily : Series Mean observed daily solar radiation.
[ "Fit", "the", "a", "and", "b", "parameters", "for", "the", "Angstroem", "(", "1924", ")", "model", "using", "observed", "daily", "sunshine", "duration", "and", "mean", "daily", "(", "e", ".", "g", ".", "aggregated", "from", "hourly", "values", ")", "sola...
ddc155c77b65f791be0021dbbaf68c6bac42ecbd
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L284-L312
train
mdredze/carmen-python
carmen/resolver.py
register
def register(name): """Return a decorator that registers the decorated class as a resolver with the given *name*.""" def decorator(class_): if name in known_resolvers: raise ValueError('duplicate resolver name "%s"' % name) known_resolvers[name] = class_ return decorator
python
def register(name): """Return a decorator that registers the decorated class as a resolver with the given *name*.""" def decorator(class_): if name in known_resolvers: raise ValueError('duplicate resolver name "%s"' % name) known_resolvers[name] = class_ return decorator
[ "def", "register", "(", "name", ")", ":", "def", "decorator", "(", "class_", ")", ":", "if", "name", "in", "known_resolvers", ":", "raise", "ValueError", "(", "'duplicate resolver name \"%s\"'", "%", "name", ")", "known_resolvers", "[", "name", "]", "=", "cl...
Return a decorator that registers the decorated class as a resolver with the given *name*.
[ "Return", "a", "decorator", "that", "registers", "the", "decorated", "class", "as", "a", "resolver", "with", "the", "given", "*", "name", "*", "." ]
070b974222b5407f7aae2518ffbdf9df198b8e96
https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/resolver.py#L105-L112
train