repo
stringlengths
1
29
path
stringlengths
24
332
code
stringlengths
39
579k
cis_interface-0.7.10
cis_interface-0.7.10//cis_interface/schema.pyfile:/cis_interface/schema.py:function:cdriver2filetype/cdriver2filetype
def cdriver2filetype(driver): """Convert a connection driver to a file type. Args: driver (str): The name of the connection driver. Returns: str: The corresponding file type for the driver. """ _legacy = {'FileInputDriver': 'binary', 'FileOutputDriver': 'binary', 'AsciiMapInputDriver': 'map', 'AsciiMapOutputDriver': 'map', 'AsciiFileInputDriver': 'ascii', 'AsciiFileOutputDriver': 'ascii', 'AsciiTableInputDriver': 'table', 'AsciiTableOutputDriver': 'table', 'PandasFileInputDriver': 'pandas', 'PandasFileOutputDriver': 'pandas', 'PickleFileInputDriver': 'pickle', 'PickleFileOutputDriver': 'pickle', 'PlyFileInputDriver': 'ply', 'PlyFileOutputDriver': 'ply', 'ObjFileInputDriver': 'obj', 'ObjFileOutputDriver': 'obj', 'MatInputDriver': 'mat', 'MatOutputDriver': 'mat'} if driver in _legacy: return _legacy[driver] raise ValueError('%s is not a registered connection driver.' % driver)
app-net-0.6.2
app-net-0.6.2//net/peer/peer.pyclass:Peer/build_connection_name
@staticmethod def build_connection_name(connection): """ Build a connections full name based on the module/name of the function. :param connection: connection :return: connection path """ return '.'.join([connection.__module__, connection.__name__])
pocoui-1.0.79
pocoui-1.0.79//poco/utils/six.pyfile:/poco/utils/six.py:function:_add_doc/_add_doc
def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc
fhirpy
fhirpy//base/searchset.pyfile:/base/searchset.py:function:transform_param/transform_param
def transform_param(param: str): """ >>> transform_param('general_practitioner') 'general-practitioner' """ if param[0] == '_' or param[0] == '.': return param return param.replace('_', '-')
WeasyPrint-51
WeasyPrint-51//weasyprint/draw.pyfile:/weasyprint/draw.py:function:xy_offset/xy_offset
def xy_offset(x, y, offset_x, offset_y, offset): """Increment X and Y coordinates by the given offsets.""" return x + offset_x * offset, y + offset_y * offset
fake-bpy-module-2.80-20200428
fake-bpy-module-2.80-20200428//bpy/ops/object.pyfile:/bpy/ops/object.py:function:select_camera/select_camera
def select_camera(extend: bool=False): """Select the active camera :param extend: Extend, Extend the selection :type extend: bool """ pass
OASYS1-XOPPY-1.0.75
OASYS1-XOPPY-1.0.75//orangecontrib/xoppy/util/script/variable.pyclass:DiscreteVariable/is_primitive
@staticmethod def is_primitive(): """ Return `True`: discrete variables are stored as floats. """ return True
msg_topgen
msg_topgen//generate.pyfile:/generate.py:function:get_neighbor_port/get_neighbor_port
def get_neighbor_port(graph, neighbor): """ Function for get port for connector according neighbor listener port. :param graph: graph :param neighbor: neighbor name :return: port number """ test = graph.nodes(data=True)[neighbor] try: if 'listener' in test: for item in test['listener']: if 'role' in item: if 'inter-route' in item['role']: return item['port'] else: raise AttributeError except AttributeError: raise AttributeError("Listener doesn't contains role!")
pymtattl-1.1.1
pymtattl-1.1.1//pymtattl/core.pyfile:/pymtattl/core.py:function:parseDate/parseDate
def parseDate(name): """return date part (yymmdd) given data url or file name""" return int(name.split('_')[-1].split('.')[0])
ayx_learn-0.0.1.172168
ayx_learn-0.0.1.172168//ayx_learn/transformers/impute_transformer.pyfile:/ayx_learn/transformers/impute_transformer.py:function:value/value
def value(_, val, *args): """Calculate fill value in VALUE mode.""" return val
pahoproxy
pahoproxy//publish.pyfile:/publish.py:function:_do_publish/_do_publish
def _do_publish(client): """Internal function""" message = client._userdata.popleft() if isinstance(message, dict): client.publish(**message) elif isinstance(message, (tuple, list)): client.publish(*message) else: raise TypeError('message must be a dict, tuple, or list')
substanced
substanced//interfaces.pyclass:IFolder/sort
def sort(oids, reverse=False, limit=None): """ Return the intersection of the oids of the folder's order with the oids passed in. If ``reverse`` is True, reverse the result set. If ``limit`` is an integer, return only that number of items (after reversing, if reverse is True)."""
richinput-1.0.0
richinput-1.0.0//richinput/richinput.pyfile:/richinput/richinput.py:function:is_char_interrupt/is_char_interrupt
def is_char_interrupt(c): """Check whether `c` is EOT (end of transmission, ^D).""" return c == u'\x04'
pya2l-0.0.1
pya2l-0.0.1//pya2l/parser/grammar/parser.pyclass:A2lParser/p_sub_function_optional
@staticmethod def p_sub_function_optional(p): """sub_function_optional : identifier""" p[0] = p.slice[1].type, p[1]
evoke-6.0
evoke-6.0//evoke/lib/library.pyfile:/evoke/lib/library.py:function:safeint/safeint
def safeint(num): """converts to int, regardless """ try: v = int(num) except: v = 0 return v
openquake
openquake//hazardlib/valid.pyfile:/hazardlib/valid.py:function:uncertainty_model/uncertainty_model
def uncertainty_model(value): """ Format whitespace in XML nodes of kind uncertaintyModel """ if value.lstrip().startswith('['): return value.strip() return ' '.join(value.split())
Axelrod-4.9.1
Axelrod-4.9.1//axelrod/_strategy_utils.pyfile:/axelrod/_strategy_utils.py:function:_calculate_scores/_calculate_scores
def _calculate_scores(p1, p2, game): """Calculates the scores for two players based their history. Parameters ---------- p1: Player The first player. p2: Player The second player. game: Game Game object used to score rounds in the players' histories. Returns ------- int, int The scores for the two input players. """ s1, s2 = 0, 0 for pair in zip(p1.history, p2.history): score = game.score(pair) s1 += score[0] s2 += score[1] return s1, s2
pytypes-1.0b5
pytypes-1.0b5//pytypes/util.pyfile:/pytypes/util.py:function:get_required_kwonly_args/get_required_kwonly_args
def get_required_kwonly_args(argspecs): """Determines whether given argspecs implies required keywords-only args and returns them as a list. Returns empty list if no such args exist. """ try: kwonly = argspecs.kwonlyargs if argspecs.kwonlydefaults is None: return kwonly res = [] for name in kwonly: if not name in argspecs.kwonlydefaults: res.append(name) return res except AttributeError: return []
rst_include-1.0.8
rst_include-1.0.8//rst_include/libs/lib_path.pyfile:/rst_include/libs/lib_path.py:function:strip_and_replace_backslashes/strip_and_replace_backslashes
def strip_and_replace_backslashes(path: str) ->str: """ >>> strip_and_replace_backslashes('c:\\\\test') 'c:/test' >>> strip_and_replace_backslashes('\\\\\\\\main\\\\install') '//main/install' """ path = path.strip().replace('\\', '/') return path
virga
virga//gas_properties.pyfile:/gas_properties.py:function:MgSiO3/MgSiO3
def MgSiO3(mw_atmos, mh=1): """Defines properties for MgSiO3 as condensible""" if mh != 1: raise Exception( 'Alert: No M/H Dependence in MgSiO3 Routine. Consult your local theorist to determine next steps.' ) gas_mw = 100.4 gas_mmr = 0.00275 rho_p = 3.192 return gas_mw, gas_mmr, rho_p
dgl_cu92-0.4.3.post2.data
dgl_cu92-0.4.3.post2.data//purelib/dgl/backend/backend.pyfile:/purelib/dgl/backend/backend.py:function:scatter_row/scatter_row
def scatter_row(data, row_index, value): """Write the value into the data tensor using the row index. This is an out-place write so it can work with autograd. Parameters ---------- data : Tensor The data tensor to be updated. row_index : Tensor A 1-D integer tensor containing which rows to be updated. value : Tensor The new value. Returns ------- Tensor The new data. """ pass
nomenclate-2.4.4
nomenclate-2.4.4//nomenclate/core/renderers.pyclass:RenderBase/render
@classmethod def render(cls, value, token, nomenclate_object, config_query_path=None, return_type=list, use_value_in_query_path=True, **kwargs): """ Default renderer for a token. It checks the config for a match, if not found it uses the value provided. :param value: str, value we are trying to match (or config setting for the token) :param token: str, token we are searching for :param nomenclate_object: nomenclate.core.nomenclate.Nomenclate, instance of nomenclate object to query :param kwargs: any config settings that relate to the token as found from the nomenclate instance :return: str, the resulting syntactically rendered string """ if config_query_path == None: config_query_path = nomenclate_object.OPTIONS_PATH + [token] if use_value_in_query_path: config_query_path += [value] config_matches = cls.get_config_match(value, config_query_path, return_type, nomenclate_object, **kwargs) options = cls.flatten_input(config_matches, value) option = cls.process_criteria(token, options, **kwargs ) if options else value return cls.process_token_augmentations(option, token_attr=getattr( nomenclate_object, token))
ocean
ocean//modules/mixin_extra_requirements.pyclass:MixIn/_pipeline_prev
@classmethod def _pipeline_prev(cls): """ Identify the previous build step in the build pipeline. """ return cls._ocean._PIPELINE[cls._ocean._PIPELINE.index(cls._PIPELINE[-1 ]) - 1][1]
enablebanking
enablebanking//models/invalid_response_signature_exception.pyclass:InvalidResponseSignatureException/__repr__
def __repr__(A): """For `print` and `pprint`""" return A.to_str()
cocopp
cocopp//compall/ppfigs.pyfile:/compall/ppfigs.py:function:providecolorsforlatex/providecolorsforlatex
def providecolorsforlatex(): """ Provides the dvipsnames colors in pure LaTeX. Used when the xcolor option of the same name is not available, e.g. within the new ACM LaTeX templates. """ return """% define some COCO/dvipsnames colors because % ACM style does not allow to use them directly \\definecolor{NavyBlue}{HTML}{000080} \\definecolor{Magenta}{HTML}{FF00FF} \\definecolor{Orange}{HTML}{FFA500} \\definecolor{CornflowerBlue}{HTML}{6495ED} \\definecolor{YellowGreen}{HTML}{9ACD32} \\definecolor{Gray}{HTML}{BEBEBE} \\definecolor{Yellow}{HTML}{FFFF00} \\definecolor{GreenYellow}{HTML}{ADFF2F} \\definecolor{ForestGreen}{HTML}{228B22} \\definecolor{Lavender}{HTML}{FFC0CB} \\definecolor{SkyBlue}{HTML}{87CEEB} \\definecolor{NavyBlue}{HTML}{000080} \\definecolor{Goldenrod}{HTML}{DDF700} \\definecolor{VioletRed}{HTML}{D02090} \\definecolor{CornflowerBlue}{HTML}{6495ED} \\definecolor{LimeGreen}{HTML}{32CD32} """
vmad-0.0.1
vmad-0.0.1//vmad/core/context.pyfile:/vmad/core/context.py:function:set_raise_internal_errors/set_raise_internal_errors
def set_raise_internal_errors(flag): """ If raise_internal_errors is set to True, then the errors in node execution are directly raised. If False, we will produce a wrapped messsage, which contains the line number where the node is declared. It is easier for debugging and in Python 3+ the underlying error message is also printed. """ global _raise_internal_errors _raise_internal_errors = flag
pymantic
pymantic//serializers.pyfile:/serializers.py:function:serialize_ntriples/serialize_ntriples
def serialize_ntriples(graph, f): """Serialize some graph to f as ntriples.""" for triple in graph: f.write(str(triple))
mxnet
mxnet//symbol/gen_op.pyfile:/symbol/gen_op.py:function:gather_nd/gather_nd
def gather_nd(data=None, indices=None, name=None, attr=None, out=None, **kwargs ): """Gather elements or slices from `data` and store to a tensor whose shape is defined by `indices`. Given `data` with shape `(X_0, X_1, ..., X_{N-1})` and indices with shape `(M, Y_0, ..., Y_{K-1})`, the output will have shape `(Y_0, ..., Y_{K-1}, X_M, ..., X_{N-1})`, where `M <= N`. If `M == N`, output shape will simply be `(Y_0, ..., Y_{K-1})`. The elements in output is defined as follows:: output[y_0, ..., y_{K-1}, x_M, ..., x_{N-1}] = data[indices[0, y_0, ..., y_{K-1}], ..., indices[M-1, y_0, ..., y_{K-1}], x_M, ..., x_{N-1}] Examples:: data = [[0, 1], [2, 3]] indices = [[1, 1, 0], [0, 1, 0]] gather_nd(data, indices) = [2, 3, 0] data = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] indices = [[0, 1], [1, 0]] gather_nd(data, indices) = [[3, 4], [5, 6]] Parameters ---------- data : Symbol data indices : Symbol indices name : string, optional. Name of the resulting symbol. Returns ------- Symbol The result symbol. """ return 0,
uwsgiconf
uwsgiconf//uwsgi_stub.pyfile:/uwsgi_stub.py:function:micros/micros
def micros(): """Returns uWSGI clock microseconds. :rtype: long """ return 0
javelin-0.1.0
javelin-0.1.0//javelin/fourier.pyfile:/javelin/fourier.py:function:get_mag_ff/get_mag_ff
def get_mag_ff(atomic_number, q, ion=0, j=0): """Returns the j0 magnetic form factor for a given atomic number, radiation and q values :param atomic_number: atomic number :type atomic_number: int :param q: value or values of q for which to get form factors :type q: float, list, :class:`numpy.ndarray` :param ion: charge of selected atom :type ion: int :param j: order of spherical Bessel function (0, 2, 4 or 6) :type j: int :return: magnetic form factor for given q :rtype: float, :class:`numpy.ndarray` :Examples: >>> get_mag_ff(8, q=2, ion=1) 0.58510426376585045 >>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=2) array([ 1. , 0.49729671, 0.09979243]) >>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=4) array([ 0.9997 , 0.58273549, 0.13948496]) >>> get_mag_ff(26, q=[0.0, 3.5, 7.0], ion=4, j=4) array([ 0. , 0.0149604, 0.0759222]) """ import periodictable return getattr(periodictable.elements[atomic_number].magnetic_ff[ion], 'j' + str(j) + '_Q')(q)
python-benedict-0.18.1
python-benedict-0.18.1//benedict/dicts/io/io_dict.pyclass:IODict/from_yaml
@classmethod def from_yaml(cls, s, **kwargs): """ Load and decode YAML data from url, filepath or data-string. Decoder specific options can be passed using kwargs: https://pyyaml.org/wiki/PyYAMLDocumentation Return a new dict instance. A ValueError is raised in case of failure. """ return cls(s, format='yaml', **kwargs)
azure-cli-batch-4.0.3
azure-cli-batch-4.0.3//azure/cli/command_modules/batch/_command_type.pyfile:/azure/cli/command_modules/batch/_command_type.py:function:_load_model/_load_model
def _load_model(name): """Load a model class from the SDK in order to inspect for parameter names and whether they're required. :param str name: The model class name to load. :returns: Model class """ if name.startswith('azure.'): namespace = name.split('.') else: namespace = ['azure', 'batch', 'models', name] model = __import__(namespace[0]) for level in namespace[1:]: model = getattr(model, level) return model
pygeostat
pygeostat//pygeostat_parameters.pyfile:/pygeostat_parameters.py:function:_validate_list/_validate_list
def _validate_list(s, accept_none=False): """ A validation method to convert input s to a list or raise error if it is not convertable """ if s is None and accept_none: return None try: return list(s) except ValueError: raise ValueError('Could not convert input to list')
oauth2_provider
oauth2_provider//views/mixins.pyclass:OAuthLibMixin/get_oauthlib_core
@classmethod def get_oauthlib_core(cls): """ Cache and return `OAuthlibCore` instance so it will be created only on first request """ if not hasattr(cls, '_oauthlib_core'): server = cls.get_server() core_class = cls.get_oauthlib_backend_class() cls._oauthlib_core = core_class(server) return cls._oauthlib_core
sip-5.2.0
sip-5.2.0//sipbuild/module/module.pyfile:/sipbuild/module/module.py:function:_install_file/_install_file
def _install_file(name_in, name_out, patches): """ Install a file and return a copy of its contents. """ with open(name_in) as f: data = f.read() for patch_name, patch in patches.items(): data = data.replace(patch_name, patch) with open(name_out, 'w') as f: f.write(data) return data
graphql-example-0.4.4
graphql-example-0.4.4//vendor/pip/_vendor/distlib/_backport/tarfile.pyclass:TarFile/taropen
@classmethod def taropen(cls, name, mode='r', fileobj=None, **kwargs): """Open uncompressed tar archive name for reading or writing. """ if len(mode) > 1 or mode not in 'raw': raise ValueError("mode must be 'r', 'a' or 'w'") return cls(name, mode, fileobj, **kwargs)
bokeh-2.0.2
bokeh-2.0.2//versioneer.pyfile:/versioneer.py:function:render_pep440_old/render_pep440_old
def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces['closest-tag']: rendered = pieces['closest-tag'] if pieces['distance'] or pieces['dirty']: rendered += '.post%d' % pieces['distance'] if pieces['dirty']: rendered += '.dev0' else: rendered = '0.post%d' % pieces['distance'] if pieces['dirty']: rendered += '.dev0' return rendered
webassets
webassets//env.pyfile:/env.py:function:parse_debug_value/parse_debug_value
def parse_debug_value(value): """Resolve the given string value to a debug option. Can be used to deal with os environment variables, for example. """ if value is None: return value value = value.lower() if value in ('true', '1'): return True elif value in ('false', '0'): return False elif value in ('merge',): return 'merge' else: raise ValueError()
persistent
persistent//interfaces.pyclass:IPickleCache/__delitem__
def __delitem__(oid): """ Remove the persistent object for OID. o 'oid' must be a string, else raise ValueError. o Raise KeyError if not found. """
pybtm
pybtm//segwit_addr.pyfile:/segwit_addr.py:function:convertbits/convertbits
def convertbits(data, frombits, tobits, pad=True): """General power-of-2 base conversion.""" acc = 0 bits = 0 ret = [] maxv = (1 << tobits) - 1 max_acc = (1 << frombits + tobits - 1) - 1 for value in data: if value < 0 or value >> frombits: return None acc = (acc << frombits | value) & max_acc bits += frombits while bits >= tobits: bits -= tobits ret.append(acc >> bits & maxv) if pad: if bits: ret.append(acc << tobits - bits & maxv) elif bits >= frombits or acc << tobits - bits & maxv: return None return ret
henipipe
henipipe//samTobed.pyfile:/samTobed.py:function:tile_region/tile_region
def tile_region(rname, start, end, step): """ Make non-overlapping tiled windows from the specified region in the UCSC-style string format. >>> list(tile_region('chr1', 1, 250, 100)) ['chr1:1-100', 'chr1:101-200', 'chr1:201-250'] >>> list(tile_region('chr1', 1, 200, 100)) ['chr1:1-100', 'chr1:101-200'] """ while start + step <= end: yield '%s:%d-%d' % (rname, start, start + step - 1) start += step if start < end: yield '%s:%d-%d' % (rname, start, end)
blackgate-0.3.0
blackgate-0.3.0//blackgate/config.pyfile:/blackgate/config.py:function:read_yaml_config/read_yaml_config
def read_yaml_config(path): """Read file content from path""" try: with open(path) as f: return f.read() except IOError: pass
indra-1.16.0
indra-1.16.0//indra/assemblers/english/assembler.pyfile:/indra/assemblers/english/assembler.py:function:_get_is_hypothesis/_get_is_hypothesis
def _get_is_hypothesis(stmt): """Returns true if there is evidence that the statement is only hypothetical. If all of the evidences associated with the statement indicate a hypothetical interaction then we assume the interaction is hypothetical.""" for ev in stmt.evidence: if not ev.epistemics.get('hypothesis') is True: return True return False
keras-retinanet-0.5.1
keras-retinanet-0.5.1//keras_retinanet/bin/train.pyfile:/keras_retinanet/bin/train.py:function:model_with_weights/model_with_weights
def model_with_weights(model, weights, skip_mismatch): """ Load weights for model. Args model : The model to load weights for. weights : The weights to load. skip_mismatch : If True, skips layers whose shape of weights doesn't match with the model. """ if weights is not None: model.load_weights(weights, by_name=True, skip_mismatch=skip_mismatch) return model
useful-0.8.5
useful-0.8.5//useful/shortcuts.pyfile:/useful/shortcuts.py:function:first/first
def first(predicate_or_None, iterable, default=None): """ Returns the first item of iterable for which predicate(item) is true. If predicate is None, matches the first item that is true. Returns value of default in case of no matching items. """ return next(filter(predicate_or_None, iterable), default)
currint-2.0.0
currint-2.0.0//currint/amount.pyclass:Amount/from_code_and_minor
@classmethod def from_code_and_minor(cls, currency_code, value): """ Initialises the amount with a currency code and an integer value of minor units """ from .currency import currencies try: return cls(currencies[currency_code.upper()], value) except KeyError: raise ValueError('Invalid currency code %s' % currency_code)
bamnostic-1.1.4
bamnostic-1.1.4//bamnostic/utils.pyfile:/bamnostic/utils.py:function:yes_no/yes_no
def yes_no(message): """ Simple prompt parser""" yes = set(['yes', 'ye', 'y', '']) no = set(['no', 'n']) print(message) while True: answer = input('Would you like to continue? [y/n] ').lower() if answer in yes: return True elif answer in no: return False else: print('Please answer "Yes" or "No"')
deuces_numpy-0.5
deuces_numpy-0.5//deuces_numpy/card.pyclass:Card/prime_product_from_hand
@staticmethod def prime_product_from_hand(card_ints): """ Expects a list of cards in integer form. """ product = 1 for c in card_ints: product *= c & 255 return product
buildbot
buildbot//interfaces.pyclass:IBuilderStatus/getBuild
def getBuild(number): """Return an IBuildStatus object for a historical build. Each build is numbered (starting at 0 when the Builder is first added), getBuild(n) will retrieve the Nth such build. getBuild(-n) will retrieve a recent build, with -1 being the most recent build started. If the Builder is idle, this will be the same as getLastFinishedBuild(). If the Builder is active, it will be an unfinished build. This method will return None if the build is no longer available. Older builds are likely to have less information stored: Logs are the first to go, then Steps."""
gnuper
gnuper//queries/level2.pyfile:/queries/level2.py:function:antenna_metrics_hourly_query/antenna_metrics_hourly_query
def antenna_metrics_hourly_query(table_name='%(table_name)s'): """ Further aggregate user event counts by the hour of the day, therefore ignoring the day and week. Most importantly aggregate up to the antenna level for all users who are predicted to live inside an antennas coverage (home antenna). Inputs ------ table_name : name of the table the query is supposed to run on, defaulting to '%(table_name)s', i.e. no substitution Output ------ Hourly antenna level aggregates of event counts, no more user ids. """ query = """ SELECT antenna_id, hour, SUM(og_sms) as og_sms, SUM(ic_sms) as ic_sms, SUM(og_calls) as og_calls, SUM(ic_calls) as ic_calls, SUM(og_vol) as og_vol, SUM(ic_vol) as ic_vol FROM %(table_name)s um JOIN table_user_home_antenna_df uha ON um.user_id = uha.user_id GROUP BY antenna_id, hour """ return query % {'table_name': table_name}
creopyson-0.5.0
creopyson-0.5.0//creopyson/view.pyfile:/creopyson/view.py:function:list_exploded/list_exploded
def list_exploded(client, file_=None, name=None): """List views that match criteria and are exploded. Args: client (obj): creopyson Client. `file_` (str, optional): Model name. Defaults is current active model. name (str, optional): View name (wildcards allowed: True). Defaults is None: all views are listed. Returns: (list:str): List of view names. """ data = {} if name is not None: data['name'] = name if file_ is not None: data['file'] = file_ else: active_file = client.file_get_active() if active_file is not None: data['file'] = active_file['file'] return client._creoson_post('view', 'list_exploded', data, 'viewlist')
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/pinpoint.pyfile:/pyboto3/pinpoint.py:function:update_campaign/update_campaign
def update_campaign(ApplicationId=None, CampaignId=None, WriteCampaignRequest=None): """ Use to update a campaign. :example: response = client.update_campaign( ApplicationId='string', CampaignId='string', WriteCampaignRequest={ 'AdditionalTreatments': [ { 'MessageConfiguration': { 'APNSMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' }, 'DefaultMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' }, 'GCMMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' } }, 'Schedule': { 'EndTime': 'string', 'Frequency': 'ONCE'|'HOURLY'|'DAILY'|'WEEKLY'|'MONTHLY', 'IsLocalTime': True|False, 'QuietTime': { 'End': 'string', 'Start': 'string' }, 'StartTime': 'string', 'Timezone': 'string' }, 'SizePercent': 123, 'TreatmentDescription': 'string', 'TreatmentName': 'string' }, ], 'Description': 'string', 'HoldoutPercent': 123, 'IsPaused': True|False, 'Limits': { 'Daily': 123, 'Total': 123 }, 'MessageConfiguration': { 'APNSMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' }, 'DefaultMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' }, 'GCMMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' } }, 'Name': 'string', 'Schedule': { 'EndTime': 'string', 'Frequency': 'ONCE'|'HOURLY'|'DAILY'|'WEEKLY'|'MONTHLY', 'IsLocalTime': True|False, 'QuietTime': { 'End': 'string', 'Start': 'string' }, 'StartTime': 'string', 'Timezone': 'string' }, 'SegmentId': 'string', 'SegmentVersion': 123, 'TreatmentDescription': 'string', 'TreatmentName': 'string' } ) :type ApplicationId: string :param ApplicationId: [REQUIRED] :type CampaignId: string :param CampaignId: [REQUIRED] :type WriteCampaignRequest: dict :param WriteCampaignRequest: [REQUIRED] Used to create a campaign. AdditionalTreatments (list) -- Treatments that are defined in addition to the default treatment. (dict) -- Used to create a campaign treatment. MessageConfiguration (dict) -- The message configuration settings. APNSMessage (dict) -- The message that the campaign delivers to APNS channels. Overrides the default message. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. DefaultMessage (dict) -- The default message for all channels. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. GCMMessage (dict) -- The message that the campaign delivers to GCM channels. Overrides the default message. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. Schedule (dict) -- The campaign schedule. EndTime (string) -- The scheduled time that the campaign ends in ISO 8601 format. Frequency (string) -- How often the campaign delivers messages. Valid values: ONCE, HOURLY, DAILY, WEEKLY, MONTHLY IsLocalTime (boolean) -- Indicates whether the campaign schedule takes effect according to each user's local time. QuietTime (dict) -- The time during which the campaign sends no messages. End (string) -- The default end time for quiet time in ISO 8601 format. Start (string) -- The default start time for quiet time in ISO 8601 format. StartTime (string) -- The scheduled time that the campaign begins in ISO 8601 format. Timezone (string) -- The starting UTC offset for the schedule if the value for isLocalTime is true Valid values: UTC UTC+01 UTC+02 UTC+03 UTC+03:30 UTC+04 UTC+04:30 UTC+05 UTC+05:30 UTC+05:45 UTC+06 UTC+06:30 UTC+07 UTC+08 UTC+09 UTC+09:30 UTC+10 UTC+10:30 UTC+11 UTC+12 UTC+13 UTC-02 UTC-03 UTC-04 UTC-05 UTC-06 UTC-07 UTC-08 UTC-09 UTC-10 UTC-11 SizePercent (integer) -- The allocated percentage of users for this treatment. TreatmentDescription (string) -- A custom description for the treatment. TreatmentName (string) -- The custom name of a variation of the campaign used for A/B testing. Description (string) -- A description of the campaign. HoldoutPercent (integer) -- The allocated percentage of end users who will not receive messages from this campaign. IsPaused (boolean) -- Indicates whether the campaign is paused. A paused campaign does not send messages unless you resume it by setting IsPaused to false. Limits (dict) -- The campaign limits settings. Daily (integer) -- The maximum number of messages that the campaign can send daily. Total (integer) -- The maximum total number of messages that the campaign can send. MessageConfiguration (dict) -- The message configuration settings. APNSMessage (dict) -- The message that the campaign delivers to APNS channels. Overrides the default message. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. DefaultMessage (dict) -- The default message for all channels. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. GCMMessage (dict) -- The message that the campaign delivers to GCM channels. Overrides the default message. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. Name (string) -- The custom name of the campaign. Schedule (dict) -- The campaign schedule. EndTime (string) -- The scheduled time that the campaign ends in ISO 8601 format. Frequency (string) -- How often the campaign delivers messages. Valid values: ONCE, HOURLY, DAILY, WEEKLY, MONTHLY IsLocalTime (boolean) -- Indicates whether the campaign schedule takes effect according to each user's local time. QuietTime (dict) -- The time during which the campaign sends no messages. End (string) -- The default end time for quiet time in ISO 8601 format. Start (string) -- The default start time for quiet time in ISO 8601 format. StartTime (string) -- The scheduled time that the campaign begins in ISO 8601 format. Timezone (string) -- The starting UTC offset for the schedule if the value for isLocalTime is true Valid values: UTC UTC+01 UTC+02 UTC+03 UTC+03:30 UTC+04 UTC+04:30 UTC+05 UTC+05:30 UTC+05:45 UTC+06 UTC+06:30 UTC+07 UTC+08 UTC+09 UTC+09:30 UTC+10 UTC+10:30 UTC+11 UTC+12 UTC+13 UTC-02 UTC-03 UTC-04 UTC-05 UTC-06 UTC-07 UTC-08 UTC-09 UTC-10 UTC-11 SegmentId (string) -- The ID of the segment to which the campaign sends messages. SegmentVersion (integer) -- The version of the segment to which the campaign sends messages. TreatmentDescription (string) -- A custom description for the treatment. TreatmentName (string) -- The custom name of a variation of the campaign used for A/B testing. :rtype: dict :return: { 'CampaignResponse': { 'AdditionalTreatments': [ { 'Id': 'string', 'MessageConfiguration': { 'APNSMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' }, 'DefaultMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' }, 'GCMMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' } }, 'Schedule': { 'EndTime': 'string', 'Frequency': 'ONCE'|'HOURLY'|'DAILY'|'WEEKLY'|'MONTHLY', 'IsLocalTime': True|False, 'QuietTime': { 'End': 'string', 'Start': 'string' }, 'StartTime': 'string', 'Timezone': 'string' }, 'SizePercent': 123, 'State': { 'CampaignStatus': 'SCHEDULED'|'EXECUTING'|'PENDING_NEXT_RUN'|'COMPLETED'|'PAUSED' }, 'TreatmentDescription': 'string', 'TreatmentName': 'string' }, ], 'ApplicationId': 'string', 'CreationDate': 'string', 'DefaultState': { 'CampaignStatus': 'SCHEDULED'|'EXECUTING'|'PENDING_NEXT_RUN'|'COMPLETED'|'PAUSED' }, 'Description': 'string', 'HoldoutPercent': 123, 'Id': 'string', 'IsPaused': True|False, 'LastModifiedDate': 'string', 'Limits': { 'Daily': 123, 'Total': 123 }, 'MessageConfiguration': { 'APNSMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' }, 'DefaultMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' }, 'GCMMessage': { 'Action': 'OPEN_APP'|'DEEP_LINK'|'URL', 'Body': 'string', 'ImageIconUrl': 'string', 'ImageUrl': 'string', 'JsonBody': 'string', 'MediaUrl': 'string', 'SilentPush': True|False, 'Title': 'string', 'Url': 'string' } }, 'Name': 'string', 'Schedule': { 'EndTime': 'string', 'Frequency': 'ONCE'|'HOURLY'|'DAILY'|'WEEKLY'|'MONTHLY', 'IsLocalTime': True|False, 'QuietTime': { 'End': 'string', 'Start': 'string' }, 'StartTime': 'string', 'Timezone': 'string' }, 'SegmentId': 'string', 'SegmentVersion': 123, 'State': { 'CampaignStatus': 'SCHEDULED'|'EXECUTING'|'PENDING_NEXT_RUN'|'COMPLETED'|'PAUSED' }, 'TreatmentDescription': 'string', 'TreatmentName': 'string', 'Version': 123 } } :returns: (dict) -- 200 response CampaignResponse (dict) -- Campaign definition AdditionalTreatments (list) -- Treatments that are defined in addition to the default treatment. (dict) -- Treatment resource Id (string) -- The unique treatment ID. MessageConfiguration (dict) -- The message configuration settings. APNSMessage (dict) -- The message that the campaign delivers to APNS channels. Overrides the default message. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. DefaultMessage (dict) -- The default message for all channels. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. GCMMessage (dict) -- The message that the campaign delivers to GCM channels. Overrides the default message. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. Schedule (dict) -- The campaign schedule. EndTime (string) -- The scheduled time that the campaign ends in ISO 8601 format. Frequency (string) -- How often the campaign delivers messages. Valid values: ONCE, HOURLY, DAILY, WEEKLY, MONTHLY IsLocalTime (boolean) -- Indicates whether the campaign schedule takes effect according to each user's local time. QuietTime (dict) -- The time during which the campaign sends no messages. End (string) -- The default end time for quiet time in ISO 8601 format. Start (string) -- The default start time for quiet time in ISO 8601 format. StartTime (string) -- The scheduled time that the campaign begins in ISO 8601 format. Timezone (string) -- The starting UTC offset for the schedule if the value for isLocalTime is true Valid values: UTC UTC+01 UTC+02 UTC+03 UTC+03:30 UTC+04 UTC+04:30 UTC+05 UTC+05:30 UTC+05:45 UTC+06 UTC+06:30 UTC+07 UTC+08 UTC+09 UTC+09:30 UTC+10 UTC+10:30 UTC+11 UTC+12 UTC+13 UTC-02 UTC-03 UTC-04 UTC-05 UTC-06 UTC-07 UTC-08 UTC-09 UTC-10 UTC-11 SizePercent (integer) -- The allocated percentage of users for this treatment. State (dict) -- The treatment status. CampaignStatus (string) -- The status of the campaign, or the status of a treatment that belongs to an A/B test campaign. Valid values: SCHEDULED, EXECUTING, PENDING_NEXT_RUN, COMPLETED, PAUSED TreatmentDescription (string) -- A custom description for the treatment. TreatmentName (string) -- The custom name of a variation of the campaign used for A/B testing. ApplicationId (string) -- The ID of the application to which the campaign applies. CreationDate (string) -- The date the campaign was created in ISO 8601 format. DefaultState (dict) -- The status of the campaign's default treatment. Only present for A/B test campaigns. CampaignStatus (string) -- The status of the campaign, or the status of a treatment that belongs to an A/B test campaign. Valid values: SCHEDULED, EXECUTING, PENDING_NEXT_RUN, COMPLETED, PAUSED Description (string) -- A description of the campaign. HoldoutPercent (integer) -- The allocated percentage of end users who will not receive messages from this campaign. Id (string) -- The unique campaign ID. IsPaused (boolean) -- Indicates whether the campaign is paused. A paused campaign does not send messages unless you resume it by setting IsPaused to false. LastModifiedDate (string) -- The date the campaign was last updated in ISO 8601 format. Limits (dict) -- The campaign limits settings. Daily (integer) -- The maximum number of messages that the campaign can send daily. Total (integer) -- The maximum total number of messages that the campaign can send. MessageConfiguration (dict) -- The message configuration settings. APNSMessage (dict) -- The message that the campaign delivers to APNS channels. Overrides the default message. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. DefaultMessage (dict) -- The default message for all channels. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. GCMMessage (dict) -- The message that the campaign delivers to GCM channels. Overrides the default message. Action (string) -- The action that occurs if the user taps a push notification delivered by the campaign: OPEN_APP Your app launches, or it becomes the foreground app if it has been sent to the background. This is the default action. DEEP_LINK Uses deep linking features in iOS and Android to open your app and display a designated user interface within the app. URL The default mobile browser on the user's device launches and opens a web page at the URL you specify. Body (string) -- The message body. Can include up to 140 characters. ImageIconUrl (string) -- The URL that points to the icon image for the push notification icon, for example, the app icon. ImageUrl (string) -- The URL that points to an image used in the push notification. JsonBody (string) -- The JSON payload used for a silent push. MediaUrl (string) -- The URL that points to the media resource, for example a .mp4 or .gif file. SilentPush (boolean) -- Indicates if the message should display on the users device. Silent pushes can be used for Remote Configuration and Phone Home use cases. Title (string) -- The message title that displays above the message on the user's device. Url (string) -- The URL to open in the user's mobile browser. Used if the value for Action is URL. Name (string) -- The custom name of the campaign. Schedule (dict) -- The campaign schedule. EndTime (string) -- The scheduled time that the campaign ends in ISO 8601 format. Frequency (string) -- How often the campaign delivers messages. Valid values: ONCE, HOURLY, DAILY, WEEKLY, MONTHLY IsLocalTime (boolean) -- Indicates whether the campaign schedule takes effect according to each user's local time. QuietTime (dict) -- The time during which the campaign sends no messages. End (string) -- The default end time for quiet time in ISO 8601 format. Start (string) -- The default start time for quiet time in ISO 8601 format. StartTime (string) -- The scheduled time that the campaign begins in ISO 8601 format. Timezone (string) -- The starting UTC offset for the schedule if the value for isLocalTime is true Valid values: UTC UTC+01 UTC+02 UTC+03 UTC+03:30 UTC+04 UTC+04:30 UTC+05 UTC+05:30 UTC+05:45 UTC+06 UTC+06:30 UTC+07 UTC+08 UTC+09 UTC+09:30 UTC+10 UTC+10:30 UTC+11 UTC+12 UTC+13 UTC-02 UTC-03 UTC-04 UTC-05 UTC-06 UTC-07 UTC-08 UTC-09 UTC-10 UTC-11 SegmentId (string) -- The ID of the segment to which the campaign sends messages. SegmentVersion (integer) -- The version of the segment to which the campaign sends messages. State (dict) -- The campaign status. An A/B test campaign will have a status of COMPLETED only when all treatments have a status of COMPLETED. CampaignStatus (string) -- The status of the campaign, or the status of a treatment that belongs to an A/B test campaign. Valid values: SCHEDULED, EXECUTING, PENDING_NEXT_RUN, COMPLETED, PAUSED TreatmentDescription (string) -- A custom description for the treatment. TreatmentName (string) -- The custom name of a variation of the campaign used for A/B testing. Version (integer) -- The campaign version number. """ pass
uszipcode-0.2.4
uszipcode-0.2.4//uszipcode/pkg/six.pyfile:/uszipcode/pkg/six.py:function:_add_doc/_add_doc
def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc
attrs-19.3.0
attrs-19.3.0//src/attr/_version_info.pyclass:VersionInfo/_from_version_string
@classmethod def _from_version_string(cls, s): """ Parse *s* and return a _VersionInfo. """ v = s.split('.') if len(v) == 3: v.append('final') return cls(year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3])
pulse2percept-0.6.0
pulse2percept-0.6.0//pulse2percept/utils/geometry.pyclass:Curcio1990Transform/dva2ret
@staticmethod def dva2ret(xdva): """Convert degrees of visual angle (dva) to retinal eccentricity (um) Assumes that one degree of visual angle is equal to 280 um on the retina [Curcio1990]_. """ return 280.0 * xdva
compas_rcf
compas_rcf//utils/util_funcs.pyfile:/utils/util_funcs.py:function:wrap_list/wrap_list
def wrap_list(list_, idx): """Return value at index, wrapping if necessary. Parameters ---------- list_ : :class:`list` List to wrap around. idx : :class:`int` Index of item to return in list. Returns ------- :class:`list` element Item at given index, index will be wrapped if necessary. """ return list_[idx % len(list_)]
python-casacore-3.3.0
python-casacore-3.3.0//casacore/util/substitute.pyfile:/casacore/util/substitute.py:function:getlocals/getlocals
def getlocals(back=2): """Get the local variables some levels back (-1 is top).""" import inspect fr = inspect.currentframe() try: while fr and back != 0: fr1 = fr fr = fr.f_back back -= 1 except: pass return fr1.f_locals
hdx
hdx//hdx_locations.pyclass:Locations/set_validlocations
@classmethod def set_validlocations(cls, locations): """ Set valid locations using list of dictionaries of form {'name': 'zmb', 'title', 'Zambia'} Args: locations (List[Dict]): List of dictionaries of form {'name': 'zmb', 'title', 'Zambia'} Returns: None """ cls._validlocations = locations
libpysal-4.2.2
libpysal-4.2.2//libpysal/weights/distance.pyclass:Kernel/from_array
@classmethod def from_array(cls, array, **kwargs): """ Construct a Kernel weights from an array. Supports all the same options as :class:`libpysal.weights.Kernel` See Also -------- :class:`libpysal.weights.weights.W` """ return cls(array, **kwargs)
mpctools-0.4.1
mpctools-0.4.1//mpctools/extensions/pdext.pyfile:/mpctools/extensions/pdext.py:function:recategorise/recategorise
def recategorise(_df, _cat_type, _cols, _map=None): """ A Convenience function to re-categorise the columns in the dataframe: the operation is performed in place. Note that the function allows mapping of categorical type with no overlaps through the _map construct. :param _df: Data-Frame to recategorise :param _cat_type: Categorical DType to set :param _cols: The columns to change :param _map: If need be, map certain values to others before recategorising: values which are not mapped and which appear in the data but not in the new label-set (CDType) will be turned into NaN :return: None (operation done in place) """ if _map is not None: for col in _cols: _df.loc[:, (col)] = _df[col].map(_map) _df.loc[:, (col)] = _df[col].astype(float, copy=False).astype( _cat_type) else: for col in _cols: _df.loc[:, (col)] = _df[col].astype(float, copy=False).astype( _cat_type)
fireant-5.4.8
fireant-5.4.8//fireant/utils.pyfile:/fireant/utils.py:function:getdeepattr/getdeepattr
def getdeepattr(d, keys, default_value=None): """ Similar to the built-in `getattr`, this function accepts a list/tuple of keys to get a value deep in a `dict` Given the following dict structure .. code-block:: python d = { 'A': { '0': { 'a': 1, 'b': 2, } }, } Calling `getdeepattr` with a key path to a value deep in the structure will return that value. If the value or any of the objects in the key path do not exist, then the default value is returned. .. code-block:: python assert 1 == getdeepattr(d, ('A', '0', 'a')) assert 2 == getdeepattr(d, ('A', '0', 'b')) assert 0 == getdeepattr(d, ('A', '0', 'c'), default_value=0) assert 0 == getdeepattr(d, ('X', '0', 'a'), default_value=0) :param d: A dict value with nested dict attributes. :param keys: A list/tuple path of keys in `d` to the desired value :param default_value: A default value that will be returned if the path `keys` does not yield a value. :return: The value following the path `keys` or `default_value` """ d_level = d for key in keys: if isinstance(d_level, dict) and key not in d_level or not hasattr( d_level, key): return default_value d_level = d_level[key] return d_level
gns3-converter-1.2.4
gns3-converter-1.2.4//gns3converter/converter.pyclass:Converter/generate_notes
@staticmethod def generate_notes(notes): """ Generate the notes list :param dict notes: A dict of converted notes from the old topology :return: List of notes for the the topology :rtype: list """ new_notes = [] for note in notes: tmp_note = {} for note_item in notes[note]: tmp_note[note_item] = notes[note][note_item] new_notes.append(tmp_note) return new_notes
fake-bpy-module-2.79-20200428
fake-bpy-module-2.79-20200428//bpy/ops/screen.pyfile:/bpy/ops/screen.py:function:region_quadview/region_quadview
def region_quadview(): """Split selected area into camera, front, right & top views """ pass
eventum-0.2.7
eventum-0.2.7//eventum/lib/events.pyclass:EventsHelper/_more_events
@classmethod def _more_events(cls, series, date_data): """Returns True if more events exist in this series after ``date_data``. :Example: If the series included a recurrence for an event five times, and ``series.events`` contained only three events, this would return True. :Example: If the series started on Jan 1 and recurred weekly until Feb 1, and date_data represented Jan 29, this would return False, because the next event in the series would be after the end of the recurrence. :param series: The event series in question :type series: :class:`EventSeries` :param dict date_data: The reference date. :returns: True if there are more events in the series. :rtype: bool. """ if series.ends_after and len(series.events ) >= series.num_occurrences or series.ends_on and date_data[ 'start_date'] > series.recurrence_end_date: return False return True
egor
egor//util.pyfile:/util.py:function:kill_process/kill_process
def kill_process(process) ->None: """ Simply kills the process passed as a parameter :param process: executing process """ process.kill()
montblanc-0.6.2
montblanc-0.6.2//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
infoblox_client
infoblox_client//objects.pyclass:InfobloxObject/from_dict
@classmethod def from_dict(cls, connector, ip_dict): """Build dict fields as SubObjects if needed. Checks if lambda for building object from dict exists. _global_field_processing and _custom_field_processing rules are checked. """ mapping = cls._global_field_processing.copy() mapping.update(cls._custom_field_processing) for field in mapping: if field in ip_dict: ip_dict[field] = mapping[field](ip_dict[field]) return cls(connector, **ip_dict)
kll-0.5.7.16
kll-0.5.7.16//kll/common/parse.pyclass:Make/number
def number(token): """ Convert string number to Python integer """ return int(token, 0)
mtwaffle-0.7
mtwaffle-0.7//mtwaffle/mt.pyfile:/mtwaffle/mt.py:function:ohms2mV_km_nT/ohms2mV_km_nT
def ohms2mV_km_nT(zs): """Convert imp. tensor(s) from ohms to mV/km/nT.""" return zs * 796.0
nagiosplugin
nagiosplugin//output.pyfile:/output.py:function:filter_output/filter_output
def filter_output(output, filtered): """ Filters out characters from output """ for char in filtered: output = output.replace(char, '') return output
collective.categorizing-0.2.3
collective.categorizing-0.2.3//collective/categorizing/interfaces/adapter.pyclass:ICategoryHierarchy/list_hierarchy_object
def list_hierarchy_object(obj): """Returns objet list of hierarchy."""
nmrglue
nmrglue//analysis/analysisbase.pyfile:/analysis/analysisbase.py:function:squish/squish
def squish(r, axis): """ Squish array along an axis. Determine the sum along all but one axis for an array. Parameters ---------- r : ndarray Array to squish. axis : int Axis of r to squish along. Returns ------- s : 1D ndarray Array r squished into a single dimension. """ N = int(r.ndim) r = r.swapaxes(axis, N - 1) for i in range(N - 1): r = r.sum(0) return r
pygorithm
pygorithm//data_structures/graph.pyclass:WeightedGraph/kruskal_time_complexity
@staticmethod def kruskal_time_complexity(): """ Return time complexity of kruskal :return: string """ return ( 'Worst case: O(E log(V)) where E in the number of edges and V the number of vertexes' )
numina-0.21
numina-0.21//numina/array/trace/traces.pyfile:/numina/array/trace/traces.py:function:axis_to_dispaxis/axis_to_dispaxis
def axis_to_dispaxis(axis): """Obtain the dispersion axis from the spatial axis.""" if axis == 0: dispaxis = 1 elif axis == 1: dispaxis = 0 else: raise ValueError("'axis' must be 0 or 1") return dispaxis
hapi-vendor-toolkit-0.0.2
hapi-vendor-toolkit-0.0.2//hyperdns/vendor/core/abstract.pyclass:AbstractDriver/get_html_template
@classmethod def get_html_template(cls): """Create a generic angular HTML template for configuring the vendor's login from the settings information. """ template = """ <fieldset> """ sinfo = cls.info.get('angular', {}) settings = cls.info.get('settings', []) for setting in settings: info = sinfo.get(setting, {}) label = info.get('label', setting) placeholder = info.get('placeholder', label) htype = info.get('type', 'text') template += ( """ <div class="form-group"> <label for="%s" class="control-label">%s</label> <div> <input required type="%s" class="form-control" id="username" placeholder="%s" ng-model="v.settings.%s"> </div> </div> """ % (setting, label, htype, placeholder, setting)) template += """ </fieldset> """ return template
netdef
netdef//Sources/XmlRpcMethodCallSource.pyclass:XmlRpcMethodCallSource/unpack_subitems
@staticmethod def unpack_subitems(value): """Yields None, cannot unpack subitems""" yield None
evp001
evp001//due.pyfile:/due.py:function:_donothing_func/_donothing_func
def _donothing_func(*args, **kwargs): """Perform no good and no bad""" pass
agentMET4FOF-0.1.7
agentMET4FOF-0.1.7//agentMET4FOF/streams.pyfile:/agentMET4FOF/streams.py:function:extract_x_y/extract_x_y
def extract_x_y(message): """ Extracts features & target from `message['data']` with expected structure such as : 1. tuple - (x,y) 2. dict - {'x':x_data,'y':y_data} Handle data structures of dictionary to extract features & target """ if type(message['data']) == tuple: x = message['data'][0] y = message['data'][1] elif type(message['data']) == dict: x = message['data']['x'] y = message['data']['y'] else: return -1 return x, y
pyAMI_atlas-5.1.0.1
pyAMI_atlas-5.1.0.1//pyAMI_atlas/api.pyfile:/pyAMI_atlas/api.py:function:get_dataset_hashtags/get_dataset_hashtags
def get_dataset_hashtags(client, dataset): """Get dataset information. Args: :client: the pyAMI client [ pyAMI.client.Client ] :dataset: the dataset [ str ] Returns: a python dictionnaries. """ command = ['DatasetWBListHashtags', '-ldn="%s"' % dataset] return client.execute(command, format='dom_object').get_rows()
aikit
aikit//scorer.pyfile:/scorer.py:function:_cached_call/_cached_call
def _cached_call(cache, estimator, method, *args, **kwargs): """Call estimator with method and args and kwargs.""" if cache is None: return getattr(estimator, method)(*args, **kwargs) try: return cache[method] except KeyError: result = getattr(estimator, method)(*args, **kwargs) cache[method] = result return result
qmeq
qmeq//various.pyfile:/various.py:function:remove_states/remove_states
def remove_states(sys, dE): """ Remove the states with energy dE larger than the ground state for the transport calculations. Parameters ---------- sys : Approach, Approach2vN, or Builder The system given as Approach, Approach2vN, or Builder object. dE : float Energy above the ground state. Modifies: sys.si.statesdm : list List containing indices of many-body state under consideration. """ Emax = min(sys.qd.Ea) + dE statesdm = [[] for i in range(sys.si.nsingle + 1)] for charge in range(sys.si.ncharge): for b in sys.si.chargelst[charge]: if sys.qd.Ea[b] < Emax: statesdm[charge].append(b) sys.si.set_statesdm(statesdm)
wolframclient-1.1.4
wolframclient-1.1.4//wolframclient/utils/url.pyfile:/wolframclient/utils/url.py:function:url_join/url_join
def url_join(*fragments): """ Join fragments of a URL, dealing with slashes.""" if len(fragments) == 0: return '' buff = [] for fragment in fragments: stripped = fragment.strip('/') if len(stripped) > 0: buff.append(stripped) buff.append('/') last = fragments[-1] if len(last) > 0 and last[-1] != '/': buff.pop() return ''.join(buff)
OWSLib-0.19.2
OWSLib-0.19.2//owslib/util.pyfile:/owslib/util.py:function:dump/dump
def dump(obj, prefix=''): """Utility function to print to standard output a generic object with all its attributes.""" print('{} {}.{} : {}'.format(prefix, obj.__module__, obj.__class__. __name__, obj.__dict__))
joblib-0.14.1
joblib-0.14.1//joblib/externals/cloudpickle/cloudpickle.pyfile:/joblib/externals/cloudpickle/cloudpickle.py:function:instance/instance
def instance(cls): """Create a new instance of a class. Parameters ---------- cls : type The class to create an instance of. Returns ------- instance : cls A new instance of ``cls``. """ return cls()
periodictable-1.5.2
periodictable-1.5.2//periodictable/nsf.pyfile:/periodictable/nsf.py:function:_sum_piece/_sum_piece
def _sum_piece(wavelength, compound): """ Helper for neutron_composite_sld which precomputes quantities of interest for material fragments in a composite formula. """ molar_mass = num_atoms = 0 sigma_a = sigma_s = b_c = 0 is_energy_dependent = False for element, quantity in compound.atoms.items(): molar_mass += element.mass * quantity num_atoms += quantity sigma_a += quantity * element.neutron.absorption sigma_s += quantity * element.neutron.total b_c += quantity * element.neutron.b_c is_energy_dependent |= element.neutron.is_energy_dependent return num_atoms, molar_mass, b_c, sigma_s, sigma_a
poorwsgi
poorwsgi//session.pyclass:NoCompress/compress
@staticmethod def compress(data, compresslevel=0): """Get two params, data, and compresslevel. Method only return data.""" return data
pymor
pymor//vectorarrays/constructions.pyfile:/vectorarrays/constructions.py:function:cat_arrays/cat_arrays
def cat_arrays(vector_arrays): """Return a new |VectorArray| which is a concatenation of the arrays in `vector_arrays`.""" vector_arrays = list(vector_arrays) total_length = sum(map(len, vector_arrays)) cated_arrays = vector_arrays[0].empty(reserve=total_length) for a in vector_arrays: cated_arrays.append(a) return cated_arrays
dfvfs-20200429
dfvfs-20200429//dfvfs/lib/vshadow.pyfile:/dfvfs/lib/vshadow.py:function:VShadowPathSpecGetStoreIndex/VShadowPathSpecGetStoreIndex
def VShadowPathSpecGetStoreIndex(path_spec): """Retrieves the store index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: store index or None if not available. """ store_index = getattr(path_spec, 'store_index', None) if store_index is None: location = getattr(path_spec, 'location', None) if location is None or not location.startswith('/vss'): return None store_index = None try: store_index = int(location[4:], 10) - 1 except (TypeError, ValueError): pass if store_index is None or store_index < 0: return None return store_index
tcp_h2_describe
tcp_h2_describe//_buffer.pyfile:/_buffer.py:function:is_closed/is_closed
def is_closed(socket_): """Determine if a socket is closed. This uses the associated file descriptor as a proxy for "closed". Args: socket_ (socket.socket): The socket to check. Returns: bool: Indicates if closed or open. """ return socket_.fileno() == -1
topology_docker
topology_docker//utils.pyfile:/utils.py:function:get_iface_name/get_iface_name
def get_iface_name(enode, netname): """ Get interface name inside a container This function will figure out the interface name inside the container for a given docker network. :param enode: The platform ("engine") node to get the iface name from. :param str netname: The name of the docker network to which the interface we're looking for is connected. """ docker_netconf = enode._client.inspect_container(enode.container_id)[ 'NetworkSettings']['Networks'][netname] ifaces_conf = enode._docker_exec('ip -o link list').strip().split('\n') for iface_conf in ifaces_conf: if docker_netconf['MacAddress'] in iface_conf: iface = iface_conf.split(': ')[1].split('@')[0] break else: raise RuntimeError( 'Unable to find interface with MAC address {docker_netconf[MacAddress]} in netns {netns} in container {enode._container_id} with name {enode._container_name}' .format(**locals())) return iface
audio.wave-4.0.2
audio.wave-4.0.2//.lib/pkg_resources.pyclass:IMetadataProvider/run_script
def run_script(script_name, namespace): """Execute the named script in the supplied namespace dictionary"""
fake-bpy-module-2.80-20200428
fake-bpy-module-2.80-20200428//bpy/ops/file.pyfile:/bpy/ops/file.py:function:hidedot/hidedot
def hidedot(): """Toggle hide hidden dot files """ pass
iapws-1.4.1
iapws-1.4.1//iapws/iapws97.pyfile:/iapws/iapws97.py:function:_TSat_P/_TSat_P
def _TSat_P(P): """Define the saturated line, T=f(P) Parameters ---------- P : float Pressure, [MPa] Returns ------- T : float Temperature, [K] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * 0.00061121 ≤ P ≤ 22.064 References ---------- IAPWS, Revised Release on the IAPWS Industrial Formulation 1997 for the Thermodynamic Properties of Water and Steam August 2007, http://www.iapws.org/relguide/IF97-Rev.html, Eq 31 Examples -------- >>> _TSat_P(10) 584.149488 """ if P < 611.212677 / 1000000.0 or P > 22.064: raise NotImplementedError('Incoming out of bound') n = [0, 1167.0521452767, -724213.16703206, -17.073846940092, 12020.82470247, -3232555.0322333, 14.91510861353, -4823.2657361591, 405113.40542057, -0.23855557567849, 650.17534844798] beta = P ** 0.25 E = beta ** 2 + n[3] * beta + n[6] F = n[1] * beta ** 2 + n[4] * beta + n[7] G = n[2] * beta ** 2 + n[5] * beta + n[8] D = 2 * G / (-F - (F ** 2 - 4 * E * G) ** 0.5) return (n[10] + D - ((n[10] + D) ** 2 - 4 * (n[9] + n[10] * D)) ** 0.5) / 2
pyboto3-1.4.4
pyboto3-1.4.4//pyboto3/lambda_.pyfile:/pyboto3/lambda_.py:function:create_alias/create_alias
def create_alias(FunctionName=None, Name=None, FunctionVersion=None, Description=None): """ Creates an alias that points to the specified Lambda function version. For more information, see Introduction to AWS Lambda Aliases . Alias names are unique for a given function. This requires permission for the lambda:CreateAlias action. See also: AWS API Documentation :example: response = client.create_alias( FunctionName='string', Name='string', FunctionVersion='string', Description='string' ) :type FunctionName: string :param FunctionName: [REQUIRED] Name of the Lambda function for which you want to create an alias. Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 characters in length. :type Name: string :param Name: [REQUIRED] Name for the alias you are creating. :type FunctionVersion: string :param FunctionVersion: [REQUIRED] Lambda function version for which you are creating the alias. :type Description: string :param Description: Description of the alias. :rtype: dict :return: { 'AliasArn': 'string', 'Name': 'string', 'FunctionVersion': 'string', 'Description': 'string' } """ pass
django-oscar-api-2.0.2
django-oscar-api-2.0.2//oscarapi/utils/request.pyfile:/oscarapi/utils/request.py:function:get_domain/get_domain
def get_domain(request): """ Get the domain name parsed from a hostname:port string >>> class FakeRequest(object): ... def __init__(self, url): ... self.url = url ... def get_host(self): ... return self.url >>> req = FakeRequest("example.com:5984") >>> get_domain(req) 'example.com' """ return request.get_host().split(':')[0]
CamAi
CamAi//mrcnn_model.pyfile:/mrcnn_model.py:function:log/log
def log(text, array=None): """Prints a text message. And, optionally, if a Numpy array is provided it prints it's shape, min, and max values. """ if array is not None: text = text.ljust(25) text += 'shape: {:20} '.format(str(array.shape)) if array.size: text += 'min: {:10.5f} max: {:10.5f}'.format(array.min(), array.max()) else: text += 'min: {:10} max: {:10}'.format('', '') text += ' {}'.format(array.dtype) print(text)
spruceup-2020.2.19
spruceup-2020.2.19//spruceup/spruceup.pyfile:/spruceup/spruceup.py:function:check_cutoff_value/check_cutoff_value
def check_cutoff_value(criterion, cutoff_value): """Validate single cutoff value from config file.""" if criterion == 'lognorm': if cutoff_value > 0 and cutoff_value < 1: pass else: exit( 'Invalid lognorm quantile cutoff value "{}". The cutoffs must be numbers greater than 0 and less than 1.' .format(cutoff_value)) elif criterion == 'mean': if cutoff_value > 1: pass elif cutoff_value > 0 and cutoff_value < 1: print( 'WARNING: cutoff value "{}" is less than 1 mean. Did you intend to specify "lognorm" as criterion?' .format(cutoff_value)) elif cutoff_value < 0: exit( 'Invalid mean cutoff value "{}". Cutoffs must be greater than 0.' )
pyGeno-2.0.0
pyGeno-2.0.0//pyGeno/tools/UsefulFunctions.pyfile:/pyGeno/tools/UsefulFunctions.py:function:highlightSubsequence/highlightSubsequence
def highlightSubsequence(sequence, x1, x2, start=' [', stop='] '): """returns a sequence where the subsequence in [x1, x2[ is placed in bewteen 'start' and 'stop'""" seq = list(sequence) print(x1, x2 - 1, len(seq)) seq[x1] = start + seq[x1] seq[x2 - 1] = seq[x2 - 1] + stop return ''.join(seq)
Kivy-1.11.1
Kivy-1.11.1//kivy/tools/pep8checker/pep8.pyfile:/kivy/tools/pep8checker/pep8.py:function:trailing_whitespace/trailing_whitespace
def trailing_whitespace(physical_line): """Trailing whitespace is superfluous. The warning returned varies on whether the line itself is blank, for easier filtering for those who want to indent their blank lines. Okay: spam(1)\\n# W291: spam(1) \\n# W293: class Foo(object):\\n \\n bang = 12 """ physical_line = physical_line.rstrip('\n') physical_line = physical_line.rstrip('\r') physical_line = physical_line.rstrip('\x0c') stripped = physical_line.rstrip(' \t\x0b') if physical_line != stripped: if stripped: return len(stripped), 'W291 trailing whitespace' else: return 0, 'W293 blank line contains whitespace'
pya2l-0.0.1
pya2l-0.0.1//pya2l/parser/grammar/parser.pyclass:A2lParser/p_ecu_address_extension
@staticmethod def p_ecu_address_extension(p): """ecu_address_extension : ECU_ADDRESS_EXTENSION NUMERIC""" p[0] = p[2]