repo
stringlengths
1
29
path
stringlengths
24
332
code
stringlengths
39
579k
JMS-Utils-1.0.2
JMS-Utils-1.0.2//versioneer.pyfile:/versioneer.py:function:render_git_describe_long/render_git_describe_long
def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces['closest-tag']: rendered = pieces['closest-tag'] rendered += '-%d-g%s' % (pieces['distance'], pieces['short']) else: rendered = pieces['short'] if pieces['dirty']: rendered += '-dirty' return rendered
eloquent-0.5
eloquent-0.5//eloquent/orm/model.pyclass:Model/query
@classmethod def query(cls): """ Begin querying the model. :return: A Builder instance :rtype: eloquent.orm.Builder """ return cls().new_query()
pyang
pyang//statements.pyfile:/statements.py:function:check_primitive_type/check_primitive_type
def check_primitive_type(stmt): """i_type_spec appears to indicate primitive type. """ return True if getattr(stmt, 'i_type_spec', None) else False
datalake-dtkav-0.36
datalake-dtkav-0.36//versioneer.pyfile:/versioneer.py:function:scan_setup_py/scan_setup_py
def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open('setup.py', 'r') as f: for line in f.readlines(): if 'import versioneer' in line: found.add('import') if 'versioneer.get_cmdclass()' in line: found.add('cmdclass') if 'versioneer.get_version()' in line: found.add('get_version') if 'versioneer.VCS' in line: setters = True if 'versioneer.versionfile_source' in line: setters = True if len(found) != 3: print('') print('Your setup.py appears to be missing some important items') print('(but I might be wrong). Please make sure it has something') print('roughly like the following:') print('') print(' import versioneer') print(' setup( version=versioneer.get_version(),') print(' cmdclass=versioneer.get_cmdclass(), ...)') print('') errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print('now lives in setup.cfg, and should be removed from setup.py') print('') errors += 1 return errors
pero-0.14.0
pero-0.14.0//pero/events/prop.pyclass:PropertyChangedEvt/from_evt
@classmethod def from_evt(cls, evt): """ Initializes a new instance of given class by copying all current data. Args: evt: pero.PropertyChangedEvt Source event from which to copy the data. Returns: cls instance New instance of requested class. """ return cls(name=evt.name, old_value=evt.old_value, new_value=evt.new_value)
zither
zither//zither.pyfile:/zither.py:function:_get_sample_names/_get_sample_names
def _get_sample_names(input_vcf): """Returns list of sample names from input VCF""" with open(input_vcf, 'r') as input_file: column_header = None sample_names = [] for line in input_file.readlines(): if not line.startswith('##'): if line.startswith('#'): column_header = line.rstrip() column_fields = column_header.split('\t') n = len(column_fields) sample_names = column_fields[9:n + 1] return sample_names
git2net
git2net//extraction.pyfile:/extraction.py:function:_get_block_length/_get_block_length
def _get_block_length(lines, k): """ Calculates the length (in number of lines) of a edit of added/deleted lines starting in a given line k. Args: lines: dictionary of added or deleted lines k: line number to check for Returns: block_size: number of lines in the contiguously block that was modified """ if k not in lines or k > 1 and k - 1 in lines: edit = False block_size = 0 else: edit = True block_size = 1 while edit: if k + block_size in lines: block_size += 1 else: edit = False return block_size
pyphs-0.5.1
pyphs-0.5.1//pyphs/graphs/netlists.pyfile:/pyphs/graphs/netlists.py:function:print_netlist_line/print_netlist_line
def print_netlist_line(dic): """ Return the line of the pyphs netlist associated to > dic.comp label nodes parameters Parameters ---------- item : dict Dictionary that encodes the component with keys: * 'dictionary': str module in 'pyphs/dicitonary/' * 'component': component in 'dictionary' * 'label': component label * 'nodes': tuple of nodes identifiers * 'arguments': dict Dictionary of parameters. Keys are parameters labels in dic.comp, and values are float (parameter value), str (new parameter label) or tuple (str, float). Output ------- line : str Formated string that corresponds to a single line in the netlist (includes end cariage return). """ component = '{0}.{1} {2} {3}:'.format(dic['dictionary'], dic[ 'component'], dic['label'], dic['nodes']) pars = '' if dic['arguments'] is not None: for par in dic['arguments'].keys(): pars += ' {}={};'.format(par, str(dic['arguments'][par])) line = component + pars + '\n' return line
script
script//lazytox.pyfile:/lazytox.py:function:validate_requirements_ok/validate_requirements_ok
def validate_requirements_ok(): """Validate requirements, returns True of ok.""" from gen_requirements_all import main as req_main return req_main(True) == 0
selinonlib
selinonlib//global_config.pyclass:GlobalConfig/_parse_trace_logging
@classmethod def _parse_trace_logging(cls, trace_def): """Parse tracing by Python's logging facilities. :param trace_def: definition of tracing as supplied in the YAML file """ if trace_def is True: cls._trace_logging.append(trace_def)
Products.CMFPlone-5.2.1
Products.CMFPlone-5.2.1//Products/CMFPlone/MigrationTool.pyfile:/Products/CMFPlone/MigrationTool.py:function:registerUpgradePath/registerUpgradePath
def registerUpgradePath(oldversion, newversion, function): """ Basic register func """ pass
pisces
pisces//util.pyfile:/util.py:function:get_options/get_options
def get_options(db, prefix=None): """ for coretable in CORETABLES: table_group.add_argument('--' + coretable.name, default=None, metavar='owner.tablename', dest=coretable.name) """ options = {'url': 'sqlite:///' + db, 'prefix': prefix} return options
opencage-1.2.1
opencage-1.2.1//opencage/geocoder.pyfile:/opencage/geocoder.py:function:float_if_float/float_if_float
def float_if_float(float_string): """ Given a float string, returns the float value. On value error returns the original string. """ try: float_val = float(float_string) return float_val except ValueError: return float_string
Mikado
Mikado//loci/excluded.pyclass:Excluded/is_intersecting
@classmethod def is_intersecting(cls): """Present to fulfill the contract with Abstractlocus, but it only raises a NotImplementedError""" raise NotImplementedError()
plaso-20200430
plaso-20200430//plaso/parsers/manager.pyclass:ParsersManager/GetParsersInformation
@classmethod def GetParsersInformation(cls): """Retrieves the parsers information. Returns: list[tuple[str, str]]: parser names and descriptions. """ parsers_information = [] for _, parser_class in cls._GetParsers(): description = getattr(parser_class, 'DESCRIPTION', '') parsers_information.append((parser_class.NAME, description)) return parsers_information
bsdiff4-1.1.9
bsdiff4-1.1.9//bsdiff4/cli.pyfile:/bsdiff4/cli.py:function:human_bytes/human_bytes
def human_bytes(n): """ return the number of bytes 'n' in more human readable form """ if n < 1024: return '%i B' % n k = (n - 1) / 1024 + 1 if k < 1024: return '%i KB' % k return '%.2f MB' % (float(n) / 2 ** 20)
simplebus-1.0.1
simplebus-1.0.1//simplebus/bus.pyclass:Bus/__get_options
@staticmethod def __get_options(cache, key, override_options, pool_options): """Gets the options for the specified key.""" options = cache.get(key) if not options: options = pool_options.get('*').copy() options_form_config = pool_options.get(key) if options_form_config: options.update(options_form_config) cache[key] = options if override_options: options = options.copy() options.update(override_options) return options
costools-1.2.3
costools-1.2.3//lib/costools/timefilter.pyfile:/lib/costools/timefilter.py:function:prtOptions/prtOptions
def prtOptions(): """Print a list of command-line options and arguments.""" print('The command-line arguments are:') print(' -h (print help)') print(' --help (print help)') print(' -r (print the full version string)') print(' --version (print the version number)') print(' -v (print messages)') print(' input: input corrtag file name') print(" output: output corrtag file name, or '' or none") print(' if output was not specified, the input file will be modified') print(' in-place (unless filter was also not specified, equivalent to' ) print(" filter='info')") print(' filter: column name, relation, cutoff value') print(" e.g. 'sun_alt > -0.5 or ly_alpha > 2'") print(" or 'info' or 'reset' ('clear' is synonymous with 'reset')")
freegames
freegames//utils.pyfile:/utils.py:function:floor/floor
def floor(value, size, offset=200): """Floor of `value` given `size` and `offset`. The floor function is best understood with a diagram of the number line:: -200 -100 0 100 200 <--|--x--|-----|--y--|--z--|--> The number line shown has offset 200 denoted by the left-hand tick mark at -200 and size 100 denoted by the tick marks at -100, 0, 100, and 200. The floor of a value is the left-hand tick mark of the range where it lies. So for the points show above: ``floor(x)`` is -200, ``floor(y)`` is 0, and ``floor(z)`` is 100. >>> floor(10, 100) 0.0 >>> floor(120, 100) 100.0 >>> floor(-10, 100) -100.0 >>> floor(-150, 100) -200.0 >>> floor(50, 167) -33.0 """ return float((value + offset) // size * size - offset)
zaqar-9.0.0
zaqar-9.0.0//zaqar/storage/mongodb/utils.pyfile:/zaqar/storage/mongodb/utils.py:function:descope_queue_name/descope_queue_name
def descope_queue_name(scoped_name): """Returns the unscoped queue name, given a fully-scoped name.""" return scoped_name.partition('/')[2] or None
pymarket-0.7.6
pymarket-0.7.6//pymarket/statistics/profits.pyfile:/pymarket/statistics/profits.py:function:get_gain/get_gain
def get_gain(row): """Finds the gain of the row Parameters ---------- row : pandas row Row obtained by merging a transaction with a bid dataframe Returns ------- gain The gain obtained by the row """ gap = row.price_y - row.price_x if not row.buying: gap = -gap return gap * row.quantity
pyredner_tensorflow
pyredner_tensorflow//device.pyfile:/device.py:function:set_gpu_device_id/set_gpu_device_id
def set_gpu_device_id(did: int): """ Set the gpu device id we are using. """ global gpu_device_id gpu_device_id = did
txrequest
txrequest//_headers.pyclass:IMutableHTTPHeaders/remove
def remove(name): """ Remove all header name/value pairs for the given header name. If the given name is L{Text}, it will be encoded as ISO-8859-1 before comparing to the (L{bytes}) header names. @param name: The name of the header to remove. """
imantics-0.1.12
imantics-0.1.12//imantics/image.pyclass:Image/empty
@classmethod def empty(cls, width=0, height=0): """ Creates an empty :class:`Image` """ return cls(width=width, height=height)
neurec
neurec//util/helpers.pyfile:/util/helpers.py:function:to_bool/to_bool
def to_bool(string): """Returns a boolean from a string. string -- string in format yes|no|true|false """ if string.lower() in ('yes', 'y', 'true', '1'): return True elif string.lower() in ('no', 'n', 'false', '0'): return False raise ValueError(str(string) + ' not in ["yes", "y", "true", "1", "no", "n", "false", "0"].')
pyNastran
pyNastran//op2/op2_interface/utils.pyfile:/op2/op2_interface/utils.py:function:update_label2/update_label2
def update_label2(label2, isubcase): """strips off SUBCASE from the label2 to simplfify the output keys (e.g., displacements)""" label2 = label2.split('$')[0].strip() if label2: subcase_expected = 'SUBCASE %i' % isubcase subcase_equal_expected = 'SUBCASE = %i' % isubcase if subcase_expected == label2: label2 = '' elif label2 == 'NONLINEAR': pass elif subcase_expected in label2: nchars = len(subcase_expected) ilabel_1 = label2.index(subcase_expected) ilabel_2 = ilabel_1 + nchars label2_prime = label2[:ilabel_1] + label2[ilabel_2:] label2 = label2_prime.strip() elif subcase_equal_expected in label2: slabel = label2.split('=') assert len(slabel) == 2, slabel label2 = '' elif label2.startswith('NONLINEAR '): sline = label2.split('NONLINEAR ', 1) label2 = 'NONLINEAR ' + sline[1].strip() elif 'PVAL ID=' in label2 and 'SUBCASE=' in label2: ilabel2 = label2.index('SUBCASE') slabel = label2[:ilabel2].strip().split('=') assert slabel[0] == 'PVAL ID', slabel label2 = slabel[0].strip() + '=' + slabel[1].strip() elif 'SUBCASE' in label2: slabel = label2.split('$')[0].strip().split() if len(slabel) == 2: label2 = '' elif len(slabel) == 3 and slabel[1] == '=': label2 = '' else: assert slabel[0] == 'SUBCASE', slabel label2 = slabel[3] + '=' + slabel[5] elif 'SUBCOM' in label2: subcom, isubcase = label2.split() label2 = '' elif 'SYM' in label2 or 'REPCASE' in label2: pass return label2
parseidf-1.0.0
parseidf-1.0.0//parseidf.pyfile:/parseidf.py:function:p_idfobjectlist_multiple/p_idfobjectlist_multiple
def p_idfobjectlist_multiple(p): """idfobjectlist : idfobject idfobjectlist""" p[0] = [p[1]] + p[2]
hyperspy
hyperspy//external/tifffile.pyfile:/external/tifffile.py:function:sequence/sequence
def sequence(value): """Return tuple containing value if value is not a tuple or list. >>> sequence(1) (1,) >>> sequence([1]) [1] >>> sequence('ab') ('ab',) """ return value if isinstance(value, (tuple, list)) else (value,)
fake-blender-api-2.79-0.3.1
fake-blender-api-2.79-0.3.1//bpy/ops/nla.pyfile:/bpy/ops/nla.py:function:mute_toggle/mute_toggle
def mute_toggle(): """Mute or un-mute selected strips """ pass
PyVISA-1.10.1
PyVISA-1.10.1//pyvisa/ctwrapper/functions.pyfile:/pyvisa/ctwrapper/functions.py:function:unmap_trigger/unmap_trigger
def unmap_trigger(library, session, trigger_source, trigger_destination): """Undo a previous map from the specified trigger source line to the specified destination line. Corresponds to viUnmapTrigger function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param trigger_source: Source line used in previous map. (Constants.TRIG*) :param trigger_destination: Destination line used in previous map. (Constants.TRIG*) :return: return value of the library call. :rtype: :class:`pyvisa.constants.StatusCode` """ return library.viUnmapTrigger(session, trigger_source, trigger_destination)
sympl-0.4.0
sympl-0.4.0//sympl/_components/timesteppers.pyfile:/sympl/_components/timesteppers.py:function:fourth_bashforth/fourth_bashforth
def fourth_bashforth(state, tendencies_list, timestep): """Return the new state using fourth-order Adams-Bashforth. tendencies_list should be a list of dictionaries whose values are tendencies in units/second (from oldest to newest), and timestep should be a timedelta object.""" return_state = {} for key in tendencies_list[0].keys(): return_state[key] = state[key] + timestep.total_seconds() * (55.0 / 24 * tendencies_list[-1][key] - 59.0 / 24 * tendencies_list[-2] [key] + 37.0 / 24 * tendencies_list[-3][key] - 3.0 / 8 * tendencies_list[-4][key]) return return_state
Pytzer-0.4.3
Pytzer-0.4.3//pytzer/parameters.pyfile:/pytzer/parameters.py:function:lambd_NH3_OH_CB89/lambd_NH3_OH_CB89
def lambd_NH3_OH_CB89(T, P): """n-a: ammonia hydroxide [CB89].""" lambd = 0.103 valid = T == 298.15 return lambd, valid
sharedpy-0.0.106
sharedpy-0.0.106//sharedpy/django/models.pyfile:/sharedpy/django/models.py:function:has_active_relation/has_active_relation
def has_active_relation(model_instance): """ Returns True if at least one other model instance has a relationship with this instance Intended to be used to determine if this object can safely be deleted without any consequential cascade deletions Customised version of https://stackoverflow.com/questions/26659023/deletion-objects-that-is-used-as-foreign-key and https://gist.github.com/vonorm/8617378 """ for field in model_instance._meta.get_fields(): if field.related_model: related = field.related_model.objects.filter(**{field.field. name: model_instance})[:1].values_list('pk', flat=True) if len(related) > 0: return True return False
electrumx
electrumx//lib/coins.pyclass:Coin/block_header
@classmethod def block_header(cls, block, height): """Returns the block header given a block and its height.""" return block[:cls.static_header_len(height)]
gc3libs
gc3libs//backends/shellcmd.pyfile:/backends/shellcmd.py:function:_parse_percentage/_parse_percentage
def _parse_percentage(val): """ Convert a percentage string into a Python float. The percent sign at the end is optional:: >>> _parse_percentage('10') 10.0 >>> _parse_percentage('10%') 10.0 >>> _parse_percentage('0.25%') 0.25 """ return float(val[:-1]) if val.endswith('%') else float(val)
habu-0.1.33
habu-0.1.33//habu/cli/beta_cmd_proxy.pyfile:/habu/cli/beta_cmd_proxy.py:function:autoCert/autoCert
def autoCert(cn, caName, name): """Create a certificate signed by caName for cn into name.""" import ca cac, cak = ca.loadOrDie(caName) c, k = ca.makeCert(cn, ca=cac, cak=cak) ca.saveOrDie(c, k, name)
pydbc
pydbc//parser/scanner.pyclass:DbcParser/p_attribute_value_type
@staticmethod def p_attribute_value_type(p): """attribute_value_type : attribute_value_type_int | attribute_value_type_hex | attribute_value_type_float | attribute_value_type_string | attribute_value_type_enum""" p[0] = p[1]
luigi-2.8.13
luigi-2.8.13//luigi/cmdline_parser.pyclass:CmdlineParser/get_instance
@classmethod def get_instance(cls): """ Singleton getter """ return cls._instance
anvil-parser-0.6.1
anvil-parser-0.6.1//anvil/block.pyclass:Block/from_name
@classmethod def from_name(cls, name: str, *args, **kwargs): """ Creates a new Block from the format: ``namespace:block_id`` Parameters ---------- name Block in said format , args, kwargs Will be passed on to the main constructor """ namespace, block_id = name.split(':') return cls(namespace, block_id, *args, **kwargs)
reportlab-3.5.42
reportlab-3.5.42//src/reportlab/platypus/doctemplate.pyfile:/src/reportlab/platypus/doctemplate.py:function:_doNothing/_doNothing
def _doNothing(canvas, doc): """Dummy callback for onPage""" pass
POSPairWordEmbeddings
POSPairWordEmbeddings//gensim/matutils.pyfile:/gensim/matutils.py:function:jaccard_distance/jaccard_distance
def jaccard_distance(set1, set2): """Calculate Jaccard distance between two sets. Parameters ---------- set1 : set Input set. set2 : set Input set. Returns ------- float Jaccard distance between `set1` and `set2`. Value in range `[0, 1]`, where 0 is min distance (max similarity) and 1 is max distance (min similarity). """ union_cardinality = len(set1 | set2) if union_cardinality == 0: return 1.0 return 1.0 - float(len(set1 & set2)) / float(union_cardinality)
fake-bpy-module-2.78-20200428
fake-bpy-module-2.78-20200428//bpy/ops/node.pyfile:/bpy/ops/node.py:function:move_detach_links_release/move_detach_links_release
def move_detach_links_release(NODE_OT_links_detach=None, NODE_OT_translate_attach=None): """Move a node to detach links :param NODE_OT_links_detach: Detach Links, Remove all links to selected nodes, and try to connect neighbor nodes together :param NODE_OT_translate_attach: Move and Attach, Move nodes and attach to frame """ pass
swm-0.0.17
swm-0.0.17//swm/workers.pyclass:BaseWorker/get_id_prefix
@classmethod def get_id_prefix(cls): """Return a prefix applied to worker Ids""" return 'swm_worker'
pytorchcv-0.0.58
pytorchcv-0.0.58//pytorchcv/models/model_store.pyfile:/pytorchcv/models/model_store.py:function:calc_num_params/calc_num_params
def calc_num_params(net): """ Calculate the count of trainable parameters for a model. Parameters ---------- net : Module Analyzed model. """ import numpy as np net_params = filter(lambda p: p.requires_grad, net.parameters()) weight_count = 0 for param in net_params: weight_count += np.prod(param.size()) return weight_count
wokkel-18.0.0
wokkel-18.0.0//wokkel/iwokkel.pyclass:IPubSubResource/affiliationsSet
def affiliationsSet(request): """ Called when a affiliations modify request has been received. @param request: The publish-subscribe request. @type request: L{wokkel.pubsub.PubSubRequest} @return: A deferred that fires with C{None} when the affiliation changes were succesfully processed.. @rtype: L{Deferred<twisted.internet.defer.Deferred>} @note: Affiliations are always on the bare JID. The JIDs in L{wokkel.pubsub.PubSubRequest}'s C{affiliations} attribute are already stripped of any resource. """
unified_plotting
unified_plotting//_unified_arguments/arguments.pyfile:/_unified_arguments/arguments.py:function:plot_color/plot_color
def plot_color(background_paper_color=None, background_plot_color=None): """ *Plot and paper color* Parameters: background_plot_color (str or tuple): Background color of the main plot area. Possible values: See :ref:`colors`. background_paper_color (str or tuple): Background color of the entire drawing area. Possible values: See :ref:`colors`. """
ndindex-1.2
ndindex-1.2//versioneer.pyfile:/versioneer.py:function:render_git_describe/render_git_describe
def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces['closest-tag']: rendered = pieces['closest-tag'] if pieces['distance']: rendered += '-%d-g%s' % (pieces['distance'], pieces['short']) else: rendered = pieces['short'] if pieces['dirty']: rendered += '-dirty' return rendered
bpy
bpy//ops/outliner.pyfile:/ops/outliner.py:function:highlight_update/highlight_update
def highlight_update(): """Update the item highlight based on the current mouse position """ pass
RSTransaction-0.2
RSTransaction-0.2//rstransaction/transaction_processor.pyclass:TransactionalActionBase/process_action
@staticmethod def process_action(*args, **kwargs): """ This static method receives preprocessed arguments in input, and shall perform the transactional action it represents, returning its result (if any). Any error preventing the success of this action shall simply be left propagating, so that upper level transactional structures can take measures accordingly (:meth:`rollback_action` shall not be directly called by this method). Note that the signature and return type of this method are free, as long as expected arguments match the output of the potential :meth:`preprocess_arguments` method. """ raise NotImplementedError()
pexdoc
pexdoc//compat2.pyfile:/compat2.py:function:_raise_exception/_raise_exception
def _raise_exception(exception_object): """Raise exception with short traceback.""" raise exception_object
gevent-fastcgi-1.1.0.0
gevent-fastcgi-1.1.0.0//gevent_fastcgi/interfaces.pyclass:IConnection/read_record
def read_record(): """ Receive and deserialize next record from peer. Return None if no more records available """
django_heroku_db_utils-0.1.0
django_heroku_db_utils-0.1.0//django_heroku_db_utils/django_heroku_db_utils.pyfile:/django_heroku_db_utils/django_heroku_db_utils.py:function:db_copy/db_copy
def db_copy(obj, to, *skip, **kwargs): """ Copies a model from one database into another. `obj` is the model that is going to be cloned `to` is the db definition `skip` is a list of attribtues that won't be copied `kwargs is a list of elements that will be overwritten over model data returns the copied object in `to` db """ from django.forms.models import model_to_dict from django.db.models import Model assert isinstance(obj, Model) data = model_to_dict(obj) for key in skip: if key in data: v = data.pop(key) print('Removing {}: {}'.format(key, v)) data.update(kwargs) return type(obj).objects.using(to).create(**data)
tag2network
tag2network//Network/louvain.pyfile:/Network/louvain.py:function:__neighcom/__neighcom
def __neighcom(node, graph, status): """ Compute the communities in the neighborood of node in the graph given with the decomposition node2com """ weights = {} for neighbor, datas in graph[node].items(): if neighbor != node: weight = datas.get('weight', 1) neighborcom = status.node2com[neighbor] weights[neighborcom] = weights.get(neighborcom, 0) + weight return weights
MAVProxy-1.8.19
MAVProxy-1.8.19//MAVProxy/modules/mavproxy_map/mp_slipmap_util.pyfile:/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py:function:image_shape/image_shape
def image_shape(img): """handle different image formats, returning (width,height) tuple""" if hasattr(img, 'shape'): return img.shape[1], img.shape[0] return img.width, img.height
mimic-2.2.0
mimic-2.2.0//mimic/canned_responses/auth.pyfile:/mimic/canned_responses/auth.py:function:get_endpoints/get_endpoints
def get_endpoints(tenant_id, entry_generator, prefix_for_endpoint): """ Canned response for Identity's get endpoints call. This returns endpoints only for the services implemented by Mimic. :param entry_generator: A callable, like :func:`canned_entries`, which takes a datetime and returns an iterable of Entry. """ result = [] for entry in entry_generator(tenant_id): for endpoint in entry.endpoints: result.append({'region': endpoint.region, 'tenantId': endpoint. tenant_id, 'internalURL': endpoint.url_with_prefix( prefix_for_endpoint(endpoint), internal_url=True), 'publicURL': endpoint.url_with_prefix(prefix_for_endpoint( endpoint)), 'name': entry.name, 'type': entry.type, 'id': endpoint.endpoint_id}) return {'endpoints': result}
Specter-0.6.1
Specter-0.6.1//specter/spec.pyfile:/specter/spec.py:function:fixture/fixture
def fixture(cls): """ A simple decorator to set the fixture flag on the class.""" setattr(cls, '__FIXTURE__', True) return cls
EtherollApp-2020.322
EtherollApp-2020.322//src/etherollapp/service/main.pyclass:EtherollApp/get_files_dir
@staticmethod def get_files_dir(): """ Alternative App._get_user_data_dir() implementation for Android that also works when within a service activity. """ from jnius import autoclass, cast PythonActivity = autoclass('org.kivy.android.PythonActivity') activity = PythonActivity.mActivity if activity is None: PythonService = autoclass('org.kivy.android.PythonService') activity = PythonService.mService context = cast('android.content.Context', activity) file_p = cast('java.io.File', context.getFilesDir()) data_dir = file_p.getAbsolutePath() return data_dir
malaya-gpu-3.4.2
malaya-gpu-3.4.2//malaya/dependency.pyfile:/malaya/dependency.py:function:describe/describe
def describe(): """ Describe Dependency supported. """ print('acl - clausal modifier of noun') print('advcl - adverbial clause modifier') print('advmod - adverbial modifier') print('amod - adjectival modifier') print('appos - appositional modifier') print('aux - auxiliary') print('case - case marking') print('ccomp - clausal complement') print('compound - compound') print('compound:plur - plural compound') print('conj - conjunct') print('cop - cop') print('csubj - clausal subject') print('dep - dependent') print('det - determiner') print('fixed - multi-word expression') print('flat - name') print('iobj - indirect object') print('mark - marker') print('nmod - nominal modifier') print('nsubj - nominal subject') print('obj - direct object') print('parataxis - parataxis') print('root - root') print('xcomp - open clausal complement') print( 'you can read more from https://universaldependencies.org/treebanks/id_pud/index.html' )
mps_youtube
mps_youtube//util.pyfile:/util.py:function:get_near_name/get_near_name
def get_near_name(begin, items): """ Return the closest matching playlist name that starts with begin. """ for name in sorted(items): if name.lower().startswith(begin.lower()): return name return begin
zope
zope//intid/interfaces.pyclass:IIntIdsSet/unregister
def unregister(ob): """Remove the object from the indexes. IntIdMissingError is raised if ob is not registered previously. """
mq_client_abstraction-0.0.36
mq_client_abstraction-0.0.36//versioneer.pyfile:/versioneer.py:function:render_git_describe_long/render_git_describe_long
def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces['closest-tag']: rendered = pieces['closest-tag'] rendered += '-%d-g%s' % (pieces['distance'], pieces['short']) else: rendered = pieces['short'] if pieces['dirty']: rendered += '-dirty' return rendered
pytzer
pytzer//parameters.pyfile:/parameters.py:function:lambd_CO2_H_HMW84/lambd_CO2_H_HMW84
def lambd_CO2_H_HMW84(T, P): """n-c: carbon-dioxide hydrogen [HMW84].""" lambd = 0.0 valid = T == 298.15 return lambd, valid
fake-bpy-module-2.80-20200428
fake-bpy-module-2.80-20200428//bpy/ops/sculpt.pyfile:/bpy/ops/sculpt.py:function:sculptmode_toggle/sculptmode_toggle
def sculptmode_toggle(): """Toggle sculpt mode in 3D view """ pass
boa
boa//builtins.pyfile:/builtins.py:function:take/take
def take(source, count): """ take(source, count) -> list object Return a subset of a string or list `source`, starting at index 0 and of length `count` """ pass
invenio_oauthclient
invenio_oauthclient//contrib/cern.pyfile:/contrib/cern.py:function:fetch_extra_data/fetch_extra_data
def fetch_extra_data(resource): """Return a dict with extra data retrieved from cern oauth.""" person_id = resource.get('PersonID', [None])[0] identity_class = resource.get('IdentityClass', [None])[0] department = resource.get('Department', [None])[0] return dict(person_id=person_id, identity_class=identity_class, department=department)
openabm-1.0.12
openabm-1.0.12//openabm/examples/conways_game_of_life/conways_game_of_life/portrayal.pyfile:/openabm/examples/conways_game_of_life/conways_game_of_life/portrayal.py:function:portrayCell/portrayCell
def portrayCell(cell): """ This function is registered with the visualization server to be called each tick to indicate how to draw the cell in its current state. :param cell: the cell in the simulation :return: the portrayal dictionary. """ assert cell is not None return {'Shape': 'rect', 'w': 1, 'h': 1, 'Filled': 'true', 'Layer': 0, 'x': cell.x, 'y': cell.y, 'Color': 'black' if cell.isAlive else 'white' }
pydarn
pydarn//io/borealis/borealis_formats.pyclass:BorealisRawrf/site_fields
@classmethod def site_fields(cls): """ All site fields """ return cls.shared_fields + cls.unshared_fields + cls.site_only_fields
monero-serialize-3.0.1
monero-serialize-3.0.1//monero_serialize/core/int_serialize.pyfile:/monero_serialize/core/int_serialize.py:function:load_uvarint_b/load_uvarint_b
def load_uvarint_b(buffer): """ Variable int deserialization, synchronous from buffer. :param buffer: :return: """ result = 0 idx = 0 byte = 128 while byte & 128: byte = buffer[idx] result += (byte & 127) << 7 * idx idx += 1 return result
tiquations
tiquations//equations.pyfile:/equations.py:function:coefficient_cfn/coefficient_cfn
def coefficient_cfn(friction, normal): """Usage: Find coefficient with friction and normal force""" return friction / normal
GSAS-II-WONDER_win-1.0.1
GSAS-II-WONDER_win-1.0.1//GSAS-II-WONDER/GSASIImath.pyfile:/GSAS-II-WONDER/GSASIImath.py:function:getTOFalphaDeriv/getTOFalphaDeriv
def getTOFalphaDeriv(dsp): """get derivatives of TOF peak profile beta wrt alpha :param float dsp: d-spacing of peak :returns: float getTOFalphaDeriv: d(alp)/d(alpha) """ return 1.0 / dsp
dynamo3-0.4.10
dynamo3-0.4.10//dynamo3/fields.pyclass:IndexUpdate/create
@classmethod def create(cls, index): """ Create a new index """ return cls('Create', None, index=index)
bpy
bpy//ops/nla.pyfile:/ops/nla.py:function:soundclip_add/soundclip_add
def soundclip_add(): """Add a strip for controlling when speaker plays its sound clip """ pass
rich_base_provider-1.0.1
rich_base_provider-1.0.1//rich_base_provider/sysadmin/recharge/balance_recharge_record/models.pyclass:BalanceRechargeRecord/get_recharge_record_by_data
@classmethod def get_recharge_record_by_data(cls, recharge_object_code_list, recharge_rule_id_list): """ 根据充值对象编号列表、充值方案ID 获取本充值对象适用此类充值方案的充值记录(返回值 所用充值方案ID) :param recharge_object_code_list: :param recharge_rule_id_list: :return: """ return cls.objects(recharge_object_code__in=recharge_object_code_list, recharge_status__in=[cls.get_dict_id('balance_recharge_status', '充值成功')], recharge_rule_id__in=recharge_rule_id_list).only( 'recharge_rule_id').all()
anymail
anymail//webhooks/mailjet.pyclass:MailjetInboundWebhookView/_flatten_mailjet_headers
@staticmethod def _flatten_mailjet_headers(headers): """Convert Mailjet's dict-of-strings-and/or-lists header format to our list-of-name-value-pairs {'name1': 'value', 'name2': ['value1', 'value2']} --> [('name1', 'value'), ('name2', 'value1'), ('name2', 'value2')] """ result = [] for name, values in headers.items(): if isinstance(values, list): for value in values: result.append((name, value)) else: result.append((name, values)) return result
zope.locking-2.1.0
zope.locking-2.1.0//src/zope/locking/interfaces.pyclass:ITokenBroker/lockShared
def lockShared(principal_ids=None, duration=None): """lock context with a shared lock, and return token. if principal_ids is None, use interaction's principals; if interaction does not have any principals, raise ValueError. if principal_ids is not None, principal_ids must be in interaction, or else raise ParticipationError. Must be at least one id. Same constraints as token utility's register method. """
cfgen
cfgen//cfgen.pyfile:/cfgen.py:function:get_string/get_string
def get_string(value): """ Returns string representation of the value or empty string if None """ if value: return str(value) else: return ''
jasmin_cis-1.0.0
jasmin_cis-1.0.0//jasmin_cis/utils.pyfile:/jasmin_cis/utils.py:function:listify/listify
def listify(item): """ If item is not a list, return it as a list :param item: Item which may or may not be a list :return: List """ if not isinstance(item, list): return [item] return item
flowserv-core-0.1.1
flowserv-core-0.1.1//flowserv/model/ranking/manager.pyfile:/flowserv/model/ranking/manager.py:function:RESULT_TABLE/RESULT_TABLE
def RESULT_TABLE(workflow_id): """Get default result table name for the workflow with the given identifier. It is assumed that the identifier is a UUID that only contains letters and digits and no white space or special characters. Parameters ---------- workflow_id: string Unique workflow identifier Returns ------- string """ return 'res_{}'.format(workflow_id)
crossroad-0.8.0
crossroad-0.8.0//platforms/modules/android-arm.pyfile:/platforms/modules/android-arm.py:function:prepare/prepare
def prepare(prefix): """ Prepare the environment. """ return True
swift-2.25.0
swift-2.25.0//swift/common/utils.pyfile:/swift/common/utils.py:function:config_fallocate_value/config_fallocate_value
def config_fallocate_value(reserve_value): """ Returns fallocate reserve_value as an int or float. Returns is_percent as a boolean. Returns a ValueError on invalid fallocate value. """ try: if str(reserve_value[-1:]) == '%': reserve_value = float(reserve_value[:-1]) is_percent = True else: reserve_value = int(reserve_value) is_percent = False except ValueError: raise ValueError( 'Error: %s is an invalid value for fallocate_reserve.' % reserve_value) return reserve_value, is_percent
jhTAlib-20200412.0
jhTAlib-20200412.0//jhtalib/pattern_recognition/pattern_recognition.pyfile:/jhtalib/pattern_recognition/pattern_recognition.py:function:CDLCONSEALBABYSWALL/CDLCONSEALBABYSWALL
def CDLCONSEALBABYSWALL(df): """ Concealing Baby Swallow """
ksr-0.1.5
ksr-0.1.5//ksr.pyfile:/ksr.py:function:smooth/smooth
def smooth(number): """Returns an integer if the float is a whole number""" return int(number) if number.is_integer() else number
pandas-gbq-0.13.1
pandas-gbq-0.13.1//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
pyannote.parser-0.8
pyannote.parser-0.8//pyannote/parser/annotation/repere.pyclass:REPEREParser/get_show_name
@staticmethod def get_show_name(uri): """Get show name from uri""" tokens = uri.split('_') channel = tokens[0] show = tokens[1] return channel + '_' + show
pathlib_mate
pathlib_mate//hashes.pyfile:/hashes.py:function:get_text_fingerprint/get_text_fingerprint
def get_text_fingerprint(text, hash_meth, encoding='utf-8'): """ Use default hash method to return hash value of a piece of string default setting use 'utf-8' encoding. """ m = hash_meth() m.update(text.encode(encoding)) return m.hexdigest()
ocrd_cis
ocrd_cis//ocropy/ocrolib/sl.pyfile:/ocropy/ocrolib/sl.py:function:dim1/dim1
def dim1(s): """Dimension of the slice list for dimension 1.""" return s[1].stop - s[1].start
lightbus
lightbus//message.pyclass:Message/from_dict
@classmethod def from_dict(cls, metadata: dict, kwargs: dict, **extra) ->'Message': """Create a message instance given the metadata and kwargs Will be used by the serializers """ raise NotImplementedError()
reportgen-0.1.8
reportgen-0.1.8//reportgen/associate/fpgrowth.pyfile:/reportgen/associate/fpgrowth.py:function:_prefix_paths/_prefix_paths
def _prefix_paths(tree, nodes): """ Generate all paths of tree leading to all item nodes """ for node in nodes: path = [] support = node.count node = node.parent while node.item is not None: path.append(node.item) node = node.parent if path: yield support, path
datarobot
datarobot//models/deployment.pyclass:Deployment/create_from_learning_model
@classmethod def create_from_learning_model(cls, model_id, label, description=None, default_prediction_server_id=None): """Create a deployment from a DataRobot model. .. versionadded:: v2.17 Parameters ---------- model_id : str id of the DataRobot model to deploy label : str a human readable label of the deployment description : str, optional a human readable description of the deployment default_prediction_server_id : str an identifier of a prediction server to be used as the default prediction server Returns ------- deployment : Deployment The created deployment Examples -------- .. code-block:: python from datarobot import Project, Deployment project = Project.get('5506fcd38bd88f5953219da0') model = project.get_models()[0] deployment = Deployment.create_from_learning_model(model.id, 'New Deployment') deployment >>> Deployment('New Deployment') """ payload = {'model_id': model_id, 'label': label, 'description': description } if default_prediction_server_id: payload['default_prediction_server_id'] = default_prediction_server_id url = '{}fromLearningModel/'.format(cls._path) deployment_id = cls._client.post(url, data=payload).json()['id'] return cls.get(deployment_id)
Mormon-0.2.4
Mormon-0.2.4//mormon/mormon.pyclass:MObject/find
@classmethod def find(cls, query, **kwargs): """ Query MongoDB to find multiple objects. :param dict query: a MongoDB query :rtype: :class:`~mormon.mormon.MCursor` OR None """ return cls._find(query, **kwargs)
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/batch.pyfile:/pyboto3/batch.py:function:create_job_queue/create_job_queue
def create_job_queue(jobQueueName=None, state=None, priority=None, computeEnvironmentOrder=None): """ Creates an AWS Batch job queue. When you create a job queue, you associate one or more compute environments to the queue and assign an order of preference for the compute environments. You also set a priority to the job queue that determines the order in which the AWS Batch scheduler places jobs onto its associated compute environments. For example, if a compute environment is associated with more than one job queue, the job queue with a higher priority is given preference for scheduling jobs to that compute environment. See also: AWS API Documentation Examples This example creates a job queue called LowPriority that uses the M4Spot compute environment. Expected Output: This example creates a job queue called HighPriority that uses the C4OnDemand compute environment with an order of 1 and the M4Spot compute environment with an order of 2. Expected Output: :example: response = client.create_job_queue( jobQueueName='string', state='ENABLED'|'DISABLED', priority=123, computeEnvironmentOrder=[ { 'order': 123, 'computeEnvironment': 'string' }, ] ) :type jobQueueName: string :param jobQueueName: [REQUIRED] The name of the job queue. :type state: string :param state: The state of the job queue. If the job queue state is ENABLED , it is able to accept jobs. :type priority: integer :param priority: [REQUIRED] The priority of the job queue. Job queues with a higher priority (or a lower integer value for the priority parameter) are evaluated first when associated with same compute environment. Priority is determined in ascending order, for example, a job queue with a priority value of 1 is given scheduling preference over a job queue with a priority value of 10 . :type computeEnvironmentOrder: list :param computeEnvironmentOrder: [REQUIRED] The set of compute environments mapped to a job queue and their order relative to each other. The job scheduler uses this parameter to determine which compute environment should execute a given job. Compute environments must be in the VALID state before you can associate them with a job queue. You can associate up to 3 compute environments with a job queue. (dict) --The order in which compute environments are tried for job placement within a queue. Compute environments are tried in ascending order. For example, if two compute environments are associated with a job queue, the compute environment with a lower order integer value is tried for job placement first. order (integer) -- [REQUIRED]The order of the compute environment. computeEnvironment (string) -- [REQUIRED]The Amazon Resource Name (ARN) of the compute environment. :rtype: dict :return: { 'jobQueueName': 'string', 'jobQueueArn': 'string' } """ pass
khmer
khmer//utils.pyfile:/utils.py:function:_split_left_right/_split_left_right
def _split_left_right(name): """Split record name at the first whitespace and return both parts. RHS is set to an empty string if not present. """ parts = name.split(None, 1) lhs, rhs = [parts[0], parts[1] if len(parts) > 1 else ''] return lhs, rhs
amphivena-0.1.dev2
amphivena-0.1.dev2//astropy_helpers/astropy_helpers/distutils_helpers.pyfile:/astropy_helpers/astropy_helpers/distutils_helpers.py:function:get_main_package_directory/get_main_package_directory
def get_main_package_directory(distribution): """ Given a Distribution object, return the main package directory. """ return min(distribution.packages, key=len)
apache-superset-078-0.35.2
apache-superset-078-0.35.2//superset/db_engine_specs/base.pyclass:BaseEngineSpec/adjust_database_uri
@classmethod def adjust_database_uri(cls, uri, selected_schema: str): """Based on a URI and selected schema, return a new URI The URI here represents the URI as entered when saving the database, ``selected_schema`` is the schema currently active presumably in the SQL Lab dropdown. Based on that, for some database engine, we can return a new altered URI that connects straight to the active schema, meaning the users won't have to prefix the object names by the schema name. Some databases engines have 2 level of namespacing: database and schema (postgres, oracle, mssql, ...) For those it's probably better to not alter the database component of the URI with the schema name, it won't work. Some database drivers like presto accept '{catalog}/{schema}' in the database component of the URL, that can be handled here. """ return uri
marxs-1.1
marxs-1.1//marxs/visualization/utils.pyfile:/marxs/visualization/utils.py:function:get_obj_name/get_obj_name
def get_obj_name(obj): """Return printable name for objects or functions.""" if hasattr(obj, 'name'): return obj.name elif hasattr(obj, 'func_name'): return obj.func_name else: return str(obj)
handprint-1.2.2
handprint-1.2.2//handprint/images.pyfile:/handprint/images.py:function:canonical_format_name/canonical_format_name
def canonical_format_name(format): """Convert format name "format" to a consistent version.""" format = format.lower() if format in ['jpg', 'jpeg']: return 'jpeg' elif format in ['tiff', 'tif']: return 'tiff' else: return format
guildai-0.6.6.data
guildai-0.6.6.data//purelib/guild/external/psutil/_common.pyfile:/purelib/guild/external/psutil/_common.py:function:usage_percent/usage_percent
def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = used / total * 100 except ZeroDivisionError: ret = 0.0 if isinstance(used, float) or isinstance(total, float) else 0 if round_ is not None: return round(ret, round_) else: return ret
pyocd-0.26.0
pyocd-0.26.0//pyocd/utility/hex.pyfile:/pyocd/utility/hex.py:function:format_hex_width/format_hex_width
def format_hex_width(value, width): """! @brief Formats the value as hex of the specified bit width. @param value Integer value to be formatted. @param width Bit width, must be one of 8, 16, 32, 64. @return String with (width / 8) hex digits. Does not have a "0x" prefix. """ if width == 8: return '%02x' % value elif width == 16: return '%04x' % value elif width == 32: return '%08x' % value elif width == 64: return '%016x' % value else: raise ValueError('unrecognized register width (%d)' % width)
aethos-1.2.5
aethos-1.2.5//aethos/cleaning/util.pyfile:/aethos/cleaning/util.py:function:remove_duplicate_columns/remove_duplicate_columns
def remove_duplicate_columns(x_train, x_test=None): """ Removes columns whose values are exact duplicates of each other. Parameters ---------- x_train: Dataframe or array like - 2d Dataset. x_test: Dataframe or array like - 2d Testing dataset, by default None. Returns ------- Dataframe, *Dataframe Transformed dataframe with rows with a missing values in a specific row are missing Returns 2 Dataframes if x_test is provided. """ x_train = x_train.T.drop_duplicates().T if x_test is not None: x_test = x_test.T.drop_duplicates().T return x_train, x_test
thug-1.6.1
thug-1.6.1//thug/Plugins/IPlugin.pyclass:IPlugin/run
def run(thug, log): """ This method is called when the plugin is invoked Parameters: @thug: Thug class main instance @log: Thug root logger """ pass