INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Return a function to parse numbers. | def _number_parser(str_to_number_func):
"""Return a function to parse numbers."""
def _parse_number_value(element_text, state):
value = None
try:
value = str_to_number_func(element_text)
except (ValueError, TypeError):
state.raise_error(InvalidPrimitiveValue,
... |
Parse the raw XML string as a boolean value. | def _parse_boolean(element_text, state):
"""Parse the raw XML string as a boolean value."""
value = None
lowered_text = element_text.lower()
if lowered_text == 'true':
value = True
elif lowered_text == 'false':
value = False
else:
state.raise_error(InvalidPrimitiveValue,... |
Return a parser function for parsing string values. | def _string_parser(strip_whitespace):
"""Return a parser function for parsing string values."""
def _parse_string_value(element_text, _state):
if element_text is None:
value = ''
elif strip_whitespace:
value = element_text.strip()
else:
value = element... |
Return an _AggregateConverter for a user object of the given class. | def _user_object_converter(cls):
# type: (Type[Any]) -> _AggregateConverter
"""Return an _AggregateConverter for a user object of the given class."""
def _from_dict(dict_value):
try:
object_value = cls(**dict_value)
except TypeError:
# Constructor does not support key... |
Strip the XML namespace prefix from all element tags under the given root Element. | def _xml_namespace_strip(root):
# type: (ET.Element) -> None
"""Strip the XML namespace prefix from all element tags under the given root Element."""
if '}' not in root.tag:
return # Nothing to do, no namespace present
for element in root.iter():
if '}' in element.tag:
elem... |
Parse the provided element as an aggregate. | def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the provided element as an aggregate."""
parsed_dict = self._dictionary.parse_at_element(element, state)
return self._converter... |
Parse the root XML element as an aggregate. | def parse_at_root(
self,
root, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the root XML element as an aggregate."""
parsed_dict = self._dictionary.parse_at_root(root, state)
return self._converter.from_dict(p... |
Parse the aggregate from the provided parent XML element. | def parse_from_parent(
self,
parent, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the aggregate from the provided parent XML element."""
parsed_dict = self._dictionary.parse_from_parent(parent, state)
return s... |
Serialize the value to a new element and returns the element. | def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize the value to a new element and returns the element."""
dict_value = self._converter.to_dict(value)
return self._dictionary.serialize... |
Serialize the value and adds it to the parent. | def serialize_on_parent(
self,
parent, # type: ET.Element
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize the value and adds it to the parent."""
dict_value = self._converter.to_dict(value)
self... |
Parse the provided element as an array. | def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the provided element as an array."""
item_iter = element.findall(self._item_processor.element_path)
return self._parse(item_ite... |
Parse the root XML element as an array. | def parse_at_root(
self,
root, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the root XML element as an array."""
if not self._nested:
raise InvalidRootProcessor('Non-nested array "{}" cannot be root elemen... |
Parse the array data from the provided parent XML element. | def parse_from_parent(
self,
parent, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the array data from the provided parent XML element."""
item_iter = parent.findall(self._item_path)
return self._parse(item_ite... |
Serialize the value into a new Element object and return it. | def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize the value into a new Element object and return it."""
if self._nested is None:
state.raise_error(InvalidRootProcessor,
... |
Serialize the value and append it to the parent element. | def serialize_on_parent(
self,
parent, # type: ET.Element
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize the value and append it to the parent element."""
if not value and self.required:
st... |
Parse the array data using the provided iterator of XML elements. | def _parse(
self,
item_iter, # type: Iterable[ET.Element]
state # type: _ProcessorState
):
# type: (...) -> List
"""Parse the array data using the provided iterator of XML elements."""
parsed_array = []
for i, item in enumerate(item_iter):
... |
Serialize the array value and add it to the array parent element. | def _serialize(
self,
array_parent, # type: ET.Element
value, # type: List
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize the array value and add it to the array parent element."""
if not value:
# Nothing to ... |
Parse the provided element as a dictionary. | def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the provided element as a dictionary."""
parsed_dict = {}
for child in self._child_processors:
state.push_location... |
Parse the root XML element as a dictionary. | def parse_at_root(
self,
root, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the root XML element as a dictionary."""
parsed_dict = {} # type: Dict
dict_element = _element_find_from_root(root, self.element_pa... |
Serialize the value to a new element and return the element. | def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize the value to a new element and return the element."""
if not value and self.required:
state.raise_error(
Missing... |
Serialize the dictionary and append all serialized children to the element. | def _serialize(
self,
element, # type: ET.Element
value, # type: Dict
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize the dictionary and append all serialized children to the element."""
for child in self._child_processor... |
Parse the given element. | def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the given element."""
xml_value = self._processor.parse_at_element(element, state)
return _hooks_apply_after_parse(self._hooks,... |
Parse the given element as the root of the document. | def parse_at_root(
self,
root, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the given element as the root of the document."""
xml_value = self._processor.parse_at_root(root, state)
return _hooks_apply_after_pa... |
Parse the element from the given parent element. | def parse_from_parent(
self,
parent, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the element from the given parent element."""
xml_value = self._processor.parse_from_parent(parent, state)
return _hooks_apply_... |
Serialize the value and returns it. | def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize the value and returns it."""
xml_value = _hooks_apply_before_serialize(self._hooks, state, value)
return self._processor.serialize(x... |
Serialize the value directory on the parent. | def serialize_on_parent(
self,
parent, # type: ET.Element
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize the value directory on the parent."""
xml_value = _hooks_apply_before_serialize(self._hooks, sta... |
Parse the primitive value at the XML element. | def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the primitive value at the XML element."""
if self._attribute:
parsed_value = self._parse_attribute(element, self._attribut... |
Parse the primitive value under the parent XML element. | def parse_from_parent(
self,
parent, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the primitive value under the parent XML element."""
element = parent.find(self.element_path)
if element is None and self.requ... |
Serialize the value and add it to the parent element. | def serialize_on_parent(
self,
parent, # type: ET.Element
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize the value and add it to the parent element."""
# Note that falsey values are not treated as miss... |
Return the message to report that the value needed for serialization is missing. | def _missing_value_message(self, parent):
# type: (ET.Element) -> Text
"""Return the message to report that the value needed for serialization is missing."""
if self._attribute is None:
message = 'Missing required value for element "{}"'.format(self.element_path)
else:
... |
Parse the primitive value within the XML element's attribute. | def _parse_attribute(
self,
element, # type: ET.Element
attribute, # type: Text
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the primitive value within the XML element's attribute."""
parsed_value = self._default
at... |
Serialize the value to the element. | def _serialize(
self,
element, # type: ET.Element
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> None
"""Serialize the value to the element."""
xml_value = _hooks_apply_before_serialize(self._hooks, state, value)
... |
Push an item onto the state's stack of locations. | def push_location(
self,
element_path, # type: Text
array_index=None # type: Optional[int]
):
# type: (...) -> None
"""Push an item onto the state's stack of locations."""
location = ProcessorLocation(element_path=element_path, array_index=array_index)
... |
Raise an exception with the current parser state information and error message. | def raise_error(
self,
exception_type, # type: Type[Exception]
message # type: Text
):
# type: (...) -> NoReturn
"""Raise an exception with the current parser state information and error message."""
error_message = '{} at {}'.format(message, repr(self))
... |
call eagle and export sch or brd to partlist text file
:param input: .sch or .brd file name
:param output: text file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: None | def export_partlist_to_file(input, output, timeout=20, showgui=False):
'''
call eagle and export sch or brd to partlist text file
:param input: .sch or .brd file name
:param output: text file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: None
'''
... |
parse partlist text delivered by eagle.
header is converted to lowercase
:param str: input string
:rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value':'1n'}, ..]) | def parse_partlist(str):
'''parse partlist text delivered by eagle.
header is converted to lowercase
:param str: input string
:rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value':'1n'}, ..])
'''
lines = str.strip().splitlines()
lines = filter(len, lines)... |
export partlist by eagle, then return it
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: string | def raw_partlist(input, timeout=20, showgui=False):
'''export partlist by eagle, then return it
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: string
'''
output = tempfile.NamedTemporaryFile(
prefix='eagexp_', su... |
export partlist by eagle, then parse it
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value':'1n'}, ..]) | def structured_partlist(input, timeout=20, showgui=False):
'''export partlist by eagle, then parse it
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: tuple of header list and dict list: (['part','value',..], [{'part':'C1', 'value'... |
print partlist text delivered by eagle
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: None | def print_partlist(input, timeout=20, showgui=False):
'''print partlist text delivered by eagle
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: None
'''
print raw_partlist(input=input, timeout=timeout, showgui=showgui) |
Graphviz source for the Hasse diagram of the domains' Boolean algebra. | def bitset(bs, member_label=None, filename=None, directory=None, format=None,
render=False, view=False):
"""Graphviz source for the Hasse diagram of the domains' Boolean algebra."""
if member_label is None:
member_label = MEMBER_LABEL
if filename is None:
kind = 'members' if memb... |
Patches a Django Field's `__init__` method for easier usage of optional `kwargs`. It defines a `humanized` attribute
on a field for better display of its value. | def field_init(self, *args, **kwargs):
"""
Patches a Django Field's `__init__` method for easier usage of optional `kwargs`. It defines a `humanized` attribute
on a field for better display of its value.
"""
humanize_func = kwargs.pop('humanized', None)
if humanize_func:
def humanize(val... |
Returns a reference to the form element's constructor method. | def _get_field_method(self, tp):
"""Returns a reference to the form element's constructor method."""
method = self.field_constructor.get(tp)
if method and hasattr(self, method.__name__):
return getattr(self, method.__name__)
return method |
Creates the form element. | def _create_plain_field(self, attr, options):
"""Creates the form element."""
method = self._get_field_method(attr.py_type) or self._create_other_field
klass, options = method(attr, options)
if attr.is_unique:
options['validators'].append(validators.UniqueEntityValidator(att... |
Creates the form element for working with entity relationships. | def _create_relational_field(self, attr, options):
"""Creates the form element for working with entity relationships."""
options['entity_class'] = attr.py_type
options['allow_empty'] = not attr.is_required
return EntityField, options |
Adds an element to the form based on the entity attribute. | def add(self, attr, field_class=None, **options):
"""Adds an element to the form based on the entity attribute."""
# print(attr.name, attr.py_type, getattr(attr, 'set', None))
# print(dir(attr))
# print(attr, attr.is_relation, attr.is_collection)
# print(attr.is_pk, attr.auto, at... |
Adds a button to the form. | def add_button(self, name, button_class=wtf_fields.SubmitField, **options):
"""Adds a button to the form."""
self._buttons[name] = button_class(**options) |
Creates a form element for the UUID type. | def field_uuid(self, attr, options):
"""Creates a form element for the UUID type."""
options['validators'].append(validators.UUIDValidator(attr.entity))
return wtf_fields.StringField, options |
Exporting eagle .sch or .brd file into image file.
GUI is not displayed if ``pyvirtualdisplay`` is installed.
If export is blocked somehow (e.g. popup window is displayed) then after timeout operation is canceled with exception.
Problem can be investigated by setting 'showgui' flag.
Exporting generates... | def export_image(input, output, timeout=20, palette='white', resolution=150, layers=None, command=None, mirror=False, showgui=False):
'''
Exporting eagle .sch or .brd file into image file.
GUI is not displayed if ``pyvirtualdisplay`` is installed.
If export is blocked somehow (e.g. popup window is displ... |
This is super minimal and pretty hacky, but it counts as a first pass. | def runm():
""" This is super minimal and pretty hacky, but it counts as a first pass.
"""
signal.signal(signal.SIGINT, signal_handler)
count = int(sys.argv.pop(1))
processes = [Process(target=run, args=()) for x in range(count)]
try:
for p in processes:
p.start()
except ... |
Establish what identity this user claims to have from request.
:param request: Request to extract identity information from.
:type request: :class:`morepath.Request`.
:returns: :class:`morepath.Identity` instance or
:attr:`morepath.NO_IDENTITY` if identity cannot
be establis... | def identify(self, request):
"""Establish what identity this user claims to have from request.
:param request: Request to extract identity information from.
:type request: :class:`morepath.Request`.
:returns: :class:`morepath.Identity` instance or
:attr:`morepath.NO_IDENTITY` ... |
Remember identity on response.
Implements ``morepath.App.remember_identity``, which is called
from user login code.
Create a JWT token and return it as the Authorization field of the
response header.
:param response: response object on which to store identity.
:type re... | def remember(self, response, request, identity):
"""Remember identity on response.
Implements ``morepath.App.remember_identity``, which is called
from user login code.
Create a JWT token and return it as the Authorization field of the
response header.
:param response: ... |
Decode a JWTAuth token into its claims set.
This method decodes the given JWT to provide the claims set. The JWT
can fail if the token has expired (with appropriate leeway) or if the
token won't validate due to the secret (key) being wrong.
If private_key/public key is set then the pu... | def decode_jwt(self, token, verify_expiration=True):
"""Decode a JWTAuth token into its claims set.
This method decodes the given JWT to provide the claims set. The JWT
can fail if the token has expired (with appropriate leeway) or if the
token won't validate due to the secret (key) be... |
Create the claims set based on the userid of the claimed identity,
the settings and the extra_claims dictionary.
The userid will be stored in settings.jwtauth.userid_claim
(default: "sub").
If settings.jwtauth.expiration_delta is set it will be added
to the current time and stor... | def create_claims_set(self, request, userid, extra_claims=None):
"""Create the claims set based on the userid of the claimed identity,
the settings and the extra_claims dictionary.
The userid will be stored in settings.jwtauth.userid_claim
(default: "sub").
If settings.jwtauth.e... |
Encode a JWT token based on the claims_set and the settings.
If available, registry.settings.jwtauth.private_key is used as key.
In this case the algorithm must be an RS* or EC* algorithm.
If registry.settings.jwtauth.private_key is not set,
registry.settings.jwtauth.master_secret is us... | def encode_jwt(self, claims_set):
"""Encode a JWT token based on the claims_set and the settings.
If available, registry.settings.jwtauth.private_key is used as key.
In this case the algorithm must be an RS* or EC* algorithm.
If registry.settings.jwtauth.private_key is not set,
... |
Get claims holding extra identity info from the claims set.
Returns a dictionary of extra claims or None if there are none.
:param claims_set: set of claims, which was included in the received
token. | def get_extra_claims(self, claims_set):
"""Get claims holding extra identity info from the claims set.
Returns a dictionary of extra claims or None if there are none.
:param claims_set: set of claims, which was included in the received
token.
"""
reserved_claims = (
... |
Extract the JWT token from the authorisation header of the request.
Returns the JWT token or None, if the token cannot be extracted.
:param request: request object.
:type request: :class:`morepath.Request` | def get_jwt(self, request):
"""Extract the JWT token from the authorisation header of the request.
Returns the JWT token or None, if the token cannot be extracted.
:param request: request object.
:type request: :class:`morepath.Request`
"""
try:
authorizatio... |
Verify if the request to refresh the token is valid.
If valid it returns the userid which can be used to create
an updated identity with ``remember_identity``.
Otherwise it raises an exception based on InvalidTokenError.
:param request: current request object
:type request: :cla... | def verify_refresh(self, request):
"""
Verify if the request to refresh the token is valid.
If valid it returns the userid which can be used to create
an updated identity with ``remember_identity``.
Otherwise it raises an exception based on InvalidTokenError.
:param requ... |
Compute a robust linear fit using the Theil-Sen method.
See http://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator for details.
This function "pairs up sample points by the rank of their x-coordinates
(the point with the smallest coordinate being paired with the first point
above the median coordinat... | def fit_theil_sen(x, y):
"""Compute a robust linear fit using the Theil-Sen method.
See http://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator for details.
This function "pairs up sample points by the rank of their x-coordinates
(the point with the smallest coordinate being paired with the first poin... |
Entry point for the Numina CLI. | def main(args=None):
"""Entry point for the Numina CLI."""
# Configuration args from a text file
config = configparser.SafeConfigParser()
# Building programatically
config.add_section('numina')
config.set('numina', 'format', 'yaml')
# Custom values
config.read([
os.path.join(x... |
Process arguments unknown to the parser | def process_unknown_arguments(unknowns):
"""Process arguments unknown to the parser"""
result = argparse.Namespace()
result.extra_control = {}
# It would be interesting to use argparse internal
# machinery for this
for unknown in unknowns:
# Check prefixes
prefix = '--parameter-... |
Helper function for getting a file descriptor. | def get_fd(file_or_fd, default=None):
"""Helper function for getting a file descriptor."""
fd = file_or_fd
if fd is None:
fd = default
if hasattr(fd, "fileno"):
fd = fd.fileno()
return fd |
Fork a child process. | def forkexec(argv, env=None):
"""Fork a child process."""
child_pid = os.fork()
if child_pid == 0:
os.closerange(3, MAXFD)
environ = os.environ.copy()
if env is not None:
environ.update(env)
os.execve(argv[0], argv, environ)
return child_pid |
Fork a child process attached to a pty. | def forkexec_pty(argv, env=None, size=None):
"""Fork a child process attached to a pty."""
child_pid, child_fd = pty.fork()
if child_pid == 0:
os.closerange(3, MAXFD)
environ = os.environ.copy()
if env is not None:
environ.update(env)
os.execve(argv[0], argv, envi... |
Find an executable by searching the user's $PATH. | def find_executable(filename, environ=None):
"""Find an executable by searching the user's $PATH."""
if environ is None:
environ = os.environ
path = environ.get("PATH", "/usr/local/bin:/usr/bin:/bin").split(":")
for dirpath in path:
dirpath = os.path.abspath(dirpath.strip())
file... |
Get a list of the executables of all ancestor processes. | def get_ancestor_processes():
"""Get a list of the executables of all ancestor processes."""
if not _ANCESTOR_PROCESSES and psutil is not None:
proc = psutil.Process(os.getpid())
while proc.parent() is not None:
try:
_ANCESTOR_PROCESSES.append(proc.parent().exe())
... |
Get the user's default shell program. | def get_default_shell(environ=None, fallback=_UNSPECIFIED):
"""Get the user's default shell program."""
if environ is None:
environ = os.environ
# If the option is specified in the environment, respect it.
if "PIAS_OPT_SHELL" in environ:
return environ["PIAS_OPT_SHELL"]
# Find all ca... |
Get the user's default terminal program. | def get_default_terminal(environ=None, fallback=_UNSPECIFIED):
"""Get the user's default terminal program."""
if environ is None:
environ = os.environ
# If the option is specified in the environment, respect it.
if "PIAS_OPT_TERMINAL" in environ:
return environ["PIAS_OPT_TERMINAL"]
#... |
Get the path to the playitagainsam command-line script. | def get_pias_script(environ=None):
"""Get the path to the playitagainsam command-line script."""
if os.path.basename(sys.argv[0]) == "pias":
return sys.argv[0]
filepath = find_executable("pias", environ)
if filepath is not None:
return filepath
filepath = os.path.join(os.path.dirname... |
Get the (width, height) size tuple for the given pty fd. | def get_terminal_size(fd):
"""Get the (width, height) size tuple for the given pty fd."""
sizebuf = array.array('h', [0, 0])
fcntl.ioctl(fd, termios.TIOCGWINSZ, sizebuf, True)
return tuple(reversed(sizebuf)) |
Set the (width, height) size tuple for the given pty fd. | def set_terminal_size(fd, size):
"""Set the (width, height) size tuple for the given pty fd."""
sizebuf = array.array('h', reversed(size))
fcntl.ioctl(fd, termios.TIOCSWINSZ, sizebuf) |
search for airwires in eagle board | def airwires(board, showgui=0):
'search for airwires in eagle board'
board = Path(board).expand().abspath()
file_out = tempfile.NamedTemporaryFile(suffix='.txt', delete=0)
file_out.close()
ulp = ulp_templ.replace('FILE_NAME', file_out.name)
file_ulp = tempfile.NamedTemporaryFile(suffix='.ulp'... |
Set up tables in SQL | def _initialize(self, con):
"""Set up tables in SQL"""
if self.initialized:
return
SQLite3Database()._initialize(con) # ASE db initialization
cur = con.execute(
'SELECT COUNT(*) FROM sqlite_master WHERE name="reaction"')
if cur.fetchone()[0] == 0: # n... |
Return an entire row of a table
Parameters
---------
id: int
row integer
table: str
'reaction', 'publication', 'publication_system', 'reaction_system' | def read(self, id, table='reaction'):
""" Return an entire row of a table
Parameters
---------
id: int
row integer
table: str
'reaction', 'publication', 'publication_system', 'reaction_system'
"""
con = self.connection or self._connect()
... |
Write publication info to db
Parameters
----------
values: dict with entries
{'pub_id': str (short name for publication),
'authors': list of str ()
'journal': str,
'volume': str,
'number': str,
'pages': 'str'
'y... | def write_publication(self, values):
"""
Write publication info to db
Parameters
----------
values: dict with entries
{'pub_id': str (short name for publication),
'authors': list of str ()
'journal': str,
'volume': str,
... |
Write reaction info to db file
Parameters
----------
values: dict
The values dict can include:
{'chemical_composition': str (chemical composition on empty slab) ,
'surface_composition': str (reduced chemical composition or
shortn... | def write(self, values, data=None):
"""
Write reaction info to db file
Parameters
----------
values: dict
The values dict can include:
{'chemical_composition': str (chemical composition on empty slab) ,
'surface_composition': str (reduced chemical compos... |
Update reaction info for a selected row
Parameters
----------
id: int
row integer
values: dict
See write() method for details
key_names: list or 'all'
list with name of columns to update. Should match the keys-value
pairs in values... | def update(self, id, values, key_names='all'):
"""
Update reaction info for a selected row
Parameters
----------
id: int
row integer
values: dict
See write() method for details
key_names: list or 'all'
list with name of columns... |
Get the id of the last written row in table
Parameters
----------
cur: database connection().cursor() object
table: str
'reaction', 'publication', 'publication_system', 'reaction_system'
Returns: id | def get_last_id(self, cur, table='reaction'):
"""
Get the id of the last written row in table
Parameters
----------
cur: database connection().cursor() object
table: str
'reaction', 'publication', 'publication_system', 'reaction_system'
Returns: id
... |
Check if entry with same surface and energy is allready written
to database file
Parameters
----------
chemcial_composition: str
reaction_energy: str
Returns id or None | def check(self, chemical_composition, reaction_energy):
"""
Check if entry with same surface and energy is allready written
to database file
Parameters
----------
chemcial_composition: str
reaction_energy: str
Returns id or None
"""
con = ... |
Check if entry with same surface and reaction is allready written
to database file
Parameters
----------
chemcial_composition: str
reactants: dict
products: dict
Returns id or None | def check_reaction_on_surface(self, chemical_composition, reactants,
products):
"""
Check if entry with same surface and reaction is allready written
to database file
Parameters
----------
chemcial_composition: str
reactants: dic... |
Compute a collapsed spectrum from a 2D image using scans in [ns1,ns2].
Parameters
----------
fitsfile : file object
File name of FITS file containing the spectra to be calibrated.
ns1 : int
First scan (from 1 to NAXIS2).
ns2 : int
Last scan (from 1 to NAXIS2).
method : s... | def collapsed_spectrum(fitsfile, ns1, ns2,
method='mean', nwin_background=0,
reverse=False, out_sp=None, debugplot=0):
"""Compute a collapsed spectrum from a 2D image using scans in [ns1,ns2].
Parameters
----------
fitsfile : file object
File name o... |
read arc line wavelengths from numpy array
Parameters
----------
master_table : Numpy array
Numpy array containing the wavelength database.
lines : string
Indicates which lines to read. For files with a single column
or two columns this parameter is irrelevant. For files with
... | def read_wv_master_from_array(master_table, lines='brightest', debugplot=0):
"""read arc line wavelengths from numpy array
Parameters
----------
master_table : Numpy array
Numpy array containing the wavelength database.
lines : string
Indicates which lines to read. For files with a ... |
read arc line wavelengths from external file.
Parameters
----------
wv_master_file : string
File name of txt file containing the wavelength database.
lines : string
Indicates which lines to read. For files with a single column
or two columns this parameter is irrelevant. For fil... | def read_wv_master_file(wv_master_file, lines='brightest', debugplot=0):
"""read arc line wavelengths from external file.
Parameters
----------
wv_master_file : string
File name of txt file containing the wavelength database.
lines : string
Indicates which lines to read. For files w... |
Locate line peaks in array coordinates (from 0 to naxis1-1).
Parameters
----------
sp : 1d numpy array
Spectrum to be wavelength calibrated.
times_sigma_threshold : float
Times robust sigma above the median to detect line peaks.
minimum_threshold : float or None
Minimum ... | def find_fxpeaks(sp,
times_sigma_threshold,
minimum_threshold,
nwinwidth_initial,
nwinwidth_refined,
npix_avoid_border,
nbrightlines,
sigma_gaussian_filtering,
minimum_gaussian_filteri... |
Execute wavelength calibration of a spectrum using fixed line peaks.
Parameters
----------
sp : 1d numpy array
Spectrum to be wavelength calibrated.
fxpeaks : 1d numpy array
Refined location of peaks in array index scale, i.e, from 0
to naxis1 - 1. The wavelength calibration is ... | def wvcal_spectrum(sp, fxpeaks, poly_degree_wfit, wv_master,
wv_ini_search=None, wv_end_search=None,
wvmin_useful=None, wvmax_useful=None,
geometry=None, debugplot=0):
"""Execute wavelength calibration of a spectrum using fixed line peaks.
Parameters
... |
get_thumbnail version that uses aliasses defined in THUMBNAIL_OPTIONS_DICT | def get_thumbnail(file_, name):
"""
get_thumbnail version that uses aliasses defined in THUMBNAIL_OPTIONS_DICT
"""
options = settings.OPTIONS_DICT[name]
opt = copy(options)
geometry = opt.pop('geometry')
return original_get_thumbnail(file_, geometry, **opt) |
Set the foreground color. | def foreground(color):
"""Set the foreground color."""
if color not in foreground_colors:
return
if is_win32:
last_fg = foreground_colors[color][1]
set_color_win32(last_fg | last_bg)
else:
set_color_ansi(foreground_colors[color][0]) |
Set the background color. | def background(color):
"""Set the background color."""
if color not in background_colors:
return
if is_win32:
last_bg = background_colors[color][1]
set_color_win32(last_fg | last_bg)
else:
set_color_ansi(background_colors[color][0]) |
Return a new bitset class with given name and members.
Args:
name: Name of the class to be created.
members: Hashable sequence of allowed bitset members.
base: Base class to derive the returned class from.
list (bool): Include a custom class for bitset lists.
tuple (bool): I... | def bitset(name, members, base=bases.BitSet, list=False, tuple=False):
"""Return a new bitset class with given name and members.
Args:
name: Name of the class to be created.
members: Hashable sequence of allowed bitset members.
base: Base class to derive the returned class from.
... |
Check permited values of extrapolation. | def _extrapolation(self, extrapolate):
"""Check permited values of extrapolation."""
modes = ['extrapolate',
'raise',
'const',
'border']
if extrapolate not in modes:
msg = 'invalid extrapolation mode {}'.format(extrapolate)
... |
Estimate secants | def _create_s(y, h):
"""Estimate secants"""
s = np.zeros_like(y)
s[:-1] = (y[1:] - y[:-1]) / h[:-1]
s[-1] = 0.0
return s |
increase between samples | def _create_h(x):
"""increase between samples"""
h = np.zeros_like(x)
h[:-1] = x[1:] - x[:-1]
# border
h[-1] = h[-2]
return h |
Parabolic derivative | def _create_p(s, h):
"""Parabolic derivative"""
p = np.zeros_like(s)
p[1:] = (s[:-1]*h[1:] + s[1:] * h[:-1]) / (h[1:] + h[:-1])
return p |
Eval polynomial inside bounds. | def _eval(self, v, in_bounds, der):
"""Eval polynomial inside bounds."""
result = np.zeros_like(v, dtype='float')
x_indices = np.searchsorted(self._x, v, side='rigth')
ids = x_indices[in_bounds] - 1
u = v[in_bounds] - self._x[ids]
result[in_bounds] = self._poly_eval(u, id... |
Extrapolate result based on extrapolation mode. | def _extrapolate(self, result, v, below_bounds, above_bounds, der):
"""Extrapolate result based on extrapolation mode."""
if self.extrapolate_mode == 'const':
fill_b = fill_a = self.fill_value
elif self.extrapolate_mode == 'border':
fill_b = self._poly_eval(0, 0, der)
... |
Evaluate internal polynomial. | def _poly_eval(self, u, ids, der=0):
"""Evaluate internal polynomial."""
if der == 0:
return self._poly_eval_0(u, ids)
elif der == 1:
return self._poly_eval_1(u, ids)
elif der == 2:
return self._poly_eval_2(u, ids)
elif der == 3:
re... |
Evaluate internal polynomial. | def _poly_eval_0(self, u, ids):
"""Evaluate internal polynomial."""
return u * (u * (self._a[ids] * u + self._b[ids]) + self._c[ids]) + self._d[ids] |
Evaluate internal polynomial. | def _poly_eval_1(self, u, ids):
"""Evaluate internal polynomial."""
return (u * (3*self._a[ids] * u + 2*self._b[ids]) + self._c[ids]) |
Evaluate internal polynomial. | def _poly_eval_2(self, u, ids):
"""Evaluate internal polynomial."""
return 6 * self._a[ids] * u + 2*self._b[ids] |
Check which values are out of bounds.
Raises
------
ValueError: | def _check_bounds(self, v):
"""Check which values are out of bounds.
Raises
------
ValueError:
"""
below_bounds = v < self._x[0]
above_bounds = v > self._x[-1]
if self.bounds_error and below_bounds.any():
raise ValueError("A value in x_new i... |
Validate tags | def tags_are_valid(subset, superset):
"""Validate tags"""
for key, val in subset.items():
if key in superset and superset[key] != val:
return False
return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.