repo
stringlengths
1
29
path
stringlengths
24
332
code
stringlengths
39
579k
RelStorage-3.0.1
RelStorage-3.0.1//src/relstorage/cache/interfaces.pyclass:ILRUCache/__setitem__
def __setitem__(key, value): """ Either set or update an entry. If the key already existed in the cache, then update its ``value`` to the new *value* and mark it as the most recently used. Otherwise, create a new entry for the key, setting it to the most recently used. This may evict other items. """
Electrum-CHI-3.3.8
Electrum-CHI-3.3.8//electrum_chi/electrum/util.pyfile:/electrum_chi/electrum/util.py:function:assert_str/assert_str
def assert_str(*args): """ porting helper, assert args type """ for x in args: assert isinstance(x, str)
adles
adles//interfaces/interface.pyclass:Interface/_is_enabled
@staticmethod def _is_enabled(spec): """ Determines if a spec is enabled. :param dict spec: Specification to check :return: If the spec is enabled :rtype: bool """ if 'enabled' in spec: return bool(spec['enabled']) else: return True
soprano
soprano//utils.pyfile:/utils.py:function:progbar/progbar
def progbar(i, i_max, bar_len=20, spinner=True, spin_rate=3.0): """A textual progress bar for the command line | Args: | i (int): current progress index | max_i (int): final progress index | bar_len (Optional[int]): length in characters of the bar (no brackets) | spinner (Optional[bool]): show a spinner at the end | spin_rate (Optional[float]): spinner rotation speed (turns per full | progress) | Returns: | bar (str): a progress bar formatted as requested """ block = {(True): '█', (False): ' '} spin = '|\\-/' perc = i / float(i_max) * bar_len bar = '[{0}]'.format(''.join([block[i < perc] for i in range(bar_len)])) if spinner: bar += ' {0}'.format(spin[int(perc * spin_rate) % len(spin)]) return bar
simplegmail
simplegmail//query.pyfile:/query.py:function:_near_words/_near_words
def _near_words(first, second, distance, exact=False): """ Returns a query item matching messages that two words within a certain distance of each other. Args: first (str): The first word to search for. second (str): The second word to search for. distance (int): How many words apart first and second can be. exact (bool): Whether first must come before second [default False]. Returns: The query string. """ query = f'{first} AROUND {distance} {second}' if exact: query = '"' + query + '"' return query
fake-bpy-module-2.80-20200428
fake-bpy-module-2.80-20200428//bpy/ops/mesh.pyfile:/bpy/ops/mesh.py:function:faces_shade_smooth/faces_shade_smooth
def faces_shade_smooth(): """Display faces smooth (using vertex normals) """ pass
freegames-2.3.2
freegames-2.3.2//freegames/crypto.pyfile:/freegames/crypto.py:function:get_key/get_key
def get_key(): """Get key from user.""" try: text = input('Enter a key (1 - 25): ') key = int(text) return key except: print('Invalid key. Using key: 0.') return 0
fake-bpy-module-2.80-20200428
fake-bpy-module-2.80-20200428//bpy/ops/wm.pyfile:/bpy/ops/wm.py:function:keyconfig_preset_add/keyconfig_preset_add
def keyconfig_preset_add(name: str='', remove_name: bool=False, remove_active: bool=False): """Add or remove a Key-config Preset :param name: Name, Name of the preset, used to make the path name :type name: str :param remove_name: remove_name :type remove_name: bool :param remove_active: remove_active :type remove_active: bool """ pass
newcli
newcli//core.pyfile:/core.py:function:create_github_repo/create_github_repo
def create_github_repo(config, push=True): """If in new project directory, begin clone and push to GitHub.""" pass
cnfconverter-1.1.1
cnfconverter-1.1.1//cnf/cnfconverter.pyfile:/cnf/cnfconverter.py:function:t_Predicate/t_Predicate
def t_Predicate(t): """[A-Z][a-zA-Z]*\\(.+?\\)""" return t
contenttypes.basic-1.6.2
contenttypes.basic-1.6.2//src/contenttypes/basic/setuphandlers.pyfile:/src/contenttypes/basic/setuphandlers.py:function:coordinates_controlpanel_install/coordinates_controlpanel_install
def coordinates_controlpanel_install(context): """Coordinates controlpanel script"""
bpy
bpy//ops/sequencer.pyfile:/ops/sequencer.py:function:paste/paste
def paste(): """Paste strips from clipboard """ pass
pystock-crawler-0.8.2
pystock-crawler-0.8.2//pystock_crawler/loaders.pyfile:/pystock_crawler/loaders.py:function:memberness/memberness
def memberness(context): """The likelihood that the context is a "member".""" if context: texts = context.xpath('.//*[local-name()="explicitMember"]/text()' ).extract() text = str(texts).lower() if len(texts) > 1: return 2 elif 'country' in text: return 2 elif 'member' not in text: return 0 elif 'successor' in text: return 1 elif 'parent' in text: return 2 return 3
ema_workbench-2.0.8
ema_workbench-2.0.8//ema_workbench/connectors/vensimDLLwrapper.pyfile:/ema_workbench/connectors/vensimDLLwrapper.py:function:synthesim_vals/synthesim_vals
def synthesim_vals(offset, tval, varval): """ This is a specialized function that uses memory managed by Vensim to give access to values while SyntheSim is active. currently not implemented """ raise NotImplementedError
neural_structured_learning
neural_structured_learning//tools/graph_utils.pyfile:/tools/graph_utils.py:function:add_edge/add_edge
def add_edge(graph, edge): """Adds an edge to a given graph. If an edge between the two nodes already exists, the one with the largest weight is retained. Args: graph: A `dict`: source_id -> (target_id -> weight) to be augmented. edge: A `list` (or `tuple`) of the form `[source, target, weight]`, where `source` and `target` are strings, and `weight` is a numeric value of type `string` or `float`. The 'weight' component is optional; if not supplied, it defaults to 1.0. Returns: `None`. Instead, this function has a side-effect on the `graph` argument. """ source = edge[0] if source not in graph: graph[source] = {} t_dict = graph[source] target = edge[1] weight = float(edge[2]) if len(edge) > 2 else 1.0 if target not in t_dict or weight > t_dict[target]: t_dict[target] = weight
zerotk.easyfs-1.0.3
zerotk.easyfs-1.0.3//zerotk/easyfs/_easyfs.pyfile:/zerotk/easyfs/_easyfs.py:function:_CallWindowsNetCommand/_CallWindowsNetCommand
def _CallWindowsNetCommand(parameters): """ Call Windows NET command, used to acquire/configure network services settings. :param parameters: list of command line parameters :return: command output """ import subprocess popen = subprocess.Popen(['net'] + parameters, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdoutdata, stderrdata = popen.communicate() if stderrdata: raise OSError('Failed on call net.exe: %s' % stderrdata) return stdoutdata
python-docx-docm-0.1.0
python-docx-docm-0.1.0//docx/oxml/text/run.pyclass:_RunContentAppender/append_to_run_from_text
@classmethod def append_to_run_from_text(cls, r, text): """ Create a "one-shot" ``_RunContentAppender`` instance and use it to append the run content elements corresponding to *text* to the ``<w:r>`` element *r*. """ appender = cls(r) appender.add_text(text)
opentimestamps-0.4.1
opentimestamps-0.4.1//opentimestamps/core/notary.pyclass:PendingAttestation/check_uri
@classmethod def check_uri(cls, uri): """Check URI for validity Raises ValueError appropriately """ if len(uri) > cls.MAX_URI_LENGTH: raise ValueError('URI exceeds maximum length') for char in uri: if char not in cls.ALLOWED_URI_CHARS: raise ValueError('URI contains invalid character %r' % bytes([ char]))
oolearning-0.3.4
oolearning-0.3.4//oolearning/model_wrappers/LinearRegressor.pyclass:LinearRegressor/_get_significance_code
@staticmethod def _get_significance_code(p_value): """ Significance codes: ‘***’ if <= 0.001 ‘**’ if <= 0.01 ‘*’ if <= 0.05 ‘.’ if <= 0.1 else ‘ ’ :param p_value: p-value to convert :return: code """ if p_value <= 0.001: return '***' elif p_value <= 0.01: return '**' elif p_value <= 0.05: return '*' elif p_value <= 0.1: return '.' else: return ''
dsplab-0.38.1
dsplab-0.38.1//dsplab/modulation.pyfile:/dsplab/modulation.py:function:freq_by_extremums/freq_by_extremums
def freq_by_extremums(xdata, sample_rate): """ Calculate frequency of oscillating signal by extremums. Parameters ---------- xdata: array_like Values of input signals. sample_rate: float Sampling frequency (Hz). Returns ------- : float Frequency. """ T = len(xdata) / sample_rate n_max = 0 n_min = 0 for x_p, x_c, x_n in zip(xdata[:-2], xdata[1:-1], xdata[2:]): if x_p < x_c and x_c >= x_n: n_max += 1 if x_p > x_c and x_c <= x_n: n_min += 1 n = (n_max + n_min) / 2 return n / T
torsiondrive-0.9.8.1
torsiondrive-0.9.8.1//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
pycorrelate-0.3
pycorrelate-0.3//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 '+'
dropbox
dropbox//team_log.pyclass:EventType/domain_verification_add_domain_success
@classmethod def domain_verification_add_domain_success(cls, val): """ Create an instance of this class set to the ``domain_verification_add_domain_success`` tag with value ``val``. :param DomainVerificationAddDomainSuccessType val: :rtype: EventType """ return cls('domain_verification_add_domain_success', val)
z2pack-2.1.1
z2pack-2.1.1//z2pack/_utils.pyfile:/z2pack/_utils.py:function:_gapfind/_gapfind
def _gapfind(wcc): """ finds the largest gap in vector wcc, modulo 1 """ wcc = sorted(wcc) gapsize = 0 gappos = 0 N = len(wcc) for i, (w1, w2) in enumerate(zip(wcc, wcc[1:])): temp = w2 - w1 if temp > gapsize: gapsize = temp gappos = i temp = wcc[0] - wcc[-1] + 1 if temp > gapsize: gapsize = temp gappos = N - 1 return (wcc[gappos] + gapsize / 2) % 1, gapsize
acli-0.1.34
acli-0.1.34//lib/acli/output/ec2.pyfile:/lib/acli/output/ec2.py:function:short_instance_profile/short_instance_profile
def short_instance_profile(instance_profile=None): """ @type instance_profile: dict """ if instance_profile and instance_profile.get('Arn'): return instance_profile.get('Arn')
scrapy-redis-cluster-0.5
scrapy-redis-cluster-0.5//scrapy_redis_cluster/dupefilter.pyclass:RFPDupeFilter/from_crawler
@classmethod def from_crawler(cls, crawler): """Returns instance from crawler. Parameters ---------- crawler : scrapy.crawler.Crawler Returns ------- RFPDupeFilter Instance of RFPDupeFilter. """ return cls.from_settings(crawler.settings)
pyatv-0.6.1
pyatv-0.6.1//pyatv/mrp/variant.pyfile:/pyatv/mrp/variant.py:function:read_variant/read_variant
def read_variant(variant): """Read and parse a binary protobuf variant value.""" result = 0 cnt = 0 for data in variant: result |= (data & 127) << 7 * cnt cnt += 1 if not data & 128: return result, variant[cnt:] raise Exception('invalid variant')
docx
docx//image/png.pyclass:_Chunk/from_offset
@classmethod def from_offset(cls, chunk_type, stream_rdr, offset): """ Return a default _Chunk instance that only knows its chunk type. """ return cls(chunk_type)
passa
passa//_pip.pyfile:/_pip.py:function:_convert_hashes/_convert_hashes
def _convert_hashes(values): """Convert Pipfile.lock hash lines into InstallRequirement option format. The option format uses a str-list mapping. Keys are hash algorithms, and the list contains all values of that algorithm. """ hashes = {} if not values: return hashes for value in values: try: name, value = value.split(':', 1) except ValueError: name = 'sha256' if name not in hashes: hashes[name] = [] hashes[name].append(value) return hashes
zope.keyreference-4.2.0
zope.keyreference-4.2.0//src/zope/keyreference/interfaces.pyclass:IKeyReference/__eq__
def __eq__(ref): """KeyReferences must be totally orderable."""
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/ec2.pyfile:/pyboto3/ec2.py:function:enable_volume_io/enable_volume_io
def enable_volume_io(DryRun=None, VolumeId=None): """ Enables I/O operations for a volume that had I/O operations disabled because the data on the volume was potentially inconsistent. See also: AWS API Documentation Examples This example enables I/O on volume vol-1234567890abcdef0. Expected Output: :example: response = client.enable_volume_io( DryRun=True|False, VolumeId='string' ) :type DryRun: boolean :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . :type VolumeId: string :param VolumeId: [REQUIRED] The ID of the volume. :return: response = client.enable_volume_io( VolumeId='vol-1234567890abcdef0', ) print(response) """ pass
frutils
frutils//jinja2_filters.pyfile:/jinja2_filters.py:function:string_for_boolean_filter/string_for_boolean_filter
def string_for_boolean_filter(value, true_value, false_value): """ Returns a different object depending on whether the value resolves to True or not. Test for True is simply: 'if value'. Args: value (object): the input true_value (object): the result if input is True false_value (object): the result if input is False Result: object: the result """ if value: return true_value else: return false_value
pisense
pisense//environ.pyfile:/environ.py:function:temp_average/temp_average
def temp_average(p_temp, h_temp): """ Use this function as :attr:`~SenseEnviron.temp_source` if you wish to read the average of both the pressure and humidity sensor's temperatures. """ if p_temp is None: return h_temp elif h_temp is None: return p_temp else: return (p_temp + h_temp) / 2
dgl-0.4.3.post2.data
dgl-0.4.3.post2.data//purelib/dgl/backend/backend.pyfile:/purelib/dgl/backend/backend.py:function:arange/arange
def arange(start, stop): """Create a 1D range int64 tensor. Parameters ---------- start : int The range start. stop : int The range stop. Returns ------- Tensor The result tensor. """ pass
thomas
thomas//core/cpt.pyclass:CPT/_short_query_str
@classmethod def _short_query_str(cls, sep1, sep2, conditioned, conditioning): """Return a short query string.""" conditioned = sep1.join(conditioned) conditioning = sep1.join(conditioning) if conditioning: return f'{conditioned}{sep2}{conditioning}' return f'{conditioned}'
autobahn
autobahn//websocket/compress_snappy.pyclass:PerMessageSnappyOffer/parse
@classmethod def parse(cls, params): """ Parses a WebSocket extension offer for `permessage-snappy` provided by a client to a server. :param params: Output from :func:`autobahn.websocket.WebSocketProtocol._parseExtensionsHeader`. :type params: list :returns: A new instance of :class:`autobahn.compress.PerMessageSnappyOffer`. :rtype: obj """ accept_no_context_takeover = False request_no_context_takeover = False for p in params: if len(params[p]) > 1: raise Exception( "multiple occurrence of extension parameter '%s' for extension '%s'" % (p, cls.EXTENSION_NAME)) val = params[p][0] if p == 'client_no_context_takeover': if val is not True: raise Exception( "illegal extension parameter value '%s' for parameter '%s' of extension '%s'" % (val, p, cls.EXTENSION_NAME)) else: accept_no_context_takeover = True elif p == 'server_no_context_takeover': if val is not True: raise Exception( "illegal extension parameter value '%s' for parameter '%s' of extension '%s'" % (val, p, cls.EXTENSION_NAME)) else: request_no_context_takeover = True else: raise Exception( "illegal extension parameter '%s' for extension '%s'" % (p, cls.EXTENSION_NAME)) offer = cls(accept_no_context_takeover, request_no_context_takeover) return offer
_CAL
_CAL//Ordinal.pyclass:Year/to_year
@classmethod def to_year(cls, yo): """Return date corresponding to year ordinal `yo`.""" return yo
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/codebuild.pyfile:/pyboto3/codebuild.py:function:list_builds_for_project/list_builds_for_project
def list_builds_for_project(projectName=None, sortOrder=None, nextToken=None): """ Gets a list of build IDs for the specified build project, with each build ID representing a single build. See also: AWS API Documentation :example: response = client.list_builds_for_project( projectName='string', sortOrder='ASCENDING'|'DESCENDING', nextToken='string' ) :type projectName: string :param projectName: [REQUIRED] The name of the build project. :type sortOrder: string :param sortOrder: The order to list build IDs. Valid values include: ASCENDING : List the build IDs in ascending order by build ID. DESCENDING : List the build IDs in descending order by build ID. :type nextToken: string :param nextToken: During a previous call, if there are more than 100 items in the list, only the first 100 items are returned, along with a unique string called a next token . To get the next batch of items in the list, call this operation again, adding the next token to the call. To get all of the items in the list, keep calling this operation with each subsequent next token that is returned, until no more next tokens are returned. :rtype: dict :return: { 'ids': [ 'string', ], 'nextToken': 'string' } :returns: (string) -- """ pass
chevah
chevah//compat/interfaces.pyclass:ILocalFilesystem/getSegments
def getSegments(path): """ Return the segments from the root path to the passed `path`. `path` is a ChevahPath and can be a relative path of the home folder. """
dropbox
dropbox//sharing.pyclass:ListFileMembersIndividualResult/access_error
@classmethod def access_error(cls, val): """ Create an instance of this class set to the ``access_error`` tag with value ``val``. :param SharingFileAccessError val: :rtype: ListFileMembersIndividualResult """ return cls('access_error', val)
zope.i18n-4.7.0
zope.i18n-4.7.0//src/zope/i18n/interfaces/locales.pyclass:ILocaleCalendar/getDayAbbr
def getDayAbbr(): """Return a list of weekday abbreviations."""
dogpile.cache-0.9.2
dogpile.cache-0.9.2//dogpile/util/langhelpers.pyfile:/dogpile/util/langhelpers.py:function:to_list/to_list
def to_list(x, default=None): """Coerce to a list.""" if x is None: return default if not isinstance(x, (list, tuple)): return [x] else: return x
plasma
plasma//enum.pyclass:EnumMeta/__call__
def __call__(cls, value, names=None, *, module=None, qualname=None, type= None, start=1): """Either returns an existing member, or creates a new enum class. This method is used both when an enum class is given a value to match to an enumeration member (i.e. Color(3)) and for the functional API (i.e. Color = Enum('Color', names='RED GREEN BLUE')). When used for the functional API: `value` will be the name of the new class. `names` should be either a string of white-space/comma delimited names (values will start at `start`), or an iterator/mapping of name, value pairs. `module` should be set to the module this class is being created in; if it is not set, an attempt to find that module will be made, but if it fails the class will not be picklable. `qualname` should be set to the actual location this class can be found at in its module; by default it is set to the global scope. If this is not correct, unpickling will fail in some circumstances. `type`, if set, will be mixed in as the first base class. """ if names is None: return cls.__new__(cls, value) return cls._create_(value, names, module=module, qualname=qualname, type=type, start=start)
coreapidr-2.3.5
coreapidr-2.3.5//coreapidr/codecs/corejson.pyfile:/coreapidr/codecs/corejson.py:function:_unescape_key/_unescape_key
def _unescape_key(string): """ Unescape '__type' and '__meta' keys if they occur. """ if string.startswith('__') and string.lstrip('_') in ('type', 'meta'): return string[1:] return string
repoze
repoze//catalog/indexes/field.pyfile:/catalog/indexes/field.py:function:fwscan_wins/fwscan_wins
def fwscan_wins(limit, rlen, numdocs): """ Primitive curve-fitting to see if forward scan will beat both nbest and timsort for a particular limit/rlen/numdocs tuple. In sortbench tests up to 'numdocs' sizes of 65536, this curve fit had a 95%+ accuracy rate, except when 'numdocs' is < 64, then its lowest accuracy percentage was 83%. Thus, it could still use some work, but accuracy at very small index sizes is not terribly important for the author. """ docratio = rlen / float(numdocs) if limit: limitratio = limit / float(numdocs) else: limitratio = 1 div = 65536.0 if docratio >= 16384 / div: return True if docratio >= 256 / div: if 512 / div <= docratio < 1024 / div and limitratio <= 4 / div: return True elif 1024 / div <= docratio < 2048 / div and limitratio <= 32 / div: return True elif 2048 / div <= docratio < 4096 / div and limitratio <= 128 / div: return True elif 4096 / div <= docratio < 8192 / div and limitratio <= 512 / div: return True elif 8192 / div <= docratio < 16384 / div and limitratio <= 4096 / div: return True return False
descarteslabs-1.2.0
descarteslabs-1.2.0//descarteslabs/workflows/types/geospatial/imagecollection.pyclass:ImageCollection/log1p
def log1p(ic): """ Element-wise log of 1 + an `ImageCollection`. If the `ImageCollection` is empty, returns the empty `ImageCollection`. Example ------- >>> import descarteslabs.workflows as wf >>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR", ... start_datetime="2017-01-01", end_datetime="2017-05-30") >>> col.log1p().compute(geoctx) # doctest: +SKIP ImageCollectionResult of length 2: ... """ from ..math import arithmetic return arithmetic.log1p(ic)
trollflow_sat
trollflow_sat//area_gatherer.pyfile:/area_gatherer.py:function:total_seconds/total_seconds
def total_seconds(tdef): """Calculate total time in seconds. """ return (tdef.microseconds + (tdef.seconds + tdef.days * 24 * 3600) * 10 ** 6) / 10.0 ** 6
novaposhta-api-client-0.2.3
novaposhta-api-client-0.2.3//novaposhta/models.pyclass:Common/get_payment_forms
@classmethod def get_payment_forms(cls): """ Method for fetching info about possible payment forms. :example: ``Common.get_payment_forms()`` :return: dictionary with info about payment forms :rtype: dict """ return cls.send(method='getPaymentForms')
cwmud-0.4.0
cwmud-0.4.0//cwmud/core/attributes.pyclass:Attribute/validate
@classmethod def validate(cls, entity, new_value): """Validate a value for this attribute. This will be called by the blob when setting the value for this attribute, override it to perform any checks or sanitation. This should either return a valid value for the attribute or raise an exception as to why the value is invalid. :param entity: The entity this attribute is on :param new_value: The potential value to validate :returns: The validated (and optionally sanitized) value """ return new_value
BESST-2.2.8
BESST-2.2.8//BESST/libmetrics.pyfile:/BESST/libmetrics.py:function:sum_chunks/sum_chunks
def sum_chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield sum(l[i:i + n])
linodecli
linodecli//plugins/k8s-alpha.pyfile:/plugins/k8s-alpha.py:function:is_valid_master_type/is_valid_master_type
def is_valid_master_type(context, linode_type): """ Kubernetes masters must have a minimum of 2 VCPUs. """ status, result = context.client.call_operation('linodes', 'type-view', args=[linode_type]) if status != 200: raise RuntimeError( '{}: Failed to look up configured default Linode type from API' .format(str(status))) else: return result['vcpus'] >= 2
alignak-2.1.5
alignak-2.1.5//alignak/objects/serviceextinfo.pyclass:ServicesExtInfo/merge_extinfo
@staticmethod def merge_extinfo(service, extinfo): """Merge extended host information into a service :param service: the service to edit :type service: alignak.objects.service.Service :param extinfo: the external info we get data from :type extinfo: alignak.objects.serviceextinfo.ServiceExtInfo :return: None """ properties = ['notes', 'notes_url', 'icon_image', 'icon_image_alt'] for prop in properties: if getattr(service, prop) == '' and getattr(extinfo, prop) != '': setattr(service, prop, getattr(extinfo, prop))
pika
pika//validators.pyfile:/validators.py:function:rpc_completion_callback/rpc_completion_callback
def rpc_completion_callback(callback): """Verify callback is callable if not None :returns: boolean indicating nowait :rtype: bool :raises: TypeError """ if callback is None: return True if callable(callback): return False else: raise TypeError('completion callback must be callable if not None')
minghu6-1.5.7
minghu6-1.5.7//minghu6/security/rsa/rsa.pyfile:/minghu6/security/rsa/rsa.py:function:fast_exp_mod/fast_exp_mod
def fast_exp_mod(b, e, m): """ e = e0*(2^0) + e1*(2^1) + e2*(2^2) + ... + en * (2^n) b^e = b^(e0*(2^0) + e1*(2^1) + e2*(2^2) + ... + en * (2^n)) = b^(e0*(2^0)) * b^(e1*(2^1)) * b^(e2*(2^2)) * ... * b^(en*(2^n)) b^e mod m = ((b^(e0*(2^0)) mod m) * (b^(e1*(2^1)) mod m) * (b^(e2*(2^2)) mod m) * ... * (b^(en*(2^n)) mod m) mod m return b^e mod m """ result = 1 while e != 0: if int(e) & 1 == 1: result = result * b % m e = int(e) >> 1 b = b * b % m return result
pyshtrih-2.0.4
pyshtrih-2.0.4//pyshtrih/handlers/functions.pyfile:/pyshtrih/handlers/functions.py:function:handle_type_field/handle_type_field
def handle_type_field(arg): """ Функция обработки типа поля таблицы. """ values = {(0): int, (1): str} return values[arg]
numba-0.49.0
numba-0.49.0//numba/typed/dictobject.pyfile:/numba/typed/dictobject.py:function:new_dict/new_dict
def new_dict(key, value): """Construct a new dict. Parameters ---------- key, value : TypeRef Key type and value type of the new dict. """ return dict()
pennies-0.2.3
pennies-0.2.3//pennies/market/market.pyclass:RatesTermStructure/of_single_curve
@classmethod def of_single_curve(cls, dt_valuation, yield_curve): """Create market consisting of a single discount curve, and a valid date If forward rates are to be computed, the discount curve will be used. """ curve_map = {yield_curve.currency: {'discount': yield_curve}} return cls(dt_valuation, curve_map)
qal
qal//sql/json.pyclass:SQLJSON/json_get_allowed_value
def json_get_allowed_value(_value, _type): """Check if a value is allowed in a certain JSON node""" if _value in _type[1] or _value == '': return _value elif _value[0:8].lower() == 'varchar(' and _value[8:len(_value) - 1 ].isnumeric() and _value[len(_value) - 1] == ')': return _value else: raise Exception('json_get_allowed_value: ' + str(_value) + ' is not a valid value in a ' + _type[0])
anyblok
anyblok//declarations.pyclass:Declarations/unregister
@classmethod def unregister(cls, entry, cls_): """ Method to remove the blok from a type of declaration :param entry: declaration entry of the model where the ``cls_`` must be removed :param ``cls_``: The ``class`` object to remove from the Declaration :rtype: ``cls_`` """ declaration = cls.declaration_types[entry.__declaration_type__] declaration.unregister(entry, cls_) return cls_
click
click//termui.pyfile:/termui.py:function:edit/edit
def edit(text=None, editor=None, env=None, require_save=True, extension= '.txt', filename=None): """Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, `None` is returned. In case a file is edited directly the return value is always `None` and `require_save` and `extension` are ignored. If the editor cannot be opened a :exc:`UsageError` is raised. Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have ``\\n`` as newline markers. :param text: the text to edit. :param editor: optionally the editor to use. Defaults to automatic detection. :param env: environment variables to forward to the editor. :param require_save: if this is true, then not saving in the editor will make the return value become `None`. :param extension: the extension to tell the editor about. This defaults to `.txt` but changing this might change syntax highlighting. :param filename: if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. """ from ._termui_impl import Editor editor = Editor(editor=editor, env=env, require_save=require_save, extension=extension) if filename is None: return editor.edit(text) editor.edit_file(filename)
Kivy-1.11.1
Kivy-1.11.1//kivy/animation.pyclass:AnimationTransition/out_expo
@staticmethod def out_expo(progress): """.. image:: images/anim_out_expo.png """ if progress == 1.0: return 1.0 return -pow(2, -10 * progress) + 1.0
hg-formatsource-0.4.0
hg-formatsource-0.4.0//hgext3rd/formatsource.pyfile:/hgext3rd/formatsource.py:function:wrap_update/wrap_update
def wrap_update(orig, repo, *args, **kwargs): """install the formatting cache""" repo._formatting_cache = {} try: return orig(repo, *args, **kwargs) finally: del repo._formatting_cache
moto
moto//dynamodb2/parsing/tokens.pyclass:ExpressionTokenizer/is_expression_attribute_name
@classmethod def is_expression_attribute_name(cls, input_string): """ https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html An expression attribute name must begin with a pound sign (#), and be followed by one or more alphanumeric characters. """ return input_string.startswith('#') and cls.is_expression_attribute( input_string[1:])
horae.planning-1.0a1
horae.planning-1.0a1//horae/planning/interfaces.pyclass:ICalculator/tickets
def tickets(resource): """ Iterator over the ordered tickets for a given resource """
cassandra
cassandra//cqltypes.pyclass:_CassandraType/to_binary
@classmethod def to_binary(cls, val, protocol_version): """ Serialize a value into a bytestring. See the serialize() method for more information. This method differs in that if None is passed in, the result is the empty string. """ return b'' if val is None else cls.serialize(val, protocol_version)
text_wargame-2.0.0
text_wargame-2.0.0//wargame/gameutils.pyfile:/wargame/gameutils.py:function:print_bold/print_bold
def print_bold(msg, end='\n'): """Convenience function to print a message in bold style Optionally you can also specify how the bold text should end. By default it ends with a new line character. :arg msg: Message to be converted to bold style :arg end: Tell how the printed string should end (newline, space etc) """ print('\x1b[1m' + msg + '\x1b[0m', end=end)
lifelib-0.0.14
lifelib-0.0.14//lifelib/projects/nestedlife/projection.pyfile:/lifelib/projects/nestedlife/projection.py:function:ReserveUernPremEnd/ReserveUernPremEnd
def ReserveUernPremEnd(t): """Unearned Premium: End of period""" return 0
alpha1p
alpha1p//robot/bthandler.pyfile:/robot/bthandler.py:function:parsing_get_action_list/parsing_get_action_list
def parsing_get_action_list(response, tips=False): """ 功能:解析动作表的返回内容,获取动作表。 输入: response:dev->pc的反应内容。 返回: cmd:解析得到的动作表,数据格式为list。 """ if response == b'': print('回应内容为空,请重新获取回应!') return poffset = 0 total_len = len(response) cmd_len = response[2] cmd_type = response[3] action_list = [] if cmd_type != 2: print('命令类型错误,请检查命令内容!当前命令类型为%d' % cmd_type) return 0 poffset = response.index(b'\xfb\xbf', poffset + 1) cmd_len = response[poffset + 2] cmd_type = response[poffset + 3] while cmd_type == 128: action_name = bytes.decode(response[poffset + 4:poffset + cmd_len - 1], encoding='gbk') action_list.append(action_name) poffset = response.index(b'\xfb\xbf', poffset + 1) cmd_len = response[poffset + 2] cmd_type = response[poffset + 3] if cmd_type != 129 or response[poffset + 4] != 0: print('获取动作表失败!请重新获取动作表,当前动作表数据最后一组命令类型为%d' % cmd_type) return 0 if tips: print('获得动作表如下:\n%s' % action_list) return action_list
collective.teamwork-0.9
collective.teamwork-0.9//collective/teamwork/user/interfaces.pyclass:ISiteMembers/refresh
def refresh(): """ Invalidate cached user list and mappings of user id to user (login) name (the latter is used as keys). """
wagtailnews-2.7.1
wagtailnews-2.7.1//wagtailnews/permissions.pyfile:/wagtailnews/permissions.py:function:format_perm/format_perm
def format_perm(model, action): """ Format a permission string "app.verb_model" for the model and the requested action (add, change, delete). """ return '{meta.app_label}.{action}_{meta.model_name}'.format(meta=model. _meta, action=action)
vispy-0.6.4
vispy-0.6.4//vispy/io/image.pyfile:/vispy/io/image.py:function:_check_img_lib/_check_img_lib
def _check_img_lib(): """Utility to search for imageio or PIL""" imageio = PIL = None try: import imageio except ImportError: try: import PIL.Image except ImportError: pass return imageio, PIL
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/iam.pyfile:/pyboto3/iam.py:function:resync_mfa_device/resync_mfa_device
def resync_mfa_device(UserName=None, SerialNumber=None, AuthenticationCode1 =None, AuthenticationCode2=None): """ Synchronizes the specified MFA device with its IAM resource object on the AWS servers. For more information about creating and working with virtual MFA devices, go to Using a Virtual MFA Device in the IAM User Guide . See also: AWS API Documentation :example: response = client.resync_mfa_device( UserName='string', SerialNumber='string', AuthenticationCode1='string', AuthenticationCode2='string' ) :type UserName: string :param UserName: [REQUIRED] The name of the user whose MFA device you want to resynchronize. 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 SerialNumber: string :param SerialNumber: [REQUIRED] Serial number that uniquely identifies the MFA device. 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 AuthenticationCode1: string :param AuthenticationCode1: [REQUIRED] An authentication code emitted by the device. The format for this parameter is a sequence of six digits. :type AuthenticationCode2: string :param AuthenticationCode2: [REQUIRED] A subsequent authentication code emitted by the device. The format for this parameter is a sequence of six digits. """ pass
a3cosmos_gas_evolution
a3cosmos_gas_evolution//Common_Python_Code/catalog_cross_matching.pyfile:/Common_Python_Code/catalog_cross_matching.py:function:search_for_matches_in_a_sorted_array/search_for_matches_in_a_sorted_array
def search_for_matches_in_a_sorted_array(input_array, match_value, start_position=0, search_direction=+1, output_allmatches=False): """ Example: xmatch2 = search_for_matches_in_a_sorted_array(array2, array1[i1], i2, -1) """ i = start_position xmatches = [] while i >= 0 and i <= len(input_array) - 1: val = input_array[i] if val == match_value: xmatches.append(i) if not output_allmatches: break elif search_direction > 0: if val > match_value: break elif search_direction < 0: if val < match_value: break i = i + search_direction return xmatches
rnaviewparser
rnaviewparser//rnaview_lex.pyfile:/rnaview_lex.py:function:t_begin_data/t_begin_data
def t_begin_data(t): """BEGIN_base-pair\\n""" t.lexer.push_state('data')
horae.auth-1.0a1
horae.auth-1.0a1//horae/auth/interfaces.pyclass:IGroupProvider/get_group
def get_group(id): """ Returns the :py:class:`IGroup` with the specified id or None """
funf
funf//__func_fibbnacci.pyfile:/__func_fibbnacci.py:function:Fibb_Store/Fibb_Store
def Fibb_Store(x, series=[1, 1]): """Optimized version for frequently used . it Generate Fibb List and Store it the fibb number range found in this then it return or it extends list """ z = len(series) if x < z: return series[x] else: for i in range(z, x): series.append(series[i - 2] + series[i - 1]) return series[x - 1]
docker-compose-xu-1.6.0dev
docker-compose-xu-1.6.0dev//compose/cli/utils.pyfile:/compose/cli/utils.py:function:yesno/yesno
def yesno(prompt, default=None): """ Prompt the user for a yes or no. Can optionally specify a default value, which will only be used if they enter a blank line. Unrecognised input (anything other than "y", "n", "yes", "no" or "") will return None. """ answer = input(prompt).strip().lower() if answer == 'y' or answer == 'yes': return True elif answer == 'n' or answer == 'no': return False elif answer == '': return default else: return None
dlgo
dlgo//gosgf/sgf_properties.pyfile:/gosgf/sgf_properties.py:function:serialise_go_point/serialise_go_point
def serialise_go_point(move, size): """Serialise a Go Point, Move, or Stone value. move -- pair (row, col), or None for a pass Returns an 8-bit string. Only supports board sizes up to 26. The move coordinates are in the GTP coordinate system (as in the rest of gomill), where (0, 0) is the lower left. """ if not 1 <= size <= 26: raise ValueError if move is None: if size <= 19: return b'tt' else: return b'' row, col = move if not (0 <= col < size and 0 <= row < size): raise ValueError col_s = 'abcdefghijklmnopqrstuvwxy'[col].encode('ascii') row_s = 'abcdefghijklmnopqrstuvwxy'[size - row - 1].encode('ascii') return col_s + row_s
ploneintranet-1.2.72
ploneintranet-1.2.72//src/ploneintranet/messaging/interfaces.pyclass:IConversation/mark_read
def mark_read(): """Mark the conversation and all contained messages as read."""
panns_inference
panns_inference//models.pyfile:/models.py:function:init_bn/init_bn
def init_bn(bn): """Initialize a Batchnorm layer. """ bn.bias.data.fill_(0.0) bn.weight.data.fill_(1.0)
pydataset-0.2.0
pydataset-0.2.0//pydataset/utils/html2text.pyfile:/pydataset/utils/html2text.py:function:google_has_height/google_has_height
def google_has_height(style): """check if the style of the element has the 'height' attribute explicitly defined""" if 'height' in style: return True return False
dgl_cu101-0.4.3.post2.data
dgl_cu101-0.4.3.post2.data//purelib/dgl/backend/backend.pyfile:/purelib/dgl/backend/backend.py:function:reshape/reshape
def reshape(input, shape): """Reshape the tensor. Parameters ---------- input : Tensor The input tensor. shape : tuple of int The new shape. Returns ------- Tensor The reshaped tensor. """ pass
ckan-2.8.4
ckan-2.8.4//ckan/controllers/group.pyclass:GroupController/add_group_type
@classmethod def add_group_type(cls, group_type): """ Notify this controller that it is to be used for a particular group_type. (Called on plugin registration.) """ cls.group_types.append(group_type)
pshtt-0.6.6
pshtt-0.6.6//pshtt/pshtt.pyfile:/pshtt/pshtt.py:function:get_domain_notes/get_domain_notes
def get_domain_notes(domain): """ Combine all domain notes if there are any. """ all_notes = (domain.http.notes + domain.httpwww.notes + domain.https. notes + domain.httpswww.notes) all_notes = all_notes.replace(',', ';') return all_notes
pdm_utils-0.3.0
pdm_utils-0.3.0//src/pdm_utils/functions/phameration.pyfile:/src/pdm_utils/functions/phameration.py:function:mmseqsdb_command/mmseqsdb_command
def mmseqsdb_command(wd): """ Builds an MMseqs2 database to use for MMseqs2 phameration :param wd: the temporary working directory for phameration :return: """ command = f'mmseqs createdb {wd}/input.fasta {wd}/sequenceDB' print('Build MMseqs2 protein database for mmseqs cluster...') return command
numpy_demo
numpy_demo//lib/_iotools.pyclass:StringConverter/upgrade_mapper
@classmethod def upgrade_mapper(cls, func, default=None): """ Upgrade the mapper of a StringConverter by adding a new function and its corresponding default. The input function (or sequence of functions) and its associated default value (if any) is inserted in penultimate position of the mapper. The corresponding type is estimated from the dtype of the default value. Parameters ---------- func : var Function, or sequence of functions Examples -------- >>> import dateutil.parser >>> import datetime >>> dateparser = dateutil.parser.parse >>> defaultdate = datetime.date(2000, 1, 1) >>> StringConverter.upgrade_mapper(dateparser, default=defaultdate) """ if hasattr(func, '__call__'): cls._mapper.insert(-1, (cls._getsubdtype(default), func, default)) return elif hasattr(func, '__iter__'): if isinstance(func[0], (tuple, list)): for _ in func: cls._mapper.insert(-1, _) return if default is None: default = [None] * len(func) else: default = list(default) default.append([None] * (len(func) - len(default))) for fct, dft in zip(func, default): cls._mapper.insert(-1, (cls._getsubdtype(dft), fct, dft))
nyx-dry-run-2.1.0
nyx-dry-run-2.1.0//nyx/panel/graph.pyfile:/nyx/panel/graph.py:function:_y_axis_labels/_y_axis_labels
def _y_axis_labels(subgraph_height, data, min_bound, max_bound): """ Provides the labels for the y-axis. This is a mapping of the position it should be drawn at to its text. """ y_axis_labels = {(2): data.y_axis_label(max_bound), (subgraph_height - 1): data.y_axis_label(min_bound)} ticks = (subgraph_height - 5) // 2 for i in range(ticks): row = subgraph_height - 2 * i - 5 if subgraph_height % 2 == 0 and i >= ticks // 2: row -= 1 val = (max_bound - min_bound) * (subgraph_height - row - 3) // ( subgraph_height - 3) if val not in (min_bound, max_bound): y_axis_labels[row + 2] = data.y_axis_label(val) return y_axis_labels
sequencer-1.8.4
sequencer-1.8.4//lib/sequencer/commons.pyfile:/lib/sequencer/commons.py:function:td_to_seconds/td_to_seconds
def td_to_seconds(delta): """ Return the number of seconds of a time duration. """ return float(delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10 ** 6) / 10 ** 6
manimlib-0.1.10
manimlib-0.1.10//manimlib/utils/config_ops.pyfile:/manimlib/utils/config_ops.py:function:soft_dict_update/soft_dict_update
def soft_dict_update(d1, d2): """ Adds key values pairs of d2 to d1 only when d1 doesn't already have that key """ for key, value in list(d2.items()): if key not in d1: d1[key] = value
pomodorotimer
pomodorotimer//graph_statistic.pyclass:PeriodPomodoros/auto_label
@staticmethod def auto_label(rects: list, ax) ->None: """ Attach a text label above each bar in *rects*, displaying its height. """ for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width( ) / 2, height), xytext=(0, 3), textcoords='offset points', ha= 'center', va='bottom')
solstice-config-0.0.21
solstice-config-0.0.21//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 '+'
vctoolkit
vctoolkit//io.pyfile:/io.py:function:load_txt/load_txt
def load_txt(path): """ Read all lines from a text file. Parameters ---------- path : str Path to the text file. Returns ------- list A list of lines. """ with open(path, 'r') as f: lines = f.read().splitlines() return lines
horae.auth-1.0a1
horae.auth-1.0a1//horae/auth/auth.pyfile:/horae/auth/auth.py:function:setup_authentication/setup_authentication
def setup_authentication(pau): """Set up pluggable authentication utility. Sets up an :py:class:`zope.pluggableauth.interfaces.IAuthenticatorPlugin` and :py:class:`zope.pluggableauth.interfaces.ICredentialsPlugin` (for the authentication mechanism) """ pau.credentialsPlugins = ['credentials'] pau.authenticatorPlugins = ['users']
rich_base_provider-1.0.1
rich_base_provider-1.0.1//rich_base_provider/sysadmin/integral/integral_rule/models.pyclass:IntegralRule/get_integral_rule_by_integral_rule_id
@classmethod def get_integral_rule_by_integral_rule_id(cls, integral_rule_id): """ 根据积分规则ID获取本记录详细信息 :param integral_rule_id: :return: """ return cls.objects(integral_rule_id=integral_rule_id, status__nin=[cls. get_dict_id('integral_status', '删除')]).first()
zag
zag//examples/simple_map_reduce.pyfile:/examples/simple_map_reduce.py:function:chunk_iter/chunk_iter
def chunk_iter(chunk_size, upperbound): """Yields back chunk size pieces from zero to upperbound - 1.""" chunk = [] for i in range(0, upperbound): chunk.append(i) if len(chunk) == chunk_size: yield chunk chunk = []
chatette
chatette//utils.pyfile:/utils.py:function:min_if_exist/min_if_exist
def min_if_exist(n1, n2): """ Returns the minimum between two numbers, or the only defined number (in case the other is `None`) or `None` if none of the numbers are defined. """ if n1 is None and n2 is None: return None elif n1 is None: return n2 elif n2 is None: return n1 return min(n1, n2)
talisker
talisker//celery.pyfile:/celery.py:function:get_store/get_store
def get_store(body, headers): """celery 3.1/4.0 compatability shim.""" if isinstance(body, tuple): return headers else: return body
parlai
parlai//core/params.pyfile:/core/params.py:function:fix_underscores/fix_underscores
def fix_underscores(args): """Converts underscores to hyphens in args. For example, converts '--gradient_clip' to '--gradient-clip'. :param args: iterable, possibly containing args strings with underscores. """ if args: new_args = [] for a in args: if type(a) is str and a.startswith('-'): a = a.replace('_', '-') new_args.append(a) args = new_args return args
zope
zope//file/interfaces.pyclass:IFile/open
def open(mode='r'): """Return an object providing access to the file data. Allowed values for `mode` are 'r' (read); 'w' (write); 'a' (append) and 'r+' (read/write). Other values cause `ValueError` to be raised. If the file is opened in read mode, an object with an API (but not necessarily interface) of `IFileReader` is returned; if opened in write mode, an object with an API of `IFileWriter` is returned; if in read/write, an object that implements both is returned. All readers and writers operate in 'binary' mode. """
fortpy
fortpy//base.pyfile:/base.py:function:_common_parser/_common_parser
def _common_parser(): """Returns a parser with common command-line options for all the scripts in the fortpy suite. """ import argparse parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-examples', action='store_true', help= 'See detailed help and examples for this script.') parser.add_argument('-verbose', action='store_true', help= 'See verbose output as the script runs.') parser.add_argument('-action', nargs=1, choices=['save', 'print'], default='print', help= 'Specify what to do with the output (print or save)') parser.add_argument('-debug', action='store_true', help= 'Print verbose calculation information for debugging.') return parser