repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
buriburisuri/sugartensor
sugartensor/sg_transform.py
https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L199-L214
def sg_argmin(tensor, opt): r"""Returns the indices of the minimum values along the specified axis. See `tf.argin()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis: Target axis. Default is the last one. name: If provided, replace current tensor's name. Returns: A `Tensor`. """ opt += tf.sg_opt(axis=tensor.get_shape().ndims - 1) return tf.argmin(tensor, opt.axis, opt.name)
[ "def", "sg_argmin", "(", "tensor", ",", "opt", ")", ":", "opt", "+=", "tf", ".", "sg_opt", "(", "axis", "=", "tensor", ".", "get_shape", "(", ")", ".", "ndims", "-", "1", ")", "return", "tf", ".", "argmin", "(", "tensor", ",", "opt", ".", "axis",...
r"""Returns the indices of the minimum values along the specified axis. See `tf.argin()` in tensorflow. Args: tensor: A `Tensor` (automatically given by chain). opt: axis: Target axis. Default is the last one. name: If provided, replace current tensor's name. Returns: A `Tensor`.
[ "r", "Returns", "the", "indices", "of", "the", "minimum", "values", "along", "the", "specified", "axis", "." ]
python
train
IdentityPython/pysaml2
src/saml2/httpbase.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/httpbase.py#L120-L149
def cookies(self, url): """ Return cookies that are matching the path and are still valid :param url: :return: """ part = urlparse(url) #if part.port: # _domain = "%s:%s" % (part.hostname, part.port) #else: _domain = part.hostname cookie_dict = {} now = utc_now() for _, a in list(self.cookiejar._cookies.items()): for _, b in a.items(): for cookie in list(b.values()): # print(cookie) if cookie.expires and cookie.expires <= now: continue if not re.search("%s$" % cookie.domain, _domain): continue if not re.match(cookie.path, part.path): continue cookie_dict[cookie.name] = cookie.value return cookie_dict
[ "def", "cookies", "(", "self", ",", "url", ")", ":", "part", "=", "urlparse", "(", "url", ")", "#if part.port:", "# _domain = \"%s:%s\" % (part.hostname, part.port)", "#else:", "_domain", "=", "part", ".", "hostname", "cookie_dict", "=", "{", "}", "now", "=",...
Return cookies that are matching the path and are still valid :param url: :return:
[ "Return", "cookies", "that", "are", "matching", "the", "path", "and", "are", "still", "valid" ]
python
train
LordDarkula/chess_py
chess_py/pieces/king.py
https://github.com/LordDarkula/chess_py/blob/14bebc2f8c49ae25c59375cc83d0b38d8ff7281d/chess_py/pieces/king.py#L51-L63
def in_check_as_result(self, pos, move): """ Finds if playing my move would make both kings meet. :type: pos: Board :type: move: Move :rtype: bool """ test = cp(pos) test.update(move) test_king = test.get_king(move.color) return self.loc_adjacent_to_opponent_king(test_king.location, test)
[ "def", "in_check_as_result", "(", "self", ",", "pos", ",", "move", ")", ":", "test", "=", "cp", "(", "pos", ")", "test", ".", "update", "(", "move", ")", "test_king", "=", "test", ".", "get_king", "(", "move", ".", "color", ")", "return", "self", "...
Finds if playing my move would make both kings meet. :type: pos: Board :type: move: Move :rtype: bool
[ "Finds", "if", "playing", "my", "move", "would", "make", "both", "kings", "meet", "." ]
python
train
hvac/hvac
hvac/api/system_backend/key.py
https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/system_backend/key.py#L304-L325
def read_backup_keys(self, recovery_key=False): """Retrieve the backup copy of PGP-encrypted unseal keys. The returned value is the nonce of the rekey operation and a map of PGP key fingerprint to hex-encoded PGP-encrypted key. Supported methods: PUT: /sys/rekey/backup. Produces: 200 application/json PUT: /sys/rekey-recovery-key/backup. Produces: 200 application/json :param recovery_key: If true, send requests to "rekey-recovery-key" instead of "rekey" api path. :type recovery_key: bool :return: The JSON response of the request. :rtype: dict """ api_path = '/v1/sys/rekey/backup' if recovery_key: api_path = '/v1/sys/rekey-recovery-key/backup' response = self._adapter.get( url=api_path, ) return response.json()
[ "def", "read_backup_keys", "(", "self", ",", "recovery_key", "=", "False", ")", ":", "api_path", "=", "'/v1/sys/rekey/backup'", "if", "recovery_key", ":", "api_path", "=", "'/v1/sys/rekey-recovery-key/backup'", "response", "=", "self", ".", "_adapter", ".", "get", ...
Retrieve the backup copy of PGP-encrypted unseal keys. The returned value is the nonce of the rekey operation and a map of PGP key fingerprint to hex-encoded PGP-encrypted key. Supported methods: PUT: /sys/rekey/backup. Produces: 200 application/json PUT: /sys/rekey-recovery-key/backup. Produces: 200 application/json :param recovery_key: If true, send requests to "rekey-recovery-key" instead of "rekey" api path. :type recovery_key: bool :return: The JSON response of the request. :rtype: dict
[ "Retrieve", "the", "backup", "copy", "of", "PGP", "-", "encrypted", "unseal", "keys", "." ]
python
train
RJT1990/pyflux
pyflux/ssm/dynlin.py
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/dynlin.py#L74-L92
def _forecast_model(self,beta,Z,h): """ Creates forecasted states and variances Parameters ---------- beta : np.ndarray Contains untransformed starting values for latent variables Returns ---------- a : np.ndarray Forecasted states P : np.ndarray Variance of forecasted states """ T, _, R, Q, H = self._ss_matrices(beta) return dl_univariate_kalman_fcst(self.data,Z,H,T,Q,R,0.0,h)
[ "def", "_forecast_model", "(", "self", ",", "beta", ",", "Z", ",", "h", ")", ":", "T", ",", "_", ",", "R", ",", "Q", ",", "H", "=", "self", ".", "_ss_matrices", "(", "beta", ")", "return", "dl_univariate_kalman_fcst", "(", "self", ".", "data", ",",...
Creates forecasted states and variances Parameters ---------- beta : np.ndarray Contains untransformed starting values for latent variables Returns ---------- a : np.ndarray Forecasted states P : np.ndarray Variance of forecasted states
[ "Creates", "forecasted", "states", "and", "variances" ]
python
train
StackStorm/pybind
pybind/slxos/v17r_1_01a/routing_system/route_map/content/set_/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/routing_system/route_map/content/set_/__init__.py#L527-L550
def _set_automatic_tag(self, v, load=False): """ Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_automatic_tag() directly. YANG Description: Automatically compute TAG value """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=automatic_tag.automatic_tag, is_container='container', presence=False, yang_name="automatic-tag", rest_name="automatic-tag", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Automatically compute TAG value', u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ip-policy', defining_module='brocade-ip-policy', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """automatic_tag must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=automatic_tag.automatic_tag, is_container='container', presence=False, yang_name="automatic-tag", rest_name="automatic-tag", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Automatically compute TAG value', u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ip-policy', defining_module='brocade-ip-policy', yang_type='container', is_config=True)""", }) self.__automatic_tag = t if hasattr(self, '_set'): self._set()
[ "def", "_set_automatic_tag", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "...
Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_automatic_tag() directly. YANG Description: Automatically compute TAG value
[ "Setter", "method", "for", "automatic_tag", "mapped", "from", "YANG", "variable", "/", "routing_system", "/", "route_map", "/", "content", "/", "set", "/", "automatic_tag", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "con...
python
train
libtcod/python-tcod
tcod/libtcodpy.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1909-L1913
def console_load_xp(con: tcod.console.Console, filename: str) -> bool: """Update a console from a REXPaint `.xp` file.""" return bool( lib.TCOD_console_load_xp(_console(con), filename.encode("utf-8")) )
[ "def", "console_load_xp", "(", "con", ":", "tcod", ".", "console", ".", "Console", ",", "filename", ":", "str", ")", "->", "bool", ":", "return", "bool", "(", "lib", ".", "TCOD_console_load_xp", "(", "_console", "(", "con", ")", ",", "filename", ".", "...
Update a console from a REXPaint `.xp` file.
[ "Update", "a", "console", "from", "a", "REXPaint", ".", "xp", "file", "." ]
python
train
globocom/GloboNetworkAPI-client-python
networkapiclient/Interface.py
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Interface.py#L41-L72
def listar_por_equipamento(self, id_equipamento): """List all interfaces of an equipment. :param id_equipamento: Equipment identifier. :return: Dictionary with the following: :: {'interface': [{'protegida': < protegida >, 'nome': < nome >, 'id_ligacao_front': < id_ligacao_front >, 'id_equipamento': < id_equipamento >, 'id': < id >, 'descricao': < descricao >, 'id_ligacao_back': < id_ligacao_back >}, ... other interfaces ...]} :raise InvalidParameterError: Equipment identifier is invalid or none. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response. """ if not is_valid_int_param(id_equipamento): raise InvalidParameterError( u'Equipment id is invalid or was not informed.') url = 'interface/equipamento/' + str(id_equipamento) + '/' code, map = self.submit(None, 'GET', url) key = 'interface' return get_list_map(self.response(code, map, [key]), key)
[ "def", "listar_por_equipamento", "(", "self", ",", "id_equipamento", ")", ":", "if", "not", "is_valid_int_param", "(", "id_equipamento", ")", ":", "raise", "InvalidParameterError", "(", "u'Equipment id is invalid or was not informed.'", ")", "url", "=", "'interface/equipa...
List all interfaces of an equipment. :param id_equipamento: Equipment identifier. :return: Dictionary with the following: :: {'interface': [{'protegida': < protegida >, 'nome': < nome >, 'id_ligacao_front': < id_ligacao_front >, 'id_equipamento': < id_equipamento >, 'id': < id >, 'descricao': < descricao >, 'id_ligacao_back': < id_ligacao_back >}, ... other interfaces ...]} :raise InvalidParameterError: Equipment identifier is invalid or none. :raise DataBaseError: Networkapi failed to access the database. :raise XMLError: Networkapi failed to generate the XML response.
[ "List", "all", "interfaces", "of", "an", "equipment", "." ]
python
train
miguelgrinberg/python-socketio
socketio/base_manager.py
https://github.com/miguelgrinberg/python-socketio/blob/c0c1bf8d21e3597389b18938550a0724dd9676b7/socketio/base_manager.py#L116-L125
def get_rooms(self, sid, namespace): """Return the rooms a client is in.""" r = [] try: for room_name, room in six.iteritems(self.rooms[namespace]): if room_name is not None and sid in room and room[sid]: r.append(room_name) except KeyError: pass return r
[ "def", "get_rooms", "(", "self", ",", "sid", ",", "namespace", ")", ":", "r", "=", "[", "]", "try", ":", "for", "room_name", ",", "room", "in", "six", ".", "iteritems", "(", "self", ".", "rooms", "[", "namespace", "]", ")", ":", "if", "room_name", ...
Return the rooms a client is in.
[ "Return", "the", "rooms", "a", "client", "is", "in", "." ]
python
train
genepattern/genepattern-python
gp/core.py
https://github.com/genepattern/genepattern-python/blob/9478ea65362b91c72a94f7300c3de8d710bebb71/gp/core.py#L403-L415
def get_tags(self): """ Returns the tags for the job, querying the server if necessary. """ # Lazily load info if self.info is None: self.get_info() if 'tags' in self.info: return [structure['tag']['tag'] for structure in self.info['tags']] else: return []
[ "def", "get_tags", "(", "self", ")", ":", "# Lazily load info", "if", "self", ".", "info", "is", "None", ":", "self", ".", "get_info", "(", ")", "if", "'tags'", "in", "self", ".", "info", ":", "return", "[", "structure", "[", "'tag'", "]", "[", "'tag...
Returns the tags for the job, querying the server if necessary.
[ "Returns", "the", "tags", "for", "the", "job", "querying", "the", "server", "if", "necessary", "." ]
python
train
monarch-initiative/dipper
dipper/models/assoc/Association.py
https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/models/assoc/Association.py#L250-L279
def make_association_id(definedby, sub, pred, obj, attributes=None): """ A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the string of concatonated values. Subclasses of Assoc can submit an additional array of attributes that will be appeded to the ID. Note this is equivalent to a RDF blank node :param definedby: The (data) resource that provided the annotation :param subject: :param predicate: :param object: :param attributes: :return: """ items_to_hash = [definedby, sub, pred, obj] if attributes is not None and len(attributes) > 0: items_to_hash += attributes items_to_hash = [x for x in items_to_hash if x is not None] assoc_id = ':'.join(('MONARCH', GraphUtils.digest_id('+'.join(items_to_hash)))) assert assoc_id is not None return assoc_id
[ "def", "make_association_id", "(", "definedby", ",", "sub", ",", "pred", ",", "obj", ",", "attributes", "=", "None", ")", ":", "items_to_hash", "=", "[", "definedby", ",", "sub", ",", "pred", ",", "obj", "]", "if", "attributes", "is", "not", "None", "a...
A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the string of concatonated values. Subclasses of Assoc can submit an additional array of attributes that will be appeded to the ID. Note this is equivalent to a RDF blank node :param definedby: The (data) resource that provided the annotation :param subject: :param predicate: :param object: :param attributes: :return:
[ "A", "method", "to", "create", "unique", "identifiers", "for", "OBAN", "-", "style", "associations", "based", "on", "all", "the", "parts", "of", "the", "association", "If", "any", "of", "the", "items", "is", "empty", "or", "None", "it", "will", "convert", ...
python
train
Kozea/cairocffi
cairocffi/surfaces.py
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/surfaces.py#L397-L411
def get_font_options(self): """Retrieves the default font rendering options for the surface. This allows display surfaces to report the correct subpixel order for rendering on them, print surfaces to disable hinting of metrics and so forth. The result can then be used with :class:`ScaledFont`. :returns: A new :class:`FontOptions` object. """ font_options = FontOptions() cairo.cairo_surface_get_font_options( self._pointer, font_options._pointer) return font_options
[ "def", "get_font_options", "(", "self", ")", ":", "font_options", "=", "FontOptions", "(", ")", "cairo", ".", "cairo_surface_get_font_options", "(", "self", ".", "_pointer", ",", "font_options", ".", "_pointer", ")", "return", "font_options" ]
Retrieves the default font rendering options for the surface. This allows display surfaces to report the correct subpixel order for rendering on them, print surfaces to disable hinting of metrics and so forth. The result can then be used with :class:`ScaledFont`. :returns: A new :class:`FontOptions` object.
[ "Retrieves", "the", "default", "font", "rendering", "options", "for", "the", "surface", "." ]
python
train
cltk/cltk
cltk/inflection/old_norse/nouns.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/inflection/old_norse/nouns.py#L693-L814
def decline_weak_feminine_noun(ns: str, gs: str, np: str): """ Gives the full declension of weak feminine nouns. >>> decline_weak_feminine_noun("saga", "sögu", "sögur") saga sögu sögu sögu sögur sögur sögum sagna >>> decline_weak_feminine_noun("kona", "konu", "konur") kona konu konu konu konur konur konum kvenna >>> decline_weak_feminine_noun("kirkja", "kirkju", "kirkjur") kirkja kirkju kirkju kirkju kirkjur kirkjur kirkjum kirkna >>> decline_weak_feminine_noun("völva", "völu", "völur") völva völu völu völu völur völur völum völna >>> decline_weak_feminine_noun("speki", "speki", "") speki speki speki speki >>> decline_weak_feminine_noun("reiði", "reiði", "") reiði reiði reiði reiði >>> decline_weak_feminine_noun("elli", "elli", "") elli elli elli elli >>> decline_weak_feminine_noun("frœði", "frœði", "") frœði frœði frœði frœði It is to note that the genitive plural of völva is not attested so the given form is analogously reconstructed. The main pattern is: -a -u -u -u -ur -ur -um -na :param ns: nominative singular :param gs: genitive singular :param np: nominative plural :return: """ if ns[-1] == "i" and gs[-1] == "i" and not np: print(ns) print(ns) print(ns) print(ns) else: # nominative singular print(ns) # accusative singular print(gs) # dative singular print(gs) # genitive singular print(gs) # nominative plural print(np) # accusative plural print(np) # dative plural print(np[:-1]+"m") # genitive plural if ns == "kona": print("kvenna") elif ns[-2] == "v" or ns[-2] == "j": print(ns[:-2]+"na") else: print(ns[:-1]+"na")
[ "def", "decline_weak_feminine_noun", "(", "ns", ":", "str", ",", "gs", ":", "str", ",", "np", ":", "str", ")", ":", "if", "ns", "[", "-", "1", "]", "==", "\"i\"", "and", "gs", "[", "-", "1", "]", "==", "\"i\"", "and", "not", "np", ":", "print",...
Gives the full declension of weak feminine nouns. >>> decline_weak_feminine_noun("saga", "sögu", "sögur") saga sögu sögu sögu sögur sögur sögum sagna >>> decline_weak_feminine_noun("kona", "konu", "konur") kona konu konu konu konur konur konum kvenna >>> decline_weak_feminine_noun("kirkja", "kirkju", "kirkjur") kirkja kirkju kirkju kirkju kirkjur kirkjur kirkjum kirkna >>> decline_weak_feminine_noun("völva", "völu", "völur") völva völu völu völu völur völur völum völna >>> decline_weak_feminine_noun("speki", "speki", "") speki speki speki speki >>> decline_weak_feminine_noun("reiði", "reiði", "") reiði reiði reiði reiði >>> decline_weak_feminine_noun("elli", "elli", "") elli elli elli elli >>> decline_weak_feminine_noun("frœði", "frœði", "") frœði frœði frœði frœði It is to note that the genitive plural of völva is not attested so the given form is analogously reconstructed. The main pattern is: -a -u -u -u -ur -ur -um -na :param ns: nominative singular :param gs: genitive singular :param np: nominative plural :return:
[ "Gives", "the", "full", "declension", "of", "weak", "feminine", "nouns", "." ]
python
train
graphql-python/graphene-django
graphene_django/filter/utils.py
https://github.com/graphql-python/graphene-django/blob/20160113948b4167b61dbdaa477bb301227aac2e/graphene_django/filter/utils.py#L6-L19
def get_filtering_args_from_filterset(filterset_class, type): """ Inspect a FilterSet and produce the arguments to pass to a Graphene Field. These arguments will be available to filter against in the GraphQL """ from ..forms.converter import convert_form_field args = {} for name, filter_field in six.iteritems(filterset_class.base_filters): field_type = convert_form_field(filter_field.field).Argument() field_type.description = filter_field.label args[name] = field_type return args
[ "def", "get_filtering_args_from_filterset", "(", "filterset_class", ",", "type", ")", ":", "from", ".", ".", "forms", ".", "converter", "import", "convert_form_field", "args", "=", "{", "}", "for", "name", ",", "filter_field", "in", "six", ".", "iteritems", "(...
Inspect a FilterSet and produce the arguments to pass to a Graphene Field. These arguments will be available to filter against in the GraphQL
[ "Inspect", "a", "FilterSet", "and", "produce", "the", "arguments", "to", "pass", "to", "a", "Graphene", "Field", ".", "These", "arguments", "will", "be", "available", "to", "filter", "against", "in", "the", "GraphQL" ]
python
train
twisted/vertex
vertex/sigma.py
https://github.com/twisted/vertex/blob/feb591aa1b9a3b2b8fdcf53e4962dad2a0bc38ca/vertex/sigma.py#L518-L551
def selectOptimalChunk(self, peer): """ select an optimal chunk to send to a peer. @return: int(chunkNumber), str(chunkData) if there is data to be sent, otherwise None, None """ # stuff I have have = sets.Set(self.mask.positions(1)) # stuff that this peer wants want = sets.Set(self.peers[peer].mask.positions(0)) exchangeable = have.intersection(want) finalSet = dict.fromkeys(exchangeable, 0) # taking a page from bittorrent, rarest-first for chunkNumber in exchangeable: for otherPeer in self.peers.itervalues(): finalSet[chunkNumber] += not otherPeer.mask[chunkNumber] rarityList = [(rarity, random.random(), chunkNumber) for (chunkNumber, rarity) in finalSet.iteritems()] if not rarityList: return None, None rarityList.sort() chunkNumber = rarityList[-1][-1] # sorted in ascending order of rarity # sanity check assert self.mask[chunkNumber], "I wanted to send a chunk I didn't have" self.file.seek(chunkNumber * CHUNK_SIZE) chunkData = self.file.read(CHUNK_SIZE) self.sha1sums[chunkNumber] = sha.new(chunkData).digest() return chunkNumber, chunkData
[ "def", "selectOptimalChunk", "(", "self", ",", "peer", ")", ":", "# stuff I have", "have", "=", "sets", ".", "Set", "(", "self", ".", "mask", ".", "positions", "(", "1", ")", ")", "# stuff that this peer wants", "want", "=", "sets", ".", "Set", "(", "sel...
select an optimal chunk to send to a peer. @return: int(chunkNumber), str(chunkData) if there is data to be sent, otherwise None, None
[ "select", "an", "optimal", "chunk", "to", "send", "to", "a", "peer", "." ]
python
train
BreakingBytes/simkit
simkit/core/data_readers.py
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/data_readers.py#L243-L310
def load_data(self, filename, *args, **kwargs): """ Load parameters from Excel spreadsheet. :param filename: Name of Excel workbook with data. :type filename: str :returns: Data read from Excel workbook. :rtype: dict """ # workbook read from file workbook = open_workbook(filename, verbosity=True) data = {} # an empty dictionary to store data # iterate through sheets in parameters # iterate through the parameters on each sheet for param, pval in self.parameters.iteritems(): sheet = pval['extras']['sheet'] # get each worksheet from the workbook worksheet = workbook.sheet_by_name(sheet) # split the parameter's range elements prng0, prng1 = pval['extras']['range'] # missing "units", json ``null`` and Python ``None`` all OK! # convert to str from unicode, None to '' (dimensionless) punits = str(pval.get('units') or '') # replace None with empty list if prng0 is None: prng0 = [] if prng1 is None: prng1 = [] # FIXME: Use duck-typing here instead of type-checking! # if both elements in range are `int` then parameter is a cell if isinstance(prng0, int) and isinstance(prng1, int): datum = worksheet.cell_value(prng0, prng1) # if the either element is a `list` then parameter is a slice elif isinstance(prng0, list) and isinstance(prng1, int): datum = worksheet.col_values(prng1, *prng0) elif isinstance(prng0, int) and isinstance(prng1, list): datum = worksheet.row_values(prng0, *prng1) # if both elements are `list` then parameter is 2-D else: datum = [] for col in xrange(prng0[1], prng1[1]): datum.append(worksheet.col_values(col, prng0[0], prng1[0])) # duck typing that datum is real try: npdatum = np.array(datum, dtype=np.float) except ValueError as err: # check for iterable: # if `datum` can't be coerced to float, then it must be # *string* & strings *are* iterables, so don't check! # check for strings: # data must be real or *all* strings! # empty string, None or JSON null also OK # all([]) == True but any([]) == False if not datum: data[param] = None # convert empty to None elif all(isinstance(_, basestring) for _ in datum): data[param] = datum # all str is OK (EG all 'TMY') elif all(not _ for _ in datum): data[param] = None # convert list of empty to None else: raise err # raise ValueError if not all real or str else: data[param] = npdatum * UREG(punits) # FYI: only put one statement into try-except test otherwise # might catch different error than expected. use ``else`` as # option to execute only if exception *not* raised. return data
[ "def", "load_data", "(", "self", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# workbook read from file", "workbook", "=", "open_workbook", "(", "filename", ",", "verbosity", "=", "True", ")", "data", "=", "{", "}", "# an empty di...
Load parameters from Excel spreadsheet. :param filename: Name of Excel workbook with data. :type filename: str :returns: Data read from Excel workbook. :rtype: dict
[ "Load", "parameters", "from", "Excel", "spreadsheet", "." ]
python
train
ihgazni2/elist
elist/elist.py
https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L2506-L2536
def all_continuous_indexes_slices(ol,value): ''' from elist.elist import * ol = [1,"a","a",2,3,"a",4,"a","a","a",5] all_continuous_indexes_slices(ol,"a") ''' rslt = [] length = ol.__len__() cursor = 0 begin = None slice = [] while(cursor < length): cond1 = (ol[cursor] == value) cond2 = (begin == None) if(cond1 & cond2): begin = cursor slice.append(cursor) elif(cond1 & (not(cond2))): slice.append(cursor) elif((not(cond1)) & (not(cond2))): rslt.append(slice) begin = None slice = [] else: pass cursor = cursor + 1 if(slice): rslt.append(slice) else: pass return(rslt)
[ "def", "all_continuous_indexes_slices", "(", "ol", ",", "value", ")", ":", "rslt", "=", "[", "]", "length", "=", "ol", ".", "__len__", "(", ")", "cursor", "=", "0", "begin", "=", "None", "slice", "=", "[", "]", "while", "(", "cursor", "<", "length", ...
from elist.elist import * ol = [1,"a","a",2,3,"a",4,"a","a","a",5] all_continuous_indexes_slices(ol,"a")
[ "from", "elist", ".", "elist", "import", "*", "ol", "=", "[", "1", "a", "a", "2", "3", "a", "4", "a", "a", "a", "5", "]", "all_continuous_indexes_slices", "(", "ol", "a", ")" ]
python
valid
scikit-learn-contrib/hdbscan
hdbscan/validity.py
https://github.com/scikit-learn-contrib/hdbscan/blob/e40ccef139e56e38adf7bd6912cd63efd97598f9/hdbscan/validity.py#L116-L178
def internal_minimum_spanning_tree(mr_distances): """ Compute the 'internal' minimum spanning tree given a matrix of mutual reachability distances. Given a minimum spanning tree the 'internal' graph is the subgraph induced by vertices of degree greater than one. Parameters ---------- mr_distances : array (cluster_size, cluster_size) The pairwise mutual reachability distances, inferred to be the edge weights of a complete graph. Since MSTs are computed per cluster this is the all-points-mutual-reacability for points within a single cluster. Returns ------- internal_nodes : array An array listing the indices of the internal nodes of the MST internal_edges : array (?, 3) An array of internal edges in weighted edge list format; that is an edge is an array of length three listing the two vertices forming the edge and weight of the edge. References ---------- Moulavi, D., Jaskowiak, P.A., Campello, R.J., Zimek, A. and Sander, J., 2014. Density-Based Clustering Validation. In SDM (pp. 839-847). """ single_linkage_data = mst_linkage_core(mr_distances) min_span_tree = single_linkage_data.copy() for index, row in enumerate(min_span_tree[1:], 1): candidates = np.where(isclose(mr_distances[int(row[1])], row[2]))[0] candidates = np.intersect1d(candidates, single_linkage_data[:index, :2].astype( int)) candidates = candidates[candidates != row[1]] assert len(candidates) > 0 row[0] = candidates[0] vertices = np.arange(mr_distances.shape[0])[ np.bincount(min_span_tree.T[:2].flatten().astype(np.intp)) > 1] # A little "fancy" we select from the flattened array reshape back # (Fortran format to get indexing right) and take the product to do an and # then convert back to boolean type. edge_selection = np.prod(np.in1d(min_span_tree.T[:2], vertices).reshape( (min_span_tree.shape[0], 2), order='F'), axis=1).astype(bool) # Density sparseness is not well defined if there are no # internal edges (as per the referenced paper). However # MATLAB code from the original authors simply selects the # largest of *all* the edges in the case that there are # no internal edges, so we do the same here if np.any(edge_selection): # If there are any internal edges, then subselect them out edges = min_span_tree[edge_selection] else: # If there are no internal edges then we want to take the # max over all the edges that exist in the MST, so we simply # do nothing and return all the edges in the MST. edges = min_span_tree.copy() return vertices, edges
[ "def", "internal_minimum_spanning_tree", "(", "mr_distances", ")", ":", "single_linkage_data", "=", "mst_linkage_core", "(", "mr_distances", ")", "min_span_tree", "=", "single_linkage_data", ".", "copy", "(", ")", "for", "index", ",", "row", "in", "enumerate", "(", ...
Compute the 'internal' minimum spanning tree given a matrix of mutual reachability distances. Given a minimum spanning tree the 'internal' graph is the subgraph induced by vertices of degree greater than one. Parameters ---------- mr_distances : array (cluster_size, cluster_size) The pairwise mutual reachability distances, inferred to be the edge weights of a complete graph. Since MSTs are computed per cluster this is the all-points-mutual-reacability for points within a single cluster. Returns ------- internal_nodes : array An array listing the indices of the internal nodes of the MST internal_edges : array (?, 3) An array of internal edges in weighted edge list format; that is an edge is an array of length three listing the two vertices forming the edge and weight of the edge. References ---------- Moulavi, D., Jaskowiak, P.A., Campello, R.J., Zimek, A. and Sander, J., 2014. Density-Based Clustering Validation. In SDM (pp. 839-847).
[ "Compute", "the", "internal", "minimum", "spanning", "tree", "given", "a", "matrix", "of", "mutual", "reachability", "distances", ".", "Given", "a", "minimum", "spanning", "tree", "the", "internal", "graph", "is", "the", "subgraph", "induced", "by", "vertices", ...
python
train
agoragames/leaderboard-python
leaderboard/leaderboard.py
https://github.com/agoragames/leaderboard-python/blob/ec309859b197a751ac0322374b36d134d8c5522f/leaderboard/leaderboard.py#L462-L481
def rank_for_in(self, leaderboard_name, member): ''' Retrieve the rank for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the rank for a member in the leaderboard. ''' if self.order == self.ASC: try: return self.redis_connection.zrank( leaderboard_name, member) + 1 except: return None else: try: return self.redis_connection.zrevrank( leaderboard_name, member) + 1 except: return None
[ "def", "rank_for_in", "(", "self", ",", "leaderboard_name", ",", "member", ")", ":", "if", "self", ".", "order", "==", "self", ".", "ASC", ":", "try", ":", "return", "self", ".", "redis_connection", ".", "zrank", "(", "leaderboard_name", ",", "member", "...
Retrieve the rank for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the rank for a member in the leaderboard.
[ "Retrieve", "the", "rank", "for", "a", "member", "in", "the", "named", "leaderboard", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17r_1_01a/beacon/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17r_1_01a/beacon/__init__.py#L94-L115
def _set_enable(self, v, load=False): """ Setter method for enable, mapped from YANG variable /beacon/enable (container) If this variable is read-only (config: false) in the source YANG file, then _set_enable is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_enable() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=enable.enable, is_container='container', presence=False, yang_name="enable", rest_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Enable Chassis/Interface Beacon', u'action': u'chassis'}}, namespace='urn:brocade.com:mgmt:brocade-beacon', defining_module='brocade-beacon', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """enable must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=enable.enable, is_container='container', presence=False, yang_name="enable", rest_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Enable Chassis/Interface Beacon', u'action': u'chassis'}}, namespace='urn:brocade.com:mgmt:brocade-beacon', defining_module='brocade-beacon', yang_type='container', is_config=True)""", }) self.__enable = t if hasattr(self, '_set'): self._set()
[ "def", "_set_enable", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base", ...
Setter method for enable, mapped from YANG variable /beacon/enable (container) If this variable is read-only (config: false) in the source YANG file, then _set_enable is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_enable() directly.
[ "Setter", "method", "for", "enable", "mapped", "from", "YANG", "variable", "/", "beacon", "/", "enable", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", "file", ...
python
train
zqfang/GSEApy
gseapy/enrichr.py
https://github.com/zqfang/GSEApy/blob/673e9ec1391e3b14d3e8a4353117151fd2cb9345/gseapy/enrichr.py#L302-L352
def run(self): """run enrichr for one sample gene list but multi-libraries""" # set organism self.get_organism() # read input file genes_list = self.parse_genelists() gss = self.parse_genesets() # if gmt self._logger.info("Connecting to Enrichr Server to get latest library names") if len(gss) < 1: sys.stderr.write("Not validated Enrichr library name provided\n") sys.stdout.write("Hint: use get_library_name() to view full list of supported names") sys.exit(1) self.results = pd.DataFrame() for g in gss: if isinstance(g, dict): ## local mode res = self.enrich(g) shortID, self._gs = str(id(g)), "CUSTOM%s"%id(g) if res is None: self._logger.info("No hits return, for gene set: Custom%s"%shortID) continue else: ## online mode self._gs = str(g) self._logger.debug("Start Enrichr using library: %s" % (self._gs)) self._logger.info('Analysis name: %s, Enrichr Library: %s' % (self.descriptions, self._gs)) shortID, res = self.get_results(genes_list) # Remember gene set library used res.insert(0, "Gene_set", self._gs) # Append to master dataframe self.results = self.results.append(res, ignore_index=True, sort=True) self.res2d = res if self._outdir is None: continue self._logger.info('Save file of enrichment results: Job Id:' + str(shortID)) outfile = "%s/%s.%s.%s.reports.txt" % (self.outdir, self._gs, self.descriptions, self.module) self.res2d.to_csv(outfile, index=False, encoding='utf-8', sep="\t") # plotting if not self.__no_plot: msg = barplot(df=res, cutoff=self.cutoff, figsize=self.figsize, top_term=self.__top_term, color='salmon', title=self._gs, ofname=outfile.replace("txt", self.format)) if msg is not None : self._logger.warning(msg) self._logger.info('Done.\n') # clean up tmpdir if self._outdir is None: self._tmpdir.cleanup() return
[ "def", "run", "(", "self", ")", ":", "# set organism", "self", ".", "get_organism", "(", ")", "# read input file", "genes_list", "=", "self", ".", "parse_genelists", "(", ")", "gss", "=", "self", ".", "parse_genesets", "(", ")", "# if gmt", "self", ".", "_...
run enrichr for one sample gene list but multi-libraries
[ "run", "enrichr", "for", "one", "sample", "gene", "list", "but", "multi", "-", "libraries" ]
python
test
raphaelm/django-i18nfield
i18nfield/strings.py
https://github.com/raphaelm/django-i18nfield/blob/fb707931e4498ab1b609eaa0323bb5c3d5f7c7e7/i18nfield/strings.py#L48-L81
def localize(self, lng: str) -> str: """ Evaluate the given string with respect to the locale defined by ``lng``. If no string is available in the currently active language, this will give you the string in the system's default language. If this is unavailable as well, it will give you the string in the first language available. :param lng: A locale code, e.g. ``de``. If you specify a code including a country or region like ``de-AT``, exact matches will be used preferably, but if only a ``de`` or ``de-AT`` translation exists, this might be returned as well. """ if self.data is None: return "" if isinstance(self.data, dict): firstpart = lng.split('-')[0] similar = [l for l in self.data.keys() if (l.startswith(firstpart + "-") or firstpart == l) and l != lng] if self.data.get(lng): return self.data[lng] elif self.data.get(firstpart): return self.data[firstpart] elif similar and any([self.data.get(s) for s in similar]): for s in similar: if self.data.get(s): return self.data.get(s) elif self.data.get(settings.LANGUAGE_CODE): return self.data[settings.LANGUAGE_CODE] elif len(self.data): return list(self.data.items())[0][1] else: return "" else: return str(self.data)
[ "def", "localize", "(", "self", ",", "lng", ":", "str", ")", "->", "str", ":", "if", "self", ".", "data", "is", "None", ":", "return", "\"\"", "if", "isinstance", "(", "self", ".", "data", ",", "dict", ")", ":", "firstpart", "=", "lng", ".", "spl...
Evaluate the given string with respect to the locale defined by ``lng``. If no string is available in the currently active language, this will give you the string in the system's default language. If this is unavailable as well, it will give you the string in the first language available. :param lng: A locale code, e.g. ``de``. If you specify a code including a country or region like ``de-AT``, exact matches will be used preferably, but if only a ``de`` or ``de-AT`` translation exists, this might be returned as well.
[ "Evaluate", "the", "given", "string", "with", "respect", "to", "the", "locale", "defined", "by", "lng", "." ]
python
train
Qiskit/qiskit-terra
qiskit/qasm/node/measure.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/qasm/node/measure.py#L24-L27
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" return "measure " + self.children[0].qasm(prec) + " -> " + \ self.children[1].qasm(prec) + ";"
[ "def", "qasm", "(", "self", ",", "prec", "=", "15", ")", ":", "return", "\"measure \"", "+", "self", ".", "children", "[", "0", "]", ".", "qasm", "(", "prec", ")", "+", "\" -> \"", "+", "self", ".", "children", "[", "1", "]", ".", "qasm", "(", ...
Return the corresponding OPENQASM string.
[ "Return", "the", "corresponding", "OPENQASM", "string", "." ]
python
test
redcanari/canari3
src/canari/entrypoints.py
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/entrypoints.py#L220-L225
def remote_transform(host, transform, input, entity_field, transform_parameter, raw_output, ssl, base_path, soft_limit, hard_limit, verbose): """Runs Canari local transforms in a terminal-friendly fashion.""" from canari.commands.remote_transform import remote_transform remote_transform(host, transform, input, entity_field, transform_parameter, raw_output, ssl, base_path, soft_limit, hard_limit, verbose)
[ "def", "remote_transform", "(", "host", ",", "transform", ",", "input", ",", "entity_field", ",", "transform_parameter", ",", "raw_output", ",", "ssl", ",", "base_path", ",", "soft_limit", ",", "hard_limit", ",", "verbose", ")", ":", "from", "canari", ".", "...
Runs Canari local transforms in a terminal-friendly fashion.
[ "Runs", "Canari", "local", "transforms", "in", "a", "terminal", "-", "friendly", "fashion", "." ]
python
train
iotile/baBLE
tools/release.py
https://github.com/iotile/baBLE/blob/faedca2c70b7fe91ea8ae0c3d8aff6bf843bd9db/tools/release.py#L23-L34
def build_wheel(platform): """Create a wheel""" if platform in ['x86_64', 'i686']: system = 'manylinux1' else: system = 'linux' setuptools.sandbox.run_setup( 'setup.py', ['-q', 'clean', '--all', 'bdist_wheel', '--plat-name', '{}_{}'.format(system, platform)] )
[ "def", "build_wheel", "(", "platform", ")", ":", "if", "platform", "in", "[", "'x86_64'", ",", "'i686'", "]", ":", "system", "=", "'manylinux1'", "else", ":", "system", "=", "'linux'", "setuptools", ".", "sandbox", ".", "run_setup", "(", "'setup.py'", ",",...
Create a wheel
[ "Create", "a", "wheel" ]
python
train
yyuu/botornado
boto/ec2/elb/__init__.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/ec2/elb/__init__.py#L328-L349
def describe_instance_health(self, load_balancer_name, instances=None): """ Get current state of all Instances registered to an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :param instances: The instance ID's of the EC2 instances to return status for. If not provided, the state of all instances will be returned. :rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list of state info for instances in this Load Balancer. """ params = {'LoadBalancerName' : load_balancer_name} if instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)])
[ "def", "describe_instance_health", "(", "self", ",", "load_balancer_name", ",", "instances", "=", "None", ")", ":", "params", "=", "{", "'LoadBalancerName'", ":", "load_balancer_name", "}", "if", "instances", ":", "self", ".", "build_list_params", "(", "params", ...
Get current state of all Instances registered to an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the Load Balancer :type instances: List of strings :param instances: The instance ID's of the EC2 instances to return status for. If not provided, the state of all instances will be returned. :rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list of state info for instances in this Load Balancer.
[ "Get", "current", "state", "of", "all", "Instances", "registered", "to", "an", "Load", "Balancer", "." ]
python
train
gpoulter/fablib
fablib.py
https://github.com/gpoulter/fablib/blob/5d14c4d998f79dd1aa3207063c3d06e30e3e2bf9/fablib.py#L280-L288
def write_version(path, ref=None): """Update version file using git desribe""" with lcd(dirname(path)): version = make_version(ref) if (env.get('full') or not os.path.exists(path) or version != open(path).read().strip()): with open(path, 'w') as out: out.write(version + '\n') return version
[ "def", "write_version", "(", "path", ",", "ref", "=", "None", ")", ":", "with", "lcd", "(", "dirname", "(", "path", ")", ")", ":", "version", "=", "make_version", "(", "ref", ")", "if", "(", "env", ".", "get", "(", "'full'", ")", "or", "not", "os...
Update version file using git desribe
[ "Update", "version", "file", "using", "git", "desribe" ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/utils/io.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L283-L303
def temp_pyfile(src, ext='.py'): """Make a temporary python file, return filename and filehandle. Parameters ---------- src : string or list of strings (no need for ending newlines if list) Source code to be written to the file. ext : optional, string Extension for the generated file. Returns ------- (filename, open filehandle) It is the caller's responsibility to close the open file and unlink it. """ fname = tempfile.mkstemp(ext)[1] f = open(fname,'w') f.write(src) f.flush() return fname, f
[ "def", "temp_pyfile", "(", "src", ",", "ext", "=", "'.py'", ")", ":", "fname", "=", "tempfile", ".", "mkstemp", "(", "ext", ")", "[", "1", "]", "f", "=", "open", "(", "fname", ",", "'w'", ")", "f", ".", "write", "(", "src", ")", "f", ".", "fl...
Make a temporary python file, return filename and filehandle. Parameters ---------- src : string or list of strings (no need for ending newlines if list) Source code to be written to the file. ext : optional, string Extension for the generated file. Returns ------- (filename, open filehandle) It is the caller's responsibility to close the open file and unlink it.
[ "Make", "a", "temporary", "python", "file", "return", "filename", "and", "filehandle", "." ]
python
test
dw/mitogen
ansible_mitogen/connection.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/connection.py#L349-L363
def _connect_mitogen_doas(spec): """ Return ContextService arguments for doas as a first class connection. """ return { 'method': 'doas', 'kwargs': { 'username': spec.remote_user(), 'password': spec.password(), 'python_path': spec.python_path(), 'doas_path': spec.become_exe(), 'connect_timeout': spec.timeout(), 'remote_name': get_remote_name(spec), } }
[ "def", "_connect_mitogen_doas", "(", "spec", ")", ":", "return", "{", "'method'", ":", "'doas'", ",", "'kwargs'", ":", "{", "'username'", ":", "spec", ".", "remote_user", "(", ")", ",", "'password'", ":", "spec", ".", "password", "(", ")", ",", "'python_...
Return ContextService arguments for doas as a first class connection.
[ "Return", "ContextService", "arguments", "for", "doas", "as", "a", "first", "class", "connection", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1140-L1153
def autoencoder_residual_discrete(): """Residual discrete autoencoder model.""" hparams = autoencoder_residual() hparams.bottleneck_bits = 1024 hparams.bottleneck_noise = 0.05 hparams.add_hparam("discretize_warmup_steps", 16000) hparams.add_hparam("bottleneck_kind", "tanh_discrete") hparams.add_hparam("isemhash_noise_dev", 0.5) hparams.add_hparam("isemhash_mix_prob", 0.5) hparams.add_hparam("isemhash_filter_size_multiplier", 2.0) hparams.add_hparam("vq_beta", 0.25) hparams.add_hparam("vq_decay", 0.999) hparams.add_hparam("vq_epsilon", 1e-5) return hparams
[ "def", "autoencoder_residual_discrete", "(", ")", ":", "hparams", "=", "autoencoder_residual", "(", ")", "hparams", ".", "bottleneck_bits", "=", "1024", "hparams", ".", "bottleneck_noise", "=", "0.05", "hparams", ".", "add_hparam", "(", "\"discretize_warmup_steps\"", ...
Residual discrete autoencoder model.
[ "Residual", "discrete", "autoencoder", "model", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/graph/graph.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/graph/graph.py#L298-L306
def log_time_frame(bcbio_log): """The bcbio running time frame. :return: an instance of :class collections.namedtuple: with the following fields: start and end """ output = collections.namedtuple("Time", ["start", "end", "steps"]) bcbio_timings = get_bcbio_timings(bcbio_log) return output(min(bcbio_timings), max(bcbio_timings), bcbio_timings)
[ "def", "log_time_frame", "(", "bcbio_log", ")", ":", "output", "=", "collections", ".", "namedtuple", "(", "\"Time\"", ",", "[", "\"start\"", ",", "\"end\"", ",", "\"steps\"", "]", ")", "bcbio_timings", "=", "get_bcbio_timings", "(", "bcbio_log", ")", "return"...
The bcbio running time frame. :return: an instance of :class collections.namedtuple: with the following fields: start and end
[ "The", "bcbio", "running", "time", "frame", "." ]
python
train
Opentrons/opentrons
api/src/opentrons/hardware_control/simulator.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/simulator.py#L199-L202
def axis_bounds(self) -> Dict[str, Tuple[float, float]]: """ The (minimum, maximum) bounds for each axis. """ return {ax: (0, pos+0.5) for ax, pos in _HOME_POSITION.items() if ax not in 'BC'}
[ "def", "axis_bounds", "(", "self", ")", "->", "Dict", "[", "str", ",", "Tuple", "[", "float", ",", "float", "]", "]", ":", "return", "{", "ax", ":", "(", "0", ",", "pos", "+", "0.5", ")", "for", "ax", ",", "pos", "in", "_HOME_POSITION", ".", "i...
The (minimum, maximum) bounds for each axis.
[ "The", "(", "minimum", "maximum", ")", "bounds", "for", "each", "axis", "." ]
python
train
tcalmant/ipopo
pelix/ipopo/instance.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L628-L665
def safe_callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any """ Calls the registered method in the component for the given event, ignoring raised exceptions :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None """ if self.state == StoredInstance.KILLED: # Invalid state return None try: return self.__callback(event, *args, **kwargs) except FrameworkException as ex: # Important error self._logger.exception( "Critical error calling back %s: %s", self.name, ex ) # Kill the component self._ipopo_service.kill(self.name) if ex.needs_stop: # Framework must be stopped... self._logger.error( "%s said that the Framework must be stopped.", self.name ) self.bundle_context.get_framework().stop() return False except: self._logger.exception( "Component '%s': error calling callback method for event %s", self.name, event, ) return False
[ "def", "safe_callback", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (str, *Any, **Any) -> Any", "if", "self", ".", "state", "==", "StoredInstance", ".", "KILLED", ":", "# Invalid state", "return", "None", "try", "...
Calls the registered method in the component for the given event, ignoring raised exceptions :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None
[ "Calls", "the", "registered", "method", "in", "the", "component", "for", "the", "given", "event", "ignoring", "raised", "exceptions" ]
python
train
gmr/httpbl
httpbl.py
https://github.com/gmr/httpbl/blob/1728720e104748def509b142231c7e48f1f80e8c/httpbl.py#L103-L133
def _decode_response(self, ip_address): """Decodes a HttpBL response IP and return data structure of response data. :param ip_address: IP address to query :type ip_address: str :rtype: dict :raises: ValueError """ # Reverse the IP, reassign the octets to integers vt, ts, days, rc = [int(o) for o in ip_address.split('.')[::-1]] # 127 reflects a valid query response, all others are errors if rc != 127: raise ValueError('Invalid Response Code: {}'.format(rc)) # Build a list of visitor types since one IP can be multiple visitor_types = [] if vt & COMMENT_SPAMMER: visitor_types.append(COMMENT_SPAMMER) if vt & HARVESTER: visitor_types.append(HARVESTER) if vt & SUSPICIOUS: visitor_types.append(SUSPICIOUS) # Return the response dictionary return {'days_since_last_activity': days if vt else None, 'name': None if vt else SEARCH_ENGINES[ts], 'threat_score': ts if vt else None, 'type': visitor_types if vt else [SEARCH_ENGINE]}
[ "def", "_decode_response", "(", "self", ",", "ip_address", ")", ":", "# Reverse the IP, reassign the octets to integers", "vt", ",", "ts", ",", "days", ",", "rc", "=", "[", "int", "(", "o", ")", "for", "o", "in", "ip_address", ".", "split", "(", "'.'", ")"...
Decodes a HttpBL response IP and return data structure of response data. :param ip_address: IP address to query :type ip_address: str :rtype: dict :raises: ValueError
[ "Decodes", "a", "HttpBL", "response", "IP", "and", "return", "data", "structure", "of", "response", "data", "." ]
python
train
ArangoDB-Community/pyArango
pyArango/document.py
https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/document.py#L289-L316
def patch(self, keepNull = True, **docArgs) : """Saves the document by only updating the modified fields. The default behaviour concening the keepNull parameter is the opposite of ArangoDB's default, Null values won't be ignored Use docArgs for things such as waitForSync = True""" if self.URL is None : raise ValueError("Cannot patch a document that was not previously saved") payload = self._store.getPatches() if self.collection._validation['on_save'] : self.validate() if len(payload) > 0 : params = dict(docArgs) params.update({'collection': self.collection.name, 'keepNull' : keepNull}) payload = json.dumps(payload, default=str) r = self.connection.session.patch(self.URL, params = params, data = payload) data = r.json() if (r.status_code == 201 or r.status_code == 202) and "error" not in data : self._rev = data['_rev'] else : raise UpdateError(data['errorMessage'], data) self.modified = False self._store.resetPatch()
[ "def", "patch", "(", "self", ",", "keepNull", "=", "True", ",", "*", "*", "docArgs", ")", ":", "if", "self", ".", "URL", "is", "None", ":", "raise", "ValueError", "(", "\"Cannot patch a document that was not previously saved\"", ")", "payload", "=", "self", ...
Saves the document by only updating the modified fields. The default behaviour concening the keepNull parameter is the opposite of ArangoDB's default, Null values won't be ignored Use docArgs for things such as waitForSync = True
[ "Saves", "the", "document", "by", "only", "updating", "the", "modified", "fields", ".", "The", "default", "behaviour", "concening", "the", "keepNull", "parameter", "is", "the", "opposite", "of", "ArangoDB", "s", "default", "Null", "values", "won", "t", "be", ...
python
train
piface/pifacedigitalio
pifacedigitalio/core.py
https://github.com/piface/pifacedigitalio/blob/d231a82bdb55d5f57f44ba7aec00bfd6c0b9a9d4/pifacedigitalio/core.py#L176-L192
def deinit(bus=DEFAULT_SPI_BUS, chip_select=DEFAULT_SPI_CHIP_SELECT): """Stops interrupts on all boards. Only required when using :func:`digital_read` and :func:`digital_write`. :param bus: SPI bus /dev/spidev<bus>.<chipselect> (default: {bus}) :type bus: int :param chip_select: SPI chip select /dev/spidev<bus>.<chipselect> (default: {chip}) :type chip_select: int """ global _pifacedigitals for pfd in _pifacedigitals: try: pfd.deinit_board() except AttributeError: pass
[ "def", "deinit", "(", "bus", "=", "DEFAULT_SPI_BUS", ",", "chip_select", "=", "DEFAULT_SPI_CHIP_SELECT", ")", ":", "global", "_pifacedigitals", "for", "pfd", "in", "_pifacedigitals", ":", "try", ":", "pfd", ".", "deinit_board", "(", ")", "except", "AttributeErro...
Stops interrupts on all boards. Only required when using :func:`digital_read` and :func:`digital_write`. :param bus: SPI bus /dev/spidev<bus>.<chipselect> (default: {bus}) :type bus: int :param chip_select: SPI chip select /dev/spidev<bus>.<chipselect> (default: {chip}) :type chip_select: int
[ "Stops", "interrupts", "on", "all", "boards", ".", "Only", "required", "when", "using", ":", "func", ":", "digital_read", "and", ":", "func", ":", "digital_write", "." ]
python
train
edeposit/edeposit.amqp.pdfgen
src/edeposit/amqp/pdfgen/__init__.py
https://github.com/edeposit/edeposit.amqp.pdfgen/blob/1022d6d01196f4928d664a71e49273c2d8c67e63/src/edeposit/amqp/pdfgen/__init__.py#L24-L58
def reactToAMQPMessage(message, sender): """ React to given (AMQP) message. `message` is usually expected to be :py:func:`collections.namedtuple` structure filled with all necessary data. Args: message (\*Request class): One of the structures defined in :mod:`.requests`. sender (fn reference): Reference to function for responding - progress monitoring for example. Function takes one parameter, which may be response namedtuple, or string or whatever would be normally returned. Returns: obj: One of the responses in :mod:`.responses`. Raises: ValueError: if bad type of `message` structure is given. """ if _instanceof(message, GenerateContract): return pdf_from_file( # TODO: rewrite to decorator get_contract(**message._asdict()) ) elif _instanceof(message, RST2PDF): return pdf_from_file( gen_pdf(**message._asdict()) ) elif _instanceof(message, GenerateReview): return pdf_from_file( get_review(message) ) raise ValueError( "Unknown type of request: '" + str(type(message)) + "'!" )
[ "def", "reactToAMQPMessage", "(", "message", ",", "sender", ")", ":", "if", "_instanceof", "(", "message", ",", "GenerateContract", ")", ":", "return", "pdf_from_file", "(", "# TODO: rewrite to decorator", "get_contract", "(", "*", "*", "message", ".", "_asdict", ...
React to given (AMQP) message. `message` is usually expected to be :py:func:`collections.namedtuple` structure filled with all necessary data. Args: message (\*Request class): One of the structures defined in :mod:`.requests`. sender (fn reference): Reference to function for responding - progress monitoring for example. Function takes one parameter, which may be response namedtuple, or string or whatever would be normally returned. Returns: obj: One of the responses in :mod:`.responses`. Raises: ValueError: if bad type of `message` structure is given.
[ "React", "to", "given", "(", "AMQP", ")", "message", ".", "message", "is", "usually", "expected", "to", "be", ":", "py", ":", "func", ":", "collections", ".", "namedtuple", "structure", "filled", "with", "all", "necessary", "data", "." ]
python
train
rigetti/pyquil
pyquil/quil.py
https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quil.py#L1024-L1035
def validate_protoquil(program: Program) -> None: """ Ensure that a program is valid ProtoQuil, otherwise raise a ValueError. Protoquil is a subset of Quil which excludes control flow and classical instructions. :param program: The Quil program to validate. """ valid_instruction_types = tuple([Pragma, Declare, Halt, Gate, Reset, ResetQubit, Measurement]) for instr in program.instructions: if not isinstance(instr, valid_instruction_types): # Instructions like MOVE, NOT, JUMP, JUMP-UNLESS will fail here raise ValueError(f"ProtoQuil validation failed: {instr} is not allowed.")
[ "def", "validate_protoquil", "(", "program", ":", "Program", ")", "->", "None", ":", "valid_instruction_types", "=", "tuple", "(", "[", "Pragma", ",", "Declare", ",", "Halt", ",", "Gate", ",", "Reset", ",", "ResetQubit", ",", "Measurement", "]", ")", "for"...
Ensure that a program is valid ProtoQuil, otherwise raise a ValueError. Protoquil is a subset of Quil which excludes control flow and classical instructions. :param program: The Quil program to validate.
[ "Ensure", "that", "a", "program", "is", "valid", "ProtoQuil", "otherwise", "raise", "a", "ValueError", ".", "Protoquil", "is", "a", "subset", "of", "Quil", "which", "excludes", "control", "flow", "and", "classical", "instructions", "." ]
python
train
spyder-ide/spyder
spyder/widgets/arraybuilder.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/arraybuilder.py#L47-L56
def keyPressEvent(self, event): """ Qt override. """ if event.key() in [Qt.Key_Enter, Qt.Key_Return]: self._parent.process_text() if self._parent.is_valid(): self._parent.keyPressEvent(event) else: QLineEdit.keyPressEvent(self, event)
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "key", "(", ")", "in", "[", "Qt", ".", "Key_Enter", ",", "Qt", ".", "Key_Return", "]", ":", "self", ".", "_parent", ".", "process_text", "(", ")", "if", "self", ".", ...
Qt override.
[ "Qt", "override", "." ]
python
train
ladybug-tools/ladybug
ladybug/dt.py
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/dt.py#L73-L79
def from_hoy(cls, hoy, leap_year=False): """Create Ladybug Datetime from an hour of the year. Args: hoy: A float value 0 <= and < 8760 """ return cls.from_moy(round(hoy * 60), leap_year)
[ "def", "from_hoy", "(", "cls", ",", "hoy", ",", "leap_year", "=", "False", ")", ":", "return", "cls", ".", "from_moy", "(", "round", "(", "hoy", "*", "60", ")", ",", "leap_year", ")" ]
Create Ladybug Datetime from an hour of the year. Args: hoy: A float value 0 <= and < 8760
[ "Create", "Ladybug", "Datetime", "from", "an", "hour", "of", "the", "year", "." ]
python
train
bitesofcode/projexui
projexui/widgets/xorbbrowserwidget/xcardwidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xcardwidget.py#L33-L40
def browserWidget( self ): """ Returns the browser widget this card is linked to. :return <XOrbBrowserWidget> || None """ from projexui.widgets.xorbbrowserwidget import XOrbBrowserWidget return projexui.ancestor(self, XOrbBrowserWidget)
[ "def", "browserWidget", "(", "self", ")", ":", "from", "projexui", ".", "widgets", ".", "xorbbrowserwidget", "import", "XOrbBrowserWidget", "return", "projexui", ".", "ancestor", "(", "self", ",", "XOrbBrowserWidget", ")" ]
Returns the browser widget this card is linked to. :return <XOrbBrowserWidget> || None
[ "Returns", "the", "browser", "widget", "this", "card", "is", "linked", "to", ".", ":", "return", "<XOrbBrowserWidget", ">", "||", "None" ]
python
train
jobovy/galpy
galpy/df/quasiisothermaldf.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/quasiisothermaldf.py#L2530-L2532
def _vmomentsurfaceMCIntegrand(vz,vR,vT,R,z,df,sigmaR1,gamma,sigmaz1,mvT,n,m,o): """Internal function that is the integrand for the vmomentsurface mass integration""" return vR**n*vT**m*vz**o*df(R,vR*sigmaR1,vT*sigmaR1*gamma,z,vz*sigmaz1,use_physical=False)*numpy.exp(vR**2./2.+(vT-mvT)**2./2.+vz**2./2.)
[ "def", "_vmomentsurfaceMCIntegrand", "(", "vz", ",", "vR", ",", "vT", ",", "R", ",", "z", ",", "df", ",", "sigmaR1", ",", "gamma", ",", "sigmaz1", ",", "mvT", ",", "n", ",", "m", ",", "o", ")", ":", "return", "vR", "**", "n", "*", "vT", "**", ...
Internal function that is the integrand for the vmomentsurface mass integration
[ "Internal", "function", "that", "is", "the", "integrand", "for", "the", "vmomentsurface", "mass", "integration" ]
python
train
python-rope/rope
rope/refactor/sourceutils.py
https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/sourceutils.py#L67-L87
def get_body_region(defined): """Return the start and end offsets of function body""" scope = defined.get_scope() pymodule = defined.get_module() lines = pymodule.lines node = defined.get_ast() start_line = node.lineno if defined.get_doc() is None: start_line = node.body[0].lineno elif len(node.body) > 1: start_line = node.body[1].lineno start = lines.get_line_start(start_line) scope_start = pymodule.logical_lines.logical_line_in(scope.start) if scope_start[1] >= start_line: # a one-liner! # XXX: what if colon appears in a string start = pymodule.source_code.index(':', start) + 1 while pymodule.source_code[start].isspace(): start += 1 end = min(lines.get_line_end(scope.end) + 1, len(pymodule.source_code)) return start, end
[ "def", "get_body_region", "(", "defined", ")", ":", "scope", "=", "defined", ".", "get_scope", "(", ")", "pymodule", "=", "defined", ".", "get_module", "(", ")", "lines", "=", "pymodule", ".", "lines", "node", "=", "defined", ".", "get_ast", "(", ")", ...
Return the start and end offsets of function body
[ "Return", "the", "start", "and", "end", "offsets", "of", "function", "body" ]
python
train
ungarj/mapchete
mapchete/config.py
https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/config.py#L714-L740
def bounds_from_opts( wkt_geometry=None, point=None, bounds=None, zoom=None, raw_conf=None ): """ Loads the process pyramid of a raw configuration. Parameters ---------- raw_conf : dict Raw mapchete configuration as dictionary. Returns ------- BufferedTilePyramid """ if wkt_geometry: return wkt.loads(wkt_geometry).bounds elif point: x, y = point zoom_levels = get_zoom_levels( process_zoom_levels=raw_conf["zoom_levels"], init_zoom_levels=zoom ) tp = raw_conf_process_pyramid(raw_conf) return tp.tile_from_xy(x, y, max(zoom_levels)).bounds else: return bounds
[ "def", "bounds_from_opts", "(", "wkt_geometry", "=", "None", ",", "point", "=", "None", ",", "bounds", "=", "None", ",", "zoom", "=", "None", ",", "raw_conf", "=", "None", ")", ":", "if", "wkt_geometry", ":", "return", "wkt", ".", "loads", "(", "wkt_ge...
Loads the process pyramid of a raw configuration. Parameters ---------- raw_conf : dict Raw mapchete configuration as dictionary. Returns ------- BufferedTilePyramid
[ "Loads", "the", "process", "pyramid", "of", "a", "raw", "configuration", "." ]
python
valid
vinitkumar/pycrawler
crawler.py
https://github.com/vinitkumar/pycrawler/blob/d3fe6d2da1469fc701c4fe04df88cee9cc8cd9c3/crawler.py#L17-L39
def option_parser(): """Option Parser to give various options.""" usage = ''' $ ./crawler -d5 <url> Here in this case it goes till depth of 5 and url is target URL to start crawling. ''' version = "2.0.0" parser = optparse.OptionParser(usage=usage, version=version) parser.add_option("-l", "--links", action="store_true", default=False, dest="links", help="links for target url") parser.add_option("-d", "--depth", action="store", type="int", default=30, dest="depth", help="Maximum depth traverse") opts, args = parser.parse_args() if len(args) < 1: parser.print_help() raise SystemExit(1) return opts, args
[ "def", "option_parser", "(", ")", ":", "usage", "=", "'''\n $ ./crawler -d5 <url>\n Here in this case it goes till depth of 5 and url is target URL to\n start crawling.\n '''", "version", "=", "\"2.0.0\"", "parser", "=", "optparse", "....
Option Parser to give various options.
[ "Option", "Parser", "to", "give", "various", "options", "." ]
python
train
pantsbuild/pants
src/python/pants/option/option_tracker.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/option_tracker.py#L72-L87
def record_option(self, scope, option, value, rank, deprecation_version=None, details=None): """Records that the given option was set to the given value. :param string scope: scope of the option. :param string option: name of the option. :param string value: value the option was set to. :param int rank: the rank of the option (Eg, RankedValue.HARDCODED), to keep track of where the option came from. :param deprecation_version: Deprecation version for this option. :param string details: optional additional details about how the option was set (eg, the name of a particular config file, if the rank is RankedValue.CONFIG). """ scoped_options = self.option_history_by_scope[scope] if option not in scoped_options: scoped_options[option] = self.OptionHistory() scoped_options[option].record_value(value, rank, deprecation_version, details)
[ "def", "record_option", "(", "self", ",", "scope", ",", "option", ",", "value", ",", "rank", ",", "deprecation_version", "=", "None", ",", "details", "=", "None", ")", ":", "scoped_options", "=", "self", ".", "option_history_by_scope", "[", "scope", "]", "...
Records that the given option was set to the given value. :param string scope: scope of the option. :param string option: name of the option. :param string value: value the option was set to. :param int rank: the rank of the option (Eg, RankedValue.HARDCODED), to keep track of where the option came from. :param deprecation_version: Deprecation version for this option. :param string details: optional additional details about how the option was set (eg, the name of a particular config file, if the rank is RankedValue.CONFIG).
[ "Records", "that", "the", "given", "option", "was", "set", "to", "the", "given", "value", "." ]
python
train
mgedmin/findimports
findimports.py
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L634-L699
def collapseCycles(self): """Create a graph with cycles collapsed. Collapse modules participating in a cycle to a single node. """ # This algorithm determines Strongly Connected Components. Look it up. # It is adapted to suit our data structures. # Phase 0: prepare the graph imports = {} for u in self.modules: imports[u] = set() for v in self.modules[u].imports: if v in self.modules: # skip external dependencies imports[u].add(v) # Phase 1: order the vertices visited = {} for u in self.modules: visited[u] = False order = [] def visit1(u): visited[u] = True for v in imports[u]: if not visited[v]: visit1(v) order.append(u) for u in self.modules: if not visited[u]: visit1(u) order.reverse() # Phase 2: compute the inverse graph revimports = {} for u in self.modules: revimports[u] = set() for u in self.modules: for v in imports[u]: revimports[v].add(u) # Phase 3: determine the strongly connected components components = {} component_of = {} for u in self.modules: visited[u] = False def visit2(u): visited[u] = True component.append(u) for v in revimports[u]: if not visited[v]: visit2(v) for u in order: if not visited[u]: component = [] visit2(u) component.sort() node = ModuleCycle(component) components[node.modname] = node for modname in component: component_of[modname] = node # Phase 4: construct the condensed graph for node in components.values(): for modname in node.modnames: for impname in imports[modname]: other = component_of[impname].modname if other != node.modname: node.imports.add(other) graph = ModuleGraph() graph.modules = components return graph
[ "def", "collapseCycles", "(", "self", ")", ":", "# This algorithm determines Strongly Connected Components. Look it up.", "# It is adapted to suit our data structures.", "# Phase 0: prepare the graph", "imports", "=", "{", "}", "for", "u", "in", "self", ".", "modules", ":", ...
Create a graph with cycles collapsed. Collapse modules participating in a cycle to a single node.
[ "Create", "a", "graph", "with", "cycles", "collapsed", "." ]
python
train
devopshq/crosspm
crosspm/helpers/downloader.py
https://github.com/devopshq/crosspm/blob/c831442ecfaa1d43c66cb148857096cea292c950/crosspm/helpers/downloader.py#L189-L217
def set_duplicated_flag(self): """ For all package set flag duplicated, if it's not unique package :return: """ package_by_name = defaultdict(list) for package1 in self._root_package.all_packages: if package1 is None: continue pkg_name = package1.package_name param_list = self._config.get_fails('unique', {}) params1 = package1.get_params(param_list) for package2 in package_by_name[pkg_name]: params2 = package2.get_params(param_list) for x in param_list: # START HACK for cached archive param1 = params1[x] param2 = params2[x] if isinstance(param1, list): param1 = [str(x) for x in param1] if isinstance(param2, list): param2 = [str(x) for x in param2] # END if str(param1) != str(param2): package1.duplicated = True package2.duplicated = True package_by_name[pkg_name].append(package1)
[ "def", "set_duplicated_flag", "(", "self", ")", ":", "package_by_name", "=", "defaultdict", "(", "list", ")", "for", "package1", "in", "self", ".", "_root_package", ".", "all_packages", ":", "if", "package1", "is", "None", ":", "continue", "pkg_name", "=", "...
For all package set flag duplicated, if it's not unique package :return:
[ "For", "all", "package", "set", "flag", "duplicated", "if", "it", "s", "not", "unique", "package", ":", "return", ":" ]
python
train
saltstack/salt
salt/cloud/clouds/qingcloud.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/qingcloud.py#L476-L521
def list_nodes_full(call=None): ''' Return a list of the instances that are on the provider. CLI Examples: .. code-block:: bash salt-cloud -F my-qingcloud ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) zone = _get_specified_zone() params = { 'action': 'DescribeInstances', 'zone': zone, 'status': ['pending', 'running', 'stopped', 'suspended'], } items = query(params=params) log.debug('Total %s instances found in zone %s', items['total_count'], zone) result = {} if items['total_count'] == 0: return result for node in items['instance_set']: normalized_node = _show_normalized_node(node) node.update(normalized_node) result[node['instance_id']] = node provider = __active_provider_name__ or 'qingcloud' if ':' in provider: comps = provider.split(':') provider = comps[0] __opts__['update_cachedir'] = True __utils__['cloud.cache_node_list'](result, provider, __opts__) return result
[ "def", "list_nodes_full", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_nodes_full function must be called with -f or --function.'", ")", "zone", "=", "_get_specified_zone", "(", ")", "params", ...
Return a list of the instances that are on the provider. CLI Examples: .. code-block:: bash salt-cloud -F my-qingcloud
[ "Return", "a", "list", "of", "the", "instances", "that", "are", "on", "the", "provider", "." ]
python
train
tmr232/Sark
sark/structure.py
https://github.com/tmr232/Sark/blob/bee62879c2aea553a3924d887e2b30f2a6008581/sark/structure.py#L33-L56
def struct_member_error(err, sid, name, offset, size): """Create and format a struct member exception. Args: err: The error value returned from struct member creation sid: The struct id name: The member name offset: Memeber offset size: Member size Returns: A ``SarkErrorAddStructMemeberFailed`` derivative exception, with an informative message. """ exception, msg = STRUCT_ERROR_MAP[err] struct_name = idc.GetStrucName(sid) return exception(('AddStructMember(struct="{}", member="{}", offset={}, size={}) ' 'failed: {}').format( struct_name, name, offset, size, msg ))
[ "def", "struct_member_error", "(", "err", ",", "sid", ",", "name", ",", "offset", ",", "size", ")", ":", "exception", ",", "msg", "=", "STRUCT_ERROR_MAP", "[", "err", "]", "struct_name", "=", "idc", ".", "GetStrucName", "(", "sid", ")", "return", "except...
Create and format a struct member exception. Args: err: The error value returned from struct member creation sid: The struct id name: The member name offset: Memeber offset size: Member size Returns: A ``SarkErrorAddStructMemeberFailed`` derivative exception, with an informative message.
[ "Create", "and", "format", "a", "struct", "member", "exception", "." ]
python
train
halcy/Mastodon.py
mastodon/Mastodon.py
https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L673-L706
def timeline_hashtag(self, hashtag, local=False, max_id=None, min_id=None, since_id=None, limit=None, only_media=False): """ Fetch a timeline of toots with a given hashtag. The hashtag parameter should not contain the leading #. Set `local` to True to retrieve only instance-local tagged posts. Set `only_media` to True to retrieve only statuses with media attachments. Returns a list of `toot dicts`_. """ if hashtag.startswith("#"): raise MastodonIllegalArgumentError("Hashtag parameter should omit leading #") if max_id != None: max_id = self.__unpack_id(max_id) if min_id != None: min_id = self.__unpack_id(min_id) if since_id != None: since_id = self.__unpack_id(since_id) params_initial = locals() if local == False: del params_initial['local'] if only_media == False: del params_initial['only_media'] url = '/api/v1/timelines/tag/{0}'.format(hashtag) params = self.__generate_params(params_initial, ['hashtag']) return self.__api_request('GET', url, params)
[ "def", "timeline_hashtag", "(", "self", ",", "hashtag", ",", "local", "=", "False", ",", "max_id", "=", "None", ",", "min_id", "=", "None", ",", "since_id", "=", "None", ",", "limit", "=", "None", ",", "only_media", "=", "False", ")", ":", "if", "has...
Fetch a timeline of toots with a given hashtag. The hashtag parameter should not contain the leading #. Set `local` to True to retrieve only instance-local tagged posts. Set `only_media` to True to retrieve only statuses with media attachments. Returns a list of `toot dicts`_.
[ "Fetch", "a", "timeline", "of", "toots", "with", "a", "given", "hashtag", ".", "The", "hashtag", "parameter", "should", "not", "contain", "the", "leading", "#", "." ]
python
train
Azure/azure-multiapi-storage-python
azure/multiapi/storage/v2015_04_05/file/fileservice.py
https://github.com/Azure/azure-multiapi-storage-python/blob/bd5482547f993c6eb56fd09070e15c2e9616e440/azure/multiapi/storage/v2015_04_05/file/fileservice.py#L1817-L1925
def get_file_to_stream( self, share_name, directory_name, file_name, stream, start_range=None, end_range=None, range_get_content_md5=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): ''' Downloads a file to a stream, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties and metadata. :param str share_name: Name of existing share. :param str directory_name: The path to the directory. :param str file_name: Name of existing file. :param io.IOBase stream: Opened file/stream to write to. :param int start_range: Start of byte range to use for downloading a section of the file. If no end_range is given, all bytes after the start_range will be downloaded. The start_range and end_range params are inclusive. Ex: start_range=0, end_range=511 will download first 512 bytes of file. :param int end_range: End of byte range to use for downloading a section of the file. If end_range is given, start_range must be provided. The start_range and end_range params are inclusive. Ex: start_range=0, end_range=511 will download first 512 bytes of file. :param bool range_get_content_md5: When this header is set to True and specified together with the Range header, the service returns the MD5 hash for the range, as long as the range is less than or equal to 4 MB in size. :param progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the file if known. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Set to 1 to download the file sequentially. Set to 2 or greater if you want to download a file larger than 64MB in chunks. If the file size does not exceed 64MB it will be downloaded in one chunk. :param int max_retries: Number of times to retry download of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. :return: A File with properties and metadata. :rtype: :class:`~azure.storage.file.models.File` ''' _validate_not_none('share_name', share_name) _validate_not_none('file_name', file_name) _validate_not_none('stream', stream) if sys.version_info >= (3,) and max_connections > 1 and not stream.seekable(): raise ValueError(_ERROR_PARALLEL_NOT_SEEKABLE) # Only get properties if parallelism will actually be used file_size = None if max_connections > 1 and range_get_content_md5 is None: file = self.get_file_properties(share_name, directory_name, file_name, timeout=timeout) file_size = file.properties.content_length # If file size is large, use parallel download if file_size >= self.MAX_SINGLE_GET_SIZE: _download_file_chunks( self, share_name, directory_name, file_name, file_size, self.MAX_CHUNK_GET_SIZE, start_range, end_range, stream, max_connections, max_retries, retry_wait, progress_callback, timeout ) return file # If parallelism is off or the file is small, do a single download download_size = _get_download_size(start_range, end_range, file_size) if progress_callback: progress_callback(0, download_size) file = self._get_file( share_name, directory_name, file_name, start_range=start_range, end_range=end_range, range_get_content_md5=range_get_content_md5, timeout=timeout) if file.content is not None: stream.write(file.content) if progress_callback: download_size = len(file.content) progress_callback(download_size, download_size) file.content = None # Clear file content since output has been written to user stream return file
[ "def", "get_file_to_stream", "(", "self", ",", "share_name", ",", "directory_name", ",", "file_name", ",", "stream", ",", "start_range", "=", "None", ",", "end_range", "=", "None", ",", "range_get_content_md5", "=", "None", ",", "progress_callback", "=", "None",...
Downloads a file to a stream, with automatic chunking and progress notifications. Returns an instance of :class:`File` with properties and metadata. :param str share_name: Name of existing share. :param str directory_name: The path to the directory. :param str file_name: Name of existing file. :param io.IOBase stream: Opened file/stream to write to. :param int start_range: Start of byte range to use for downloading a section of the file. If no end_range is given, all bytes after the start_range will be downloaded. The start_range and end_range params are inclusive. Ex: start_range=0, end_range=511 will download first 512 bytes of file. :param int end_range: End of byte range to use for downloading a section of the file. If end_range is given, start_range must be provided. The start_range and end_range params are inclusive. Ex: start_range=0, end_range=511 will download first 512 bytes of file. :param bool range_get_content_md5: When this header is set to True and specified together with the Range header, the service returns the MD5 hash for the range, as long as the range is less than or equal to 4 MB in size. :param progress_callback: Callback for progress with signature function(current, total) where current is the number of bytes transfered so far, and total is the size of the file if known. :type progress_callback: callback function in format of func(current, total) :param int max_connections: Set to 1 to download the file sequentially. Set to 2 or greater if you want to download a file larger than 64MB in chunks. If the file size does not exceed 64MB it will be downloaded in one chunk. :param int max_retries: Number of times to retry download of file chunk if an error occurs. :param int retry_wait: Sleep time in secs between retries. :param int timeout: The timeout parameter is expressed in seconds. This method may make multiple calls to the Azure service and the timeout will apply to each call individually. :return: A File with properties and metadata. :rtype: :class:`~azure.storage.file.models.File`
[ "Downloads", "a", "file", "to", "a", "stream", "with", "automatic", "chunking", "and", "progress", "notifications", ".", "Returns", "an", "instance", "of", ":", "class", ":", "File", "with", "properties", "and", "metadata", "." ]
python
train
SatelliteQE/nailgun
nailgun/entities.py
https://github.com/SatelliteQE/nailgun/blob/c36d8c20862e87bf6975bd48ac1ca40a9e634eaa/nailgun/entities.py#L2319-L2326
def create_payload(self): """Reset ``errata_id`` from DB ID to ``errata_id``.""" payload = super(ContentViewFilterRule, self).create_payload() if 'errata_id' in payload: if not hasattr(self.errata, 'errata_id'): self.errata = self.errata.read() payload['errata_id'] = self.errata.errata_id return payload
[ "def", "create_payload", "(", "self", ")", ":", "payload", "=", "super", "(", "ContentViewFilterRule", ",", "self", ")", ".", "create_payload", "(", ")", "if", "'errata_id'", "in", "payload", ":", "if", "not", "hasattr", "(", "self", ".", "errata", ",", ...
Reset ``errata_id`` from DB ID to ``errata_id``.
[ "Reset", "errata_id", "from", "DB", "ID", "to", "errata_id", "." ]
python
train
joke2k/faker
faker/providers/address/ko_KR/__init__.py
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/address/ko_KR/__init__.py#L346-L351
def town(self): """ :example 가나동 """ pattern = self.random_element(self.town_formats) return self.generator.parse(pattern)
[ "def", "town", "(", "self", ")", ":", "pattern", "=", "self", ".", "random_element", "(", "self", ".", "town_formats", ")", "return", "self", ".", "generator", ".", "parse", "(", "pattern", ")" ]
:example 가나동
[ ":", "example", "가나동" ]
python
train
proycon/pynlpl
pynlpl/datatypes.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L196-L198
def randomprune(self,n): """prune down to n items at random, disregarding their score""" self.data = random.sample(self.data, n)
[ "def", "randomprune", "(", "self", ",", "n", ")", ":", "self", ".", "data", "=", "random", ".", "sample", "(", "self", ".", "data", ",", "n", ")" ]
prune down to n items at random, disregarding their score
[ "prune", "down", "to", "n", "items", "at", "random", "disregarding", "their", "score" ]
python
train
lucastheis/django-publications
publications/models/publication.py
https://github.com/lucastheis/django-publications/blob/5a75cf88cf794937711b6850ff2acb07fe005f08/publications/models/publication.py#L108-L207
def _produce_author_lists(self): """ Parse authors string to create lists of authors. """ # post-process author names self.authors = self.authors.replace(', and ', ', ') self.authors = self.authors.replace(',and ', ', ') self.authors = self.authors.replace(' and ', ', ') self.authors = self.authors.replace(';', ',') # list of authors self.authors_list = [author.strip() for author in self.authors.split(',')] # simplified representation of author names self.authors_list_simple = [] # author names represented as a tuple of given and family name self.authors_list_split = [] # tests if title already ends with a punctuation mark self.title_ends_with_punct = self.title[-1] in ['.', '!', '?'] \ if len(self.title) > 0 else False suffixes = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', "Jr.", "Sr."] prefixes = ['Dr.'] prepositions = ['van', 'von', 'der', 'de', 'den'] # further post-process author names for i, author in enumerate(self.authors_list): if author == '': continue names = author.split(' ') # check if last string contains initials if (len(names[-1]) <= 3) \ and names[-1] not in suffixes \ and all(c in ascii_uppercase for c in names[-1]): # turn "Gauss CF" into "C. F. Gauss" names = [c + '.' for c in names[-1]] + names[:-1] # number of suffixes num_suffixes = 0 for name in names[::-1]: if name in suffixes: num_suffixes += 1 else: break # abbreviate names for j, name in enumerate(names[:-1 - num_suffixes]): # don't try to abbreviate these if j == 0 and name in prefixes: continue if j > 0 and name in prepositions: continue if (len(name) > 2) or (len(name) and (name[-1] != '.')): k = name.find('-') if 0 < k + 1 < len(name): # take care of dash names[j] = name[0] + '.-' + name[k + 1] + '.' else: names[j] = name[0] + '.' if len(names): self.authors_list[i] = ' '.join(names) # create simplified/normalized representation of author name if len(names) > 1: for name in names[0].split('-'): name_simple = self.simplify_name(' '.join([name, names[-1]])) self.authors_list_simple.append(name_simple) else: self.authors_list_simple.append(self.simplify_name(names[0])) # number of prepositions num_prepositions = 0 for name in names: if name in prepositions: num_prepositions += 1 # splitting point sp = 1 + num_suffixes + num_prepositions self.authors_list_split.append( (' '.join(names[:-sp]), ' '.join(names[-sp:]))) # list of authors in BibTex format self.authors_bibtex = ' and '.join(self.authors_list) # overwrite authors string if len(self.authors_list) > 2: self.authors = ', and '.join([ ', '.join(self.authors_list[:-1]), self.authors_list[-1]]) elif len(self.authors_list) > 1: self.authors = ' and '.join(self.authors_list) else: self.authors = self.authors_list[0]
[ "def", "_produce_author_lists", "(", "self", ")", ":", "# post-process author names", "self", ".", "authors", "=", "self", ".", "authors", ".", "replace", "(", "', and '", ",", "', '", ")", "self", ".", "authors", "=", "self", ".", "authors", ".", "replace",...
Parse authors string to create lists of authors.
[ "Parse", "authors", "string", "to", "create", "lists", "of", "authors", "." ]
python
valid
AndresMWeber/Nomenclate
nomenclate/core/formatter.py
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/formatter.py#L88-L111
def validate_matched_parenthesis(cls, format_target): """ Adapted from https://stackoverflow.com/questions/6701853/parentheses-pairing-issue :param format_order: :return: """ iparens = iter('(){}[]<>') parens = dict(zip(iparens, iparens)) closing = parens.values() def balanced(astr): stack = [] for c in astr: d = parens.get(c, None) if d: stack.append(d) elif c in closing: if not stack or c != stack.pop(): return False return not stack if format_target: if not balanced(format_target): raise exceptions.BalanceError("Format string has unmatching parentheses.")
[ "def", "validate_matched_parenthesis", "(", "cls", ",", "format_target", ")", ":", "iparens", "=", "iter", "(", "'(){}[]<>'", ")", "parens", "=", "dict", "(", "zip", "(", "iparens", ",", "iparens", ")", ")", "closing", "=", "parens", ".", "values", "(", ...
Adapted from https://stackoverflow.com/questions/6701853/parentheses-pairing-issue :param format_order: :return:
[ "Adapted", "from", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "6701853", "/", "parentheses", "-", "pairing", "-", "issue" ]
python
train
CalebBell/thermo
thermo/utils.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L3446-L3483
def property_derivative_P(self, T, P, zs, ws, order=1): r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition, of a given order. Methods found valid by `select_valid_methods` are attempted until a method succeeds. If no methods are valid and succeed, None is returned. Calls `calculate_derivative_P` internally to perform the actual calculation. .. math:: \text{derivative} = \frac{d (\text{property})}{d P}|_{T, z} Parameters ---------- T : float Temperature at which to calculate the derivative, [K] P : float Pressure at which to calculate the derivative, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] order : int Order of the derivative, >= 1 Returns ------- d_prop_d_P_at_T : float Calculated derivative property, [`units/Pa^order`] ''' sorted_valid_methods = self.select_valid_methods(T, P, zs, ws) for method in sorted_valid_methods: try: return self.calculate_derivative_P(P, T, zs, ws, method, order) except: pass return None
[ "def", "property_derivative_P", "(", "self", ",", "T", ",", "P", ",", "zs", ",", "ws", ",", "order", "=", "1", ")", ":", "sorted_valid_methods", "=", "self", ".", "select_valid_methods", "(", "T", ",", "P", ",", "zs", ",", "ws", ")", "for", "method",...
r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition, of a given order. Methods found valid by `select_valid_methods` are attempted until a method succeeds. If no methods are valid and succeed, None is returned. Calls `calculate_derivative_P` internally to perform the actual calculation. .. math:: \text{derivative} = \frac{d (\text{property})}{d P}|_{T, z} Parameters ---------- T : float Temperature at which to calculate the derivative, [K] P : float Pressure at which to calculate the derivative, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] order : int Order of the derivative, >= 1 Returns ------- d_prop_d_P_at_T : float Calculated derivative property, [`units/Pa^order`]
[ "r", "Method", "to", "calculate", "a", "derivative", "of", "a", "mixture", "property", "with", "respect", "to", "pressure", "at", "constant", "temperature", "and", "composition", "of", "a", "given", "order", ".", "Methods", "found", "valid", "by", "select_vali...
python
valid
BlueBrain/hpcbench
hpcbench/benchmark/ior.py
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/ior.py#L313-L327
def file_mode(self): """onefile, fpp, or both""" fms = self.attributes['file_mode'] eax = set() if isinstance(fms, six.string_types): fms = shlex.split(fms) for fm in fms: if fm == 'both': eax.add('fpp') eax.add('onefile') elif fm in ['fpp', 'onefile']: eax.add(fm) else: raise Exception('Invalid IOR file mode: ' + fm) return eax
[ "def", "file_mode", "(", "self", ")", ":", "fms", "=", "self", ".", "attributes", "[", "'file_mode'", "]", "eax", "=", "set", "(", ")", "if", "isinstance", "(", "fms", ",", "six", ".", "string_types", ")", ":", "fms", "=", "shlex", ".", "split", "(...
onefile, fpp, or both
[ "onefile", "fpp", "or", "both" ]
python
train
timkpaine/pyEX
pyEX/stocks.py
https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/stocks.py#L1029-L1046
def largestTradesDF(symbol, token='', version=''): '''This returns 15 minute delayed, last sale eligible trades. https://iexcloud.io/docs/api/#largest-trades 9:30-4pm ET M-F during regular market hours Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: DataFrame: result ''' df = pd.DataFrame(largestTrades(symbol, token, version)) _toDatetime(df) _reindex(df, 'time') return df
[ "def", "largestTradesDF", "(", "symbol", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "largestTrades", "(", "symbol", ",", "token", ",", "version", ")", ")", "_toDatetime", "(", "df", ")", "_re...
This returns 15 minute delayed, last sale eligible trades. https://iexcloud.io/docs/api/#largest-trades 9:30-4pm ET M-F during regular market hours Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: DataFrame: result
[ "This", "returns", "15", "minute", "delayed", "last", "sale", "eligible", "trades", "." ]
python
valid
ktbyers/netmiko
netmiko/cisco/cisco_ios.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/cisco/cisco_ios.py#L167-L172
def file_md5(self, file_name): """Compute MD5 hash of file.""" file_contents = self._read_file(file_name) file_contents = file_contents + "\n" # Cisco IOS automatically adds this file_contents = file_contents.encode("UTF-8") return hashlib.md5(file_contents).hexdigest()
[ "def", "file_md5", "(", "self", ",", "file_name", ")", ":", "file_contents", "=", "self", ".", "_read_file", "(", "file_name", ")", "file_contents", "=", "file_contents", "+", "\"\\n\"", "# Cisco IOS automatically adds this", "file_contents", "=", "file_contents", "...
Compute MD5 hash of file.
[ "Compute", "MD5", "hash", "of", "file", "." ]
python
train
tanghaibao/jcvi
jcvi/assembly/bambus.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/bambus.py#L22-L99
def scaffold(args): """ %prog scaffold ctgfasta reads1.fasta mapping1.bed reads2.fasta mapping2.bed ... Run BAMBUS on set of contigs, reads and read mappings. """ from jcvi.formats.base import FileMerger from jcvi.formats.bed import mates from jcvi.formats.contig import frombed from jcvi.formats.fasta import join from jcvi.utils.iter import grouper p = OptionParser(scaffold.__doc__) p.set_rclip(rclip=1) p.add_option("--conf", help="BAMBUS configuration file [default: %default]") p.add_option("--prefix", default=False, action="store_true", help="Only keep links between IDs with same prefix [default: %default]") opts, args = p.parse_args(args) nargs = len(args) if nargs < 3 or nargs % 2 != 1: sys.exit(not p.print_help()) rclip = opts.rclip ctgfasta = args[0] duos = list(grouper(args[1:], 2)) trios = [] for fastafile, bedfile in duos: prefix = bedfile.rsplit(".", 1)[0] matefile = prefix + ".mates" matebedfile = matefile + ".bed" if need_update(bedfile, [matefile, matebedfile]): matesopt = [bedfile, "--lib", "--nointra", "--rclip={0}".format(rclip), "--cutoff={0}".format(opts.cutoff)] if opts.prefix: matesopt += ["--prefix"] matefile, matebedfile = mates(matesopt) trios.append((fastafile, matebedfile, matefile)) # Merge the readfasta, bedfile and matefile bbfasta, bbbed, bbmate = "bambus.reads.fasta", "bambus.bed", "bambus.mates" for files, outfile in zip(zip(*trios), (bbfasta, bbbed, bbmate)): FileMerger(files, outfile=outfile).merge(checkexists=True) ctgfile = "bambus.contig" idsfile = "bambus.ids" frombedInputs = [bbbed, ctgfasta, bbfasta] if need_update(frombedInputs, ctgfile): frombed(frombedInputs) inputfasta = "bambus.contigs.fasta" singletonfasta = "bambus.singletons.fasta" cmd = "faSomeRecords {0} {1} ".format(ctgfasta, idsfile) sh(cmd + inputfasta) sh(cmd + singletonfasta + " -exclude") # Run bambus prefix = "bambus" cmd = "goBambus -c {0} -m {1} -o {2}".format(ctgfile, bbmate, prefix) if opts.conf: cmd += " -C {0}".format(opts.conf) sh(cmd) cmd = "untangle -e {0}.evidence.xml -s {0}.out.xml -o {0}.untangle.xml".\ format(prefix) sh(cmd) final = "final" cmd = "printScaff -e {0}.evidence.xml -s {0}.untangle.xml -l {0}.lib " \ "-merge -detail -oo -sum -o {1}".format(prefix, final) sh(cmd) oofile = final + ".oo" join([inputfasta, "--oo={0}".format(oofile)])
[ "def", "scaffold", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "base", "import", "FileMerger", "from", "jcvi", ".", "formats", ".", "bed", "import", "mates", "from", "jcvi", ".", "formats", ".", "contig", "import", "frombed", "from", "jcv...
%prog scaffold ctgfasta reads1.fasta mapping1.bed reads2.fasta mapping2.bed ... Run BAMBUS on set of contigs, reads and read mappings.
[ "%prog", "scaffold", "ctgfasta", "reads1", ".", "fasta", "mapping1", ".", "bed", "reads2", ".", "fasta", "mapping2", ".", "bed", "..." ]
python
train
devision-io/metasdk
metasdk/services/MediaService.py
https://github.com/devision-io/metasdk/blob/1a1af5ceeb8ade843fd656c9c27c8b9ff789fc68/metasdk/services/MediaService.py#L13-L18
def persist_one(self, file_base64_content, filename, extension, mime, is_private=True): """ Загружает файл в облако :type origin: string Принимает значения ROBOT, USER """ return self.__app.api_call("MediaService", "persist_one", locals(), {})
[ "def", "persist_one", "(", "self", ",", "file_base64_content", ",", "filename", ",", "extension", ",", "mime", ",", "is_private", "=", "True", ")", ":", "return", "self", ".", "__app", ".", "api_call", "(", "\"MediaService\"", ",", "\"persist_one\"", ",", "l...
Загружает файл в облако :type origin: string Принимает значения ROBOT, USER
[ "Загружает", "файл", "в", "облако", ":", "type", "origin", ":", "string", "Принимает", "значения", "ROBOT", "USER" ]
python
train
artefactual-labs/agentarchives
agentarchives/atom/client.py
https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/atom/client.py#L114-L141
def _format_notes(self, record): """ Extracts notes from a record and reformats them in a simplified format. """ notes = [] if "notes" in record: for note in record["notes"]: self._append_note_dict_to_list(notes, "general", note) if "language_and_script_notes" in record: self._append_note_dict_to_list( notes, "language_and_script", record["language_and_script_notes"] ) if "publication_notes" in record: self._append_note_dict_to_list( notes, "publication_notes", record["publication_notes"] ) if "physical_characteristics_and_technical_requirements" in record: self._append_note_dict_to_list( notes, "physical_condition", record["physical_characteristics_and_technical_requirements"], ) return notes
[ "def", "_format_notes", "(", "self", ",", "record", ")", ":", "notes", "=", "[", "]", "if", "\"notes\"", "in", "record", ":", "for", "note", "in", "record", "[", "\"notes\"", "]", ":", "self", ".", "_append_note_dict_to_list", "(", "notes", ",", "\"gener...
Extracts notes from a record and reformats them in a simplified format.
[ "Extracts", "notes", "from", "a", "record", "and", "reformats", "them", "in", "a", "simplified", "format", "." ]
python
train
google/prettytensor
prettytensor/pretty_tensor_loss_methods.py
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_loss_methods.py#L222-L257
def sparse_cross_entropy(input_, labels, name=PROVIDED, loss_weight=None, per_example_weights=None): """Calculates the Cross Entropy of input_ vs labels. Args: input_: A rank 2 `Tensor` or a Pretty Tensor holding the logits. labels: A rank 1 integer `Tensor` with class ordinals name: The optional name. loss_weight: A weight to scale the loss. Used when there are multiple losses. per_example_weights: A weighting for each example. Returns: A loss. Raises: ValueError: if labels is None or the type is not float or double. """ if labels is None: raise ValueError('Labels must be set') if per_example_weights is not None: per_example_weights = _convert_and_assert_per_example_weights_compatible( input_, per_example_weights, dtype=input_.dtype) return apply_regression( input_, tf.contrib.nn.deprecated_flipped_sparse_softmax_cross_entropy_with_logits, labels, [], name='%s_loss' % name, loss_weight=loss_weight, per_example_weights=per_example_weights)
[ "def", "sparse_cross_entropy", "(", "input_", ",", "labels", ",", "name", "=", "PROVIDED", ",", "loss_weight", "=", "None", ",", "per_example_weights", "=", "None", ")", ":", "if", "labels", "is", "None", ":", "raise", "ValueError", "(", "'Labels must be set'"...
Calculates the Cross Entropy of input_ vs labels. Args: input_: A rank 2 `Tensor` or a Pretty Tensor holding the logits. labels: A rank 1 integer `Tensor` with class ordinals name: The optional name. loss_weight: A weight to scale the loss. Used when there are multiple losses. per_example_weights: A weighting for each example. Returns: A loss. Raises: ValueError: if labels is None or the type is not float or double.
[ "Calculates", "the", "Cross", "Entropy", "of", "input_", "vs", "labels", "." ]
python
train
couchbase/couchbase-python-client
couchbase/bucket.py
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2406-L2429
def queue_pop(self, key, **kwargs): """ Remove and return the first item queue. :param key: The document ID :param kwargs: Arguments passed to :meth:`mutate_in` :return: A :class:`ValueResult` :raise: :cb_exc:`QueueEmpty` if there are no items in the queue. :raise: :cb_exc:`NotFoundError` if the queue does not exist. """ while True: try: itm = self.list_get(key, -1) except IndexError: raise E.QueueEmpty kwargs['cas'] = itm.cas try: self.list_remove(key, -1, **kwargs) return itm except E.KeyExistsError: pass except IndexError: raise E.QueueEmpty
[ "def", "queue_pop", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")", ":", "while", "True", ":", "try", ":", "itm", "=", "self", ".", "list_get", "(", "key", ",", "-", "1", ")", "except", "IndexError", ":", "raise", "E", ".", "QueueEmpty", "...
Remove and return the first item queue. :param key: The document ID :param kwargs: Arguments passed to :meth:`mutate_in` :return: A :class:`ValueResult` :raise: :cb_exc:`QueueEmpty` if there are no items in the queue. :raise: :cb_exc:`NotFoundError` if the queue does not exist.
[ "Remove", "and", "return", "the", "first", "item", "queue", "." ]
python
train
OnroerendErfgoed/pyramid_urireferencer
pyramid_urireferencer/__init__.py
https://github.com/OnroerendErfgoed/pyramid_urireferencer/blob/c6ee4ba863e32ced304b9cf00f3f5b450757a29a/pyramid_urireferencer/__init__.py#L26-L37
def _add_referencer(registry): """ Gets the Referencer from config and adds it to the registry. """ referencer = registry.queryUtility(IReferencer) if referencer is not None: return referencer ref = registry.settings['urireferencer.referencer'] url = registry.settings['urireferencer.registry_url'] r = DottedNameResolver() registry.registerUtility(r.resolve(ref)(url), IReferencer) return registry.queryUtility(IReferencer)
[ "def", "_add_referencer", "(", "registry", ")", ":", "referencer", "=", "registry", ".", "queryUtility", "(", "IReferencer", ")", "if", "referencer", "is", "not", "None", ":", "return", "referencer", "ref", "=", "registry", ".", "settings", "[", "'urireference...
Gets the Referencer from config and adds it to the registry.
[ "Gets", "the", "Referencer", "from", "config", "and", "adds", "it", "to", "the", "registry", "." ]
python
train
pybel/pybel
src/pybel/struct/filters/node_predicates.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/filters/node_predicates.py#L45-L63
def node_predicate(f: Callable[[BaseEntity], bool]) -> NodePredicate: # noqa: D202 """Tag a node predicate that takes a dictionary to also accept a pair of (BELGraph, node). Apply this as a decorator to a function that takes a single argument, a PyBEL node, to make sure that it can also accept a pair of arguments, a BELGraph and a PyBEL node as well. """ @wraps(f) def wrapped(*args): x = args[0] if isinstance(x, BELGraph): return f(args[1], *args[2:]) # Assume: # if isinstance(x, dict): return f(*args) return wrapped
[ "def", "node_predicate", "(", "f", ":", "Callable", "[", "[", "BaseEntity", "]", ",", "bool", "]", ")", "->", "NodePredicate", ":", "# noqa: D202", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "*", "args", ")", ":", "x", "=", "args", "[", "0...
Tag a node predicate that takes a dictionary to also accept a pair of (BELGraph, node). Apply this as a decorator to a function that takes a single argument, a PyBEL node, to make sure that it can also accept a pair of arguments, a BELGraph and a PyBEL node as well.
[ "Tag", "a", "node", "predicate", "that", "takes", "a", "dictionary", "to", "also", "accept", "a", "pair", "of", "(", "BELGraph", "node", ")", "." ]
python
train
sosy-lab/benchexec
benchexec/util.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/util.py#L371-L376
def copy_all_lines_from_to(inputFile, outputFile): """Copy all lines from an input file object to an output file object.""" currentLine = inputFile.readline() while currentLine: outputFile.write(currentLine) currentLine = inputFile.readline()
[ "def", "copy_all_lines_from_to", "(", "inputFile", ",", "outputFile", ")", ":", "currentLine", "=", "inputFile", ".", "readline", "(", ")", "while", "currentLine", ":", "outputFile", ".", "write", "(", "currentLine", ")", "currentLine", "=", "inputFile", ".", ...
Copy all lines from an input file object to an output file object.
[ "Copy", "all", "lines", "from", "an", "input", "file", "object", "to", "an", "output", "file", "object", "." ]
python
train
sprockets/sprockets-influxdb
sprockets_influxdb.py
https://github.com/sprockets/sprockets-influxdb/blob/cce73481b8f26b02e65e3f9914a9a22eceff3063/sprockets_influxdb.py#L235-L331
def install(url=None, auth_username=None, auth_password=None, submission_interval=None, max_batch_size=None, max_clients=10, base_tags=None, max_buffer_size=None, trigger_size=None, sample_probability=1.0): """Call this to install/setup the InfluxDB client collector. All arguments are optional. :param str url: The InfluxDB API URL. If URL is not specified, the ``INFLUXDB_SCHEME``, ``INFLUXDB_HOST`` and ``INFLUXDB_PORT`` environment variables will be used to construct the base URL. Default: ``http://localhost:8086/write`` :param str auth_username: A username to use for InfluxDB authentication. If not specified, the ``INFLUXDB_USER`` environment variable will be used. Default: ``None`` :param str auth_password: A password to use for InfluxDB authentication. If not specified, the ``INFLUXDB_PASSWORD`` environment variable will be used. Default: ``None`` :param int submission_interval: The maximum number of milliseconds to wait after the last batch submission before submitting a batch that is smaller than ``trigger_size``. Default: ``60000`` :param int max_batch_size: The number of measurements to be submitted in a single HTTP request. Default: ``10000`` :param int max_clients: The number of simultaneous batch submissions that may be made at any given time. Default: ``10`` :param dict base_tags: Default tags that are to be submitted with each measurement. Default: ``None`` :param int max_buffer_size: The maximum number of pending measurements in the buffer before new measurements are discarded. Default: ``25000`` :param int trigger_size: The minimum number of measurements that are in the buffer before a batch can be submitted. Default: ``5000`` :param float sample_probability: Value between 0 and 1.0 specifying the probability that a batch will be submitted (0.25 == 25%) :returns: :data:`True` if the client was installed by this call and :data:`False` otherwise. If ``INFLUXDB_PASSWORD`` is specified as an environment variable, it will be masked in the Python process. """ global _base_tags, _base_url, _credentials, _enabled, _installed, \ _max_batch_size, _max_buffer_size, _max_clients, \ _sample_probability, _timeout, _timeout_interval, _trigger_size _enabled = os.environ.get('INFLUXDB_ENABLED', 'true') == 'true' if not _enabled: LOGGER.warning('Disabling InfluxDB support') return if _installed: LOGGER.warning('InfluxDB client already installed') return False _base_url = url or '{}://{}:{}/write'.format( os.environ.get('INFLUXDB_SCHEME', 'http'), os.environ.get('INFLUXDB_HOST', 'localhost'), os.environ.get('INFLUXDB_PORT', 8086)) _credentials = (auth_username or os.environ.get('INFLUXDB_USER', None), auth_password or os.environ.get('INFLUXDB_PASSWORD', None)) # Don't leave the environment variable out there with the password if os.environ.get('INFLUXDB_PASSWORD'): os.environ['INFLUXDB_PASSWORD'] = \ 'X' * len(os.environ['INFLUXDB_PASSWORD']) # Submission related values _timeout_interval = submission_interval or \ int(os.environ.get('INFLUXDB_INTERVAL', _timeout_interval)) _max_batch_size = max_batch_size or \ int(os.environ.get('INFLUXDB_MAX_BATCH_SIZE', _max_batch_size)) _max_clients = max_clients _max_buffer_size = max_buffer_size or \ int(os.environ.get('INFLUXDB_MAX_BUFFER_SIZE', _max_buffer_size)) _sample_probability = sample_probability or \ float(os.environ.get('INFLUXDB_SAMPLE_PROBABILITY', _sample_probability)) _trigger_size = trigger_size or \ int(os.environ.get('INFLUXDB_TRIGGER_SIZE', _trigger_size)) # Set the base tags if os.environ.get('INFLUXDB_TAG_HOSTNAME', 'true') == 'true': _base_tags.setdefault('hostname', socket.gethostname()) if os.environ.get('ENVIRONMENT'): _base_tags.setdefault('environment', os.environ['ENVIRONMENT']) _base_tags.update(base_tags or {}) # Seed the random number generator for batch sampling random.seed() # Don't let this run multiple times _installed = True LOGGER.info('sprockets_influxdb v%s installed; %i measurements or %.2f ' 'seconds will trigger batch submission', __version__, _trigger_size, _timeout_interval / 1000.0) return True
[ "def", "install", "(", "url", "=", "None", ",", "auth_username", "=", "None", ",", "auth_password", "=", "None", ",", "submission_interval", "=", "None", ",", "max_batch_size", "=", "None", ",", "max_clients", "=", "10", ",", "base_tags", "=", "None", ",",...
Call this to install/setup the InfluxDB client collector. All arguments are optional. :param str url: The InfluxDB API URL. If URL is not specified, the ``INFLUXDB_SCHEME``, ``INFLUXDB_HOST`` and ``INFLUXDB_PORT`` environment variables will be used to construct the base URL. Default: ``http://localhost:8086/write`` :param str auth_username: A username to use for InfluxDB authentication. If not specified, the ``INFLUXDB_USER`` environment variable will be used. Default: ``None`` :param str auth_password: A password to use for InfluxDB authentication. If not specified, the ``INFLUXDB_PASSWORD`` environment variable will be used. Default: ``None`` :param int submission_interval: The maximum number of milliseconds to wait after the last batch submission before submitting a batch that is smaller than ``trigger_size``. Default: ``60000`` :param int max_batch_size: The number of measurements to be submitted in a single HTTP request. Default: ``10000`` :param int max_clients: The number of simultaneous batch submissions that may be made at any given time. Default: ``10`` :param dict base_tags: Default tags that are to be submitted with each measurement. Default: ``None`` :param int max_buffer_size: The maximum number of pending measurements in the buffer before new measurements are discarded. Default: ``25000`` :param int trigger_size: The minimum number of measurements that are in the buffer before a batch can be submitted. Default: ``5000`` :param float sample_probability: Value between 0 and 1.0 specifying the probability that a batch will be submitted (0.25 == 25%) :returns: :data:`True` if the client was installed by this call and :data:`False` otherwise. If ``INFLUXDB_PASSWORD`` is specified as an environment variable, it will be masked in the Python process.
[ "Call", "this", "to", "install", "/", "setup", "the", "InfluxDB", "client", "collector", ".", "All", "arguments", "are", "optional", "." ]
python
train
dpkp/kafka-python
kafka/admin/client.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/admin/client.py#L589-L644
def describe_consumer_groups(self, group_ids, group_coordinator_id=None): """Describe a set of consumer groups. Any errors are immediately raised. :param group_ids: A list of consumer group IDs. These are typically the group names as strings. :param group_coordinator_id: The node_id of the groups' coordinator broker. If set to None, it will query the cluster for each group to find that group's coordinator. Explicitly specifying this can be useful for avoiding extra network round trips if you already know the group coordinator. This is only useful when all the group_ids have the same coordinator, otherwise it will error. Default: None. :return: A list of group descriptions. For now the group descriptions are the raw results from the DescribeGroupsResponse. Long-term, we plan to change this to return namedtuples as well as decoding the partition assignments. """ group_descriptions = [] version = self._matching_api_version(DescribeGroupsRequest) for group_id in group_ids: if group_coordinator_id is not None: this_groups_coordinator_id = group_coordinator_id else: this_groups_coordinator_id = self._find_group_coordinator_id(group_id) if version <= 1: # Note: KAFKA-6788 A potential optimization is to group the # request per coordinator and send one request with a list of # all consumer groups. Java still hasn't implemented this # because the error checking is hard to get right when some # groups error and others don't. request = DescribeGroupsRequest[version](groups=(group_id,)) response = self._send_request_to_node(this_groups_coordinator_id, request) assert len(response.groups) == 1 # TODO need to implement converting the response tuple into # a more accessible interface like a namedtuple and then stop # hardcoding tuple indices here. Several Java examples, # including KafkaAdminClient.java group_description = response.groups[0] error_code = group_description[0] error_type = Errors.for_code(error_code) # Java has the note: KAFKA-6789, we can retry based on the error code if error_type is not Errors.NoError: raise error_type( "Request '{}' failed with response '{}'." .format(request, response)) # TODO Java checks the group protocol type, and if consumer # (ConsumerProtocol.PROTOCOL_TYPE) or empty string, it decodes # the members' partition assignments... that hasn't yet been # implemented here so just return the raw struct results group_descriptions.append(group_description) else: raise NotImplementedError( "Support for DescribeGroups v{} has not yet been added to KafkaAdminClient." .format(version)) return group_descriptions
[ "def", "describe_consumer_groups", "(", "self", ",", "group_ids", ",", "group_coordinator_id", "=", "None", ")", ":", "group_descriptions", "=", "[", "]", "version", "=", "self", ".", "_matching_api_version", "(", "DescribeGroupsRequest", ")", "for", "group_id", "...
Describe a set of consumer groups. Any errors are immediately raised. :param group_ids: A list of consumer group IDs. These are typically the group names as strings. :param group_coordinator_id: The node_id of the groups' coordinator broker. If set to None, it will query the cluster for each group to find that group's coordinator. Explicitly specifying this can be useful for avoiding extra network round trips if you already know the group coordinator. This is only useful when all the group_ids have the same coordinator, otherwise it will error. Default: None. :return: A list of group descriptions. For now the group descriptions are the raw results from the DescribeGroupsResponse. Long-term, we plan to change this to return namedtuples as well as decoding the partition assignments.
[ "Describe", "a", "set", "of", "consumer", "groups", "." ]
python
train
bitlabstudio/django-dashboard-app
dashboard_app/widget_pool.py
https://github.com/bitlabstudio/django-dashboard-app/blob/ed98f2bca91a4ced36d0dd1aa1baee78e989cf64/dashboard_app/widget_pool.py#L93-L96
def unregister_widget(self, widget_cls): """Unregisters the given widget.""" if widget_cls.__name__ in self.widgets: del self.widgets[widget_cls().get_name()]
[ "def", "unregister_widget", "(", "self", ",", "widget_cls", ")", ":", "if", "widget_cls", ".", "__name__", "in", "self", ".", "widgets", ":", "del", "self", ".", "widgets", "[", "widget_cls", "(", ")", ".", "get_name", "(", ")", "]" ]
Unregisters the given widget.
[ "Unregisters", "the", "given", "widget", "." ]
python
test
blockstack/virtualchain
virtualchain/lib/blockchain/bitcoin_blockchain/keys.py
https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/blockchain/bitcoin_blockchain/keys.py#L161-L215
def btc_script_deserialize(script): """ Given a script (hex or bin), decode it into its list of opcodes and data. Return a list of strings and ints. Based on code in pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin """ if isinstance(script, str) and re.match('^[0-9a-fA-F]*$', script): script = binascii.unhexlify(script) # output buffer out = [] pos = 0 while pos < len(script): # next script op... code = encoding.from_byte_to_int(script[pos]) if code == 0: # empty (OP_0) out.append(None) pos += 1 elif code <= 75: # literal numeric constant, followed by a slice of data. # push the slice of data. out.append(script[pos+1:pos+1+code]) pos += 1 + code elif code <= 78: # OP_PUSHDATA1, OP_PUSHDATA2, OP_PUSHDATA4, followed by length and data # push the data itself szsz = pow(2, code - 76) sz = encoding.decode(script[pos+szsz: pos:-1], 256) out.append(script[pos + 1 + szsz : pos + 1 + szsz + sz]) pos += 1 + szsz + sz elif code <= 96: # OP_1NEGATE, OP_RESERVED, OP_1 thru OP_16 # pass -1 for OP_1NEGATE # pass 0 for OP_RESERVED (shouldn't be used anyway) # pass 1 thru 16 for OP_1 thru OP_16 out.append(code - 80) pos += 1 else: # raw opcode out.append(code) pos += 1 # make sure each string is hex'ed out = encoding.json_changebase(out, lambda x: encoding.safe_hexlify(x)) return out
[ "def", "btc_script_deserialize", "(", "script", ")", ":", "if", "isinstance", "(", "script", ",", "str", ")", "and", "re", ".", "match", "(", "'^[0-9a-fA-F]*$'", ",", "script", ")", ":", "script", "=", "binascii", ".", "unhexlify", "(", "script", ")", "#...
Given a script (hex or bin), decode it into its list of opcodes and data. Return a list of strings and ints. Based on code in pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
[ "Given", "a", "script", "(", "hex", "or", "bin", ")", "decode", "it", "into", "its", "list", "of", "opcodes", "and", "data", ".", "Return", "a", "list", "of", "strings", "and", "ints", "." ]
python
train
waqasbhatti/astrobase
astrobase/astrokep.py
https://github.com/waqasbhatti/astrobase/blob/2922a14619d183fb28005fa7d02027ac436f2265/astrobase/astrokep.py#L2085-L2130
def _legendre_dtr(x, y, y_err, legendredeg=10): '''This calculates the residual and chi-sq values for a Legendre function fit. Parameters ---------- x : np.array Array of the independent variable. y : np.array Array of the dependent variable. y_err : np.array Array of errors associated with each `y` value. Used to calculate fit weights. legendredeg : int The degree of the Legendre function to use when fitting. Returns ------- tuple The tuple returned is of the form: (fit_y, fitchisq, fitredchisq) ''' try: p = Legendre.fit(x, y, legendredeg) fit_y = p(x) except Exception as e: fit_y = npzeros_like(y) fitchisq = npsum( ((fit_y - y)*(fit_y - y)) / (y_err*y_err) ) nparams = legendredeg + 1 fitredchisq = fitchisq/(len(y) - nparams - 1) LOGINFO( 'legendre detrend applied. chisq = %.5f, reduced chisq = %.5f' % (fitchisq, fitredchisq) ) return fit_y, fitchisq, fitredchisq
[ "def", "_legendre_dtr", "(", "x", ",", "y", ",", "y_err", ",", "legendredeg", "=", "10", ")", ":", "try", ":", "p", "=", "Legendre", ".", "fit", "(", "x", ",", "y", ",", "legendredeg", ")", "fit_y", "=", "p", "(", "x", ")", "except", "Exception",...
This calculates the residual and chi-sq values for a Legendre function fit. Parameters ---------- x : np.array Array of the independent variable. y : np.array Array of the dependent variable. y_err : np.array Array of errors associated with each `y` value. Used to calculate fit weights. legendredeg : int The degree of the Legendre function to use when fitting. Returns ------- tuple The tuple returned is of the form: (fit_y, fitchisq, fitredchisq)
[ "This", "calculates", "the", "residual", "and", "chi", "-", "sq", "values", "for", "a", "Legendre", "function", "fit", "." ]
python
valid
frascoweb/frasco
frasco/views.py
https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/views.py#L28-L40
def exec_after_request_actions(actions, response, **kwargs): """Executes actions of the "after" and "after_METHOD" groups. A "response" var will be injected in the current context. """ current_context["response"] = response groups = ("after_" + flask.request.method.lower(), "after") try: rv = execute_actions(actions, limit_groups=groups, **kwargs) except ReturnValueException as e: rv = e.value if rv: return rv return response
[ "def", "exec_after_request_actions", "(", "actions", ",", "response", ",", "*", "*", "kwargs", ")", ":", "current_context", "[", "\"response\"", "]", "=", "response", "groups", "=", "(", "\"after_\"", "+", "flask", ".", "request", ".", "method", ".", "lower"...
Executes actions of the "after" and "after_METHOD" groups. A "response" var will be injected in the current context.
[ "Executes", "actions", "of", "the", "after", "and", "after_METHOD", "groups", ".", "A", "response", "var", "will", "be", "injected", "in", "the", "current", "context", "." ]
python
train
awacha/sastool
sastool/misc/easylsq.py
https://github.com/awacha/sastool/blob/deaddfa3002f3f6818697e36139633b7e30427a3/sastool/misc/easylsq.py#L217-L319
def nlsq_fit(x, y, dy, func, params_init, verbose=False, **kwargs): """Perform a non-linear least squares fit Inputs: x: one-dimensional numpy array of the independent variable y: one-dimensional numpy array of the dependent variable dy: absolute error (square root of the variance) of the dependent variable. Either a one-dimensional numpy array or None. In the array case, if any of its elements is NaN, the whole array is treated as NaN (= no weighting) func: a callable with the signature func(x,par1,par2,par3,...) params_init: list or tuple of the first estimates of the parameters par1, par2, par3 etc. to be fitted `verbose`: if various messages useful for debugging should be printed on stdout. other optional keyword arguments will be passed to leastsq(). Outputs: p, dp, statdict where p: list of fitted values of par1, par2 etc. dp: list of estimated errors statdict: dictionary of various statistical parameters: 'DoF': Degrees of freedom 'Chi2': Chi-squared 'Chi2_reduced': Reduced Chi-squared 'R2': Coefficient of determination 'num_func_eval': number of function evaluations during fit. 'func_value': the function evaluated in the best fitting parameters 'message': status message from leastsq() 'error_flag': integer status flag from leastsq() ('ier') 'Covariance': covariance matrix (variances in the diagonal) 'Correlation_coeffs': Pearson's correlation coefficients (usually denoted by 'r') in a matrix. The diagonal is unity. Notes: for the actual fitting, scipy.optimize.leastsq() is used. """ if verbose: t0 = time.monotonic() print("nlsq_fit starting.") else: t0 = 0 func_orig = func params_init_orig = params_init func, params_init = hide_fixedparams(func_orig, params_init_orig) if (dy is None) or (dy == np.nan).sum() > 0 or (dy <= 0).sum() > 0: if verbose: print("nlsq_fit: no weighting") dy = None def objectivefunc(params, x, y, dy): """The target function for leastsq().""" if dy is None: return (func(x, *(params.tolist())) - y) else: return (func(x, *(params.tolist())) - y) / dy # do the fitting if verbose: print("nlsq_fit: now doing the fitting...") t1 = time.monotonic() else: t1 = 0 par, cov, infodict, mesg, ier = leastsq(objectivefunc, np.array(params_init), (x, y, dy), full_output=True, **kwargs) if verbose: print("nlsq_fit: fitting done in %.2f seconds." % (time.monotonic() - t1)) print("nlsq_fit: status from scipy.optimize.leastsq(): %d (%s)" % (ier, mesg)) print("nlsq_fit: extracting statistics.") # test if the covariance was singular (cov is None) if cov is None: cov = np.ones((len(par), len(par))) * np.nan # set it to a NaN matrix # calculate the Pearson's R^2 parameter (coefficient of determination) if dy is None: sserr = np.sum(((func(x, *(par.tolist())) - y)) ** 2) sstot = np.sum((y - np.mean(y)) ** 2) else: sserr = np.sum(((func(x, *(par.tolist())) - y) / dy) ** 2) sstot = np.sum((y - np.mean(y)) ** 2 / dy ** 2) r2 = 1 - sserr / sstot # assemble the statistics dictionary statdict = {'DoF' : len(x) - len(par), # degrees of freedom 'Chi2' : (infodict['fvec'] ** 2).sum(), 'R2' : r2, 'num_func_eval' : infodict['nfev'], 'func_value' : func(x, *(par.tolist())), 'message' : mesg, 'error_flag' : ier, } statdict['Chi2_reduced'] = statdict['Chi2'] / statdict['DoF'] statdict['Covariance'] = cov * statdict['Chi2_reduced'] par, statdict['Covariance'] = resubstitute_fixedparams(par, params_init_orig, statdict['Covariance']) # calculate the estimated errors of the fit parameters dpar = np.sqrt(statdict['Covariance'].diagonal()) # Pearson's correlation coefficients (usually 'r') in a matrix. statdict['Correlation_coeffs'] = statdict['Covariance'] / np.outer(dpar, dpar) if verbose: print("nlsq_fit: returning with results.") print("nlsq_fit: total time: %.2f sec." % (time.monotonic() - t0)) return par, dpar, statdict
[ "def", "nlsq_fit", "(", "x", ",", "y", ",", "dy", ",", "func", ",", "params_init", ",", "verbose", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "verbose", ":", "t0", "=", "time", ".", "monotonic", "(", ")", "print", "(", "\"nlsq_fit start...
Perform a non-linear least squares fit Inputs: x: one-dimensional numpy array of the independent variable y: one-dimensional numpy array of the dependent variable dy: absolute error (square root of the variance) of the dependent variable. Either a one-dimensional numpy array or None. In the array case, if any of its elements is NaN, the whole array is treated as NaN (= no weighting) func: a callable with the signature func(x,par1,par2,par3,...) params_init: list or tuple of the first estimates of the parameters par1, par2, par3 etc. to be fitted `verbose`: if various messages useful for debugging should be printed on stdout. other optional keyword arguments will be passed to leastsq(). Outputs: p, dp, statdict where p: list of fitted values of par1, par2 etc. dp: list of estimated errors statdict: dictionary of various statistical parameters: 'DoF': Degrees of freedom 'Chi2': Chi-squared 'Chi2_reduced': Reduced Chi-squared 'R2': Coefficient of determination 'num_func_eval': number of function evaluations during fit. 'func_value': the function evaluated in the best fitting parameters 'message': status message from leastsq() 'error_flag': integer status flag from leastsq() ('ier') 'Covariance': covariance matrix (variances in the diagonal) 'Correlation_coeffs': Pearson's correlation coefficients (usually denoted by 'r') in a matrix. The diagonal is unity. Notes: for the actual fitting, scipy.optimize.leastsq() is used.
[ "Perform", "a", "non", "-", "linear", "least", "squares", "fit" ]
python
train
saltstack/salt
salt/utils/openstack/neutron.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/neutron.py#L680-L686
def delete_vpnservice(self, vpnservice): ''' Deletes the specified VPN service ''' vpnservice_id = self._find_vpnservice_id(vpnservice) ret = self.network_conn.delete_vpnservice(vpnservice_id) return ret if ret else True
[ "def", "delete_vpnservice", "(", "self", ",", "vpnservice", ")", ":", "vpnservice_id", "=", "self", ".", "_find_vpnservice_id", "(", "vpnservice", ")", "ret", "=", "self", ".", "network_conn", ".", "delete_vpnservice", "(", "vpnservice_id", ")", "return", "ret",...
Deletes the specified VPN service
[ "Deletes", "the", "specified", "VPN", "service" ]
python
train
NarrativeScience/lsi
src/lsi/utils/hosts.py
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L481-L492
def _is_valid_cache(): """ Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool`` """ if not os.path.exists(get_cache_location()): return False modified = os.path.getmtime(get_cache_location()) modified = time.ctime(modified) modified = datetime.strptime(modified, '%a %b %d %H:%M:%S %Y') return datetime.now() - modified <= CACHE_EXPIRATION_INTERVAL
[ "def", "_is_valid_cache", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "get_cache_location", "(", ")", ")", ":", "return", "False", "modified", "=", "os", ".", "path", ".", "getmtime", "(", "get_cache_location", "(", ")", ")", "mo...
Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool``
[ "Returns", "if", "the", "cache", "is", "valid", "(", "exists", "and", "modified", "within", "the", "interval", ")", ".", ":", "return", ":", "Whether", "the", "cache", "is", "valid", ".", ":", "rtype", ":", "bool" ]
python
test
amzn/ion-python
amazon/ion/writer_buffer.py
https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/writer_buffer.py#L122-L129
def add_scalar_value(self, value_buf): """Add a node to the tree containing a scalar value. Args: value_buf (bytearray): bytearray containing the scalar value. """ self.__container_node.add_child(_Node(value_buf)) self.current_container_length += len(value_buf)
[ "def", "add_scalar_value", "(", "self", ",", "value_buf", ")", ":", "self", ".", "__container_node", ".", "add_child", "(", "_Node", "(", "value_buf", ")", ")", "self", ".", "current_container_length", "+=", "len", "(", "value_buf", ")" ]
Add a node to the tree containing a scalar value. Args: value_buf (bytearray): bytearray containing the scalar value.
[ "Add", "a", "node", "to", "the", "tree", "containing", "a", "scalar", "value", "." ]
python
train
nutechsoftware/alarmdecoder
alarmdecoder/devices/usb_device.py
https://github.com/nutechsoftware/alarmdecoder/blob/b0c014089e24455228cb4402cf30ba98157578cd/alarmdecoder/devices/usb_device.py#L324-L339
def write(self, data): """ Writes data to the device. :param data: data to write :type data: string :raises: :py:class:`~alarmdecoder.util.CommError` """ try: self._device.write_data(data) self.on_write(data=data) except FtdiError as err: raise CommError('Error writing to device: {0}'.format(str(err)), err)
[ "def", "write", "(", "self", ",", "data", ")", ":", "try", ":", "self", ".", "_device", ".", "write_data", "(", "data", ")", "self", ".", "on_write", "(", "data", "=", "data", ")", "except", "FtdiError", "as", "err", ":", "raise", "CommError", "(", ...
Writes data to the device. :param data: data to write :type data: string :raises: :py:class:`~alarmdecoder.util.CommError`
[ "Writes", "data", "to", "the", "device", "." ]
python
train
juicer/juicer
juicer/admin/JuicerAdmin.py
https://github.com/juicer/juicer/blob/0c9f0fd59e293d45df6b46e81f675d33221c600d/juicer/admin/JuicerAdmin.py#L439-L461
def sync_repo(self, repo_name=None, envs=[], query='/repositories/'): """ Sync repository in specified environments """ juicer.utils.Log.log_debug( "Sync Repo %s In: %s" % (repo_name, ",".join(envs))) data = { 'override_config': { 'verify_checksum': 'true', 'verify_size': 'true' }, } for env in envs: url = "%s%s-%s/actions/sync/" % (query, repo_name, env) juicer.utils.Log.log_info("%s:", env) _r = self.connectors[env].post(url, data) if _r.status_code == Constants.PULP_POST_ACCEPTED: juicer.utils.Log.log_info("`%s` sync scheduled" % repo_name) else: _r.raise_for_status() return True
[ "def", "sync_repo", "(", "self", ",", "repo_name", "=", "None", ",", "envs", "=", "[", "]", ",", "query", "=", "'/repositories/'", ")", ":", "juicer", ".", "utils", ".", "Log", ".", "log_debug", "(", "\"Sync Repo %s In: %s\"", "%", "(", "repo_name", ",",...
Sync repository in specified environments
[ "Sync", "repository", "in", "specified", "environments" ]
python
train
niklasf/python-chess
chess/pgn.py
https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/pgn.py#L432-L439
def board(self, *, _cache: bool = False) -> chess.Board: """ Gets the starting position of the game. Unless the ``FEN`` header tag is set, this is the default starting position (for the ``Variant``). """ return self.headers.board()
[ "def", "board", "(", "self", ",", "*", ",", "_cache", ":", "bool", "=", "False", ")", "->", "chess", ".", "Board", ":", "return", "self", ".", "headers", ".", "board", "(", ")" ]
Gets the starting position of the game. Unless the ``FEN`` header tag is set, this is the default starting position (for the ``Variant``).
[ "Gets", "the", "starting", "position", "of", "the", "game", "." ]
python
train
zarr-developers/zarr
zarr/core.py
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/core.py#L1635-L1659
def _chunk_setitem(self, chunk_coords, chunk_selection, value, fields=None): """Replace part or whole of a chunk. Parameters ---------- chunk_coords : tuple of ints Indices of the chunk. chunk_selection : tuple of slices Location of region within the chunk. value : scalar or ndarray Value to set. """ if self._synchronizer is None: # no synchronization lock = nolock else: # synchronize on the chunk ckey = self._chunk_key(chunk_coords) lock = self._synchronizer[ckey] with lock: self._chunk_setitem_nosync(chunk_coords, chunk_selection, value, fields=fields)
[ "def", "_chunk_setitem", "(", "self", ",", "chunk_coords", ",", "chunk_selection", ",", "value", ",", "fields", "=", "None", ")", ":", "if", "self", ".", "_synchronizer", "is", "None", ":", "# no synchronization", "lock", "=", "nolock", "else", ":", "# synch...
Replace part or whole of a chunk. Parameters ---------- chunk_coords : tuple of ints Indices of the chunk. chunk_selection : tuple of slices Location of region within the chunk. value : scalar or ndarray Value to set.
[ "Replace", "part", "or", "whole", "of", "a", "chunk", "." ]
python
train
saltstack/salt
salt/cloud/clouds/digitalocean.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1051-L1090
def create_floating_ip(kwargs=None, call=None): ''' Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567' ''' if call != 'function': log.error( 'The create_floating_ip function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'droplet_id' in kwargs: result = query(method='floating_ips', args={'droplet_id': kwargs['droplet_id']}, http_method='post') return result elif 'region' in kwargs: result = query(method='floating_ips', args={'region': kwargs['region']}, http_method='post') return result else: log.error('A droplet_id or region is required.') return False
[ "def", "create_floating_ip", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "log", ".", "error", "(", "'The create_floating_ip function must be called with -f or --function.'", ")", "return", "False", "if", "...
Create a new floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2' salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
[ "Create", "a", "new", "floating", "IP" ]
python
train
fishtown-analytics/dbt
core/dbt/task/runnable.py
https://github.com/fishtown-analytics/dbt/blob/aa4f771df28b307af0cf9fe2fc24432f10a8236b/core/dbt/task/runnable.py#L268-L287
def run(self): """ Run dbt for the query, based on the graph. """ self._runtime_initialize() if len(self._flattened_nodes) == 0: logger.warning("WARNING: Nothing to do. Try checking your model " "configs and model specification args") return [] else: logger.info("") selected_uids = frozenset(n.unique_id for n in self._flattened_nodes) result = self.execute_with_hooks(selected_uids) result.write(self.result_path()) self.task_end_messages(result.results) return result.results
[ "def", "run", "(", "self", ")", ":", "self", ".", "_runtime_initialize", "(", ")", "if", "len", "(", "self", ".", "_flattened_nodes", ")", "==", "0", ":", "logger", ".", "warning", "(", "\"WARNING: Nothing to do. Try checking your model \"", "\"configs and model s...
Run dbt for the query, based on the graph.
[ "Run", "dbt", "for", "the", "query", "based", "on", "the", "graph", "." ]
python
train
escaped/django-video-encoding
video_encoding/tasks.py
https://github.com/escaped/django-video-encoding/blob/50d228dd91aca40acc7f9293808b1e87cb645e5d/video_encoding/tasks.py#L36-L90
def convert_video(fieldfile, force=False): """ Converts a given video file into all defined formats. """ instance = fieldfile.instance field = fieldfile.field filename = os.path.basename(fieldfile.path) source_path = fieldfile.path encoding_backend = get_backend() for options in settings.VIDEO_ENCODING_FORMATS[encoding_backend.name]: video_format, created = Format.objects.get_or_create( object_id=instance.pk, content_type=ContentType.objects.get_for_model(instance), field_name=field.name, format=options['name']) # do not reencode if not requested if video_format.file and not force: continue else: # set progress to 0 video_format.reset_progress() # TODO do not upscale videos _, target_path = tempfile.mkstemp( suffix='_{name}.{extension}'.format(**options)) try: encoding = encoding_backend.encode( source_path, target_path, options['params']) while encoding: try: progress = next(encoding) except StopIteration: break video_format.update_progress(progress) except VideoEncodingError: # TODO handle with more care video_format.delete() os.remove(target_path) continue # save encoded file video_format.file.save( '{filename}_{name}.{extension}'.format(filename=filename, **options), File(open(target_path, mode='rb'))) video_format.update_progress(100) # now we are ready # remove temporary file os.remove(target_path)
[ "def", "convert_video", "(", "fieldfile", ",", "force", "=", "False", ")", ":", "instance", "=", "fieldfile", ".", "instance", "field", "=", "fieldfile", ".", "field", "filename", "=", "os", ".", "path", ".", "basename", "(", "fieldfile", ".", "path", ")...
Converts a given video file into all defined formats.
[ "Converts", "a", "given", "video", "file", "into", "all", "defined", "formats", "." ]
python
train
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L14222-L14239
def get_hw_virt_ex_property(self, property_p): """Returns the value of the specified hardware virtualization boolean property. in property_p of type :class:`HWVirtExPropertyType` Property type to query. return value of type bool Property value. raises :class:`OleErrorInvalidarg` Invalid property. """ if not isinstance(property_p, HWVirtExPropertyType): raise TypeError("property_p can only be an instance of type HWVirtExPropertyType") value = self._call("getHWVirtExProperty", in_p=[property_p]) return value
[ "def", "get_hw_virt_ex_property", "(", "self", ",", "property_p", ")", ":", "if", "not", "isinstance", "(", "property_p", ",", "HWVirtExPropertyType", ")", ":", "raise", "TypeError", "(", "\"property_p can only be an instance of type HWVirtExPropertyType\"", ")", "value",...
Returns the value of the specified hardware virtualization boolean property. in property_p of type :class:`HWVirtExPropertyType` Property type to query. return value of type bool Property value. raises :class:`OleErrorInvalidarg` Invalid property.
[ "Returns", "the", "value", "of", "the", "specified", "hardware", "virtualization", "boolean", "property", "." ]
python
train
ray-project/ray
python/ray/experimental/features.py
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/features.py#L155-L169
def flush_finished_tasks_unsafe(): """This removes some critical state from the Redis shards. In a multitenant environment, this will flush metadata for all jobs, which may be undesirable. This removes all of the metadata for finished tasks. This can be used to try to address out-of-memory errors caused by the accumulation of metadata in Redis. However, after running this command, fault tolerance will most likely not work. """ ray.worker.global_worker.check_connected() for shard_index in range(len(ray.global_state.redis_clients)): _flush_finished_tasks_unsafe_shard(shard_index)
[ "def", "flush_finished_tasks_unsafe", "(", ")", ":", "ray", ".", "worker", ".", "global_worker", ".", "check_connected", "(", ")", "for", "shard_index", "in", "range", "(", "len", "(", "ray", ".", "global_state", ".", "redis_clients", ")", ")", ":", "_flush_...
This removes some critical state from the Redis shards. In a multitenant environment, this will flush metadata for all jobs, which may be undesirable. This removes all of the metadata for finished tasks. This can be used to try to address out-of-memory errors caused by the accumulation of metadata in Redis. However, after running this command, fault tolerance will most likely not work.
[ "This", "removes", "some", "critical", "state", "from", "the", "Redis", "shards", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L8421-L8429
def serial_udb_extra_f15_send(self, sue_ID_VEHICLE_MODEL_NAME, sue_ID_VEHICLE_REGISTRATION, force_mavlink1=False): ''' Backwards compatible version of SERIAL_UDB_EXTRA F15 and F16: format sue_ID_VEHICLE_MODEL_NAME : Serial UDB Extra Model Name Of Vehicle (uint8_t) sue_ID_VEHICLE_REGISTRATION : Serial UDB Extra Registraton Number of Vehicle (uint8_t) ''' return self.send(self.serial_udb_extra_f15_encode(sue_ID_VEHICLE_MODEL_NAME, sue_ID_VEHICLE_REGISTRATION), force_mavlink1=force_mavlink1)
[ "def", "serial_udb_extra_f15_send", "(", "self", ",", "sue_ID_VEHICLE_MODEL_NAME", ",", "sue_ID_VEHICLE_REGISTRATION", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "serial_udb_extra_f15_encode", "(", "sue_ID_VEHICLE_MOD...
Backwards compatible version of SERIAL_UDB_EXTRA F15 and F16: format sue_ID_VEHICLE_MODEL_NAME : Serial UDB Extra Model Name Of Vehicle (uint8_t) sue_ID_VEHICLE_REGISTRATION : Serial UDB Extra Registraton Number of Vehicle (uint8_t)
[ "Backwards", "compatible", "version", "of", "SERIAL_UDB_EXTRA", "F15", "and", "F16", ":", "format" ]
python
train
Opentrons/opentrons
api/src/opentrons/system/nmcli.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/nmcli.py#L570-L592
async def _call(cmd: List[str]) -> Tuple[str, str]: """ Runs the command in a subprocess and returns the captured stdout output. :param cmd: a list of arguments to nmcli. Should not include nmcli itself. :return: (stdout, stderr) """ to_exec = [quote(c) for c in ['nmcli'] + cmd] cmd_str = ' '.join(to_exec) # We have to use a shell invocation here because nmcli will not accept # secrets specified on the command line unless it’s in a shell. The other # option is editing the connection configuration file in /etc/ afterwards # (or using d-bus and pretending to be an auth agent) proc = await as_subprocess.create_subprocess_shell( cmd_str, stdout=as_subprocess.PIPE, stderr=as_subprocess.PIPE) out, err = await proc.communicate() out_str, err_str = out.decode().strip(), err.decode().strip() sanitized = sanitize_args(to_exec) log.debug('{}: stdout={}'.format(' '.join(sanitized), out_str)) if err_str: log.info('{}: stderr={}'.format(' '.join(sanitized), err_str)) return out_str, err_str
[ "async", "def", "_call", "(", "cmd", ":", "List", "[", "str", "]", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "to_exec", "=", "[", "quote", "(", "c", ")", "for", "c", "in", "[", "'nmcli'", "]", "+", "cmd", "]", "cmd_str", "=", "' '...
Runs the command in a subprocess and returns the captured stdout output. :param cmd: a list of arguments to nmcli. Should not include nmcli itself. :return: (stdout, stderr)
[ "Runs", "the", "command", "in", "a", "subprocess", "and", "returns", "the", "captured", "stdout", "output", ".", ":", "param", "cmd", ":", "a", "list", "of", "arguments", "to", "nmcli", ".", "Should", "not", "include", "nmcli", "itself", "." ]
python
train
chrisrink10/basilisp
src/basilisp/lang/runtime.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/runtime.py#L910-L917
def partial(f, *args): """Return a function which is the partial application of f with args.""" @functools.wraps(f) def partial_f(*inner_args): return f(*itertools.chain(args, inner_args)) return partial_f
[ "def", "partial", "(", "f", ",", "*", "args", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "partial_f", "(", "*", "inner_args", ")", ":", "return", "f", "(", "*", "itertools", ".", "chain", "(", "args", ",", "inner_args", ")", ...
Return a function which is the partial application of f with args.
[ "Return", "a", "function", "which", "is", "the", "partial", "application", "of", "f", "with", "args", "." ]
python
test
ewels/MultiQC
multiqc/modules/slamdunk/slamdunk.py
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/slamdunk/slamdunk.py#L364-L433
def slamdunkFilterStatsTable(self): """ Take the parsed filter stats from Slamdunk and add it to a separate table """ headers = OrderedDict() headers['mapped'] = { 'namespace': 'Slamdunk', 'title': '{} Mapped'.format(config.read_count_prefix), 'description': '# mapped reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'YlGn', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['multimapper'] = { 'namespace': 'Slamdunk', 'title': '{} Multimap-Filtered'.format(config.read_count_prefix), 'description': '# multimap-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['nmfiltered'] = { 'namespace': 'Slamdunk', 'title': '{} NM-Filtered'.format(config.read_count_prefix), 'description': '# NM-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['idfiltered'] = { 'namespace': 'Slamdunk', 'title': '{} Identity-Filtered'.format(config.read_count_prefix), 'description': '# identity-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } headers['mqfiltered'] = { 'namespace': 'Slamdunk', 'title': '{} MQ-Filtered'.format(config.read_count_prefix), 'description': '# MQ-filtered reads ({})'.format(config.read_count_desc), 'shared_key': 'read_count', 'min': 0, 'format': '{:,.2f}', 'suffix': config.read_count_prefix, 'scale': 'OrRd', 'modify': lambda x: float(x) * config.read_count_multiplier, } pconfig = { 'id': 'slamdunk_filtering_table', 'min': 0, } self.add_section ( name = 'Filter statistics', anchor = 'slamdunk_filtering', description = 'This table shows the number of reads filtered with each filter criterion during filtering phase of slamdunk.', plot = table.plot(self.slamdunk_data, headers, pconfig) )
[ "def", "slamdunkFilterStatsTable", "(", "self", ")", ":", "headers", "=", "OrderedDict", "(", ")", "headers", "[", "'mapped'", "]", "=", "{", "'namespace'", ":", "'Slamdunk'", ",", "'title'", ":", "'{} Mapped'", ".", "format", "(", "config", ".", "read_count...
Take the parsed filter stats from Slamdunk and add it to a separate table
[ "Take", "the", "parsed", "filter", "stats", "from", "Slamdunk", "and", "add", "it", "to", "a", "separate", "table" ]
python
train
wummel/linkchecker
linkcheck/HtmlParser/htmllib.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/HtmlParser/htmllib.py#L137-L146
def end_element (self, tag): """ Print HTML end element. @param tag: tag name @type tag: string @return: None """ tag = tag.encode(self.encoding, "ignore") self.fd.write("</%s>" % tag)
[ "def", "end_element", "(", "self", ",", "tag", ")", ":", "tag", "=", "tag", ".", "encode", "(", "self", ".", "encoding", ",", "\"ignore\"", ")", "self", ".", "fd", ".", "write", "(", "\"</%s>\"", "%", "tag", ")" ]
Print HTML end element. @param tag: tag name @type tag: string @return: None
[ "Print", "HTML", "end", "element", "." ]
python
train
AustralianSynchrotron/lightflow
lightflow/models/task.py
https://github.com/AustralianSynchrotron/lightflow/blob/dc53dbc1d961e20fb144273baca258060705c03e/lightflow/models/task.py#L208-L295
def _run(self, data, store, signal, context, *, success_callback=None, stop_callback=None, abort_callback=None): """ The internal run method that decorates the public run method. This method makes sure data is being passed to and from the task. Args: data (MultiTaskData): The data object that has been passed from the predecessor task. store (DataStoreDocument): The persistent data store object that allows the task to store data for access across the current workflow run. signal (TaskSignal): The signal object for tasks. It wraps the construction and sending of signals into easy to use methods. context (TaskContext): The context in which the tasks runs. success_callback: This function is called when the task completed successfully stop_callback: This function is called when a StopTask exception was raised. abort_callback: This function is called when an AbortWorkflow exception was raised. Raises: TaskReturnActionInvalid: If the return value of the task is not an Action object. Returns: Action: An Action object containing the data that should be passed on to the next task and optionally a list of successor tasks that should be executed. """ if data is None: data = MultiTaskData() data.add_dataset(self._name) try: if self._callback_init is not None: self._callback_init(data, store, signal, context) result = self.run(data, store, signal, context) if self._callback_finally is not None: self._callback_finally(TaskStatus.Success, data, store, signal, context) if success_callback is not None: success_callback() # the task should be stopped and optionally all successor tasks skipped except StopTask as err: if self._callback_finally is not None: self._callback_finally(TaskStatus.Stopped, data, store, signal, context) if stop_callback is not None: stop_callback(exc=err) result = Action(data, limit=[]) if err.skip_successors else None # the workflow should be stopped immediately except AbortWorkflow as err: if self._callback_finally is not None: self._callback_finally(TaskStatus.Aborted, data, store, signal, context) if abort_callback is not None: abort_callback(exc=err) result = None signal.stop_workflow() # catch any other exception, call the finally callback, then re-raise except: if self._callback_finally is not None: self._callback_finally(TaskStatus.Error, data, store, signal, context) signal.stop_workflow() raise # handle the returned data (either implicitly or as an returned Action object) by # flattening all, possibly modified, input datasets in the MultiTask data down to # a single output dataset. if result is None: data.flatten(in_place=True) data.add_task_history(self.name) return Action(data) else: if not isinstance(result, Action): raise TaskReturnActionInvalid() result.data.flatten(in_place=True) result.data.add_task_history(self.name) return result
[ "def", "_run", "(", "self", ",", "data", ",", "store", ",", "signal", ",", "context", ",", "*", ",", "success_callback", "=", "None", ",", "stop_callback", "=", "None", ",", "abort_callback", "=", "None", ")", ":", "if", "data", "is", "None", ":", "d...
The internal run method that decorates the public run method. This method makes sure data is being passed to and from the task. Args: data (MultiTaskData): The data object that has been passed from the predecessor task. store (DataStoreDocument): The persistent data store object that allows the task to store data for access across the current workflow run. signal (TaskSignal): The signal object for tasks. It wraps the construction and sending of signals into easy to use methods. context (TaskContext): The context in which the tasks runs. success_callback: This function is called when the task completed successfully stop_callback: This function is called when a StopTask exception was raised. abort_callback: This function is called when an AbortWorkflow exception was raised. Raises: TaskReturnActionInvalid: If the return value of the task is not an Action object. Returns: Action: An Action object containing the data that should be passed on to the next task and optionally a list of successor tasks that should be executed.
[ "The", "internal", "run", "method", "that", "decorates", "the", "public", "run", "method", "." ]
python
train
praekeltfoundation/seed-stage-based-messaging
subscriptions/management/commands/remove_duplicate_subscriptions.py
https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/management/commands/remove_duplicate_subscriptions.py#L79-L84
def is_within_limits(self, limit, date, dates): """ Returns True if the difference between date and any value in dates is less than or equal to limit. """ return any((self.second_diff(date, d) <= limit for d in dates))
[ "def", "is_within_limits", "(", "self", ",", "limit", ",", "date", ",", "dates", ")", ":", "return", "any", "(", "(", "self", ".", "second_diff", "(", "date", ",", "d", ")", "<=", "limit", "for", "d", "in", "dates", ")", ")" ]
Returns True if the difference between date and any value in dates is less than or equal to limit.
[ "Returns", "True", "if", "the", "difference", "between", "date", "and", "any", "value", "in", "dates", "is", "less", "than", "or", "equal", "to", "limit", "." ]
python
train
sosreport/sos
sos/policies/__init__.py
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L873-L877
def lsmod(self): """Return a list of kernel module names as strings. """ lines = shell_out("lsmod", timeout=0).splitlines() return [line.split()[0].strip() for line in lines]
[ "def", "lsmod", "(", "self", ")", ":", "lines", "=", "shell_out", "(", "\"lsmod\"", ",", "timeout", "=", "0", ")", ".", "splitlines", "(", ")", "return", "[", "line", ".", "split", "(", ")", "[", "0", "]", ".", "strip", "(", ")", "for", "line", ...
Return a list of kernel module names as strings.
[ "Return", "a", "list", "of", "kernel", "module", "names", "as", "strings", "." ]
python
train
gwpy/gwpy
gwpy/table/filter.py
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/table/filter.py#L99-L171
def parse_column_filter(definition): """Parse a `str` of the form 'column>50' Parameters ---------- definition : `str` a column filter definition of the form ``<name><operator><threshold>`` or ``<threshold><operator><name><operator><threshold>``, e.g. ``frequency >= 10``, or ``50 < snr < 100`` Returns ------- filters : `list` of `tuple` a `list` of filter 3-`tuple`s, where each `tuple` contains the following elements: - ``column`` (`str`) - the name of the column on which to operate - ``operator`` (`callable`) - the operator to call when evaluating the filter - ``operand`` (`anything`) - the argument to the operator function Raises ------ ValueError if the filter definition cannot be parsed KeyError if any parsed operator string cannnot be mapped to a function from the `operator` module Notes ----- Strings that contain non-alphanumeric characters (e.g. hyphen `-`) should be quoted inside the filter definition, to prevent such characters being interpreted as operators, e.g. ``channel = X1:TEST`` should always be passed as ``channel = "X1:TEST"``. Examples -------- >>> parse_column_filter("frequency>10") [('frequency', <function operator.gt>, 10.)] >>> parse_column_filter("50 < snr < 100") [('snr', <function operator.gt>, 50.), ('snr', <function operator.lt>, 100.)] >>> parse_column_filter("channel = "H1:TEST") [('channel', <function operator.eq>, 'H1:TEST')] """ # noqa # parse definition into parts (skipping null tokens) parts = list(generate_tokens(StringIO(definition.strip()).readline)) while parts[-1][0] in (token.ENDMARKER, token.NEWLINE): parts = parts[:-1] # parse simple definition: e.g: snr > 5 if len(parts) == 3: a, b, c = parts # pylint: disable=invalid-name if a[0] in [token.NAME, token.STRING]: # string comparison name = QUOTE_REGEX.sub('', a[1]) oprtr = OPERATORS[b[1]] value = _float_or_str(c[1]) return [(name, oprtr, value)] elif b[0] in [token.NAME, token.STRING]: name = QUOTE_REGEX.sub('', b[1]) oprtr = OPERATORS_INV[b[1]] value = _float_or_str(a[1]) return [(name, oprtr, value)] # parse between definition: e.g: 5 < snr < 10 elif len(parts) == 5: a, b, c, d, e = list(zip(*parts))[1] # pylint: disable=invalid-name name = QUOTE_REGEX.sub('', c) return [(name, OPERATORS_INV[b], _float_or_str(a)), (name, OPERATORS[d], _float_or_str(e))] raise ValueError("Cannot parse filter definition from %r" % definition)
[ "def", "parse_column_filter", "(", "definition", ")", ":", "# noqa", "# parse definition into parts (skipping null tokens)", "parts", "=", "list", "(", "generate_tokens", "(", "StringIO", "(", "definition", ".", "strip", "(", ")", ")", ".", "readline", ")", ")", "...
Parse a `str` of the form 'column>50' Parameters ---------- definition : `str` a column filter definition of the form ``<name><operator><threshold>`` or ``<threshold><operator><name><operator><threshold>``, e.g. ``frequency >= 10``, or ``50 < snr < 100`` Returns ------- filters : `list` of `tuple` a `list` of filter 3-`tuple`s, where each `tuple` contains the following elements: - ``column`` (`str`) - the name of the column on which to operate - ``operator`` (`callable`) - the operator to call when evaluating the filter - ``operand`` (`anything`) - the argument to the operator function Raises ------ ValueError if the filter definition cannot be parsed KeyError if any parsed operator string cannnot be mapped to a function from the `operator` module Notes ----- Strings that contain non-alphanumeric characters (e.g. hyphen `-`) should be quoted inside the filter definition, to prevent such characters being interpreted as operators, e.g. ``channel = X1:TEST`` should always be passed as ``channel = "X1:TEST"``. Examples -------- >>> parse_column_filter("frequency>10") [('frequency', <function operator.gt>, 10.)] >>> parse_column_filter("50 < snr < 100") [('snr', <function operator.gt>, 50.), ('snr', <function operator.lt>, 100.)] >>> parse_column_filter("channel = "H1:TEST") [('channel', <function operator.eq>, 'H1:TEST')]
[ "Parse", "a", "str", "of", "the", "form", "column", ">", "50" ]
python
train
jborean93/ntlm-auth
ntlm_auth/compute_hash.py
https://github.com/jborean93/ntlm-auth/blob/2c7cd81516d9bfd42e8ff473a534d876b21ebb38/ntlm_auth/compute_hash.py#L48-L67
def _ntowfv1(password): """ [MS-NLMP] v28.0 2016-07-14 3.3.1 NTLM v1 Authentication Same function as NTOWFv1 in document to create a one way hash of the password. Only used in NTLMv1 auth without session security :param password: The password or hash of the user we are trying to authenticate with :return digest: An NT hash of the password supplied """ # if the password is a hash, return the NT hash if re.match(r'^[a-fA-F\d]{32}:[a-fA-F\d]{32}$', password): nt_hash = binascii.unhexlify(password.split(':')[1]) return nt_hash digest = hashlib.new('md4', password.encode('utf-16-le')).digest() return digest
[ "def", "_ntowfv1", "(", "password", ")", ":", "# if the password is a hash, return the NT hash", "if", "re", ".", "match", "(", "r'^[a-fA-F\\d]{32}:[a-fA-F\\d]{32}$'", ",", "password", ")", ":", "nt_hash", "=", "binascii", ".", "unhexlify", "(", "password", ".", "sp...
[MS-NLMP] v28.0 2016-07-14 3.3.1 NTLM v1 Authentication Same function as NTOWFv1 in document to create a one way hash of the password. Only used in NTLMv1 auth without session security :param password: The password or hash of the user we are trying to authenticate with :return digest: An NT hash of the password supplied
[ "[", "MS", "-", "NLMP", "]", "v28", ".", "0", "2016", "-", "07", "-", "14" ]
python
train
willkg/markus
markus/main.py
https://github.com/willkg/markus/blob/0cfbe67fb7ccfa7488b0120d21ddc0cdc1f8ed33/markus/main.py#L396-L464
def get_metrics(thing, extra=''): """Return MetricsInterface instance with specified name. The name is used as the prefix for all keys generated with this :py:class:`markus.main.MetricsInterface`. The :py:class:`markus.main.MetricsInterface` is not tied to metrics backends. The list of active backends are globally configured. This allows us to create :py:class:`markus.main.MetricsInterface` classes without having to worry about bootstrapping order of the app. :arg class/instance/str thing: The name to use as a key prefix. If this is a class, it uses the dotted Python path. If this is an instance, it uses the dotted Python path plus ``str(instance)``. :arg str extra: Any extra bits to add to the end of the name. :returns: a ``MetricsInterface`` instance Examples: >>> from markus import get_metrics Create a MetricsInterface with the name "myapp" and generate a count with stat "myapp.thing1" and value 1: >>> metrics = get_metrics('myapp') >>> metrics.incr('thing1', value=1) Create a MetricsInterface with the prefix of the Python module it's being called in: >>> metrics = get_metrics(__name__) Create a MetricsInterface with the prefix as the qualname of the class: >>> class Foo: ... def __init__(self): ... self.metrics = get_metrics(self) Create a prefix of the class path plus some identifying information: >>> class Foo: ... def __init__(self, myname): ... self.metrics = get_metrics(self, extra=myname) ... >>> foo = Foo('jim') Assume that ``Foo`` is defined in the ``myapp`` module. Then this will generate the name ``myapp.Foo.jim``. """ thing = thing or '' if not isinstance(thing, str): # If it's not a str, it's either a class or an instance. Handle # accordingly. if type(thing) == type: thing = '%s.%s' % (thing.__module__, thing.__name__) else: thing = '%s.%s' % ( thing.__class__.__module__, thing.__class__.__name__ ) if extra: thing = '%s.%s' % (thing, extra) return MetricsInterface(thing)
[ "def", "get_metrics", "(", "thing", ",", "extra", "=", "''", ")", ":", "thing", "=", "thing", "or", "''", "if", "not", "isinstance", "(", "thing", ",", "str", ")", ":", "# If it's not a str, it's either a class or an instance. Handle", "# accordingly.", "if", "t...
Return MetricsInterface instance with specified name. The name is used as the prefix for all keys generated with this :py:class:`markus.main.MetricsInterface`. The :py:class:`markus.main.MetricsInterface` is not tied to metrics backends. The list of active backends are globally configured. This allows us to create :py:class:`markus.main.MetricsInterface` classes without having to worry about bootstrapping order of the app. :arg class/instance/str thing: The name to use as a key prefix. If this is a class, it uses the dotted Python path. If this is an instance, it uses the dotted Python path plus ``str(instance)``. :arg str extra: Any extra bits to add to the end of the name. :returns: a ``MetricsInterface`` instance Examples: >>> from markus import get_metrics Create a MetricsInterface with the name "myapp" and generate a count with stat "myapp.thing1" and value 1: >>> metrics = get_metrics('myapp') >>> metrics.incr('thing1', value=1) Create a MetricsInterface with the prefix of the Python module it's being called in: >>> metrics = get_metrics(__name__) Create a MetricsInterface with the prefix as the qualname of the class: >>> class Foo: ... def __init__(self): ... self.metrics = get_metrics(self) Create a prefix of the class path plus some identifying information: >>> class Foo: ... def __init__(self, myname): ... self.metrics = get_metrics(self, extra=myname) ... >>> foo = Foo('jim') Assume that ``Foo`` is defined in the ``myapp`` module. Then this will generate the name ``myapp.Foo.jim``.
[ "Return", "MetricsInterface", "instance", "with", "specified", "name", "." ]
python
test
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/api/core_v1_api.py
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/core_v1_api.py#L3243-L3265
def connect_patch_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501 """connect_patch_namespaced_service_proxy # noqa: E501 connect PATCH requests to proxy of Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_patch_namespaced_service_proxy(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the ServiceProxyOptions (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.connect_patch_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501 else: (data) = self.connect_patch_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501 return data
[ "def", "connect_patch_namespaced_service_proxy", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":...
connect_patch_namespaced_service_proxy # noqa: E501 connect PATCH requests to proxy of Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_patch_namespaced_service_proxy(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the ServiceProxyOptions (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. :return: str If the method is called asynchronously, returns the request thread.
[ "connect_patch_namespaced_service_proxy", "#", "noqa", ":", "E501" ]
python
train