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
autokey/autokey
0c848b8b3e066f1261260ad580d5996408cf2b98
lib/autokey/model.py
python
Phrase.should_prompt
(self, buffer)
return self.prompt
Get a value indicating whether the user should be prompted to select the phrase. Always returns true if the phrase has been triggered using predictive mode.
Get a value indicating whether the user should be prompted to select the phrase. Always returns true if the phrase has been triggered using predictive mode.
[ "Get", "a", "value", "indicating", "whether", "the", "user", "should", "be", "prompted", "to", "select", "the", "phrase", ".", "Always", "returns", "true", "if", "the", "phrase", "has", "been", "triggered", "using", "predictive", "mode", "." ]
def should_prompt(self, buffer): """ Get a value indicating whether the user should be prompted to select the phrase. Always returns true if the phrase has been triggered using predictive mode. """ # TODO - re-enable me if restoring predictive functionality #if TriggerMode.PREDICTIVE in self.modes: # if self._should_trigger_predictive(buffer): # return True return self.prompt
[ "def", "should_prompt", "(", "self", ",", "buffer", ")", ":", "# TODO - re-enable me if restoring predictive functionality", "#if TriggerMode.PREDICTIVE in self.modes:", "# if self._should_trigger_predictive(buffer):", "# return True", "return", "self", ".", "prompt" ]
https://github.com/autokey/autokey/blob/0c848b8b3e066f1261260ad580d5996408cf2b98/lib/autokey/model.py#L844-L854
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/gettext.py
python
NullTranslations.ngettext
(self, msgid1, msgid2, n)
[]
def ngettext(self, msgid1, msgid2, n): if self._fallback: return self._fallback.ngettext(msgid1, msgid2, n) if n == 1: return msgid1 else: return msgid2
[ "def", "ngettext", "(", "self", ",", "msgid1", ",", "msgid2", ",", "n", ")", ":", "if", "self", ".", "_fallback", ":", "return", "self", ".", "_fallback", ".", "ngettext", "(", "msgid1", ",", "msgid2", ",", "n", ")", "if", "n", "==", "1", ":", "r...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/gettext.py#L181-L187
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/wheel/signatures/__init__.py
python
get_ed25519ll
()
return ed25519ll
Lazy import-and-test of ed25519 module
Lazy import-and-test of ed25519 module
[ "Lazy", "import", "-", "and", "-", "test", "of", "ed25519", "module" ]
def get_ed25519ll(): """Lazy import-and-test of ed25519 module""" global ed25519ll if not ed25519ll: try: import ed25519ll # fast (thousands / s) except (ImportError, OSError): # pragma nocover from . import ed25519py as ed25519ll # pure Python (hundreds / s) test() return ed25519ll
[ "def", "get_ed25519ll", "(", ")", ":", "global", "ed25519ll", "if", "not", "ed25519ll", ":", "try", ":", "import", "ed25519ll", "# fast (thousands / s)", "except", "(", "ImportError", ",", "OSError", ")", ":", "# pragma nocover", "from", ".", "import", "ed25519p...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/wheel/signatures/__init__.py#L15-L26
grnet/synnefo
d06ec8c7871092131cdaabf6b03ed0b504c93e43
snf-pithos-backend/pithos/backends/lib/sqlalchemy/groups.py
python
Groups.group_destroy
(self, owner)
Delete all groups belonging to owner.
Delete all groups belonging to owner.
[ "Delete", "all", "groups", "belonging", "to", "owner", "." ]
def group_destroy(self, owner): """Delete all groups belonging to owner.""" s = self.groups.delete().where(self.groups.c.owner == owner) r = self.conn.execute(s) r.close()
[ "def", "group_destroy", "(", "self", ",", "owner", ")", ":", "s", "=", "self", ".", "groups", ".", "delete", "(", ")", ".", "where", "(", "self", ".", "groups", ".", "c", ".", "owner", "==", "owner", ")", "r", "=", "self", ".", "conn", ".", "ex...
https://github.com/grnet/synnefo/blob/d06ec8c7871092131cdaabf6b03ed0b504c93e43/snf-pithos-backend/pithos/backends/lib/sqlalchemy/groups.py#L120-L125
tenable/pyTenable
1ccab9fc6f6e4c9f1cfe5128f694388ea112719d
tenable/ot/graphql/assets.py
python
AssetSchema.to_object
(self, data, **kwargs)
return Asset(**data)
This method turns the schema into its corresponding object.
This method turns the schema into its corresponding object.
[ "This", "method", "turns", "the", "schema", "into", "its", "corresponding", "object", "." ]
def to_object(self, data, **kwargs): '''This method turns the schema into its corresponding object.''' return Asset(**data)
[ "def", "to_object", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "return", "Asset", "(", "*", "*", "data", ")" ]
https://github.com/tenable/pyTenable/blob/1ccab9fc6f6e4c9f1cfe5128f694388ea112719d/tenable/ot/graphql/assets.py#L187-L189
gratipay/gratipay.com
dc4e953a8a5b96908e2f3ea7f8fef779217ba2b6
gratipay/models/team/__init__.py
python
slugize
(name)
return slug
Create a slug from a team name.
Create a slug from a team name.
[ "Create", "a", "slug", "from", "a", "team", "name", "." ]
def slugize(name): """ Create a slug from a team name. """ if TEAM_NAME_PATTERN.match(name) is None: raise InvalidTeamName slug = name.strip() for c in (',', ' '): slug = slug.replace(c, '-') # Avoid % encoded characters in slug url. while '--' in slug: slug = slug.replace('--', '-') slug = slug.strip('-') return slug
[ "def", "slugize", "(", "name", ")", ":", "if", "TEAM_NAME_PATTERN", ".", "match", "(", "name", ")", "is", "None", ":", "raise", "InvalidTeamName", "slug", "=", "name", ".", "strip", "(", ")", "for", "c", "in", "(", "','", ",", "' '", ")", ":", "slu...
https://github.com/gratipay/gratipay.com/blob/dc4e953a8a5b96908e2f3ea7f8fef779217ba2b6/gratipay/models/team/__init__.py#L26-L38
opensourcesec/CIRTKit
58b8793ada69320ffdbdd4ecdc04a3bb2fa83c37
modules/reversing/viper/peepdf/jsbeautifier/unpackers/packer.py
python
_replacestrings
(source)
return source
Strip string lookup table (list) and replace values in source.
Strip string lookup table (list) and replace values in source.
[ "Strip", "string", "lookup", "table", "(", "list", ")", "and", "replace", "values", "in", "source", "." ]
def _replacestrings(source): """Strip string lookup table (list) and replace values in source.""" match = re.search(r'var *(_\w+)\=\["(.*?)"\];', source, re.DOTALL) if match: varname, strings = match.groups() startpoint = len(match.group(0)) lookup = strings.split('","') variable = '%s[%%d]' % varname for index, value in enumerate(lookup): source = source.replace(variable % index, '"%s"' % value) return source[startpoint:] return source
[ "def", "_replacestrings", "(", "source", ")", ":", "match", "=", "re", ".", "search", "(", "r'var *(_\\w+)\\=\\[\"(.*?)\"\\];'", ",", "source", ",", "re", ".", "DOTALL", ")", "if", "match", ":", "varname", ",", "strings", "=", "match", ".", "groups", "(", ...
https://github.com/opensourcesec/CIRTKit/blob/58b8793ada69320ffdbdd4ecdc04a3bb2fa83c37/modules/reversing/viper/peepdf/jsbeautifier/unpackers/packer.py#L56-L68
scipy/scipy
e0a749f01e79046642ccfdc419edbf9e7ca141ad
scipy/sparse/linalg/_dsolve/linsolve.py
python
_get_umf_family
(A)
return family, A_new
Get umfpack family string given the sparse matrix dtype.
Get umfpack family string given the sparse matrix dtype.
[ "Get", "umfpack", "family", "string", "given", "the", "sparse", "matrix", "dtype", "." ]
def _get_umf_family(A): """Get umfpack family string given the sparse matrix dtype.""" _families = { (np.float64, np.int32): 'di', (np.complex128, np.int32): 'zi', (np.float64, np.int64): 'dl', (np.complex128, np.int64): 'zl' } f_type = np.sctypeDict[A.dtype.name] i_type = np.sctypeDict[A.indices.dtype.name] try: family = _families[(f_type, i_type)] except KeyError as e: msg = 'only float64 or complex128 matrices with int32 or int64' \ ' indices are supported! (got: matrix: %s, indices: %s)' \ % (f_type, i_type) raise ValueError(msg) from e # See gh-8278. Considered converting only if # A.shape[0]*A.shape[1] > np.iinfo(np.int32).max, # but that didn't always fix the issue. family = family[0] + "l" A_new = copy.copy(A) A_new.indptr = np.array(A.indptr, copy=False, dtype=np.int64) A_new.indices = np.array(A.indices, copy=False, dtype=np.int64) return family, A_new
[ "def", "_get_umf_family", "(", "A", ")", ":", "_families", "=", "{", "(", "np", ".", "float64", ",", "np", ".", "int32", ")", ":", "'di'", ",", "(", "np", ".", "complex128", ",", "np", ".", "int32", ")", ":", "'zi'", ",", "(", "np", ".", "float...
https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/sparse/linalg/_dsolve/linsolve.py#L60-L89
dBeker/Faster-RCNN-TensorFlow-Python3
027e5603551b3b9053042a113b4c7be9579dbb4a
lib/datasets/voc_eval.py
python
parse_rec
(filename)
return objects
Parse a PASCAL VOC xml file
Parse a PASCAL VOC xml file
[ "Parse", "a", "PASCAL", "VOC", "xml", "file" ]
def parse_rec(filename): """ Parse a PASCAL VOC xml file """ tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_struct = {} obj_struct['name'] = obj.find('name').text obj_struct['pose'] = obj.find('pose').text obj_struct['truncated'] = int(obj.find('truncated').text) obj_struct['difficult'] = int(obj.find('difficult').text) bbox = obj.find('bndbox') obj_struct['bbox'] = [int(bbox.find('xmin').text), int(bbox.find('ymin').text), int(bbox.find('xmax').text), int(bbox.find('ymax').text)] objects.append(obj_struct) return objects
[ "def", "parse_rec", "(", "filename", ")", ":", "tree", "=", "ET", ".", "parse", "(", "filename", ")", "objects", "=", "[", "]", "for", "obj", "in", "tree", ".", "findall", "(", "'object'", ")", ":", "obj_struct", "=", "{", "}", "obj_struct", "[", "...
https://github.com/dBeker/Faster-RCNN-TensorFlow-Python3/blob/027e5603551b3b9053042a113b4c7be9579dbb4a/lib/datasets/voc_eval.py#L17-L34
funnyzhou/FPN-Pytorch
423a4499c4e826d17367762e821b51b9b1b0f2f3
lib/datasets/json_dataset_evaluator.py
python
evaluate_box_proposals
( json_dataset, roidb, thresholds=None, area='all', limit=None )
return {'ar': ar, 'recalls': recalls, 'thresholds': thresholds, 'gt_overlaps': gt_overlaps, 'num_pos': num_pos}
Evaluate detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results.
Evaluate detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results.
[ "Evaluate", "detection", "proposal", "recall", "metrics", ".", "This", "function", "is", "a", "much", "faster", "alternative", "to", "the", "official", "COCO", "API", "recall", "evaluation", "code", ".", "However", "it", "produces", "slightly", "different", "res...
def evaluate_box_proposals( json_dataset, roidb, thresholds=None, area='all', limit=None ): """Evaluate detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results. """ # Record max overlap value for each gt box # Return vector of overlap values areas = { 'all': 0, 'small': 1, 'medium': 2, 'large': 3, '96-128': 4, '128-256': 5, '256-512': 6, '512-inf': 7} area_ranges = [ [0**2, 1e5**2], # all [0**2, 32**2], # small [32**2, 96**2], # medium [96**2, 1e5**2], # large [96**2, 128**2], # 96-128 [128**2, 256**2], # 128-256 [256**2, 512**2], # 256-512 [512**2, 1e5**2]] # 512-inf assert area in areas, 'Unknown area range: {}'.format(area) area_range = area_ranges[areas[area]] gt_overlaps = np.zeros(0) num_pos = 0 for entry in roidb: gt_inds = np.where( (entry['gt_classes'] > 0) & (entry['is_crowd'] == 0))[0] gt_boxes = entry['boxes'][gt_inds, :] gt_areas = entry['seg_areas'][gt_inds] valid_gt_inds = np.where( (gt_areas >= area_range[0]) & (gt_areas <= area_range[1]))[0] gt_boxes = gt_boxes[valid_gt_inds, :] num_pos += len(valid_gt_inds) non_gt_inds = np.where(entry['gt_classes'] == 0)[0] boxes = entry['boxes'][non_gt_inds, :] if boxes.shape[0] == 0: continue if limit is not None and boxes.shape[0] > limit: boxes = boxes[:limit, :] overlaps = box_utils.bbox_overlaps( boxes.astype(dtype=np.float32, copy=False), gt_boxes.astype(dtype=np.float32, copy=False)) _gt_overlaps = np.zeros((gt_boxes.shape[0])) for j in range(min(boxes.shape[0], gt_boxes.shape[0])): # find which proposal box maximally covers each gt box argmax_overlaps = overlaps.argmax(axis=0) # and get the iou amount of coverage for each gt box max_overlaps = overlaps.max(axis=0) # find which gt box is 'best' covered (i.e. 'best' = most iou) gt_ind = max_overlaps.argmax() gt_ovr = max_overlaps.max() assert gt_ovr >= 0 # find the proposal box that covers the best covered gt box box_ind = argmax_overlaps[gt_ind] # record the iou coverage of this gt box _gt_overlaps[j] = overlaps[box_ind, gt_ind] assert _gt_overlaps[j] == gt_ovr # mark the proposal box and the gt box as used overlaps[box_ind, :] = -1 overlaps[:, gt_ind] = -1 # append recorded iou coverage level gt_overlaps = np.hstack((gt_overlaps, _gt_overlaps)) gt_overlaps = np.sort(gt_overlaps) if thresholds is None: step = 0.05 thresholds = np.arange(0.5, 0.95 + 1e-5, step) recalls = np.zeros_like(thresholds) # compute recall for each iou threshold for i, t in enumerate(thresholds): recalls[i] = (gt_overlaps >= t).sum() / float(num_pos) # ar = 2 * np.trapz(recalls, thresholds) ar = recalls.mean() return {'ar': ar, 'recalls': recalls, 'thresholds': thresholds, 'gt_overlaps': gt_overlaps, 'num_pos': num_pos}
[ "def", "evaluate_box_proposals", "(", "json_dataset", ",", "roidb", ",", "thresholds", "=", "None", ",", "area", "=", "'all'", ",", "limit", "=", "None", ")", ":", "# Record max overlap value for each gt box", "# Return vector of overlap values", "areas", "=", "{", ...
https://github.com/funnyzhou/FPN-Pytorch/blob/423a4499c4e826d17367762e821b51b9b1b0f2f3/lib/datasets/json_dataset_evaluator.py#L295-L376
elbayadm/attn2d
982653439dedc7306e484e00b3dfb90e2cd7c9e1
examples/pervasive/modules/archive/pa_gatenet8.py
python
PAGateNet8.forward
(self, x, encoder_mask=None, decoder_mask=None, incremental_state=None)
return features
Input : B, Tt, Ts, C Output : B, Tt, Ts, C
Input : B, Tt, Ts, C Output : B, Tt, Ts, C
[ "Input", ":", "B", "Tt", "Ts", "C", "Output", ":", "B", "Tt", "Ts", "C" ]
def forward(self, x, encoder_mask=None, decoder_mask=None, incremental_state=None): """ Input : B, Tt, Ts, C Output : B, Tt, Ts, C """ if self.reduce_channels is not None: x = self.reduce_channels(x) features = self.gate_embeddings(x) for layer, gate in zip(self.blocks, self.gates): xlayer = layer(x, encoder_mask=encoder_mask, decoder_mask=decoder_mask, incremental_state=incremental_state) features += gate(xlayer) x = self.depth_gate(x + xlayer) return features
[ "def", "forward", "(", "self", ",", "x", ",", "encoder_mask", "=", "None", ",", "decoder_mask", "=", "None", ",", "incremental_state", "=", "None", ")", ":", "if", "self", ".", "reduce_channels", "is", "not", "None", ":", "x", "=", "self", ".", "reduce...
https://github.com/elbayadm/attn2d/blob/982653439dedc7306e484e00b3dfb90e2cd7c9e1/examples/pervasive/modules/archive/pa_gatenet8.py#L78-L97
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/analyses/binary_optimizer.py
python
BinaryOptimizer._constant_propagation
(self, function, data_graph)
:param function: :param networkx.MultiDiGraph data_graph: :return:
[]
def _constant_propagation(self, function, data_graph): #pylint:disable=unused-argument """ :param function: :param networkx.MultiDiGraph data_graph: :return: """ # find all edge sequences that looks like const->reg->memory for n0 in data_graph.nodes(): if not isinstance(n0.variable, SimConstantVariable): continue n1s = list(data_graph.successors(n0)) if len(n1s) != 1: continue n1 = n1s[0] if not isinstance(n1.variable, SimRegisterVariable): continue if len(list(data_graph.predecessors(n1))) != 1: continue n2s = list(data_graph.successors(n1)) if len(n2s) != 1: continue n2 = n2s[0] if not isinstance(n2.variable, SimMemoryVariable): continue n2_inedges = data_graph.in_edges(n2, data=True) if len([ 0 for _, _, data in n2_inedges if 'type' in data and data['type'] == 'mem_data' ]) != 1: continue cp = ConstantPropagation(n0.variable.value, n0.location, n2.location) self.constant_propagations.append(cp)
[ "def", "_constant_propagation", "(", "self", ",", "function", ",", "data_graph", ")", ":", "#pylint:disable=unused-argument", "# find all edge sequences that looks like const->reg->memory", "for", "n0", "in", "data_graph", ".", "nodes", "(", ")", ":", "if", "not", "isin...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/analyses/binary_optimizer.py#L202-L238
BlackLight/platypush
a6b552504e2ac327c94f3a28b607061b6b60cf36
platypush/plugins/mail/imap/__init__.py
python
MailImapPlugin.remove_flags
(self, messages: List[int], flags: Union[str, List[str]], folder: str = 'INBOX', **connect_args)
Remove a set of flags to the specified set of message IDs. :param messages: List of message IDs. :param flags: List of flags to be added. Examples: .. code-block:: python ['Flagged'] ['Seen', 'Deleted'] ['Junk'] :param folder: IMAP folder (default: ``INBOX``). :param connect_args: Arguments to pass to :meth:`._get_server_info` for server configuration override.
Remove a set of flags to the specified set of message IDs.
[ "Remove", "a", "set", "of", "flags", "to", "the", "specified", "set", "of", "message", "IDs", "." ]
def remove_flags(self, messages: List[int], flags: Union[str, List[str]], folder: str = 'INBOX', **connect_args): """ Remove a set of flags to the specified set of message IDs. :param messages: List of message IDs. :param flags: List of flags to be added. Examples: .. code-block:: python ['Flagged'] ['Seen', 'Deleted'] ['Junk'] :param folder: IMAP folder (default: ``INBOX``). :param connect_args: Arguments to pass to :meth:`._get_server_info` for server configuration override. """ with self.connect(**connect_args) as client: client.select_folder(folder) client.remove_flags(messages, self._convert_flags(flags))
[ "def", "remove_flags", "(", "self", ",", "messages", ":", "List", "[", "int", "]", ",", "flags", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "folder", ":", "str", "=", "'INBOX'", ",", "*", "*", "connect_args", ")", ":", "wit...
https://github.com/BlackLight/platypush/blob/a6b552504e2ac327c94f3a28b607061b6b60cf36/platypush/plugins/mail/imap/__init__.py#L465-L483
lmb-freiburg/mv3d
7118c2fe37071ed236e6457b95f6efb361b746ff
utils/renderer.py
python
Renderer.deactivateLightSources
(self)
[]
def deactivateLightSources(self): for i in range(0, 7): self.light_sources[i].setColor(VBase4(0, 0, 0, 0))
[ "def", "deactivateLightSources", "(", "self", ")", ":", "for", "i", "in", "range", "(", "0", ",", "7", ")", ":", "self", ".", "light_sources", "[", "i", "]", ".", "setColor", "(", "VBase4", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")" ]
https://github.com/lmb-freiburg/mv3d/blob/7118c2fe37071ed236e6457b95f6efb361b746ff/utils/renderer.py#L107-L109
weinbe58/QuSpin
5bbc3204dbf5c227a87a44f0dacf39509cba580c
docs/downloads/9fcc9e398d1dd9d5f23ac37f6401eb0b/example16.py
python
make_basis
(N_half)
return (states_b+shift_states_b.T).ravel()
Generates a list of integers to represent external, user-imported basis
Generates a list of integers to represent external, user-imported basis
[ "Generates", "a", "list", "of", "integers", "to", "represent", "external", "user", "-", "imported", "basis" ]
def make_basis(N_half): """ Generates a list of integers to represent external, user-imported basis """ old_basis = spin_basis_general(N_half,m=0) # states = old_basis.states shift_states = np.left_shift(states,N_half) # shape=states.shape+states.shape # states_b = np.broadcast_to(states,shape) shift_states_b = np.broadcast_to(shift_states,shape) # this does the kronecker sum in a more memory efficient way. return (states_b+shift_states_b.T).ravel()
[ "def", "make_basis", "(", "N_half", ")", ":", "old_basis", "=", "spin_basis_general", "(", "N_half", ",", "m", "=", "0", ")", "#", "states", "=", "old_basis", ".", "states", "shift_states", "=", "np", ".", "left_shift", "(", "states", ",", "N_half", ")",...
https://github.com/weinbe58/QuSpin/blob/5bbc3204dbf5c227a87a44f0dacf39509cba580c/docs/downloads/9fcc9e398d1dd9d5f23ac37f6401eb0b/example16.py#L28-L40
pypa/pip
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
src/pip/_vendor/rich/pretty.py
python
_get_attr_fields
(obj: Any)
return _attr_module.fields(type(obj)) if _attr_module is not None else []
Get fields for an attrs object.
Get fields for an attrs object.
[ "Get", "fields", "for", "an", "attrs", "object", "." ]
def _get_attr_fields(obj: Any) -> Iterable["_attr_module.Attribute[Any]"]: """Get fields for an attrs object.""" return _attr_module.fields(type(obj)) if _attr_module is not None else []
[ "def", "_get_attr_fields", "(", "obj", ":", "Any", ")", "->", "Iterable", "[", "\"_attr_module.Attribute[Any]\"", "]", ":", "return", "_attr_module", ".", "fields", "(", "type", "(", "obj", ")", ")", "if", "_attr_module", "is", "not", "None", "else", "[", ...
https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/rich/pretty.py#L63-L65
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_git/build/lib/base.py
python
GitCLI._push
(self, remote, src_branch, dest_branch)
return results
Do a git checkout to <branch>
Do a git checkout to <branch>
[ "Do", "a", "git", "checkout", "to", "<branch", ">" ]
def _push(self, remote, src_branch, dest_branch): ''' Do a git checkout to <branch> ''' push_branches = src_branch + ":" + dest_branch cmd = ["push", remote, push_branches] results = self.git_cmd(cmd, output=True, output_type='raw') return results
[ "def", "_push", "(", "self", ",", "remote", ",", "src_branch", ",", "dest_branch", ")", ":", "push_branches", "=", "src_branch", "+", "\":\"", "+", "dest_branch", "cmd", "=", "[", "\"push\"", ",", "remote", ",", "push_branches", "]", "results", "=", "self"...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_git/build/lib/base.py#L127-L135
wummel/linkchecker
c2ce810c3fb00b895a841a7be6b2e78c64e7b042
linkcheck/i18n.py
python
get_encoded_writer
(out=sys.stdout, encoding=None, errors='replace')
return Writer(out, errors)
Get wrapped output writer with given encoding and error handling.
Get wrapped output writer with given encoding and error handling.
[ "Get", "wrapped", "output", "writer", "with", "given", "encoding", "and", "error", "handling", "." ]
def get_encoded_writer (out=sys.stdout, encoding=None, errors='replace'): """Get wrapped output writer with given encoding and error handling.""" if encoding is None: encoding = default_encoding Writer = codecs.getwriter(encoding) return Writer(out, errors)
[ "def", "get_encoded_writer", "(", "out", "=", "sys", ".", "stdout", ",", "encoding", "=", "None", ",", "errors", "=", "'replace'", ")", ":", "if", "encoding", "is", "None", ":", "encoding", "=", "default_encoding", "Writer", "=", "codecs", ".", "getwriter"...
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/i18n.py#L200-L205
PaddlePaddle/Research
2da0bd6c72d60e9df403aff23a7802779561c4a1
KG/CoKE/bin/pathquery_data_preprocess.py
python
Graph.walk_all
(self, start, path)
return set_s
walk from start and get all the paths :param start: start entity :param path: (r1, r2, ...,rk) :return: entities set for candidates path
walk from start and get all the paths :param start: start entity :param path: (r1, r2, ...,rk) :return: entities set for candidates path
[ "walk", "from", "start", "and", "get", "all", "the", "paths", ":", "param", "start", ":", "start", "entity", ":", "param", "path", ":", "(", "r1", "r2", "...", "rk", ")", ":", "return", ":", "entities", "set", "for", "candidates", "path" ]
def walk_all(self, start, path): """ walk from start and get all the paths :param start: start entity :param path: (r1, r2, ...,rk) :return: entities set for candidates path """ set_s = set() set_t = set() set_s.add(start) for _, r in enumerate(path): if len(set_s) == 0: return set() for _s in set_s: if _s in self.neighbors and r in self.neighbors[_s]: _tset = set(self.neighbors[_s][r]) #tupe to set set_t.update(_tset) set_s = set_t.copy() set_t.clear() return set_s
[ "def", "walk_all", "(", "self", ",", "start", ",", "path", ")", ":", "set_s", "=", "set", "(", ")", "set_t", "=", "set", "(", ")", "set_s", ".", "add", "(", "start", ")", "for", "_", ",", "r", "in", "enumerate", "(", "path", ")", ":", "if", "...
https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/KG/CoKE/bin/pathquery_data_preprocess.py#L105-L124
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventDetails.team_profile_remove_logo_details
(cls, val)
return cls('team_profile_remove_logo_details', val)
Create an instance of this class set to the ``team_profile_remove_logo_details`` tag with value ``val``. :param TeamProfileRemoveLogoDetails val: :rtype: EventDetails
Create an instance of this class set to the ``team_profile_remove_logo_details`` tag with value ``val``.
[ "Create", "an", "instance", "of", "this", "class", "set", "to", "the", "team_profile_remove_logo_details", "tag", "with", "value", "val", "." ]
def team_profile_remove_logo_details(cls, val): """ Create an instance of this class set to the ``team_profile_remove_logo_details`` tag with value ``val``. :param TeamProfileRemoveLogoDetails val: :rtype: EventDetails """ return cls('team_profile_remove_logo_details', val)
[ "def", "team_profile_remove_logo_details", "(", "cls", ",", "val", ")", ":", "return", "cls", "(", "'team_profile_remove_logo_details'", ",", "val", ")" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L12988-L12996
nitishsrivastava/deepnet
f4e4ff207923e01552c96038a1e2c29eb5d16160
cudamat/cudamat.py
python
CUDAMatrix.set_selected_columns
(self, indices, source)
return self
copies all columns of source into some columns of self. <indices> must be a row vector. Its elements are float32's representing integers, e.g. "34.0" means the integer "34". after this call, for all r,c, self[r,indices[c]]=source[r,c]. This returns self. Negative indices are interpreted in the usual Python way: all elements of <indices> had better be in the range [-self.shape[1], self.shape[1]-1]. This does bounds checking, but out of bounds indices do not raise an exception (because the programmer was lazy). Instead, they result in NaN values in <self>.
copies all columns of source into some columns of self. <indices> must be a row vector. Its elements are float32's representing integers, e.g. "34.0" means the integer "34". after this call, for all r,c, self[r,indices[c]]=source[r,c]. This returns self. Negative indices are interpreted in the usual Python way: all elements of <indices> had better be in the range [-self.shape[1], self.shape[1]-1]. This does bounds checking, but out of bounds indices do not raise an exception (because the programmer was lazy). Instead, they result in NaN values in <self>.
[ "copies", "all", "columns", "of", "source", "into", "some", "columns", "of", "self", ".", "<indices", ">", "must", "be", "a", "row", "vector", ".", "Its", "elements", "are", "float32", "s", "representing", "integers", "e", ".", "g", ".", "34", ".", "0"...
def set_selected_columns(self, indices, source): """ copies all columns of source into some columns of self. <indices> must be a row vector. Its elements are float32's representing integers, e.g. "34.0" means the integer "34". after this call, for all r,c, self[r,indices[c]]=source[r,c]. This returns self. Negative indices are interpreted in the usual Python way: all elements of <indices> had better be in the range [-self.shape[1], self.shape[1]-1]. This does bounds checking, but out of bounds indices do not raise an exception (because the programmer was lazy). Instead, they result in NaN values in <self>. """ err_code = _cudamat.setSelectedRows(self.p_mat, source.p_mat, indices.p_mat) if err_code: raise generate_exception(err_code) return self
[ "def", "set_selected_columns", "(", "self", ",", "indices", ",", "source", ")", ":", "err_code", "=", "_cudamat", ".", "setSelectedRows", "(", "self", ".", "p_mat", ",", "source", ".", "p_mat", ",", "indices", ".", "p_mat", ")", "if", "err_code", ":", "r...
https://github.com/nitishsrivastava/deepnet/blob/f4e4ff207923e01552c96038a1e2c29eb5d16160/cudamat/cudamat.py#L1514-L1531
dmlc/gluon-cv
709bc139919c02f7454cb411311048be188cde64
gluoncv/model_zoo/icnet.py
python
get_icnet_resnet50_citys
(**kwargs)
return get_icnet(dataset='citys', backbone='resnet50', **kwargs)
r"""Image Cascade Network Parameters ---------- dataset : str, default citys The dataset that model pretrained on. (default: cityscapes) backbone : string Pre-trained dilated backbone network type (default:'resnet50').
r"""Image Cascade Network
[ "r", "Image", "Cascade", "Network" ]
def get_icnet_resnet50_citys(**kwargs): r"""Image Cascade Network Parameters ---------- dataset : str, default citys The dataset that model pretrained on. (default: cityscapes) backbone : string Pre-trained dilated backbone network type (default:'resnet50'). """ return get_icnet(dataset='citys', backbone='resnet50', **kwargs)
[ "def", "get_icnet_resnet50_citys", "(", "*", "*", "kwargs", ")", ":", "return", "get_icnet", "(", "dataset", "=", "'citys'", ",", "backbone", "=", "'resnet50'", ",", "*", "*", "kwargs", ")" ]
https://github.com/dmlc/gluon-cv/blob/709bc139919c02f7454cb411311048be188cde64/gluoncv/model_zoo/icnet.py#L363-L374
flosell/trailscraper
2509b8da81b49edf375a44fbc22a58fd9e2ea928
trailscraper/cli.py
python
select
(log_dir, filter_assumed_role_arn, use_cloudtrail_api, from_s, to_s)
Finds all CloudTrail records matching the given filters and prints them.
Finds all CloudTrail records matching the given filters and prints them.
[ "Finds", "all", "CloudTrail", "records", "matching", "the", "given", "filters", "and", "prints", "them", "." ]
def select(log_dir, filter_assumed_role_arn, use_cloudtrail_api, from_s, to_s): """Finds all CloudTrail records matching the given filters and prints them.""" log_dir = os.path.expanduser(log_dir) from_date = time_utils.parse_human_readable_time(from_s) to_date = time_utils.parse_human_readable_time(to_s) if use_cloudtrail_api: records = CloudTrailAPIRecordSource().load_from_api(from_date, to_date) else: records = LocalDirectoryRecordSource(log_dir).load_from_dir(from_date, to_date) filtered_records = filter_records(records, filter_assumed_role_arn, from_date, to_date) filtered_records_as_json = [record.raw_source for record in filtered_records] click.echo(json.dumps({"Records": filtered_records_as_json}))
[ "def", "select", "(", "log_dir", ",", "filter_assumed_role_arn", ",", "use_cloudtrail_api", ",", "from_s", ",", "to_s", ")", ":", "log_dir", "=", "os", ".", "path", ".", "expanduser", "(", "log_dir", ")", "from_date", "=", "time_utils", ".", "parse_human_reada...
https://github.com/flosell/trailscraper/blob/2509b8da81b49edf375a44fbc22a58fd9e2ea928/trailscraper/cli.py#L88-L103
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/sqlalchemy/engine/base.py
python
Connection.closed
(self)
return '_Connection__connection' not in self.__dict__ \ and not self.__can_reconnect
Return True if this connection is closed.
Return True if this connection is closed.
[ "Return", "True", "if", "this", "connection", "is", "closed", "." ]
def closed(self): """Return True if this connection is closed.""" return '_Connection__connection' not in self.__dict__ \ and not self.__can_reconnect
[ "def", "closed", "(", "self", ")", ":", "return", "'_Connection__connection'", "not", "in", "self", ".", "__dict__", "and", "not", "self", ".", "__can_reconnect" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/sqlalchemy/engine/base.py#L289-L293
anyoptimization/pymoo
c6426a721d95c932ae6dbb610e09b6c1b0e13594
pymoo/experimental/algorithms/moadawa.py
python
MOEADAWA.__init__
(self, ref_dirs, n_neighbors=20, decomposition=Tchebicheff(), prob_neighbor_mating=0.9, rate_update_weight=0.05, rate_evol=0.8, wag=20, archive_size_multiplier=1.5, use_new_ref_dirs_initialization=True, display=MultiObjectiveDisplay(), **kwargs)
MOEAD-AWA Algorithm. Parameters ---------- ref_dirs n_neighbors decomposition prob_neighbor_mating rate_update_weight rate_evol wag archive_size_multiplier use_new_ref_dirs_initialization display kwargs
[]
def __init__(self, ref_dirs, n_neighbors=20, decomposition=Tchebicheff(), prob_neighbor_mating=0.9, rate_update_weight=0.05, rate_evol=0.8, wag=20, archive_size_multiplier=1.5, use_new_ref_dirs_initialization=True, display=MultiObjectiveDisplay(), **kwargs): """ MOEAD-AWA Algorithm. Parameters ---------- ref_dirs n_neighbors decomposition prob_neighbor_mating rate_update_weight rate_evol wag archive_size_multiplier use_new_ref_dirs_initialization display kwargs """ self.n_neighbors = n_neighbors self.prob_neighbor_mating = prob_neighbor_mating self.decomp = decomposition self.rate_update_weight = rate_update_weight self.rate_evol = rate_evol self.wag = wag self.EP = None self.nEP = np.ceil(len(ref_dirs) * archive_size_multiplier) set_if_none(kwargs, 'pop_size', len(ref_dirs)) set_if_none(kwargs, 'sampling', FloatRandomSampling()) set_if_none(kwargs, 'crossover', SBX(prob=1.0, eta=20)) set_if_none(kwargs, 'mutation', PM(prob=None, eta=20)) set_if_none(kwargs, 'survival', None) set_if_none(kwargs, 'selection', None) super().__init__(display=display, **kwargs) # initialized when problem is known self.ref_dirs = ref_dirs if use_new_ref_dirs_initialization: self.ref_dirs = 1.0 / (self.ref_dirs + 1e-6) self.ref_dirs = self.ref_dirs / np.sum(self.ref_dirs, axis=1)[:, None] if self.ref_dirs.shape[0] < self.n_neighbors: print("Setting number of neighbours to population size: %s" % self.ref_dirs.shape[0]) self.n_neighbors = self.ref_dirs.shape[0] self.nds = NonDominatedSorting() # compute neighbors of reference directions using euclidean distance self._update_neighbors()
[ "def", "__init__", "(", "self", ",", "ref_dirs", ",", "n_neighbors", "=", "20", ",", "decomposition", "=", "Tchebicheff", "(", ")", ",", "prob_neighbor_mating", "=", "0.9", ",", "rate_update_weight", "=", "0.05", ",", "rate_evol", "=", "0.8", ",", "wag", "...
https://github.com/anyoptimization/pymoo/blob/c6426a721d95c932ae6dbb610e09b6c1b0e13594/pymoo/experimental/algorithms/moadawa.py#L32-L96
kivy/kivy
fbf561f73ddba9941b1b7e771f86264c6e6eef36
kivy/uix/modalview.py
python
ModalView.dismiss
(self, *_args, **kwargs)
Close the view if it is open. If you really want to close the view, whatever the on_dismiss event returns, you can use the *force* keyword argument:: view = ModalView() view.dismiss(force=True) When the view is dismissed, it will be faded out before being removed from the parent. If you don't want this animation, use:: view.dismiss(animation=False)
Close the view if it is open.
[ "Close", "the", "view", "if", "it", "is", "open", "." ]
def dismiss(self, *_args, **kwargs): """ Close the view if it is open. If you really want to close the view, whatever the on_dismiss event returns, you can use the *force* keyword argument:: view = ModalView() view.dismiss(force=True) When the view is dismissed, it will be faded out before being removed from the parent. If you don't want this animation, use:: view.dismiss(animation=False) """ if not self._is_open: return self.dispatch('on_pre_dismiss') if self.dispatch('on_dismiss') is True: if kwargs.get('force', False) is not True: return if kwargs.get('animation', True): Animation(_anim_alpha=0., d=self._anim_duration).start(self) else: self._anim_alpha = 0 self._real_remove_widget()
[ "def", "dismiss", "(", "self", ",", "*", "_args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "_is_open", ":", "return", "self", ".", "dispatch", "(", "'on_pre_dismiss'", ")", "if", "self", ".", "dispatch", "(", "'on_dismiss'", ")", ...
https://github.com/kivy/kivy/blob/fbf561f73ddba9941b1b7e771f86264c6e6eef36/kivy/uix/modalview.py#L227-L252
cjdrake/pyeda
554ee53aa678f4b61bcd7e07ba2c74ddc749d665
pyeda/boolalg/bfarray.py
python
farray.uand
(self)
return reduce(operator.and_, self._items, self.ftype.box(1))
Unary AND reduction operator
Unary AND reduction operator
[ "Unary", "AND", "reduction", "operator" ]
def uand(self): """Unary AND reduction operator""" return reduce(operator.and_, self._items, self.ftype.box(1))
[ "def", "uand", "(", "self", ")", ":", "return", "reduce", "(", "operator", ".", "and_", ",", "self", ".", "_items", ",", "self", ".", "ftype", ".", "box", "(", "1", ")", ")" ]
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/bfarray.py#L732-L734
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oo_iam_kms.py
python
AwsIamKms.__init__
(self)
constructor
constructor
[ "constructor" ]
def __init__(self): ''' constructor ''' self.module = None self.kms_client = None self.aliases = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "module", "=", "None", "self", ".", "kms_client", "=", "None", "self", ".", "aliases", "=", "None" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oo_iam_kms.py#L40-L44
facebookresearch/demucs
7317db81a34349e028ec943b199c9b9cdda47a12
demucs/demucs.py
python
DConv.__init__
(self, channels: int, compress: float = 4, depth: int = 2, init: float = 1e-4, norm=True, attn=False, heads=4, ndecay=4, lstm=False, gelu=True, kernel=3, dilate=True)
Args: channels: input/output channels for residual branch. compress: amount of channel compression inside the branch. depth: number of layers in the residual branch. Each layer has its own projection, and potentially LSTM and attention. init: initial scale for LayerNorm. norm: use GroupNorm. attn: use LocalAttention. heads: number of heads for the LocalAttention. ndecay: number of decay controls in the LocalAttention. lstm: use LSTM. gelu: Use GELU activation. kernel: kernel size for the (dilated) convolutions. dilate: if true, use dilation, increasing with the depth.
Args: channels: input/output channels for residual branch. compress: amount of channel compression inside the branch. depth: number of layers in the residual branch. Each layer has its own projection, and potentially LSTM and attention. init: initial scale for LayerNorm. norm: use GroupNorm. attn: use LocalAttention. heads: number of heads for the LocalAttention. ndecay: number of decay controls in the LocalAttention. lstm: use LSTM. gelu: Use GELU activation. kernel: kernel size for the (dilated) convolutions. dilate: if true, use dilation, increasing with the depth.
[ "Args", ":", "channels", ":", "input", "/", "output", "channels", "for", "residual", "branch", ".", "compress", ":", "amount", "of", "channel", "compression", "inside", "the", "branch", ".", "depth", ":", "number", "of", "layers", "in", "the", "residual", ...
def __init__(self, channels: int, compress: float = 4, depth: int = 2, init: float = 1e-4, norm=True, attn=False, heads=4, ndecay=4, lstm=False, gelu=True, kernel=3, dilate=True): """ Args: channels: input/output channels for residual branch. compress: amount of channel compression inside the branch. depth: number of layers in the residual branch. Each layer has its own projection, and potentially LSTM and attention. init: initial scale for LayerNorm. norm: use GroupNorm. attn: use LocalAttention. heads: number of heads for the LocalAttention. ndecay: number of decay controls in the LocalAttention. lstm: use LSTM. gelu: Use GELU activation. kernel: kernel size for the (dilated) convolutions. dilate: if true, use dilation, increasing with the depth. """ super().__init__() assert kernel % 2 == 1 self.channels = channels self.compress = compress self.depth = abs(depth) dilate = depth > 0 norm_fn: tp.Callable[[int], nn.Module] norm_fn = lambda d: nn.Identity() # noqa if norm: norm_fn = lambda d: nn.GroupNorm(1, d) # noqa hidden = int(channels / compress) act: tp.Type[nn.Module] if gelu: act = nn.GELU else: act = nn.ReLU self.layers = nn.ModuleList([]) for d in range(self.depth): dilation = 2 ** d if dilate else 1 padding = dilation * (kernel // 2) mods = [ nn.Conv1d(channels, hidden, kernel, dilation=dilation, padding=padding), norm_fn(hidden), act(), nn.Conv1d(hidden, 2 * channels, 1), norm_fn(2 * channels), nn.GLU(1), LayerScale(channels, init), ] if attn: mods.insert(3, LocalState(hidden, heads=heads, ndecay=ndecay)) if lstm: mods.insert(3, BLSTM(hidden, layers=2, max_steps=200, skip=True)) layer = nn.Sequential(*mods) self.layers.append(layer)
[ "def", "__init__", "(", "self", ",", "channels", ":", "int", ",", "compress", ":", "float", "=", "4", ",", "depth", ":", "int", "=", "2", ",", "init", ":", "float", "=", "1e-4", ",", "norm", "=", "True", ",", "attn", "=", "False", ",", "heads", ...
https://github.com/facebookresearch/demucs/blob/7317db81a34349e028ec943b199c9b9cdda47a12/demucs/demucs.py#L105-L161
skylander86/lambda-text-extractor
6da52d077a2fc571e38bfe29c33ae68f6443cd5a
lib-linux_x64/pptx/slide.py
python
NotesSlide.notes_text_frame
(self)
return notes_placeholder.text_frame
Return the text frame of the notes placeholder on this notes slide, or |None| if there is no notes placeholder. This is a shortcut to accommodate the common case of simply adding "notes" text to the notes "page".
Return the text frame of the notes placeholder on this notes slide, or |None| if there is no notes placeholder. This is a shortcut to accommodate the common case of simply adding "notes" text to the notes "page".
[ "Return", "the", "text", "frame", "of", "the", "notes", "placeholder", "on", "this", "notes", "slide", "or", "|None|", "if", "there", "is", "no", "notes", "placeholder", ".", "This", "is", "a", "shortcut", "to", "accommodate", "the", "common", "case", "of"...
def notes_text_frame(self): """ Return the text frame of the notes placeholder on this notes slide, or |None| if there is no notes placeholder. This is a shortcut to accommodate the common case of simply adding "notes" text to the notes "page". """ notes_placeholder = self.notes_placeholder if notes_placeholder is None: return None return notes_placeholder.text_frame
[ "def", "notes_text_frame", "(", "self", ")", ":", "notes_placeholder", "=", "self", ".", "notes_placeholder", "if", "notes_placeholder", "is", "None", ":", "return", "None", "return", "notes_placeholder", ".", "text_frame" ]
https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/pptx/slide.py#L125-L135
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/urllib/parse.py
python
splittag
(url)
return url, None
splittag('/path#tag') --> '/path', 'tag'.
splittag('/path#tag') --> '/path', 'tag'.
[ "splittag", "(", "/", "path#tag", ")", "--", ">", "/", "path", "tag", "." ]
def splittag(url): """splittag('/path#tag') --> '/path', 'tag'.""" path, delim, tag = url.rpartition('#') if delim: return path, tag return url, None
[ "def", "splittag", "(", "url", ")", ":", "path", ",", "delim", ",", "tag", "=", "url", ".", "rpartition", "(", "'#'", ")", "if", "delim", ":", "return", "path", ",", "tag", "return", "url", ",", "None" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/urllib/parse.py#L1052-L1057
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/decimal.py
python
Decimal.__ne__
(self, other, context=None)
return self._cmp(other) != 0
[]
def __ne__(self, other, context=None): self, other = _convert_for_comparison(self, other, equality_op=True) if other is NotImplemented: return other if self._check_nans(other, context): return True return self._cmp(other) != 0
[ "def", "__ne__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "self", ",", "other", "=", "_convert_for_comparison", "(", "self", ",", "other", ",", "equality_op", "=", "True", ")", "if", "other", "is", "NotImplemented", ":", "return"...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/decimal.py#L931-L937
pytroll/satpy
09e51f932048f98cce7919a4ff8bd2ec01e1ae98
satpy/readers/yaml_reader.py
python
_get_FCI_L1c_FDHSI_chunk_height
(chunk_width, chunk_n)
return chunk_height
Get the height in pixels of a FCI L1c FDHSI chunk given the chunk width and number (starting from 1).
Get the height in pixels of a FCI L1c FDHSI chunk given the chunk width and number (starting from 1).
[ "Get", "the", "height", "in", "pixels", "of", "a", "FCI", "L1c", "FDHSI", "chunk", "given", "the", "chunk", "width", "and", "number", "(", "starting", "from", "1", ")", "." ]
def _get_FCI_L1c_FDHSI_chunk_height(chunk_width, chunk_n): """Get the height in pixels of a FCI L1c FDHSI chunk given the chunk width and number (starting from 1).""" if chunk_width == 11136: # 1km resolution case if chunk_n in [3, 5, 8, 10, 13, 15, 18, 20, 23, 25, 28, 30, 33, 35, 38, 40]: chunk_height = 279 else: chunk_height = 278 elif chunk_width == 5568: # 2km resolution case if chunk_n in [5, 10, 15, 20, 25, 30, 35, 40]: chunk_height = 140 else: chunk_height = 139 else: raise ValueError("FCI L1c FDHSI chunk width {} not recognized. Must be either 5568 or 11136.".format( chunk_width)) return chunk_height
[ "def", "_get_FCI_L1c_FDHSI_chunk_height", "(", "chunk_width", ",", "chunk_n", ")", ":", "if", "chunk_width", "==", "11136", ":", "# 1km resolution case", "if", "chunk_n", "in", "[", "3", ",", "5", ",", "8", ",", "10", ",", "13", ",", "15", ",", "18", ","...
https://github.com/pytroll/satpy/blob/09e51f932048f98cce7919a4ff8bd2ec01e1ae98/satpy/readers/yaml_reader.py#L1369-L1387
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/idlelib/macosxSupport.py
python
tkVersionWarning
(root)
Returns a string warning message if the Tk version in use appears to be one known to cause problems with IDLE. The Apple Cocoa-based Tk 8.5 that was shipped with Mac OS X 10.6.
Returns a string warning message if the Tk version in use appears to be one known to cause problems with IDLE. The Apple Cocoa-based Tk 8.5 that was shipped with Mac OS X 10.6.
[ "Returns", "a", "string", "warning", "message", "if", "the", "Tk", "version", "in", "use", "appears", "to", "be", "one", "known", "to", "cause", "problems", "with", "IDLE", ".", "The", "Apple", "Cocoa", "-", "based", "Tk", "8", ".", "5", "that", "was",...
def tkVersionWarning(root): """ Returns a string warning message if the Tk version in use appears to be one known to cause problems with IDLE. The Apple Cocoa-based Tk 8.5 that was shipped with Mac OS X 10.6. """ if runningAsOSXApp() and 'AppKit' in root.tk.call('winfo', 'server', '.') and root.tk.call('info', 'patchlevel') == '8.5.7': return 'WARNING: The version of Tcl/Tk (8.5.7) in use may be unstable.\\nVisit http://www.python.org/download/mac/tcltk/ for current information.' else: return False
[ "def", "tkVersionWarning", "(", "root", ")", ":", "if", "runningAsOSXApp", "(", ")", "and", "'AppKit'", "in", "root", ".", "tk", ".", "call", "(", "'winfo'", ",", "'server'", ",", "'.'", ")", "and", "root", ".", "tk", ".", "call", "(", "'info'", ",",...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/idlelib/macosxSupport.py#L40-L49
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/quantum/quantum/agent/linux/interface.py
python
LinuxInterfaceDriver.init_l3
(self, device_name, ip_cidrs, namespace=None)
Set the L3 settings for the interface using data from the port. ip_cidrs: list of 'X.X.X.X/YY' strings
Set the L3 settings for the interface using data from the port. ip_cidrs: list of 'X.X.X.X/YY' strings
[ "Set", "the", "L3", "settings", "for", "the", "interface", "using", "data", "from", "the", "port", ".", "ip_cidrs", ":", "list", "of", "X", ".", "X", ".", "X", ".", "X", "/", "YY", "strings" ]
def init_l3(self, device_name, ip_cidrs, namespace=None): """Set the L3 settings for the interface using data from the port. ip_cidrs: list of 'X.X.X.X/YY' strings """ device = ip_lib.IPDevice(device_name, self.root_helper, namespace=namespace) previous = {} for address in device.addr.list(scope='global', filters=['permanent']): previous[address['cidr']] = address['ip_version'] # add new addresses for ip_cidr in ip_cidrs: net = netaddr.IPNetwork(ip_cidr) if ip_cidr in previous: del previous[ip_cidr] continue device.addr.add(net.version, ip_cidr, str(net.broadcast)) # clean up any old addresses for ip_cidr, ip_version in previous.items(): device.addr.delete(ip_version, ip_cidr)
[ "def", "init_l3", "(", "self", ",", "device_name", ",", "ip_cidrs", ",", "namespace", "=", "None", ")", ":", "device", "=", "ip_lib", ".", "IPDevice", "(", "device_name", ",", "self", ".", "root_helper", ",", "namespace", "=", "namespace", ")", "previous",...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/quantum/quantum/agent/linux/interface.py#L73-L97
cbrgm/telegram-robot-rss
58fe98de427121fdc152c8df0721f1891174e6c9
venv/lib/python2.7/site-packages/setuptools/command/bdist_egg.py
python
make_zipfile
(zip_filename, base_dir, verbose=0, dry_run=0, compress=True, mode='w')
return zip_filename
Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_dir' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises DistutilsExecError. Returns the name of the output zip file.
Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_dir' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises DistutilsExecError. Returns the name of the output zip file.
[ "Create", "a", "zip", "file", "from", "all", "the", "files", "under", "base_dir", ".", "The", "output", "zip", "file", "will", "be", "named", "base_dir", "+", ".", "zip", ".", "Uses", "either", "the", "zipfile", "Python", "module", "(", "if", "available"...
def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True, mode='w'): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_dir' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises DistutilsExecError. Returns the name of the output zip file. """ import zipfile mkpath(os.path.dirname(zip_filename), dry_run=dry_run) log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir) def visit(z, dirname, names): for name in names: path = os.path.normpath(os.path.join(dirname, name)) if os.path.isfile(path): p = path[len(base_dir) + 1:] if not dry_run: z.write(path, p) log.debug("adding '%s'", p) compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED if not dry_run: z = zipfile.ZipFile(zip_filename, mode, compression=compression) for dirname, dirs, files in sorted_walk(base_dir): visit(z, dirname, files) z.close() else: for dirname, dirs, files in sorted_walk(base_dir): visit(None, dirname, files) return zip_filename
[ "def", "make_zipfile", "(", "zip_filename", ",", "base_dir", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "compress", "=", "True", ",", "mode", "=", "'w'", ")", ":", "import", "zipfile", "mkpath", "(", "os", ".", "path", ".", "dirname", "...
https://github.com/cbrgm/telegram-robot-rss/blob/58fe98de427121fdc152c8df0721f1891174e6c9/venv/lib/python2.7/site-packages/setuptools/command/bdist_egg.py#L449-L480
openstack/horizon
12bb9fe5184c9dd3329ba17b3d03c90887dbcc3d
openstack_dashboard/usage/quotas.py
python
QuotaUsage.tally
(self, name, value)
Adds to the "used" metric for the given quota.
Adds to the "used" metric for the given quota.
[ "Adds", "to", "the", "used", "metric", "for", "the", "given", "quota", "." ]
def tally(self, name, value): """Adds to the "used" metric for the given quota.""" value = value or 0 # Protection against None. # Start at 0 if this is the first value. if 'used' not in self.usages[name]: self.usages[name]['used'] = 0 # Increment our usage and update the "available" metric. self.usages[name]['used'] += int(value) # Fail if can't coerce to int. self.update_available(name)
[ "def", "tally", "(", "self", ",", "name", ",", "value", ")", ":", "value", "=", "value", "or", "0", "# Protection against None.", "# Start at 0 if this is the first value.", "if", "'used'", "not", "in", "self", ".", "usages", "[", "name", "]", ":", "self", "...
https://github.com/openstack/horizon/blob/12bb9fe5184c9dd3329ba17b3d03c90887dbcc3d/openstack_dashboard/usage/quotas.py#L153-L161
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
apps/impala/gen-py/hive_metastore/ThriftHiveMetastore.py
python
Iface.getMetaConf
(self, key)
Parameters: - key
Parameters: - key
[ "Parameters", ":", "-", "key" ]
def getMetaConf(self, key): """ Parameters: - key """ pass
[ "def", "getMetaConf", "(", "self", ",", "key", ")", ":", "pass" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/apps/impala/gen-py/hive_metastore/ThriftHiveMetastore.py#L27-L33
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/hachoir_core/tools.py
python
timestampUUID60
(value)
Convert UUID 60-bit timestamp to string. The timestamp format is a 60-bit number which represents number of 100ns since the the 15 October 1582 at 00:00. Result is an unicode string. >>> timestampUUID60(0) datetime.datetime(1582, 10, 15, 0, 0) >>> timestampUUID60(130435676263032368) datetime.datetime(1996, 2, 14, 5, 13, 46, 303236)
Convert UUID 60-bit timestamp to string. The timestamp format is a 60-bit number which represents number of 100ns since the the 15 October 1582 at 00:00. Result is an unicode string.
[ "Convert", "UUID", "60", "-", "bit", "timestamp", "to", "string", ".", "The", "timestamp", "format", "is", "a", "60", "-", "bit", "number", "which", "represents", "number", "of", "100ns", "since", "the", "the", "15", "October", "1582", "at", "00", ":", ...
def timestampUUID60(value): """ Convert UUID 60-bit timestamp to string. The timestamp format is a 60-bit number which represents number of 100ns since the the 15 October 1582 at 00:00. Result is an unicode string. >>> timestampUUID60(0) datetime.datetime(1582, 10, 15, 0, 0) >>> timestampUUID60(130435676263032368) datetime.datetime(1996, 2, 14, 5, 13, 46, 303236) """ if not isinstance(value, (float, int, long)): raise TypeError("an integer or float is required") if value < 0: raise ValueError("value have to be a positive or nul integer") try: return UUID60_TIMESTAMP_T0 + timedelta(microseconds=value/10) except OverflowError: raise ValueError(_("timestampUUID60() overflow (value=%s)") % value)
[ "def", "timestampUUID60", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "float", ",", "int", ",", "long", ")", ")", ":", "raise", "TypeError", "(", "\"an integer or float is required\"", ")", "if", "value", "<", "0", ":", "ra...
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/hachoir_core/tools.py#L528-L546
IronLanguages/ironpython2
51fdedeeda15727717fb8268a805f71b06c0b9f1
Src/StdLib/Lib/ConfigParser.py
python
RawConfigParser.options
(self, section)
return opts.keys()
Return a list of option names for the given section name.
Return a list of option names for the given section name.
[ "Return", "a", "list", "of", "option", "names", "for", "the", "given", "section", "name", "." ]
def options(self, section): """Return a list of option names for the given section name.""" try: opts = self._sections[section].copy() except KeyError: raise NoSectionError(section) opts.update(self._defaults) if '__name__' in opts: del opts['__name__'] return opts.keys()
[ "def", "options", "(", "self", ",", "section", ")", ":", "try", ":", "opts", "=", "self", ".", "_sections", "[", "section", "]", ".", "copy", "(", ")", "except", "KeyError", ":", "raise", "NoSectionError", "(", "section", ")", "opts", ".", "update", ...
https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/ConfigParser.py#L274-L283
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pywin/Lib/SocketServer.py
python
TCPServer.server_close
(self)
Called to clean-up the server. May be overridden.
Called to clean-up the server.
[ "Called", "to", "clean", "-", "up", "the", "server", "." ]
def server_close(self): """Called to clean-up the server. May be overridden. """ self.socket.close()
[ "def", "server_close", "(", "self", ")", ":", "self", ".", "socket", ".", "close", "(", ")" ]
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/SocketServer.py#L442-L448
Franck-Dernoncourt/NeuroNER
3817feaf290c1f6e03ae23ea964e68c88d0e7a88
neuroner/train.py
python
prediction_step
(sess, dataset, dataset_type, model, transition_params_trained, stats_graph_folder, epoch_number, parameters, dataset_filepaths)
return all_predictions, all_y_true, output_filepath
Predict.
Predict.
[ "Predict", "." ]
def prediction_step(sess, dataset, dataset_type, model, transition_params_trained, stats_graph_folder, epoch_number, parameters, dataset_filepaths): """ Predict. """ if dataset_type == 'deploy': print('Predict labels for the {0} set'.format(dataset_type)) else: print('Evaluate model on the {0} set'.format(dataset_type)) all_predictions = [] all_y_true = [] output_filepath = os.path.join(stats_graph_folder, '{1:03d}_{0}.txt'.format(dataset_type, epoch_number)) output_file = codecs.open(output_filepath, 'w', 'UTF-8') original_conll_file = codecs.open(dataset_filepaths[dataset_type], 'r', 'UTF-8') for i in range(len(dataset.token_indices[dataset_type])): feed_dict = { model.input_token_indices: dataset.token_indices[dataset_type][i], model.input_token_character_indices: dataset.character_indices_padded[dataset_type][i], model.input_token_lengths: dataset.token_lengths[dataset_type][i], model.input_label_indices_vector: dataset.label_vector_indices[dataset_type][i], model.dropout_keep_prob: 1. } unary_scores, predictions = sess.run([model.unary_scores, model.predictions], feed_dict) if parameters['use_crf']: predictions, _ = tf.contrib.crf.viterbi_decode(unary_scores, transition_params_trained) predictions = predictions[1:-1] else: predictions = predictions.tolist() assert(len(predictions) == len(dataset.tokens[dataset_type][i])) output_string = '' prediction_labels = [dataset.index_to_label[prediction] for prediction in predictions] unary_score_list = unary_scores.tolist()[1:-1] gold_labels = dataset.labels[dataset_type][i] if parameters['tagging_format'] == 'bioes': prediction_labels = utils_nlp.bioes_to_bio(prediction_labels) gold_labels = utils_nlp.bioes_to_bio(gold_labels) for prediction, token, gold_label, scores in zip(prediction_labels, dataset.tokens[dataset_type][i], gold_labels, unary_score_list): while True: line = original_conll_file.readline() split_line = line.strip().split(' ') if '-DOCSTART-' in split_line[0] or len(split_line) == 0 \ or len(split_line[0]) == 0: continue else: token_original = split_line[0] if parameters['tagging_format'] == 'bioes': split_line.pop() gold_label_original = split_line[-1] assert(token == token_original and gold_label == gold_label_original) break split_line.append(prediction) try: if parameters['output_scores']: # space separated scores scores = ' '.join([str(i) for i in scores]) split_line.append('{}'.format(scores)) except KeyError: pass output_string += ' '.join(split_line) + '\n' output_file.write(output_string+'\n') all_predictions.extend(predictions) all_y_true.extend(dataset.label_indices[dataset_type][i]) output_file.close() original_conll_file.close() if dataset_type != 'deploy': if parameters['main_evaluation_mode'] == 'conll': # run perl evaluation script in python package # conll_evaluation_script = os.path.join('.', 'conlleval') package_name = 'neuroner' root_dir = os.path.dirname(pkg_resources.resource_filename(package_name, '__init__.py')) conll_evaluation_script = os.path.join(root_dir, 'conlleval') conll_output_filepath = '{0}_conll_evaluation.txt'.format(output_filepath) shell_command = 'perl {0} < {1} > {2}'.format(conll_evaluation_script, output_filepath, conll_output_filepath) os.system(shell_command) with open(conll_output_filepath, 'r') as f: classification_report = f.read() print(classification_report) else: new_y_pred, new_y_true, new_label_indices, new_label_names, _, _ = remap_labels(all_predictions, all_y_true, dataset, parameters['main_evaluation_mode']) print(sklearn.metrics.classification_report(new_y_true, new_y_pred, digits=4, labels=new_label_indices, target_names=new_label_names)) return all_predictions, all_y_true, output_filepath
[ "def", "prediction_step", "(", "sess", ",", "dataset", ",", "dataset_type", ",", "model", ",", "transition_params_trained", ",", "stats_graph_folder", ",", "epoch_number", ",", "parameters", ",", "dataset_filepaths", ")", ":", "if", "dataset_type", "==", "'deploy'",...
https://github.com/Franck-Dernoncourt/NeuroNER/blob/3817feaf290c1f6e03ae23ea964e68c88d0e7a88/neuroner/train.py#L41-L156
RasaHQ/rasa
54823b68c1297849ba7ae841a4246193cd1223a1
rasa/engine/training/hooks.py
python
TrainingHook.on_before_node
( self, node_name: Text, execution_context: ExecutionContext, config: Dict[Text, Any], received_inputs: Dict[Text, Any], )
return {"fingerprint_key": fingerprint_key}
Calculates the run fingerprint for use in `on_after_node`.
Calculates the run fingerprint for use in `on_after_node`.
[ "Calculates", "the", "run", "fingerprint", "for", "use", "in", "on_after_node", "." ]
def on_before_node( self, node_name: Text, execution_context: ExecutionContext, config: Dict[Text, Any], received_inputs: Dict[Text, Any], ) -> Dict: """Calculates the run fingerprint for use in `on_after_node`.""" graph_component_class = self._get_graph_component_class( execution_context, node_name ) fingerprint_key = fingerprinting.calculate_fingerprint_key( graph_component_class=graph_component_class, config=config, inputs=received_inputs, ) return {"fingerprint_key": fingerprint_key}
[ "def", "on_before_node", "(", "self", ",", "node_name", ":", "Text", ",", "execution_context", ":", "ExecutionContext", ",", "config", ":", "Dict", "[", "Text", ",", "Any", "]", ",", "received_inputs", ":", "Dict", "[", "Text", ",", "Any", "]", ",", ")",...
https://github.com/RasaHQ/rasa/blob/54823b68c1297849ba7ae841a4246193cd1223a1/rasa/engine/training/hooks.py#L34-L52
ianmiell/shutit
ef724e1ed4dcc544e594200e0b6cdfa53d04a95f
shutit.py
python
create_session
(docker_image=None, docker_rm=None, echo=False, loglevel='', nocolor=False, session_type='bash', vagrant_session_name=None, vagrant_image='ubuntu/xenial64', vagrant_gui=False, vagrant_memory='1024', vagrant_num_machines='1', vagrant_provider='virtualbox', vagrant_root_folder=None, vagrant_swapsize='2G', vagrant_version='1.8.6', vagrant_virt_method='virtualbox', vagrant_cpu='1', video=-1, walkthrough=False)
Creates a distinct ShutIt session. Sessions can be of type: bash - a bash shell is spawned and vagrant - a Vagrantfile is created and 'vagrant up'ped
Creates a distinct ShutIt session. Sessions can be of type:
[ "Creates", "a", "distinct", "ShutIt", "session", ".", "Sessions", "can", "be", "of", "type", ":" ]
def create_session(docker_image=None, docker_rm=None, echo=False, loglevel='', nocolor=False, session_type='bash', vagrant_session_name=None, vagrant_image='ubuntu/xenial64', vagrant_gui=False, vagrant_memory='1024', vagrant_num_machines='1', vagrant_provider='virtualbox', vagrant_root_folder=None, vagrant_swapsize='2G', vagrant_version='1.8.6', vagrant_virt_method='virtualbox', vagrant_cpu='1', video=-1, walkthrough=False): """Creates a distinct ShutIt session. Sessions can be of type: bash - a bash shell is spawned and vagrant - a Vagrantfile is created and 'vagrant up'ped """ assert session_type in ('bash','docker','vagrant'), shutit_util.print_debug() shutit_global_object = shutit_global.shutit_global_object if video != -1 and video > 0: walkthrough = True if session_type in ('bash','docker'): return shutit_global_object.create_session(session_type, docker_image=docker_image, rm=docker_rm, echo=echo, walkthrough=walkthrough, walkthrough_wait=video, nocolor=nocolor, loglevel=loglevel) elif session_type == 'vagrant': if vagrant_session_name is None: vagrant_session_name = 'shutit' + shutit_util.random_id() if isinstance(vagrant_num_machines, int): vagrant_num_machines = str(vagrant_num_machines) assert isinstance(vagrant_num_machines, str) assert isinstance(int(vagrant_num_machines), int) if vagrant_root_folder is None: vagrant_root_folder = shutit_global.shutit_global_object.owd return create_session_vagrant(vagrant_session_name, vagrant_num_machines, vagrant_image, vagrant_provider, vagrant_gui, vagrant_memory, vagrant_swapsize, echo, walkthrough, nocolor, video, vagrant_version, vagrant_virt_method, vagrant_root_folder, vagrant_cpu, loglevel)
[ "def", "create_session", "(", "docker_image", "=", "None", ",", "docker_rm", "=", "None", ",", "echo", "=", "False", ",", "loglevel", "=", "''", ",", "nocolor", "=", "False", ",", "session_type", "=", "'bash'", ",", "vagrant_session_name", "=", "None", ","...
https://github.com/ianmiell/shutit/blob/ef724e1ed4dcc544e594200e0b6cdfa53d04a95f/shutit.py#L33-L94
ncoudray/DeepPATH
62bf7e7f74a80889f1e07890b8fe814f076f780d
DeepPATH_code/01_training/xClasses/inception/data/nc_build_imagenet_data.py
python
_process_image
(filename, coder)
return image_data, height, width
Process a single image file. Args: filename: string, path to an image file e.g., '/path/to/example.JPG'. coder: instance of ImageCoder to provide TensorFlow image coding utils. Returns: image_buffer: string, JPEG encoding of RGB image. height: integer, image height in pixels. width: integer, image width in pixels.
Process a single image file.
[ "Process", "a", "single", "image", "file", "." ]
def _process_image(filename, coder): """Process a single image file. Args: filename: string, path to an image file e.g., '/path/to/example.JPG'. coder: instance of ImageCoder to provide TensorFlow image coding utils. Returns: image_buffer: string, JPEG encoding of RGB image. height: integer, image height in pixels. width: integer, image width in pixels. """ # Read the image file. with tf.gfile.FastGFile(filename, 'r') as f: image_data = f.read() # Clean the dirty data. if _is_png(filename): # 1 image is a PNG. print('Converting PNG to JPEG for %s' % filename) image_data = coder.png_to_jpeg(image_data) elif _is_cmyk(filename): # 22 JPEG images are in CMYK colorspace. print('Converting CMYK to RGB for %s' % filename) image_data = coder.cmyk_to_rgb(image_data) # Decode the RGB JPEG. image = coder.decode_jpeg(image_data) # Check that image converted to RGB assert len(image.shape) == 3 height = image.shape[0] width = image.shape[1] assert image.shape[2] == 3 return image_data, height, width
[ "def", "_process_image", "(", "filename", ",", "coder", ")", ":", "# Read the image file.", "with", "tf", ".", "gfile", ".", "FastGFile", "(", "filename", ",", "'r'", ")", "as", "f", ":", "image_data", "=", "f", ".", "read", "(", ")", "# Clean the dirty da...
https://github.com/ncoudray/DeepPATH/blob/62bf7e7f74a80889f1e07890b8fe814f076f780d/DeepPATH_code/01_training/xClasses/inception/data/nc_build_imagenet_data.py#L303-L337
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/paramiko/client.py
python
SSHClient.open_sftp
(self)
return self._transport.open_sftp_client()
Open an SFTP session on the SSH server. :return: a new `.SFTPClient` session object
Open an SFTP session on the SSH server.
[ "Open", "an", "SFTP", "session", "on", "the", "SSH", "server", "." ]
def open_sftp(self): """ Open an SFTP session on the SSH server. :return: a new `.SFTPClient` session object """ return self._transport.open_sftp_client()
[ "def", "open_sftp", "(", "self", ")", ":", "return", "self", ".", "_transport", ".", "open_sftp_client", "(", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/paramiko/client.py#L433-L439
guillermooo/Vintageous
f958207009902052aed5fcac09745f1742648604
vi/mappings.py
python
Mappings.resolve
(self, sequence=None, mode=None, check_user_mappings=True)
Looks at the current global state and returns the command mapped to the available sequence. It may be a 'missing' command. @sequence If a @sequence is passed, it is used instead of the global state's. This is necessary for some commands that aren't name spaces but act as them (for example, ys from the surround plugin). @mode If different than `None`, it will be used instead of the global state's. This is necessary when we are in operator pending mode and we receive a new action. By combining the existing action's name with name of the action just received we could find a new action. For example, this is the case of g~~.
Looks at the current global state and returns the command mapped to the available sequence. It may be a 'missing' command.
[ "Looks", "at", "the", "current", "global", "state", "and", "returns", "the", "command", "mapped", "to", "the", "available", "sequence", ".", "It", "may", "be", "a", "missing", "command", "." ]
def resolve(self, sequence=None, mode=None, check_user_mappings=True): """ Looks at the current global state and returns the command mapped to the available sequence. It may be a 'missing' command. @sequence If a @sequence is passed, it is used instead of the global state's. This is necessary for some commands that aren't name spaces but act as them (for example, ys from the surround plugin). @mode If different than `None`, it will be used instead of the global state's. This is necessary when we are in operator pending mode and we receive a new action. By combining the existing action's name with name of the action just received we could find a new action. For example, this is the case of g~~. """ # we usually need to look at the partial sequence, but some commands do weird things, # like ys, which isn't a namespace but behaves as such sometimes. seq = sequence or self.state.partial_sequence seq = to_bare_command_name(seq) # TODO: Use same structure as in mappings (nested dicst). command = None if check_user_mappings: self.state.logger.info('[Mappings] checking user mappings') # TODO: We should be able to force a mode here too as, below. command = self.expand_first(seq) if command: self.state.logger.info('[Mappings] {0} equals command: {1}'.format(seq, command)) return command # return {'name': command.mapping, 'type': cmd_types.USER} else: self.state.logger.info('[Mappings] looking up >{0}<'.format(seq)) command = seq_to_command(self.state, seq, mode=mode) self.state.logger.info('[Mappings] got {0}'.format(command)) return command
[ "def", "resolve", "(", "self", ",", "sequence", "=", "None", ",", "mode", "=", "None", ",", "check_user_mappings", "=", "True", ")", ":", "# we usually need to look at the partial sequence, but some commands do weird things,", "# like ys, which isn't a namespace but behaves as ...
https://github.com/guillermooo/Vintageous/blob/f958207009902052aed5fcac09745f1742648604/vi/mappings.py#L110-L148
yandex/yandex-tank
b41bcc04396c4ed46fc8b28a261197320854fd33
yandextank/plugins/Autostop/cumulative_criterions.py
python
TotalNetCodesCriterion.__init__
(self, autostop, param_str)
[]
def __init__(self, autostop, param_str): AbstractCriterion.__init__(self) self.seconds_count = 0 params = param_str.split(',') self.codes_mask = params[0].lower() self.codes_regex = re.compile(self.codes_mask.replace("x", '.')) self.autostop = autostop self.data = deque() self.second_window = deque() level_str = params[1].strip() if level_str[-1:] == '%': self.level = float(level_str[:-1]) self.is_relative = True else: self.level = int(level_str) self.is_relative = False self.seconds_limit = expand_to_seconds(params[2]) self.tag = params[3].strip() if len(params) == 4 else None
[ "def", "__init__", "(", "self", ",", "autostop", ",", "param_str", ")", ":", "AbstractCriterion", ".", "__init__", "(", "self", ")", "self", ".", "seconds_count", "=", "0", "params", "=", "param_str", ".", "split", "(", "','", ")", "self", ".", "codes_ma...
https://github.com/yandex/yandex-tank/blob/b41bcc04396c4ed46fc8b28a261197320854fd33/yandextank/plugins/Autostop/cumulative_criterions.py#L245-L263
google-research/motion_imitation
d0e7b963c5a301984352d25a3ee0820266fa4218
mpc_controller/static_gait_controller.py
python
StaticGaitController.__init__
(self, robot)
[]
def __init__(self, robot): self._robot = robot self._toe_ids = tuple(robot.urdf_loader.get_end_effector_id_dict().values()) self._wait_count = 0 self._stepper = foot_stepper.FootStepper(self._robot.pybullet_client, self._toe_ids, toe_pos_local_ref)
[ "def", "__init__", "(", "self", ",", "robot", ")", ":", "self", ".", "_robot", "=", "robot", "self", ".", "_toe_ids", "=", "tuple", "(", "robot", ".", "urdf_loader", ".", "get_end_effector_id_dict", "(", ")", ".", "values", "(", ")", ")", "self", ".", ...
https://github.com/google-research/motion_imitation/blob/d0e7b963c5a301984352d25a3ee0820266fa4218/mpc_controller/static_gait_controller.py#L24-L29
aws-samples/aws-cdk-examples
4ac65cc171044d1f6dbb8b131c77abb44014d6c6
csharp/elasticbeanstalk/elasticbeanstalk-bg-pipeline/resources/blue_green.py
python
put_job_failure
(job, message)
Notify CodePipeline of a failed job Args: job: The CodePipeline job ID message: A message to be logged relating to the job status Raises: Exception: Any exception thrown by .put_job_failure_result()
Notify CodePipeline of a failed job Args: job: The CodePipeline job ID message: A message to be logged relating to the job status Raises: Exception: Any exception thrown by .put_job_failure_result()
[ "Notify", "CodePipeline", "of", "a", "failed", "job", "Args", ":", "job", ":", "The", "CodePipeline", "job", "ID", "message", ":", "A", "message", "to", "be", "logged", "relating", "to", "the", "job", "status", "Raises", ":", "Exception", ":", "Any", "ex...
def put_job_failure(job, message): """Notify CodePipeline of a failed job Args: job: The CodePipeline job ID message: A message to be logged relating to the job status Raises: Exception: Any exception thrown by .put_job_failure_result() """ print('Putting job failure') print(message) code_pipeline.put_job_failure_result(jobId=job, failureDetails={'message': message, 'type': 'JobFailed'})
[ "def", "put_job_failure", "(", "job", ",", "message", ")", ":", "print", "(", "'Putting job failure'", ")", "print", "(", "message", ")", "code_pipeline", ".", "put_job_failure_result", "(", "jobId", "=", "job", ",", "failureDetails", "=", "{", "'message'", ":...
https://github.com/aws-samples/aws-cdk-examples/blob/4ac65cc171044d1f6dbb8b131c77abb44014d6c6/csharp/elasticbeanstalk/elasticbeanstalk-bg-pipeline/resources/blue_green.py#L30-L40
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/gdata/docs/data.py
python
Resource.get_resumable_edit_media_link
(self)
return self.get_link(RESUMABLE_EDIT_MEDIA_LINK_REL)
Extracts the Resource's resumable update link. Returns: A gdata.data.FeedLink object.
Extracts the Resource's resumable update link.
[ "Extracts", "the", "Resource", "s", "resumable", "update", "link", "." ]
def get_resumable_edit_media_link(self): """Extracts the Resource's resumable update link. Returns: A gdata.data.FeedLink object. """ return self.get_link(RESUMABLE_EDIT_MEDIA_LINK_REL)
[ "def", "get_resumable_edit_media_link", "(", "self", ")", ":", "return", "self", ".", "get_link", "(", "RESUMABLE_EDIT_MEDIA_LINK_REL", ")" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/gdata/docs/data.py#L457-L463
miyosuda/unreal
31d4886149412fa248f6efa490ab65bd2f425cde
model/model.py
python
conv_initializer
(kernel_width, kernel_height, input_channels, dtype=tf.float32)
return _initializer
[]
def conv_initializer(kernel_width, kernel_height, input_channels, dtype=tf.float32): def _initializer(shape, dtype=dtype, partition_info=None): d = 1.0 / np.sqrt(input_channels * kernel_width * kernel_height) return tf.random_uniform(shape, minval=-d, maxval=d) return _initializer
[ "def", "conv_initializer", "(", "kernel_width", ",", "kernel_height", ",", "input_channels", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "def", "_initializer", "(", "shape", ",", "dtype", "=", "dtype", ",", "partition_info", "=", "None", ")", ":", "...
https://github.com/miyosuda/unreal/blob/31d4886149412fa248f6efa490ab65bd2f425cde/model/model.py#L19-L23
radlab/sparrow
afb8efadeb88524f1394d1abe4ea66c6fd2ac744
deploy/third_party/boto-2.1.1/boto/gs/resumable_upload_handler.py
python
ResumableUploadHandler._check_final_md5
(self, key, etag)
Checks that etag from server agrees with md5 computed before upload. This is important, since the upload could have spanned a number of hours and multiple processes (e.g., gsutil runs), and the user could change some of the file and not realize they have inconsistent data.
Checks that etag from server agrees with md5 computed before upload. This is important, since the upload could have spanned a number of hours and multiple processes (e.g., gsutil runs), and the user could change some of the file and not realize they have inconsistent data.
[ "Checks", "that", "etag", "from", "server", "agrees", "with", "md5", "computed", "before", "upload", ".", "This", "is", "important", "since", "the", "upload", "could", "have", "spanned", "a", "number", "of", "hours", "and", "multiple", "processes", "(", "e",...
def _check_final_md5(self, key, etag): """ Checks that etag from server agrees with md5 computed before upload. This is important, since the upload could have spanned a number of hours and multiple processes (e.g., gsutil runs), and the user could change some of the file and not realize they have inconsistent data. """ if key.bucket.connection.debug >= 1: print 'Checking md5 against etag.' if key.md5 != etag.strip('"\''): # Call key.open_read() before attempting to delete the # (incorrect-content) key, so we perform that request on a # different HTTP connection. This is neededb because httplib # will return a "Response not ready" error if you try to perform # a second transaction on the connection. key.open_read() key.close() key.delete() raise ResumableUploadException( 'File changed during upload: md5 signature doesn\'t match etag ' '(incorrect uploaded object deleted)', ResumableTransferDisposition.ABORT)
[ "def", "_check_final_md5", "(", "self", ",", "key", ",", "etag", ")", ":", "if", "key", ".", "bucket", ".", "connection", ".", "debug", ">=", "1", ":", "print", "'Checking md5 against etag.'", "if", "key", ".", "md5", "!=", "etag", ".", "strip", "(", "...
https://github.com/radlab/sparrow/blob/afb8efadeb88524f1394d1abe4ea66c6fd2ac744/deploy/third_party/boto-2.1.1/boto/gs/resumable_upload_handler.py#L453-L474
mrlesmithjr/Ansible
d44f0dc0d942bdf3bf7334b307e6048f0ee16e36
roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/setuptools/config.py
python
ConfigMetadataHandler._parse_version
(self, value)
return version
Parses `version` option value. :param value: :rtype: str
Parses `version` option value.
[ "Parses", "version", "option", "value", "." ]
def _parse_version(self, value): """Parses `version` option value. :param value: :rtype: str """ version = self._parse_attr(value) if callable(version): version = version() if not isinstance(version, string_types): if hasattr(version, '__iter__'): version = '.'.join(map(str, version)) else: version = '%s' % version return version
[ "def", "_parse_version", "(", "self", ",", "value", ")", ":", "version", "=", "self", ".", "_parse_attr", "(", "value", ")", "if", "callable", "(", "version", ")", ":", "version", "=", "version", "(", ")", "if", "not", "isinstance", "(", "version", ","...
https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/setuptools/config.py#L421-L439
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/contour/_colorbar.py
python
ColorBar.tickprefix
(self)
return self["tickprefix"]
Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string
[ "Sets", "a", "tick", "label", "prefix", ".", "The", "tickprefix", "property", "is", "a", "string", "and", "must", "be", "specified", "as", ":", "-", "A", "string", "-", "A", "number", "that", "will", "be", "converted", "to", "a", "string" ]
def tickprefix(self): """ Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickprefix"]
[ "def", "tickprefix", "(", "self", ")", ":", "return", "self", "[", "\"tickprefix\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/contour/_colorbar.py#L975-L987
idiap/importance-sampling
9c9cab2ac91081ae2b64f99891504155057c09e3
scripts/variance_reduction.py
python
build_grad_batched
(network, batch_size)
return inner
Compute the average gradient by splitting the inputs in batches of size 'batch_size' and averaging.
Compute the average gradient by splitting the inputs in batches of size 'batch_size' and averaging.
[ "Compute", "the", "average", "gradient", "by", "splitting", "the", "inputs", "in", "batches", "of", "size", "batch_size", "and", "averaging", "." ]
def build_grad_batched(network, batch_size): """Compute the average gradient by splitting the inputs in batches of size 'batch_size' and averaging.""" grad = build_grad(network) def inner(inputs): X, y, w = inputs N = len(X) g = 0 for i in range(0, N, batch_size): g = g + w[i:i+batch_size].sum() * grad([ X[i:i+batch_size], y[i:i+batch_size], w[i:i+batch_size] ])[0] return [g / w.sum()] return inner
[ "def", "build_grad_batched", "(", "network", ",", "batch_size", ")", ":", "grad", "=", "build_grad", "(", "network", ")", "def", "inner", "(", "inputs", ")", ":", "X", ",", "y", ",", "w", "=", "inputs", "N", "=", "len", "(", "X", ")", "g", "=", "...
https://github.com/idiap/importance-sampling/blob/9c9cab2ac91081ae2b64f99891504155057c09e3/scripts/variance_reduction.py#L46-L62
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/elasticsearch.py
python
pipeline_get
(id, hosts=None, profile=None)
.. versionadded:: 2017.7.0 Retrieve Ingest pipeline definition. Available since Elasticsearch 5.0. id Pipeline id CLI Example: .. code-block:: bash salt myminion elasticsearch.pipeline_get mypipeline
.. versionadded:: 2017.7.0
[ "..", "versionadded", "::", "2017", ".", "7", ".", "0" ]
def pipeline_get(id, hosts=None, profile=None): """ .. versionadded:: 2017.7.0 Retrieve Ingest pipeline definition. Available since Elasticsearch 5.0. id Pipeline id CLI Example: .. code-block:: bash salt myminion elasticsearch.pipeline_get mypipeline """ es = _get_instance(hosts, profile) try: return es.ingest.get_pipeline(id=id) except elasticsearch.NotFoundError: return None except elasticsearch.TransportError as e: raise CommandExecutionError( "Cannot create pipeline {}, server returned code {} with message {}".format( id, e.status_code, e.error ) ) except AttributeError: raise CommandExecutionError("Method is applicable only for Elasticsearch 5.0+")
[ "def", "pipeline_get", "(", "id", ",", "hosts", "=", "None", ",", "profile", "=", "None", ")", ":", "es", "=", "_get_instance", "(", "hosts", ",", "profile", ")", "try", ":", "return", "es", ".", "ingest", ".", "get_pipeline", "(", "id", "=", "id", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/elasticsearch.py#L1185-L1213
iyah4888/SIGGRAPH18SSS
8bb634316a1234f639cf4e6d26c671cc43491d48
kaffe/graph.py
python
GraphBuilder.load
(self)
Load the layer definitions from the prototxt.
Load the layer definitions from the prototxt.
[ "Load", "the", "layer", "definitions", "from", "the", "prototxt", "." ]
def load(self): '''Load the layer definitions from the prototxt.''' self.params = get_caffe_resolver().NetParameter() with open(self.def_path, 'rb') as def_file: text_format.Merge(def_file.read(), self.params)
[ "def", "load", "(", "self", ")", ":", "self", ".", "params", "=", "get_caffe_resolver", "(", ")", ".", "NetParameter", "(", ")", "with", "open", "(", "self", ".", "def_path", ",", "'rb'", ")", "as", "def_file", ":", "text_format", ".", "Merge", "(", ...
https://github.com/iyah4888/SIGGRAPH18SSS/blob/8bb634316a1234f639cf4e6d26c671cc43491d48/kaffe/graph.py#L142-L146
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/_vendor/ipaddress.py
python
IPv6Address.teredo
(self)
return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF))
Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32)
Tuple of embedded teredo IPs.
[ "Tuple", "of", "embedded", "teredo", "IPs", "." ]
def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF))
[ "def", "teredo", "(", "self", ")", ":", "if", "(", "self", ".", "_ip", ">>", "96", ")", "!=", "0x20010000", ":", "return", "None", "return", "(", "IPv4Address", "(", "(", "self", ".", "_ip", ">>", "64", ")", "&", "0xFFFFFFFF", ")", ",", "IPv4Addres...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/ipaddress.py#L2155-L2167
quip/quip-api
19f3b32a05ed092a70dc2c616e214aaff8a06de2
samples/twitterbot/quip.py
python
QuipClient.get_users
(self, ids)
return self._fetch_json("users/", post_data={"ids": ",".join(ids)})
Returns a dictionary of users for the given IDs.
Returns a dictionary of users for the given IDs.
[ "Returns", "a", "dictionary", "of", "users", "for", "the", "given", "IDs", "." ]
def get_users(self, ids): """Returns a dictionary of users for the given IDs.""" return self._fetch_json("users/", post_data={"ids": ",".join(ids)})
[ "def", "get_users", "(", "self", ",", "ids", ")", ":", "return", "self", ".", "_fetch_json", "(", "\"users/\"", ",", "post_data", "=", "{", "\"ids\"", ":", "\",\"", ".", "join", "(", "ids", ")", "}", ")" ]
https://github.com/quip/quip-api/blob/19f3b32a05ed092a70dc2c616e214aaff8a06de2/samples/twitterbot/quip.py#L168-L170
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/voiper/sulley/impacket/dcerpc/dcerpc.py
python
MSRPCBindAck.get_header_size
(self)
return self._SIZE + var_size
[]
def get_header_size(self): var_size = len(self.get_bytes()) - self._SIZE # assert var_size > 0 return self._SIZE + var_size
[ "def", "get_header_size", "(", "self", ")", ":", "var_size", "=", "len", "(", "self", ".", "get_bytes", "(", ")", ")", "-", "self", ".", "_SIZE", "# assert var_size > 0", "return", "self", ".", "_SIZE", "+", "var_size" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/voiper/sulley/impacket/dcerpc/dcerpc.py#L540-L543
kerlomz/captcha_platform
f7d719bd1239a987996e266bd7fe35c96003b378
config.py
python
Model.model_conf
(self)
[]
def model_conf(self) -> dict: with open(self.model_conf_path, 'r', encoding="utf-8") as sys_fp: sys_stream = sys_fp.read() return yaml.load(sys_stream, Loader=yaml.SafeLoader)
[ "def", "model_conf", "(", "self", ")", "->", "dict", ":", "with", "open", "(", "self", ".", "model_conf_path", ",", "'r'", ",", "encoding", "=", "\"utf-8\"", ")", "as", "sys_fp", ":", "sys_stream", "=", "sys_fp", ".", "read", "(", ")", "return", "yaml"...
https://github.com/kerlomz/captcha_platform/blob/f7d719bd1239a987996e266bd7fe35c96003b378/config.py#L249-L252
renemarc/home-assistant-config
775d60ad436cd0f432d2260e503b530920041165
custom_components/hacs/hacsbase/__init__.py
python
Hacs.prosess_queue
(self, notarealarg=None)
Recuring tasks for installed repositories.
Recuring tasks for installed repositories.
[ "Recuring", "tasks", "for", "installed", "repositories", "." ]
async def prosess_queue(self, notarealarg=None): """Recuring tasks for installed repositories.""" if not self.queue.has_pending_tasks: self.logger.debug("Nothing in the queue") return if self.queue.running: self.logger.debug("Queue is already running") return can_update = await get_fetch_updates_for(self.github) if can_update == 0: self.logger.info( "HACS is ratelimited, repository updates will resume later." ) else: self.system.status.background_task = True self.hass.bus.async_fire("hacs/status", {}) await self.queue.execute(can_update) self.system.status.background_task = False self.hass.bus.async_fire("hacs/status", {})
[ "async", "def", "prosess_queue", "(", "self", ",", "notarealarg", "=", "None", ")", ":", "if", "not", "self", ".", "queue", ".", "has_pending_tasks", ":", "self", ".", "logger", ".", "debug", "(", "\"Nothing in the queue\"", ")", "return", "if", "self", "....
https://github.com/renemarc/home-assistant-config/blob/775d60ad436cd0f432d2260e503b530920041165/custom_components/hacs/hacsbase/__init__.py#L264-L283
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/grades/course_grade.py
python
CourseGrade._compute_percent
(grader_result)
return round_away_from_zero(grader_result['percent'] * 100 + 0.05) / 100
Computes and returns the grade percentage from the given result from the grader.
Computes and returns the grade percentage from the given result from the grader.
[ "Computes", "and", "returns", "the", "grade", "percentage", "from", "the", "given", "result", "from", "the", "grader", "." ]
def _compute_percent(grader_result): """ Computes and returns the grade percentage from the given result from the grader. """ # Confused about the addition of .05 here? See https://openedx.atlassian.net/browse/TNL-6972 return round_away_from_zero(grader_result['percent'] * 100 + 0.05) / 100
[ "def", "_compute_percent", "(", "grader_result", ")", ":", "# Confused about the addition of .05 here? See https://openedx.atlassian.net/browse/TNL-6972", "return", "round_away_from_zero", "(", "grader_result", "[", "'percent'", "]", "*", "100", "+", "0.05", ")", "/", "100" ...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/grades/course_grade.py#L302-L309
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/xml/sax/xmlreader.py
python
InputSource.setByteStream
(self, bytefile)
Set the byte stream (a Python file-like object which does not perform byte-to-character conversion) for this input source. The SAX parser will ignore this if there is also a character stream specified, but it will use a byte stream in preference to opening a URI connection itself. If the application knows the character encoding of the byte stream, it should set it with the setEncoding method.
Set the byte stream (a Python file-like object which does not perform byte-to-character conversion) for this input source.
[ "Set", "the", "byte", "stream", "(", "a", "Python", "file", "-", "like", "object", "which", "does", "not", "perform", "byte", "-", "to", "-", "character", "conversion", ")", "for", "this", "input", "source", "." ]
def setByteStream(self, bytefile): """Set the byte stream (a Python file-like object which does not perform byte-to-character conversion) for this input source. The SAX parser will ignore this if there is also a character stream specified, but it will use a byte stream in preference to opening a URI connection itself. If the application knows the character encoding of the byte stream, it should set it with the setEncoding method.""" self.__bytefile = bytefile
[ "def", "setByteStream", "(", "self", ",", "bytefile", ")", ":", "self", ".", "__bytefile", "=", "bytefile" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/xml/sax/xmlreader.py#L241-L252
hyde/hyde
7f415402cc3e007a746eb2b5bc102281fdb415bd
hyde/ext/plugins/css.py
python
LessCSSPlugin.begin_text_resource
(self, resource, text)
return text
Replace @import statements with {% include %} statements.
Replace
[ "Replace" ]
def begin_text_resource(self, resource, text): """ Replace @import statements with {% include %} statements. """ if not self._should_parse_resource(resource) or \ not self._should_replace_imports(resource): return text def import_to_include(match): if not match.lastindex: return '' path = match.groups(1)[0] afile = File(resource.source_file.parent.child(path)) if len(afile.kind.strip()) == 0: afile = File(afile.path + '.less') ref = self.site.content.resource_from_path(afile.path) if not ref: raise HydeException( "Cannot import from path [%s]" % afile.path) ref.is_processable = False return self.template.get_include_statement(ref.relative_path) text = self.import_finder.sub(import_to_include, text) return text
[ "def", "begin_text_resource", "(", "self", ",", "resource", ",", "text", ")", ":", "if", "not", "self", ".", "_should_parse_resource", "(", "resource", ")", "or", "not", "self", ".", "_should_replace_imports", "(", "resource", ")", ":", "return", "text", "de...
https://github.com/hyde/hyde/blob/7f415402cc3e007a746eb2b5bc102281fdb415bd/hyde/ext/plugins/css.py#L58-L81
PowerScript/KatanaFramework
0f6ad90a88de865d58ec26941cb4460501e75496
lib/future/src/future/backports/http/cookiejar.py
python
CookieJar.clear_expired_cookies
(self)
Discard all expired cookies. You probably don't need to call this method: expired cookies are never sent back to the server (provided you're using DefaultCookiePolicy), this method is called by CookieJar itself every so often, and the .save() method won't save expired cookies anyway (unless you ask otherwise by passing a true ignore_expires argument).
Discard all expired cookies.
[ "Discard", "all", "expired", "cookies", "." ]
def clear_expired_cookies(self): """Discard all expired cookies. You probably don't need to call this method: expired cookies are never sent back to the server (provided you're using DefaultCookiePolicy), this method is called by CookieJar itself every so often, and the .save() method won't save expired cookies anyway (unless you ask otherwise by passing a true ignore_expires argument). """ self._cookies_lock.acquire() try: now = time.time() for cookie in self: if cookie.is_expired(now): self.clear(cookie.domain, cookie.path, cookie.name) finally: self._cookies_lock.release()
[ "def", "clear_expired_cookies", "(", "self", ")", ":", "self", ".", "_cookies_lock", ".", "acquire", "(", ")", "try", ":", "now", "=", "time", ".", "time", "(", ")", "for", "cookie", "in", "self", ":", "if", "cookie", ".", "is_expired", "(", "now", "...
https://github.com/PowerScript/KatanaFramework/blob/0f6ad90a88de865d58ec26941cb4460501e75496/lib/future/src/future/backports/http/cookiejar.py#L1712-L1729
mongodb/mongo-python-driver
c760f900f2e4109a247c2ffc8ad3549362007772
pymongo/pool.py
python
Pool.connect
(self)
return sock_info
Connect to Mongo and return a new SocketInfo. Can raise ConnectionFailure. Note that the pool does not keep a reference to the socket -- you must call return_socket() when you're done with it.
Connect to Mongo and return a new SocketInfo.
[ "Connect", "to", "Mongo", "and", "return", "a", "new", "SocketInfo", "." ]
def connect(self): """Connect to Mongo and return a new SocketInfo. Can raise ConnectionFailure. Note that the pool does not keep a reference to the socket -- you must call return_socket() when you're done with it. """ with self.lock: conn_id = self.next_connection_id self.next_connection_id += 1 listeners = self.opts._event_listeners if self.enabled_for_cmap: listeners.publish_connection_created(self.address, conn_id) try: sock = _configured_socket(self.address, self.opts) except BaseException as error: if self.enabled_for_cmap: listeners.publish_connection_closed( self.address, conn_id, ConnectionClosedReason.ERROR) if isinstance(error, (IOError, OSError, _SSLError)): _raise_connection_failure(self.address, error) raise sock_info = SocketInfo(sock, self, self.address, conn_id) try: if self.handshake: sock_info.hello() self.is_writable = sock_info.is_writable sock_info.authenticate() except BaseException: sock_info.close_socket(ConnectionClosedReason.ERROR) raise return sock_info
[ "def", "connect", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "conn_id", "=", "self", ".", "next_connection_id", "self", ".", "next_connection_id", "+=", "1", "listeners", "=", "self", ".", "opts", ".", "_event_listeners", "if", "self", ".", ...
https://github.com/mongodb/mongo-python-driver/blob/c760f900f2e4109a247c2ffc8ad3549362007772/pymongo/pool.py#L1273-L1312
my8100/scrapydweb
7a3b81dba2cba4279c9465064a693bb277ac20e9
scrapydweb/views/operations/deploy.py
python
DeployUploadView.search_scrapy_cfg_path
(self, search_path, func_walk=os.walk, retry=True)
[]
def search_scrapy_cfg_path(self, search_path, func_walk=os.walk, retry=True): try: for dirpath, dirnames, filenames in func_walk(search_path): self.scrapy_cfg_searched_paths.append(os.path.abspath(dirpath)) self.scrapy_cfg_path = os.path.abspath(os.path.join(dirpath, 'scrapy.cfg')) if os.path.exists(self.scrapy_cfg_path): self.logger.debug("scrapy_cfg_path: %s", self.scrapy_cfg_path) return except UnicodeDecodeError: msg = "Found illegal filenames in %s" % search_path self.logger.error(msg) flash(msg, self.WARN) if PY2 and retry: self.search_scrapy_cfg_path(search_path, func_walk=self.safe_walk, retry=False) else: raise else: self.logger.error("scrapy.cfg not found in: %s", search_path) self.scrapy_cfg_path = ''
[ "def", "search_scrapy_cfg_path", "(", "self", ",", "search_path", ",", "func_walk", "=", "os", ".", "walk", ",", "retry", "=", "True", ")", ":", "try", ":", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "func_walk", "(", "search_path", ")", ...
https://github.com/my8100/scrapydweb/blob/7a3b81dba2cba4279c9465064a693bb277ac20e9/scrapydweb/views/operations/deploy.py#L390-L408
urwid/urwid
e2423b5069f51d318ea1ac0f355a0efe5448f7eb
urwid/widget.py
python
Edit.position_coords
(self,maxcol,pos)
return x,y
Return (*x*, *y*) coordinates for an offset into self.edit_text.
Return (*x*, *y*) coordinates for an offset into self.edit_text.
[ "Return", "(", "*", "x", "*", "*", "y", "*", ")", "coordinates", "for", "an", "offset", "into", "self", ".", "edit_text", "." ]
def position_coords(self,maxcol,pos): """ Return (*x*, *y*) coordinates for an offset into self.edit_text. """ p = pos + len(self.caption) trans = self.get_line_translation(maxcol) x,y = calc_coords(self.get_text()[0], trans,p) return x,y
[ "def", "position_coords", "(", "self", ",", "maxcol", ",", "pos", ")", ":", "p", "=", "pos", "+", "len", "(", "self", ".", "caption", ")", "trans", "=", "self", ".", "get_line_translation", "(", "maxcol", ")", "x", ",", "y", "=", "calc_coords", "(", ...
https://github.com/urwid/urwid/blob/e2423b5069f51d318ea1ac0f355a0efe5448f7eb/urwid/widget.py#L1674-L1682
arsenetar/dupeguru
eb57d269fcc1392fac9d49eb10d597a9c66fcc82
core/exclude.py
python
ExcludeDict.error
(self, regex)
return self._excluded.get(regex).get("error")
Return the compilation error message for regex string
Return the compilation error message for regex string
[ "Return", "the", "compilation", "error", "message", "for", "regex", "string" ]
def error(self, regex): """Return the compilation error message for regex string""" return self._excluded.get(regex).get("error")
[ "def", "error", "(", "self", ",", "regex", ")", ":", "return", "self", ".", "_excluded", ".", "get", "(", "regex", ")", ".", "get", "(", "\"error\"", ")" ]
https://github.com/arsenetar/dupeguru/blob/eb57d269fcc1392fac9d49eb10d597a9c66fcc82/core/exclude.py#L425-L427
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/markdown/markdown/blockprocessors.py
python
ListIndentProcessor.create_item
(self, parent, block)
Create a new li and parse the block with it as the parent.
Create a new li and parse the block with it as the parent.
[ "Create", "a", "new", "li", "and", "parse", "the", "block", "with", "it", "as", "the", "parent", "." ]
def create_item(self, parent, block): """ Create a new li and parse the block with it as the parent. """ li = markdown.etree.SubElement(parent, 'li') self.parser.parseBlocks(li, [block])
[ "def", "create_item", "(", "self", ",", "parent", ",", "block", ")", ":", "li", "=", "markdown", ".", "etree", ".", "SubElement", "(", "parent", ",", "'li'", ")", "self", ".", "parser", ".", "parseBlocks", "(", "li", ",", "[", "block", "]", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/markdown/markdown/blockprocessors.py#L153-L156
websauna/websauna
a57de54fb8a3fae859f24f373f0292e1e4b3c344
websauna/system/model/retry.py
python
retryable
(tm: t.Optional[TransactionManager] = None, get_tm: t.Optional[t.Callable] = None)
return _transaction_retry_wrapper
Function decorator for§ SQL Serialized transaction conflict resolution through retries. You need to give either ``tm`` or ``get_tm`` argument. * New transaction is started when entering the decorated function * If there is already a transaction in progress when entering the decorated function raise an error * Commit when existing the decorated function * If the commit fails due to a SQL serialization conflict then try to rerun the decorated function max ``tm.retry_attempt_count`` times. Usually this is configured in TODO. Example: .. code-block:: python from websauna.system.model.retry import retryable def deposit_eth(web3: Web3, dbsession: Session, opid: UUID): @retryable(tm=dbsession.transaction_manager) def perform_tx(): op = dbsession.query(CryptoOperation).get(opid) op.mark_performed() op.mark_broadcasted() # Transaction confirmation count updater will make sure we have enough blocks, # and then will call mark_completed() perform_tx() Example using class based transaction manager resolver: .. code-block:: python from websauna.system.model.retry import retryable class OperationQueueManager: def __init__(self, web3: Web3, dbsession: Session, asset_network_id, registry: Registry): assert isinstance(registry, Registry) assert isinstance(asset_network_id, UUID) self.web3 = web3 self.dbsession = dbsession self.asset_network_id = asset_network_id self.registry = registry self.tm = self.dbsession.transaction_manager def _get_tm(*args, **kargs): self = args[0] return self.tm @retryable(get_tm=_get_tm) def get_waiting_operation_ids(self) -> List[Tuple[UUID, CryptoOperationType]]: wait_list = self.dbsession.query(CryptoOperation, CryptoOperation.id, CryptoOperation.state, CryptoOperation.operation_type).filter_by(network_id=self.asset_network_id, state=CryptoOperationState.waiting) # Flatten wait_list = [(o.id, o.operation_type) for o in wait_list] return wait_list def run_waiting_operations(self): # Performed inside TX retry boundary ops = self.get_waiting_operation_ids() Transaction manager needs ``retry_attempt_count`` attribute set by Websauna framework. :param tm: Transaction manager used to control the TX execution :param get_tm: Factory function that is called with ``args`` and ``kwargs`` to get the transaction manager
Function decorator for§ SQL Serialized transaction conflict resolution through retries.
[ "Function", "decorator", "for§", "SQL", "Serialized", "transaction", "conflict", "resolution", "through", "retries", "." ]
def retryable(tm: t.Optional[TransactionManager] = None, get_tm: t.Optional[t.Callable] = None): """Function decorator for§ SQL Serialized transaction conflict resolution through retries. You need to give either ``tm`` or ``get_tm`` argument. * New transaction is started when entering the decorated function * If there is already a transaction in progress when entering the decorated function raise an error * Commit when existing the decorated function * If the commit fails due to a SQL serialization conflict then try to rerun the decorated function max ``tm.retry_attempt_count`` times. Usually this is configured in TODO. Example: .. code-block:: python from websauna.system.model.retry import retryable def deposit_eth(web3: Web3, dbsession: Session, opid: UUID): @retryable(tm=dbsession.transaction_manager) def perform_tx(): op = dbsession.query(CryptoOperation).get(opid) op.mark_performed() op.mark_broadcasted() # Transaction confirmation count updater will make sure we have enough blocks, # and then will call mark_completed() perform_tx() Example using class based transaction manager resolver: .. code-block:: python from websauna.system.model.retry import retryable class OperationQueueManager: def __init__(self, web3: Web3, dbsession: Session, asset_network_id, registry: Registry): assert isinstance(registry, Registry) assert isinstance(asset_network_id, UUID) self.web3 = web3 self.dbsession = dbsession self.asset_network_id = asset_network_id self.registry = registry self.tm = self.dbsession.transaction_manager def _get_tm(*args, **kargs): self = args[0] return self.tm @retryable(get_tm=_get_tm) def get_waiting_operation_ids(self) -> List[Tuple[UUID, CryptoOperationType]]: wait_list = self.dbsession.query(CryptoOperation, CryptoOperation.id, CryptoOperation.state, CryptoOperation.operation_type).filter_by(network_id=self.asset_network_id, state=CryptoOperationState.waiting) # Flatten wait_list = [(o.id, o.operation_type) for o in wait_list] return wait_list def run_waiting_operations(self): # Performed inside TX retry boundary ops = self.get_waiting_operation_ids() Transaction manager needs ``retry_attempt_count`` attribute set by Websauna framework. :param tm: Transaction manager used to control the TX execution :param get_tm: Factory function that is called with ``args`` and ``kwargs`` to get the transaction manager """ def _transaction_retry_wrapper(func): @wraps(func) def decorated_func(*args, **kwargs): global _retry_count if get_tm: manager = get_tm(*args, **kwargs) else: # Get how many attempts we want to do manager = tm assert manager, "No transaction manager available for retry" # Make sure we don't re-enter to transaction ensure_transactionless(transaction_manager=manager) retry_attempt_count = getattr(manager, "retry_attempt_count", None) if retry_attempt_count is None: raise NotRetryable("TransactionManager is not configured with default retry attempt count") # Run attempt loop latest_exc = None for num in range(retry_attempt_count): if num >= 1: logger.info("Transaction attempt #%d for function %s", num + 1, func) txn = manager.begin() # Expose retry count for testing manager.latest_retry_count = num try: val = func(*args, **kwargs) try: txn.commit() except ValueError as ve: # Means there was a nested transaction begin raise TooDeepInTransactions("Looks like transaction.commit() failed - usually this means that the wrapped function {} begun its own transaction and ruined transaction state management".format(func)) from ve return val except Exception as e: if is_retryable(txn, e): latest_exc = e continue else: txn.abort() # We could not commit raise e raise CannotRetryAnymore("Out of transaction retry attempts, tried {} times".format(num + 1)) from latest_exc return decorated_func return _transaction_retry_wrapper
[ "def", "retryable", "(", "tm", ":", "t", ".", "Optional", "[", "TransactionManager", "]", "=", "None", ",", "get_tm", ":", "t", ".", "Optional", "[", "t", ".", "Callable", "]", "=", "None", ")", ":", "def", "_transaction_retry_wrapper", "(", "func", ")...
https://github.com/websauna/websauna/blob/a57de54fb8a3fae859f24f373f0292e1e4b3c344/websauna/system/model/retry.py#L81-L205
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/setuptools/command/egg_info.py
python
egg_info.delete_file
(self, filename)
Delete `filename` (if not a dry run) after announcing it
Delete `filename` (if not a dry run) after announcing it
[ "Delete", "filename", "(", "if", "not", "a", "dry", "run", ")", "after", "announcing", "it" ]
def delete_file(self, filename): """Delete `filename` (if not a dry run) after announcing it""" log.info("deleting %s", filename) if not self.dry_run: os.unlink(filename)
[ "def", "delete_file", "(", "self", ",", "filename", ")", ":", "log", ".", "info", "(", "\"deleting %s\"", ",", "filename", ")", "if", "not", "self", ".", "dry_run", ":", "os", ".", "unlink", "(", "filename", ")" ]
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/setuptools/command/egg_info.py#L253-L257
whoosh-community/whoosh
5421f1ab3bb802114105b3181b7ce4f44ad7d0bb
src/whoosh/searching.py
python
Results.key_terms
(self, fieldname, docs=10, numterms=5, model=classify.Bo1Model, normalize=True)
return expander.expanded_terms(numterms, normalize=normalize)
Returns the 'numterms' most important terms from the top 'docs' documents in these results. "Most important" is generally defined as terms that occur frequently in the top hits but relatively infrequently in the collection as a whole. :param fieldname: Look at the terms in this field. This field must store vectors. :param docs: Look at this many of the top documents of the results. :param numterms: Return this number of important terms. :param model: The classify.ExpansionModel to use. See the classify module. :returns: list of unicode strings.
Returns the 'numterms' most important terms from the top 'docs' documents in these results. "Most important" is generally defined as terms that occur frequently in the top hits but relatively infrequently in the collection as a whole.
[ "Returns", "the", "numterms", "most", "important", "terms", "from", "the", "top", "docs", "documents", "in", "these", "results", ".", "Most", "important", "is", "generally", "defined", "as", "terms", "that", "occur", "frequently", "in", "the", "top", "hits", ...
def key_terms(self, fieldname, docs=10, numterms=5, model=classify.Bo1Model, normalize=True): """Returns the 'numterms' most important terms from the top 'docs' documents in these results. "Most important" is generally defined as terms that occur frequently in the top hits but relatively infrequently in the collection as a whole. :param fieldname: Look at the terms in this field. This field must store vectors. :param docs: Look at this many of the top documents of the results. :param numterms: Return this number of important terms. :param model: The classify.ExpansionModel to use. See the classify module. :returns: list of unicode strings. """ if not len(self): return [] docs = min(docs, len(self)) reader = self.searcher.reader() expander = classify.Expander(reader, fieldname, model=model) for _, docnum in self.top_n[:docs]: expander.add_document(docnum) return expander.expanded_terms(numterms, normalize=normalize)
[ "def", "key_terms", "(", "self", ",", "fieldname", ",", "docs", "=", "10", ",", "numterms", "=", "5", ",", "model", "=", "classify", ".", "Bo1Model", ",", "normalize", "=", "True", ")", ":", "if", "not", "len", "(", "self", ")", ":", "return", "[",...
https://github.com/whoosh-community/whoosh/blob/5421f1ab3bb802114105b3181b7ce4f44ad7d0bb/src/whoosh/searching.py#L1247-L1273
deepchem/deepchem
054eb4b2b082e3df8e1a8e77f36a52137ae6e375
deepchem/models/layers.py
python
WeaveLayer.__init__
(self, n_atom_input_feat: int = 75, n_pair_input_feat: int = 14, n_atom_output_feat: int = 50, n_pair_output_feat: int = 50, n_hidden_AA: int = 50, n_hidden_PA: int = 50, n_hidden_AP: int = 50, n_hidden_PP: int = 50, update_pair: bool = True, init: str = 'glorot_uniform', activation: str = 'relu', batch_normalize: bool = True, batch_normalize_kwargs: Dict = {"renorm": True}, **kwargs)
Parameters ---------- n_atom_input_feat: int, optional (default 75) Number of features for each atom in input. n_pair_input_feat: int, optional (default 14) Number of features for each pair of atoms in input. n_atom_output_feat: int, optional (default 50) Number of features for each atom in output. n_pair_output_feat: int, optional (default 50) Number of features for each pair of atoms in output. n_hidden_AA: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer n_hidden_PA: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer n_hidden_AP: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer n_hidden_PP: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer update_pair: bool, optional (default True) Whether to calculate for pair features, could be turned off for last layer init: str, optional (default 'glorot_uniform') Weight initialization for filters. activation: str, optional (default 'relu') Activation function applied batch_normalize: bool, optional (default True) If this is turned on, apply batch normalization before applying activation functions on convolutional layers. batch_normalize_kwargs: Dict, optional (default `{renorm=True}`) Batch normalization is a complex layer which has many potential argumentswhich change behavior. This layer accepts user-defined parameters which are passed to all `BatchNormalization` layers in `WeaveModel`, `WeaveLayer`, and `WeaveGather`.
Parameters ---------- n_atom_input_feat: int, optional (default 75) Number of features for each atom in input. n_pair_input_feat: int, optional (default 14) Number of features for each pair of atoms in input. n_atom_output_feat: int, optional (default 50) Number of features for each atom in output. n_pair_output_feat: int, optional (default 50) Number of features for each pair of atoms in output. n_hidden_AA: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer n_hidden_PA: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer n_hidden_AP: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer n_hidden_PP: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer update_pair: bool, optional (default True) Whether to calculate for pair features, could be turned off for last layer init: str, optional (default 'glorot_uniform') Weight initialization for filters. activation: str, optional (default 'relu') Activation function applied batch_normalize: bool, optional (default True) If this is turned on, apply batch normalization before applying activation functions on convolutional layers. batch_normalize_kwargs: Dict, optional (default `{renorm=True}`) Batch normalization is a complex layer which has many potential argumentswhich change behavior. This layer accepts user-defined parameters which are passed to all `BatchNormalization` layers in `WeaveModel`, `WeaveLayer`, and `WeaveGather`.
[ "Parameters", "----------", "n_atom_input_feat", ":", "int", "optional", "(", "default", "75", ")", "Number", "of", "features", "for", "each", "atom", "in", "input", ".", "n_pair_input_feat", ":", "int", "optional", "(", "default", "14", ")", "Number", "of", ...
def __init__(self, n_atom_input_feat: int = 75, n_pair_input_feat: int = 14, n_atom_output_feat: int = 50, n_pair_output_feat: int = 50, n_hidden_AA: int = 50, n_hidden_PA: int = 50, n_hidden_AP: int = 50, n_hidden_PP: int = 50, update_pair: bool = True, init: str = 'glorot_uniform', activation: str = 'relu', batch_normalize: bool = True, batch_normalize_kwargs: Dict = {"renorm": True}, **kwargs): """ Parameters ---------- n_atom_input_feat: int, optional (default 75) Number of features for each atom in input. n_pair_input_feat: int, optional (default 14) Number of features for each pair of atoms in input. n_atom_output_feat: int, optional (default 50) Number of features for each atom in output. n_pair_output_feat: int, optional (default 50) Number of features for each pair of atoms in output. n_hidden_AA: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer n_hidden_PA: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer n_hidden_AP: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer n_hidden_PP: int, optional (default 50) Number of units(convolution depths) in corresponding hidden layer update_pair: bool, optional (default True) Whether to calculate for pair features, could be turned off for last layer init: str, optional (default 'glorot_uniform') Weight initialization for filters. activation: str, optional (default 'relu') Activation function applied batch_normalize: bool, optional (default True) If this is turned on, apply batch normalization before applying activation functions on convolutional layers. batch_normalize_kwargs: Dict, optional (default `{renorm=True}`) Batch normalization is a complex layer which has many potential argumentswhich change behavior. This layer accepts user-defined parameters which are passed to all `BatchNormalization` layers in `WeaveModel`, `WeaveLayer`, and `WeaveGather`. """ super(WeaveLayer, self).__init__(**kwargs) self.init = init # Set weight initialization self.activation = activation # Get activations self.activation_fn = activations.get(activation) self.update_pair = update_pair # last weave layer does not need to update self.n_hidden_AA = n_hidden_AA self.n_hidden_PA = n_hidden_PA self.n_hidden_AP = n_hidden_AP self.n_hidden_PP = n_hidden_PP self.n_hidden_A = n_hidden_AA + n_hidden_PA self.n_hidden_P = n_hidden_AP + n_hidden_PP self.batch_normalize = batch_normalize self.batch_normalize_kwargs = batch_normalize_kwargs self.n_atom_input_feat = n_atom_input_feat self.n_pair_input_feat = n_pair_input_feat self.n_atom_output_feat = n_atom_output_feat self.n_pair_output_feat = n_pair_output_feat self.W_AP, self.b_AP, self.W_PP, self.b_PP, self.W_P, self.b_P = None, None, None, None, None, None
[ "def", "__init__", "(", "self", ",", "n_atom_input_feat", ":", "int", "=", "75", ",", "n_pair_input_feat", ":", "int", "=", "14", ",", "n_atom_output_feat", ":", "int", "=", "50", ",", "n_pair_output_feat", ":", "int", "=", "50", ",", "n_hidden_AA", ":", ...
https://github.com/deepchem/deepchem/blob/054eb4b2b082e3df8e1a8e77f36a52137ae6e375/deepchem/models/layers.py#L2727-L2795
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/http/server.py
python
SimpleHTTPRequestHandler.copyfile
(self, source, outputfile)
Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well.
Copy all data between two file objects.
[ "Copy", "all", "data", "between", "two", "file", "objects", "." ]
def copyfile(self, source, outputfile): """Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replace newlines by CRLF -- note however that this the default server uses this to copy binary data as well. """ shutil.copyfileobj(source, outputfile)
[ "def", "copyfile", "(", "self", ",", "source", ",", "outputfile", ")", ":", "shutil", ".", "copyfileobj", "(", "source", ",", "outputfile", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/http/server.py#L804-L818
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/inject/thirdparty/gprof2dot/gprof2dot.py
python
SleepyParser.parse_symbols
(self)
[]
def parse_symbols(self): lines = self.database.read('symbols.txt').splitlines() for line in lines: mo = self._symbol_re.match(line) if mo: symbol_id, module, procname, sourcefile, sourceline = mo.groups() function_id = ':'.join([module, procname]) try: function = self.profile.functions[function_id] except KeyError: function = Function(function_id, procname) function.module = module function[SAMPLES] = 0 self.profile.add_function(function) self.symbols[symbol_id] = function
[ "def", "parse_symbols", "(", "self", ")", ":", "lines", "=", "self", ".", "database", ".", "read", "(", "'symbols.txt'", ")", ".", "splitlines", "(", ")", "for", "line", "in", "lines", ":", "mo", "=", "self", ".", "_symbol_re", ".", "match", "(", "li...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/gprof2dot/gprof2dot.py#L1829-L1846
nadineproject/nadine
c41c8ef7ffe18f1853029c97eecc329039b4af6c
nadine/models/profile.py
python
UserQueryHelper.payers
(self, target_date=None)
return User.objects.filter(id__in=combined_set).distinct()
Return a set of Users that are paying for the active memberships
Return a set of Users that are paying for the active memberships
[ "Return", "a", "set", "of", "Users", "that", "are", "paying", "for", "the", "active", "memberships" ]
def payers(self, target_date=None): ''' Return a set of Users that are paying for the active memberships ''' # I tried to make this method as easy to read as possible. -- JLS # This joins the following sets: # Individuals paying for their own membership, # Organization leads of active organizations, # Users paying for other's memberships active_paid_subscriptions = ResourceSubscription.objects.active_subscriptions(target_date).filter(monthly_rate__gt=0) paid_by_self = active_paid_subscriptions.filter(paid_by__isnull=True) paid_by_other = active_paid_subscriptions.filter(paid_by__isnull=False) other_payers = paid_by_other.annotate(payer=F('paid_by')).values('payer') is_individual_membership = Q(membership__individualmembership__isnull=False) individual_payers = paid_by_self.filter(is_individual_membership).annotate(payer=F('membership__individualmembership__user')).values('payer') is_organizaion_membership = Q(membership__organizationmembership__isnull=False) organization_leads = paid_by_self.filter(is_organizaion_membership).annotate(payer=F('membership__organizationmembership__organization__lead')).values('payer') combined_set = (individual_payers | organization_leads | other_payers) return User.objects.filter(id__in=combined_set).distinct()
[ "def", "payers", "(", "self", ",", "target_date", "=", "None", ")", ":", "# I tried to make this method as easy to read as possible. -- JLS", "# This joins the following sets:", "# Individuals paying for their own membership,", "# Organization leads of active organizations,", "# Us...
https://github.com/nadineproject/nadine/blob/c41c8ef7ffe18f1853029c97eecc329039b4af6c/nadine/models/profile.py#L81-L101
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
example/ctp/futures/ApiStruct.py
python
BrokerUserPassword.__init__
(self, BrokerID='', UserID='', Password='')
[]
def __init__(self, BrokerID='', UserID='', Password=''): self.BrokerID = '' #经纪公司代码, char[11] self.UserID = '' #用户代码, char[16] self.Password = ''
[ "def", "__init__", "(", "self", ",", "BrokerID", "=", "''", ",", "UserID", "=", "''", ",", "Password", "=", "''", ")", ":", "self", ".", "BrokerID", "=", "''", "#经纪公司代码, char[11]", "self", ".", "UserID", "=", "''", "#用户代码, char[16]", "self", ".", "Pass...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/ctp/futures/ApiStruct.py#L2372-L2375
alanhamlett/pip-update-requirements
ce875601ef278c8ce00ad586434a978731525561
pur/packages/pip/_vendor/ipaddress.py
python
_IPAddressBase._prefix_from_ip_int
(cls, ip_int)
return prefixlen
Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones
Return prefix length from the bitwise netmask.
[ "Return", "prefix", "length", "from", "the", "bitwise", "netmask", "." ]
def _prefix_from_ip_int(cls, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, cls._max_prefixlen) prefixlen = cls._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = cls._max_prefixlen // 8 details = _compat_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen
[ "def", "_prefix_from_ip_int", "(", "cls", ",", "ip_int", ")", ":", "trailing_zeroes", "=", "_count_righthand_zero_bits", "(", "ip_int", ",", "cls", ".", "_max_prefixlen", ")", "prefixlen", "=", "cls", ".", "_max_prefixlen", "-", "trailing_zeroes", "leading_ones", ...
https://github.com/alanhamlett/pip-update-requirements/blob/ce875601ef278c8ce00ad586434a978731525561/pur/packages/pip/_vendor/ipaddress.py#L570-L592
respeaker/get_started_with_respeaker
ec859759fcec7e683a5e09328a8ea307046f353d
files/usr/lib/python2.7/site-packages/serial/sermsdos.py
python
Serial.getCD
(self)
Eead terminal status line
Eead terminal status line
[ "Eead", "terminal", "status", "line" ]
def getCD(self): """Eead terminal status line""" raise NotImplementedError
[ "def", "getCD", "(", "self", ")", ":", "raise", "NotImplementedError" ]
https://github.com/respeaker/get_started_with_respeaker/blob/ec859759fcec7e683a5e09328a8ea307046f353d/files/usr/lib/python2.7/site-packages/serial/sermsdos.py#L189-L191
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/codec/whoosh2.py
python
OLD_NUMERIC.parse_query
(self, fieldname, qstring, boost=1.0)
return query.Term(fieldname, text, boost=boost)
[]
def parse_query(self, fieldname, qstring, boost=1.0): from whoosh import query if qstring == "*": return query.Every(fieldname, boost=boost) try: text = self.to_text(qstring) except Exception: e = sys.exc_info()[1] return query.error_query(e) return query.Term(fieldname, text, boost=boost)
[ "def", "parse_query", "(", "self", ",", "fieldname", ",", "qstring", ",", "boost", "=", "1.0", ")", ":", "from", "whoosh", "import", "query", "if", "qstring", "==", "\"*\"", ":", "return", "query", ".", "Every", "(", "fieldname", ",", "boost", "=", "bo...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/codec/whoosh2.py#L2036-L2048
zedshaw/learn-more-python-the-hard-way-solutions
7886c860f69d69739a41d6490b8dc3fa777f227b
ex33_parsers/ex33.py
python
plus
(tokens, left)
return {'type': 'PLUS', 'left': left, 'right': right}
plus = expression PLUS expression
plus = expression PLUS expression
[ "plus", "=", "expression", "PLUS", "expression" ]
def plus(tokens, left): """plus = expression PLUS expression""" match(tokens, 'PLUS') right = expression(tokens) return {'type': 'PLUS', 'left': left, 'right': right}
[ "def", "plus", "(", "tokens", ",", "left", ")", ":", "match", "(", "tokens", ",", "'PLUS'", ")", "right", "=", "expression", "(", "tokens", ")", "return", "{", "'type'", ":", "'PLUS'", ",", "'left'", ":", "left", ",", "'right'", ":", "right", "}" ]
https://github.com/zedshaw/learn-more-python-the-hard-way-solutions/blob/7886c860f69d69739a41d6490b8dc3fa777f227b/ex33_parsers/ex33.py#L70-L74
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
check_server/check_scripts/8.py
python
check.index_check
(self)
return False
[]
def index_check(self): res = http('get',host,port,'/index.php?file=news&cid=1&page=1&test=eval&time=%s'%str(my_time),'',headers) if 'lalalala' in res: return True if debug: print "[fail!] index_fail" return False
[ "def", "index_check", "(", "self", ")", ":", "res", "=", "http", "(", "'get'", ",", "host", ",", "port", ",", "'/index.php?file=news&cid=1&page=1&test=eval&time=%s'", "%", "str", "(", "my_time", ")", ",", "''", ",", "headers", ")", "if", "'lalalala'", "in", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/check_server/check_scripts/8.py#L80-L86
ustayready/CredKing
68b612e4cdf01d2b65b14ab2869bb8a5531056ee
plugins/gmail/bs4/element.py
python
Tag.index
(self, element)
Find the index of a child by identity, not value. Avoids issues with tag.contents.index(element) getting the index of equal elements.
Find the index of a child by identity, not value. Avoids issues with tag.contents.index(element) getting the index of equal elements.
[ "Find", "the", "index", "of", "a", "child", "by", "identity", "not", "value", ".", "Avoids", "issues", "with", "tag", ".", "contents", ".", "index", "(", "element", ")", "getting", "the", "index", "of", "equal", "elements", "." ]
def index(self, element): """ Find the index of a child by identity, not value. Avoids issues with tag.contents.index(element) getting the index of equal elements. """ for i, child in enumerate(self.contents): if child is element: return i raise ValueError("Tag.index: element not in tag")
[ "def", "index", "(", "self", ",", "element", ")", ":", "for", "i", ",", "child", "in", "enumerate", "(", "self", ".", "contents", ")", ":", "if", "child", "is", "element", ":", "return", "i", "raise", "ValueError", "(", "\"Tag.index: element not in tag\"",...
https://github.com/ustayready/CredKing/blob/68b612e4cdf01d2b65b14ab2869bb8a5531056ee/plugins/gmail/bs4/element.py#L979-L987
amansrivastava17/embedding-as-service
8cd4087cbd39ecb57ee732c029dea465ad364a5e
server/embedding_as_service/text/xlnet/models/tpu_estimator.py
python
_clone_export_output_with_tensors
(export_output, tensors)
Clones `export_output` but with new `tensors`. Args: export_output: an `ExportOutput` object such as `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. tensors: a list of `Tensors` used to construct a new `export_output`. Returns: A dict similar to `export_output` but with `tensors`. Raises: ValueError: if `export_output` is not one of `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`.
Clones `export_output` but with new `tensors`.
[ "Clones", "export_output", "but", "with", "new", "tensors", "." ]
def _clone_export_output_with_tensors(export_output, tensors): """Clones `export_output` but with new `tensors`. Args: export_output: an `ExportOutput` object such as `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. tensors: a list of `Tensors` used to construct a new `export_output`. Returns: A dict similar to `export_output` but with `tensors`. Raises: ValueError: if `export_output` is not one of `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. """ if isinstance(export_output, export_output_lib.ClassificationOutput): if len(tensors) != 2: raise ValueError('tensors must be of length 2; ' 'got {}.'.format(len(tensors))) return export_output_lib.ClassificationOutput(*tensors) elif isinstance(export_output, export_output_lib.RegressionOutput): if len(tensors) != 1: raise ValueError('tensors must be of length 1; ' 'got {}'.format(len(tensors))) return export_output_lib.RegressionOutput(*tensors) elif isinstance(export_output, export_output_lib.PredictOutput): return export_output_lib.PredictOutput( dict(zip(export_output.outputs.keys(), tensors))) else: raise ValueError( '`export_output` must be have type `ClassificationOutput`, ' '`RegressionOutput`, or `PredictOutput`; got {}.'.format(export_output))
[ "def", "_clone_export_output_with_tensors", "(", "export_output", ",", "tensors", ")", ":", "if", "isinstance", "(", "export_output", ",", "export_output_lib", ".", "ClassificationOutput", ")", ":", "if", "len", "(", "tensors", ")", "!=", "2", ":", "raise", "Val...
https://github.com/amansrivastava17/embedding-as-service/blob/8cd4087cbd39ecb57ee732c029dea465ad364a5e/server/embedding_as_service/text/xlnet/models/tpu_estimator.py#L2842-L2873
xiaobai1217/MBMD
246f3434bccb9c8357e0f698995b659578bf1afb
core/man_meta_arch.py
python
MANMetaArch._add_box_predictions_to_feature_maps
(self, feature_maps,reuse=None)
return box_encodings, class_predictions_with_background
Adds box predictors to each feature map and returns concatenated results. Args: feature_maps: a list of tensors where the ith tensor has shape [batch, height_i, width_i, depth_i] Returns: box_encodings: 4-D float tensor of shape [batch_size, num_anchors, box_code_dimension] containing predicted boxes. class_predictions_with_background: 2-D float tensor of shape [batch_size, num_anchors, num_classes+1] containing class predictions (logits) for each of the anchors. Note that this tensor *includes* background class predictions (at class index 0). Raises: RuntimeError: if the number of feature maps extracted via the extract_features method does not match the length of the num_anchors_per_locations list that was passed to the constructor. RuntimeError: if box_encodings from the box_predictor does not have shape of the form [batch_size, num_anchors, 1, code_size].
Adds box predictors to each feature map and returns concatenated results.
[ "Adds", "box", "predictors", "to", "each", "feature", "map", "and", "returns", "concatenated", "results", "." ]
def _add_box_predictions_to_feature_maps(self, feature_maps,reuse=None): """Adds box predictors to each feature map and returns concatenated results. Args: feature_maps: a list of tensors where the ith tensor has shape [batch, height_i, width_i, depth_i] Returns: box_encodings: 4-D float tensor of shape [batch_size, num_anchors, box_code_dimension] containing predicted boxes. class_predictions_with_background: 2-D float tensor of shape [batch_size, num_anchors, num_classes+1] containing class predictions (logits) for each of the anchors. Note that this tensor *includes* background class predictions (at class index 0). Raises: RuntimeError: if the number of feature maps extracted via the extract_features method does not match the length of the num_anchors_per_locations list that was passed to the constructor. RuntimeError: if box_encodings from the box_predictor does not have shape of the form [batch_size, num_anchors, 1, code_size]. """ num_anchors_per_location_list = ( self._anchor_generator.num_anchors_per_location()) if len(feature_maps) != len(num_anchors_per_location_list): raise RuntimeError('the number of feature maps must match the ' 'length of self.anchors.NumAnchorsPerLocation().') box_encodings_list = [] cls_predictions_with_background_list = [] for idx, (feature_map, num_anchors_per_location ) in enumerate(zip(feature_maps, num_anchors_per_location_list)): box_predictor_scope = 'BoxPredictor' box_predictions = self._box_predictor.predict(feature_map, num_anchors_per_location, box_predictor_scope,reuse=reuse) box_encodings = box_predictions[bpredictor.BOX_ENCODINGS] cls_predictions_with_background = box_predictions[ bpredictor.CLASS_PREDICTIONS_WITH_BACKGROUND] box_encodings_shape = box_encodings.get_shape().as_list() if len(box_encodings_shape) != 4 or box_encodings_shape[2] != 1: raise RuntimeError('box_encodings from the box_predictor must be of ' 'shape `[batch_size, num_anchors, 1, code_size]`; ' 'actual shape', box_encodings_shape) box_encodings = tf.squeeze(box_encodings, axis=2) box_encodings_list.append(box_encodings) cls_predictions_with_background_list.append( cls_predictions_with_background) num_predictions = sum( [tf.shape(box_encodings)[1] for box_encodings in box_encodings_list]) num_anchors = self.anchors.num_boxes() anchors_assert = tf.assert_equal(num_anchors, num_predictions, [ 'Mismatch: number of anchors vs number of predictions', num_anchors, num_predictions ]) with tf.control_dependencies([anchors_assert]): box_encodings = tf.concat(box_encodings_list, 1) class_predictions_with_background = tf.concat( cls_predictions_with_background_list, 1) return box_encodings, class_predictions_with_background
[ "def", "_add_box_predictions_to_feature_maps", "(", "self", ",", "feature_maps", ",", "reuse", "=", "None", ")", ":", "num_anchors_per_location_list", "=", "(", "self", ".", "_anchor_generator", ".", "num_anchors_per_location", "(", ")", ")", "if", "len", "(", "fe...
https://github.com/xiaobai1217/MBMD/blob/246f3434bccb9c8357e0f698995b659578bf1afb/core/man_meta_arch.py#L154-L214
tlsfuzzer/tlslite-ng
8720db53067ba4f7bb7b5a32d682033d8b5446f9
tlslite/bufferedsocket.py
python
BufferedSocket.__init__
(self, socket)
Associate socket with the object
Associate socket with the object
[ "Associate", "socket", "with", "the", "object" ]
def __init__(self, socket): """Associate socket with the object""" self.socket = socket self._write_queue = deque() self.buffer_writes = False self._read_buffer = bytearray()
[ "def", "__init__", "(", "self", ",", "socket", ")", ":", "self", ".", "socket", "=", "socket", "self", ".", "_write_queue", "=", "deque", "(", ")", "self", ".", "buffer_writes", "=", "False", "self", ".", "_read_buffer", "=", "bytearray", "(", ")" ]
https://github.com/tlsfuzzer/tlslite-ng/blob/8720db53067ba4f7bb7b5a32d682033d8b5446f9/tlslite/bufferedsocket.py#L23-L28
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/contourcarpet/_contours.py
python
Contours.showlines
(self)
return self["showlines"]
Determines whether or not the contour lines are drawn. Has an effect only if `contours.coloring` is set to "fill". The 'showlines' property must be specified as a bool (either True, or False) Returns ------- bool
Determines whether or not the contour lines are drawn. Has an effect only if `contours.coloring` is set to "fill". The 'showlines' property must be specified as a bool (either True, or False)
[ "Determines", "whether", "or", "not", "the", "contour", "lines", "are", "drawn", ".", "Has", "an", "effect", "only", "if", "contours", ".", "coloring", "is", "set", "to", "fill", ".", "The", "showlines", "property", "must", "be", "specified", "as", "a", ...
def showlines(self): """ Determines whether or not the contour lines are drawn. Has an effect only if `contours.coloring` is set to "fill". The 'showlines' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showlines"]
[ "def", "showlines", "(", "self", ")", ":", "return", "self", "[", "\"showlines\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/contourcarpet/_contours.py#L195-L207
649453932/Bert-Chinese-Text-Classification-Pytorch
050a7b0dc75d8a2d7fd526002c4642d5329a0c27
pytorch_pretrained/modeling_gpt2.py
python
GPT2Config.to_json_string
(self)
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
Serializes this instance to a JSON string.
Serializes this instance to a JSON string.
[ "Serializes", "this", "instance", "to", "a", "JSON", "string", "." ]
def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
[ "def", "to_json_string", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "to_dict", "(", ")", ",", "indent", "=", "2", ",", "sort_keys", "=", "True", ")", "+", "\"\\n\"" ]
https://github.com/649453932/Bert-Chinese-Text-Classification-Pytorch/blob/050a7b0dc75d8a2d7fd526002c4642d5329a0c27/pytorch_pretrained/modeling_gpt2.py#L176-L178
alexsax/pytorch-visdom
6e46601d71ea417ec2a5b39316d2a0ea8ac921cf
trainer/plugins/visdom_logger.py
python
VisdomTextLogger.__init__
(self, fields, interval=None, win=None, env=None, opts={}, update_type=valid_update_types[0])
Args: fields: The fields to log. May either be the name of some stat (e.g. ProgressMonitor) will have `stat_name='progress'`, in which case all of the fields under `log_HOOK_fields` will be logged. Finer-grained control can be specified by using individual fields such as `progress.percent`. interval: A List of 2-tuples where each tuple contains (k, HOOK_TIME). k (int): The logger will be called every 'k' HOOK_TIMES HOOK_TIME (string): The logger will be called at the given hook update_type: One of {'REPLACE', 'APPEND'}. Default 'REPLACE'. Examples: >>> progress_m = ProgressMonitor() >>> logger = VisdomTextLogger(["progress"], [(2, 'iteration')]) >>> train.register_plugin(progress_m) >>> train.register_plugin(logger)
Args: fields: The fields to log. May either be the name of some stat (e.g. ProgressMonitor) will have `stat_name='progress'`, in which case all of the fields under `log_HOOK_fields` will be logged. Finer-grained control can be specified by using individual fields such as `progress.percent`. interval: A List of 2-tuples where each tuple contains (k, HOOK_TIME). k (int): The logger will be called every 'k' HOOK_TIMES HOOK_TIME (string): The logger will be called at the given hook update_type: One of {'REPLACE', 'APPEND'}. Default 'REPLACE'.
[ "Args", ":", "fields", ":", "The", "fields", "to", "log", ".", "May", "either", "be", "the", "name", "of", "some", "stat", "(", "e", ".", "g", ".", "ProgressMonitor", ")", "will", "have", "stat_name", "=", "progress", "in", "which", "case", "all", "o...
def __init__(self, fields, interval=None, win=None, env=None, opts={}, update_type=valid_update_types[0]): ''' Args: fields: The fields to log. May either be the name of some stat (e.g. ProgressMonitor) will have `stat_name='progress'`, in which case all of the fields under `log_HOOK_fields` will be logged. Finer-grained control can be specified by using individual fields such as `progress.percent`. interval: A List of 2-tuples where each tuple contains (k, HOOK_TIME). k (int): The logger will be called every 'k' HOOK_TIMES HOOK_TIME (string): The logger will be called at the given hook update_type: One of {'REPLACE', 'APPEND'}. Default 'REPLACE'. Examples: >>> progress_m = ProgressMonitor() >>> logger = VisdomTextLogger(["progress"], [(2, 'iteration')]) >>> train.register_plugin(progress_m) >>> train.register_plugin(logger) ''' super(VisdomTextLogger, self).__init__(fields, interval, win, env, opts) self.text = '' if update_type not in self.valid_update_types: raise ValueError("update type '{}' not found. Must be one of {}".format(update_type, self.valid_update_types)) self.update_type = update_type self.viz_logger = self._viz_prototype(self.viz.text)
[ "def", "__init__", "(", "self", ",", "fields", ",", "interval", "=", "None", ",", "win", "=", "None", ",", "env", "=", "None", ",", "opts", "=", "{", "}", ",", "update_type", "=", "valid_update_types", "[", "0", "]", ")", ":", "super", "(", "Visdom...
https://github.com/alexsax/pytorch-visdom/blob/6e46601d71ea417ec2a5b39316d2a0ea8ac921cf/trainer/plugins/visdom_logger.py#L177-L202
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/docbook/__init__.py
python
__extend_targets_sources
(target, source)
return target, source
Prepare the lists of target and source files.
Prepare the lists of target and source files.
[ "Prepare", "the", "lists", "of", "target", "and", "source", "files", "." ]
def __extend_targets_sources(target, source): """ Prepare the lists of target and source files. """ if not SCons.Util.is_List(target): target = [target] if not source: source = target[:] elif not SCons.Util.is_List(source): source = [source] if len(target) < len(source): target.extend(source[len(target):]) return target, source
[ "def", "__extend_targets_sources", "(", "target", ",", "source", ")", ":", "if", "not", "SCons", ".", "Util", ".", "is_List", "(", "target", ")", ":", "target", "=", "[", "target", "]", "if", "not", "source", ":", "source", "=", "target", "[", ":", "...
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/docbook/__init__.py#L75-L86
Esri/ArcREST
ab240fde2b0200f61d4a5f6df033516e53f2f416
src/arcrest/packages/ntlm3/ntlm.py
python
create_NT_hashed_password_v1
(passwd, user=None, domain=None)
return digest
create NT hashed password
create NT hashed password
[ "create", "NT", "hashed", "password" ]
def create_NT_hashed_password_v1(passwd, user=None, domain=None): "create NT hashed password" # if the passwd provided is already a hash, we just return the second half if re.match(r'^[\w]{32}:[\w]{32}$', passwd): return binascii.unhexlify(passwd.split(':')[1]) digest = hashlib.new('md4', passwd.encode('utf-16le')).digest() return digest
[ "def", "create_NT_hashed_password_v1", "(", "passwd", ",", "user", "=", "None", ",", "domain", "=", "None", ")", ":", "# if the passwd provided is already a hash, we just return the second half", "if", "re", ".", "match", "(", "r'^[\\w]{32}:[\\w]{32}$'", ",", "passwd", ...
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/packages/ntlm3/ntlm.py#L397-L404
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/tarfile.py
python
TarInfo._apply_pax_info
(self, pax_headers, encoding, errors)
Replace fields with supplemental information from a previous pax extended or global header.
Replace fields with supplemental information from a previous pax extended or global header.
[ "Replace", "fields", "with", "supplemental", "information", "from", "a", "previous", "pax", "extended", "or", "global", "header", "." ]
def _apply_pax_info(self, pax_headers, encoding, errors): """Replace fields with supplemental information from a previous pax extended or global header. """ for keyword, value in pax_headers.items(): if keyword == "GNU.sparse.name": setattr(self, "path", value) elif keyword == "GNU.sparse.size": setattr(self, "size", int(value)) elif keyword == "GNU.sparse.realsize": setattr(self, "size", int(value)) elif keyword in PAX_FIELDS: if keyword in PAX_NUMBER_FIELDS: try: value = PAX_NUMBER_FIELDS[keyword](value) except ValueError: value = 0 if keyword == "path": value = value.rstrip("/") setattr(self, keyword, value) self.pax_headers = pax_headers.copy()
[ "def", "_apply_pax_info", "(", "self", ",", "pax_headers", ",", "encoding", ",", "errors", ")", ":", "for", "keyword", ",", "value", "in", "pax_headers", ".", "items", "(", ")", ":", "if", "keyword", "==", "\"GNU.sparse.name\"", ":", "setattr", "(", "self"...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tarfile.py#L1335-L1356
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/pybench/CommandLine.py
python
Application.handle__examples
(self,arg)
return 0
[]
def handle__examples(self,arg): self.print_header() if self.examples: print 'Examples:' print print string.strip(self.examples % self.__dict__) print else: print 'No examples available.' print return 0
[ "def", "handle__examples", "(", "self", ",", "arg", ")", ":", "self", ".", "print_header", "(", ")", "if", "self", ".", "examples", ":", "print", "'Examples:'", "print", "print", "string", ".", "strip", "(", "self", ".", "examples", "%", "self", ".", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/pybench/CommandLine.py#L589-L600
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/interfaces/kenzo.py
python
KenzoChainComplex.tensor_product
(self, other)
return KenzoChainComplex(__tnsr_prdc__(self._kenzo, other._kenzo))
r""" Return the tensor product of ``self`` and ``other``. INPUT: - ``other`` -- The Kenzo object with which to compute the tensor product OUTPUT: - A :class:`KenzoChainComplex` EXAMPLES:: sage: from sage.interfaces.kenzo import Sphere # optional - kenzo sage: s2 = Sphere(2) # optional - kenzo sage: s3 = Sphere(3) # optional - kenzo sage: p = s2.tensor_product(s3) # optional - kenzo sage: type(p) # optional - kenzo <class 'sage.interfaces.kenzo.KenzoChainComplex'> sage: [p.homology(i) for i in range(8)] # optional - kenzo [Z, 0, Z, Z, 0, Z, 0, 0]
r""" Return the tensor product of ``self`` and ``other``.
[ "r", "Return", "the", "tensor", "product", "of", "self", "and", "other", "." ]
def tensor_product(self, other): r""" Return the tensor product of ``self`` and ``other``. INPUT: - ``other`` -- The Kenzo object with which to compute the tensor product OUTPUT: - A :class:`KenzoChainComplex` EXAMPLES:: sage: from sage.interfaces.kenzo import Sphere # optional - kenzo sage: s2 = Sphere(2) # optional - kenzo sage: s3 = Sphere(3) # optional - kenzo sage: p = s2.tensor_product(s3) # optional - kenzo sage: type(p) # optional - kenzo <class 'sage.interfaces.kenzo.KenzoChainComplex'> sage: [p.homology(i) for i in range(8)] # optional - kenzo [Z, 0, Z, Z, 0, Z, 0, 0] """ return KenzoChainComplex(__tnsr_prdc__(self._kenzo, other._kenzo))
[ "def", "tensor_product", "(", "self", ",", "other", ")", ":", "return", "KenzoChainComplex", "(", "__tnsr_prdc__", "(", "self", ".", "_kenzo", ",", "other", ".", "_kenzo", ")", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/interfaces/kenzo.py#L449-L472
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/mpmath/functions/zetazeros.py
python
separate_zeros_in_block
(ctx, zero_number_block, T, V, limitloop=None, fp_tolerance=None)
return (T,V, separated)
Separate the zeros contained in the block T, limitloop determines how long one must search
Separate the zeros contained in the block T, limitloop determines how long one must search
[ "Separate", "the", "zeros", "contained", "in", "the", "block", "T", "limitloop", "determines", "how", "long", "one", "must", "search" ]
def separate_zeros_in_block(ctx, zero_number_block, T, V, limitloop=None, fp_tolerance=None): """Separate the zeros contained in the block T, limitloop determines how long one must search""" if limitloop is None: limitloop = ctx.inf loopnumber = 0 variations = count_variations(V) while ((variations < zero_number_block) and (loopnumber <limitloop)): a = T[0] v = V[0] newT = [a] newV = [v] variations = 0 for n in range(1,len(T)): b2 = T[n] u = V[n] if (u*v>0): alpha = ctx.sqrt(u/v) b= (alpha*a+b2)/(alpha+1) else: b = (a+b2)/2 if fp_tolerance < 10: w = ctx._fp.siegelz(b) if abs(w)<fp_tolerance: w = ctx.siegelz(b) else: w=ctx.siegelz(b) if v*w<0: variations += 1 newT.append(b) newV.append(w) u = V[n] if u*w <0: variations += 1 newT.append(b2) newV.append(u) a = b2 v = u T = newT V = newV loopnumber +=1 if (limitloop>ITERATION_LIMIT)and(loopnumber>2)and(variations+2==zero_number_block): dtMax=0 dtSec=0 kMax = 0 for k1 in range(1,len(T)): dt = T[k1]-T[k1-1] if dt > dtMax: kMax=k1 dtSec = dtMax dtMax = dt elif (dt<dtMax) and(dt >dtSec): dtSec = dt if dtMax>3*dtSec: f = lambda x: ctx.rs_z(x,derivative=1) t0=T[kMax-1] t1 = T[kMax] t=ctx.findroot(f, (t0,t1), solver ='illinois',verify=False, verbose=False) v = ctx.siegelz(t) if (t0<t) and (t<t1) and (v*V[kMax]<0): T.insert(kMax,t) V.insert(kMax,v) variations = count_variations(V) if variations == zero_number_block: separated = True else: separated = False return (T,V, separated)
[ "def", "separate_zeros_in_block", "(", "ctx", ",", "zero_number_block", ",", "T", ",", "V", ",", "limitloop", "=", "None", ",", "fp_tolerance", "=", "None", ")", ":", "if", "limitloop", "is", "None", ":", "limitloop", "=", "ctx", ".", "inf", "loopnumber", ...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/mpmath/functions/zetazeros.py#L67-L135
mks0601/A-Convolutional-Neural-Network-Cascade-for-Face-Detection
2a7e8464fff041d128a8dc536ae200ca51784045
data.py
python
load_db_calib_train
(dim)
return x_db
[]
def load_db_calib_train(dim): print "Loading calibration training db..." annot_dir = param.db_dir + "AFLW/aflw/data/" annot_fp = open(annot_dir + "annot", "r") raw_data = annot_fp.readlines() #pos image cropping x_db = [0 for _ in xrange(len(raw_data))] for i,line in enumerate(raw_data): parsed_line = line.split(',') filename = parsed_line[0][3:-1] xmin = int(parsed_line[1]) ymin = int(parsed_line[2]) xmax = xmin + int(parsed_line[3]) ymax = ymin + int(parsed_line[4][:-2]) img = Image.open(param.pos_dir+filename) #truncated image(error) if i == 8160 or i == 14884 or i == 14886: continue #check if gray if len(np.shape(np.asarray(img))) != param.input_channel: img = np.asarray(img) img = np.reshape(img,(np.shape(img)[0],np.shape(img)[1],1)) img = np.concatenate((img,img,img),axis=2) img = Image.fromarray(img) if xmax >= img.size[0]: xmax = img.size[0]-1 if ymax >= img.size[1]: ymax = img.size[1]-1 x_db_list = [0 for _ in xrange(param.cali_patt_num)] for si,s in enumerate(param.cali_scale): for xi,x in enumerate(param.cali_off_x): for yi,y in enumerate(param.cali_off_y): new_xmin = xmin - x*float(xmax-xmin)/s new_ymin = ymin - y*float(ymax-ymin)/s new_xmax = new_xmin+float(xmax-xmin)/s new_ymax = new_ymin+float(ymax-ymin)/s new_xmin = int(new_xmin) new_ymin = int(new_ymin) new_xmax = int(new_xmax) new_ymax = int(new_ymax) if new_xmin < 0 or new_ymin < 0 or new_xmax >= img.size[0] or new_ymax >= img.size[1]: continue cropped_img = util.img2array(img.crop((new_xmin, new_ymin, new_xmax, new_ymax)),dim) calib_idx = si*len(param.cali_off_x)*len(param.cali_off_y)+xi*len(param.cali_off_y)+yi #for debugging #cropped_img.save(param.pos_dir + str(i) + ".jpg") x_db_list[calib_idx] = [cropped_img,calib_idx] x_db_list = [elem for elem in x_db_list if type(elem) != int] if len(x_db_list) > 0: x_db[i] = x_db_list x_db = [elem for elem in x_db if type(elem) != int] x_db = [x_db[i][j] for i in xrange(len(x_db)) for j in xrange(len(x_db[i]))] return x_db
[ "def", "load_db_calib_train", "(", "dim", ")", ":", "print", "\"Loading calibration training db...\"", "annot_dir", "=", "param", ".", "db_dir", "+", "\"AFLW/aflw/data/\"", "annot_fp", "=", "open", "(", "annot_dir", "+", "\"annot\"", ",", "\"r\"", ")", "raw_data", ...
https://github.com/mks0601/A-Convolutional-Neural-Network-Cascade-for-Face-Detection/blob/2a7e8464fff041d128a8dc536ae200ca51784045/data.py#L185-L259
haiwen/seahub
e92fcd44e3e46260597d8faa9347cb8222b8b10d
scripts/setup-seafile-mysql.py
python
Utils.must_copy
(src, dst)
Copy src to dst, exit on failure
Copy src to dst, exit on failure
[ "Copy", "src", "to", "dst", "exit", "on", "failure" ]
def must_copy(src, dst): '''Copy src to dst, exit on failure''' try: shutil.copy(src, dst) except Exception as e: Utils.error('failed to copy %s to %s: %s' % (src, dst, e))
[ "def", "must_copy", "(", "src", ",", "dst", ")", ":", "try", ":", "shutil", ".", "copy", "(", "src", ",", "dst", ")", "except", "Exception", "as", "e", ":", "Utils", ".", "error", "(", "'failed to copy %s to %s: %s'", "%", "(", "src", ",", "dst", ","...
https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/scripts/setup-seafile-mysql.py#L140-L145