repo
stringlengths
1
29
path
stringlengths
24
332
code
stringlengths
39
579k
DRecPy
DRecPy//Evaluation/Metrics/ranking.pyfile:/Evaluation/Metrics/ranking.py:function:reciprocal_rank/reciprocal_rank
def reciprocal_rank(recommendations, relevant_recommendation, k=None): """Reciprocal Rank at k Example calls: >>> reciprocal_rank([1,2,3], 1) == 1.0 >>> reciprocal_rank([1,2,3], 2) == 0.5 >>> reciprocal_rank([1,2,3], 3) == 0.3333333333333333 >>> reciprocal_rank([1,2,3], 4) == 0 >>> reciprocal_rank([1,2,3], 3, k=2) == 0 >>> reciprocal_rank([1,2,3], 2, k=2) == 0.5 :param recommendations: :param relevant_recommendation: :param k: :return: """ if k is not None: recommendations = recommendations[:k] if relevant_recommendation in recommendations: return 1 / (recommendations.index(relevant_recommendation) + 1) return 0
fmriprep
fmriprep//cli/sample_openfmri.pyfile:/cli/sample_openfmri.py:function:get_parser/get_parser
def get_parser(): """Build parser object""" from argparse import ArgumentParser from argparse import RawTextHelpFormatter parser = ArgumentParser(description= "OpenfMRI participants sampler, for FMRIPREP's testing purposes", formatter_class=RawTextHelpFormatter) parser.add_argument('openfmri_dir', action='store', help= 'the root folder of a the openfmri dataset') parser.add_argument('-D', '--datalad_fetch', action='store_true', default=False, help='download sampled subjects') parser.add_argument('-o', '--output-file', action='store', help= 'write output file') parser.add_argument('-n', '--num-participants', action='store', type= int, default=4, help= 'number of participants randomly selected per dataset') parser.add_argument('--njobs', action='store', type=int, help= 'parallel downloads') parser.add_argument('--seed', action='store', type=int, default= 20170914, help='seed for random number generation') return parser
pyutil-3.3.0
pyutil-3.3.0//versioneer.pyfile:/versioneer.py:function:render_pep440_pre/render_pep440_pre
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces['closest-tag']: rendered = pieces['closest-tag'] if pieces['distance']: rendered += '.post.dev%d' % pieces['distance'] else: rendered = '0.post.dev%d' % pieces['distance'] return rendered
flywheel
flywheel//models/avatars.pyclass:Avatars/positional_to_model
@staticmethod def positional_to_model(value): """Converts a positional argument to a model value""" return value
jikken-0.2.1
jikken-0.2.1//src/jikken/setups.pyfile:/src/jikken/setups.py:function:prepare_arg/prepare_arg
def prepare_arg(argument): """Prepend dashes to conform with cli standards on arguments if necessary""" keyword, arg = argument.split('=') if len(keyword) == 1: keyword = '-' + keyword elif len(keyword) == 2 and keyword[0] == '-': pass elif keyword[:2] != '--': keyword = '--' + keyword return [keyword, arg]
numpy_demo
numpy_demo//lib/_iotools.pyfile:/lib/_iotools.py:function:_decode_line/_decode_line
def _decode_line(line, encoding=None): """Decode bytes from binary input streams. Defaults to decoding from 'latin1'. That differs from the behavior of np.compat.asunicode that decodes from 'ascii'. Parameters ---------- line : str or bytes Line to be decoded. Returns ------- decoded_line : unicode Unicode in Python 2, a str (unicode) in Python 3. """ if type(line) is bytes: if encoding is None: line = line.decode('latin1') else: line = line.decode(encoding) return line
autoshell
autoshell//common/hosts.pyfile:/common/hosts.py:function:_process_string_exps/_process_string_exps
def _process_string_exps(str_list): """ common.hosts._process_string_exps accepts pre-parsed string data from the common.expressions library and pulls address, tcp port, and type information from the list of lists based on position. """ if len(str_list) == 1: htype = None else: htype = str_list[1][0] if len(str_list[0]) == 1: return {'address': str_list[0][0], 'port': None, 'type': htype} elif len(str_list[0]) > 1: return {'address': str_list[0][0], 'port': str_list[0][1], 'type': htype}
pyanp
pyanp//rowsens.pyfile:/rowsens.py:function:p0mode_is_smart/p0mode_is_smart
def p0mode_is_smart(p0mode_value) ->bool: """ Is the p0mode value a "smart value". See calcp0 for more info on p0mode values. :param p0mode_value: If it is an int, this p0mode value represents doing smart p0 making the node of that index (i.e.p0mode's value) smooth :return: True | False """ return isinstance(p0mode_value, int)
maestral-1.0.0
maestral-1.0.0//maestral/config/user.pyclass:UserConfig/_get_major_version
@staticmethod def _get_major_version(version): """Return the 'major' component of the version.""" return version[:version.find('.')]
mathutils
mathutils//geometry.pyfile:/geometry.py:function:box_fit_2d/box_fit_2d
def box_fit_2d(points: list) ->float: """Returns an angle that best fits the points to an axis aligned rectangle :param points: list of 2d points. :type points: list :return: angle """ pass
weboob
weboob//capabilities/base.pyfile:/capabilities/base.py:function:find_object/find_object
def find_object(mylist, error=None, **kwargs): """ Very simple tools to return an object with the matching parameters in kwargs. """ for a in mylist: for key, value in kwargs.items(): if getattr(a, key) != value: break else: return a if error is not None: raise error() return None
python-msp430-tools-0.9.2
python-msp430-tools-0.9.2//msp430/legacy/jtag.pyfile:/msp430/legacy/jtag.py:function:parseAddressRange/parseAddressRange
def parseAddressRange(text): """parse a single address or an address range and return a tuple.""" if '-' in text: adr1, adr2 = text.split('-', 1) try: adr1 = int(adr1, 0) except ValueError: raise ValueError( 'Address range start address must be a valid number in dec, hex or octal' ) try: adr2 = int(adr2, 0) except ValueError: raise ValueError( 'Address range end address must be a valid number in dec, hex or octal' ) return adr1, adr2 elif '/' in text: adr1, size = text.split('/', 1) try: adr1 = int(adr1, 0) except ValueError: raise ValueError( 'Address range start address must be a valid number in dec, hex or octal' ) multiplier = 1 if size.endswith('k'): size = size[:-1] multiplier = 1024 try: size = int(size, 0) * multiplier except ValueError: raise ValueError( 'Address range size must be a valid number in dec, hex or octal' ) return adr1, adr1 + size - 1 else: try: adr = int(text, 0) return adr, None except ValueError: raise ValueError( 'Address must be a valid number in dec, hex or octal or a range adr1-adr2' )
dgl
dgl//backend/backend.pyfile:/backend/backend.py:function:softmax/softmax
def softmax(input, dim=-1): """Apply the softmax function on given dimension. Parameters ---------- input : Tensor The input tensor. dim : int The dimension along which to compute softmax. Returns ------- Tensor The output tensor. """ pass
soupsieve-2.0
soupsieve-2.0//soupsieve/css_match.pyclass:_DocumentNav/is_doc
@staticmethod def is_doc(obj): """Is `BeautifulSoup` object.""" import bs4 return isinstance(obj, bs4.BeautifulSoup)
ogs5py-1.1.1
ogs5py-1.1.1//ogs5py/tools/tools.pyfile:/ogs5py/tools/tools.py:function:format_dict/format_dict
def format_dict(dict_in): """ Format the dictionary to use upper-case keys. Parameters ---------- dict_in : dict input dictionary """ dict_out = {} for key in dict_in: new_key = str(key).upper() if new_key != key and new_key in dict_in: print('Your given OGS-keywords are not unique: ' + new_key) print(' --> DATA WILL BE LOST') dict_out[new_key] = dict_in[key] return dict_out
fake-bpy-module-2.78-20200428
fake-bpy-module-2.78-20200428//bpy/ops/mesh.pyfile:/bpy/ops/mesh.py:function:vertex_color_remove/vertex_color_remove
def vertex_color_remove(): """Remove vertex color layer """ pass
authl
authl//utils.pyfile:/utils.py:function:read_file/read_file
def read_file(filename): """ Given a filename, read the entire thing into a string """ with open(filename, encoding='utf-8') as file: return file.read()
introcs
introcs//geom/matrix.pyclass:Matrix/CreateScale
@classmethod def CreateScale(cls, x=1, y=1, z=1): """ Scales this matrix (in-place) by the given amount :param x: x-coordinate of the scale (default 1) :type x: ``int`` or ``float`` :param y: y-coordinate of the scale (default 1) :type Y: ``int`` or ``float`` :param z: z-coordinate of the scale (default 1) :type Z: ``int`` or ``float`` """ result = cls() result.scale(x, y, z) return result
ec2mc
ec2mc//utils/find/find_instances.pyfile:/utils/find/find_instances.py:function:argparse_args/argparse_args
def argparse_args(cmd_parser): """initialize argparse arguments that the main() function expects""" cmd_parser.add_argument('-n', dest='name_filter', nargs='+', metavar='', help='Instance tag value filter for the tag key "Name".') cmd_parser.add_argument('-r', dest='region_filter', nargs='+', metavar= '', help= 'AWS region(s) to probe for instances. If not set, all whitelisted regions will be probed.' ) cmd_parser.add_argument('-t', dest='tag_filters', nargs='+', action= 'append', metavar='', help= 'Instance tag value filter. First value is the tag key, with proceeding value(s) as the tag value(s). If only 1 value given, the tag key itself will be filtered for instead.' ) cmd_parser.add_argument('-i', dest='id_filter', nargs='+', metavar='', help='Instance ID filter.')
sunpy
sunpy//map/sources/source_type.pyfile:/map/sources/source_type.py:function:from_helioviewer_project/from_helioviewer_project
def from_helioviewer_project(meta): """ Test determining if the MapMeta object contains Helioviewer Project sourced data. Parameters ---------- meta : `~sunpy.map.MapMeta` Returns ------- If the data of the map comes from the Helioviewer Project, then True is returned. If not, False is returned. """ return 'helioviewer' in meta.keys()
fake-blender-api-2.79-0.3.1
fake-blender-api-2.79-0.3.1//bpy/ops/clip.pyfile:/bpy/ops/clip.py:function:slide_marker/slide_marker
def slide_marker(offset: float=(0.0, 0.0)): """Slide marker areas :param offset: Offset, Offset in floating point units, 1.0 is the width and height of the image :type offset: float """ pass
jatayu
jatayu//database.pyclass:CRUDMixin/create
@classmethod def create(cls, **kwargs): """Create a new record and save it the database.""" instance = cls(**kwargs) return instance.save()
metomi
metomi//rosie/vc.pyclass:RosieVCClient/_dummy
@staticmethod def _dummy(*args, **kwargs): """Dummy event handler.""" pass
PyQtChart-5.14.0
PyQtChart-5.14.0//configure.pyfile:/configure.py:function:_format/_format
def _format(msg, left_margin=0, right_margin=78): """ Format a message by inserting line breaks at appropriate places. msg is the text of the message. left_margin is the position of the left margin. right_margin is the position of the right margin. Returns the formatted message. """ curs = left_margin fmsg = ' ' * left_margin for w in msg.split(): l = len(w) if curs != left_margin and curs + l > right_margin: fmsg = fmsg + '\n' + ' ' * left_margin curs = left_margin if curs > left_margin: fmsg = fmsg + ' ' curs = curs + 1 fmsg = fmsg + w curs = curs + l return fmsg
dgl_cu100-0.4.3.post2.data
dgl_cu100-0.4.3.post2.data//purelib/dgl/backend/backend.pyfile:/purelib/dgl/backend/backend.py:function:unsorted_1d_segment_sum/unsorted_1d_segment_sum
def unsorted_1d_segment_sum(input, seg_id, n_segs, dim): """Computes the sum along segments of a tensor. Equivalent to tf.unsorted_segment_sum, but seg_id is required to be a 1D tensor. Parameters ---------- input : Tensor The input tensor seg_id : 1D Tensor The segment IDs whose values are between 0 and n_segs - 1. Should have the same length as input. n_segs : int Number of distinct segments dim : int Dimension to sum on Returns ------- Tensor The result """ pass
veriloggen-1.8.2
veriloggen-1.8.2//veriloggen/thread/ttypes.pyfile:/veriloggen/thread/ttypes.py:function:intrinsic/intrinsic
def intrinsic(fsm, func, *args, **kwargs): """ function call as an intrinsic """ func(fsm, *args, **kwargs)
audiotools
audiotools//toc/yaccrules.pyfile:/toc/yaccrules.py:function:p_track_flag_no_pre_emphasis/p_track_flag_no_pre_emphasis
def p_track_flag_no_pre_emphasis(t): """track_flag : NO PRE_EMPHASIS""" from audiotools.toc import TOCFlag_PRE_EMPHASIS t[0] = TOCFlag_PRE_EMPHASIS(False)
eldonationtracker
eldonationtracker//extralife_IO.pyfile:/extralife_IO.py:function:write_text_files/write_text_files
def write_text_files(dictionary: dict, text_folder: str): """Write info to text files. The dictionary key will become the filename and the values will be the content of the files. :param dictionary: The dictionary with items to output. :param text_folder: The directory to write the text files. """ for filename, text in dictionary.items(): f = open(f'{text_folder}/{filename}.txt', 'w', encoding='utf8') f.write(text) f.close
sfftk
sfftk//formats/surf.pyclass:AmiraHyperSurfaceMesh/translate_indexes
@staticmethod def translate_indexes(triangle_list, lut): """Translate the values of the list of 3-tuples according to the provided look-up table Is a generator. :param list triangle_list: a list of 3-tuples of integers :param dict lut: a dictionary mapping current to new values """ for t0, t1, t2 in triangle_list: yield lut[t0], lut[t1], lut[t2]
pluggdapps-0.43dev
pluggdapps-0.43dev//pluggdapps/erl/codec.pyfile:/pluggdapps/erl/codec.py:function:decode_float/decode_float
def decode_float(b): """ *----*--------------* | 1 | 31 | *----*--------------* | 99 | Float String | *----*--------------* """ return float(b[:31].split(b'\x00', 1)[0]), b[31:]
fbchat-asyncio-0.3.0
fbchat-asyncio-0.3.0//fbchat/_util.pyfile:/fbchat/_util.py:function:timedelta_to_seconds/timedelta_to_seconds
def timedelta_to_seconds(td): """Convert a timedelta to seconds. The returned seconds will be rounded to the nearest whole number. """ return round(td.total_seconds())
DateTime
DateTime//interfaces.pyclass:IDateTime/lessThan
def lessThan(t): """Compare this DateTime object to another DateTime object OR a floating point number such as that which is returned by the python time module. Returns true if the object represents a date/time less than the specified DateTime or time module style time. Revised to give more correct results through comparison of long integer milliseconds."""
pyDR-0.1.3
pyDR-0.1.3//pyDR/utils.pyfile:/pyDR/utils.py:function:_PGE_tariff_data_2015/_PGE_tariff_data_2015
def _PGE_tariff_data_2015(): """ Prepares data for PGE tariffs. nrg : Energy charges dem : Demand charges meter : meter charges? """ nrg = {'Zero': {'Summer': {'Peak': 0.0, 'PartialPeak': 0.0, 'OffPeak': 0.0}, 'Winter': {'PartialPeak': 0.0, 'OffPeak': 0.0}}, 'A1': { 'Summer': {'Peak': 0.23977, 'PartialPeak': 0.23977, 'OffPeak': 0.23977}, 'Winter': {'PartialPeak': 0.16246, 'OffPeak': 0.16246}}, 'A1TOU': {'Summer': {'Peak': 0.26042, 'PartialPeak': 0.25109, 'OffPeak': 0.22269}, 'Winter': {'PartialPeak': 0.1728, 'OffPeak': 0.15298}}, 'A6TOU': {'Summer': {'Peak': 0.60974, 'PartialPeak': 0.28352, 'OffPeak': 0.15605}, 'Winter': {'PartialPeak': 0.17883, 'OffPeak': 0.14605}}, 'A10_secondary': {'Summer': {'Peak': 0.16116, 'PartialPeak': 0.16116, 'OffPeak': 0.16116}, 'Winter': { 'PartialPeak': 0.11674, 'OffPeak': 0.11674}}, 'A10_primary': { 'Summer': {'Peak': 0.14936, 'PartialPeak': 0.14936, 'OffPeak': 0.14936}, 'Winter': {'PartialPeak': 0.11069, 'OffPeak': 0.11069}}, 'A10_transmission': {'Summer': {'Peak': 0.12137, 'PartialPeak': 0.12137, 'OffPeak': 0.12137}, 'Winter': {'PartialPeak': 0.09583, 'OffPeak': 0.09583}}, 'A10TOU_secondary': {'Summer': {'Peak': 0.17891, 'PartialPeak': 0.17087, 'OffPeak': 0.14642}, 'Winter': { 'PartialPeak': 0.1275, 'OffPeak': 0.10654}}, 'A10TOU_primary': { 'Summer': {'Peak': 0.1642, 'PartialPeak': 0.15846, 'OffPeak': 0.1365}, 'Winter': {'PartialPeak': 0.11949, 'OffPeak': 0.10231}}, 'A10TOU_transmission': {'Summer': {'Peak': 0.13481, 'PartialPeak': 0.12958, 'OffPeak': 0.10973}, 'Winter': {'PartialPeak': 0.10392, 'OffPeak': 0.08816}}, 'E19TOU_secondary': {'Summer': {'Peak': 0.16233, 'PartialPeak': 0.10893, 'OffPeak': 0.07397}, 'Winter': { 'PartialPeak': 0.10185, 'OffPeak': 0.07797}}, 'E19TOU_primary': { 'Summer': {'Peak': 0.14861, 'PartialPeak': 0.10219, 'OffPeak': 0.07456}, 'Winter': {'PartialPeak': 0.09696, 'OffPeak': 0.07787}}, 'E19TOU_transmission': {'Summer': {'Peak': 0.09129, 'PartialPeak': 0.08665, 'OffPeak': 0.07043}, 'Winter': {'PartialPeak': 0.085, 'OffPeak': 0.07214}}} dem = {'A10_primary': {'Summer': 15.54, 'Winter': 7.31}, 'A10_secondary': {'Summer': 14.53, 'Winter': 7.51}, 'A10_transmission': {'Summer': 10.16, 'Winter': 5.6}, 'A10TOU_primary': {'Summer': 15.54, 'Winter': 7.31}, 'A10TOU_secondary': {'Summer': 14.53, 'Winter': 7.51}, 'A10TOU_transmission': {'Summer': 10.16, 'Winter': 5.6}, 'E19TOU_secondary': {'Summer': {'mpeak': 19.04, 'ppeak': 4.42, 'max': 14.38}, 'Winter': {'ppeak': 0.24, 'max': 14.38}}, 'E19TOU_primary': {'Summer': {'mpeak': 18.91, 'ppeak': 4.06, 'max': 11.39}, 'Winter': {'ppeak': 0.46, 'max': 11.39}}, 'E19TOU_transmission': {'Summer': {'mpeak': 17.03, 'ppeak': 3.78, 'max': 7.18}, 'Winter': {'ppeak': 0.0, 'max': 7.18}}} meter = {'A1': 0.65708, 'A1TOU': 0.65708, 'A6TOU': 0.65708 + 0.20107, 'A10_secondary': 4.59959, 'A10_primary': 4.59959, 'A10_transmission': 4.59959, 'A10TOU_secondary': 4.59959, 'A10TOU_primary': 4.59959, 'A10TOU_transmission': 4.59959, 'E19TOU_secondary': {'Mandatory': {'S': 19.71253, 'P': 32.85421, 'T': 59.13758}, 'Voluntary': {'SmartMeter': 4.59959, 'NoSmartMeter': 4.777}}, 'E19TOU_primary': {'Mandatory': {'S': 19.71253, 'P': 32.85421, 'T': 59.13758}, 'Voluntary': {'SmartMeter': 4.59959, 'NoSmartMeter': 4.777}}, 'E19TOU_transmission': {'Mandatory': {'S': 19.71253, 'P': 32.85421, 'T': 59.13758}, 'Voluntary': {'SmartMeter': 4.59959, 'NoSmartMeter': 4.777}}, 'Zero': 0.0} return nrg, dem, meter
wpiformat-2020.28
wpiformat-2020.28//wpiformat/cpplint.pyfile:/wpiformat/cpplint.py:function:IsCppString/IsCppString
def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace('\\\\', 'XX') return line.count('"') - line.count('\\"') - line.count('\'"\'') & 1 == 1
stoqlib
stoqlib//lib/interfaces.pyclass:IPaymentOperation/can_change_due_date
def can_change_due_date(payment): """If it's possible to change the due date of a payment :param payment: the payment to change due date """
asyncio_redis
asyncio_redis//protocol.pyclass:PostProcessors/get_all
@classmethod def get_all(cls, return_type): """ Return list of (suffix, return_type, post_processor) """ default = cls.get_default(return_type) alternate = cls.get_alternate_post_processor(return_type) result = [('', return_type, default)] if alternate: result.append(alternate) return result
nf
nf//utils.pyfile:/utils.py:function:to_exchange/to_exchange
def to_exchange(exchange): """转换成正确的交易市场. 如果不存在, 则返回None""" exchange_set = {'SHSE', 'SZSE', 'CFFEX', 'SHFE', 'DCE', 'CZCE'} if not exchange: return None s = str(exchange).upper().strip() return s if s in exchange_set else None
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/iam.pyfile:/pyboto3/iam.py:function:detach_role_policy/detach_role_policy
def detach_role_policy(RoleName=None, PolicyArn=None): """ Removes the specified managed policy from the specified role. A role can also have inline policies embedded with it. To delete an inline policy, use the DeleteRolePolicy API. For information about policies, see Managed Policies and Inline Policies in the IAM User Guide . See also: AWS API Documentation :example: response = client.detach_role_policy( RoleName='string', PolicyArn='string' ) :type RoleName: string :param RoleName: [REQUIRED] The name (friendly name, not ARN) of the IAM role to detach the policy from. This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: _+=,.@- :type PolicyArn: string :param PolicyArn: [REQUIRED] The Amazon Resource Name (ARN) of the IAM policy you want to detach. For more information about ARNs, see Amazon Resource Names (ARNs) and AWS Service Namespaces in the AWS General Reference . """ pass
pyobo-0.2.2
pyobo-0.2.2//src/pyobo/sources/expasy.pyfile:/src/pyobo/sources/expasy.py:function:normalize_expasy_id/normalize_expasy_id
def normalize_expasy_id(expasy_id: str) ->str: """Return a standardized ExPASy identifier string. :param expasy_id: A possibly non-normalized ExPASy identifier """ return expasy_id.replace(' ', '')
tlsenum-0.3
tlsenum-0.3//tlsenum/parse_hello.pyfile:/tlsenum/parse_hello.py:function:construct_sslv2_client_hello/construct_sslv2_client_hello
def construct_sslv2_client_hello(): """ Returns a SSLv2 ClientHello message in bytes. This is a quick and dirty function to return a SSLv2 ClientHello with all 7 specified cipher suites. I don't really want to enumerate the supported SSLv2 cipher suites so this doesn't have to be flexible... This function does not require test coverage because I am simply returning bytes constructed from a fix list. """ return bytes([128, 46, 1, 0, 2, 0, 21, 0, 0, 0, 16, 1, 0, 128, 2, 0, 128, 3, 0, 128, 4, 0, 128, 5, 0, 128, 6, 0, 64, 7, 0, 192, 83, 67, 91, 144, 157, 155, 114, 11, 188, 12, 188, 43, 146, 168, 72, 151])
bpy
bpy//ops/outliner.pyfile:/ops/outliner.py:function:hide/hide
def hide(): """Hide selected objects and collections """ pass
GridCal-3.7.0
GridCal-3.7.0//GridCal/Engine/Sparse/utils.pyfile:/GridCal/Engine/Sparse/utils.py:function:slice_to_range/slice_to_range
def slice_to_range(sl: slice, n): """ Turn a slice into a range :param sl: slice object :param n: total number of items :return: range object, if the slice is not supported an exception is raised """ if sl.start is None and sl.step is None and sl.start is None: return range(n) elif sl.start is not None and sl.step is None and sl.start is None: return range(sl.start, n) elif sl.start is not None and sl.step is not None and sl.start is None: raise Exception('Invalid slice') elif sl.start is not None and sl.step is None and sl.start is not None: return range(sl.start, sl.stop) elif sl.start is not None and sl.step is not None and sl.start is not None: return range(sl.start, sl.stop, sl.step) elif sl.start is None and sl.step is None and sl.start is not None: return range(sl.stop) else: raise Exception('Invalid slice')
onegov.election_day-3.13.9
onegov.election_day-3.13.9//onegov/election_day/utils/election/parties.pyfile:/onegov/election_day/utils/election/parties.py:function:has_party_results/has_party_results
def has_party_results(item): """ Returns True, if the item has party results. """ if getattr(item, 'type', 'proporz') == 'proporz': if item.party_results.first(): return True return False
mnemonicode-1.4.5
mnemonicode-1.4.5//mnemonicode/_utils.pyfile:/mnemonicode/_utils.py:function:to_base/to_base
def to_base(base, num): """Encode a positive integer as a big-endian list of digits in the given base. """ if num < 0: raise ValueError('only works on positive integers') out = [] while num > 0: out.insert(0, num % base) num //= base return out
ak-androguard-3.3.7
ak-androguard-3.3.7//androguard/core/androconf.pyfile:/androguard/core/androconf.py:function:is_android_raw/is_android_raw
def is_android_raw(raw): """ Returns a string that describes the type of file, for common Android specific formats """ val = None if raw[0:2] == b'PK' and b'AndroidManifest.xml' in raw: val = 'APK' elif raw[0:3] == b'dex': val = 'DEX' elif raw[0:3] == b'dey': val = 'DEY' elif raw[0:4] == b'\x03\x00\x08\x00': val = 'AXML' elif raw[0:4] == b'\x02\x00\x0c\x00': val = b'ARSC' return val
radon
radon//raw.pyfile:/raw.py:function:_split_tokens/_split_tokens
def _split_tokens(tokens, token, value): """Split a list of tokens on the specified token pair (token, value), where *token* is the token type (i.e. its code) and *value* its actual value in the code. """ res = [[]] for token_values in tokens: if (token, value) == token_values[:2]: res.append([]) continue res[-1].append(token_values) return res
lazr.batchnavigator-1.3.0
lazr.batchnavigator-1.3.0//src/lazr/batchnavigator/z3batching/interfaces.pyclass:IBatch/__getitem__
def __getitem__(index): """Return the element at the given offset."""
coremltools
coremltools//models/neural_network/quantization_utils.pyfile:/models/neural_network/quantization_utils.py:function:_decompose_bytes_to_bit_arr/_decompose_bytes_to_bit_arr
def _decompose_bytes_to_bit_arr(arr): """ Unpack bytes to bits :param arr: list Byte Stream, as a list of uint8 values Returns ------- bit_arr: list Decomposed bit stream as a list of 0/1s of length (len(arr) * 8) """ bit_arr = [] for idx in range(len(arr)): for i in reversed(range(8)): bit_arr.append(arr[idx] >> i & 1 << 0) return bit_arr
Monary-0.5.0
Monary-0.5.0//monary/monary_param.pyclass:MonaryParam/from_lists
@classmethod def from_lists(cls, data, fields, types=None): """Create a list of MonaryParams from lists of arguments. These three lists will be repeated passed to __init__ as array, field, and mtype. :Parameters: - `data`: List of numpy masked arrays. - `fields`: List of field name. - `types` (optional): List of corresponding types. """ if types is None: if not len(data) == len(fields): raise ValueError('Data and fields must be of equal length.') return cls.from_groups(zip(data, fields)) else: if not len(data) == len(fields) == len(types): raise ValueError('Data, fields, and types must be of equal length.' ) return cls.from_groups(zip(data, fields, types))
eppy-0.5.52
eppy-0.5.52//eppy/loops.pyfile:/eppy/loops.py:function:getfieldindex/getfieldindex
def getfieldindex(data, commdct, objkey, fname): """given objkey and fieldname, return its index""" objindex = data.dtls.index(objkey) objcomm = commdct[objindex] for i_index, item in enumerate(objcomm): try: if item['field'] == [fname]: break except KeyError as err: pass return i_index
ethereum-2.3.2
ethereum-2.3.2//ethereum/utils.pyfile:/ethereum/utils.py:function:encode_root/encode_root
def encode_root(v): """encodes a trie root into serialization""" return v
pyschoof-0.1
pyschoof-0.1//pyschoof/naive_schoof.pyfile:/pyschoof/naive_schoof.py:function:possible_frobenius_trace_range/possible_frobenius_trace_range
def possible_frobenius_trace_range(field): """ Return the interval in which the trace of the Frobenius endomorphism must reside. This is the naive estimation: a curve has at least one point (at infinity), and at most @f$ 2q + 1 @f$ points, where @f$ q @f$ is the field size. @return The interval that must contain the trace of the Frobenius endomorphism. """ return range(-field.size(), field.size() + 1)
cpyvke-1.2.7
cpyvke-1.2.7//cpyvke/utils/display.pyfile:/cpyvke/utils/display.py:function:format_kernel/format_kernel
def format_kernel(variables, name, screen_width): """ Format regular variables """ max_width = int(screen_width / 5) typ = '[' + variables[name]['type'] + ']' val = variables[name]['value'] if len(val) > 3 * max_width: val = val[0:3 * max_width - 4] + '... ' if len(name) > max_width: name = name[0:max_width - 4] + '... ' if len(typ) > max_width: typ = typ[0:max_width - 4] + '... ' s1 = '{:{wname}} {:{wval}}'.format(name, val, wname=max_width, wval=3 * max_width) s2 = '{:{wtype}}'.format(typ, wtype=screen_width - len(s1)) return s1, s2
cnregion-0.1.0
cnregion-0.1.0//cnregion/division.pyclass:Division/is_placeholder
@classmethod def is_placeholder(cls, code): """省直辖县级行政区划/自治区直辖县级行政区划。不属于正常地区,占位连接直辖县""" if code in ('156419000000000', '156429000000000', '156469000000000', '156659000000000'): return True return False
fake-bpy-module-2.79-20200428
fake-bpy-module-2.79-20200428//bpy/ops/node.pyfile:/bpy/ops/node.py:function:properties/properties
def properties(): """Toggle the properties region visibility """ pass
markdown-to-html-1.1
markdown-to-html-1.1//markdown-to-html/practice.pyfile:/markdown-to-html/practice.py:function:generator/generator
def generator(lines): """ >>> lines = ['Question: 1', 'Option: 1', 'Question: 2', 'Option: 3', "Question: 3", "Option: 4"] >>> questions = list(generator(lines)) >>> len(questions) 3 >>> len(questions[0]) 2 >>> len(questions[1]) 2 """ lst = [] for line in lines: if line.startswith('Question:'): if lst: yield lst lst = [line.replace('Question:', '', 1)] elif line.strip(): lst.append(line.replace('Option:', '', 1)) if lst: yield lst
horae.notification-1.0a1
horae.notification-1.0a1//horae/notification/interfaces.pyclass:INotifications/unread
def unread(): """ Number of unread notifications for the current user """
uspto-opendata-python-0.8.3
uspto-opendata-python-0.8.3//uspto/util/common.pyfile:/uspto/util/common.py:function:to_list/to_list
def to_list(obj): """Convert an object to a list if it is not already one""" if not isinstance(obj, (list, tuple)): obj = [obj] return obj
zope.i18n-4.7.0
zope.i18n-4.7.0//src/zope/i18n/interfaces/locales.pyclass:ILocaleCalendar/getMonthNames
def getMonthNames(): """Return a list of month names."""
Trionyx-2.1.3
Trionyx-2.1.3//trionyx/renderer.pyfile:/trionyx/renderer.py:function:list_value_renderer/list_value_renderer
def list_value_renderer(value, **options): """Render list value""" return ', '.join(map(str, value))
dxlfiletransferclient
dxlfiletransferclient//store.pyfile:/store.py:function:_get_value_as_int/_get_value_as_int
def _get_value_as_int(dict_obj, key): """ Return the value associated with a key in a dictionary, converted to an int. :param dict dict_obj: Dictionary to retrieve the value from :param str key: Key associated with the value to return :return The value, as an integer. Returns 'None' if the key cannot be found in the dictionary. :rtype: int :raises ValueError: If the key is present in the dictionary but the value cannot be converted to an int. """ return_value = None if key in dict_obj: try: return_value = int(dict_obj.get(key)) except ValueError: raise ValueError("'{}' of '{}' could not be converted to an int" .format(key, return_value)) return return_value
pyaux
pyaux//monkeys.pyfile:/monkeys.py:function:use_exc_ipdb/use_exc_ipdb
def use_exc_ipdb(): """ Set unhandled exception handler to automatically start ipdb """ import pyaux.exc_ipdb as exc_ipdb exc_ipdb.init()
Products.ATContentTypes-3.0.3
Products.ATContentTypes-3.0.3//Products/ATContentTypes/interfaces/topic.pyclass:IATTopic/removeSortCriterion
def removeSortCriterion(): """remove the Sort criterion. """
refl1d
refl1d//experiment.pyfile:/experiment.py:function:_polarized_nonmagnetic/_polarized_nonmagnetic
def _polarized_nonmagnetic(r): """Convert nonmagnetic data to polarized representation. Polarized non-magnetic data repeats the reflectivity in the non spin flip channels and sets the spin flip channels to zero. """ nsf = r sf = 0 * r return [nsf, sf, sf, nsf]
Django_504
Django_504//contrib/sessions/backends/base.pyclass:SessionBase/clear_expired
@classmethod def clear_expired(cls): """ Remove expired sessions from the session store. If this operation isn't possible on a given backend, it should raise NotImplementedError. If it isn't necessary, because the backend has a built-in expiration mechanism, it should be a no-op. """ raise NotImplementedError('This backend does not support clear_expired().')
iaesdk
iaesdk//ibm_analytics_engine_api_v2.pyclass:AnalyticsEngineLoggingNodeSpec/_from_dict
@classmethod def _from_dict(cls, _dict): """Initialize a AnalyticsEngineLoggingNodeSpec object from a json dictionary.""" return cls.from_dict(_dict)
trefoil
trefoil//netcdf/utilities.pyfile:/netcdf/utilities.py:function:copy_attributes/copy_attributes
def copy_attributes(source, target, attribute_names, overwrite=True): """ Copies attributes from source object to target object, overwriting if already exists. :param source: the source object (dataset, variable, etc) :param target: the target object :param attribute_names: tuple / list of attribute names to copy across """ for attribute_name in attribute_names: if attribute_name in '_FillValue': continue if hasattr(target, attribute_name) and not overwrite: raise Exception( 'Attribute already exists in target, but overwrite is false') setattr(target, attribute_name, getattr(source, attribute_name))
Soprano-0.8.7.1
Soprano-0.8.7.1//soprano/properties/nmr/utils.pyfile:/soprano/properties/nmr/utils.py:function:_anisotropy/_anisotropy
def _anisotropy(haeb_evals, reduced=False): """Calculate anisotropy given eigenvalues sorted with Haeberlen convention""" f = 2.0 / 3.0 if reduced else 1.0 return (haeb_evals[:, (2)] - (haeb_evals[:, (0)] + haeb_evals[:, (1)]) / 2.0) * f
rma
rma//redis.pyfile:/redis.py:function:size_of_pointer_fn/size_of_pointer_fn
def size_of_pointer_fn(): """ Return pointer size for current Redis connection :return int: """ return 8
dsu
dsu//sklearnUtils.pyfile:/sklearnUtils.py:function:feature_scale_or_normalize/feature_scale_or_normalize
def feature_scale_or_normalize(dataframe, col_names, norm_type='StandardScaler' ): """ Basically converts floating point or integer valued columns to fit into the range of 0 to 1 """ from sklearn.preprocessing import StandardScaler, MinMaxScaler if norm_type == 'StandardScaler': return StandardScaler().fit_transform(dataframe[col_names]) elif norm_type == 'MinMaxScaler': return MinMaxScaler().fit_transform(dataframe[col_names]) else: return None
pandas
pandas//core/indexes/api.pyfile:/core/indexes/api.py:function:all_indexes_same/all_indexes_same
def all_indexes_same(indexes): """ Determine if all indexes contain the same elements. Parameters ---------- indexes : list of Index objects Returns ------- bool True if all indexes contain the same elements, False otherwise. """ first = indexes[0] for index in indexes[1:]: if not first.equals(index): return False return True
python-clu-0.7.1
python-clu-0.7.1//clu/exporting.pyclass:ExporterBase/unregister
@classmethod def unregister(cls, dotpath): """ Unregister a previously-registered ExporterBase instance, specified by the dotted path (née “dotpath”) of the module in which it is ensconced. Returns the successfully unregistered instance in question. """ return cls.instances.pop(dotpath, None)
rdmlpython
rdmlpython//rdml.pyfile:/rdml.py:function:_sort_list_int/_sort_list_int
def _sort_list_int(elem): """Get the first element of the array as int. for sorting. Args: elem: The 2d list Returns: The a int value of the first list element. """ return int(elem[0])
dbnd_airflow_operator
dbnd_airflow_operator//airflow_utils.pyfile:/airflow_utils.py:function:DbndFunctionalOperator_1_10_0/DbndFunctionalOperator_1_10_0
def DbndFunctionalOperator_1_10_0(task_id, dbnd_task_type, dbnd_task_params_fields, **ctor_kwargs): """ Workaround for backwards compatibility with Airflow 1.10.0, dynamically creating new operator class (that inherits AirflowDagDbndOperator). This is used because XCom templates for each operator are found in a class attribute and we have different XCom templates for each INSTANCE of the operator. Also, the template_fields attribute has a different value for each task, so we must ensure that they don't get mixed up. """ template_fields = dbnd_task_params_fields from dbnd_airflow_operator.dbnd_functional_operator import DbndFunctionalOperator new_op = type(dbnd_task_type, (DbndFunctionalOperator,), { 'template_fields': template_fields}) op = new_op(task_id=task_id, dbnd_task_type=dbnd_task_type, dbnd_task_params_fields=dbnd_task_params_fields, **ctor_kwargs) return op
astropy
astropy//table/np_utils.pyfile:/table/np_utils.py:function:fix_column_name/fix_column_name
def fix_column_name(val): """ Fixes column names so that they are compatible with Numpy on Python 2. Raises a ValueError exception if the column name contains Unicode characters, which can not reasonably be used as a column name. """ if val is not None: try: val = str(val) except UnicodeEncodeError: raise return val
pyjwkest-1.4.2
pyjwkest-1.4.2//src/jwkest/elliptic.pyfile:/src/jwkest/elliptic.py:function:_gbd/_gbd
def _gbd(n): """Compute second greatest base-2 divisor""" i = 1 if n <= 0: return 0 while not n % i: i <<= 1 return i >> 2
viper
viper//demo/processors.pyfile:/demo/processors.py:function:text_stripper/text_stripper
def text_stripper(txt: str) ->str: """This is a stdout/stderr processor that strips the given text. :param str txt: The text to be stripped :rtype: str """ return txt.strip()
mando-0.7.0
mando-0.7.0//mando/utils.pyfile:/mando/utils.py:function:purify_kwargs/purify_kwargs
def purify_kwargs(kwargs): """If type or metavar are set to None, they are removed from kwargs.""" for key, value in kwargs.copy().items(): if key in set(['type', 'metavar']) and value is None: del kwargs[key] return kwargs
dfvfs-20200429
dfvfs-20200429//dfvfs/mount/manager.pyclass:MountPointManager/DeregisterMountPoint
@classmethod def DeregisterMountPoint(cls, mount_point): """Deregisters a path specification mount point. Args: mount_point (str): mount point identifier. Raises: KeyError: if the corresponding mount point is not set. """ if mount_point not in cls._mount_points: raise KeyError('Mount point: {0:s} not set.'.format(mount_point)) del cls._mount_points[mount_point]
oci
oci//resource_manager/models/config_source.pyclass:ConfigSource/get_subtype
@staticmethod def get_subtype(object_dictionary): """ Given the hash representation of a subtype of this class, use the info in the hash to return the class of the subtype. """ type = object_dictionary['configSourceType'] if type == 'ZIP_UPLOAD': return 'ZipUploadConfigSource' else: return 'ConfigSource'
sopel_modules.stats-0.1
sopel_modules.stats-0.1//sopel_modules/stats/stats.pyfile:/sopel_modules/stats/stats.py:function:get_local_word_count/get_local_word_count
def get_local_word_count(bot, _nick, _count_key): """ Returns the word count for a given nick for the specific channel""" try: word_count = int(bot.db.get_nick_value(_nick, _count_key)) except: word_count = 0 return word_count
nodeconductor-zabbix-0.6.0
nodeconductor-zabbix-0.6.0//src/nodeconductor_zabbix/models.pyclass:Host/get_visible_name_from_scope
@classmethod def get_visible_name_from_scope(cls, scope): """ Generate visible name based on host scope """ return ('%s-%s' % (scope.uuid.hex, scope.name))[:64]
synology_dsm
synology_dsm//helpers.pyclass:SynoFormatHelper/bytes_to_readable
@staticmethod def bytes_to_readable(num): """Converts bytes to a human readable format.""" if num < 512: return '0 Kb' elif num < 1024: return '1 Kb' for unit in ['', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb']: if abs(num) < 1024.0: return '%3.1f%s' % (num, unit) num /= 1024.0 return '%.1f%s' % (num, 'Yb')
chinesepostman-0.0.2
chinesepostman-0.0.2//chinesepostman/my_math.pyfile:/chinesepostman/my_math.py:function:is_even/is_even
def is_even(number): """ Return True if a number is even, False if odd. """ return not number % 2
scour-0.37
scour-0.37//scour/scour.pyfile:/scour/scour.py:function:optimizeAngle/optimizeAngle
def optimizeAngle(angle): """ Because any rotation can be expressed within 360 degrees of any given number, and since negative angles sometimes are one character longer than corresponding positive angle, we shorten the number to one in the range to [-90, 270[. """ if angle < 0: angle %= -360 else: angle %= 360 if angle >= 270: angle -= 360 elif angle < -90: angle += 360 return angle
eclcli-1.3.5
eclcli-1.3.5//eclcli/monitoring/monitoringclient/ecl/common/cliutils.pyfile:/eclcli/monitoring/monitoringclient/ecl/common/cliutils.py:function:add_arg/add_arg
def add_arg(func, *args, **kwargs): """Bind CLI arguments to a shell.py `do_foo` function.""" if not hasattr(func, 'arguments'): func.arguments = [] if (args, kwargs) not in func.arguments: func.arguments.insert(0, (args, kwargs))
silva.core.interfaces-3.0.4
silva.core.interfaces-3.0.4//src/silva/core/interfaces/adapters.pyclass:IPublicationWorkflow/reject_request
def reject_request(message): """Reject a request for approval. """
pygenes-0.0.5.post3
pygenes-0.0.5.post3//versioneer.pyfile:/versioneer.py:function:plus_or_dot/plus_or_dot
def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if '+' in pieces.get('closest-tag', ''): return '.' return '+'
dpay
dpay//utils.pyfile:/utils.py:function:construct_identifier/construct_identifier
def construct_identifier(*args): """ Create a post identifier from comment/post object or arguments. Examples: :: construct_identifier('username', 'permlink') construct_identifier({'author': 'username', 'permlink': 'permlink'}) """ if len(args) == 1: op = args[0] author, permlink = op['author'], op['permlink'] elif len(args) == 2: author, permlink = args else: raise ValueError('construct_identifier() received unparsable arguments' ) author = author.replace('@', '') fields = dict(author=author, permlink=permlink) return '{author}/{permlink}'.format(**fields)
metatube
metatube//_version.pyfile:/_version.py:function:plus_or_dot/plus_or_dot
def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if '+' in pieces.get('closest-tag', ''): return '.' return '+'
cpyvke-1.2.7
cpyvke-1.2.7//cpyvke/utils/comm.pyfile:/cpyvke/utils/comm.py:function:recv_all/recv_all
def recv_all(sock, n): """ Helper function to recv n bytes or return None if EOF is hit """ data = b'' while len(data) < n: packet = sock.recv(n - len(data)) if not packet: return None data += packet return data
plonetheme.cleanblog-1.2.3
plonetheme.cleanblog-1.2.3//src/plonetheme/clean_blog/setuphandlers.pyfile:/src/plonetheme/clean_blog/setuphandlers.py:function:post_install/post_install
def post_install(context): """Post install script"""
plaso-20200430
plaso-20200430//plaso/output/manager.pyclass:OutputManager/DeregisterOutput
@classmethod def DeregisterOutput(cls, output_class): """Deregisters an output class. The output classes are identified based on their NAME attribute. Args: output_class (type): output module class. Raises: KeyError: if output class is not set for the corresponding data type. """ output_class_name = output_class.NAME.lower() if output_class_name in cls._disabled_output_classes: class_dict = cls._disabled_output_classes else: class_dict = cls._output_classes if output_class_name not in class_dict: raise KeyError('Output class not set for name: {0:s}.'.format( output_class.NAME)) del class_dict[output_class_name]
jdcloud_cli-1.2.5
jdcloud_cli-1.2.5//jdcloud_cli/cement/core/arg.pyclass:IArgument/add_argument
def add_argument(*args, **kw): """ Add arguments for parsing. This should be -o/--option or positional. Note that the interface defines the following parameters so that at the very least, external extensions can guarantee that they can properly add command line arguments when necessary. The implementation itself should, and will provide and support many more options than those listed here. That said, the implementation must support the following: :arg args: List of option arguments. Generally something like ['-h', '--help']. :keyword dest: The destination name (var). Default: arg[0]'s string. :keyword help: The help text for --help output (for that argument). :keyword action: Must support: ['store', 'store_true', 'store_false', 'store_const'] :keyword choices: A list of valid values that can be passed to an option whose action is ``store``. :keyword const: The value stored if action == 'store_const'. :keyword default: The default value. :returns: ``None`` """
desc
desc//original/train.pyfile:/original/train.py:function:getdims/getdims
def getdims(x=(10000, 200)): """ return the dims for network """ assert len(x) == 2 n_sample = x[0] if n_sample > 20000: dims = [x[-1], 128, 32] elif n_sample > 10000: dims = [x[-1], 64, 32] elif n_sample > 5000: dims = [x[-1], 32, 16] elif n_sample > 2000: dims = [x[-1], 128] elif n_sample > 500: dims = [x[-1], 64] else: dims = [x[-1], 16] return dims
crabpy_pyramid-0.8.1
crabpy_pyramid-0.8.1//crabpy_pyramid/renderers/crab.pyfile:/crabpy_pyramid/renderers/crab.py:function:list_straten_adapter/list_straten_adapter
def list_straten_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Straat` to json. """ return {'id': obj.id, 'label': obj.label, 'status': {'id': obj.status. id, 'naam': obj.status.naam, 'definitie': obj.status.definitie}}
tiffany
tiffany//from-pil-py3/Image.pyfile:/from-pil-py3/Image.py:function:composite/composite
def composite(image1, image2, mask): """Create composite image by blending images using a transparency mask""" image = image2.copy() image.paste(image1, None, mask) return image
dropbox
dropbox//team_log.pyclass:EventType/paper_folder_team_invite
@classmethod def paper_folder_team_invite(cls, val): """ Create an instance of this class set to the ``paper_folder_team_invite`` tag with value ``val``. :param PaperFolderTeamInviteType val: :rtype: EventType """ return cls('paper_folder_team_invite', val)
z3c.metrics-0.1
z3c.metrics-0.1//z3c/metrics/interfaces.pyclass:IScale/fromValue
def fromValue(value): """Return the scaled value for the metric value"""
sonicparanoid-1.3.2
sonicparanoid-1.3.2//sonicparanoid/mmseqs_parser_cython.pyfile:/sonicparanoid/mmseqs_parser_cython.py:function:get_params/get_params
def get_params(): """Parse and analyse command line parameters.""" import argparse parser_usage = """ Provide an input file generated using mmseqs2 and converted into BLASTP compatible tab-separated format. Outputs a file of ortholog and paralogs that can be processed by InParanoid. """ parser = argparse.ArgumentParser(description='mmseqs2 parser 0.1', usage=parser_usage) parser.add_argument('-i', '--input', type=str, required=True, help= """Tab-separated alignment file generated using mmseqs2 and converted in BLASTP tab-separated format. NOTE: for details on the fields contained in the output refer to function inparanoid_like_parser""" , default=None) parser.add_argument('-q', '--query', type=str, required=True, help= 'FASTA file with the query proteins.', default=None) parser.add_argument('-t', '--db', type=str, required=True, help= 'FASTA file with the target proteins.', default=None) parser.add_argument('-o', '--output', type=str, required=True, help= 'File in which the output will be stored.', default=None) parser.add_argument('-r', '--run-dir', type=str, required=False, help= 'Directory in which the files with sequence lengths are stored.', default=None) parser.add_argument('-c', '--cutoff', type=int, required=False, help= 'Cutoff score (sum of hsp bitscores for each hit) for alignments.', default=40) parser.add_argument('-d', '--debug', required=False, help= """Output debug information. NOTE: this is not used when the input is STDIN.""" , default=False, action='store_true') args = parser.parse_args() return args, parser