_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q54100 | Ztimerset.add | train | def add(self, interval, handler, arg):
"""
Add a timer to the set. Returns timer id if OK, -1 on failure.
"""
return lib.ztimerset_add(self._as_parameter_, interval, handler, arg) | python | {
"resource": ""
} |
q54101 | Ztimerset.set_interval | train | def set_interval(self, timer_id, interval):
"""
Set timer interval. Returns 0 if OK, -1 on failure.
This method is slow, canceling the timer and adding a new one yield better performance.
"""
return lib.ztimerset_set_interval(self._as_parameter_, timer_id, interval) | python | {
"resource": ""
} |
q54102 | Ztrie.insert_route | train | def insert_route(self, path, data, destroy_data_fn):
"""
Inserts a new route into the tree and attaches the data. Returns -1
if the route already exists, otherwise 0. This method takes ownership of
the provided data if a destroy_data_fn is provided.
"""
return lib.ztrie_insert_route(self... | python | {
"resource": ""
} |
q54103 | ae | train | def ae(actual, predicted):
"""
Computes the absolute error.
This function computes the absolute error between two numbers,
or for element between a pair of lists or numpy arrays.
Parameters
----------
actual : int, float, list of numbers, numpy array
The ground truth value
... | python | {
"resource": ""
} |
q54104 | ce | train | def ce(actual, predicted):
"""
Computes the classification error.
This function computes the classification error between two lists
Parameters
----------
actual : list
A list of the true classes
predicted : list
A list of the predicted classes
Returns
... | python | {
"resource": ""
} |
q54105 | se | train | def se(actual, predicted):
"""
Computes the squared error.
This function computes the squared error between two numbers,
or for element between a pair of lists or numpy arrays.
Parameters
----------
actual : int, float, list of numbers, numpy array
The ground truth value
p... | python | {
"resource": ""
} |
q54106 | sle | train | def sle(actual, predicted):
"""
Computes the squared log error.
This function computes the squared log error between two numbers,
or for element between a pair of lists or numpy arrays.
Parameters
----------
actual : int, float, list of numbers, numpy array
The ground truth va... | python | {
"resource": ""
} |
q54107 | display_grid_scores | train | def display_grid_scores(grid_scores, top=None):
"""Helper function to format a report on a grid of scores"""
grid_scores = sorted(grid_scores, key=lambda x: x[1], reverse=True)
if top is not None:
grid_scores = grid_scores[:top]
# Compute a threshold for staring models with overlapping ... | python | {
"resource": ""
} |
q54108 | FASTQ.guess_phred_format | train | def guess_phred_format(self):
"""Guess the PHRED score format. The gold standard is the first one, aka
the one called "Sanger". Sanger encoding is exactly equivalent to
Illumina-1.8 encoding. In other words, they finally gave up with their bullshit."""
# Possibilities #
self.inte... | python | {
"resource": ""
} |
q54109 | FASTQ.phred_13_to_18 | train | def phred_13_to_18(self, new_path=None, in_place=True):
"""Illumina-1.3 format conversion to Illumina-1.8 format via BioPython."""
# New file #
if new_path is None: new_fastq = self.__class__(new_temp_path(suffix=self.extension))
else: new_fastq = self.__class__(new_path)
... | python | {
"resource": ""
} |
q54110 | Preferences.set_key | train | def set_key(self, section, key, value):
"""
Stores given key in settings file.
:param section: Current section to save the key into.
:type section: unicode
:param key: Current key to save.
:type key: unicode
:param value: Current key value to save.
:type ... | python | {
"resource": ""
} |
q54111 | Preferences.get_key | train | def get_key(self, section, key):
"""
Gets key value from settings file.
:param section: Current section to retrieve key from.
:type section: unicode
:param key: Current key to retrieve.
:type key: unicode
:return: Current key value.
:rtype: object
... | python | {
"resource": ""
} |
q54112 | Preferences.key_exists | train | def key_exists(self, section, key):
"""
Checks if given key exists.
:param section: Current section to check key in.
:type section: unicode
:param key: Current key to check.
:type key: unicode
:return: Key existence.
:rtype: bool
"""
LOGG... | python | {
"resource": ""
} |
q54113 | Preferences.__get_default_settings | train | def __get_default_settings(self):
"""
Gets the default settings.
"""
LOGGER.debug("> Accessing '{0}' default settings file!".format(UiConstants.settings_file))
self.__default_settings = QSettings(
umbra.ui.common.get_resource_path(UiConstants.settings_file), QSetting... | python | {
"resource": ""
} |
q54114 | Preferences.__get_default_layouts_settings | train | def __get_default_layouts_settings(self):
"""
Gets the default layouts settings.
"""
LOGGER.debug("> Accessing '{0}' default layouts settings file!".format(UiConstants.layouts_file))
self.__default_layouts_settings = QSettings(umbra.ui.common.get_resource_path(UiConstants.layout... | python | {
"resource": ""
} |
q54115 | Preferences.set_default_preferences | train | def set_default_preferences(self):
"""
Defines the default settings file content.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Initializing default settings!")
for key in self.__default_settings.allKeys():
self.__settings.setValue(key, ... | python | {
"resource": ""
} |
q54116 | Preferences.set_default_layouts | train | def set_default_layouts(self, ignored_layouts=None):
"""
Sets the default layouts in the preferences file.
:param ignored_layouts: Ignored layouts.
:type ignored_layouts: tuple or list
:return: Method success.
:rtype: bool
"""
for key in self.__default_l... | python | {
"resource": ""
} |
q54117 | Worker.run | train | def run(self):
"""
Blocking method that run the server.
"""
if self.tasks:
logger.info('Registered tasks: %s' % ', '.join(self.tasks))
else:
logger.info('No tasks registered')
logger.info('Listening on %s ...' % self.bind)
self.socket.bind(... | python | {
"resource": ""
} |
q54118 | Worker.stop | train | def stop(self):
"""
Stop server and all its threads.
"""
try:
self.running = False
logger.info('Waiting tasks to finish...')
self.queue.join()
self.socket.close()
logger.info('Exiting (C-Ctrl again to force it)...')
exce... | python | {
"resource": ""
} |
q54119 | mount_volume | train | def mount_volume(volume, device='/dev/xvdf', mountpoint='/mnt/data', fstype='ext4'):
'''
Mount an EBS volume
Args:
volume (str): EBS volume ID
device (str): default /dev/xvdf
mountpoint (str): default /mnt/data
fstype (str): default ext4
'''
_ec2().attach_volume(volu... | python | {
"resource": ""
} |
q54120 | get_input_ids | train | def get_input_ids(query, limit=None):
"""Get the ids of existing input documents that match a query"""
docs = scan(_es, index=esconfig.ES_INPUT_INDEX,
doc_type=esconfig.ES_INPUT_DOCTYPE,
query=query, size=(limit or 1000), fields="")
for i, a in enumerate(docs):
if lim... | python | {
"resource": ""
} |
q54121 | get_cached_document_ids | train | def get_cached_document_ids(ids, doc_type):
"""Get the ids of documents that have been parsed with this doc_type"""
for batch in _split_list(ids):
for id in _get_cached_document_ids(batch, doc_type):
yield id | python | {
"resource": ""
} |
q54122 | _replace_series_name | train | def _replace_series_name(seriesname, replacements):
"""Performs replacement of series name.
Allow specified replacements of series names in cases where default
filenames match the wrong series, e.g. missing year gives wrong answer,
or vice versa. This helps the TVDB query get the right match.
"""
... | python | {
"resource": ""
} |
q54123 | clean_series_name | train | def clean_series_name(seriesname):
"""Cleans up series name.
By removing any . and _ characters, along with any trailing hyphens.
Is basically equivalent to replacing all _ and . with a
space, but handles decimal numbers in string, for example:
>>> _clean_series_name("an.example.1.0.test")
'a... | python | {
"resource": ""
} |
q54124 | apply_replacements | train | def apply_replacements(cfile, replacements):
"""Applies custom replacements.
mapping(dict), where each dict contains:
'match' - filename match pattern to check against, the filename
replacement is applied.
'replacement' - string used to replace the matched part of the filename
... | python | {
"resource": ""
} |
q54125 | _format_episode_name | train | def _format_episode_name(names):
"""Takes a list of episode names, formats them into a string.
If two names are supplied, such as "Pilot (1)" and "Pilot (2)", the
returned string will be "Pilot (1-2)". Note that the first number
is not required, for example passing "Pilot" and "Pilot (2)" will
also... | python | {
"resource": ""
} |
q54126 | _make_valid_filename | train | def _make_valid_filename(value):
"""Takes a string and makes it into a valid filename.
replaces accented characters with ASCII equivalent, and
removes characters that cannot be converted sensibly to ASCII.
additional characters that will removed. This
will not touch the extension separator:
... | python | {
"resource": ""
} |
q54127 | format_filename | train | def format_filename(series_name, season_number,
episode_numbers, episode_names,
extension):
"""Generates a filename based on metadata using configured format.
:param str series_name: name of TV series
:param int season_number: the numeric season of series
:param ... | python | {
"resource": ""
} |
q54128 | format_dirname | train | def format_dirname(series_name, season_number):
"""Generates a directory name based on metadata using configured format.
:param str series_name: name of TV series
:param int season_number: the numeric season of series
:returns: formatted directory name using input values and configured format
:rtyp... | python | {
"resource": ""
} |
q54129 | find_library | train | def find_library(series_path):
"""Search for the location of a series within the library.
:param str series_path: name of the relative path of the series
:returns: library path
:rtype: str
"""
for location in cfg.CONF.libraries:
if os.path.isdir(os.path.join(location, series_path)):
... | python | {
"resource": ""
} |
q54130 | Dice.roll | train | def roll(cls, num, sides, add):
"""Rolls a die of sides sides, num times, sums them, and adds add"""
rolls = []
for i in range(num):
rolls.append(random.randint(1, sides))
rolls.append(add)
return rolls | python | {
"resource": ""
} |
q54131 | Pangler.subscribe | train | def subscribe(self, _func=None, needs=(), returns=(), modifies=(),
**conditions):
"""Add a hook to a pangler.
This method can either be used as a decorator for a function or method,
or standalone on a callable.
* `needs` is an iterable of parameters that this hook operates... | python | {
"resource": ""
} |
q54132 | Pangler.trigger | train | def trigger(self, **event):
"""Trigger an event.
Event parameters are passed as keyword arguments. Passing an `event`
argument isn't required, but generally recommended.
"""
if not event:
raise ValueError("tried to trigger nothing")
for hook in self.hooks:
... | python | {
"resource": ""
} |
q54133 | Pangler.clone | train | def clone(self):
"""Duplicate a Pangler.
Returns a copy of this Pangler, with all the same state. Both will be
bound to the same instance and have the same `id`, but new hooks will
not be shared.
"""
p = type(self)(self.id)
p.hooks = list(self.hooks)
p.... | python | {
"resource": ""
} |
q54134 | Pangler.combine | train | def combine(self, *others):
"""Combine other Panglers into this Pangler.
Returns a copy of this Pangler with all of the hooks from the provided
Panglers added to it as well. The new Pangler will be bound to the same
instance and have the same `id`, but new hooks will not be shared with
... | python | {
"resource": ""
} |
q54135 | Pangler.bind | train | def bind(self, instance):
"""Bind an instance to this Pangler.
Returns a clone of this Pangler, with the only difference being that
the new Pangler is bound to the provided instance. Both will have the
same `id`, but new hooks will not be shared.
"""
p = self.clone()
... | python | {
"resource": ""
} |
q54136 | Pangler.stored_bind | train | def stored_bind(self, instance):
"""Bind an instance to this Pangler, using the bound Pangler store.
This method functions identically to `bind`, except that it might
return a Pangler which was previously bound to the provided instance.
"""
if self.id is None:
retu... | python | {
"resource": ""
} |
q54137 | PanglerAggregate.aggregate | train | def aggregate(self, instance, owner):
"""Given an instance and a class, aggregate together some panglers.
Walks every class in the MRO of the `owner` class, including `owner`,
collecting panglers exposed as `self.attr_name`. The resulting pangler
will be bound to the provided `instance`... | python | {
"resource": ""
} |
q54138 | Auth | train | def Auth(email=None, password=None):
"""Get a reusable google data client."""
gd_client = SpreadsheetsService()
gd_client.source = "texastribune-ttspreadimporter-1"
if email is None:
email = os.environ.get('GOOGLE_ACCOUNT_EMAIL')
if password is None:
password = os.environ.get('GOOGLE... | python | {
"resource": ""
} |
q54139 | rst2pub | train | def rst2pub(source, source_path=None, source_class=None,
destination_path=None,
reader=None, reader_name='standalone',
parser=None, parser_name='restructuredtext',
writer=None, writer_name='pseudoxml',
settings=None, settings_spec=None,
settings_ov... | python | {
"resource": ""
} |
q54140 | docinfo2dict | train | def docinfo2dict(doctree):
"""
Return the docinfo field list from a doctree as a dictionary
Note: there can be multiple instances of a single field in the docinfo.
Since a dictionary is returned, the last instance's value will win.
Example:
pub = rst2pub(rst_string)
print docinfo2... | python | {
"resource": ""
} |
q54141 | rst2html | train | def rst2html(rst_src, **kwargs):
"""
Convert a reStructuredText string into a unicode HTML fragment.
For `kwargs`, see `default_rst_opts` and
http://docutils.sourceforge.net/docs/user/config.html
"""
pub = rst2pub(rst_src, settings_overrides=kwargs, writer_name='html')
return pu... | python | {
"resource": ""
} |
q54142 | print_languages_and_exit | train | def print_languages_and_exit(lst, status=1, header=True):
"""print a list of languages and exit"""
if header:
print("Available languages:")
for lg in lst:
print("- %s" % lg)
sys.exit(status) | python | {
"resource": ""
} |
q54143 | extract_opts | train | def extract_opts(**opts):
"""
Small utility to extract a set of one-char options from sys.argv.
"""
values = {}
for opt, init in opts.items():
try:
idx = sys.argv.index('-%s' % opt)
except ValueError:
continue
if idx+1 < len(sys.argv):
opts... | python | {
"resource": ""
} |
q54144 | Parser.parse | train | def parse(self, text):
'''Parses input string and returns list of DDLObjects'''
in_comment = False
result = []
for s in iter(text.splitlines()):
self.log.debug('Parsing string: {}'.format(s))
rsc = self.RE_START_COMMENT.match(s)
if rsc:
... | python | {
"resource": ""
} |
q54145 | Generator.render | train | def render(self):
"""Render the blueprint into a temp directory using the context."""
context = self.context
if 'app' not in context:
context['app'] = self.application.name
temp_dir = self.temp_dir
templates_root = self.blueprint.templates_directory
for root, ... | python | {
"resource": ""
} |
q54146 | Generator.merge | train | def merge(self):
"""Merges the rendered blueprint into the application."""
temp_dir = self.temp_dir
app_dir = self.application.directory
for root, dirs, files in os.walk(temp_dir):
for directory in dirs:
directory = os.path.join(root, directory)
... | python | {
"resource": ""
} |
q54147 | median | train | def median(array):
"""
Return the median value of a list of numbers.
"""
n = len(array)
if n < 1:
return 0
elif n == 1:
return array[0]
sorted_vals = sorted(array)
midpoint = int(n / 2)
if n % 2 == 1:
return sorted_vals[midpoint]
else:
return (so... | python | {
"resource": ""
} |
q54148 | variance | train | def variance(array):
"""
Return the variance of a list of divisible numbers.
"""
if len(array) < 2:
return 0
u = mean(array)
return sum([(x - u) ** 2 for x in array]) / (len(array) - 1) | python | {
"resource": ""
} |
q54149 | filter_iqr | train | def filter_iqr(array, lower, upper):
"""
Return elements which falls within specified interquartile range.
Arguments:
array (list): Sequence of numbers.
lower (float): Lower bound for IQR, in range 0 <= lower <= 1.
upper (float): Upper bound for IQR, in range 0 <= upper <= 1.
... | python | {
"resource": ""
} |
q54150 | confinterval | train | def confinterval(array, conf=0.95, normal_threshold=30, error_only=False,
array_mean=None):
"""
Return the confidence interval of a list for a given confidence.
Arguments:
array (list): Sequence of numbers.
conf (float): Confidence interval, in range 0 <= ci <= 1
n... | python | {
"resource": ""
} |
q54151 | SpcWebGateway.start | train | def start(self):
"""Connect websocket to SPC Web Gateway."""
self._websocket = AIOWSClient(loop=self._loop,
session=self._session,
url=self._ws_url,
async_callback=self._async_ws_handler)
... | python | {
"resource": ""
} |
q54152 | SpcWebGateway.async_load_parameters | train | async def async_load_parameters(self):
"""Fetch area and zone info from SPC to initialize."""
zones = await self._async_get_data('zone')
areas = await self._async_get_data('area')
if not zones or not areas:
return False
for spc_area in areas:
area = Area... | python | {
"resource": ""
} |
q54153 | SpcWebGateway._async_ws_handler | train | async def _async_ws_handler(self, data):
"""Process incoming websocket message."""
sia_message = data['data']['sia']
spc_id = sia_message['sia_address']
sia_code = sia_message['sia_code']
_LOGGER.debug("SIA code is %s for ID %s", sia_code, spc_id)
if sia_code in Area.SU... | python | {
"resource": ""
} |
q54154 | SpcWebGateway._async_get_data | train | async def _async_get_data(self, resource, id=None):
"""Get the data from the resource."""
if id:
url = urljoin(self._api_url, "spc/{}/{}".format(resource, id))
else:
url = urljoin(self._api_url, "spc/{}".format(resource))
data = await async_request(self._session.g... | python | {
"resource": ""
} |
q54155 | Plot.set_bounds | train | def set_bounds(self, ymin, ymax, xmin, xmax, zmin, zmax, edist=None):
"""Set Y,X,Z bounds for the plot."""
self.ymin, self.ymax = ymin, ymax
self.xmin, self.xmax = xmin, xmax
self.zmin, self.zmax = zmin, zmax
self.edist = None | python | {
"resource": ""
} |
q54156 | scan | train | def scan(phenotype, X, G=None, K=None, covariates=None, progress=True,
options=None):
"""Association between genetic variants and phenotype.
Matrix `X` shall contain the genetic markers (e.g., number of minor
alleles) with rows and columns representing samples and genetic markers,
respectively... | python | {
"resource": ""
} |
q54157 | Settings.get | train | def get(cls, option, default_value=None):
"""
Return value of given option.
If option isn't found - return default_value (None by default).
Args:
- option: string with path to option with `:` separator
"""
config = cls.__get_instance()
for name in option... | python | {
"resource": ""
} |
q54158 | merge_dicts | train | def merge_dicts(*dict_list):
"""Extract all of the dictionaries from this list, then merge them together """
# if not isinstance(dict_list, list):
# raise TypeError("dict_list is not a list. Please try again")
# print(dict_list)
all_dicts = []
for ag in dict_list:
if isinstance(ag, d... | python | {
"resource": ""
} |
q54159 | filter_query | train | def filter_query(filter_dict, required_keys):
"""Ensure that the dict has all of the information available. If not, return what does"""
if not isinstance(filter_dict, dict):
raise TypeError("dict_list is not a list. Please try again")
if not isinstance(required_keys, list):
raise TypeError(... | python | {
"resource": ""
} |
q54160 | price_query_filter | train | def price_query_filter(price_query_dict):
"""
Ensure that certain keys are available.
- exchange
- period
"""
if not isinstance(price_query_dict, dict):
raise TypeError("dict_list is not a list. Please try again")
required = ["period", "exchange"]
pkeys = pric... | python | {
"resource": ""
} |
q54161 | import_path | train | def import_path(path):
"""
Imports any valid python module or attribute path as though it were a
module
:Example:
>>> from yamlconf import import_path
>>> from my_package.my_module.my_submodule import attribute
>>> attribute.sub_attribute == \
... import_path("y_pack... | python | {
"resource": ""
} |
q54162 | get_compiler | train | def get_compiler(compiler, **compiler_attrs):
"""get and customize a compiler"""
if compiler is None or isinstance(compiler, str):
cc = ccompiler.new_compiler(compiler=compiler, verbose=0)
customize_compiler(cc)
if cc.compiler_type == 'mingw32':
customize_mingw(cc)
else:
... | python | {
"resource": ""
} |
q54163 | FoodsPlugin.describe_ingredient | train | def describe_ingredient(self):
""" apple. tart apple with vinegar. """
resp = random.choice(ingredients)
if random.random() < .2:
resp = random.choice(foodqualities) + " " + resp
if random.random() < .2:
resp += " with " + self.describe_additive()
return r... | python | {
"resource": ""
} |
q54164 | FoodsPlugin.describe_additive | train | def describe_additive(self):
""" vinegar. spicy vinegar. a spicy vinegar. """
resp = random.choice(additives)
if random.random() < .2:
resp = random.choice(foodqualities) + ' ' + resp
if random.random() < .01:
resp = self.articleize(resp)
return resp | python | {
"resource": ""
} |
q54165 | FoodsPlugin.describe_dish | train | def describe_dish(self):
"""a burrito. a lettuce burrito with ketchup and raspberry."""
resp = random.choice(foodpreparations)
if random.random() < .85:
resp = self.describe_ingredient() + ' ' + resp
if random.random() < .2:
resp = self.describe_ingredient... | python | {
"resource": ""
} |
q54166 | main | train | def main(filepath, in_debug_mode):
"""Gibica Interpreter."""
with open(filepath) as file:
try:
# Lexical analysis
lexer = Lexer(file.read())
# Syntax analysis
parser = Parser(lexer)
tree = parser.parse()
# Sementic analysis
... | python | {
"resource": ""
} |
q54167 | rm | train | def rm(name):
"""
Remove an existing project and its container.
"""
path = get_existing_project_path(name)
click.confirm(
'Are you sure you want to delete project %s?' % name, abort=True)
container_name = get_container_name(name)
client = docker.Client()
try:
client.ins... | python | {
"resource": ""
} |
q54168 | stop | train | def stop(name):
"""
Stop project's container.
"""
container_name = get_container_name(name)
client = docker.Client()
try:
client.stop(container_name)
except docker.errors.NotFound:
pass
except docker.errors.APIError as error:
die(error.explanation.decode()) | python | {
"resource": ""
} |
q54169 | Timer.elapsed_time_s | train | def elapsed_time_s(self):
"""
Return the amount of time that has elapsed since the timer was started.
Only works if the timer is active.
"""
if self._start_time:
return (datetime.datetime.now() - self._start_time).total_seconds()
else:
return 0 | python | {
"resource": ""
} |
q54170 | get | train | def get(name, *args, **kwargs):
"""Find command class for given command name and return it's instance
:param name: str
:param args: additional arguments for Command
:param kwargs: additional arguments for Command
:return: Command
"""
cmd = COMMAND_MAPPER.get(name)
return cmd(*args, **kw... | python | {
"resource": ""
} |
q54171 | NGram.remove | train | def remove(self, item):
"""Remove an item from the set. Inverts the add operation.
>>> from ngram import NGram
>>> n = NGram(['spam', 'eggs'])
>>> n.remove('spam')
>>> list(n)
['eggs']
"""
if item in self:
super(NGram, self).remove(item)
... | python | {
"resource": ""
} |
q54172 | stringToDate | train | def stringToDate(fmt="%Y-%m-%d"):
"""returns a function to convert a string to a datetime.date instance
using the formatting string fmt as in time.strftime"""
import time
import datetime
def conv_func(s):
return datetime.date(*time.strptime(s,fmt)[:3])
return conv_func | python | {
"resource": ""
} |
q54173 | PyDbLite_to_csv | train | def PyDbLite_to_csv(src,dest=None,dialect='excel'):
"""Convert a PyDbLite base to a CSV file
src is the PyDbLite.Base instance
dest is the file-like object for the CSV output
dialect is the same as in csv module"""
import csv
fieldnames = ["__id__","__version__"]+src.fields
if dest is... | python | {
"resource": ""
} |
q54174 | ConfigurationValidator.validate_user_threaded_json | train | def validate_user_threaded_json(pjson):
"""Takes a parsed JSON dict representing a set of tests in the user-threaded
format and validates it."""
tests = pjson["tests"]
# Verify that 'tests' is a two dimensional list
is_2d_list = lambda ls: len(ls) == len(filter(lambda l: type(l... | python | {
"resource": ""
} |
q54175 | ConfigurationValidator.validate_auto_threaded_json | train | def validate_auto_threaded_json(pjson):
"""Takes a parsed JSON dict representing a set of tests in the auto-threaded
format and validates it, descending recursively if necessary."""
# pjson should be a dict or unicode
if not type(pjson) is dict:
raise ParseError("Expected a J... | python | {
"resource": ""
} |
q54176 | Models.addElement | train | def addElement(self, *ele):
""" add element to lattice element list
:param ele: magnetic element defined in element module
return total element number
"""
for el in list(Models.flatten(ele)):
e = copy.deepcopy(el)
self._lattice_eleobjlist.append(e... | python | {
"resource": ""
} |
q54177 | Models.getCtrlConf | train | def getCtrlConf(self, msgout=True):
""" get control configurations regarding to the PV names,
read PV value
:param msgout: print information if True (by default)
return updated element object list
"""
_lattice_eleobjlist_copy = copy.deepcopy(self._lattice_ele... | python | {
"resource": ""
} |
q54178 | Models.putCtrlConf | train | def putCtrlConf(self, eleobj, ctrlkey, val, type='raw'):
""" put the value to control PV field
:param eleobj: element object in lattice
:param ctrlkey: element control property, PV name
:param val: new value for ctrlkey
:param type: set in 'raw' or 'real' mode, '... | python | {
"resource": ""
} |
q54179 | Models.getAllConfig | train | def getAllConfig(self, fmt='json'):
"""
return all element configurations as json string file.
could be further processed by beamline.Lattice class
:param fmt: 'json' (default) or 'dict'
"""
for e in self.getCtrlConf(msgout=False):
self._lattice_c... | python | {
"resource": ""
} |
q54180 | Models.updateConfig | train | def updateConfig(self, eleobj, config, type='simu'):
""" write new configuration to element
:param eleobj: define element object
:param config: new configuration for element, string or dict
:param type: 'simu' by default, could be online, misc, comm, ctrl
"""
... | python | {
"resource": ""
} |
q54181 | Models.getElementsByName | train | def getElementsByName(self, name):
""" get element with given name,
return list of element objects regarding to 'name'
:param name: element name, case sensitive, if elements are
auto-generated from LteParser, the name should be lower cased.
"""
try:
... | python | {
"resource": ""
} |
q54182 | Models.printAllElements | train | def printAllElements(self):
""" print out all modeled elements
"""
cnt = 1
print("{id:<3s}: {name:<12s} {type:<10s} {classname:<10s}"
.format(id='ID', name='Name', type='Type', classname='Class Name'))
for e in self._lattice_eleobjlist:
print("{cnt:>03d}... | python | {
"resource": ""
} |
q54183 | fetch_gbwithparts | train | def fetch_gbwithparts(list_of_NC_accessions, email, folder):
'''Download genbank files from NCBI using Biopython Entrez efetch.
Args:
list_of_NC_accessions (list): a list of strings, e.g ['NC_015758', 'NC_002695']
email (string): NCBI wants your email
folder (string): Where the gb fil... | python | {
"resource": ""
} |
q54184 | OrganismDB.make_organisms | train | def make_organisms(self, genome_list, genome_dir):
'''Organism factory method.
Appends organisms to the organisms list.
Args
genome_list (list)
genome_dir (string)
'''
for genome in genome_list:
genome_path = genome_dir + genome
... | python | {
"resource": ""
} |
q54185 | OrganismDB.add_protein_to_organisms | train | def add_protein_to_organisms(self, orgprot_list):
'''
Protein factory method.
Iterates through a list of SearchIO hit objects, matches
the accession against SeqRecord features for each organism.
If there is a match, the new Protein object is created and
stored in the pr... | python | {
"resource": ""
} |
q54186 | OrganismDB.add_hits_to_proteins | train | def add_hits_to_proteins(self, hmm_hit_list):
'''Add HMMER results to Protein objects'''
for org in self.organisms:
print "adding SearchIO hit objects for", org.accession
for hit in hmm_hit_list:
hit_org_id = hit.id.split(',')[0]
hit_prot_id = h... | python | {
"resource": ""
} |
q54187 | OrganismDB.cluster_number | train | def cluster_number(self, data, maxgap):
'''General function that clusters numbers.
Args
data (list): list of integers.
maxgap (int): max gap between numbers in the cluster.
'''
data.sort()
groups = [[data[0]]]
for x in data[1:]:
if ... | python | {
"resource": ""
} |
q54188 | OrganismDB.find_loci | train | def find_loci(self, cluster_size, maxgap, locusview=False, colordict=None):
'''
Finds the loci of a given cluster size & maximum gap between cluster members.
Args
cluster_size (int): minimum number of genes in the cluster.
maxgap (int): max basepair gap between ... | python | {
"resource": ""
} |
q54189 | Protein.parse_hmm_hit_list | train | def parse_hmm_hit_list(self, hmm_hit_list):
'''
take a list of hmm hit results, take needed info,
'''
tuplist = []
for hit in hmm_hit_list:
for hsp in hit.hsps:
tup = tuplist.append((hit._query_id.split('_')[0],
... | python | {
"resource": ""
} |
q54190 | rRNA16SDB.write_16S_rRNA_fasta | train | def write_16S_rRNA_fasta(self, org_list):
'''
Writes a fasta file containing 16S rRNA sequences
for a list of Organism objects,
The first 16S sequence found in the seq record object is used,
since it looks like there are duplicates
'''
fasta = []
for or... | python | {
"resource": ""
} |
q54191 | rRNA16SDB.import_tree_order_from_file | train | def import_tree_order_from_file(self, MyOrganismDB, filename):
'''
Import the accession list that has been ordered by position
in a phylogenetic tree. Get the index in the list, and
add this to the Organism object. Later we can use this position
to make a heatmap that matches up... | python | {
"resource": ""
} |
q54192 | HmmSearch.run_hmmbuild | train | def run_hmmbuild(self):
'''
Generate hmm with hhbuild,
output to file. Also stores query names.
'''
for alignment in self.alignment_list:
print 'building Hmm for', alignment
alignment_full_path = self.alignment_dir + alignment
query_name = ... | python | {
"resource": ""
} |
q54193 | HmmSearch.extract_hit_list_from_hmmsearch_results | train | def extract_hit_list_from_hmmsearch_results(self):
'''
Make a giant list of all the hit objects from
our search
'''
combined_list_of_hits = []
for result in self.hmm_result_list:
fullpath = self.hhsearch_result_folder + result
se =... | python | {
"resource": ""
} |
q54194 | HmmSearch.make_protein_arrow_color_dict | train | def make_protein_arrow_color_dict(self, query_names):
'''
Generates a random color for all proteins in query_names,
stores these in a dict.
'''
protein_arrow_color_dict = dict()
for protein in self.query_names:
protein_arrow_color_dict[protein] = (random(),... | python | {
"resource": ""
} |
q54195 | HmmSearch.parse_proteins | train | def parse_proteins(self,OrganismDB):
'''
Iterate through all the proteins in the DB,
creates a hit_dataframe for each protein.
'''
for org in OrganismDB.organisms:
for prot in org.proteins:
if len(prot.hmm_hit_list) > 0:
try:
... | python | {
"resource": ""
} |
q54196 | HmmSearch.set_best_hit_values_for_proteins | train | def set_best_hit_values_for_proteins(self, OrganismDB):
'''
Iterate through all proteins in the DB,
drop duplicates in the hit_dataframe, then store the maximum
hit information as protein attributes.
'''
for org in OrganismDB.organisms:
print 'setting best h... | python | {
"resource": ""
} |
q54197 | RelatedProteinGroup.make_related_protein_fasta_from_dataframe | train | def make_related_protein_fasta_from_dataframe(self, input_df):
'''
DataFrame should have
'''
dirname = './group_fastas'
if not os.path.exists(dirname):
os.makedirs(dirname)
unique_hit_queries = set(input_df.hit_query)
for hq in unique_hit_queries... | python | {
"resource": ""
} |
q54198 | our_IsUsableForDesktopGUI | train | def our_IsUsableForDesktopGUI(m):
""" A more leniant version of CGDisplayModeIsUsableForDesktopGUI """
if guess_bitDepth(Q.CGDisplayModeCopyPixelEncoding(m)) != 24:
return False
if Q.CGDisplayModeGetWidth(m) < 640:
return False
if Q.CGDisplayModeGetHeight(... | python | {
"resource": ""
} |
q54199 | cmp_mode | train | def cmp_mode(b, a):
""" A comparison function for displaymodes """
tmp = cmp(Q.CGDisplayModeIsUsableForDesktopGUI(a),
Q.CGDisplayModeIsUsableForDesktopGUI(b))
if tmp != 0: return tmp
tmp = cmp(our_IsUsableForDesktopGUI(a),
our_IsUsableForDesktopGUI(b))... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.