_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q11400 | imprints2marc | train | def imprints2marc(self, key, value):
"""Populate the ``260`` MARC field."""
return {
'a': value.get('place'),
| python | {
"resource": ""
} |
q11401 | thesis_info | train | def thesis_info(self, key, value):
"""Populate the ``thesis_info`` key."""
def _get_degree_type(value):
DEGREE_TYPES_MAP = {
'RAPPORT DE STAGE': 'other',
'INTERNSHIP REPORT': 'other',
'DIPLOMA': 'diploma',
'BACHELOR': 'bachelor',
'LAUREA': 'laurea',
'MASTER': 'master',
'THESIS': 'other',
'PHD': 'phd',
'PDF': 'phd',
'PH.D. THESIS': 'phd',
'HABILITATION': 'habilitation',
}
b_value = force_single_element(value.get('b', ''))
if b_value:
return DEGREE_TYPES_MAP.get(b_value.upper(), 'other')
| python | {
"resource": ""
} |
q11402 | thesis_info2marc | train | def thesis_info2marc(self, key, value):
"""Populate the ``502`` MARC field.
Also populates the ``500`` MARC field through side effects.
"""
def _get_b_value(value):
DEGREE_TYPES_MAP = {
'bachelor': 'Bachelor',
'diploma': 'Diploma',
'habilitation': 'Habilitation',
'laurea': 'Laurea',
'master': 'Master',
'other': 'Thesis',
'phd': 'PhD',
}
degree_type = value.get('degree_type')
if degree_type:
return DEGREE_TYPES_MAP.get(degree_type)
result_500 = self.get('500', [])
| python | {
"resource": ""
} |
q11403 | abstracts | train | def abstracts(self, key, value):
"""Populate the ``abstracts`` key."""
result = []
source = force_single_element(value.get('9'))
| python | {
"resource": ""
} |
q11404 | funding_info | train | def funding_info(self, key, value):
"""Populate the ``funding_info`` key."""
return {
'agency': value.get('a'),
| python | {
"resource": ""
} |
q11405 | funding_info2marc | train | def funding_info2marc(self, key, value):
"""Populate the ``536`` MARC field."""
return {
'a': value.get('agency'),
| python | {
"resource": ""
} |
q11406 | license | train | def license(self, key, value):
"""Populate the ``license`` key."""
def _get_license(value):
a_values = force_list(value.get('a'))
oa_licenses = [el for el in a_values if el == 'OA' or el == 'Open Access']
other_licenses = [el for el in a_values if el != 'OA' and el != 'Open Access']
| python | {
"resource": ""
} |
q11407 | license2marc | train | def license2marc(self, key, value):
"""Populate the ``540`` MARC field."""
return {
'a': value.get('license'),
'b': value.get('imposing'),
| python | {
"resource": ""
} |
q11408 | copyright | train | def copyright(self, key, value):
"""Populate the ``copyright`` key."""
MATERIAL_MAP = {
'Article': 'publication',
'Published thesis as a book': 'publication',
}
material = value.get('e') or value.get('3')
return {
'holder': value.get('d'),
| python | {
"resource": ""
} |
q11409 | copyright2marc | train | def copyright2marc(self, key, value):
"""Populate the ``542`` MARC field."""
E_MAP = {
'publication': 'Article',
}
e_value = value.get('material')
return {
'd': | python | {
"resource": ""
} |
q11410 | _private_notes2marc | train | def _private_notes2marc(self, key, value):
"""Populate the ``595`` MARC key.
Also populates the `595_H` MARC key through side effects.
"""
def _is_from_hal(value):
return value.get('source') == 'HAL'
if not _is_from_hal(value):
return {
| python | {
"resource": ""
} |
q11411 | _export_to2marc | train | def _export_to2marc(self, key, value):
"""Populate the ``595`` MARC field."""
def _is_for_cds(value):
return 'CDS' in value
def _is_for_hal(value):
return 'HAL' in value and value['HAL']
def _is_not_for_hal(value):
return 'HAL' in value and not value['HAL']
result = []
if | python | {
"resource": ""
} |
q11412 | _desy_bookkeeping | train | def _desy_bookkeeping(self, key, value):
"""Populate the ``_desy_bookkeeping`` key."""
return {
'date': normalize_date(value.get('d')),
| python | {
"resource": ""
} |
q11413 | _desy_bookkeeping2marc | train | def _desy_bookkeeping2marc(self, key, value):
"""Populate the ``595_D`` MARC field.
Also populates the ``035`` MARC field through side effects.
"""
if 'identifier' not in value:
return {
'a': value.get('expert'),
| python | {
"resource": ""
} |
q11414 | _dates | train | def _dates(self, key, value):
"""Don't populate any key through the return value.
On the other hand, populates the ``date_proposed``, ``date_approved``,
``date_started``, ``date_cancelled``, and the ``date_completed`` keys
through side effects.
"""
if value.get('q'):
self['date_proposed'] = normalize_date(value['q'])
if value.get('r'):
self['date_approved'] = normalize_date(value['r'])
if value.get('s'):
| python | {
"resource": ""
} |
q11415 | experiment | train | def experiment(self, key, values):
"""Populate the ``experiment`` key.
Also populates the ``legacy_name``, the ``accelerator``, and the
``institutions`` keys through side effects.
"""
experiment = self.get('experiment', {})
legacy_name = self.get('legacy_name', '')
accelerator = self.get('accelerator', {})
institutions = self.get('institutions', [])
for value in force_list(values):
if value.get('c'):
experiment['value'] = value.get('c')
| python | {
"resource": ""
} |
q11416 | core | train | def core(self, key, value):
"""Populate the ``core`` key.
Also populates the ``deleted`` and ``project_type`` keys through side
effects.
"""
core = self.get('core')
deleted = self.get('deleted')
project_type = self.get('project_type', [])
if not core:
normalized_a_values = [el.upper() for el in force_list(value.get('a'))]
if 'CORE' in normalized_a_values:
core = True
if not deleted:
normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
if 'DELETED' in normalized_c_values:
| python | {
"resource": ""
} |
q11417 | control_number | train | def control_number(endpoint):
"""Populate the ``control_number`` key.
Also populates the ``self`` key through side effects.
"""
def _control_number(self, key, value):
| python | {
"resource": ""
} |
q11418 | acquisition_source | train | def acquisition_source(self, key, value):
"""Populate the ``acquisition_source`` key."""
def _get_datetime(value):
d_value = force_single_element(value.get('d', ''))
if d_value:
try:
date = PartialDate.loads(d_value)
except ValueError:
return d_value
else:
datetime_ = datetime(year=date.year, month=date.month, day=date.day)
return datetime_.isoformat()
internal_uid, orcid, source = None, None, None
a_values = force_list(value.get('a'))
for a_value in a_values:
if IS_INTERNAL_UID.match(a_value):
if a_value.startswith('inspire:uid:'):
internal_uid = int(a_value[12:])
else:
internal_uid = int(a_value)
elif IS_ORCID.match(a_value):
if a_value.startswith('orcid:'):
orcid = a_value[6:]
else:
orcid = a_value
| python | {
"resource": ""
} |
q11419 | external_system_identifiers | train | def external_system_identifiers(endpoint):
"""Populate the ``external_system_identifiers`` key.
Also populates the ``new_record`` key through side effects.
"""
@utils.flatten
@utils.for_each_value
def _external_system_identifiers(self, key, value):
new_recid = maybe_int(value.get('d'))
if new_recid:
self['new_record'] | python | {
"resource": ""
} |
q11420 | deleted_records | train | def deleted_records(endpoint):
"""Populate the ``deleted_records`` key."""
@utils.for_each_value
def _deleted_records(self, key, value):
deleted_recid = maybe_int(value.get('a'))
| python | {
"resource": ""
} |
q11421 | accelerator_experiments | train | def accelerator_experiments(self, key, value):
"""Populate the ``accelerator_experiments`` key."""
result = []
a_value = force_single_element(value.get('a'))
e_values = [el for el in force_list(value.get('e')) if el != '-']
zero_values = force_list(value.get('0'))
if a_value and not e_values:
result.append({'accelerator': a_value})
| python | {
"resource": ""
} |
q11422 | keywords | train | def keywords(self, key, values):
"""Populate the ``keywords`` key.
Also populates the ``energy_ranges`` key through side effects.
"""
keywords = self.get('keywords', [])
energy_ranges = self.get('energy_ranges', [])
for value in force_list(values):
if value.get('a'):
schema = force_single_element(value.get('2', '')).upper()
| python | {
"resource": ""
} |
q11423 | keywords2marc | train | def keywords2marc(self, key, values):
"""Populate the ``695`` MARC field.
Also populates the ``084`` and ``6531`` MARC fields through side effects.
"""
result_695 = self.get('695', [])
result_084 = self.get('084', [])
result_6531 = self.get('6531', [])
for value in values:
schema = value.get('schema')
source = value.get('source')
keyword = value.get('value')
if schema == 'PACS' or schema == 'PDG':
result_084.append({
'2': schema,
'9': source,
'a': keyword,
})
elif schema == 'JACOW':
result_6531.append({
'2': 'JACoW',
'9': source,
'a': keyword,
})
elif schema == 'INSPIRE': | python | {
"resource": ""
} |
q11424 | collaborations | train | def collaborations(self, key, value):
"""Populate the ``collaborations`` key."""
result = []
for g_value in force_list(value.get('g')):
collaborations = normalize_collaboration(g_value)
if len(collaborations) == 1:
result.append({
'record': get_record_ref(maybe_int(value.get('0')), 'experiments'), | python | {
"resource": ""
} |
q11425 | publication_info | train | def publication_info(self, key, value):
"""Populate the ``publication_info`` key."""
def _get_cnum(value):
w_value = force_single_element(value.get('w', ''))
normalized_w_value = w_value.replace('/', '-').upper()
return normalized_w_value
def _get_material(value):
schema = load_schema('elements/material')
valid_materials = schema['enum']
m_value = force_single_element(value.get('m', ''))
normalized_m_value = m_value.lower()
if normalized_m_value in valid_materials:
return normalized_m_value
def _get_parent_isbn(value):
z_value = force_single_element(value.get('z', ''))
if z_value:
return normalize_isbn(z_value)
def _get_pubinfo_freetext(value):
x_value = force_single_element(value.get('x', ''))
if not x_value.startswith('#DONE'):
return x_value
page_start, page_end, artid = split_page_artid(value.get('c'))
parent_recid = maybe_int(force_single_element(value.get('0')))
parent_record = get_record_ref(parent_recid, 'literature')
journal_recid = maybe_int(force_single_element(value.get('1')))
journal_record = get_record_ref(journal_recid, 'journals')
conference_recid = maybe_int(force_single_element(value.get('2')))
conference_record = get_record_ref(conference_recid, 'conferences')
return {
| python | {
"resource": ""
} |
q11426 | publication_info2marc | train | def publication_info2marc(self, key, values):
"""Populate the ``773`` MARC field.
Also populates the ``7731`` MARC field through side effects.
"""
result_773 = self.get('773', [])
result_7731 = self.get('7731', [])
for value in force_list(convert_new_publication_info_to_old(values)):
page_artid = []
if value.get('page_start') and value.get('page_end'):
page_artid.append(u'{page_start}-{page_end}'.format(**value))
elif value.get('page_start'):
page_artid.append(u'{page_start}'.format(**value))
| python | {
"resource": ""
} |
q11427 | related_records2marc | train | def related_records2marc(self, key, value):
"""Populate the ``78708`` MARC field
Also populates the ``78002``, ``78502`` MARC fields through side effects.
"""
if value.get('relation_freetext'):
return {
'i': value.get('relation_freetext'),
'w': get_recid_from_ref(value.get('record')),
}
elif value.get('relation') == 'successor':
self.setdefault('78502', []).append({
'i': 'superseded by',
'w': get_recid_from_ref(value.get('record')),
})
elif value.get('relation') == 'predecessor':
| python | {
"resource": ""
} |
q11428 | proceedings | train | def proceedings(self, key, value):
"""Populate the ``proceedings`` key.
Also populates the ``refereed`` key through side effects.
"""
proceedings = self.get('proceedings')
refereed = self.get('refereed')
if not proceedings:
normalized_a_values = [el.upper() for el in force_list(value.get('a'))]
if 'PROCEEDINGS' in normalized_a_values:
proceedings = True
| python | {
"resource": ""
} |
q11429 | short_title | train | def short_title(self, key, value):
"""Populate the ``short_title`` key.
Also populates the ``title_variants`` key through side effects.
"""
short_title = value.get('a')
title_variants = self.get('title_variants', [])
if value.get('u'):
| python | {
"resource": ""
} |
q11430 | ranks | train | def ranks(self, key, value):
"""Populate the ``ranks`` key."""
| python | {
"resource": ""
} |
q11431 | BaseProgram.new_parser | train | def new_parser(self):
""" Create a command line argument parser
Add a few default flags, such as --version
for displaying the program version when invoked """
parser = argparse.ArgumentParser(description=self.description)
parser.add_argument(
'--version', help='show version and exit',
| python | {
"resource": ""
} |
q11432 | Program.help_function | train | def help_function(self, command=None):
""" Show help for all available commands or just a single one """
| python | {
"resource": ""
} |
q11433 | Program.add_command | train | def add_command(self, command, function, description=None):
""" Register a new function for command """
| python | {
"resource": ""
} |
q11434 | Response._show | train | def _show(self, res, err, prefix='', colored=False):
""" Show result or error """
if self.kind is 'local':
what = res if not err else err
print(what)
return
if self.kind is 'remote':
if colored:
red, green, reset = Fore.RED, Fore.GREEN, Fore.RESET
else:
red = green = reset = '' | python | {
"resource": ""
} |
q11435 | CtlProgram.call | train | def call(self, command, *args):
""" Execute local OR remote command and show response """
if not command:
return
# Look for local methods first
try:
res = self.registered[command]['function'](self, *args)
return Response('local', res, None)
# Method not found, try remote
except KeyError:
# Execute remote command
res, err = | python | {
"resource": ""
} |
q11436 | CtlProgram.parse_input | train | def parse_input(self, text):
""" Parse ctl user input. Double quotes are used
to group together multi words arguments. """
parts | python | {
"resource": ""
} |
q11437 | CtlProgram.loop | train | def loop(self):
""" Enter loop, read user input then run command. Repeat """
while True:
text = compat.input('ctl > ')
command, args = self.parse_input(text)
if not command:
| python | {
"resource": ""
} |
q11438 | split | train | def split(text):
""" Split text into arguments accounting for muti-word arguments
which are double quoted """
# Cleanup text
text = text.strip()
text = re.sub('\s+', ' ', text) # collpse multiple spaces
space, quote, parts = ' ', '"', []
part, quoted = '', False
for char in text:
# Encoutered beginning double quote
if char is quote and quoted is False:
quoted = True
continue
# Encountered the ending double quote
if char is quote and quoted is True:
quoted = False
parts.append(part.strip())
part = ''
continue
# Found space in quoted
if char is space and quoted is True:
part += char
continue
| python | {
"resource": ""
} |
q11439 | read_version | train | def read_version():
""" Read package version """
with open('./oi/version.py') as fh:
for line in fh:
| python | {
"resource": ""
} |
q11440 | PrettyGraph.strip_prefixes | train | def strip_prefixes(g: Graph):
""" Remove the prefixes from the graph for aesthetics """
return re.sub(r'^@prefix .* .\n', '',
| python | {
"resource": ""
} |
q11441 | _PickleJar.clear | train | def clear(self) -> None:
"""
Clear all cache entries for directory and, if it is a 'pure' directory, remove the directory itself
"""
if self._cache_directory is not None:
# Safety - if there isn't a cache directory file, this probably isn't a valid cache
assert os.path.exists(self._cache_directory_index), "Attempt to clear a non-existent cache"
| python | {
"resource": ""
} |
q11442 | fhirtordf | train | def fhirtordf(argv: List[str], default_exit: bool = True) -> bool:
""" Entry point for command line utility """
dlp = dirlistproc.DirectoryListProcessor(argv,
description="Convert FHIR JSON into RDF",
infile_suffix=".json",
outfile_suffix=".ttl",
addargs=addargs,
noexit=not default_exit)
if not dlp.successful_parse:
return False
# Version
if dlp.opts.version:
print("FHIR to RDF Conversion Tool -- Version {}".format(__version__))
# We either have to have an input file or an input directory
if not dlp.opts.infile and not dlp.opts.indir:
if not dlp.opts.version:
dlp.parser.error("Either an input file or an input directory must be supplied")
return dlp.opts.version
# Create the output directory if needed
if dlp.opts.outdir and not os.path.exists(dlp.opts.outdir):
os.makedirs(dlp.opts.outdir)
# If we are going to a single output file or stdout, gather all the input
dlp.opts.graph = Graph() if (not dlp.opts.outfile and not dlp.opts.outdir) or\
(dlp.opts.outfile and len(dlp.opts.outfile) | python | {
"resource": ""
} |
q11443 | get_distutils_option | train | def get_distutils_option(option, commands):
""" Returns the value of the given distutils option.
Parameters
----------
option : str
The name of the option
commands : list of str
The list of commands on which this option is available
| python | {
"resource": ""
} |
q11444 | add_command_option | train | def add_command_option(command, name, doc, is_bool=False):
"""
Add a custom option to a setup command.
Issues a warning if the option already exists on that command.
Parameters
----------
command : str
The name of the command as given on the command line
name : str
The name of the build option
doc : str
A short description of the option, for the `--help` message
is_bool : bool, optional
When `True`, the option is a boolean option and doesn't
require an associated value.
"""
dist = get_dummy_distribution()
cmdcls = dist.get_command_class(command)
if (hasattr(cmdcls, '_astropy_helpers_options') and
name in cmdcls._astropy_helpers_options):
return
attr = name.replace('-', '_')
if hasattr(cmdcls, attr):
raise RuntimeError(
'{0!r} already has a {1!r} class attribute, barring {2!r} from '
'being usable as a custom option name.'.format(cmdcls, attr, name))
for idx, cmd in enumerate(cmdcls.user_options):
if cmd[0] == name:
log.warn('Overriding existing {0!r} option '
'{1!r}'.format(command, name))
del cmdcls.user_options[idx]
if name in cmdcls.boolean_options:
| python | {
"resource": ""
} |
q11445 | ensure_sphinx_astropy_installed | train | def ensure_sphinx_astropy_installed():
"""
Make sure that sphinx-astropy is available, installing it temporarily if not.
This returns the available version of sphinx-astropy as well as any
paths that should be added to sys.path for sphinx-astropy to be available.
"""
# We've split out the Sphinx part of astropy-helpers into sphinx-astropy
# but we want it to be auto-installed seamlessly for anyone using
# build_docs. We check if it's already installed, and if not, we install
# it to a local .eggs directory and add the eggs to the path (these
# have to each be added to the path, we can't add them by simply adding
# .eggs to the path)
sys_path_inserts = []
sphinx_astropy_version = None
try:
from sphinx_astropy import __version__ as sphinx_astropy_version # noqa
except ImportError:
from setuptools import Distribution
dist = Distribution()
# Numpydoc 0.9.0 requires sphinx 1.6+, we can limit the version here
# until we also makes our minimum required version Sphinx 1.6
if SPHINX_LT_16:
dist.fetch_build_eggs('numpydoc<0.9')
# This egg build doesn't respect python_requires, not aware of
# pre-releases. We know that mpl 3.1+ requires Python 3.6+, so this
# ugly workaround takes care of it until there is a solution for
# https://github.com/astropy/astropy-helpers/issues/462 | python | {
"resource": ""
} |
q11446 | get_numpy_include_path | train | def get_numpy_include_path():
"""
Gets the path to the numpy headers.
"""
# We need to go through this nonsense in case setuptools
# downloaded and installed Numpy for us as part of the build or
# install, since Numpy may still think it's in "setup mode", when
# in fact we're ready to use it to build astropy now.
import builtins
if hasattr(builtins, '__NUMPY_SETUP__'):
| python | {
"resource": ""
} |
q11447 | is_path_hidden | train | def is_path_hidden(filepath):
"""
Determines if a given file or directory is hidden.
Parameters
----------
filepath : str
The path to a file or directory
Returns
-------
hidden : bool
Returns `True` if the file is hidden
"""
name = os.path.basename(os.path.abspath(filepath))
| python | {
"resource": ""
} |
q11448 | walk_skip_hidden | train | def walk_skip_hidden(top, onerror=None, followlinks=False):
"""
A wrapper for `os.walk` that skips hidden files and directories.
This function does not have the parameter `topdown` from
`os.walk`: the directories must always be recursed top-down when
using this function.
See also
| python | {
"resource": ""
} |
q11449 | write_if_different | train | def write_if_different(filename, data):
"""Write `data` to `filename`, if the content of the file is different.
Parameters
----------
filename : str
The file name to be written to.
data : bytes
The data to be written to `filename`.
"""
assert isinstance(data, bytes)
if os.path.exists(filename):
| python | {
"resource": ""
} |
q11450 | import_file | train | def import_file(filename, name=None):
"""
Imports a module from a single file as if it doesn't belong to a
particular package.
The returned module will have the optional ``name`` if given, or else
a name generated from the filename.
"""
# Specifying a traditional dot-separated fully qualified name here
# results in a number of "Parent module 'astropy' not found while
# handling absolute import" warnings. Using the same name, the
# namespaces of the modules get merged together. So, this
# generates an underscore-separated name which is more likely to
# be unique, and it doesn't really matter because the name isn't
# used directly here anyway.
mode = 'r'
if name is None:
basename = os.path.splitext(filename)[0] | python | {
"resource": ""
} |
q11451 | resolve_name | train | def resolve_name(name):
"""Resolve a name like ``module.object`` to an object and return it.
Raise `ImportError` if the module or name is not found.
"""
parts = name.split('.')
cursor = len(parts) - 1
module_name = parts[:cursor]
attr_name = parts[-1]
while cursor > 0:
try:
ret = __import__('.'.join(module_name), fromlist=[attr_name])
break
except ImportError:
if cursor == 0:
| python | {
"resource": ""
} |
q11452 | find_data_files | train | def find_data_files(package, pattern):
"""
Include files matching ``pattern`` inside ``package``.
Parameters
----------
package : str
The package inside which to look for data files
pattern : str
Pattern (glob-style) to match for the data files (e.g. ``*.dat``).
This supports the``**``recursive syntax. For example, ``**/*.fits``
matches | python | {
"resource": ""
} |
q11453 | get_pkg_version_module | train | def get_pkg_version_module(packagename, fromlist=None):
"""Returns the package's .version module generated by
`astropy_helpers.version_helpers.generate_version_py`. Raises an
ImportError if the version module is not found.
If ``fromlist`` is an iterable, return a tuple of the members of the
version module corresponding to the member names given in ``fromlist``.
Raises an `AttributeError` if any of these module members are | python | {
"resource": ""
} |
q11454 | get_debug_option | train | def get_debug_option(packagename):
""" Determines if the build is in debug mode.
Returns
-------
debug : bool
True if the current build was started with the debug option, False
otherwise.
"""
try:
current_debug = get_pkg_version_module(packagename,
fromlist=['debug'])[0]
except (ImportError, AttributeError):
| python | {
"resource": ""
} |
q11455 | generate_hooked_command | train | def generate_hooked_command(cmd_name, cmd_cls, hooks):
"""
Returns a generated subclass of ``cmd_cls`` that runs the pre- and
post-command hooks for that command before and after the ``cmd_cls.run``
method.
"""
def run(self, orig_run=cmd_cls.run):
self.run_command_hooks('pre_hooks')
orig_run(self)
self.run_command_hooks('post_hooks')
return type(cmd_name, (cmd_cls, | python | {
"resource": ""
} |
q11456 | run_command_hooks | train | def run_command_hooks(cmd_obj, hook_kind):
"""Run hooks registered for that command and phase.
*cmd_obj* is a finalized command object; *hook_kind* is either
'pre_hook' or 'post_hook'.
"""
hooks = getattr(cmd_obj, hook_kind, None)
if not hooks:
return
for modname, hook in hooks:
if isinstance(hook, str):
try:
hook_obj = resolve_name(hook)
except ImportError as exc:
| python | {
"resource": ""
} |
q11457 | update_package_files | train | def update_package_files(srcdir, extensions, package_data, packagenames,
package_dirs):
"""
This function is deprecated and maintained for backward compatibility
with affiliated packages. Affiliated | python | {
"resource": ""
} |
q11458 | get_package_info | train | def get_package_info(srcdir='.', exclude=()):
"""
Collates all of the information for building all subpackages
and returns a dictionary of keyword arguments that can
be passed directly to `distutils.setup`.
The purpose of this function is to allow subpackages to update the
arguments to the package's ``setup()`` function in its setup.py
script, rather than having to specify all extensions/package data
directly in the ``setup.py``. See Astropy's own
``setup.py`` for example usage and the Astropy development docs
for more details.
This function obtains that information by iterating through all
packages in ``srcdir`` and locating a ``setup_package.py`` module.
This module can contain the following functions:
``get_extensions()``, ``get_package_data()``,
``get_build_options()``, and ``get_external_libraries()``.
Each of those functions take no arguments.
- ``get_extensions`` returns a list of
`distutils.extension.Extension` objects.
- ``get_package_data()`` returns a dict formatted as required by
the ``package_data`` argument to ``setup()``.
- ``get_build_options()`` returns a list of tuples describing the
extra build options to add.
- ``get_external_libraries()`` returns
a list of libraries that can optionally be built using external
dependencies.
"""
ext_modules = []
packages = []
package_dir = {}
# Read in existing package data, and add to it below
setup_cfg = os.path.join(srcdir, 'setup.cfg')
if os.path.exists(setup_cfg):
conf = read_configuration(setup_cfg)
if 'options' in conf and 'package_data' in conf['options']:
package_data = conf['options']['package_data']
else:
package_data = {}
else:
package_data = {}
if exclude:
warnings.warn(
"Use of the exclude parameter is no longer supported since it does "
"not work as expected. Use add_exclude_packages instead. Note that "
"it must be called prior to any other calls from setup helpers.",
AstropyDeprecationWarning)
# Use the find_packages tool to locate all packages and modules
packages = find_packages(srcdir, exclude=exclude)
# Update package_dir if the package lies in a subdirectory
if srcdir != '.':
package_dir[''] = srcdir
# For each of the setup_package.py modules, extract any
# information that is needed to install them. The build options
# are extracted first, so that their values will be available in
# subsequent calls to `get_extensions`, etc.
for setuppkg in iter_setup_packages(srcdir, packages):
if hasattr(setuppkg, 'get_build_options'):
options = setuppkg.get_build_options()
for option in options:
add_command_option('build', *option)
| python | {
"resource": ""
} |
q11459 | iter_setup_packages | train | def iter_setup_packages(srcdir, packages):
""" A generator that finds and imports all of the ``setup_package.py``
modules in the source packages.
Returns
-------
modgen : generator
A generator that yields (modname, mod), where `mod` is the module and
`modname` is the module name for the ``setup_package.py`` modules.
"""
for packagename in packages:
package_parts = packagename.split('.')
| python | {
"resource": ""
} |
q11460 | get_cython_extensions | train | def get_cython_extensions(srcdir, packages, prevextensions=tuple(),
extincludedirs=None):
"""
Looks for Cython files and generates Extensions if needed.
Parameters
----------
srcdir : str
Path to the root of the source directory to search.
prevextensions : list of `~distutils.core.Extension` objects
The extensions that are already defined. Any .pyx files already here
will be ignored.
extincludedirs : list of str or None
Directories to include as the `include_dirs` argument to the generated
`~distutils.core.Extension` objects.
Returns
-------
exts : list of `~distutils.core.Extension` objects
The new extensions that are needed to compile all .pyx files (does not
include any already in `prevextensions`).
"""
# Vanilla setuptools and old versions of distribute include Cython files
# as .c files in the sources, not .pyx, so we cannot simply look for
# existing .pyx sources in the previous sources, but we should also check
# for .c files with the same remaining filename. So we look for .pyx and
# .c files, and we strip the extension.
prevsourcepaths = []
ext_modules = []
for ext in prevextensions:
for s in ext.sources:
| python | {
"resource": ""
} |
q11461 | pkg_config | train | def pkg_config(packages, default_libraries, executable='pkg-config'):
"""
Uses pkg-config to update a set of distutils Extension arguments
to include the flags necessary to link against the given packages.
If the pkg-config lookup fails, default_libraries is applied to
libraries.
Parameters
----------
packages : list of str
A list of pkg-config packages to look up.
default_libraries : list of str
A list of library names to use if the pkg-config lookup fails.
Returns
-------
config : dict
A dictionary containing keyword arguments to
`distutils.Extension`. These entries include:
- ``include_dirs``: A list of include directories
- ``library_dirs``: A list of library directories
- ``libraries``: A list of libraries
- ``define_macros``: A list of macro defines
- ``undef_macros``: A list of macros to undefine
- ``extra_compile_args``: A list of extra arguments to pass to
the compiler
"""
flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries',
'-D': 'define_macros', '-U': 'undef_macros'}
command = "{0} --libs --cflags {1}".format(executable, ' '.join(packages)),
result = DistutilsExtensionArgs()
try:
pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
output = pipe.communicate()[0].strip()
except subprocess.CalledProcessError as e:
lines = [
("{0} failed. This may cause the build to fail below."
.format(executable)),
" command: {0}".format(e.cmd),
" returncode: {0}".format(e.returncode),
" output: {0}".format(e.output)
]
log.warn('\n'.join(lines))
result['libraries'].extend(default_libraries)
else:
if pipe.returncode != 0:
lines = [
"pkg-config could not lookup up package(s) {0}.".format(
", ".join(packages)),
"This may cause the build to fail below."
]
| python | {
"resource": ""
} |
q11462 | add_external_library | train | def add_external_library(library):
"""
Add a build option for selecting the internal or system copy of a library.
Parameters
----------
library : str
The name of the library. If the library is `foo`, the build
option will be called `--use-system-foo`.
"""
for command in ['build', 'build_ext', 'install']:
| python | {
"resource": ""
} |
q11463 | find_packages | train | def find_packages(where='.', exclude=(), invalidate_cache=False):
"""
This version of ``find_packages`` caches previous results to speed up
subsequent calls. Use ``invalide_cache=True`` to ignore cached results
from previous ``find_packages`` calls, and repeat the package search.
"""
if exclude:
warnings.warn(
"Use of the exclude parameter is no longer supported since it does "
"not work as expected. Use add_exclude_packages instead. Note that "
"it must be called prior to any other calls from setup helpers.",
AstropyDeprecationWarning)
# Calling add_exclude_packages after this point | python | {
"resource": ""
} |
q11464 | _get_flag_value_from_var | train | def _get_flag_value_from_var(flag, var, delim=' '):
"""
Extract flags from an environment variable.
Parameters
----------
flag : str
The flag to extract, for example '-I' or '-L'
var : str
The environment variable to extract the flag from, e.g. CFLAGS or LDFLAGS.
delim : str, optional
The delimiter separating flags inside the environment variable
Examples
--------
Let's assume the LDFLAGS is set to '-L/usr/local/include -customflag'. This
function will then return the following:
>>> _get_flag_value_from_var('-L', 'LDFLAGS')
'/usr/local/include'
Notes
-----
Environment variables are first checked in ``os.environ[var]``, then in
``distutils.sysconfig.get_config_var(var)``.
This function is not supported on Windows.
"""
if sys.platform.startswith('win'):
return None | python | {
"resource": ""
} |
q11465 | get_openmp_flags | train | def get_openmp_flags():
"""
Utility for returning compiler and linker flags possibly needed for
OpenMP support.
Returns
-------
result : `{'compiler_flags':<flags>, 'linker_flags':<flags>}`
Notes
-----
The flags returned are not tested for validity, use
`check_openmp_support(openmp_flags=get_openmp_flags())` to do so.
"""
compile_flags = []
link_flags = []
if get_compiler_option() == 'msvc':
compile_flags.append('-openmp')
else:
include_path = _get_flag_value_from_var('-I', 'CFLAGS')
if include_path:
compile_flags.append('-I' + include_path)
| python | {
"resource": ""
} |
q11466 | check_openmp_support | train | def check_openmp_support(openmp_flags=None):
"""
Check whether OpenMP test code can be compiled and run.
Parameters
----------
openmp_flags : dict, optional
This should be a dictionary with keys ``compiler_flags`` and
``linker_flags`` giving the compiliation and linking flags respectively.
These are passed as `extra_postargs` to `compile()` and
`link_executable()` respectively. If this is not set, the flags will
be automatically determined using environment variables.
Returns
-------
result : bool
`True` if the test passed, `False` otherwise.
"""
ccompiler = new_compiler()
customize_compiler(ccompiler)
if not openmp_flags:
# customize_compiler() extracts info from os.environ. If certain keys
# exist it uses these plus those from sysconfig.get_config_vars().
# If the key is missing in os.environ it is not extracted from
# sysconfig.get_config_var(). E.g. 'LDFLAGS' get left out, preventing
# clang from finding libomp.dylib because -L<path> is not passed to
# linker. Call get_openmp_flags() to get flags missed by
# customize_compiler().
openmp_flags = get_openmp_flags()
compile_flags = openmp_flags.get('compiler_flags')
link_flags = openmp_flags.get('linker_flags')
# Pass -coverage flag to linker.
# https://github.com/astropy/astropy-helpers/pull/374
if '-coverage' in compile_flags and '-coverage' not in link_flags:
link_flags.append('-coverage')
tmp_dir = tempfile.mkdtemp()
start_dir = os.path.abspath('.')
try:
os.chdir(tmp_dir)
# Write test program
with open('test_openmp.c', 'w') as f:
f.write(CCODE)
os.mkdir('objects')
# Compile, test program | python | {
"resource": ""
} |
q11467 | is_openmp_supported | train | def is_openmp_supported():
"""
Determine whether the build compiler has OpenMP support.
"""
log_threshold = log.set_threshold(log.FATAL)
ret = | python | {
"resource": ""
} |
q11468 | generate_openmp_enabled_py | train | def generate_openmp_enabled_py(packagename, srcdir='.', disable_openmp=None):
"""
Generate ``package.openmp_enabled.is_openmp_enabled``, which can then be used
to determine, post build, whether the package was built with or without
OpenMP support.
"""
if packagename.lower() == 'astropy':
packagetitle = 'Astropy'
else:
packagetitle = packagename
epoch = int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))
timestamp = datetime.datetime.utcfromtimestamp(epoch)
| python | {
"resource": ""
} |
q11469 | HugeTable.GetValue | train | def GetValue(self, row, col):
"""
Find the matching value from pandas DataFrame,
| python | {
"resource": ""
} |
q11470 | HugeTable.SetValue | train | def SetValue(self, row, col, value):
"""
Set value | python | {
"resource": ""
} |
q11471 | HugeTable.SetColumnValues | train | def SetColumnValues(self, col, value):
"""
Custom method to efficiently set all values
in a column.
Parameters
----------
col : str or int
name or index position of column
value : list-like
| python | {
"resource": ""
} |
q11472 | HugeTable.GetColLabelValue | train | def GetColLabelValue(self, col):
"""
Get col label from dataframe
"""
if | python | {
"resource": ""
} |
q11473 | HugeTable.SetColLabelValue | train | def SetColLabelValue(self, col, value):
"""
Set col label value in dataframe
"""
if len(self.dataframe):
col_name = str(self.dataframe.columns[col])
| python | {
"resource": ""
} |
q11474 | BaseMagicGrid.set_scrollbars | train | def set_scrollbars(self):
"""
Set to always have vertical scrollbar.
Have horizontal scrollbar unless grid has very few rows.
Older versions of wxPython will choke on this,
in which case nothing happens.
"""
try:
if len(self.row_labels) < 5:
show_horizontal = wx.SHOW_SB_NEVER
else:
| python | {
"resource": ""
} |
q11475 | BaseMagicGrid.on_edit_grid | train | def on_edit_grid(self, event):
"""sets self.changes to true when user edits the grid.
provides down and up key functionality for exiting the editor"""
if not self.changes:
self.changes = {event.Row}
| python | {
"resource": ""
} |
q11476 | BaseMagicGrid.do_paste | train | def do_paste(self, event):
"""
Read clipboard into dataframe
Paste data into grid, adding extra rows if needed
and ignoring extra columns.
"""
# find where the user has clicked
col_ind = self.GetGridCursorCol()
row_ind = self.GetGridCursorRow()
# read in clipboard text
text_df = pd.read_clipboard(header=None, sep='\t').fillna('')
# add extra rows if need to accomadate clipboard text
row_length_diff = len(text_df) - (len(self.row_labels) - row_ind)
if row_length_diff > 0:
for n in range(row_length_diff):
self.add_row()
| python | {
"resource": ""
} |
q11477 | BaseMagicGrid.update_changes_after_row_delete | train | def update_changes_after_row_delete(self, row_num):
"""
Update self.changes so that row numbers for edited rows are still correct.
I.e., if row 4 was edited and then row 2 was deleted, row 4 becomes row 3.
This function updates self.changes to reflect that.
"""
if row_num in self.changes.copy():
self.changes.remove(row_num)
updated_rows = []
for changed_row in self.changes:
if changed_row == -1:
| python | {
"resource": ""
} |
q11478 | BaseMagicGrid.paint_invalid_cell | train | def paint_invalid_cell(self, row, col, color='MEDIUM VIOLET RED',
skip_cell=False):
"""
Take row, column, and turn it color
| python | {
"resource": ""
} |
q11479 | HugeMagicGrid.add_col | train | def add_col(self, label):
"""
Update table dataframe, and append a new column
Parameters
----------
label : str
Returns
---------
last_col: int
index column number of added col
"""
self.table.dataframe[label] = ''
| python | {
"resource": ""
} |
q11480 | HugeMagicGrid.remove_col | train | def remove_col(self, col_num):
"""
update table dataframe, and remove a column.
resize grid to display correctly
"""
label_value = self.GetColLabelValue(col_num).strip('**').strip('^^')
self.col_labels.remove(label_value)
del | python | {
"resource": ""
} |
q11481 | main | train | def main():
"""
NAME
plotdi_a.py
DESCRIPTION
plots equal area projection from dec inc data and fisher mean, cone of confidence
INPUT FORMAT
takes dec, inc, alpha95 as first three columns in space delimited file
SYNTAX
plotdi_a.py [-i][-f FILE]
OPTIONS
-f FILE to read file name from command line
-fmt [png,jpg,eps,pdf,svg] set plot file format ['svg' is default]
-sav save plot and quit
"""
fmt,plot='svg',0
if len(sys.argv) > 0:
if '-h' in sys.argv: # check if help is needed
print(main.__doc__)
sys.exit() # graceful quit
if '-fmt' in sys.argv:
ind=sys.argv.index('-fmt')
fmt=sys.argv[ind+1]
if '-sav' in sys.argv:plot=1
if '-f' in sys.argv:
ind=sys.argv.index('-f')
file=sys.argv[ind+1]
f=open(file,'r')
data=f.readlines()
else:
data=sys.stdin.readlines() # read in data from standard input
DIs,Pars=[],[]
for line in data: # read in the data from standard input
pars=[]
rec=line.split() # split each line on space to get records
DIs.append([float(rec[0]),float(rec[1])])
pars.append(float(rec[0]))
pars.append(float(rec[1]))
pars.append(float(rec[2]))
pars.append(float(rec[0]))
isign=abs(float(rec[1])) / float(rec[1])
pars.append(float(rec[1])-isign*90.) #Beta inc
pars.append(float(rec[2])) # gamma
pars.append(float(rec[0])+90.) # Beta dec
| python | {
"resource": ""
} |
q11482 | main | train | def main():
"""
NAME
di_rot.py
DESCRIPTION
rotates set of directions to new coordinate system
SYNTAX
di_rot.py [command line options]
OPTIONS
-h prints help message and quits
-f specify input file, default is standard input
-F specify output file, default is standard output
-D D specify Dec of new coordinate system, default is 0
-I I specify Inc of new coordinate system, default is 90
INTPUT/OUTPUT
dec inc [space delimited]
"""
D,I=0.,90.
outfile=""
infile=""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-f' in sys.argv:
ind=sys.argv.index('-f')
infile=sys.argv[ind+1]
data=numpy.loadtxt(infile)
else:
| python | {
"resource": ""
} |
q11483 | Fit.get | train | def get(self,coordinate_system):
"""
Return the pmagpy paramters dictionary associated with this fit and the given
coordinate system
@param: coordinate_system -> the coordinate system who's parameters to return
"""
if coordinate_system == 'DA-DIR' or coordinate_system == 'specimen':
return self.pars
elif coordinate_system == 'DA-DIR-GEO' or coordinate_system == 'geographic':
| python | {
"resource": ""
} |
q11484 | Fit.has_values | train | def has_values(self, name, tmin, tmax):
"""
A basic fit equality checker compares name and bounds of 2 fits
@param: name -> name of the other fit
@param: tmin -> lower bound of the other fit
@param: tmax -> upper bound of the other fit
| python | {
"resource": ""
} |
q11485 | get_n_tail | train | def get_n_tail(tmax, tail_temps):
"""determines number of included tail checks in best fit segment"""
#print "tail_temps: {0}, tmax: {0}".format(tail_temps, tmax)
t_index = 0
adj_tmax = 0
if tmax < tail_temps[0]:
return 0
try:
t_index = list(tail_temps).index(tmax)
except: # finds correct tmax if there was no tail check performed at tmax
| python | {
"resource": ""
} |
q11486 | main | train | def main():
"""
NAME
dir_redo.py
DESCRIPTION
converts the Cogne DIR format to PmagPy redo file
SYNTAX
dir_redo.py [-h] [command line options]
OPTIONS
-h: prints help message and quits
-f FILE: specify input file
-F FILE: specify output file, default is 'zeq_redo'
"""
dir_path='.'
zfile='zeq_redo'
if '-WD' in sys.argv:
ind=sys.argv.index('-WD')
dir_path=sys.argv[ind+1]
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-f' in sys.argv:
ind=sys.argv.index('-f')
inspec=sys.argv[ind+1]
if '-F' in sys.argv:
ind=sys.argv.index('-F')
zfile=sys.argv[ind+1]
inspec=dir_path+"/"+inspec
zfile=dir_path+"/"+zfile
zredo=open(zfile,"w")
#
# read in DIR file
#
specs=[]
prior_spec_data=open(inspec,'r').readlines()
for line in prior_spec_data:
line=line.replace("Dir"," Dir")
line=line.replace("OKir"," OKir")
line=line.replace("Fish"," Fish")
line=line.replace("Man"," Man")
line=line.replace("GC"," GC")
line=line.replace("-T"," - T")
line=line.replace("-M"," - M")
rec=line.split()
if len(rec)<2:
sys.exit()
if rec[1]=='Dir' or rec[1]=='GC': # skip all the other stuff
spec=rec[0]
specs.append(spec)
comp_name=string.uppercase[specs.count(spec)-1] # assign component names
| python | {
"resource": ""
} |
q11487 | MagMainFrame.set_dm | train | def set_dm(self, num):
"""
Make GUI changes based on data model num.
Get info from WD in appropriate format.
"""
#enable or disable self.btn1a
if self.data_model_num == 3:
self.btn1a.Enable()
else:
self.btn1a.Disable()
#
# set pmag_gui_dialogs
global pmag_gui_dialogs
if self.data_model_num == 2:
pmag_gui_dialogs = pgd2
wx.CallAfter(self.get_wd_data2)
elif self.data_model_num == 3:
| python | {
"resource": ""
} |
q11488 | MagMainFrame.get_wd_data | train | def get_wd_data(self):
"""
Show dialog to get user input for which directory
to set as working directory.
Called by self.get_dm_and_wd
"""
| python | {
"resource": ""
} |
q11489 | MagMainFrame.get_wd_data2 | train | def get_wd_data2(self):
"""
Get 2.5 data from self.WD and put it into
ErMagicBuilder object.
Called by get_dm_and_wd
"""
wait = wx.BusyInfo('Reading in data from current | python | {
"resource": ""
} |
q11490 | MagMainFrame.get_dir | train | def get_dir(self):
"""
Choose a working directory dialog.
Called by self.get_dm_and_wd.
"""
if "-WD" in sys.argv and self.FIRST_RUN:
ind = sys.argv.index('-WD')
self.WD = os.path.abspath(sys.argv[ind+1])
os.chdir(self.WD)
| python | {
"resource": ""
} |
q11491 | MagMainFrame.on_btn_thellier_gui | train | def on_btn_thellier_gui(self, event):
"""
Open Thellier GUI
"""
if not self.check_for_meas_file():
return
if not self.check_for_uncombined_files():
return
outstring = "thellier_gui.py -WD %s"%self.WD
print("-I- running python script:\n %s"%(outstring))
if self.data_model_num == 2.5:
thellier_gui.main(self.WD, standalone_app=False, parent=self, DM=self.data_model_num)
else:
# disable and hide Pmag GUI mainframe
self.Disable()
self.Hide()
# show busyinfo
wait = wx.BusyInfo('Compiling required data, please wait...')
wx.SafeYield()
# create custom Thellier GUI closing event and bind it
ThellierGuiExitEvent, EVT_THELLIER_GUI_EXIT = newevent.NewCommandEvent()
| python | {
"resource": ""
} |
q11492 | MagMainFrame.on_btn_demag_gui | train | def on_btn_demag_gui(self, event):
"""
Open Demag GUI
"""
if not self.check_for_meas_file():
return
if not self.check_for_uncombined_files():
return
outstring = "demag_gui.py -WD %s"%self.WD
print("-I- running python script:\n %s"%(outstring))
if self.data_model_num == 2:
demag_gui.start(self.WD, standalone_app=False, parent=self, DM=self.data_model_num)
else:
# disable and hide Pmag GUI mainframe
self.Disable()
| python | {
"resource": ""
} |
q11493 | MagMainFrame.on_btn_convert_3 | train | def on_btn_convert_3(self, event):
"""
Open dialog for rough conversion of
2.5 files to 3.0 files.
Offer link to earthref for proper upgrade.
"""
dia = pw.UpgradeDialog(None)
dia.Center()
res = dia.ShowModal()
if res == wx.ID_CANCEL:
webbrowser.open("https://www2.earthref.org/MagIC/upgrade", new=2)
return
## more nicely styled way, but doesn't link to earthref
#msg = "This tool is meant for relatively simple upgrades (for instance, a measurement file, a sample file, and a criteria file).\nIf you have a more complex contribution to upgrade, and you want maximum accuracy, use the upgrade tool at https://www2.earthref.org/MagIC/upgrade.\n\nDo you want to continue?"
#result = pw.warning_with_override(msg)
#if result == wx.ID_NO:
#webbrowser.open("https://www2.earthref.org/MagIC/upgrade", new=2)
#return
# turn files from 2.5 --> 3.0 (rough translation)
meas, upgraded, no_upgrade = pmag.convert_directory_2_to_3('magic_measurements.txt',
input_dir=self.WD, output_dir=self.WD,
data_model=self.contribution.data_model)
if not meas:
wx.MessageBox('2.5 --> 3.0 failed. Do you have a magic_measurements.txt file in your working directory?',
'Info', wx.OK | wx.ICON_INFORMATION)
return
# create a contribution
self.contribution = cb.Contribution(self.WD)
# make skeleton files with specimen, sample, site, location data
self.contribution.propagate_measurement_info()
# pop up
upgraded_string = ", ".join(upgraded)
if no_upgrade:
no_upgrade_string = ", ".join(no_upgrade)
msg = '2.5 --> 3.0 translation completed!\n\nThese 3.0 | python | {
"resource": ""
} |
q11494 | MagMainFrame.on_btn_metadata | train | def on_btn_metadata(self, event):
"""
Initiate the series of windows to add metadata
to the contribution.
"""
# make sure we have a measurements file
if not self.check_for_meas_file():
return
# make sure all files of the same type have been combined
if not self.check_for_uncombined_files():
return
if self.data_model_num == 2:
wait = wx.BusyInfo('Compiling required data, please wait...')
wx.SafeYield()
self.ErMagic_frame = ErMagicBuilder.MagIC_model_builder(self.WD, self, self.er_magic)
elif self.data_model_num == 3:
wait = wx.BusyInfo('Compiling required data, please wait...')
| python | {
"resource": ""
} |
q11495 | MagMainFrame.on_btn_orientation | train | def on_btn_orientation(self, event):
"""
Create and fill wxPython grid for entering
orientation data.
"""
wait = wx.BusyInfo('Compiling required data, please wait...')
wx.SafeYield()
#dw, dh = wx.DisplaySize()
size = wx.DisplaySize()
size = (size[0]-0.1 * size[0], size[1]-0.1 * size[1])
| python | {
"resource": ""
} |
q11496 | MagMainFrame.on_btn_unpack | train | def on_btn_unpack(self, event):
"""
Create dialog to choose a file to unpack
with download magic.
Then run download_magic and create self.contribution.
"""
dlg = wx.FileDialog(
None, message = "choose txt file to unpack",
defaultDir=self.WD,
defaultFile="",
style=wx.FD_OPEN #| wx.FD_CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
FILE = dlg.GetPath()
input_dir, f = os.path.split(FILE)
else:
return False
outstring="download_magic.py -f {} -WD {} -ID {} -DM {}".format(f, self.WD, input_dir, self.data_model_num)
# run as module:
print("-I- running python script:\n %s"%(outstring))
wait = wx.BusyInfo("Please wait, working...")
wx.SafeYield()
ex = None
try:
if ipmag.download_magic(f, self.WD, input_dir, overwrite=True, data_model=self.data_model):
text = "Successfully ran download_magic.py program.\nMagIC files were saved in your working directory.\nSee Terminal/message window for details."
else:
text = "Something went wrong. Make sure you chose a | python | {
"resource": ""
} |
q11497 | MagMainFrame.on_end_validation | train | def on_end_validation(self, event):
"""
Switch back from validation mode to main Pmag GUI mode.
Hide validation frame and show main frame.
| python | {
"resource": ""
} |
q11498 | MagMainFrame.on_menu_exit | train | def on_menu_exit(self, event):
"""
Exit the GUI
"""
# also delete appropriate copy file
try:
self.help_window.Destroy()
except:
pass
if '-i' in sys.argv:
self.Destroy()
| python | {
"resource": ""
} |
q11499 | MagMainFrame.check_for_meas_file | train | def check_for_meas_file(self):
"""
Check the working directory for a measurement file.
If not found, show a warning and return False.
Otherwise return True.
"""
if self.data_model_num == 2:
meas_file_name = "magic_measurements.txt"
dm = "2.5"
else:
meas_file_name = "measurements.txt"
dm = "3.0"
if not os.path.isfile(os.path.join(self.WD, meas_file_name)):
pw.simple_warning("Your working directory must have a {} format {} file | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.