nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
inasafe/inasafe
355eb2ce63f516b9c26af0c86a24f99e53f63f87
safe/utilities/unicode.py
python
get_string
(input_text, encoding='utf-8')
return input_text
Get byte string representation of an object. :param input_text: The input text. :type input_text: unicode, str, float, int :param encoding: The encoding used to do the conversion, default to utf-8. :type encoding: str :returns: Byte string representation of the input. :rtype: bytes
Get byte string representation of an object.
[ "Get", "byte", "string", "representation", "of", "an", "object", "." ]
def get_string(input_text, encoding='utf-8'): """Get byte string representation of an object. :param input_text: The input text. :type input_text: unicode, str, float, int :param encoding: The encoding used to do the conversion, default to utf-8. :type encoding: str :returns: Byte string representation of the input. :rtype: bytes """ if isinstance(input_text, str): return input_text.encode(encoding) return input_text
[ "def", "get_string", "(", "input_text", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "input_text", ",", "str", ")", ":", "return", "input_text", ".", "encode", "(", "encoding", ")", "return", "input_text" ]
https://github.com/inasafe/inasafe/blob/355eb2ce63f516b9c26af0c86a24f99e53f63f87/safe/utilities/unicode.py#L50-L64
pret/pokemon-reverse-engineering-tools
5e0715f2579adcfeb683448c9a7826cfd3afa57d
pokemontools/crystal.py
python
ItemFragmentParam.parse
(self)
[]
def parse(self): PointerLabelParam.parse(self) address = calculate_pointer_from_bytes_at(self.address, bank=self.bank) self.calculated_address = address itemfrag = ItemFragment(address=address, map_group=self.map_group, map_id=self.map_id, debug=self.debug) self.itemfrag = itemfrag
[ "def", "parse", "(", "self", ")", ":", "PointerLabelParam", ".", "parse", "(", "self", ")", "address", "=", "calculate_pointer_from_bytes_at", "(", "self", ".", "address", ",", "bank", "=", "self", ".", "bank", ")", "self", ".", "calculated_address", "=", ...
https://github.com/pret/pokemon-reverse-engineering-tools/blob/5e0715f2579adcfeb683448c9a7826cfd3afa57d/pokemontools/crystal.py#L3296-L3303
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
packages/python/pyfora/PyforaInspect.py
python
getsourcelines
(pyObject)
Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.
Return a list of source lines and starting line number for an object.
[ "Return", "a", "list", "of", "source", "lines", "and", "starting", "line", "number", "for", "an", "object", "." ]
def getsourcelines(pyObject): """Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = findsource(pyObject) if ismodule(pyObject): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1
[ "def", "getsourcelines", "(", "pyObject", ")", ":", "lines", ",", "lnum", "=", "findsource", "(", "pyObject", ")", "if", "ismodule", "(", "pyObject", ")", ":", "return", "lines", ",", "0", "else", ":", "return", "getblock", "(", "lines", "[", "lnum", "...
https://github.com/ufora/ufora/blob/04db96ab049b8499d6d6526445f4f9857f1b6c7e/packages/python/pyfora/PyforaInspect.py#L287-L298
Baekalfen/PyBoy
96d2b3d54fe73a6030ff61b6c70952b8e6aa6299
pyboy/botsupport/tilemap.py
python
_tile_address
(self, column, row)
return self.map_offset + 32*row + column
Returns the memory address in the tilemap for the tile at the given coordinate. The address contains the index of tile which will be shown at this position. This should not be confused with the actual tile data of `pyboy.botsupport.tile.Tile.data_address`. This can be used as an global identifier for the specific location in a tile map. Be aware, that the tile index referenced at the memory address might change between calls to `pyboy.PyBoy.tick`. And the tile data for the same tile index might also change to display something else on the screen. The index might also be a signed number. Depending on if it is signed or not, will change where the tile data is read from. Use `pyboy.botsupport.tilemap.TileMap.signed_tile_index` to test if the indexes are signed for this tile view. You can read how the indexes work in the [Pan Docs: VRAM Tile Data](http://bgb.bircd.org/pandocs.htm#vramtiledata). Args: column (int): Column in this tile map. row (int): Row in this tile map. Returns ------- int: Address in the tile map to read a tile index.
Returns the memory address in the tilemap for the tile at the given coordinate. The address contains the index of tile which will be shown at this position. This should not be confused with the actual tile data of `pyboy.botsupport.tile.Tile.data_address`.
[ "Returns", "the", "memory", "address", "in", "the", "tilemap", "for", "the", "tile", "at", "the", "given", "coordinate", ".", "The", "address", "contains", "the", "index", "of", "tile", "which", "will", "be", "shown", "at", "this", "position", ".", "This",...
def _tile_address(self, column, row): """ Returns the memory address in the tilemap for the tile at the given coordinate. The address contains the index of tile which will be shown at this position. This should not be confused with the actual tile data of `pyboy.botsupport.tile.Tile.data_address`. This can be used as an global identifier for the specific location in a tile map. Be aware, that the tile index referenced at the memory address might change between calls to `pyboy.PyBoy.tick`. And the tile data for the same tile index might also change to display something else on the screen. The index might also be a signed number. Depending on if it is signed or not, will change where the tile data is read from. Use `pyboy.botsupport.tilemap.TileMap.signed_tile_index` to test if the indexes are signed for this tile view. You can read how the indexes work in the [Pan Docs: VRAM Tile Data](http://bgb.bircd.org/pandocs.htm#vramtiledata). Args: column (int): Column in this tile map. row (int): Row in this tile map. Returns ------- int: Address in the tile map to read a tile index. """ if not 0 <= column < 32: raise IndexError("column is out of bounds. Value of 0 to 31 is allowed") if not 0 <= row < 32: raise IndexError("row is out of bounds. Value of 0 to 31 is allowed") return self.map_offset + 32*row + column
[ "def", "_tile_address", "(", "self", ",", "column", ",", "row", ")", ":", "if", "not", "0", "<=", "column", "<", "32", ":", "raise", "IndexError", "(", "\"column is out of bounds. Value of 0 to 31 is allowed\"", ")", "if", "not", "0", "<=", "row", "<", "32",...
https://github.com/Baekalfen/PyBoy/blob/96d2b3d54fe73a6030ff61b6c70952b8e6aa6299/pyboy/botsupport/tilemap.py#L106-L137
alanhamlett/pip-update-requirements
ce875601ef278c8ce00ad586434a978731525561
pur/packages/pip/_vendor/distlib/database.py
python
DistributionPath.provides_distribution
(self, name, version=None)
Iterates over all distributions to find which distributions provide *name*. If a *version* is provided, it will be used to filter the results. This function only returns the first result found, since no more than one values are expected. If the directory is not found, returns ``None``. :parameter version: a version specifier that indicates the version required, conforming to the format in ``PEP-345`` :type name: string :type version: string
Iterates over all distributions to find which distributions provide *name*. If a *version* is provided, it will be used to filter the results.
[ "Iterates", "over", "all", "distributions", "to", "find", "which", "distributions", "provide", "*", "name", "*", ".", "If", "a", "*", "version", "*", "is", "provided", "it", "will", "be", "used", "to", "filter", "the", "results", "." ]
def provides_distribution(self, name, version=None): """ Iterates over all distributions to find which distributions provide *name*. If a *version* is provided, it will be used to filter the results. This function only returns the first result found, since no more than one values are expected. If the directory is not found, returns ``None``. :parameter version: a version specifier that indicates the version required, conforming to the format in ``PEP-345`` :type name: string :type version: string """ matcher = None if version is not None: try: matcher = self._scheme.matcher('%s (%s)' % (name, version)) except ValueError: raise DistlibException('invalid name or version: %r, %r' % (name, version)) for dist in self.get_distributions(): # We hit a problem on Travis where enum34 was installed and doesn't # have a provides attribute ... if not hasattr(dist, 'provides'): logger.debug('No "provides": %s', dist) else: provided = dist.provides for p in provided: p_name, p_ver = parse_name_and_version(p) if matcher is None: if p_name == name: yield dist break else: if p_name == name and matcher.match(p_ver): yield dist break
[ "def", "provides_distribution", "(", "self", ",", "name", ",", "version", "=", "None", ")", ":", "matcher", "=", "None", "if", "version", "is", "not", "None", ":", "try", ":", "matcher", "=", "self", ".", "_scheme", ".", "matcher", "(", "'%s (%s)'", "%...
https://github.com/alanhamlett/pip-update-requirements/blob/ce875601ef278c8ce00ad586434a978731525561/pur/packages/pip/_vendor/distlib/database.py#L248-L287
tensorflow/lingvo
ce10019243d954c3c3ebe739f7589b5eebfdf907
lingvo/tasks/lm/input_generator.py
python
TFRecordBertInput._ParseRecord
(self, record)
return ret
Reads and parses a single record.
Reads and parses a single record.
[ "Reads", "and", "parses", "a", "single", "record", "." ]
def _ParseRecord(self, record): """Reads and parses a single record.""" p = self.params name_to_features = { 'input_ids': tf.io.FixedLenFeature([p.max_sequence_length], tf.int64), 'input_mask': tf.io.FixedLenFeature([p.max_sequence_length], tf.int64), 'masked_lm_positions': tf.io.FixedLenFeature([p.max_predictions_per_seq], tf.int64), 'masked_lm_ids': tf.io.FixedLenFeature([p.max_predictions_per_seq], tf.int64), 'masked_lm_weights': tf.io.FixedLenFeature([p.max_predictions_per_seq], tf.float32), } example = tf.io.parse_single_example(record, name_to_features) mask_length = tf.cast( tf.reduce_sum(example['masked_lm_weights']), dtype=tf.int32) masked_lm_positions = tf.slice(example['masked_lm_positions'], [0], [mask_length]) masked_lm_ids = tf.cast( tf.slice(example['masked_lm_ids'], [0], [mask_length]), dtype=tf.int32) ret = py_utils.NestedMap() ret.masked_ids = tf.cast(example['input_ids'], dtype=tf.int32) # Get back non-masked, original ids. ret.ids = tf.tensor_scatter_nd_update( tensor=ret.masked_ids, indices=tf.reshape(masked_lm_positions, [-1, 1]), updates=masked_lm_ids) ret.masked_pos = tf.tensor_scatter_nd_update( tensor=tf.zeros_like(ret.masked_ids, dtype=tf.float32), indices=tf.reshape(masked_lm_positions, [-1, 1]), updates=tf.ones_like(masked_lm_ids, dtype=tf.float32)) ret.segment_ids = tf.cast(example['input_mask'], dtype=tf.float32) first_eos_idx = tf.where(tf.math.equal(ret.ids, p.eos_token_id))[0][0] def _RemoveFirstEos(x): # We remove the element at position `first_eos_idx`, and pad with 0 # to keep length unchanged. zero = tf.constant(0, shape=(1,), dtype=x.dtype) return tf.concat([x[:first_eos_idx], x[first_eos_idx + 1:], zero], axis=0) ret = ret.Transform(_RemoveFirstEos) ret.paddings = 1.0 - ret.segment_ids pos = tf.cast(tf.range(p.max_sequence_length), dtype=tf.float32) ret.segment_pos = tf.cast(ret.segment_ids * pos, dtype=tf.int32) if p.remove_mask: del ret.masked_pos del ret.masked_ids return ret
[ "def", "_ParseRecord", "(", "self", ",", "record", ")", ":", "p", "=", "self", ".", "params", "name_to_features", "=", "{", "'input_ids'", ":", "tf", ".", "io", ".", "FixedLenFeature", "(", "[", "p", ".", "max_sequence_length", "]", ",", "tf", ".", "in...
https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/tasks/lm/input_generator.py#L307-L358
django/django
0a17666045de6739ae1c2ac695041823d5f827f7
django/contrib/auth/models.py
python
_user_has_module_perms
(user, app_label)
return False
A backend can raise `PermissionDenied` to short-circuit permission checking.
A backend can raise `PermissionDenied` to short-circuit permission checking.
[ "A", "backend", "can", "raise", "PermissionDenied", "to", "short", "-", "circuit", "permission", "checking", "." ]
def _user_has_module_perms(user, app_label): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_module_perms'): continue try: if backend.has_module_perms(user, app_label): return True except PermissionDenied: return False return False
[ "def", "_user_has_module_perms", "(", "user", ",", "app_label", ")", ":", "for", "backend", "in", "auth", ".", "get_backends", "(", ")", ":", "if", "not", "hasattr", "(", "backend", ",", "'has_module_perms'", ")", ":", "continue", "try", ":", "if", "backen...
https://github.com/django/django/blob/0a17666045de6739ae1c2ac695041823d5f827f7/django/contrib/auth/models.py#L218-L230
kiwiz/gkeepapi
229d2981bd18a6b2acc058017f84298af4fbe824
gkeepapi/__init__.py
python
MediaAPI.get
(self, blob)
return self._send( url=url, method='GET', allow_redirects=False ).headers['location']
Get the canonical link to a media blob. Args: blob (gkeepapi.node.Blob): The blob. Returns: str: A link to the media.
Get the canonical link to a media blob.
[ "Get", "the", "canonical", "link", "to", "a", "media", "blob", "." ]
def get(self, blob): """Get the canonical link to a media blob. Args: blob (gkeepapi.node.Blob): The blob. Returns: str: A link to the media. """ url = self._base_url + blob.parent.server_id + '/' + blob.server_id if blob.blob.type == _node.BlobType.Drawing: url += '/' + blob.blob._drawing_info.drawing_id return self._send( url=url, method='GET', allow_redirects=False ).headers['location']
[ "def", "get", "(", "self", ",", "blob", ")", ":", "url", "=", "self", ".", "_base_url", "+", "blob", ".", "parent", ".", "server_id", "+", "'/'", "+", "blob", ".", "server_id", "if", "blob", ".", "blob", ".", "type", "==", "_node", ".", "BlobType",...
https://github.com/kiwiz/gkeepapi/blob/229d2981bd18a6b2acc058017f84298af4fbe824/gkeepapi/__init__.py#L372-L388
dagster-io/dagster
b27d569d5fcf1072543533a0c763815d96f90b8f
python_modules/libraries/dagster-databricks/dagster_databricks/databricks.py
python
DatabricksClient.read_file
(self, dbfs_path, block_size=1024 ** 2)
return data
Read a file from DBFS to a **byte string**.
Read a file from DBFS to a **byte string**.
[ "Read", "a", "file", "from", "DBFS", "to", "a", "**", "byte", "string", "**", "." ]
def read_file(self, dbfs_path, block_size=1024 ** 2): """Read a file from DBFS to a **byte string**.""" if dbfs_path.startswith("dbfs://"): dbfs_path = dbfs_path[7:] data = b"" bytes_read = 0 jdoc = self.client.dbfs.read(path=dbfs_path, length=block_size) # pylint: disable=no-member data += base64.b64decode(jdoc["data"]) while jdoc["bytes_read"] == block_size: bytes_read += jdoc["bytes_read"] jdoc = self.client.dbfs.read( # pylint: disable=no-member path=dbfs_path, offset=bytes_read, length=block_size ) data += base64.b64decode(jdoc["data"]) return data
[ "def", "read_file", "(", "self", ",", "dbfs_path", ",", "block_size", "=", "1024", "**", "2", ")", ":", "if", "dbfs_path", ".", "startswith", "(", "\"dbfs://\"", ")", ":", "dbfs_path", "=", "dbfs_path", "[", "7", ":", "]", "data", "=", "b\"\"", "bytes_...
https://github.com/dagster-io/dagster/blob/b27d569d5fcf1072543533a0c763815d96f90b8f/python_modules/libraries/dagster-databricks/dagster_databricks/databricks.py#L35-L50
jobovy/galpy
8e6a230bbe24ce16938db10053f92eb17fe4bb52
galpy/potential/FerrersPotential.py
python
FerrersPotential._Rphideriv
(self,R,z,phi=0.,t=0.)
return R*numpy.cos(phi)*numpy.sin(phi)*\ (phiyy-phixx)+R*numpy.cos(2.*(phi))*phixy\ +numpy.sin(phi)*Fx-numpy.cos(phi)*Fy
NAME: _Rphideriv PURPOSE: evaluate the mixed radial, azimuthal derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the mixed radial, azimuthal derivative
NAME: _Rphideriv PURPOSE: evaluate the mixed radial, azimuthal derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the mixed radial, azimuthal derivative
[ "NAME", ":", "_Rphideriv", "PURPOSE", ":", "evaluate", "the", "mixed", "radial", "azimuthal", "derivative", "for", "this", "potential", "INPUT", ":", "R", "-", "Galactocentric", "cylindrical", "radius", "z", "-", "vertical", "height", "phi", "-", "azimuth", "t...
def _Rphideriv(self,R,z,phi=0.,t=0.): """ NAME: _Rphideriv PURPOSE: evaluate the mixed radial, azimuthal derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the mixed radial, azimuthal derivative """ if not self.isNonAxi: phi= 0. x,y,z= self._compute_xyz(R,phi,z,t) Fx= self._xforce_xyz(x,y,z) Fy= self._yforce_xyz(x,y,z) Fxy= numpy.dot(self.rot(t, transposed = True),numpy.array([Fx,Fy])) Fx, Fy= Fxy[0], Fxy[1] phixxa= self._2ndderiv_xyz(x,y,z,0,0) phixya= self._2ndderiv_xyz(x,y,z,0,1) phiyya= self._2ndderiv_xyz(x,y,z,1,1) ang = self._omegab*t + self._pa c, s = numpy.cos(ang), numpy.sin(ang) phixx = c**2*phixxa + 2.*c*s*phixya + s**2*phiyya phixy = (c**2-s**2)*phixya + c*s*(phiyya - phixxa) phiyy = s**2*phixxa - 2.*c*s*phixya + c**2*phiyya return R*numpy.cos(phi)*numpy.sin(phi)*\ (phiyy-phixx)+R*numpy.cos(2.*(phi))*phixy\ +numpy.sin(phi)*Fx-numpy.cos(phi)*Fy
[ "def", "_Rphideriv", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "if", "not", "self", ".", "isNonAxi", ":", "phi", "=", "0.", "x", ",", "y", ",", "z", "=", "self", ".", "_compute_xyz", "(", "R", ",...
https://github.com/jobovy/galpy/blob/8e6a230bbe24ce16938db10053f92eb17fe4bb52/galpy/potential/FerrersPotential.py#L328-L359
bokeh/bokeh
a00e59da76beb7b9f83613533cfd3aced1df5f06
bokeh/document/events.py
python
RootAddedEvent.generate
(self, references: Set[Model], buffers: Buffers)
return RootAdded( kind = self.kind, model = self.model.ref, )
Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'RootAdded' 'title' : <reference to a Model> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place.
Create a JSON representation of this event suitable for sending to clients.
[ "Create", "a", "JSON", "representation", "of", "this", "event", "suitable", "for", "sending", "to", "clients", "." ]
def generate(self, references: Set[Model], buffers: Buffers) -> RootAdded: ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'RootAdded' 'title' : <reference to a Model> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place. ''' references.update(self.model.references()) return RootAdded( kind = self.kind, model = self.model.ref, )
[ "def", "generate", "(", "self", ",", "references", ":", "Set", "[", "Model", "]", ",", "buffers", ":", "Buffers", ")", "->", "RootAdded", ":", "references", ".", "update", "(", "self", ".", "model", ".", "references", "(", ")", ")", "return", "RootAdde...
https://github.com/bokeh/bokeh/blob/a00e59da76beb7b9f83613533cfd3aced1df5f06/bokeh/document/events.py#L892-L923
quentinhardy/msdat
879377410f9063c58b67f4624c082faa26169e5d
progressbar.py
python
ProgressBar.finish
(self)
Used to tell the progress is finished.
Used to tell the progress is finished.
[ "Used", "to", "tell", "the", "progress", "is", "finished", "." ]
def finish(self): """Used to tell the progress is finished.""" self.update(self.maxval) if self.signal_set: signal.signal(signal.SIGWINCH, signal.SIG_DFL)
[ "def", "finish", "(", "self", ")", ":", "self", ".", "update", "(", "self", ".", "maxval", ")", "if", "self", ".", "signal_set", ":", "signal", ".", "signal", "(", "signal", ".", "SIGWINCH", ",", "signal", ".", "SIG_DFL", ")" ]
https://github.com/quentinhardy/msdat/blob/879377410f9063c58b67f4624c082faa26169e5d/progressbar.py#L299-L303
nightmaredimple/libmot
23b8e2ac00f8b45d5a0ecabd57af90585966f3ff
libmot/motion/epipolar_geometry.py
python
Epipolar.FeatureExtract
(self, img)
return keypoints, descriptors
Detect and Compute the input image's keypoints and descriptors Parameters ---------- img : ndarray of opencv An HxW(x3) matrix of img Returns ------- keypoints : List of cv2.KeyPoint using keypoint.pt can see (x,y) descriptors: List of descriptors[keypoints, features] keypoints: keypoints which a descriptor cannot be computed are removed features: An Nx32 ndarray of unit8 when using "orb" method
Detect and Compute the input image's keypoints and descriptors
[ "Detect", "and", "Compute", "the", "input", "image", "s", "keypoints", "and", "descriptors" ]
def FeatureExtract(self, img): """Detect and Compute the input image's keypoints and descriptors Parameters ---------- img : ndarray of opencv An HxW(x3) matrix of img Returns ------- keypoints : List of cv2.KeyPoint using keypoint.pt can see (x,y) descriptors: List of descriptors[keypoints, features] keypoints: keypoints which a descriptor cannot be computed are removed features: An Nx32 ndarray of unit8 when using "orb" method """ if img.ndim == 3: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # find the keypoints with ORB keypoints = self.feature_extractor.detect(img, None) # compute the descriptors with ORB keypoints, descriptors = self.feature_extractor.compute(img, keypoints) return keypoints, descriptors
[ "def", "FeatureExtract", "(", "self", ",", "img", ")", ":", "if", "img", ".", "ndim", "==", "3", ":", "img", "=", "cv2", ".", "cvtColor", "(", "img", ",", "cv2", ".", "COLOR_BGR2GRAY", ")", "# find the keypoints with ORB", "keypoints", "=", "self", ".", ...
https://github.com/nightmaredimple/libmot/blob/23b8e2ac00f8b45d5a0ecabd57af90585966f3ff/libmot/motion/epipolar_geometry.py#L57-L80
mozilla/zamboni
14b1a44658e47b9f048962fa52dbf00a3beaaf30
lib/geoip/__init__.py
python
GeoIP.lookup
(self, address)
return self.default_val
Resolve an IP address to a block of geo information. If a given address is unresolvable or the geoip server is not defined, return the default as defined by the settings, or "restofworld".
Resolve an IP address to a block of geo information.
[ "Resolve", "an", "IP", "address", "to", "a", "block", "of", "geo", "information", "." ]
def lookup(self, address): """Resolve an IP address to a block of geo information. If a given address is unresolvable or the geoip server is not defined, return the default as defined by the settings, or "restofworld". """ public_ip = is_public(address) if self.url and public_ip: with statsd.timer('z.geoip'): res = None try: res = requests.post('{0}/country.json'.format(self.url), timeout=self.timeout, data={'ip': address}) except requests.Timeout: statsd.incr('z.geoip.timeout') log.error(('Geodude timed out looking up: {0}' .format(address))) except requests.RequestException as e: statsd.incr('z.geoip.error') log.error('Geodude connection error: {0}'.format(str(e))) if res and res.status_code == 200: statsd.incr('z.geoip.success') country_code = res.json().get( 'country_code', self.default_val).lower() log.info(('Geodude lookup for {0} returned {1}' .format(address, country_code))) return country_code log.info('Geodude lookup returned non-200 response: {0}' .format(res.status_code)) else: if public_ip: log.info('Geodude lookup skipped for public IP: {0}' .format(address)) else: log.info('Geodude lookup skipped for private IP: {0}' .format(address)) return self.default_val
[ "def", "lookup", "(", "self", ",", "address", ")", ":", "public_ip", "=", "is_public", "(", "address", ")", "if", "self", ".", "url", "and", "public_ip", ":", "with", "statsd", ".", "timer", "(", "'z.geoip'", ")", ":", "res", "=", "None", "try", ":",...
https://github.com/mozilla/zamboni/blob/14b1a44658e47b9f048962fa52dbf00a3beaaf30/lib/geoip/__init__.py#L37-L75
tbotnz/netpalm
9668a59ee8c15573804abcb21dad26d1b2dc3c03
netpalm/backend/core/manager/netpalm_manager.py
python
NetpalmManager.redeploy_service_instance_state
(self, service_id: str)
return resp
redeploys the service instance
redeploys the service instance
[ "redeploys", "the", "service", "instance" ]
def redeploy_service_instance_state(self, service_id: str): """ redeploys the service instance """ r = self.redeploy_service_instance(sid=service_id) resp = jsonable_encoder(r) return resp
[ "def", "redeploy_service_instance_state", "(", "self", ",", "service_id", ":", "str", ")", ":", "r", "=", "self", ".", "redeploy_service_instance", "(", "sid", "=", "service_id", ")", "resp", "=", "jsonable_encoder", "(", "r", ")", "return", "resp" ]
https://github.com/tbotnz/netpalm/blob/9668a59ee8c15573804abcb21dad26d1b2dc3c03/netpalm/backend/core/manager/netpalm_manager.py#L166-L170
albertz/music-player
d23586f5bf657cbaea8147223be7814d117ae73d
src/lastfm/client.py
python
LastfmClient.__init__
(self, session, rest_client=RESTClient)
Initialize the LastfmClient object. Args: session: A lastfm.session.LastfmSession object to use for making requests. rest_client: A lastfm.rest.RESTClient-like object to use for making requests. [optional]
Initialize the LastfmClient object.
[ "Initialize", "the", "LastfmClient", "object", "." ]
def __init__(self, session, rest_client=RESTClient): """Initialize the LastfmClient object. Args: session: A lastfm.session.LastfmSession object to use for making requests. rest_client: A lastfm.rest.RESTClient-like object to use for making requests. [optional] """ self.session = session self.rest_client = rest_client
[ "def", "__init__", "(", "self", ",", "session", ",", "rest_client", "=", "RESTClient", ")", ":", "self", ".", "session", "=", "session", "self", ".", "rest_client", "=", "rest_client" ]
https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/src/lastfm/client.py#L52-L60
radlab/sparrow
afb8efadeb88524f1394d1abe4ea66c6fd2ac744
deploy/third_party/boto-2.1.1/boto/s3/key.py
python
Key.get_contents_to_file
(self, fp, headers=None, cb=None, num_cb=10, torrent=False, version_id=None, res_download_handler=None, response_headers=None)
Retrieve an object from S3 using the name of the Key object as the key in S3. Write the contents of the object to the file pointed to by 'fp'. :type fp: File -like object :param fp: :type headers: dict :param headers: additional HTTP headers that will be sent with the GET request. :type cb: function :param cb: a callback function that will be called to report progress on the upload. The callback should accept two integer parameters, the first representing the number of bytes that have been successfully transmitted to S3 and the second representing the size of the to be transmitted object. :type cb: int :param num_cb: (optional) If a callback is specified with the cb parameter this parameter determines the granularity of the callback by defining the maximum number of times the callback will be called during the file transfer. :type torrent: bool :param torrent: If True, returns the contents of a torrent file as a string. :type res_upload_handler: ResumableDownloadHandler :param res_download_handler: If provided, this handler will perform the download. :type response_headers: dict :param response_headers: A dictionary containing HTTP headers/values that will override any headers associated with the stored object in the response. See http://goo.gl/EWOPb for details.
Retrieve an object from S3 using the name of the Key object as the key in S3. Write the contents of the object to the file pointed to by 'fp'.
[ "Retrieve", "an", "object", "from", "S3", "using", "the", "name", "of", "the", "Key", "object", "as", "the", "key", "in", "S3", ".", "Write", "the", "contents", "of", "the", "object", "to", "the", "file", "pointed", "to", "by", "fp", "." ]
def get_contents_to_file(self, fp, headers=None, cb=None, num_cb=10, torrent=False, version_id=None, res_download_handler=None, response_headers=None): """ Retrieve an object from S3 using the name of the Key object as the key in S3. Write the contents of the object to the file pointed to by 'fp'. :type fp: File -like object :param fp: :type headers: dict :param headers: additional HTTP headers that will be sent with the GET request. :type cb: function :param cb: a callback function that will be called to report progress on the upload. The callback should accept two integer parameters, the first representing the number of bytes that have been successfully transmitted to S3 and the second representing the size of the to be transmitted object. :type cb: int :param num_cb: (optional) If a callback is specified with the cb parameter this parameter determines the granularity of the callback by defining the maximum number of times the callback will be called during the file transfer. :type torrent: bool :param torrent: If True, returns the contents of a torrent file as a string. :type res_upload_handler: ResumableDownloadHandler :param res_download_handler: If provided, this handler will perform the download. :type response_headers: dict :param response_headers: A dictionary containing HTTP headers/values that will override any headers associated with the stored object in the response. See http://goo.gl/EWOPb for details. """ if self.bucket != None: if res_download_handler: res_download_handler.get_file(self, fp, headers, cb, num_cb, torrent=torrent, version_id=version_id) else: self.get_file(fp, headers, cb, num_cb, torrent=torrent, version_id=version_id, response_headers=response_headers)
[ "def", "get_contents_to_file", "(", "self", ",", "fp", ",", "headers", "=", "None", ",", "cb", "=", "None", ",", "num_cb", "=", "10", ",", "torrent", "=", "False", ",", "version_id", "=", "None", ",", "res_download_handler", "=", "None", ",", "response_h...
https://github.com/radlab/sparrow/blob/afb8efadeb88524f1394d1abe4ea66c6fd2ac744/deploy/third_party/boto-2.1.1/boto/s3/key.py#L1038-L1093
idlesign/django-sitetree
244a3c935b59a396ffe5d462a437762bff45183b
sitetree/sitetreeapp.py
python
SiteTree.init_tree
( self, tree_alias: str, context: Context )
return tree_alias, sitetree_items
Initializes sitetree in memory. Returns tuple with resolved tree alias and items on success. On fail returns (None, None). :param tree_alias: :param context:
Initializes sitetree in memory.
[ "Initializes", "sitetree", "in", "memory", "." ]
def init_tree( self, tree_alias: str, context: Context ) -> Tuple[Optional[str], Optional[List['TreeItemBase']]]: """Initializes sitetree in memory. Returns tuple with resolved tree alias and items on success. On fail returns (None, None). :param tree_alias: :param context: """ request = context.get('request', None) if request is None: if any(exc_info()): # Probably we're in a technical # exception handling view. So we won't mask # the initial exception with the one below. return None, None raise SiteTreeError( 'Sitetree requires "django.core.context_processors.request" template context processor to be active. ' 'If it is, check that your view pushes request data into the template.') if id(request) != id(self.current_request): self.init(context) # Resolve tree_alias from the context. tree_alias = self.resolve_var(tree_alias) tree_alias, sitetree_items = self.get_sitetree(tree_alias) if not sitetree_items: return None, None return tree_alias, sitetree_items
[ "def", "init_tree", "(", "self", ",", "tree_alias", ":", "str", ",", "context", ":", "Context", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "Optional", "[", "List", "[", "'TreeItemBase'", "]", "]", "]", ":", "request", "=", "context", ...
https://github.com/idlesign/django-sitetree/blob/244a3c935b59a396ffe5d462a437762bff45183b/sitetree/sitetreeapp.py#L712-L751
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/bsddb/dbobj.py
python
DBEnv.set_lg_dir
(self, *args, **kwargs)
return self._cobj.set_lg_dir(*args, **kwargs)
[]
def set_lg_dir(self, *args, **kwargs): return self._cobj.set_lg_dir(*args, **kwargs)
[ "def", "set_lg_dir", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_cobj", ".", "set_lg_dir", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/bsddb/dbobj.py#L58-L59
rwightman/pytorch-image-models
ccfeb06936549f19c453b7f1f27e8e632cfbe1c2
timm/data/tf_preprocessing.py
python
preprocess_for_eval
(image_bytes, use_bfloat16, image_size=IMAGE_SIZE, interpolation='bicubic')
return image
Preprocesses the given image for evaluation. Args: image_bytes: `Tensor` representing an image binary of arbitrary size. use_bfloat16: `bool` for whether to use bfloat16. image_size: image size. interpolation: image interpolation method Returns: A preprocessed image `Tensor`.
Preprocesses the given image for evaluation.
[ "Preprocesses", "the", "given", "image", "for", "evaluation", "." ]
def preprocess_for_eval(image_bytes, use_bfloat16, image_size=IMAGE_SIZE, interpolation='bicubic'): """Preprocesses the given image for evaluation. Args: image_bytes: `Tensor` representing an image binary of arbitrary size. use_bfloat16: `bool` for whether to use bfloat16. image_size: image size. interpolation: image interpolation method Returns: A preprocessed image `Tensor`. """ resize_method = tf.image.ResizeMethod.BICUBIC if interpolation == 'bicubic' else tf.image.ResizeMethod.BILINEAR image = _decode_and_center_crop(image_bytes, image_size, resize_method) image = tf.reshape(image, [image_size, image_size, 3]) image = tf.image.convert_image_dtype( image, dtype=tf.bfloat16 if use_bfloat16 else tf.float32) return image
[ "def", "preprocess_for_eval", "(", "image_bytes", ",", "use_bfloat16", ",", "image_size", "=", "IMAGE_SIZE", ",", "interpolation", "=", "'bicubic'", ")", ":", "resize_method", "=", "tf", ".", "image", ".", "ResizeMethod", ".", "BICUBIC", "if", "interpolation", "...
https://github.com/rwightman/pytorch-image-models/blob/ccfeb06936549f19c453b7f1f27e8e632cfbe1c2/timm/data/tf_preprocessing.py#L161-L178
cylc/cylc-flow
5ec221143476c7c616c156b74158edfbcd83794a
cylc/flow/task_trigger.py
python
Dependency.get_expression
(self, point)
return ''.join(self._stringify_list(self._exp, point))
Return the expression as a string. Args: point (cylc.flow.cycling.PointBase): The cycle point at which to generate the expression string for. Return: string: The expression as a parsable string in the cylc graph format.
Return the expression as a string.
[ "Return", "the", "expression", "as", "a", "string", "." ]
def get_expression(self, point): """Return the expression as a string. Args: point (cylc.flow.cycling.PointBase): The cycle point at which to generate the expression string for. Return: string: The expression as a parsable string in the cylc graph format. """ return ''.join(self._stringify_list(self._exp, point))
[ "def", "get_expression", "(", "self", ",", "point", ")", ":", "return", "''", ".", "join", "(", "self", ".", "_stringify_list", "(", "self", ".", "_exp", ",", "point", ")", ")" ]
https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/task_trigger.py#L239-L251
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/httpagentparser/__init__.py
python
IPad.getVersion
(self, agent, word)
return None
[]
def getVersion(self, agent, word): version_end_chars = [' '] if not "CPU OS " in agent: return None part = agent.split('CPU OS ')[-1].strip() for c in version_end_chars: if c in part: version = part.split(c)[0] return version.replace('_', '.') return None
[ "def", "getVersion", "(", "self", ",", "agent", ",", "word", ")", ":", "version_end_chars", "=", "[", "' '", "]", "if", "not", "\"CPU OS \"", "in", "agent", ":", "return", "None", "part", "=", "agent", ".", "split", "(", "'CPU OS '", ")", "[", "-", "...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/httpagentparser/__init__.py#L478-L487
ros/ros_comm
52b0556dadf3ec0c0bc72df4fc202153a53b539e
tools/roslaunch/src/roslaunch/substitution_args.py
python
_anon
(resolved, a, args, context)
return resolved.replace("$(%s)" % a, _eval_anon(id=args[0], anons=anon_context))
process $(anon) arg @return: updated resolved argument @rtype: str @raise SubstitutionException: if arg invalidly specified
process $(anon) arg
[ "process", "$", "(", "anon", ")", "arg" ]
def _anon(resolved, a, args, context): """ process $(anon) arg @return: updated resolved argument @rtype: str @raise SubstitutionException: if arg invalidly specified """ # #1559 #1660 if len(args) == 0: raise SubstitutionException("$(anon var) must specify a name [%s]"%a) elif len(args) > 1: raise SubstitutionException("$(anon var) may only specify one name [%s]"%a) if 'anon' not in context: context['anon'] = {} anon_context = context['anon'] return resolved.replace("$(%s)" % a, _eval_anon(id=args[0], anons=anon_context))
[ "def", "_anon", "(", "resolved", ",", "a", ",", "args", ",", "context", ")", ":", "# #1559 #1660", "if", "len", "(", "args", ")", "==", "0", ":", "raise", "SubstitutionException", "(", "\"$(anon var) must specify a name [%s]\"", "%", "a", ")", "elif", "len",...
https://github.com/ros/ros_comm/blob/52b0556dadf3ec0c0bc72df4fc202153a53b539e/tools/roslaunch/src/roslaunch/substitution_args.py#L105-L120
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/requirementslib/models/metadata.py
python
get_releases_from_package
(releases, name=None)
return release_list
[]
def get_releases_from_package(releases, name=None): # type: (TReleasesDict, Optional[str]) -> List[Release] release_list = [] for version, urls in releases.items(): release_list.append(get_release(version, urls, name=name)) return release_list
[ "def", "get_releases_from_package", "(", "releases", ",", "name", "=", "None", ")", ":", "# type: (TReleasesDict, Optional[str]) -> List[Release]", "release_list", "=", "[", "]", "for", "version", ",", "urls", "in", "releases", ".", "items", "(", ")", ":", "releas...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/requirementslib/models/metadata.py#L820-L825
anchore/anchore-engine
bb18b70e0cbcad58beb44cd439d00067d8f7ea8b
anchore_engine/util/docker.py
python
DockerV2ManifestMetadata.__init__
(self, manifest_json, image_config_json)
:param manifest_json: :param image_config_json: :param downloaded_blob_list: list of string filenames for blobs downloaded, assumed to be sh256 digests
[]
def __init__(self, manifest_json, image_config_json): """ :param manifest_json: :param image_config_json: :param downloaded_blob_list: list of string filenames for blobs downloaded, assumed to be sh256 digests """ self.raw = manifest_json self.image_config = image_config_json self.layer_ids = self._layer_ids() self.history = self._history() self.inferred_dockerfile = self._infer_dockerfile() self.architecture = self._architecture()
[ "def", "__init__", "(", "self", ",", "manifest_json", ",", "image_config_json", ")", ":", "self", ".", "raw", "=", "manifest_json", "self", ".", "image_config", "=", "image_config_json", "self", ".", "layer_ids", "=", "self", ".", "_layer_ids", "(", ")", "se...
https://github.com/anchore/anchore-engine/blob/bb18b70e0cbcad58beb44cd439d00067d8f7ea8b/anchore_engine/util/docker.py#L313-L326
fritzy/SleekXMPP
cc1d470397de768ffcc41d2ed5ac3118d19f09f5
sleekxmpp/plugins/xep_0050/adhoc.py
python
XEP_0050._handle_command_complete
(self, iq)
Process a request to finish the execution of command and terminate the workflow. All data related to the command session will be removed. Arguments: iq -- The command completion request.
Process a request to finish the execution of command and terminate the workflow.
[ "Process", "a", "request", "to", "finish", "the", "execution", "of", "command", "and", "terminate", "the", "workflow", "." ]
def _handle_command_complete(self, iq): """ Process a request to finish the execution of command and terminate the workflow. All data related to the command session will be removed. Arguments: iq -- The command completion request. """ node = iq['command']['node'] sessionid = iq['command']['sessionid'] session = self.sessions.get(sessionid) if session: handler = session['next'] interfaces = session['interfaces'] results = [] for stanza in iq['command']['substanzas']: if stanza.plugin_attrib in interfaces: results.append(stanza) if len(results) == 1: results = results[0] if handler: handler(results, session) del self.sessions[sessionid] payload = session['payload'] if payload is None: payload = [] if not isinstance(payload, list): payload = [payload] for item in payload: register_stanza_plugin(Command, item.__class__, iterable=True) iq.reply() iq['command']['node'] = node iq['command']['sessionid'] = sessionid iq['command']['actions'] = [] iq['command']['status'] = 'completed' iq['command']['notes'] = session['notes'] for item in payload: iq['command'].append(item) iq.send() else: raise XMPPError('item-not-found')
[ "def", "_handle_command_complete", "(", "self", ",", "iq", ")", ":", "node", "=", "iq", "[", "'command'", "]", "[", "'node'", "]", "sessionid", "=", "iq", "[", "'command'", "]", "[", "'sessionid'", "]", "session", "=", "self", ".", "sessions", ".", "ge...
https://github.com/fritzy/SleekXMPP/blob/cc1d470397de768ffcc41d2ed5ac3118d19f09f5/sleekxmpp/plugins/xep_0050/adhoc.py#L399-L449
mrDoctorWho/vk4xmpp
e8f25a16832adb6b93fe8b50afdc9547e429389b
extensions/groupchats.py
python
leaveChat
(chat, jidFrom, reason=None)
Leave chat. Parameters: * chat - chat to leave from * jidFrom - jid to leave with * reason - special reason
Leave chat. Parameters: * chat - chat to leave from * jidFrom - jid to leave with * reason - special reason
[ "Leave", "chat", ".", "Parameters", ":", "*", "chat", "-", "chat", "to", "leave", "from", "*", "jidFrom", "-", "jid", "to", "leave", "with", "*", "reason", "-", "special", "reason" ]
def leaveChat(chat, jidFrom, reason=None): """ Leave chat. Parameters: * chat - chat to leave from * jidFrom - jid to leave with * reason - special reason """ prs = xmpp.Presence(chat, "unavailable", frm=jidFrom, status=reason) sender(Component, prs)
[ "def", "leaveChat", "(", "chat", ",", "jidFrom", ",", "reason", "=", "None", ")", ":", "prs", "=", "xmpp", ".", "Presence", "(", "chat", ",", "\"unavailable\"", ",", "frm", "=", "jidFrom", ",", "status", "=", "reason", ")", "sender", "(", "Component", ...
https://github.com/mrDoctorWho/vk4xmpp/blob/e8f25a16832adb6b93fe8b50afdc9547e429389b/extensions/groupchats.py#L95-L104
ayeowch/bitnodes
5fa4ac3fe8e748d450228ec1fea01b8e61978e5c
protocol.py
python
addr_to_onion_v2
(addr)
return b32encode(addr).lower() + '.onion'
Returns .onion address for the specified v2 onion addr.
Returns .onion address for the specified v2 onion addr.
[ "Returns", ".", "onion", "address", "for", "the", "specified", "v2", "onion", "addr", "." ]
def addr_to_onion_v2(addr): """ Returns .onion address for the specified v2 onion addr. """ return b32encode(addr).lower() + '.onion'
[ "def", "addr_to_onion_v2", "(", "addr", ")", ":", "return", "b32encode", "(", "addr", ")", ".", "lower", "(", ")", "+", "'.onion'" ]
https://github.com/ayeowch/bitnodes/blob/5fa4ac3fe8e748d450228ec1fea01b8e61978e5c/protocol.py#L256-L260
OpenMDAO/OpenMDAO1
791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317
benchmarks/benchmark_multipoint.py
python
Times.__init__
(self, scalar)
[]
def __init__(self, scalar): super(Times, self).__init__() self.add_param('f1', np.random.random()) self.add_output('f2', shape=1) self.scalar = float(scalar)
[ "def", "__init__", "(", "self", ",", "scalar", ")", ":", "super", "(", "Times", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "add_param", "(", "'f1'", ",", "np", ".", "random", ".", "random", "(", ")", ")", "self", ".", "add_output", ...
https://github.com/OpenMDAO/OpenMDAO1/blob/791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317/benchmarks/benchmark_multipoint.py#L21-L25
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/email/_header_value_parser.py
python
EWWhiteSpaceTerminal.value
(self)
return ''
[]
def value(self): return ''
[ "def", "value", "(", "self", ")", ":", "return", "''" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/email/_header_value_parser.py#L936-L937
brainiak/brainiak
ee093597c6c11597b0a59e95b48d2118e40394a5
brainiak/funcalign/srm.py
python
SRM._likelihood
(self, chol_sigma_s_rhos, log_det_psi, chol_sigma_s, trace_xt_invsigma2_x, inv_sigma_s_rhos, wt_invpsi_x, samples)
return loglikehood
Calculate the log-likelihood function Parameters ---------- chol_sigma_s_rhos : array, shape=[features, features] Cholesky factorization of the matrix (Sigma_S + sum_i(1/rho_i^2) * I) log_det_psi : float Determinant of diagonal matrix Psi (containing the rho_i^2 value voxels_i times). chol_sigma_s : array, shape=[features, features] Cholesky factorization of the matrix Sigma_S trace_xt_invsigma2_x : float Trace of :math:`\\sum_i (||X_i||_F^2/\\rho_i^2)` inv_sigma_s_rhos : array, shape=[features, features] Inverse of :math:`(\\Sigma_S + \\sum_i(1/\\rho_i^2) * I)` wt_invpsi_x : array, shape=[features, samples] samples : int The total number of samples in the data. Returns ------- loglikehood : float The log-likelihood value.
Calculate the log-likelihood function
[ "Calculate", "the", "log", "-", "likelihood", "function" ]
def _likelihood(self, chol_sigma_s_rhos, log_det_psi, chol_sigma_s, trace_xt_invsigma2_x, inv_sigma_s_rhos, wt_invpsi_x, samples): """Calculate the log-likelihood function Parameters ---------- chol_sigma_s_rhos : array, shape=[features, features] Cholesky factorization of the matrix (Sigma_S + sum_i(1/rho_i^2) * I) log_det_psi : float Determinant of diagonal matrix Psi (containing the rho_i^2 value voxels_i times). chol_sigma_s : array, shape=[features, features] Cholesky factorization of the matrix Sigma_S trace_xt_invsigma2_x : float Trace of :math:`\\sum_i (||X_i||_F^2/\\rho_i^2)` inv_sigma_s_rhos : array, shape=[features, features] Inverse of :math:`(\\Sigma_S + \\sum_i(1/\\rho_i^2) * I)` wt_invpsi_x : array, shape=[features, samples] samples : int The total number of samples in the data. Returns ------- loglikehood : float The log-likelihood value. """ log_det = (np.log(np.diag(chol_sigma_s_rhos) ** 2).sum() + log_det_psi + np.log(np.diag(chol_sigma_s) ** 2).sum()) loglikehood = -0.5 * samples * log_det - 0.5 * trace_xt_invsigma2_x loglikehood += 0.5 * np.trace( wt_invpsi_x.T.dot(inv_sigma_s_rhos).dot(wt_invpsi_x)) # + const --> -0.5*nTR*nvoxel*subjects*math.log(2*math.pi) return loglikehood
[ "def", "_likelihood", "(", "self", ",", "chol_sigma_s_rhos", ",", "log_det_psi", ",", "chol_sigma_s", ",", "trace_xt_invsigma2_x", ",", "inv_sigma_s_rhos", ",", "wt_invpsi_x", ",", "samples", ")", ":", "log_det", "=", "(", "np", ".", "log", "(", "np", ".", "...
https://github.com/brainiak/brainiak/blob/ee093597c6c11597b0a59e95b48d2118e40394a5/brainiak/funcalign/srm.py#L349-L394
census-instrumentation/opencensus-python
15c122dd7e0187b35f956f5d3b77b78455a2aadb
contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
python
StackdriverStatsExporter.get_metric_type
(self, oc_md)
return namespaced_view_name(oc_md.name, self.options.metric_prefix)
Get a SD metric type for an OC metric descriptor.
Get a SD metric type for an OC metric descriptor.
[ "Get", "a", "SD", "metric", "type", "for", "an", "OC", "metric", "descriptor", "." ]
def get_metric_type(self, oc_md): """Get a SD metric type for an OC metric descriptor.""" return namespaced_view_name(oc_md.name, self.options.metric_prefix)
[ "def", "get_metric_type", "(", "self", ",", "oc_md", ")", ":", "return", "namespaced_view_name", "(", "oc_md", ".", "name", ",", "self", ".", "options", ".", "metric_prefix", ")" ]
https://github.com/census-instrumentation/opencensus-python/blob/15c122dd7e0187b35f956f5d3b77b78455a2aadb/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L265-L267
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/utils/parsers/robots/data_structures.py
python
MultiBody.static
(self, static)
Set the root element in the tree to be static or not.
Set the root element in the tree to be static or not.
[ "Set", "the", "root", "element", "in", "the", "tree", "to", "be", "static", "or", "not", "." ]
def static(self, static): """Set the root element in the tree to be static or not.""" if self.root is not None: self.root.static = static
[ "def", "static", "(", "self", ",", "static", ")", ":", "if", "self", ".", "root", "is", "not", "None", ":", "self", ".", "root", ".", "static", "=", "static" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/utils/parsers/robots/data_structures.py#L950-L953
vahidk/TensorflowFramework
a9377d0dd8f5ac93e810876fbe8987990e3c728f
common/ops/activation_ops.py
python
leaky_relu
(tensor, alpha=0.1)
return tf.maximum(tensor, alpha * tensor)
Computes the leaky rectified linear activation.
Computes the leaky rectified linear activation.
[ "Computes", "the", "leaky", "rectified", "linear", "activation", "." ]
def leaky_relu(tensor, alpha=0.1): """Computes the leaky rectified linear activation.""" return tf.maximum(tensor, alpha * tensor)
[ "def", "leaky_relu", "(", "tensor", ",", "alpha", "=", "0.1", ")", ":", "return", "tf", ".", "maximum", "(", "tensor", ",", "alpha", "*", "tensor", ")" ]
https://github.com/vahidk/TensorflowFramework/blob/a9377d0dd8f5ac93e810876fbe8987990e3c728f/common/ops/activation_ops.py#L13-L15
rytilahti/python-miio
b6e53dd16fac77915426e7592e2528b78ef65190
miio/gateway/devices/subdevice.py
python
SubDevice.get_voltage
(self)
return self._voltage
Update the battery voltage, if available.
Update the battery voltage, if available.
[ "Update", "the", "battery", "voltage", "if", "available", "." ]
def get_voltage(self) -> Optional[float]: """Update the battery voltage, if available.""" if not self._battery_powered: _LOGGER.debug( "%s is not battery powered, get_voltage not supported", self.name, ) return None if self._gw.model in [GATEWAY_MODEL_EU, GATEWAY_MODEL_ZIG3]: self._voltage = self.get_property("voltage").pop() / 1000 else: _LOGGER.info( "Gateway model '%s' does not (yet) support get_voltage", self._gw.model, ) return self._voltage
[ "def", "get_voltage", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "if", "not", "self", ".", "_battery_powered", ":", "_LOGGER", ".", "debug", "(", "\"%s is not battery powered, get_voltage not supported\"", ",", "self", ".", "name", ",", ")", "...
https://github.com/rytilahti/python-miio/blob/b6e53dd16fac77915426e7592e2528b78ef65190/miio/gateway/devices/subdevice.py#L234-L250
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/mutagen/flac.py
python
FLAC.__check_header
(self, fileobj, name)
return size
Returns the offset of the flac block start (skipping id3 tags if found). The passed fileobj will be advanced to that offset as well.
Returns the offset of the flac block start (skipping id3 tags if found). The passed fileobj will be advanced to that offset as well.
[ "Returns", "the", "offset", "of", "the", "flac", "block", "start", "(", "skipping", "id3", "tags", "if", "found", ")", ".", "The", "passed", "fileobj", "will", "be", "advanced", "to", "that", "offset", "as", "well", "." ]
def __check_header(self, fileobj, name): """Returns the offset of the flac block start (skipping id3 tags if found). The passed fileobj will be advanced to that offset as well. """ size = 4 header = fileobj.read(4) if header != b"fLaC": size = None if header[:3] == b"ID3": size = 14 + BitPaddedInt(fileobj.read(6)[2:]) fileobj.seek(size - 4) if fileobj.read(4) != b"fLaC": size = None if size is None: raise FLACNoHeaderError( "%r is not a valid FLAC file" % name) return size
[ "def", "__check_header", "(", "self", ",", "fileobj", ",", "name", ")", ":", "size", "=", "4", "header", "=", "fileobj", ".", "read", "(", "4", ")", "if", "header", "!=", "b\"fLaC\"", ":", "size", "=", "None", "if", "header", "[", ":", "3", "]", ...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/mutagen/flac.py#L897-L915
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar.keys
(self)
return list(self.iterkeys())
Dict-like keys() that returns a list of names of cookies from the jar. .. seealso:: values() and items().
Dict-like keys() that returns a list of names of cookies from the jar.
[ "Dict", "-", "like", "keys", "()", "that", "returns", "a", "list", "of", "names", "of", "cookies", "from", "the", "jar", "." ]
def keys(self): """Dict-like keys() that returns a list of names of cookies from the jar. .. seealso:: values() and items(). """ return list(self.iterkeys())
[ "def", "keys", "(", "self", ")", ":", "return", "list", "(", "self", ".", "iterkeys", "(", ")", ")" ]
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pip/_vendor/requests/cookies.py#L228-L234
nccgroup/fuzzowski
a9f96700a2697a66f5d7af5e817835bd3f1f790c
fuzzowski/loggers/fuzz_logger_file.py
python
FuzzLoggerFile.log_send
(self, data)
Records data as about to be sent to the target. :param data: Transmitted data :type data: bytes :return: None :rtype: None
Records data as about to be sent to the target.
[ "Records", "data", "as", "about", "to", "be", "sent", "to", "the", "target", "." ]
def log_send(self, data): """ Records data as about to be sent to the target. :param data: Transmitted data :type data: bytes :return: None :rtype: None """ self._tx_count += 1 filename = "{0}-tx-{1}.txt".format(self._current_id, self._tx_count) full_name = os.path.join(self._path, filename) # Write data in binary mode to avoid newline conversion with open(full_name, "wb") as file_handle: file_handle.write(data)
[ "def", "log_send", "(", "self", ",", "data", ")", ":", "self", ".", "_tx_count", "+=", "1", "filename", "=", "\"{0}-tx-{1}.txt\"", ".", "format", "(", "self", ".", "_current_id", ",", "self", ".", "_tx_count", ")", "full_name", "=", "os", ".", "path", ...
https://github.com/nccgroup/fuzzowski/blob/a9f96700a2697a66f5d7af5e817835bd3f1f790c/fuzzowski/loggers/fuzz_logger_file.py#L63-L80
Netflix/vmaf
e768a2be57116c76bf33be7f8ee3566d8b774664
python/vmaf/tools/misc.py
python
parallel_map
(func, list_args, processes=None)
return rets
Build my own parallelized map function since multiprocessing's Process(), or Pool.map() cannot meet my both needs: 1) be able to control the maximum number of processes in parallel 2) be able to take in non-picklable objects as arguments
Build my own parallelized map function since multiprocessing's Process(), or Pool.map() cannot meet my both needs: 1) be able to control the maximum number of processes in parallel 2) be able to take in non-picklable objects as arguments
[ "Build", "my", "own", "parallelized", "map", "function", "since", "multiprocessing", "s", "Process", "()", "or", "Pool", ".", "map", "()", "cannot", "meet", "my", "both", "needs", ":", "1", ")", "be", "able", "to", "control", "the", "maximum", "number", ...
def parallel_map(func, list_args, processes=None): """ Build my own parallelized map function since multiprocessing's Process(), or Pool.map() cannot meet my both needs: 1) be able to control the maximum number of processes in parallel 2) be able to take in non-picklable objects as arguments """ # get maximum number of active processes that can be used max_active_procs = processes if processes is not None else multiprocessing.cpu_count() # create shared dictionary return_dict = multiprocessing.Manager().dict() # define runner function def func_wrapper(idx_args): idx, args = idx_args executor = func(args) return_dict[idx] = executor # add idx to args list_idx_args = [] for idx, args in enumerate(list_args): list_idx_args.append((idx, args)) procs = [] for idx_args in list_idx_args: proc = multiprocessing.Process(target=func_wrapper, args=(idx_args,)) procs.append(proc) waiting_procs = set(procs) active_procs = set([]) # processing while True: # check if any procs in active_procs is done; if yes, remove them for p in active_procs.copy(): if not p.is_alive(): active_procs.remove(p) # check if can add a proc to active_procs (add gradually one per loop) if len(active_procs) < max_active_procs and len(waiting_procs) > 0: # move one proc from waiting_procs to active_procs p = waiting_procs.pop() active_procs.add(p) p.start() # if both waiting_procs and active_procs are empty, can terminate if len(waiting_procs) == 0 and len(active_procs) == 0: break sleep(0.01) # check every x sec # finally, collect results rets = list(map(lambda idx: return_dict[idx], range(len(list_args)))) return rets
[ "def", "parallel_map", "(", "func", ",", "list_args", ",", "processes", "=", "None", ")", ":", "# get maximum number of active processes that can be used", "max_active_procs", "=", "processes", "if", "processes", "is", "not", "None", "else", "multiprocessing", ".", "c...
https://github.com/Netflix/vmaf/blob/e768a2be57116c76bf33be7f8ee3566d8b774664/python/vmaf/tools/misc.py#L293-L349
tonybaloney/wily
e72b7d95228bbe5538a072dc5d1186daa318bb03
src/wily/cache.py
python
exists
(config)
return True
Check whether the .wily/ directory exists. :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: Whether the .wily directory exists :rtype: ``boolean``
Check whether the .wily/ directory exists.
[ "Check", "whether", "the", ".", "wily", "/", "directory", "exists", "." ]
def exists(config): """ Check whether the .wily/ directory exists. :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: Whether the .wily directory exists :rtype: ``boolean`` """ exists = ( pathlib.Path(config.cache_path).exists() and pathlib.Path(config.cache_path).is_dir() ) if not exists: return False index_path = pathlib.Path(config.cache_path) / "index.json" if index_path.exists(): with open(index_path, "r") as out: index = json.load(out) if index["version"] != __version__: # TODO: Inspect the versions properly. logger.warning( "Wily cache is old, you may incur errors until you rebuild the cache." ) else: logger.warning( "Wily cache was not versioned, you may incur errors until you rebuild the cache." ) create_index(config) return True
[ "def", "exists", "(", "config", ")", ":", "exists", "=", "(", "pathlib", ".", "Path", "(", "config", ".", "cache_path", ")", ".", "exists", "(", ")", "and", "pathlib", ".", "Path", "(", "config", ".", "cache_path", ")", ".", "is_dir", "(", ")", ")"...
https://github.com/tonybaloney/wily/blob/e72b7d95228bbe5538a072dc5d1186daa318bb03/src/wily/cache.py#L20-L50
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/DocXMLRPCServer.py
python
XMLRPCDocGenerator.set_server_name
(self, server_name)
Set the name of the generated HTML server documentation
Set the name of the generated HTML server documentation
[ "Set", "the", "name", "of", "the", "generated", "HTML", "server", "documentation" ]
def set_server_name(self, server_name): """Set the name of the generated HTML server documentation""" self.server_name = server_name
[ "def", "set_server_name", "(", "self", ",", "server_name", ")", ":", "self", ".", "server_name", "=", "server_name" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/DocXMLRPCServer.py#L154-L157
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/db/backends/__init__.py
python
BaseDatabaseOperations.field_cast_sql
(self, db_type)
return '%s'
Given a column type (e.g. 'BLOB', 'VARCHAR'), returns the SQL necessary to cast it before using it in a WHERE statement. Note that the resulting string should contain a '%s' placeholder for the column being searched against.
Given a column type (e.g. 'BLOB', 'VARCHAR'), returns the SQL necessary to cast it before using it in a WHERE statement. Note that the resulting string should contain a '%s' placeholder for the column being searched against.
[ "Given", "a", "column", "type", "(", "e", ".", "g", ".", "BLOB", "VARCHAR", ")", "returns", "the", "SQL", "necessary", "to", "cast", "it", "before", "using", "it", "in", "a", "WHERE", "statement", ".", "Note", "that", "the", "resulting", "string", "sho...
def field_cast_sql(self, db_type): """ Given a column type (e.g. 'BLOB', 'VARCHAR'), returns the SQL necessary to cast it before using it in a WHERE statement. Note that the resulting string should contain a '%s' placeholder for the column being searched against. """ return '%s'
[ "def", "field_cast_sql", "(", "self", ",", "db_type", ")", ":", "return", "'%s'" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/db/backends/__init__.py#L579-L586
reingart/pyafipws
3141894e82d538e297a85b8bc960016a3a871fbe
wsfev1.py
python
WSFEv1.ParamGetPtosVenta
(self, sep="|")
return [ ( u"%(Nro)s\tEmisionTipo:%(EmisionTipo)s\tBloqueado:%(Bloqueado)s\tFchBaja:%(FchBaja)s" % p["PtoVenta"] ).replace("\t", sep) for p in res.get("ResultGet", []) ]
Recuperador de valores referenciales Puntos de Venta registrados
Recuperador de valores referenciales Puntos de Venta registrados
[ "Recuperador", "de", "valores", "referenciales", "Puntos", "de", "Venta", "registrados" ]
def ParamGetPtosVenta(self, sep="|"): "Recuperador de valores referenciales Puntos de Venta registrados" ret = self.client.FEParamGetPtosVenta( Auth={"Token": self.Token, "Sign": self.Sign, "Cuit": self.Cuit}, ) res = ret.get("FEParamGetPtosVentaResult", {}) return [ ( u"%(Nro)s\tEmisionTipo:%(EmisionTipo)s\tBloqueado:%(Bloqueado)s\tFchBaja:%(FchBaja)s" % p["PtoVenta"] ).replace("\t", sep) for p in res.get("ResultGet", []) ]
[ "def", "ParamGetPtosVenta", "(", "self", ",", "sep", "=", "\"|\"", ")", ":", "ret", "=", "self", ".", "client", ".", "FEParamGetPtosVenta", "(", "Auth", "=", "{", "\"Token\"", ":", "self", ".", "Token", ",", "\"Sign\"", ":", "self", ".", "Sign", ",", ...
https://github.com/reingart/pyafipws/blob/3141894e82d538e297a85b8bc960016a3a871fbe/wsfev1.py#L1242-L1254
pysathq/pysat
07bf3a5a4428d40eca804e7ebdf4f496aadf4213
pysat/solvers.py
python
Minisat22.solve_limited
(self, assumptions=[], expect_interrupt=False)
Solve internal formula using given budgets for conflicts and propagations.
Solve internal formula using given budgets for conflicts and propagations.
[ "Solve", "internal", "formula", "using", "given", "budgets", "for", "conflicts", "and", "propagations", "." ]
def solve_limited(self, assumptions=[], expect_interrupt=False): """ Solve internal formula using given budgets for conflicts and propagations. """ if self.minisat: if self.use_timer: start_time = process_time() self.status = pysolvers.minisat22_solve_lim(self.minisat, assumptions, int(MainThread.check()), int(expect_interrupt)) if self.use_timer: self.call_time = process_time() - start_time self.accu_time += self.call_time return self.status
[ "def", "solve_limited", "(", "self", ",", "assumptions", "=", "[", "]", ",", "expect_interrupt", "=", "False", ")", ":", "if", "self", ".", "minisat", ":", "if", "self", ".", "use_timer", ":", "start_time", "=", "process_time", "(", ")", "self", ".", "...
https://github.com/pysathq/pysat/blob/07bf3a5a4428d40eca804e7ebdf4f496aadf4213/pysat/solvers.py#L4568-L4585
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/conf/__init__.py
python
BaseSettings.__setattr__
(self, name, value)
[]
def __setattr__(self, name, value): if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'): raise ImproperlyConfigured("If set, %s must end with a slash" % name) object.__setattr__(self, name, value)
[ "def", "__setattr__", "(", "self", ",", "name", ",", "value", ")", ":", "if", "name", "in", "(", "\"MEDIA_URL\"", ",", "\"STATIC_URL\"", ")", "and", "value", "and", "not", "value", ".", "endswith", "(", "'/'", ")", ":", "raise", "ImproperlyConfigured", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/conf/__init__.py#L81-L84
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/binary_tree.py
python
BinaryTree.hook_number
(self)
return 1 + sum(t.hook_number() for t in self.comb('left') + self.comb('right'))
r""" Return the number of hooks. Recalling that a branch is a path from a vertex of the tree to a leaf, the leftmost (resp. rightmost) branch of a vertex `v` is the branch from `v` made only of left (resp. right) edges. The hook of a vertex `v` is a set of vertices formed by the union of `{v}`, and the vertices of its leftmost and rightmost branches. There is a unique way to partition the set of vertices in hooks. The number of hooks in such a partition is the hook number of the tree. We can obtain this partition recursively by extracting the root's hook and iterating the processus on each tree of the remaining forest. EXAMPLES:: sage: BT = BinaryTree( '.' ) sage: BT.hook_number() 0 sage: BT = BinaryTree( '[.,.]' ) sage: BT.hook_number() 1 sage: BT = BinaryTree( '[[[.,.], .], [.,.]]' ); ascii_art(BT) o / \ o o / o sage: BT.hook_number() 1 sage: BT = BinaryTree( '[[[[., [., .]], .], [[., .], [[[., .], [., .]], [., .]]]], [., [[[., .], [[[., .], [., .]], .]], .]]]' ) sage: ascii_art(BT) ________o________ / \ __o__ o / \ \ o __o___ o / / \ / o o _o_ __o__ \ / \ / \ o o o o o / \ / o o o / \ o o sage: BT.hook_number() 6
r""" Return the number of hooks.
[ "r", "Return", "the", "number", "of", "hooks", "." ]
def hook_number(self): r""" Return the number of hooks. Recalling that a branch is a path from a vertex of the tree to a leaf, the leftmost (resp. rightmost) branch of a vertex `v` is the branch from `v` made only of left (resp. right) edges. The hook of a vertex `v` is a set of vertices formed by the union of `{v}`, and the vertices of its leftmost and rightmost branches. There is a unique way to partition the set of vertices in hooks. The number of hooks in such a partition is the hook number of the tree. We can obtain this partition recursively by extracting the root's hook and iterating the processus on each tree of the remaining forest. EXAMPLES:: sage: BT = BinaryTree( '.' ) sage: BT.hook_number() 0 sage: BT = BinaryTree( '[.,.]' ) sage: BT.hook_number() 1 sage: BT = BinaryTree( '[[[.,.], .], [.,.]]' ); ascii_art(BT) o / \ o o / o sage: BT.hook_number() 1 sage: BT = BinaryTree( '[[[[., [., .]], .], [[., .], [[[., .], [., .]], [., .]]]], [., [[[., .], [[[., .], [., .]], .]], .]]]' ) sage: ascii_art(BT) ________o________ / \ __o__ o / \ \ o __o___ o / / \ / o o _o_ __o__ \ / \ / \ o o o o o / \ / o o o / \ o o sage: BT.hook_number() 6 """ if self.is_empty(): return 0 return 1 + sum(t.hook_number() for t in self.comb('left') + self.comb('right'))
[ "def", "hook_number", "(", "self", ")", ":", "if", "self", ".", "is_empty", "(", ")", ":", "return", "0", "return", "1", "+", "sum", "(", "t", ".", "hook_number", "(", ")", "for", "t", "in", "self", ".", "comb", "(", "'left'", ")", "+", "self", ...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/binary_tree.py#L2600-L2654
openbmc/openbmc
5f4109adae05f4d6925bfe960007d52f98c61086
poky/bitbake/lib/bb/pysh/pyshyacc.py
python
p_else_part
(p)
else_part : Elif compound_list then_word compound_list else_part | Elif compound_list then_word compound_list | Else compound_list
else_part : Elif compound_list then_word compound_list else_part | Elif compound_list then_word compound_list | Else compound_list
[ "else_part", ":", "Elif", "compound_list", "then_word", "compound_list", "else_part", "|", "Elif", "compound_list", "then_word", "compound_list", "|", "Else", "compound_list" ]
def p_else_part(p): """else_part : Elif compound_list then_word compound_list else_part | Elif compound_list then_word compound_list | Else compound_list""" if len(p)==3: p[0] = p[2][1:] else: else_part = [] if len(p)==6: else_part = p[5] p[0] = ('elif', IfCond(p[2][1:], p[4][1:], else_part))
[ "def", "p_else_part", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "3", ":", "p", "[", "0", "]", "=", "p", "[", "2", "]", "[", "1", ":", "]", "else", ":", "else_part", "=", "[", "]", "if", "len", "(", "p", ")", "==", "6", ":", ...
https://github.com/openbmc/openbmc/blob/5f4109adae05f4d6925bfe960007d52f98c61086/poky/bitbake/lib/bb/pysh/pyshyacc.py#L362-L372
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/requests/packages/urllib3/response.py
python
HTTPResponse.fileno
(self)
[]
def fileno(self): if self._fp is None: raise IOError("HTTPResponse has no file to get a fileno from") elif hasattr(self._fp, "fileno"): return self._fp.fileno() else: raise IOError("The file-like object this HTTPResponse is wrapped " "around has no file descriptor")
[ "def", "fileno", "(", "self", ")", ":", "if", "self", ".", "_fp", "is", "None", ":", "raise", "IOError", "(", "\"HTTPResponse has no file to get a fileno from\"", ")", "elif", "hasattr", "(", "self", ".", "_fp", ",", "\"fileno\"", ")", ":", "return", "self",...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/requests/packages/urllib3/response.py#L417-L424
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/xml/sax/handler.py
python
ContentHandler.ignorableWhitespace
(self, whitespace)
Receive notification of ignorable whitespace in element content. Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models. SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information.
Receive notification of ignorable whitespace in element content.
[ "Receive", "notification", "of", "ignorable", "whitespace", "in", "element", "content", "." ]
def ignorableWhitespace(self, whitespace): """Receive notification of ignorable whitespace in element content. Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models. SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information."""
[ "def", "ignorableWhitespace", "(", "self", ",", "whitespace", ")", ":" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/xml/sax/handler.py#L168-L180
statsmodels/statsmodels
debbe7ea6ba28fe5bdb78f09f8cac694bef98722
statsmodels/tsa/vector_ar/var_model.py
python
VARResults.sample_acov
(self, nlags=1)
return _compute_acov(self.endog[self.k_ar :], nlags=nlags)
Sample acov
Sample acov
[ "Sample", "acov" ]
def sample_acov(self, nlags=1): """Sample acov""" return _compute_acov(self.endog[self.k_ar :], nlags=nlags)
[ "def", "sample_acov", "(", "self", ",", "nlags", "=", "1", ")", ":", "return", "_compute_acov", "(", "self", ".", "endog", "[", "self", ".", "k_ar", ":", "]", ",", "nlags", "=", "nlags", ")" ]
https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/tsa/vector_ar/var_model.py#L1420-L1422
JordyZomer/autoSubTakeover
3825a35a34043d71843cd1ced8fa468198ae7587
autosubtakeover/_version.py
python
render_pep440_old
(pieces)
return rendered
TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0]
TAG[.postDISTANCE[.dev0]] .
[ "TAG", "[", ".", "postDISTANCE", "[", ".", "dev0", "]]", "." ]
def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered
[ "def", "render_pep440_old", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", "or", "pieces", "[", "\"dirty\"", "]", ":", "rendered", ...
https://github.com/JordyZomer/autoSubTakeover/blob/3825a35a34043d71843cd1ced8fa468198ae7587/autosubtakeover/_version.py#L417-L436
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/contrib/gis/db/models/functions.py
python
Length.as_sqlite
(self, compiler, connection)
return super(Length, self).as_sql(compiler, connection)
[]
def as_sqlite(self, compiler, connection): geo_field = GeometryField(srid=self.srid) if geo_field.geodetic(connection): if self.spheroid: self.function = 'GeodesicLength' else: self.function = 'GreatCircleLength' return super(Length, self).as_sql(compiler, connection)
[ "def", "as_sqlite", "(", "self", ",", "compiler", ",", "connection", ")", ":", "geo_field", "=", "GeometryField", "(", "srid", "=", "self", ".", "srid", ")", "if", "geo_field", ".", "geodetic", "(", "connection", ")", ":", "if", "self", ".", "spheroid", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/gis/db/models/functions.py#L313-L320
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
libs/requests/packages/urllib3/packages/ordered_dict.py
python
OrderedDict.clear
(self)
od.clear() -> None. Remove all items from od.
od.clear() -> None. Remove all items from od.
[ "od", ".", "clear", "()", "-", ">", "None", ".", "Remove", "all", "items", "from", "od", "." ]
def clear(self): 'od.clear() -> None. Remove all items from od.' try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass dict.clear(self)
[ "def", "clear", "(", "self", ")", ":", "try", ":", "for", "node", "in", "self", ".", "__map", ".", "itervalues", "(", ")", ":", "del", "node", "[", ":", "]", "root", "=", "self", ".", "__root", "root", "[", ":", "]", "=", "[", "root", ",", "r...
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/requests/packages/urllib3/packages/ordered_dict.py#L79-L89
google/coursebuilder-core
08f809db3226d9269e30d5edd0edd33bd22041f4
coursebuilder/common/utc.py
python
hour_start
(seconds)
return (seconds // _SECONDS_PER_HOUR) * _SECONDS_PER_HOUR
Truncates a POSIX timestamp to the start of that hour (HH:00:00). Args: seconds: an arbitrary UTC time, as seconds since epoch (stored in whatever time.gmtime will accept, i.e. int, long, or float). Returns: The supplied UTC time truncated to HH:00:00 of that same hour, as whole seconds since epoch.
Truncates a POSIX timestamp to the start of that hour (HH:00:00).
[ "Truncates", "a", "POSIX", "timestamp", "to", "the", "start", "of", "that", "hour", "(", "HH", ":", "00", ":", "00", ")", "." ]
def hour_start(seconds): """Truncates a POSIX timestamp to the start of that hour (HH:00:00). Args: seconds: an arbitrary UTC time, as seconds since epoch (stored in whatever time.gmtime will accept, i.e. int, long, or float). Returns: The supplied UTC time truncated to HH:00:00 of that same hour, as whole seconds since epoch. """ # datetime alternative: # # if seconds is None: # utc_dt = datetime.datetime.utcnow() # else: # utc_dt = datetime.datetime.utcfromtimestamp(seconds) # day_dt = utc_dt.replace(minute=0, second=0) # return long(calendar.timegm(day_dt.utctimetuple())) # # struct_time alternative: # # gmt_st = time.gmtime(seconds) # Convert UTC seconds to struct_time. # day_st = (gmt_st.tm_year, gmt_st.tm_mon, gmt_st.tm_mday, # gmt_st.tm_hour, 0, 0, # Force to HH:00:00. # gmt_st.tm_wday, gmt_st.tm_yday, gmt_st.tm_isdst) # return long(calendar.timegm(day_st)) # Back to seconds since epoch. return (seconds // _SECONDS_PER_HOUR) * _SECONDS_PER_HOUR
[ "def", "hour_start", "(", "seconds", ")", ":", "# datetime alternative:", "#", "# if seconds is None:", "# utc_dt = datetime.datetime.utcnow()", "# else:", "# utc_dt = datetime.datetime.utcfromtimestamp(seconds)", "# day_dt = utc_dt.replace(minute=0, second=0)", "# return l...
https://github.com/google/coursebuilder-core/blob/08f809db3226d9269e30d5edd0edd33bd22041f4/coursebuilder/common/utc.py#L213-L239
python-cmd2/cmd2
c1f6114d52161a3b8a32d3cee1c495d79052e1fb
examples/colors.py
python
CmdLineApp.do_timetravel
(self, _)
A command which always generates an error message, to demonstrate custom error colors
A command which always generates an error message, to demonstrate custom error colors
[ "A", "command", "which", "always", "generates", "an", "error", "message", "to", "demonstrate", "custom", "error", "colors" ]
def do_timetravel(self, _): """A command which always generates an error message, to demonstrate custom error colors""" self.perror('Mr. Fusion failed to start. Could not energize flux capacitor.')
[ "def", "do_timetravel", "(", "self", ",", "_", ")", ":", "self", ".", "perror", "(", "'Mr. Fusion failed to start. Could not energize flux capacitor.'", ")" ]
https://github.com/python-cmd2/cmd2/blob/c1f6114d52161a3b8a32d3cee1c495d79052e1fb/examples/colors.py#L82-L84
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
pytorch/pytorchcv/models/preresnet_cifar.py
python
preresnet164bn_cifar100
(num_classes=100, **kwargs)
return get_preresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name="preresnet164bn_cifar100", **kwargs)
PreResNet-164(BN) model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- num_classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location for keeping the model parameters.
PreResNet-164(BN) model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027.
[ "PreResNet", "-", "164", "(", "BN", ")", "model", "for", "CIFAR", "-", "100", "from", "Identity", "Mappings", "in", "Deep", "Residual", "Networks", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1603", ".", "05027", "." ]
def preresnet164bn_cifar100(num_classes=100, **kwargs): """ PreResNet-164(BN) model for CIFAR-100 from 'Identity Mappings in Deep Residual Networks,' https://arxiv.org/abs/1603.05027. Parameters: ---------- num_classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location for keeping the model parameters. """ return get_preresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name="preresnet164bn_cifar100", **kwargs)
[ "def", "preresnet164bn_cifar100", "(", "num_classes", "=", "100", ",", "*", "*", "kwargs", ")", ":", "return", "get_preresnet_cifar", "(", "num_classes", "=", "num_classes", ",", "blocks", "=", "164", ",", "bottleneck", "=", "True", ",", "model_name", "=", "...
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/pytorch/pytorchcv/models/preresnet_cifar.py#L335-L350
seppius-xbmc-repo/ru
d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2
plugin.video.online.anidub.com/resources/lib/BeautifulSoup.py
python
BeautifulStoneSoup.handle_charref
(self, ref)
Handle character references as data.
Handle character references as data.
[ "Handle", "character", "references", "as", "data", "." ]
def handle_charref(self, ref): "Handle character references as data." if self.convertEntities: data = unichr(int(ref)) else: data = '&#%s;' % ref self.handle_data(data)
[ "def", "handle_charref", "(", "self", ",", "ref", ")", ":", "if", "self", ".", "convertEntities", ":", "data", "=", "unichr", "(", "int", "(", "ref", ")", ")", "else", ":", "data", "=", "'&#%s;'", "%", "ref", "self", ".", "handle_data", "(", "data", ...
https://github.com/seppius-xbmc-repo/ru/blob/d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2/plugin.video.online.anidub.com/resources/lib/BeautifulSoup.py#L1392-L1398
bittorrent/btc
b12f1523a2ef86b57bc72af1ae2c550040417014
btc/bencode.py
python
encode_dict
(x,r)
[]
def encode_dict(x,r): r.append(b'd') ilist = list(x.items()) ilist.sort() for k, v in ilist: r.extend((bytes(str(len(k)), 'ascii'), b':', k)) encode_func[type(v)](v, r) r.append(b'e')
[ "def", "encode_dict", "(", "x", ",", "r", ")", ":", "r", ".", "append", "(", "b'd'", ")", "ilist", "=", "list", "(", "x", ".", "items", "(", ")", ")", "ilist", ".", "sort", "(", ")", "for", "k", ",", "v", "in", "ilist", ":", "r", ".", "exte...
https://github.com/bittorrent/btc/blob/b12f1523a2ef86b57bc72af1ae2c550040417014/btc/bencode.py#L129-L136
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/idlelib/configDialog.py
python
ConfigDialog.VarChanged_highlightTarget
(self, *params)
[]
def VarChanged_highlightTarget(self, *params): self.SetHighlightTarget()
[ "def", "VarChanged_highlightTarget", "(", "self", ",", "*", "params", ")", ":", "self", ".", "SetHighlightTarget", "(", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/idlelib/configDialog.py#L555-L556
mahmoud/lithoxyl
b4bfa92c54df85b4bd5935fe270e2aa3fb25c412
lithoxyl/utils.py
python
reseed_guid
()
return
This is called automatically on fork by the functions below. You probably don't need to call this.
This is called automatically on fork by the functions below. You probably don't need to call this.
[ "This", "is", "called", "automatically", "on", "fork", "by", "the", "functions", "below", ".", "You", "probably", "don", "t", "need", "to", "call", "this", "." ]
def reseed_guid(): """This is called automatically on fork by the functions below. You probably don't need to call this. """ global _PID global _GUID_SALT global _GUID_START try: random_hex = os.urandom(4).hex() except AttributeError: # py2 random_hex = binascii.hexlify(os.urandom(4)) _PID = getpid() _GUID_SALT = '-'.join([str(getpid()), socket.gethostname() or '<nohostname>', str(time.time()), random_hex]) _GUID_START = int(hashlib.sha1(_GUID_SALT.encode('utf8')).hexdigest()[:24], 16) return
[ "def", "reseed_guid", "(", ")", ":", "global", "_PID", "global", "_GUID_SALT", "global", "_GUID_START", "try", ":", "random_hex", "=", "os", ".", "urandom", "(", "4", ")", ".", "hex", "(", ")", "except", "AttributeError", ":", "# py2", "random_hex", "=", ...
https://github.com/mahmoud/lithoxyl/blob/b4bfa92c54df85b4bd5935fe270e2aa3fb25c412/lithoxyl/utils.py#L184-L205
Zulko/easyAI
a5cbd0b600ebbeadc3730df9e7a211d7643cff8b
easyAI/games/ConnectFour.py
python
ConnectFour.show
(self)
[]
def show(self): print( "\n" + "\n".join( ["0 1 2 3 4 5 6", 13 * "-"] + [ " ".join([[".", "O", "X"][self.board[5 - j][i]] for i in range(7)]) for j in range(6) ] ) )
[ "def", "show", "(", "self", ")", ":", "print", "(", "\"\\n\"", "+", "\"\\n\"", ".", "join", "(", "[", "\"0 1 2 3 4 5 6\"", ",", "13", "*", "\"-\"", "]", "+", "[", "\" \"", ".", "join", "(", "[", "[", "\".\"", ",", "\"O\"", ",", "\"X\"", "]", "[",...
https://github.com/Zulko/easyAI/blob/a5cbd0b600ebbeadc3730df9e7a211d7643cff8b/easyAI/games/ConnectFour.py#L32-L42
bnpy/bnpy
d5b311e8f58ccd98477f4a0c8a4d4982e3fca424
bnpy/obsmodel/AutoRegGaussObsModel.py
python
AutoRegGaussObsModel.__init__
(self, inferType='EM', D=None, E=None, min_covar=None, Data=None, **PriorArgs)
Initialize bare obsmodel with valid prior hyperparameters. Resulting object lacks either EstParams or Post, which must be created separately (see init_global_params).
Initialize bare obsmodel with valid prior hyperparameters.
[ "Initialize", "bare", "obsmodel", "with", "valid", "prior", "hyperparameters", "." ]
def __init__(self, inferType='EM', D=None, E=None, min_covar=None, Data=None, **PriorArgs): ''' Initialize bare obsmodel with valid prior hyperparameters. Resulting object lacks either EstParams or Post, which must be created separately (see init_global_params). ''' # Set dimension D if Data is not None: D = Data.X.shape[1] else: assert D is not None D = int(D) self.D = D # Set dimension E if Data is not None: E = Data.Xprev.shape[1] else: assert E is not None E = int(E) self.E = E self.K = 0 self.inferType = inferType self.min_covar = min_covar self.createPrior(Data, D=D, E=E, **PriorArgs) self.Cache = dict()
[ "def", "__init__", "(", "self", ",", "inferType", "=", "'EM'", ",", "D", "=", "None", ",", "E", "=", "None", ",", "min_covar", "=", "None", ",", "Data", "=", "None", ",", "*", "*", "PriorArgs", ")", ":", "# Set dimension D", "if", "Data", "is", "no...
https://github.com/bnpy/bnpy/blob/d5b311e8f58ccd98477f4a0c8a4d4982e3fca424/bnpy/obsmodel/AutoRegGaussObsModel.py#L45-L74
uqfoundation/multiprocess
028cc73f02655e6451d92e5147d19d8c10aebe50
py3.6/multiprocess/spawn.py
python
get_command_line
(**kwds)
Returns prefix of command line used for spawning a child process
Returns prefix of command line used for spawning a child process
[ "Returns", "prefix", "of", "command", "line", "used", "for", "spawning", "a", "child", "process" ]
def get_command_line(**kwds): ''' Returns prefix of command line used for spawning a child process ''' if getattr(sys, 'frozen', False): return ([sys.executable, '--multiprocessing-fork'] + ['%s=%r' % item for item in kwds.items()]) else: prog = 'from multiprocess.spawn import spawn_main; spawn_main(%s)' prog %= ', '.join('%s=%r' % item for item in kwds.items()) opts = util._args_from_interpreter_flags() return [_python_exe] + opts + ['-c', prog, '--multiprocessing-fork']
[ "def", "get_command_line", "(", "*", "*", "kwds", ")", ":", "if", "getattr", "(", "sys", ",", "'frozen'", ",", "False", ")", ":", "return", "(", "[", "sys", ".", "executable", ",", "'--multiprocessing-fork'", "]", "+", "[", "'%s=%r'", "%", "item", "for...
https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py3.6/multiprocess/spawn.py#L78-L89
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/fate_client/pipeline/component/component_base.py
python
Component._decrease_instance_count
(cls)
[]
def _decrease_instance_count(cls): cls.__instance[cls.__name__.lower()] -= 1 LOGGER.debug(f"decrease instance count")
[ "def", "_decrease_instance_count", "(", "cls", ")", ":", "cls", ".", "__instance", "[", "cls", ".", "__name__", ".", "lower", "(", ")", "]", "-=", "1", "LOGGER", ".", "debug", "(", "f\"decrease instance count\"", ")" ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/fate_client/pipeline/component/component_base.py#L94-L96
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/requests/packages/chardet/chardistribution.py
python
EUCTWDistributionAnalysis.get_order
(self, aBuf)
[]
def get_order(self, aBuf): # for euc-TW encoding, we are interested # first byte range: 0xc4 -- 0xfe # second byte range: 0xa1 -- 0xfe # no validation needed here. State machine has done that first_char = wrap_ord(aBuf[0]) if first_char >= 0xC4: return 94 * (first_char - 0xC4) + wrap_ord(aBuf[1]) - 0xA1 else: return -1
[ "def", "get_order", "(", "self", ",", "aBuf", ")", ":", "# for euc-TW encoding, we are interested", "# first byte range: 0xc4 -- 0xfe", "# second byte range: 0xa1 -- 0xfe", "# no validation needed here. State machine has done that", "first_char", "=", "wrap_ord", "(", "aBuf", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/requests/packages/chardet/chardistribution.py#L118-L127
nipy/nibabel
4703f4d8e32be4cec30e829c2d93ebe54759bb62
nibabel/gifti/gifti.py
python
GiftiMetaData.__init__
(self, nvpair=None)
[]
def __init__(self, nvpair=None): self.data = [] if nvpair is not None: self.data.append(nvpair)
[ "def", "__init__", "(", "self", ",", "nvpair", "=", "None", ")", ":", "self", ".", "data", "=", "[", "]", "if", "nvpair", "is", "not", "None", ":", "self", ".", "data", ".", "append", "(", "nvpair", ")" ]
https://github.com/nipy/nibabel/blob/4703f4d8e32be4cec30e829c2d93ebe54759bb62/nibabel/gifti/gifti.py#L31-L34
nlpyang/BertSum
05f8c634197d0ed1be8157d71f29aa7765abdd2a
src/models/optimizers.py
python
MultipleOptimizer.load_state_dict
(self, state_dicts)
?
?
[ "?" ]
def load_state_dict(self, state_dicts): """ ? """ assert len(state_dicts) == len(self.optimizers) for i in range(len(state_dicts)): self.optimizers[i].load_state_dict(state_dicts[i])
[ "def", "load_state_dict", "(", "self", ",", "state_dicts", ")", ":", "assert", "len", "(", "state_dicts", ")", "==", "len", "(", "self", ".", "optimizers", ")", "for", "i", "in", "range", "(", "len", "(", "state_dicts", ")", ")", ":", "self", ".", "o...
https://github.com/nlpyang/BertSum/blob/05f8c634197d0ed1be8157d71f29aa7765abdd2a/src/models/optimizers.py#L104-L108
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/smartthings/smartapp.py
python
format_unique_id
(app_id: str, location_id: str)
return f"{app_id}_{location_id}"
Format the unique id for a config entry.
Format the unique id for a config entry.
[ "Format", "the", "unique", "id", "for", "a", "config", "entry", "." ]
def format_unique_id(app_id: str, location_id: str) -> str: """Format the unique id for a config entry.""" return f"{app_id}_{location_id}"
[ "def", "format_unique_id", "(", "app_id", ":", "str", ",", "location_id", ":", "str", ")", "->", "str", ":", "return", "f\"{app_id}_{location_id}\"" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/smartthings/smartapp.py#L58-L60
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e
tensorflow_dl_models/research/tcn/data_providers.py
python
record_dataset
(filename)
return tf.data.TFRecordDataset(filename)
Generate a TFRecordDataset from a `filename`.
Generate a TFRecordDataset from a `filename`.
[ "Generate", "a", "TFRecordDataset", "from", "a", "filename", "." ]
def record_dataset(filename): """Generate a TFRecordDataset from a `filename`.""" return tf.data.TFRecordDataset(filename)
[ "def", "record_dataset", "(", "filename", ")", ":", "return", "tf", ".", "data", ".", "TFRecordDataset", "(", "filename", ")" ]
https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/tensorflow_dl_models/research/tcn/data_providers.py#L28-L30
Georce/lepus
5b01bae82b5dc1df00c9e058989e2eb9b89ff333
lepus/redis-2.10.3/redis/client.py
python
StrictRedis.lpushx
(self, name, value)
return self.execute_command('LPUSHX', name, value)
Push ``value`` onto the head of the list ``name`` if ``name`` exists
Push ``value`` onto the head of the list ``name`` if ``name`` exists
[ "Push", "value", "onto", "the", "head", "of", "the", "list", "name", "if", "name", "exists" ]
def lpushx(self, name, value): "Push ``value`` onto the head of the list ``name`` if ``name`` exists" return self.execute_command('LPUSHX', name, value)
[ "def", "lpushx", "(", "self", ",", "name", ",", "value", ")", ":", "return", "self", ".", "execute_command", "(", "'LPUSHX'", ",", "name", ",", "value", ")" ]
https://github.com/Georce/lepus/blob/5b01bae82b5dc1df00c9e058989e2eb9b89ff333/lepus/redis-2.10.3/redis/client.py#L1212-L1214
PowerScript/KatanaFramework
0f6ad90a88de865d58ec26941cb4460501e75496
lib/scapy/build/lib.linux-i686-2.7/scapy/arch/windows/__init__.py
python
NetworkInterfaceDict.devname
(self, pcap_name)
Return libdnet/Scapy device name for given pypcap device name This mapping is necessary because pypcap numbers the devices differently.
Return libdnet/Scapy device name for given pypcap device name This mapping is necessary because pypcap numbers the devices differently.
[ "Return", "libdnet", "/", "Scapy", "device", "name", "for", "given", "pypcap", "device", "name", "This", "mapping", "is", "necessary", "because", "pypcap", "numbers", "the", "devices", "differently", "." ]
def devname(self, pcap_name): """Return libdnet/Scapy device name for given pypcap device name This mapping is necessary because pypcap numbers the devices differently.""" for devname, iface in self.items(): if iface.pcap_name == pcap_name: return iface.name raise ValueError("Unknown pypcap network interface %r" % pcap_name)
[ "def", "devname", "(", "self", ",", "pcap_name", ")", ":", "for", "devname", ",", "iface", "in", "self", ".", "items", "(", ")", ":", "if", "iface", ".", "pcap_name", "==", "pcap_name", ":", "return", "iface", ".", "name", "raise", "ValueError", "(", ...
https://github.com/PowerScript/KatanaFramework/blob/0f6ad90a88de865d58ec26941cb4460501e75496/lib/scapy/build/lib.linux-i686-2.7/scapy/arch/windows/__init__.py#L193-L201
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Trello/Integrations/Trello/Trello.py
python
test_module
(client)
Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Args: client: HelloWorld client Returns: 'ok' if test passed, anything else will fail the test.
Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful.
[ "Returning", "ok", "indicates", "that", "the", "integration", "works", "like", "it", "is", "supposed", "to", ".", "Connection", "to", "the", "service", "is", "successful", "." ]
def test_module(client): """ Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Args: client: HelloWorld client Returns: 'ok' if test passed, anything else will fail the test. """ result = client.list_boards() if result: return 'ok' else: return "Test failed."
[ "def", "test_module", "(", "client", ")", ":", "result", "=", "client", ".", "list_boards", "(", ")", "if", "result", ":", "return", "'ok'", "else", ":", "return", "\"Test failed.\"" ]
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Trello/Integrations/Trello/Trello.py#L449-L464
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py
python
WorkerChannelInstance.date_created
(self)
return self._properties['date_created']
:returns: The RFC 2822 date and time in GMT when the resource was created :rtype: datetime
:returns: The RFC 2822 date and time in GMT when the resource was created :rtype: datetime
[ ":", "returns", ":", "The", "RFC", "2822", "date", "and", "time", "in", "GMT", "when", "the", "resource", "was", "created", ":", "rtype", ":", "datetime" ]
def date_created(self): """ :returns: The RFC 2822 date and time in GMT when the resource was created :rtype: datetime """ return self._properties['date_created']
[ "def", "date_created", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'date_created'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py#L365-L370
geekori/pyqt5
49b2538fa5afe43b3b2bdadaa0560d0d6ef4924c
src/windows/ScaleImage.py
python
ScaleImage.__init__
(self)
[]
def __init__(self): super().__init__() self.setWindowTitle("图片大小缩放例子") filename = './images/Cloudy_72px.png' img = QImage(filename) label1 = QLabel(self) label1.setFixedWidth(200) label1.setFixedHeight(200) result = img.scaled(label1.width(),label1.height(),Qt.IgnoreAspectRatio,Qt.SmoothTransformation) label1.setPixmap(QPixmap.fromImage(result)) vbox = QVBoxLayout() vbox.addWidget(label1) self.setLayout(vbox)
[ "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "setWindowTitle", "(", "\"图片大小缩放例子\")", "", "filename", "=", "'./images/Cloudy_72px.png'", "img", "=", "QImage", "(", "filename", ")", "label1", "=", "QLab...
https://github.com/geekori/pyqt5/blob/49b2538fa5afe43b3b2bdadaa0560d0d6ef4924c/src/windows/ScaleImage.py#L16-L31
adafruit/Adafruit_Python_BluefruitLE
a01dec2c88fa38143afb855e1df4f9ac774156b7
Adafruit_BluefruitLE/interfaces/device.py
python
Device.__ne__
(self, other)
return self.id != other.id
Test if this device is not the same as the provided device.
Test if this device is not the same as the provided device.
[ "Test", "if", "this", "device", "is", "not", "the", "same", "as", "the", "provided", "device", "." ]
def __ne__(self, other): """Test if this device is not the same as the provided device.""" return self.id != other.id
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "id", "!=", "other", ".", "id" ]
https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/a01dec2c88fa38143afb855e1df4f9ac774156b7/Adafruit_BluefruitLE/interfaces/device.py#L100-L102
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/ftplib.py
python
FTP.cwd
(self, dirname)
return self.voidcmd(cmd)
Change to a directory.
Change to a directory.
[ "Change", "to", "a", "directory", "." ]
def cwd(self, dirname): '''Change to a directory.''' if dirname == '..': try: return self.voidcmd('CDUP') except error_perm, msg: if msg.args[0][:3] != '500': raise elif dirname == '': dirname = '.' # does nothing, but could return error cmd = 'CWD ' + dirname return self.voidcmd(cmd)
[ "def", "cwd", "(", "self", ",", "dirname", ")", ":", "if", "dirname", "==", "'..'", ":", "try", ":", "return", "self", ".", "voidcmd", "(", "'CDUP'", ")", "except", "error_perm", ",", "msg", ":", "if", "msg", ".", "args", "[", "0", "]", "[", ":",...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/ftplib.py#L542-L553
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/sets/sets.py
python
UniversalSet._complement
(self)
return S.EmptySet
[]
def _complement(self): return S.EmptySet
[ "def", "_complement", "(", "self", ")", ":", "return", "S", ".", "EmptySet" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/sets/sets.py#L1417-L1418
jgyates/genmon
2cb2ed2945f55cd8c259b09ccfa9a51e23f1341e
genemail2sms.py
python
OnExercise
(Active)
[]
def OnExercise(Active): if Active: console.info("Generator Exercising") SendNotice("Generator Exercising") else: console.info("Generator Exercising End")
[ "def", "OnExercise", "(", "Active", ")", ":", "if", "Active", ":", "console", ".", "info", "(", "\"Generator Exercising\"", ")", "SendNotice", "(", "\"Generator Exercising\"", ")", "else", ":", "console", ".", "info", "(", "\"Generator Exercising End\"", ")" ]
https://github.com/jgyates/genmon/blob/2cb2ed2945f55cd8c259b09ccfa9a51e23f1341e/genemail2sms.py#L54-L60
TurboWay/spiderman
168f18552e0abb06187388b542d6a0df057ba852
SP/utils/tool.py
python
decode_base64
(st)
return str(decode, 'utf-8')
base64解密 :param st: str :return: base64解密后的明文
base64解密 :param st: str :return: base64解密后的明文
[ "base64解密", ":", "param", "st", ":", "str", ":", "return", ":", "base64解密后的明文" ]
def decode_base64(st): """ base64解密 :param st: str :return: base64解密后的明文 """ decode = base64.b64decode(st.encode('utf-8')) return str(decode, 'utf-8')
[ "def", "decode_base64", "(", "st", ")", ":", "decode", "=", "base64", ".", "b64decode", "(", "st", ".", "encode", "(", "'utf-8'", ")", ")", "return", "str", "(", "decode", ",", "'utf-8'", ")" ]
https://github.com/TurboWay/spiderman/blob/168f18552e0abb06187388b542d6a0df057ba852/SP/utils/tool.py#L66-L73
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/platform.py
python
release
()
return uname()[2]
Returns the system's release, e.g. '2.2.0' or 'NT' An empty string is returned if the value cannot be determined.
Returns the system's release, e.g. '2.2.0' or 'NT'
[ "Returns", "the", "system", "s", "release", "e", ".", "g", ".", "2", ".", "2", ".", "0", "or", "NT" ]
def release(): """ Returns the system's release, e.g. '2.2.0' or 'NT' An empty string is returned if the value cannot be determined. """ return uname()[2]
[ "def", "release", "(", ")", ":", "return", "uname", "(", ")", "[", "2", "]" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/platform.py#L1322-L1329
kivymd/KivyMD
1cb82f7d2437770f71be7c5a4f7de4b8da61f352
kivymd/uix/pickers/timepicker/timepicker.py
python
CircularSelector._get_centers
(self, *args)
Returns a list of all center. we use this for positioning the selector indicator.
Returns a list of all center. we use this for positioning the selector indicator.
[ "Returns", "a", "list", "of", "all", "center", ".", "we", "use", "this", "for", "positioning", "the", "selector", "indicator", "." ]
def _get_centers(self, *args): """ Returns a list of all center. we use this for positioning the selector indicator. """ self._centers_pos = [] for child in self.children: self._centers_pos.append(child.center)
[ "def", "_get_centers", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_centers_pos", "=", "[", "]", "for", "child", "in", "self", ".", "children", ":", "self", ".", "_centers_pos", ".", "append", "(", "child", ".", "center", ")" ]
https://github.com/kivymd/KivyMD/blob/1cb82f7d2437770f71be7c5a4f7de4b8da61f352/kivymd/uix/pickers/timepicker/timepicker.py#L354-L362
terrycojones/daudin
d11b2c43467634e6a1006366ece5b795bad3f376
daudinlib/pipeline.py
python
Pipeline.sh
(self, *args, print_=False, **kwargs)
return result
Execute a shell command, with input from our C{self.stdin}. @param args: Positional arguments to pass to C{subprocess.run}. @param print_: If C{True}, use a pseudo-tty and print the output to stdout. @param kwargs: Keyword arguments to pass to C{Pipe} or C{subprocess.run} (depending on the value of C{print_}). @raise CalledProcessError: If the command results in an error. @return: The C{str} output of the command.
Execute a shell command, with input from our C{self.stdin}.
[ "Execute", "a", "shell", "command", "with", "input", "from", "our", "C", "{", "self", ".", "stdin", "}", "." ]
def sh(self, *args, print_=False, **kwargs): """ Execute a shell command, with input from our C{self.stdin}. @param args: Positional arguments to pass to C{subprocess.run}. @param print_: If C{True}, use a pseudo-tty and print the output to stdout. @param kwargs: Keyword arguments to pass to C{Pipe} or C{subprocess.run} (depending on the value of C{print_}). @raise CalledProcessError: If the command results in an error. @return: The C{str} output of the command. """ kwargs.setdefault('shell', len(args) == 1 and isinstance(args[0], str)) if self.inPipeline: if self.stdin is None: stdin = None elif isinstance(self.stdin, list): stdin = '\n'.join(map(str, self.stdin)) + '\n' else: stdin = str(self.stdin) + '\n' else: stdin = None if print_ and self.usePtys: result = self._shPty(stdin, *args, **kwargs) else: result = self._sh(stdin, *args, **kwargs) if print_: print(result, end='', file=self.outfp) return result
[ "def", "sh", "(", "self", ",", "*", "args", ",", "print_", "=", "False", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'shell'", ",", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", "...
https://github.com/terrycojones/daudin/blob/d11b2c43467634e6a1006366ece5b795bad3f376/daudinlib/pipeline.py#L273-L304
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/PIL/PyAccess.py
python
_PyAccessI16_L._post_init
(self, *args, **kwargs)
[]
def _post_init(self, *args, **kwargs): self.pixels = ffi.cast("struct Pixel_I16 **", self.image)
[ "def", "_post_init", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "pixels", "=", "ffi", ".", "cast", "(", "\"struct Pixel_I16 **\"", ",", "self", ".", "image", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/PIL/PyAccess.py#L217-L218
codeinthehole/purl
2bd51cabecfd4dcd20544fba7092cfd98dc7dac0
purl/url.py
python
URL.has_query_params
(self, keys)
return all([self.has_query_param(k) for k in keys])
Test if a given set of query parameters are present :param list keys: keys to test for
Test if a given set of query parameters are present
[ "Test", "if", "a", "given", "set", "of", "query", "parameters", "are", "present" ]
def has_query_params(self, keys): """ Test if a given set of query parameters are present :param list keys: keys to test for """ return all([self.has_query_param(k) for k in keys])
[ "def", "has_query_params", "(", "self", ",", "keys", ")", ":", "return", "all", "(", "[", "self", ".", "has_query_param", "(", "k", ")", "for", "k", "in", "keys", "]", ")" ]
https://github.com/codeinthehole/purl/blob/2bd51cabecfd4dcd20544fba7092cfd98dc7dac0/purl/url.py#L429-L435
JimmXinu/FanFicFare
bc149a2deb2636320fe50a3e374af6eef8f61889
included_dependencies/urllib3/util/ssl_.py
python
ssl_wrap_socket
( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None, key_password=None, ca_cert_data=None, tls_in_tls=False, )
return ssl_sock
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted. :param ca_cert_data: Optional string containing CA certificates in PEM format suitable for passing as the cadata parameter to SSLContext.load_verify_locations() :param tls_in_tls: Use SSLTransport to wrap the existing socket.
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`.
[ "All", "arguments", "except", "for", "server_hostname", "ssl_context", "and", "ca_cert_dir", "have", "the", "same", "meaning", "as", "they", "do", "when", "using", ":", "func", ":", "ssl", ".", "wrap_socket", "." ]
def ssl_wrap_socket( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None, key_password=None, ca_cert_data=None, tls_in_tls=False, ): """ All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted. :param ca_cert_data: Optional string containing CA certificates in PEM format suitable for passing as the cadata parameter to SSLContext.load_verify_locations() :param tls_in_tls: Use SSLTransport to wrap the existing socket. """ context = ssl_context if context is None: # Note: This branch of code and all the variables in it are no longer # used by urllib3 itself. We should consider deprecating and removing # this code. context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs or ca_cert_dir or ca_cert_data: try: context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) except (IOError, OSError) as e: raise SSLError(e) elif ssl_context is None and hasattr(context, "load_default_certs"): # try to load OS default certs; works well on Windows (require Python3.4+) context.load_default_certs() # Attempt to detect if we get the goofy behavior of the # keyfile being encrypted and OpenSSL asking for the # passphrase via the terminal and instead error out. if keyfile and key_password is None and _is_key_file_encrypted(keyfile): raise SSLError("Client private key is encrypted, password is required") if certfile: if key_password is None: context.load_cert_chain(certfile, keyfile) else: context.load_cert_chain(certfile, keyfile, key_password) try: if hasattr(context, "set_alpn_protocols"): context.set_alpn_protocols(ALPN_PROTOCOLS) except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols pass # If we detect server_hostname is an IP address then the SNI # extension should not be used according to RFC3546 Section 3.1 use_sni_hostname = server_hostname and not is_ipaddress(server_hostname) # SecureTransport uses server_hostname in certificate verification. send_sni = (use_sni_hostname and HAS_SNI) or ( IS_SECURETRANSPORT and server_hostname ) # Do not warn the user if server_hostname is an invalid SNI hostname. if not HAS_SNI and use_sni_hostname: warnings.warn( "An HTTPS request has been made, but the SNI (Server Name " "Indication) extension to TLS is not available on this platform. " "This may cause the server to present an incorrect TLS " "certificate, which can cause validation failures. You can upgrade to " "a newer version of Python to solve this. For more information, see " "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html" "#ssl-warnings", SNIMissingWarning, ) if send_sni: ssl_sock = _ssl_wrap_socket_impl( sock, context, tls_in_tls, server_hostname=server_hostname ) else: ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls) return ssl_sock
[ "def", "ssl_wrap_socket", "(", "sock", ",", "keyfile", "=", "None", ",", "certfile", "=", "None", ",", "cert_reqs", "=", "None", ",", "ca_certs", "=", "None", ",", "server_hostname", "=", "None", ",", "ssl_version", "=", "None", ",", "ciphers", "=", "Non...
https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/included_dependencies/urllib3/util/ssl_.py#L355-L454
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/api/request_info.py
python
RequestInfo.get_dispatcher
(self)
Returns the Dispatcher. Returns: The Dispatcher instance.
Returns the Dispatcher.
[ "Returns", "the", "Dispatcher", "." ]
def get_dispatcher(self): """Returns the Dispatcher. Returns: The Dispatcher instance. """ raise NotImplementedError()
[ "def", "get_dispatcher", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/request_info.py#L644-L650
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/pypy-deltablue.py
python
Planner.incremental_add
(self, constraint)
[]
def incremental_add(self, constraint): mark = self.new_mark() overridden = constraint.satisfy(mark) while overridden is not None: overridden = overridden.satisfy(mark)
[ "def", "incremental_add", "(", "self", ",", "constraint", ")", ":", "mark", "=", "self", ".", "new_mark", "(", ")", "overridden", "=", "constraint", ".", "satisfy", "(", "mark", ")", "while", "overridden", "is", "not", "None", ":", "overridden", "=", "ov...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/pypy-deltablue.py#L382-L387
prompt-toolkit/python-prompt-toolkit
e9eac2eb59ec385e81742fa2ac623d4b8de00925
prompt_toolkit/input/defaults.py
python
create_input
( stdin: Optional[TextIO] = None, always_prefer_tty: bool = False )
Create the appropriate `Input` object for the current os/environment. :param always_prefer_tty: When set, if `sys.stdin` is connected to a Unix `pipe`, check whether `sys.stdout` or `sys.stderr` are connected to a pseudo terminal. If so, open the tty for reading instead of reading for `sys.stdin`. (We can open `stdout` or `stderr` for reading, this is how a `$PAGER` works.)
Create the appropriate `Input` object for the current os/environment.
[ "Create", "the", "appropriate", "Input", "object", "for", "the", "current", "os", "/", "environment", "." ]
def create_input( stdin: Optional[TextIO] = None, always_prefer_tty: bool = False ) -> Input: """ Create the appropriate `Input` object for the current os/environment. :param always_prefer_tty: When set, if `sys.stdin` is connected to a Unix `pipe`, check whether `sys.stdout` or `sys.stderr` are connected to a pseudo terminal. If so, open the tty for reading instead of reading for `sys.stdin`. (We can open `stdout` or `stderr` for reading, this is how a `$PAGER` works.) """ if is_windows(): from .win32 import Win32Input return Win32Input(stdin or sys.stdin) else: from .vt100 import Vt100Input # If no input TextIO is given, use stdin/stdout. if stdin is None: stdin = sys.stdin if always_prefer_tty: for io in [sys.stdin, sys.stdout, sys.stderr]: if io.isatty(): stdin = io break return Vt100Input(stdin)
[ "def", "create_input", "(", "stdin", ":", "Optional", "[", "TextIO", "]", "=", "None", ",", "always_prefer_tty", ":", "bool", "=", "False", ")", "->", "Input", ":", "if", "is_windows", "(", ")", ":", "from", ".", "win32", "import", "Win32Input", "return"...
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/e9eac2eb59ec385e81742fa2ac623d4b8de00925/prompt_toolkit/input/defaults.py#L14-L43
sunpy/sunpy
528579df0a4c938c133bd08971ba75c131b189a7
sunpy/net/helio/hec.py
python
HECClient.__init__
(self, link=None)
The constructor; establishes the webservice link for the client Initializes the client with a weblink Parameters ---------- link : str Contains URL to valid WSDL endpoint Examples -------- >>> from sunpy.net.helio import hec >>> hc = hec.HECClient() # doctest: +REMOTE_DATA
The constructor; establishes the webservice link for the client
[ "The", "constructor", ";", "establishes", "the", "webservice", "link", "for", "the", "client" ]
def __init__(self, link=None): """ The constructor; establishes the webservice link for the client Initializes the client with a weblink Parameters ---------- link : str Contains URL to valid WSDL endpoint Examples -------- >>> from sunpy.net.helio import hec >>> hc = hec.HECClient() # doctest: +REMOTE_DATA """ if link is None: # The default wsdl file link = parser.wsdl_retriever() session = Session() # This is for use in our test suite. session.verify = not(bool(os.environ.get("NO_VERIFY_HELIO_SSL", 0))) transport = Transport(session=session) self.hec_client = Client(link, transport=transport)
[ "def", "__init__", "(", "self", ",", "link", "=", "None", ")", ":", "if", "link", "is", "None", ":", "# The default wsdl file", "link", "=", "parser", ".", "wsdl_retriever", "(", ")", "session", "=", "Session", "(", ")", "# This is for use in our test suite.",...
https://github.com/sunpy/sunpy/blob/528579df0a4c938c133bd08971ba75c131b189a7/sunpy/net/helio/hec.py#L67-L90
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/crypto/crypto.py
python
encipher_bg
(i, key, seed=None)
return (encrypt_msg, x_L)
Encrypts the message using public key and seed. Explanation =========== ALGORITHM: 1. Encodes i as a string of L bits, m. 2. Select a random element r, where 1 < r < key, and computes x = r^2 mod key. 3. Use BBS pseudo-random number generator to generate L random bits, b, using the initial seed as x. 4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L. 5. x_L = x^(2^L) mod key. 6. Return (c, x_L) Parameters ========== i Message, a non-negative integer key The public key Returns ======= Tuple (encrypted_message, x_L) Raises ====== ValueError If i is negative.
Encrypts the message using public key and seed.
[ "Encrypts", "the", "message", "using", "public", "key", "and", "seed", "." ]
def encipher_bg(i, key, seed=None): """ Encrypts the message using public key and seed. Explanation =========== ALGORITHM: 1. Encodes i as a string of L bits, m. 2. Select a random element r, where 1 < r < key, and computes x = r^2 mod key. 3. Use BBS pseudo-random number generator to generate L random bits, b, using the initial seed as x. 4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L. 5. x_L = x^(2^L) mod key. 6. Return (c, x_L) Parameters ========== i Message, a non-negative integer key The public key Returns ======= Tuple (encrypted_message, x_L) Raises ====== ValueError If i is negative. """ if i < 0: raise ValueError( "message must be a non-negative " "integer: got %d instead" % i) enc_msg = [] while i > 0: enc_msg.append(i % 2) i //= 2 enc_msg.reverse() L = len(enc_msg) r = _randint(seed)(2, key - 1) x = r**2 % key x_L = pow(int(x), int(2**L), int(key)) rand_bits = [] for _ in range(L): rand_bits.append(x % 2) x = x**2 % key encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)] return (encrypt_msg, x_L)
[ "def", "encipher_bg", "(", "i", ",", "key", ",", "seed", "=", "None", ")", ":", "if", "i", "<", "0", ":", "raise", "ValueError", "(", "\"message must be a non-negative \"", "\"integer: got %d instead\"", "%", "i", ")", "enc_msg", "=", "[", "]", "while", "i...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/crypto/crypto.py#L3239-L3302
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-build/python-libs/gdata/src/atom/http_core.py
python
HttpRequest.add_body_part
(self, data, mime_type, size=None)
Adds data to the HTTP request body. If more than one part is added, this is assumed to be a mime-multipart request. This method is designed to create MIME 1.0 requests as specified in RFC 1341. Args: data: str or a file-like object containing a part of the request body. mime_type: str The MIME type describing the data size: int Required if the data is a file like object. If the data is a string, the size is calculated so this parameter is ignored.
Adds data to the HTTP request body. If more than one part is added, this is assumed to be a mime-multipart request. This method is designed to create MIME 1.0 requests as specified in RFC 1341.
[ "Adds", "data", "to", "the", "HTTP", "request", "body", ".", "If", "more", "than", "one", "part", "is", "added", "this", "is", "assumed", "to", "be", "a", "mime", "-", "multipart", "request", ".", "This", "method", "is", "designed", "to", "create", "MI...
def add_body_part(self, data, mime_type, size=None): """Adds data to the HTTP request body. If more than one part is added, this is assumed to be a mime-multipart request. This method is designed to create MIME 1.0 requests as specified in RFC 1341. Args: data: str or a file-like object containing a part of the request body. mime_type: str The MIME type describing the data size: int Required if the data is a file like object. If the data is a string, the size is calculated so this parameter is ignored. """ if isinstance(data, str): size = len(data) if size is None: # TODO: support chunked transfer if some of the body is of unknown size. raise UnknownSize('Each part of the body must have a known size.') if 'Content-Length' in self.headers: content_length = int(self.headers['Content-Length']) else: content_length = 0 # If this is the first part added to the body, then this is not a multipart # request. if len(self._body_parts) == 0: self.headers['Content-Type'] = mime_type content_length = size self._body_parts.append(data) elif len(self._body_parts) == 1: # This is the first member in a mime-multipart request, so change the # _body_parts list to indicate a multipart payload. self._body_parts.insert(0, 'Media multipart posting') boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,) content_length += len(boundary_string) + size self._body_parts.insert(1, boundary_string) content_length += len('Media multipart posting') # Put the content type of the first part of the body into the multipart # payload. original_type_string = 'Content-Type: %s\r\n\r\n' % ( self.headers['Content-Type'],) self._body_parts.insert(2, original_type_string) content_length += len(original_type_string) boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,) self._body_parts.append(boundary_string) content_length += len(boundary_string) # Change the headers to indicate this is now a mime multipart request. self.headers['Content-Type'] = 'multipart/related; boundary="%s"' % ( MIME_BOUNDARY,) self.headers['MIME-version'] = '1.0' # Include the mime type of this part. type_string = 'Content-Type: %s\r\n\r\n' % (mime_type) self._body_parts.append(type_string) content_length += len(type_string) self._body_parts.append(data) ending_boundary_string = '\r\n--%s--' % (MIME_BOUNDARY,) self._body_parts.append(ending_boundary_string) content_length += len(ending_boundary_string) else: # This is a mime multipart request. boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,) self._body_parts.insert(-1, boundary_string) content_length += len(boundary_string) + size # Include the mime type of this part. type_string = 'Content-Type: %s\r\n\r\n' % (mime_type) self._body_parts.insert(-1, type_string) content_length += len(type_string) self._body_parts.insert(-1, data) self.headers['Content-Length'] = str(content_length)
[ "def", "add_body_part", "(", "self", ",", "data", ",", "mime_type", ",", "size", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "size", "=", "len", "(", "data", ")", "if", "size", "is", "None", ":", "# TODO: support chu...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/src/atom/http_core.py#L75-L142
AlexTan-b-z/ZhihuSpider
7f35d157fa7f3a7ac8545b386e98286ee2764462
zhihu/zhihu/scrapy_redis/spiders.py
python
RedisMixin.start_requests
(self)
return self.next_requests()
Returns a batch of start requests from redis.
Returns a batch of start requests from redis.
[ "Returns", "a", "batch", "of", "start", "requests", "from", "redis", "." ]
def start_requests(self): """Returns a batch of start requests from redis.""" return self.next_requests()
[ "def", "start_requests", "(", "self", ")", ":", "return", "self", ".", "next_requests", "(", ")" ]
https://github.com/AlexTan-b-z/ZhihuSpider/blob/7f35d157fa7f3a7ac8545b386e98286ee2764462/zhihu/zhihu/scrapy_redis/spiders.py#L18-L20
mihaip/readerisdead
0e35cf26e88f27e0a07432182757c1ce230f6936
third_party/web/utils.py
python
ThreadedDict.__del__
(self)
[]
def __del__(self): ThreadedDict._instances.remove(self)
[ "def", "__del__", "(", "self", ")", ":", "ThreadedDict", ".", "_instances", ".", "remove", "(", "self", ")" ]
https://github.com/mihaip/readerisdead/blob/0e35cf26e88f27e0a07432182757c1ce230f6936/third_party/web/utils.py#L1204-L1205
rotki/rotki
aafa446815cdd5e9477436d1b02bee7d01b398c8
rotkehlchen/chain/manager.py
python
ChainManager.get_eth2_staking_details
(self)
return eth2.get_details(addresses=self.queried_addresses_for_module('eth2'))
May raise: - ModuleInactive if eth2 module is not activated
May raise: - ModuleInactive if eth2 module is not activated
[ "May", "raise", ":", "-", "ModuleInactive", "if", "eth2", "module", "is", "not", "activated" ]
def get_eth2_staking_details(self) -> List['ValidatorDetails']: """May raise: - ModuleInactive if eth2 module is not activated """ eth2 = self.get_module('eth2') if eth2 is None: raise ModuleInactive('Cant query eth2 staking details since eth2 module is not active') return eth2.get_details(addresses=self.queried_addresses_for_module('eth2'))
[ "def", "get_eth2_staking_details", "(", "self", ")", "->", "List", "[", "'ValidatorDetails'", "]", ":", "eth2", "=", "self", ".", "get_module", "(", "'eth2'", ")", "if", "eth2", "is", "None", ":", "raise", "ModuleInactive", "(", "'Cant query eth2 staking details...
https://github.com/rotki/rotki/blob/aafa446815cdd5e9477436d1b02bee7d01b398c8/rotkehlchen/chain/manager.py#L1622-L1629
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
source/addons/base_report_designer/plugin/openerp_report_designer/bin/script/lib/gui.py
python
createUnoStruct
( cTypeName )
return oStruct
Create a UNO struct and return it. Similar to the function of the same name in OOo Basic.
Create a UNO struct and return it. Similar to the function of the same name in OOo Basic.
[ "Create", "a", "UNO", "struct", "and", "return", "it", ".", "Similar", "to", "the", "function", "of", "the", "same", "name", "in", "OOo", "Basic", "." ]
def createUnoStruct( cTypeName ): """Create a UNO struct and return it. Similar to the function of the same name in OOo Basic. """ oCoreReflection = getCoreReflection() # Get the IDL class for the type name oXIdlClass = oCoreReflection.forName( cTypeName ) # Create the struct. oReturnValue, oStruct = oXIdlClass.createObject( None ) return oStruct
[ "def", "createUnoStruct", "(", "cTypeName", ")", ":", "oCoreReflection", "=", "getCoreReflection", "(", ")", "# Get the IDL class for the type name", "oXIdlClass", "=", "oCoreReflection", ".", "forName", "(", "cTypeName", ")", "# Create the struct.", "oReturnValue", ",", ...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/source/addons/base_report_designer/plugin/openerp_report_designer/bin/script/lib/gui.py#L108-L117
falconry/falcon
ee97769eab6a951864876202474133446aa50297
falcon/asgi/ws.py
python
WebSocket.receive_media
(self)
return self._mh_bin_deserialize(data)
Receive a deserialized object from the client. The incoming payload type determines the media handler that will be used to deserialize the object (see also: :ref:`ws_media_handlers`).
Receive a deserialized object from the client.
[ "Receive", "a", "deserialized", "object", "from", "the", "client", "." ]
async def receive_media(self) -> object: """Receive a deserialized object from the client. The incoming payload type determines the media handler that will be used to deserialize the object (see also: :ref:`ws_media_handlers`). """ self._require_accepted() event = await self._receive() # NOTE(kgriffs): Most likely case is going to be JSON via text # payload, so try that first. text = event.get('text') if text is not None: return self._mh_text_deserialize(text) # PERF(kgriffs): At this point there better be a 'bytes' key, so # use EAFP this time. try: data = event['bytes'] except KeyError: data = None # NOTE(kgriffs): Even if the key is present, it may be None if data is None: raise errors.PayloadTypeError( 'Message did not contain either a TEXT (0x01) or BINARY (0x02) payload' ) return self._mh_bin_deserialize(data)
[ "async", "def", "receive_media", "(", "self", ")", "->", "object", ":", "self", ".", "_require_accepted", "(", ")", "event", "=", "await", "self", ".", "_receive", "(", ")", "# NOTE(kgriffs): Most likely case is going to be JSON via text", "# payload, so try that firs...
https://github.com/falconry/falcon/blob/ee97769eab6a951864876202474133446aa50297/falcon/asgi/ws.py#L404-L434
sqall01/alertR
e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13
alertClientMail/lib/update.py
python
Updater._releaseLock
(self)
# Internal function that releases the lock.
# Internal function that releases the lock.
[ "#", "Internal", "function", "that", "releases", "the", "lock", "." ]
def _releaseLock(self): """ # Internal function that releases the lock. """ logging.debug("[%s]: Release lock." % self.fileName) self.updaterLock.release()
[ "def", "_releaseLock", "(", "self", ")", ":", "logging", ".", "debug", "(", "\"[%s]: Release lock.\"", "%", "self", ".", "fileName", ")", "self", ".", "updaterLock", ".", "release", "(", ")" ]
https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/alertClientMail/lib/update.py#L98-L103
jpvanhal/inflection
b00d4d348b32ef5823221b20ee4cbd1d2d924462
inflection/__init__.py
python
ordinalize
(number: int)
return "{}{}".format(number, ordinal(number))
Turn a number into an ordinal string used to denote the position in an ordered sequence such as 1st, 2nd, 3rd, 4th. Examples:: >>> ordinalize(1) '1st' >>> ordinalize(2) '2nd' >>> ordinalize(1002) '1002nd' >>> ordinalize(1003) '1003rd' >>> ordinalize(-11) '-11th' >>> ordinalize(-1021) '-1021st'
Turn a number into an ordinal string used to denote the position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
[ "Turn", "a", "number", "into", "an", "ordinal", "string", "used", "to", "denote", "the", "position", "in", "an", "ordered", "sequence", "such", "as", "1st", "2nd", "3rd", "4th", "." ]
def ordinalize(number: int) -> str: """ Turn a number into an ordinal string used to denote the position in an ordered sequence such as 1st, 2nd, 3rd, 4th. Examples:: >>> ordinalize(1) '1st' >>> ordinalize(2) '2nd' >>> ordinalize(1002) '1002nd' >>> ordinalize(1003) '1003rd' >>> ordinalize(-11) '-11th' >>> ordinalize(-1021) '-1021st' """ return "{}{}".format(number, ordinal(number))
[ "def", "ordinalize", "(", "number", ":", "int", ")", "->", "str", ":", "return", "\"{}{}\"", ".", "format", "(", "number", ",", "ordinal", "(", "number", ")", ")" ]
https://github.com/jpvanhal/inflection/blob/b00d4d348b32ef5823221b20ee4cbd1d2d924462/inflection/__init__.py#L236-L257
aliyun/aliyun-openapi-python-sdk
bda53176cc9cf07605b1cf769f0df444cca626a0
aliyun-python-sdk-core/aliyunsdkcore/vendored/requests/packages/urllib3/contrib/pyopenssl.py
python
get_subj_alt_name
(peer_cert)
return names
Given an PyOpenSSL certificate, provides all the subject alternative names.
Given an PyOpenSSL certificate, provides all the subject alternative names.
[ "Given", "an", "PyOpenSSL", "certificate", "provides", "all", "the", "subject", "alternative", "names", "." ]
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names
[ "def", "get_subj_alt_name", "(", "peer_cert", ")", ":", "# Pass the cert to cryptography, which has much better APIs for this.", "if", "hasattr", "(", "peer_cert", ",", "\"to_cryptography\"", ")", ":", "cert", "=", "peer_cert", ".", "to_cryptography", "(", ")", "else", ...
https://github.com/aliyun/aliyun-openapi-python-sdk/blob/bda53176cc9cf07605b1cf769f0df444cca626a0/aliyun-python-sdk-core/aliyunsdkcore/vendored/requests/packages/urllib3/contrib/pyopenssl.py#L198-L247
python-hyper/rfc3986
164073434fe530e14ceca4ff6a0683e23e2fde48
src/rfc3986/exceptions.py
python
ResolutionError.__init__
(self, uri)
Initialize the error with the failed URI.
Initialize the error with the failed URI.
[ "Initialize", "the", "error", "with", "the", "failed", "URI", "." ]
def __init__(self, uri): """Initialize the error with the failed URI.""" super().__init__( "{} does not meet the requirements for resolution.".format( uri.unsplit() ) )
[ "def", "__init__", "(", "self", ",", "uri", ")", ":", "super", "(", ")", ".", "__init__", "(", "\"{} does not meet the requirements for resolution.\"", ".", "format", "(", "uri", ".", "unsplit", "(", ")", ")", ")" ]
https://github.com/python-hyper/rfc3986/blob/164073434fe530e14ceca4ff6a0683e23e2fde48/src/rfc3986/exceptions.py#L32-L38