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
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/dev/boards/relations.py
python
show_work_item
(id, organization=None, detect=None)
return work_item
Get work item, fill relations with friendly name
Get work item, fill relations with friendly name
[ "Get", "work", "item", "fill", "relations", "with", "friendly", "name" ]
def show_work_item(id, organization=None, detect=None): # pylint: disable=redefined-builtin """ Get work item, fill relations with friendly name """ organization = resolve_instance(detect=detect, organization=organization) client = get_work_item_tracking_client(organization) work_item = client.get_work_item(id, expand='All') relation_types_from_service = client.get_relation_types() work_item = fill_friendly_name_for_relations_in_work_item(relation_types_from_service, work_item) return work_item
[ "def", "show_work_item", "(", "id", ",", "organization", "=", "None", ",", "detect", "=", "None", ")", ":", "# pylint: disable=redefined-builtin", "organization", "=", "resolve_instance", "(", "detect", "=", "detect", ",", "organization", "=", "organization", ")",...
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/dev/boards/relations.py#L109-L118
apache/bloodhound
c3e31294e68af99d4e040e64fbdf52394344df9e
trac/trac/web/api.py
python
Request.remote_addr
(self)
return self.environ.get('REMOTE_ADDR')
IP address of the remote user
IP address of the remote user
[ "IP", "address", "of", "the", "remote", "user" ]
def remote_addr(self): """IP address of the remote user""" return self.environ.get('REMOTE_ADDR')
[ "def", "remote_addr", "(", "self", ")", ":", "return", "self", ".", "environ", ".", "get", "(", "'REMOTE_ADDR'", ")" ]
https://github.com/apache/bloodhound/blob/c3e31294e68af99d4e040e64fbdf52394344df9e/trac/trac/web/api.py#L349-L351
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/templates/historic/ARC/menus.py
python
S3OptionsMenu.admin
(self)
return menu
ADMIN menu
ADMIN menu
[ "ADMIN", "menu" ]
def admin(self): """ ADMIN menu """ menu = super(S3OptionsMenu, self).admin() gis_item = M("Map Settings", c="gis", f="config") menu.append(gis_item) return menu
[ "def", "admin", "(", "self", ")", ":", "menu", "=", "super", "(", "S3OptionsMenu", ",", "self", ")", ".", "admin", "(", ")", "gis_item", "=", "M", "(", "\"Map Settings\"", ",", "c", "=", "\"gis\"", ",", "f", "=", "\"config\"", ")", "menu", ".", "ap...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/templates/historic/ARC/menus.py#L304-L311
dipy/dipy
be956a529465b28085f8fc435a756947ddee1c89
dipy/reconst/qtdmri.py
python
QtdmriFit.odf
(self, sphere, tau, s=2)
return odf
r""" Calculates the analytical Orientation Distribution Function (ODF) for a given diffusion time tau from the signal, [1]_ Eq. (32). The qtdmri coefficients are first converted to mapmri coefficients following [2]. Parameters ---------- sphere : dipy sphere object sphere object with vertice orientations to compute the ODF on. tau : float diffusion time (big_delta - small_delta / 3.) in seconds s : unsigned int radial moment of the ODF References ---------- .. [1] Ozarslan E. et. al, "Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure", NeuroImage, 2013. .. [2] Fick, Rutger HJ, et al. "Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time", Medical Image Analysis, 2017.
r""" Calculates the analytical Orientation Distribution Function (ODF) for a given diffusion time tau from the signal, [1]_ Eq. (32). The qtdmri coefficients are first converted to mapmri coefficients following [2].
[ "r", "Calculates", "the", "analytical", "Orientation", "Distribution", "Function", "(", "ODF", ")", "for", "a", "given", "diffusion", "time", "tau", "from", "the", "signal", "[", "1", "]", "_", "Eq", ".", "(", "32", ")", ".", "The", "qtdmri", "coefficien...
def odf(self, sphere, tau, s=2): r""" Calculates the analytical Orientation Distribution Function (ODF) for a given diffusion time tau from the signal, [1]_ Eq. (32). The qtdmri coefficients are first converted to mapmri coefficients following [2]. Parameters ---------- sphere : dipy sphere object sphere object with vertice orientations to compute the ODF on. tau : float diffusion time (big_delta - small_delta / 3.) in seconds s : unsigned int radial moment of the ODF References ---------- .. [1] Ozarslan E. et. al, "Mean apparent propagator (MAP) MRI: A novel diffusion imaging method for mapping tissue microstructure", NeuroImage, 2013. .. [2] Fick, Rutger HJ, et al. "Non-Parametric GraphNet-Regularized Representation of dMRI in Space and Time", Medical Image Analysis, 2017. """ mapmri_coef = self.qtdmri_to_mapmri_coef(tau) if self.model.cartesian: v_ = sphere.vertices v = np.dot(v_, self.R) I_s = mapmri.mapmri_odf_matrix(self.model.radial_order, self.us, s, v) odf = np.dot(I_s, mapmri_coef) else: II = self.model.cache_get('ODF_matrix', key=(sphere, s)) if II is None: II = mapmri.mapmri_isotropic_odf_matrix( self.model.radial_order, 1, s, sphere.vertices) self.model.cache_set('ODF_matrix', (sphere, s), II) odf = self.us[0] ** s * np.dot(II, mapmri_coef) return odf
[ "def", "odf", "(", "self", ",", "sphere", ",", "tau", ",", "s", "=", "2", ")", ":", "mapmri_coef", "=", "self", ".", "qtdmri_to_mapmri_coef", "(", "tau", ")", "if", "self", ".", "model", ".", "cartesian", ":", "v_", "=", "sphere", ".", "vertices", ...
https://github.com/dipy/dipy/blob/be956a529465b28085f8fc435a756947ddee1c89/dipy/reconst/qtdmri.py#L593-L632
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/idlelib/rpc.py
python
SocketIO.asyncreturn
(self, seq)
return self.decoderesponse(response)
[]
def asyncreturn(self, seq): self.debug("asyncreturn:%d:call getresponse(): " % seq) response = self.getresponse(seq, wait=0.05) self.debug(("asyncreturn:%d:response: " % seq), response) return self.decoderesponse(response)
[ "def", "asyncreturn", "(", "self", ",", "seq", ")", ":", "self", ".", "debug", "(", "\"asyncreturn:%d:call getresponse(): \"", "%", "seq", ")", "response", "=", "self", ".", "getresponse", "(", "seq", ",", "wait", "=", "0.05", ")", "self", ".", "debug", ...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/idlelib/rpc.py#L246-L250
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/fractions.py
python
Fraction._richcmp
(self, other, op)
Helper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators.
Helper for comparison operators, for internal use only.
[ "Helper", "for", "comparison", "operators", "for", "internal", "use", "only", "." ]
def _richcmp(self, other, op): """Helper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators. """ # convert other to a Rational instance where reasonable. if isinstance(other, Rational): return op(self._numerator * other.denominator, self._denominator * other.numerator) # comparisons with complex should raise a TypeError, for consistency # with int<->complex, float<->complex, and complex<->complex comparisons. if isinstance(other, complex): raise TypeError("no ordering relation is defined for complex numbers") if isinstance(other, float): if math.isnan(other) or math.isinf(other): return op(0.0, other) else: return op(self, self.from_float(other)) else: return NotImplemented
[ "def", "_richcmp", "(", "self", ",", "other", ",", "op", ")", ":", "# convert other to a Rational instance where reasonable.", "if", "isinstance", "(", "other", ",", "Rational", ")", ":", "return", "op", "(", "self", ".", "_numerator", "*", "other", ".", "deno...
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/fractions.py#L546-L570
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/voiper/sulley/impacket/dcerpc/dcom.py
python
RemoteActivationRequestHeader.get_mode
(self)
return self.get_long(60, '<')
[]
def get_mode(self): return self.get_long(60, '<')
[ "def", "get_mode", "(", "self", ")", ":", "return", "self", ".", "get_long", "(", "60", ",", "'<'", ")" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/voiper/sulley/impacket/dcerpc/dcom.py#L137-L138
devitocodes/devito
6abd441e3f5f091775ad332be6b95e017b8cbd16
devito/types/sparse.py
python
SparseFunction._coordinate_symbols
(self)
return tuple([self.coordinates.indexify((p_dim, i)) for i in range(self.grid.dim)])
Symbol representing the coordinate values in each dimension.
Symbol representing the coordinate values in each dimension.
[ "Symbol", "representing", "the", "coordinate", "values", "in", "each", "dimension", "." ]
def _coordinate_symbols(self): """Symbol representing the coordinate values in each dimension.""" p_dim = self.indices[-1] return tuple([self.coordinates.indexify((p_dim, i)) for i in range(self.grid.dim)])
[ "def", "_coordinate_symbols", "(", "self", ")", ":", "p_dim", "=", "self", ".", "indices", "[", "-", "1", "]", "return", "tuple", "(", "[", "self", ".", "coordinates", ".", "indexify", "(", "(", "p_dim", ",", "i", ")", ")", "for", "i", "in", "range...
https://github.com/devitocodes/devito/blob/6abd441e3f5f091775ad332be6b95e017b8cbd16/devito/types/sparse.py#L563-L567
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/local_comp/smoothchar.py
python
SmoothCharacterGeneric.restrict_to_Qp
(self)
return G.character(self.level(), [self(x) for x in ugs])
r""" Return the restriction of this character to `\QQ_p^\times`, embedded as a subfield of `F^\times`. EXAMPLES:: sage: from sage.modular.local_comp.smoothchar import SmoothCharacterGroupRamifiedQuadratic sage: SmoothCharacterGroupRamifiedQuadratic(3, 0, QQ).character(0, [2]).restrict_to_Qp() Character of Q_3*, of level 0, mapping 3 |--> 4
r""" Return the restriction of this character to `\QQ_p^\times`, embedded as a subfield of `F^\times`.
[ "r", "Return", "the", "restriction", "of", "this", "character", "to", "\\", "QQ_p^", "\\", "times", "embedded", "as", "a", "subfield", "of", "F^", "\\", "times", "." ]
def restrict_to_Qp(self): r""" Return the restriction of this character to `\QQ_p^\times`, embedded as a subfield of `F^\times`. EXAMPLES:: sage: from sage.modular.local_comp.smoothchar import SmoothCharacterGroupRamifiedQuadratic sage: SmoothCharacterGroupRamifiedQuadratic(3, 0, QQ).character(0, [2]).restrict_to_Qp() Character of Q_3*, of level 0, mapping 3 |--> 4 """ G = SmoothCharacterGroupQp(self.parent().prime(), self.base_ring()) ugs = G.unit_gens(self.level()) return G.character(self.level(), [self(x) for x in ugs])
[ "def", "restrict_to_Qp", "(", "self", ")", ":", "G", "=", "SmoothCharacterGroupQp", "(", "self", ".", "parent", "(", ")", ".", "prime", "(", ")", ",", "self", ".", "base_ring", "(", ")", ")", "ugs", "=", "G", ".", "unit_gens", "(", "self", ".", "le...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/local_comp/smoothchar.py#L295-L308
google/macops
8442745359c0c941cd4e4e7d243e43bd16b40dec
gmacpyutil/gmacpyutil/profiles.py
python
Profile.Get
(self, key)
return self._profile.get(key)
[]
def Get(self, key): return self._profile.get(key)
[ "def", "Get", "(", "self", ",", "key", ")", ":", "return", "self", ".", "_profile", ".", "get", "(", "key", ")" ]
https://github.com/google/macops/blob/8442745359c0c941cd4e4e7d243e43bd16b40dec/gmacpyutil/gmacpyutil/profiles.py#L106-L107
wbond/asn1crypto
9ae350f212532dfee7f185f6b3eda24753249cf3
asn1crypto/_iri.py
python
_iri_utf8_errors_handler
(exc)
return (''.join(replacements), exc.end)
Error handler for decoding UTF-8 parts of a URI into an IRI. Leaves byte sequences encoded in %XX format, but as part of a unicode string. :param exc: The UnicodeDecodeError exception :return: A 2-element tuple of (replacement unicode string, integer index to resume at)
Error handler for decoding UTF-8 parts of a URI into an IRI. Leaves byte sequences encoded in %XX format, but as part of a unicode string.
[ "Error", "handler", "for", "decoding", "UTF", "-", "8", "parts", "of", "a", "URI", "into", "an", "IRI", ".", "Leaves", "byte", "sequences", "encoded", "in", "%XX", "format", "but", "as", "part", "of", "a", "unicode", "string", "." ]
def _iri_utf8_errors_handler(exc): """ Error handler for decoding UTF-8 parts of a URI into an IRI. Leaves byte sequences encoded in %XX format, but as part of a unicode string. :param exc: The UnicodeDecodeError exception :return: A 2-element tuple of (replacement unicode string, integer index to resume at) """ bytes_as_ints = bytes_to_list(exc.object[exc.start:exc.end]) replacements = ['%%%02x' % num for num in bytes_as_ints] return (''.join(replacements), exc.end)
[ "def", "_iri_utf8_errors_handler", "(", "exc", ")", ":", "bytes_as_ints", "=", "bytes_to_list", "(", "exc", ".", "object", "[", "exc", ".", "start", ":", "exc", ".", "end", "]", ")", "replacements", "=", "[", "'%%%02x'", "%", "num", "for", "num", "in", ...
https://github.com/wbond/asn1crypto/blob/9ae350f212532dfee7f185f6b3eda24753249cf3/asn1crypto/_iri.py#L172-L187
onnx/onnx-coreml
141fc33d7217674ea8bda36494fa8089a543a3f3
onnx_coreml/_operators.py
python
_convert_neg
(builder, node, graph, err)
[]
def _convert_neg(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None builder.add_elementwise( name=node.name, input_names=node.inputs, output_name=node.outputs[0], mode='MULTIPLY', alpha=-1.0 ) _update_shape_mapping_unchanged(node, graph, err)
[ "def", "_convert_neg", "(", "builder", ",", "node", ",", "graph", ",", "err", ")", ":", "# type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None", "builder", ".", "add_elementwise", "(", "name", "=", "node", ".", "name", ",", "input_names", "=", "node", ...
https://github.com/onnx/onnx-coreml/blob/141fc33d7217674ea8bda36494fa8089a543a3f3/onnx_coreml/_operators.py#L1554-L1562
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
static/deploy/openvino/python/transforms/seg_transforms.py
python
Compose.__call__
(self, im, im_info=None, label=None)
return outputs
Args: im (str/np.ndarray): 图像路径/图像np.ndarray数据。 im_info (list): 存储图像reisze或padding前的shape信息,如 [('resize', [200, 300]), ('padding', [400, 600])]表示 图像在过resize前shape为(200, 300), 过padding前shape为 (400, 600) label (str/np.ndarray): 标注图像路径/标注图像np.ndarray数据。 Returns: tuple: 根据网络所需字段所组成的tuple;字段由transforms中的最后一个数据预处理操作决定。
Args: im (str/np.ndarray): 图像路径/图像np.ndarray数据。 im_info (list): 存储图像reisze或padding前的shape信息,如 [('resize', [200, 300]), ('padding', [400, 600])]表示 图像在过resize前shape为(200, 300), 过padding前shape为 (400, 600) label (str/np.ndarray): 标注图像路径/标注图像np.ndarray数据。
[ "Args", ":", "im", "(", "str", "/", "np", ".", "ndarray", ")", ":", "图像路径", "/", "图像np", ".", "ndarray数据。", "im_info", "(", "list", ")", ":", "存储图像reisze或padding前的shape信息,如", "[", "(", "resize", "[", "200", "300", "]", ")", "(", "padding", "[", "400"...
def __call__(self, im, im_info=None, label=None): """ Args: im (str/np.ndarray): 图像路径/图像np.ndarray数据。 im_info (list): 存储图像reisze或padding前的shape信息,如 [('resize', [200, 300]), ('padding', [400, 600])]表示 图像在过resize前shape为(200, 300), 过padding前shape为 (400, 600) label (str/np.ndarray): 标注图像路径/标注图像np.ndarray数据。 Returns: tuple: 根据网络所需字段所组成的tuple;字段由transforms中的最后一个数据预处理操作决定。 """ im, label = self.decode_image(im, label) if self.to_rgb: im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) if im_info is None: im_info = [('origin_shape', im.shape[0:2])] if label is not None: origin_label = label.copy() for op in self.transforms: if isinstance(op, SegTransform): outputs = op(im, im_info, label) im = outputs[0] if len(outputs) >= 2: im_info = outputs[1] if len(outputs) == 3: label = outputs[2] else: im = execute_imgaug(op, im) if label is not None: outputs = (im, im_info, label) else: outputs = (im, im_info) if self.transforms[-1].__class__.__name__ == 'ArrangeSegmenter': if self.transforms[-1].mode == 'eval': if label is not None: outputs = (im, im_info, origin_label) return outputs
[ "def", "__call__", "(", "self", ",", "im", ",", "im_info", "=", "None", ",", "label", "=", "None", ")", ":", "im", ",", "label", "=", "self", ".", "decode_image", "(", "im", ",", "label", ")", "if", "self", ".", "to_rgb", ":", "im", "=", "cv2", ...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/static/deploy/openvino/python/transforms/seg_transforms.py#L113-L152
respeaker/get_started_with_respeaker
ec859759fcec7e683a5e09328a8ea307046f353d
files/usr/lib/python2.7/site-packages/sockjs/tornado/session.py
python
BaseSession.send_message
(self, msg, stats=True, binary=False)
Send or queue outgoing message `msg` Message to send `stats` If set to True, will update statistics after operation completes
Send or queue outgoing message
[ "Send", "or", "queue", "outgoing", "message" ]
def send_message(self, msg, stats=True, binary=False): """Send or queue outgoing message `msg` Message to send `stats` If set to True, will update statistics after operation completes """ raise NotImplemented()
[ "def", "send_message", "(", "self", ",", "msg", ",", "stats", "=", "True", ",", "binary", "=", "False", ")", ":", "raise", "NotImplemented", "(", ")" ]
https://github.com/respeaker/get_started_with_respeaker/blob/ec859759fcec7e683a5e09328a8ea307046f353d/files/usr/lib/python2.7/site-packages/sockjs/tornado/session.py#L177-L185
qntm/greenery
da23f57b737e19338777f4d327e58f95bb59556a
greenery/fsm.py
python
fsm.ispropersuperset
(self, other)
return self >= other and self != other
Treat `self` and `other` as sets of strings and see if `self` is a proper superset of `other`.
Treat `self` and `other` as sets of strings and see if `self` is a proper superset of `other`.
[ "Treat", "self", "and", "other", "as", "sets", "of", "strings", "and", "see", "if", "self", "is", "a", "proper", "superset", "of", "other", "." ]
def ispropersuperset(self, other): ''' Treat `self` and `other` as sets of strings and see if `self` is a proper superset of `other`. ''' return self >= other and self != other
[ "def", "ispropersuperset", "(", "self", ",", "other", ")", ":", "return", "self", ">=", "other", "and", "self", "!=", "other" ]
https://github.com/qntm/greenery/blob/da23f57b737e19338777f4d327e58f95bb59556a/greenery/fsm.py#L625-L630
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Axonius/Integrations/Axonius/Axonius.py
python
parse_key
(key: str)
return key
Parse fields into required format.
Parse fields into required format.
[ "Parse", "fields", "into", "required", "format", "." ]
def parse_key(key: str) -> str: """Parse fields into required format.""" if key.startswith("specific_data.data."): key = strip_left(obj=key, fix="specific_data.data.") key = f"aggregated_{key}" if key.startswith("adapters_data."): key = strip_left(obj=key, fix="adapters_data.") key = key.replace(".", "_") return key
[ "def", "parse_key", "(", "key", ":", "str", ")", "->", "str", ":", "if", "key", ".", "startswith", "(", "\"specific_data.data.\"", ")", ":", "key", "=", "strip_left", "(", "obj", "=", "key", ",", "fix", "=", "\"specific_data.data.\"", ")", "key", "=", ...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Axonius/Integrations/Axonius/Axonius.py#L70-L78
magenta/ddsp
8536a366c7834908f418a6721547268e8f2083cc
ddsp/training/ddsp_run.py
python
allow_memory_growth
()
Sets the GPUs to grow the memory usage as is needed by the process.
Sets the GPUs to grow the memory usage as is needed by the process.
[ "Sets", "the", "GPUs", "to", "grow", "the", "memory", "usage", "as", "is", "needed", "by", "the", "process", "." ]
def allow_memory_growth(): """Sets the GPUs to grow the memory usage as is needed by the process.""" gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: # Currently, memory growth needs to be the same across GPUs. for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) except RuntimeError as e: # Memory growth must be set before GPUs have been initialized. print(e)
[ "def", "allow_memory_growth", "(", ")", ":", "gpus", "=", "tf", ".", "config", ".", "experimental", ".", "list_physical_devices", "(", "'GPU'", ")", "if", "gpus", ":", "try", ":", "# Currently, memory growth needs to be the same across GPUs.", "for", "gpu", "in", ...
https://github.com/magenta/ddsp/blob/8536a366c7834908f418a6721547268e8f2083cc/ddsp/training/ddsp_run.py#L161-L171
timonwong/OmniMarkupPreviewer
21921ac7a99d2b5924a2219b33679a5b53621392
OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver2.py
python
HTTPServer.stop
(self)
Gracefully shutdown a server that is serving forever.
Gracefully shutdown a server that is serving forever.
[ "Gracefully", "shutdown", "a", "server", "that", "is", "serving", "forever", "." ]
def stop(self): """Gracefully shutdown a server that is serving forever.""" self.ready = False if self._start_time is not None: self._run_time += (time.time() - self._start_time) self._start_time = None sock = getattr(self, "socket", None) if sock: if not isinstance(self.bind_addr, basestring): # Touch our own socket to make accept() return immediately. try: host, port = sock.getsockname()[:2] except socket.error: x = sys.exc_info()[1] if x.args[0] not in socket_errors_to_ignore: # Changed to use error code and not message # See https://bitbucket.org/cherrypy/cherrypy/issue/860. raise else: # Note that we're explicitly NOT using AI_PASSIVE, # here, because we want an actual IP to touch. # localhost won't work if we've bound to a public IP, # but it will if we bound to '0.0.0.0' (INADDR_ANY). for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res s = None try: s = socket.socket(af, socktype, proto) # See http://groups.google.com/group/cherrypy-users/ # browse_frm/thread/bbfe5eb39c904fe0 s.settimeout(1.0) s.connect((host, port)) s.close() except socket.error: if s: s.close() if hasattr(sock, "close"): sock.close() self.socket = None self.requests.stop(self.shutdown_timeout)
[ "def", "stop", "(", "self", ")", ":", "self", ".", "ready", "=", "False", "if", "self", ".", "_start_time", "is", "not", "None", ":", "self", ".", "_run_time", "+=", "(", "time", ".", "time", "(", ")", "-", "self", ".", "_start_time", ")", "self", ...
https://github.com/timonwong/OmniMarkupPreviewer/blob/21921ac7a99d2b5924a2219b33679a5b53621392/OmniMarkupLib/libs/cherrypy/wsgiserver/wsgiserver2.py#L2017-L2059
avrae/avrae
6ebe46a1ec3d4dfaa2f9b18fac948325f39f87de
ddb/dice/tree.py
python
RollContext.from_character
(cls, character)
return cls(character.upstream_id, 'character', character.name, character.image)
Returns a context associated with a DDB character.
Returns a context associated with a DDB character.
[ "Returns", "a", "context", "associated", "with", "a", "DDB", "character", "." ]
def from_character(cls, character): """Returns a context associated with a DDB character.""" return cls(character.upstream_id, 'character', character.name, character.image)
[ "def", "from_character", "(", "cls", ",", "character", ")", ":", "return", "cls", "(", "character", ".", "upstream_id", ",", "'character'", ",", "character", ".", "name", ",", "character", ".", "image", ")" ]
https://github.com/avrae/avrae/blob/6ebe46a1ec3d4dfaa2f9b18fac948325f39f87de/ddb/dice/tree.py#L87-L89
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/caldav/datastore/sql.py
python
Calendar.updateShareeGroupLink
(self, groupUID, mode=None)
update schema.GROUP_SHAREE
update schema.GROUP_SHAREE
[ "update", "schema", ".", "GROUP_SHAREE" ]
def updateShareeGroupLink(self, groupUID, mode=None): """ update schema.GROUP_SHAREE """ changed = False group = yield self._txn.groupByUID(groupUID) gs = schema.GROUP_SHAREE rows = yield Select( [gs.MEMBERSHIP_HASH, gs.GROUP_BIND_MODE], From=gs, Where=(gs.CALENDAR_ID == self._resourceID).And( gs.GROUP_ID == group.groupID) ).on(self._txn) if rows: [[gsMembershipHash, gsMode]] = rows updateMap = {} if gsMembershipHash != group.membershipHash: updateMap[gs.MEMBERSHIP_HASH] = group.membershipHash if mode is not None and gsMode != mode: updateMap[gs.GROUP_BIND_MODE] = mode if updateMap: yield Update( updateMap, Where=(gs.CALENDAR_ID == self._resourceID).And( gs.GROUP_ID == group.groupID ) ).on(self._txn) changed = True else: yield Insert({ gs.MEMBERSHIP_HASH: group.membershipHash, gs.GROUP_BIND_MODE: mode, gs.CALENDAR_ID: self._resourceID, gs.GROUP_ID: group.groupID, }).on(self._txn) changed = True returnValue(changed)
[ "def", "updateShareeGroupLink", "(", "self", ",", "groupUID", ",", "mode", "=", "None", ")", ":", "changed", "=", "False", "group", "=", "yield", "self", ".", "_txn", ".", "groupByUID", "(", "groupUID", ")", "gs", "=", "schema", ".", "GROUP_SHAREE", "row...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/caldav/datastore/sql.py#L2270-L2308
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex/ppdet/data/source/category.py
python
_visdrone_category
()
return clsid2catid, catid2name
[]
def _visdrone_category(): clsid2catid = {i: i for i in range(10)} catid2name = { 0: 'pedestrian', 1: 'people', 2: 'bicycle', 3: 'car', 4: 'van', 5: 'truck', 6: 'tricycle', 7: 'awning-tricycle', 8: 'bus', 9: 'motor' } return clsid2catid, catid2name
[ "def", "_visdrone_category", "(", ")", ":", "clsid2catid", "=", "{", "i", ":", "i", "for", "i", "in", "range", "(", "10", ")", "}", "catid2name", "=", "{", "0", ":", "'pedestrian'", ",", "1", ":", "'people'", ",", "2", ":", "'bicycle'", ",", "3", ...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/ppdet/data/source/category.py#L889-L904
CoinCheung/BiSeNet
f9231b7c971413e6ebdfcd961fbea53417b18851
old/model.py
python
SpatialPath.init_weight
(self)
[]
def init_weight(self): for ly in self.children(): if isinstance(ly, nn.Conv2d): nn.init.kaiming_normal_(ly.weight, a=1) if not ly.bias is None: nn.init.constant_(ly.bias, 0)
[ "def", "init_weight", "(", "self", ")", ":", "for", "ly", "in", "self", ".", "children", "(", ")", ":", "if", "isinstance", "(", "ly", ",", "nn", ".", "Conv2d", ")", ":", "nn", ".", "init", ".", "kaiming_normal_", "(", "ly", ".", "weight", ",", "...
https://github.com/CoinCheung/BiSeNet/blob/f9231b7c971413e6ebdfcd961fbea53417b18851/old/model.py#L162-L166
okigan/awscurl
ea2a9b192e80053a4edf7dbfe7b390e249a92527
awscurl/awscurl.py
python
inner_main
(argv)
return 0
Awscurl CLI main entry point
Awscurl CLI main entry point
[ "Awscurl", "CLI", "main", "entry", "point" ]
def inner_main(argv): """ Awscurl CLI main entry point """ # note EC2 ignores Accept header and responds in xml default_headers = ['Accept: application/xml', 'Content-Type: application/json'] parser = configargparse.ArgumentParser( description='Curl AWS request signing', formatter_class=configargparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('-v', '--verbose', action='store_true', help='verbose flag', default=False) parser.add_argument('-i', '--include', action='store_true', help='include headers in the output', default=False) parser.add_argument('-X', '--request', help='Specify request command to use', default='GET') parser.add_argument('-d', '--data', help='HTTP POST data', default='') parser.add_argument('-H', '--header', help='HTTP header', action='append') parser.add_argument('-k', '--insecure', action='store_true', default=False, help='Allow insecure server connections when using SSL') parser.add_argument('--data-binary', action='store_true', help='Process HTTP POST data exactly as specified with ' 'no extra processing whatsoever.', default=False) parser.add_argument('--region', help='AWS region', default='us-east-1', env_var='AWS_DEFAULT_REGION') parser.add_argument('--profile', help='AWS profile', default='default', env_var='AWS_PROFILE') parser.add_argument('--service', help='AWS service', default='execute-api') parser.add_argument('--access_key', env_var='AWS_ACCESS_KEY_ID') parser.add_argument('--secret_key', env_var='AWS_SECRET_ACCESS_KEY') # AWS_SECURITY_TOKEN is deprecated, but kept for backward compatibility # https://github.com/boto/botocore/blob/c76553d3158b083d818f88c898d8f6d7918478fd/botocore/credentials.py#L260-262 parser.add_argument('--security_token', env_var='AWS_SECURITY_TOKEN') parser.add_argument('--session_token', env_var='AWS_SESSION_TOKEN') parser.add_argument('-L', '--location', action='store_true', default=False, help="Follow redirects") parser.add_argument('uri') args = parser.parse_args(argv) # pylint: disable=global-statement global IS_VERBOSE IS_VERBOSE = args.verbose if args.verbose: __log(vars(args)) data = args.data if data is not None and data.startswith("@"): filename = data[1:] with open(filename, "r") as post_data_file: data = post_data_file.read() if args.header is None: args.header = default_headers if args.security_token is not None: args.session_token = args.security_token del args.security_token # pylint: disable=deprecated-lambda headers = {k: v for (k, v) in map(lambda s: s.split(": "), args.header)} headers = CaseInsensitiveDict(headers) credentials_path = os.path.expanduser("~") + "/.aws/credentials" args.access_key, args.secret_key, args.session_token = load_aws_config(args.access_key, args.secret_key, args.session_token, credentials_path, args.profile) if args.access_key is None: raise ValueError('No access key is available') if args.secret_key is None: raise ValueError('No secret key is available') response = make_request(args.request, args.service, args.region, args.uri, headers, data, args.access_key, args.secret_key, args.session_token, args.data_binary, verify=not args.insecure, allow_redirects=args.location) if args.include or IS_VERBOSE: print(response.headers, end='\n\n') print(response.text) response.raise_for_status() return 0
[ "def", "inner_main", "(", "argv", ")", ":", "# note EC2 ignores Accept header and responds in xml", "default_headers", "=", "[", "'Accept: application/xml'", ",", "'Content-Type: application/json'", "]", "parser", "=", "configargparse", ".", "ArgumentParser", "(", "descriptio...
https://github.com/okigan/awscurl/blob/ea2a9b192e80053a4edf7dbfe7b390e249a92527/awscurl/awscurl.py#L415-L517
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/polys/subresultants_qq_zz.py
python
row2poly
(row, deg, x)
return Poly(poly, x)
Converts the row of a matrix to a poly of degree deg and variable x. Some entries at the beginning and/or at the end of the row may be zero.
Converts the row of a matrix to a poly of degree deg and variable x. Some entries at the beginning and/or at the end of the row may be zero.
[ "Converts", "the", "row", "of", "a", "matrix", "to", "a", "poly", "of", "degree", "deg", "and", "variable", "x", ".", "Some", "entries", "at", "the", "beginning", "and", "/", "or", "at", "the", "end", "of", "the", "row", "may", "be", "zero", "." ]
def row2poly(row, deg, x): ''' Converts the row of a matrix to a poly of degree deg and variable x. Some entries at the beginning and/or at the end of the row may be zero. ''' k = 0 poly = [] leng = len(row) # find the beginning of the poly ; i.e. the first # non-zero element of the row while row[k] == 0: k = k + 1 # append the next deg + 1 elements to poly for j in range( deg + 1): if k + j <= leng: poly.append(row[k + j]) return Poly(poly, x)
[ "def", "row2poly", "(", "row", ",", "deg", ",", "x", ")", ":", "k", "=", "0", "poly", "=", "[", "]", "leng", "=", "len", "(", "row", ")", "# find the beginning of the poly ; i.e. the first", "# non-zero element of the row", "while", "row", "[", "k", "]", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/polys/subresultants_qq_zz.py#L2207-L2227
shazow/workerpool
2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5
workerpool/pools.py
python
WorkerPool.grow
(self)
Add another worker to the pool.
Add another worker to the pool.
[ "Add", "another", "worker", "to", "the", "pool", "." ]
def grow(self): "Add another worker to the pool." t = self.worker_factory(self) t.start() self._size += 1
[ "def", "grow", "(", "self", ")", ":", "t", "=", "self", ".", "worker_factory", "(", "self", ")", "t", ".", "start", "(", ")", "self", ".", "_size", "+=", "1" ]
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/pools.py#L66-L70
tensorflow/lattice
784eca50cbdfedf39f183cc7d298c9fe376b69c0
tensorflow_lattice/python/premade_lib.py
python
_verify_prefitting_model
(prefitting_model, feature_names)
Checks that prefitting_model has the proper input layer.
Checks that prefitting_model has the proper input layer.
[ "Checks", "that", "prefitting_model", "has", "the", "proper", "input", "layer", "." ]
def _verify_prefitting_model(prefitting_model, feature_names): """Checks that prefitting_model has the proper input layer.""" if isinstance(prefitting_model, tf.keras.Model): layer_names = [layer.name for layer in prefitting_model.layers] elif isinstance(prefitting_model, tf.estimator.Estimator): layer_names = prefitting_model.get_variable_names() else: raise ValueError('Invalid model type for prefitting_model: {}'.format( type(prefitting_model))) for feature_name in feature_names: if isinstance(prefitting_model, tf.keras.Model): input_layer_name = '{}_{}'.format(INPUT_LAYER_NAME, feature_name) if input_layer_name not in layer_names: raise ValueError( 'prefitting_model does not match prefitting_model_config. Make ' 'sure that prefitting_model is the proper type and constructed ' 'from the prefitting_model_config: {}'.format( type(prefitting_model))) else: pwl_input_layer_name = '{}_{}/{}'.format( CALIB_LAYER_NAME, feature_name, pwl_calibration_layer.PWL_CALIBRATION_KERNEL_NAME) cat_input_layer_name = '{}_{}/{}'.format( CALIB_LAYER_NAME, feature_name, categorical_calibration_layer.CATEGORICAL_CALIBRATION_KERNEL_NAME) if (pwl_input_layer_name not in layer_names and cat_input_layer_name not in layer_names): raise ValueError( 'prefitting_model does not match prefitting_model_config. Make ' 'sure that prefitting_model is the proper type and constructed ' 'from the prefitting_model_config: {}'.format( type(prefitting_model)))
[ "def", "_verify_prefitting_model", "(", "prefitting_model", ",", "feature_names", ")", ":", "if", "isinstance", "(", "prefitting_model", ",", "tf", ".", "keras", ".", "Model", ")", ":", "layer_names", "=", "[", "layer", ".", "name", "for", "layer", "in", "pr...
https://github.com/tensorflow/lattice/blob/784eca50cbdfedf39f183cc7d298c9fe376b69c0/tensorflow_lattice/python/premade_lib.py#L1068-L1099
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/Babel-0.9.6-py2.7.egg/babel/messages/catalog.py
python
Catalog._key_for
(self, id)
return key
The key for a message is just the singular ID even for pluralizable messages.
The key for a message is just the singular ID even for pluralizable messages.
[ "The", "key", "for", "a", "message", "is", "just", "the", "singular", "ID", "even", "for", "pluralizable", "messages", "." ]
def _key_for(self, id): """The key for a message is just the singular ID even for pluralizable messages. """ key = id if isinstance(key, (list, tuple)): key = id[0] return key
[ "def", "_key_for", "(", "self", ",", "id", ")", ":", "key", "=", "id", "if", "isinstance", "(", "key", ",", "(", "list", ",", "tuple", ")", ")", ":", "key", "=", "id", "[", "0", "]", "return", "key" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/Babel-0.9.6-py2.7.egg/babel/messages/catalog.py#L761-L768
marshmallow-code/django-rest-marshmallow
117f89bd5f06de6049dd51d4705d0ccafcc351d7
setup.py
python
get_packages
(package)
return [dirpath for dirpath, dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, '__init__.py'))]
Return root package and all sub-packages.
Return root package and all sub-packages.
[ "Return", "root", "package", "and", "all", "sub", "-", "packages", "." ]
def get_packages(package): """ Return root package and all sub-packages. """ return [dirpath for dirpath, dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, '__init__.py'))]
[ "def", "get_packages", "(", "package", ")", ":", "return", "[", "dirpath", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "package", ")", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join",...
https://github.com/marshmallow-code/django-rest-marshmallow/blob/117f89bd5f06de6049dd51d4705d0ccafcc351d7/setup.py#L29-L35
ChenglongChen/tensorflow-XNN
6534a832f5b4461cbdf1ebbdf5620a0cd80f0aa9
code/nn_module.py
python
word_dropout
(x, training, dropout=0, seed=0)
return x
tf.layers.Dropout doesn't work as it can't switch training or inference
tf.layers.Dropout doesn't work as it can't switch training or inference
[ "tf", ".", "layers", ".", "Dropout", "doesn", "t", "work", "as", "it", "can", "t", "switch", "training", "or", "inference" ]
def word_dropout(x, training, dropout=0, seed=0): # word dropout (dropout the entire embedding for some words) """ tf.layers.Dropout doesn't work as it can't switch training or inference """ if dropout > 0: input_shape = tf.shape(x) noise_shape = [input_shape[0], input_shape[1], 1] x = tf.layers.Dropout(rate=dropout, noise_shape=noise_shape, seed=seed)(x, training=training) return x
[ "def", "word_dropout", "(", "x", ",", "training", ",", "dropout", "=", "0", ",", "seed", "=", "0", ")", ":", "# word dropout (dropout the entire embedding for some words)", "if", "dropout", ">", "0", ":", "input_shape", "=", "tf", ".", "shape", "(", "x", ")"...
https://github.com/ChenglongChen/tensorflow-XNN/blob/6534a832f5b4461cbdf1ebbdf5620a0cd80f0aa9/code/nn_module.py#L52-L61
c-w/gutenberg
df8fcfab87e9d8f5b97bb44857beb9af5eb9e96c
gutenberg/acquire/metadata.py
python
MetadataCache._download_metadata_archive
(self)
Makes a remote call to the Project Gutenberg servers and downloads the entire Project Gutenberg meta-data catalog. The catalog describes the texts on Project Gutenberg in RDF. The function returns a file-pointer to the catalog.
Makes a remote call to the Project Gutenberg servers and downloads the entire Project Gutenberg meta-data catalog. The catalog describes the texts on Project Gutenberg in RDF. The function returns a file-pointer to the catalog.
[ "Makes", "a", "remote", "call", "to", "the", "Project", "Gutenberg", "servers", "and", "downloads", "the", "entire", "Project", "Gutenberg", "meta", "-", "data", "catalog", ".", "The", "catalog", "describes", "the", "texts", "on", "Project", "Gutenberg", "in",...
def _download_metadata_archive(self): """Makes a remote call to the Project Gutenberg servers and downloads the entire Project Gutenberg meta-data catalog. The catalog describes the texts on Project Gutenberg in RDF. The function returns a file-pointer to the catalog. """ with tempfile.NamedTemporaryFile(delete=False) as metadata_archive: shutil.copyfileobj(urlopen(self.catalog_source), metadata_archive) yield metadata_archive.name remove(metadata_archive.name)
[ "def", "_download_metadata_archive", "(", "self", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "as", "metadata_archive", ":", "shutil", ".", "copyfileobj", "(", "urlopen", "(", "self", ".", "catalog_source", ")", "...
https://github.com/c-w/gutenberg/blob/df8fcfab87e9d8f5b97bb44857beb9af5eb9e96c/gutenberg/acquire/metadata.py#L138-L148
rll/rllab
ba78e4c16dc492982e648f117875b22af3965579
rllab/distributions/recurrent_categorical.py
python
RecurrentCategorical.kl
(self, old_dist_info, new_dist_info)
return np.sum( old_prob * (np.log(old_prob + TINY) - np.log(new_prob + TINY)), axis=2 )
Compute the KL divergence of two categorical distributions
Compute the KL divergence of two categorical distributions
[ "Compute", "the", "KL", "divergence", "of", "two", "categorical", "distributions" ]
def kl(self, old_dist_info, new_dist_info): """ Compute the KL divergence of two categorical distributions """ old_prob = old_dist_info["prob"] new_prob = new_dist_info["prob"] return np.sum( old_prob * (np.log(old_prob + TINY) - np.log(new_prob + TINY)), axis=2 )
[ "def", "kl", "(", "self", ",", "old_dist_info", ",", "new_dist_info", ")", ":", "old_prob", "=", "old_dist_info", "[", "\"prob\"", "]", "new_prob", "=", "new_dist_info", "[", "\"prob\"", "]", "return", "np", ".", "sum", "(", "old_prob", "*", "(", "np", "...
https://github.com/rll/rllab/blob/ba78e4c16dc492982e648f117875b22af3965579/rllab/distributions/recurrent_categorical.py#L31-L40
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/utils/Utils.py
python
getUserName
()
return pwd.getpwuid(os.getuid())[0]
Return the user name. Notes: Currently doesn't work on Windows.
Return the user name.
[ "Return", "the", "user", "name", "." ]
def getUserName(): """Return the user name. Notes: Currently doesn't work on Windows. """ import pwd # pylint: disable=I0021,import-error return pwd.getpwuid(os.getuid())[0]
[ "def", "getUserName", "(", ")", ":", "import", "pwd", "# pylint: disable=I0021,import-error", "return", "pwd", ".", "getpwuid", "(", "os", ".", "getuid", "(", ")", ")", "[", "0", "]" ]
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/utils/Utils.py#L230-L237
suavecode/SUAVE
4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5
trunk/SUAVE/Methods/Geometry/Three_Dimensional/compute_span_location_from_chord_length.py
python
compute_span_location_from_chord_length
(wing,chord_length)
return span_location
Computes the location along the half-span given a chord length. Assumptions: Linear variation of chord with span. Returns 0 if constant chord wing. Source: None Inputs: wing.chords. root [m] tip [m] wing.spans.projected [m] chord_length [m] Outputs: span_location [m] Properties Used: N/A
Computes the location along the half-span given a chord length.
[ "Computes", "the", "location", "along", "the", "half", "-", "span", "given", "a", "chord", "length", "." ]
def compute_span_location_from_chord_length(wing,chord_length): """Computes the location along the half-span given a chord length. Assumptions: Linear variation of chord with span. Returns 0 if constant chord wing. Source: None Inputs: wing.chords. root [m] tip [m] wing.spans.projected [m] chord_length [m] Outputs: span_location [m] Properties Used: N/A """ #unpack ct = wing.chords.tip cr = wing.chords.root b = wing.spans.projected b_2 = b/2. if (cr-ct)==0: span_location = 0. else: span_location = b_2*(1-(chord_length-ct)/(cr-ct)) return span_location
[ "def", "compute_span_location_from_chord_length", "(", "wing", ",", "chord_length", ")", ":", "#unpack", "ct", "=", "wing", ".", "chords", ".", "tip", "cr", "=", "wing", ".", "chords", ".", "root", "b", "=", "wing", ".", "spans", ".", "projected", "b_2", ...
https://github.com/suavecode/SUAVE/blob/4f83c467c5662b6cc611ce2ab6c0bdd25fd5c0a5/trunk/SUAVE/Methods/Geometry/Three_Dimensional/compute_span_location_from_chord_length.py#L13-L49
kexinyi/ns-vqa
df357618af224723acffb66a17ce3e94298642a7
scene_parse/mask_rcnn/lib/utils/resnet_weights_helper.py
python
convert_state_dict
(src_dict)
return dst_dict
Return the correct mapping of tensor name and value Mapping from the names of torchvision model to our resnet conv_body and box_head.
Return the correct mapping of tensor name and value
[ "Return", "the", "correct", "mapping", "of", "tensor", "name", "and", "value" ]
def convert_state_dict(src_dict): """Return the correct mapping of tensor name and value Mapping from the names of torchvision model to our resnet conv_body and box_head. """ dst_dict = {} for k, v in src_dict.items(): toks = k.split('.') if k.startswith('layer'): assert len(toks[0]) == 6 res_id = int(toks[0][5]) + 1 name = '.'.join(['res%d' % res_id] + toks[1:]) dst_dict[name] = v elif k.startswith('fc'): continue else: name = '.'.join(['res1'] + toks) dst_dict[name] = v return dst_dict
[ "def", "convert_state_dict", "(", "src_dict", ")", ":", "dst_dict", "=", "{", "}", "for", "k", ",", "v", "in", "src_dict", ".", "items", "(", ")", ":", "toks", "=", "k", ".", "split", "(", "'.'", ")", "if", "k", ".", "startswith", "(", "'layer'", ...
https://github.com/kexinyi/ns-vqa/blob/df357618af224723acffb66a17ce3e94298642a7/scene_parse/mask_rcnn/lib/utils/resnet_weights_helper.py#L67-L85
mongodb/docs
03c2e030a97da6a818dab6e1b3e5301cb0f8eb43
bin/archive/errorcodes.py
python
genErrorOutput
()
Sort and iterate through codes printing out error codes and messages in RST format.
Sort and iterate through codes printing out error codes and messages in RST format.
[ "Sort", "and", "iterate", "through", "codes", "printing", "out", "error", "codes", "and", "messages", "in", "RST", "format", "." ]
def genErrorOutput(): """Sort and iterate through codes printing out error codes and messages in RST format.""" sys.stderr.write("Generating RST files\n"); separatefiles = False if errorsFormat == 'single': errorsrst = resultsRoot + "/errors.txt" if os.path.exists(errorsrst ): i = open(errorsrst , "r" ) out = open( errorsrst , 'wb' ) sys.stderr.write("Generating single file: {}\n".format(errorsrst)) titleLen = len(errorsTitle) out.write(":orphan:\n") out.write("=" * titleLen + "\n") out.write(errorsTitle + "\n") out.write("=" * titleLen + "\n") out.write(default_domain); elif errorsFormat == 'separate': separatefiles = True else: raise Exception("Unknown output format: {}".format(errorsFormat)) prev = "" seen = {} sourcerootOffset = len(sourceroot) stripChars = " " + "\n" # codes.sort( key=lambda x: x[0]+"-"+x[3] ) codes.sort( key=lambda x: int(x[3]) ) for f,l,line,num,message,severity in codes: if num in seen: continue seen[num] = True if f.startswith(sourceroot): f = f[sourcerootOffset+1:] fn = f.rpartition("/")[2] url = ":source:`" + f + "#L" + str(l) + "`" if separatefiles: outputFile = "{}/{:d}.txt".format(resultsRoot,int(num)) out = open(outputFile, 'wb') out.write(default_domain) sys.stderr.write("Generating file: {}\n".format(outputFile)) out.write(".. line: {}\n\n".format(line.strip(stripChars))) out.write(".. error:: {}\n\n".format(num)) if message != '': out.write(" :message: {}\n".format(message.strip(stripChars))) else: message = getBestMessage(line,str(num)).strip(stripChars) if message != '': out.write(" :message: {}\n".format(message)) if severity: if severity in severityTexts: out.write(" :severity: {}\n".format(severityTexts[severity])) elif severity in exceptionTexts: out.write(" :throws: {}\n".format(exceptionTexts[severity])) else: out.write(" :severity: {}\n".format(severity)) out.write(" :module: {}\n".format(url) ) if separatefiles: out.write("\n") out.close() if separatefiles==False: out.write( "\n" ) out.close()
[ "def", "genErrorOutput", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"Generating RST files\\n\"", ")", "separatefiles", "=", "False", "if", "errorsFormat", "==", "'single'", ":", "errorsrst", "=", "resultsRoot", "+", "\"/errors.txt\"", "if", "os", ...
https://github.com/mongodb/docs/blob/03c2e030a97da6a818dab6e1b3e5301cb0f8eb43/bin/archive/errorcodes.py#L250-L318
kovidgoyal/calibre
2b41671370f2a9eb1109b9ae901ccf915f1bd0c8
src/calibre/devices/errors.py
python
OpenFeedback.custom_dialog
(self, parent)
If you need to show the user a custom dialog, instead of just displaying the feedback_msg, create and return it here.
If you need to show the user a custom dialog, instead of just displaying the feedback_msg, create and return it here.
[ "If", "you", "need", "to", "show", "the", "user", "a", "custom", "dialog", "instead", "of", "just", "displaying", "the", "feedback_msg", "create", "and", "return", "it", "here", "." ]
def custom_dialog(self, parent): ''' If you need to show the user a custom dialog, instead of just displaying the feedback_msg, create and return it here. ''' raise NotImplementedError()
[ "def", "custom_dialog", "(", "self", ",", "parent", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/kovidgoyal/calibre/blob/2b41671370f2a9eb1109b9ae901ccf915f1bd0c8/src/calibre/devices/errors.py#L55-L60
odlgroup/odl
0b088df8dc4621c68b9414c3deff9127f4c4f11d
odl/diagnostics/space.py
python
SpaceTest._lincomb
(self)
Verify linear combination.
Verify linear combination.
[ "Verify", "linear", "combination", "." ]
def _lincomb(self): """Verify linear combination.""" self.log('\nTesting lincomb') self._lincomb_aliased()
[ "def", "_lincomb", "(", "self", ")", ":", "self", ".", "log", "(", "'\\nTesting lincomb'", ")", "self", ".", "_lincomb_aliased", "(", ")" ]
https://github.com/odlgroup/odl/blob/0b088df8dc4621c68b9414c3deff9127f4c4f11d/odl/diagnostics/space.py#L325-L328
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
libs/CodernityDB/database.py
python
Database._compact_indexes
(self)
Runs compact on all indexes
Runs compact on all indexes
[ "Runs", "compact", "on", "all", "indexes" ]
def _compact_indexes(self): """ Runs compact on all indexes """ for index in self.indexes: self.compact_index(index)
[ "def", "_compact_indexes", "(", "self", ")", ":", "for", "index", "in", "self", ".", "indexes", ":", "self", ".", "compact_index", "(", "index", ")" ]
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/libs/CodernityDB/database.py#L813-L818
google/trax
d6cae2067dedd0490b78d831033607357e975015
trax/rl/actor_critic_joint.py
python
ActorCriticJointAgent.train_epoch
(self)
Trains RL for one epoch.
Trains RL for one epoch.
[ "Trains", "RL", "for", "one", "epoch", "." ]
def train_epoch(self): """Trains RL for one epoch.""" n_evals = rl_training.remaining_evals( self._trainer.step, self._epoch, self._train_steps_per_epoch, self._supervised_evals_per_epoch) for _ in range(n_evals): self._trainer.train_epoch( self._train_steps_per_epoch // self._supervised_evals_per_epoch, self._supervised_eval_steps)
[ "def", "train_epoch", "(", "self", ")", ":", "n_evals", "=", "rl_training", ".", "remaining_evals", "(", "self", ".", "_trainer", ".", "step", ",", "self", ".", "_epoch", ",", "self", ".", "_train_steps_per_epoch", ",", "self", ".", "_supervised_evals_per_epoc...
https://github.com/google/trax/blob/d6cae2067dedd0490b78d831033607357e975015/trax/rl/actor_critic_joint.py#L196-L206
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/pysaml2-4.9.0/src/saml2/ident.py
python
IdentDB.handle_name_id_mapping_request
(self, name_id, name_id_policy)
return self.construct_nameid(_id, name_id_policy=name_id_policy)
:param name_id: The NameID that specifies the principal :param name_id_policy: The NameIDPolicy of the requester :return: If an old name_id exists that match the name-id policy that is return otherwise if a new one can be created it will be and returned. If no old matching exists and a new is not allowed to be created None is returned.
[]
def handle_name_id_mapping_request(self, name_id, name_id_policy): """ :param name_id: The NameID that specifies the principal :param name_id_policy: The NameIDPolicy of the requester :return: If an old name_id exists that match the name-id policy that is return otherwise if a new one can be created it will be and returned. If no old matching exists and a new is not allowed to be created None is returned. """ _id = self.find_local_id(name_id) if not _id: raise Unknown("Unknown entity") # return an old one if present for val in self.db[_id].split(" "): _nid = decode(val) if _nid.format == name_id_policy.format: if _nid.sp_name_qualifier == name_id_policy.sp_name_qualifier: return _nid if name_id_policy.allow_create == "false": raise PolicyError("Not allowed to create new identifier") # else create and return a new one return self.construct_nameid(_id, name_id_policy=name_id_policy)
[ "def", "handle_name_id_mapping_request", "(", "self", ",", "name_id", ",", "name_id_policy", ")", ":", "_id", "=", "self", ".", "find_local_id", "(", "name_id", ")", "if", "not", "_id", ":", "raise", "Unknown", "(", "\"Unknown entity\"", ")", "# return an old on...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/pysaml2-4.9.0/src/saml2/ident.py#L322-L347
iopsgroup/imoocc
de810eb6d4c1697b7139305925a5b0ba21225f3f
scanhosts/modules/paramiko_old/sftp_attr.py
python
SFTPAttributes.__init__
(self)
Create a new (empty) SFTPAttributes object. All fields will be empty.
Create a new (empty) SFTPAttributes object. All fields will be empty.
[ "Create", "a", "new", "(", "empty", ")", "SFTPAttributes", "object", ".", "All", "fields", "will", "be", "empty", "." ]
def __init__(self): """ Create a new (empty) SFTPAttributes object. All fields will be empty. """ self._flags = 0 self.st_size = None self.st_uid = None self.st_gid = None self.st_mode = None self.st_atime = None self.st_mtime = None self.attr = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_flags", "=", "0", "self", ".", "st_size", "=", "None", "self", ".", "st_uid", "=", "None", "self", ".", "st_gid", "=", "None", "self", ".", "st_mode", "=", "None", "self", ".", "st_atime", "=...
https://github.com/iopsgroup/imoocc/blob/de810eb6d4c1697b7139305925a5b0ba21225f3f/scanhosts/modules/paramiko_old/sftp_attr.py#L49-L60
DLR-RM/BlenderProc
e04e03f34b66702bbca45d1ac701599b6d764609
blenderproc/python/modules/utility/ConfigParser.py
python
ConfigParser._show_help
(self)
Print out help message which describes the placeholders that are used in the given config file
Print out help message which describes the placeholders that are used in the given config file
[ "Print", "out", "help", "message", "which", "describes", "the", "placeholders", "that", "are", "used", "in", "the", "given", "config", "file" ]
def _show_help(self): """ Print out help message which describes the placeholders that are used in the given config file """ self._print_placeholders(self.placeholders, {PlaceholderTypes.ARG: "Arguments:", PlaceholderTypes.ENV: "Environment variables:"})
[ "def", "_show_help", "(", "self", ")", ":", "self", ".", "_print_placeholders", "(", "self", ".", "placeholders", ",", "{", "PlaceholderTypes", ".", "ARG", ":", "\"Arguments:\"", ",", "PlaceholderTypes", ".", "ENV", ":", "\"Environment variables:\"", "}", ")" ]
https://github.com/DLR-RM/BlenderProc/blob/e04e03f34b66702bbca45d1ac701599b6d764609/blenderproc/python/modules/utility/ConfigParser.py#L117-L119
isl-org/MultiObjectiveOptimization
d45eb262ec61c0dafecebfb69027ff6de280dbb3
multi_task/loaders/celeba_loader.py
python
CELEBA.__getitem__
(self, index)
return [img] + label
__getitem__ :param index:
__getitem__
[ "__getitem__" ]
def __getitem__(self, index): """__getitem__ :param index: """ img_path = self.files[self.split][index].rstrip() label = self.labels[self.split][index] img = m.imread(img_path) if self.augmentations is not None: img = self.augmentations(np.array(img, dtype=np.uint8)) if self.is_transform: img = self.transform_img(img) return [img] + label
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "img_path", "=", "self", ".", "files", "[", "self", ".", "split", "]", "[", "index", "]", ".", "rstrip", "(", ")", "label", "=", "self", ".", "labels", "[", "self", ".", "split", "]", "["...
https://github.com/isl-org/MultiObjectiveOptimization/blob/d45eb262ec61c0dafecebfb69027ff6de280dbb3/multi_task/loaders/celeba_loader.py#L71-L86
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/lib2to3/pgen2/conv.py
python
Converter.run
(self, graminit_h, graminit_c)
Load the grammar tables from the text files written by pgen.
Load the grammar tables from the text files written by pgen.
[ "Load", "the", "grammar", "tables", "from", "the", "text", "files", "written", "by", "pgen", "." ]
def run(self, graminit_h, graminit_c): """Load the grammar tables from the text files written by pgen.""" self.parse_graminit_h(graminit_h) self.parse_graminit_c(graminit_c) self.finish_off()
[ "def", "run", "(", "self", ",", "graminit_h", ",", "graminit_c", ")", ":", "self", ".", "parse_graminit_h", "(", "graminit_h", ")", "self", ".", "parse_graminit_c", "(", "graminit_c", ")", "self", ".", "finish_off", "(", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/lib2to3/pgen2/conv.py#L47-L51
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
marklogic/datadog_checks/marklogic/api.py
python
MarkLogicApi.get_health
(self)
return self.http_get(params=params)
Return the cluster health querying http://localhost:8002/manage/v2?view=health&format=json. See https://docs.marklogic.com/REST/GET/manage/v2.
Return the cluster health querying http://localhost:8002/manage/v2?view=health&format=json. See https://docs.marklogic.com/REST/GET/manage/v2.
[ "Return", "the", "cluster", "health", "querying", "http", ":", "//", "localhost", ":", "8002", "/", "manage", "/", "v2?view", "=", "health&format", "=", "json", ".", "See", "https", ":", "//", "docs", ".", "marklogic", ".", "com", "/", "REST", "/", "GE...
def get_health(self): # type: () -> Dict[str, Any] """ Return the cluster health querying http://localhost:8002/manage/v2?view=health&format=json. See https://docs.marklogic.com/REST/GET/manage/v2. """ params = {'view': 'health'} return self.http_get(params=params)
[ "def", "get_health", "(", "self", ")", ":", "# type: () -> Dict[str, Any]", "params", "=", "{", "'view'", ":", "'health'", "}", "return", "self", ".", "http_get", "(", "params", "=", "params", ")" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/marklogic/datadog_checks/marklogic/api.py#L97-L105
googledatalab/pydatalab
1c86e26a0d24e3bc8097895ddeab4d0607be4c40
google/datalab/contrib/mlworkbench/commands/_ml.py
python
_TextLimeExplainerInstance.visualize
(self, label_index)
[]
def visualize(self, label_index): if self._show_overview: IPython.display.display( IPython.display.HTML('<br/> Text Column "<b>%s</b>"<br/>' % self._col_name)) self._exp.show_in_notebook(labels=[label_index]) else: fig = self._exp.as_pyplot_figure(label=label_index) # Clear original title set by lime. plt.title('') fig.suptitle('Text Column "%s"' % self._col_name, fontsize=16) plt.close(fig) IPython.display.display(fig)
[ "def", "visualize", "(", "self", ",", "label_index", ")", ":", "if", "self", ".", "_show_overview", ":", "IPython", ".", "display", ".", "display", "(", "IPython", ".", "display", ".", "HTML", "(", "'<br/> Text Column \"<b>%s</b>\"<br/>'", "%", "self", ".", ...
https://github.com/googledatalab/pydatalab/blob/1c86e26a0d24e3bc8097895ddeab4d0607be4c40/google/datalab/contrib/mlworkbench/commands/_ml.py#L884-L895
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/requests/utils.py
python
parse_dict_header
(value)
return result
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict:
[ "Parse", "lists", "of", "key", "value", "pairs", "as", "described", "by", "RFC", "2068", "Section", "2", "and", "convert", "them", "into", "a", "python", "dict", ":" ]
def parse_dict_header(value): """Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it will be `None`: >>> parse_dict_header('key_without_value') {'key_without_value': None} To create a header from the :class:`dict` again, use the :func:`dump_header` function. :param value: a string with a dict header. :return: :class:`dict` :rtype: dict """ result = {} for item in _parse_list_header(value): if '=' not in item: result[item] = None continue name, value = item.split('=', 1) if value[:1] == value[-1:] == '"': value = unquote_header_value(value[1:-1]) result[name] = value return result
[ "def", "parse_dict_header", "(", "value", ")", ":", "result", "=", "{", "}", "for", "item", "in", "_parse_list_header", "(", "value", ")", ":", "if", "'='", "not", "in", "item", ":", "result", "[", "item", "]", "=", "None", "continue", "name", ",", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/requests/utils.py#L344-L375
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/_osx_support.py
python
customize_compiler
(_config_vars)
return _config_vars
Customize compiler path and configuration variables. This customization is performed when the first extension module build is requested in distutils.sysconfig.customize_compiler).
Customize compiler path and configuration variables.
[ "Customize", "compiler", "path", "and", "configuration", "variables", "." ]
def customize_compiler(_config_vars): """Customize compiler path and configuration variables. This customization is performed when the first extension module build is requested in distutils.sysconfig.customize_compiler). """ # Find a compiler to use for extension module builds _find_appropriate_compiler(_config_vars) # Remove ppc arch flags if not supported here _remove_unsupported_archs(_config_vars) # Allow user to override all archs with ARCHFLAGS env var _override_all_archs(_config_vars) return _config_vars
[ "def", "customize_compiler", "(", "_config_vars", ")", ":", "# Find a compiler to use for extension module builds", "_find_appropriate_compiler", "(", "_config_vars", ")", "# Remove ppc arch flags if not supported here", "_remove_unsupported_archs", "(", "_config_vars", ")", "# Allow...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/_osx_support.py#L409-L426
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/datastore/datastore_stub_util.py
python
StubQueryConverter.v4_to_v3_compiled_cursor
(self, v4_cursor, v3_compiled_cursor)
Converts a v4 cursor string to a v3 CompiledCursor. Args: v4_cursor: a string representing a v4 query cursor v3_compiled_cursor: a datastore_pb.CompiledCursor to populate
Converts a v4 cursor string to a v3 CompiledCursor.
[ "Converts", "a", "v4", "cursor", "string", "to", "a", "v3", "CompiledCursor", "." ]
def v4_to_v3_compiled_cursor(self, v4_cursor, v3_compiled_cursor): """Converts a v4 cursor string to a v3 CompiledCursor. Args: v4_cursor: a string representing a v4 query cursor v3_compiled_cursor: a datastore_pb.CompiledCursor to populate """ v3_compiled_cursor.Clear() v3_compiled_cursor.ParseFromString(v4_cursor)
[ "def", "v4_to_v3_compiled_cursor", "(", "self", ",", "v4_cursor", ",", "v3_compiled_cursor", ")", ":", "v3_compiled_cursor", ".", "Clear", "(", ")", "v3_compiled_cursor", ".", "ParseFromString", "(", "v4_cursor", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/datastore/datastore_stub_util.py#L3206-L3214
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/pkg_resources.py
python
_handle_ns
(packageName, path_item)
return subpath
Ensure that named package includes a subpath of path_item (if needed)
Ensure that named package includes a subpath of path_item (if needed)
[ "Ensure", "that", "named", "package", "includes", "a", "subpath", "of", "path_item", "(", "if", "needed", ")" ]
def _handle_ns(packageName, path_item): """Ensure that named package includes a subpath of path_item (if needed)""" importer = get_importer(path_item) if importer is None: return None loader = importer.find_module(packageName) if loader is None: return None module = sys.modules.get(packageName) if module is None: module = sys.modules[packageName] = imp.new_module(packageName) module.__path__ = [] _set_parent_ns(packageName) elif not hasattr(module,'__path__'): raise TypeError("Not a package:", packageName) handler = _find_adapter(_namespace_handlers, importer) subpath = handler(importer, path_item, packageName, module) if subpath is not None: path = module.__path__ path.append(subpath) loader.load_module(packageName) for path_item in path: if path_item not in module.__path__: module.__path__.append(path_item) return subpath
[ "def", "_handle_ns", "(", "packageName", ",", "path_item", ")", ":", "importer", "=", "get_importer", "(", "path_item", ")", "if", "importer", "is", "None", ":", "return", "None", "loader", "=", "importer", ".", "find_module", "(", "packageName", ")", "if", ...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/pkg_resources.py#L1949-L1974
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/idlelib/IOBinding.py
python
IOBinding.set_filename
(self, filename)
[]
def set_filename(self, filename): if filename and os.path.isdir(filename): self.filename = None self.dirname = filename else: self.filename = filename self.dirname = None self.set_saved(1) if self.filename_change_hook: self.filename_change_hook()
[ "def", "set_filename", "(", "self", ",", "filename", ")", ":", "if", "filename", "and", "os", ".", "path", ".", "isdir", "(", "filename", ")", ":", "self", ".", "filename", "=", "None", "self", ".", "dirname", "=", "filename", "else", ":", "self", "....
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/idlelib/IOBinding.py#L188-L197
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_env.py
python
Yedit.valid_key
(key, sep='.')
return True
validate the incoming key
validate the incoming key
[ "validate", "the", "incoming", "key" ]
def valid_key(key, sep='.'): '''validate the incoming key''' common_separators = list(Yedit.com_sep - set([sep])) if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key): return False return True
[ "def", "valid_key", "(", "key", ",", "sep", "=", "'.'", ")", ":", "common_separators", "=", "list", "(", "Yedit", ".", "com_sep", "-", "set", "(", "[", "sep", "]", ")", ")", "if", "not", "re", ".", "match", "(", "Yedit", ".", "re_valid_key", ".", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_env.py#L198-L204
RichardFrangenberg/Prism
09283b5146d9cdf9d489dcf252f7927083534a48
Prism/Plugins/ProjectManagers/Shotgun/external_modules/shotgun_api3/shotgun.py
python
Shotgun._visit_data
(self, data, visitor)
return visitor(data)
Walk the data (simple python types) and call the visitor.
Walk the data (simple python types) and call the visitor.
[ "Walk", "the", "data", "(", "simple", "python", "types", ")", "and", "call", "the", "visitor", "." ]
def _visit_data(self, data, visitor): """ Walk the data (simple python types) and call the visitor. """ if not data: return data recursive = self._visit_data if isinstance(data, list): return [recursive(i, visitor) for i in data] if isinstance(data, tuple): return tuple(recursive(i, visitor) for i in data) if isinstance(data, dict): return dict( (k, recursive(v, visitor)) for k, v in six.iteritems(data) ) return visitor(data)
[ "def", "_visit_data", "(", "self", ",", "data", ",", "visitor", ")", ":", "if", "not", "data", ":", "return", "data", "recursive", "=", "self", ".", "_visit_data", "if", "isinstance", "(", "data", ",", "list", ")", ":", "return", "[", "recursive", "(",...
https://github.com/RichardFrangenberg/Prism/blob/09283b5146d9cdf9d489dcf252f7927083534a48/Prism/Plugins/ProjectManagers/Shotgun/external_modules/shotgun_api3/shotgun.py#L3622-L3643
andsens/bootstrap-vz
fcdc6993f59e521567fb101302b02312e741b88c
bootstrapvz/base/fs/partitionmaps/gpt.py
python
GPTPartitionMap._before_create
(self, event)
Creates the partition map
Creates the partition map
[ "Creates", "the", "partition", "map" ]
def _before_create(self, event): """Creates the partition map """ volume = event.volume # Disk alignment still plays a role in virtualized environment, # but I honestly have no clue as to what best practice is here, so we choose 'none' log_check_call(['parted', '--script', '--align', 'none', volume.device_path, '--', 'mklabel', 'gpt']) # Create the partitions for partition in self.partitions: partition.create(volume)
[ "def", "_before_create", "(", "self", ",", "event", ")", ":", "volume", "=", "event", ".", "volume", "# Disk alignment still plays a role in virtualized environment,", "# but I honestly have no clue as to what best practice is here, so we choose 'none'", "log_check_call", "(", "[",...
https://github.com/andsens/bootstrap-vz/blob/fcdc6993f59e521567fb101302b02312e741b88c/bootstrapvz/base/fs/partitionmaps/gpt.py#L97-L107
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/3rdparty/tvm/tutorials/nnvm/from_mxnet_to_webgl.py
python
transform_image
(image)
return image
Perform necessary preprocessing to input image. Parameters ---------- image : numpy.ndarray The raw image. Returns ------- image : numpy.ndarray The preprocessed image.
Perform necessary preprocessing to input image.
[ "Perform", "necessary", "preprocessing", "to", "input", "image", "." ]
def transform_image(image): """Perform necessary preprocessing to input image. Parameters ---------- image : numpy.ndarray The raw image. Returns ------- image : numpy.ndarray The preprocessed image. """ image = np.array(image) - np.array([123., 117., 104.]) image /= np.array([58.395, 57.12, 57.375]) image = image.transpose((2, 0, 1)) image = image[np.newaxis, :] return image
[ "def", "transform_image", "(", "image", ")", ":", "image", "=", "np", ".", "array", "(", "image", ")", "-", "np", ".", "array", "(", "[", "123.", ",", "117.", ",", "104.", "]", ")", "image", "/=", "np", ".", "array", "(", "[", "58.395", ",", "5...
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/3rdparty/tvm/tutorials/nnvm/from_mxnet_to_webgl.py#L163-L181
coreemu/core
7e18a7a72023a69a92ad61d87461bd659ba27f7c
daemon/core/api/tlv/coreapi.py
python
CoreMessage.repack
(self)
Invoke after updating self.tlv_data[] to rebuild self.raw_message. Useful for modifying a message that has been parsed, before sending the raw data again. :return: nothing
Invoke after updating self.tlv_data[] to rebuild self.raw_message. Useful for modifying a message that has been parsed, before sending the raw data again.
[ "Invoke", "after", "updating", "self", ".", "tlv_data", "[]", "to", "rebuild", "self", ".", "raw_message", ".", "Useful", "for", "modifying", "a", "message", "that", "has", "been", "parsed", "before", "sending", "the", "raw", "data", "again", "." ]
def repack(self): """ Invoke after updating self.tlv_data[] to rebuild self.raw_message. Useful for modifying a message that has been parsed, before sending the raw data again. :return: nothing """ tlv_data = self.pack_tlv_data() self.raw_message = self.pack(self.flags, tlv_data)
[ "def", "repack", "(", "self", ")", ":", "tlv_data", "=", "self", ".", "pack_tlv_data", "(", ")", "self", ".", "raw_message", "=", "self", ".", "pack", "(", "self", ".", "flags", ",", "tlv_data", ")" ]
https://github.com/coreemu/core/blob/7e18a7a72023a69a92ad61d87461bd659ba27f7c/daemon/core/api/tlv/coreapi.py#L778-L787
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/templates_entity.py
python
TemplatesEntity.generated
(self, generated)
Sets the generated of this TemplatesEntity. When this content was generated. :param generated: The generated of this TemplatesEntity. :type: str
Sets the generated of this TemplatesEntity. When this content was generated.
[ "Sets", "the", "generated", "of", "this", "TemplatesEntity", ".", "When", "this", "content", "was", "generated", "." ]
def generated(self, generated): """ Sets the generated of this TemplatesEntity. When this content was generated. :param generated: The generated of this TemplatesEntity. :type: str """ self._generated = generated
[ "def", "generated", "(", "self", ",", "generated", ")", ":", "self", ".", "_generated", "=", "generated" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/templates_entity.py#L89-L98
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail/wagtailsearch/backends/elasticsearch2.py
python
Elasticsearch2Mapping.get_content_type
(self)
return self.model._meta.app_label + '.' + self.model.__name__
Returns the content type as a string for the model. For example: "wagtailcore.Page" "myapp.MyModel"
Returns the content type as a string for the model.
[ "Returns", "the", "content", "type", "as", "a", "string", "for", "the", "model", "." ]
def get_content_type(self): """ Returns the content type as a string for the model. For example: "wagtailcore.Page" "myapp.MyModel" """ return self.model._meta.app_label + '.' + self.model.__name__
[ "def", "get_content_type", "(", "self", ")", ":", "return", "self", ".", "model", ".", "_meta", ".", "app_label", "+", "'.'", "+", "self", ".", "model", ".", "__name__" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail/wagtailsearch/backends/elasticsearch2.py#L60-L67
reviewboard/reviewboard
7395902e4c181bcd1d633f61105012ffb1d18e1b
reviewboard/diffviewer/chunk_generator.py
python
DiffChunkGenerator.normalize_path_for_display
(self, filename)
return self.tool.normalize_path_for_display( filename, extra_data=self.filediff.extra_data)
Normalize a file path for display to the user. This uses the associated :py:class:`~reviewboard.scmtools.core.SCMTool` to normalize the filename. Args: filename (unicode): The filename to normalize. Returns: unicode: The normalized filename.
Normalize a file path for display to the user.
[ "Normalize", "a", "file", "path", "for", "display", "to", "the", "user", "." ]
def normalize_path_for_display(self, filename): """Normalize a file path for display to the user. This uses the associated :py:class:`~reviewboard.scmtools.core.SCMTool` to normalize the filename. Args: filename (unicode): The filename to normalize. Returns: unicode: The normalized filename. """ return self.tool.normalize_path_for_display( filename, extra_data=self.filediff.extra_data)
[ "def", "normalize_path_for_display", "(", "self", ",", "filename", ")", ":", "return", "self", ".", "tool", ".", "normalize_path_for_display", "(", "filename", ",", "extra_data", "=", "self", ".", "filediff", ".", "extra_data", ")" ]
https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/diffviewer/chunk_generator.py#L1143-L1159
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/phonon/bandstructure.py
python
PhononBandStructure.has_imaginary_freq
(self, tol=1e-5)
return self.min_freq()[1] + tol < 0
True if imaginary frequencies are present in the BS.
True if imaginary frequencies are present in the BS.
[ "True", "if", "imaginary", "frequencies", "are", "present", "in", "the", "BS", "." ]
def has_imaginary_freq(self, tol=1e-5): """ True if imaginary frequencies are present in the BS. """ return self.min_freq()[1] + tol < 0
[ "def", "has_imaginary_freq", "(", "self", ",", "tol", "=", "1e-5", ")", ":", "return", "self", ".", "min_freq", "(", ")", "[", "1", "]", "+", "tol", "<", "0" ]
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/phonon/bandstructure.py#L162-L167
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/linux_packages/mkl.py
python
Install
(vm)
Installs the MKL package on the VM.
Installs the MKL package on the VM.
[ "Installs", "the", "MKL", "package", "on", "the", "VM", "." ]
def Install(vm): """Installs the MKL package on the VM.""" if UseMklRepo(): vm.Install('intel_repo') if intel_repo.UseOneApi(): vm.InstallPackages(f'intel-oneapi-mkl-{MKL_VERSION.value}') # do not need to symlink the vars file return vm.InstallPackages(f'intel-mkl-{MKL_VERSION.value}') else: _InstallFromPreprovisionedData(vm) # Restore the /opt/intel/mkl/bin/mklvars.sh symlink that is missing if # Intel MPI > 2018 installed. if not vm.TryRemoteCommand(f'test -e {_MKL_VARS_FILE}'): txt, _ = vm.RemoteCommand('realpath /opt/intel/*/linux/mkl | sort | uniq') vm.RemoteCommand(f'sudo ln -s {txt.strip()} /opt/intel/mkl') _LogEnvVariables(vm) _CompileInterfaces(vm)
[ "def", "Install", "(", "vm", ")", ":", "if", "UseMklRepo", "(", ")", ":", "vm", ".", "Install", "(", "'intel_repo'", ")", "if", "intel_repo", ".", "UseOneApi", "(", ")", ":", "vm", ".", "InstallPackages", "(", "f'intel-oneapi-mkl-{MKL_VERSION.value}'", ")", ...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/linux_packages/mkl.py#L72-L89
deepfakes/faceswap
09c7d8aca3c608d1afad941ea78e9fd9b64d9219
lib/gui/wrapper.py
python
FaceswapControl.capture_tqdm
(self, string)
return True
Capture tqdm output for progress bar
Capture tqdm output for progress bar
[ "Capture", "tqdm", "output", "for", "progress", "bar" ]
def capture_tqdm(self, string): """ Capture tqdm output for progress bar """ logger.trace("Capturing tqdm") tqdm = self.consoleregex["tqdm"].match(string) if not tqdm: return False tqdm = tqdm.groupdict() if any("?" in val for val in tqdm.values()): logger.trace("tqdm initializing. Skipping") return True description = tqdm["dsc"].strip() description = description if description == "" else "{} | ".format(description[:-1]) processtime = "Elapsed: {} Remaining: {}".format(tqdm["tme"].split("<")[0], tqdm["tme"].split("<")[1]) message = "{}{} | {} | {} | {}".format(description, processtime, tqdm["rte"], tqdm["itm"], tqdm["pct"]) position = tqdm["pct"].replace("%", "") position = int(position) if position.isdigit() else 0 self.statusbar.progress_update(message, position, True) logger.trace("Succesfully captured tqdm message: %s", message) return True
[ "def", "capture_tqdm", "(", "self", ",", "string", ")", ":", "logger", ".", "trace", "(", "\"Capturing tqdm\"", ")", "tqdm", "=", "self", ".", "consoleregex", "[", "\"tqdm\"", "]", ".", "match", "(", "string", ")", "if", "not", "tqdm", ":", "return", "...
https://github.com/deepfakes/faceswap/blob/09c7d8aca3c608d1afad941ea78e9fd9b64d9219/lib/gui/wrapper.py#L324-L349
puremourning/vimspector
bc57b1dd14214cf3e3a476ef75e9dcb56cf0c76d
python3/vimspector/vendor/cpuinfo.py
python
CPUID.get_max_extension_support
(self)
return max_extension_support
[]
def get_max_extension_support(self): # Check for extension support max_extension_support = self._run_asm( b"\xB8\x00\x00\x00\x80" # mov ax,0x80000000 b"\x0f\xa2" # cpuid b"\xC3" # ret ) return max_extension_support
[ "def", "get_max_extension_support", "(", "self", ")", ":", "# Check for extension support", "max_extension_support", "=", "self", ".", "_run_asm", "(", "b\"\\xB8\\x00\\x00\\x00\\x80\"", "# mov ax,0x80000000", "b\"\\x0f\\xa2\"", "# cpuid", "b\"\\xC3\"", "# ret", ")", "return",...
https://github.com/puremourning/vimspector/blob/bc57b1dd14214cf3e3a476ef75e9dcb56cf0c76d/python3/vimspector/vendor/cpuinfo.py#L1079-L1087
raghakot/keras-vis
90ae5565951b5e6a90d706b8205c2c4dfc271505
vis/grad_modifiers.py
python
get
(identifier)
return utils.get_identifier(identifier, globals(), __name__)
[]
def get(identifier): return utils.get_identifier(identifier, globals(), __name__)
[ "def", "get", "(", "identifier", ")", ":", "return", "utils", ".", "get_identifier", "(", "identifier", ",", "globals", "(", ")", ",", "__name__", ")" ]
https://github.com/raghakot/keras-vis/blob/90ae5565951b5e6a90d706b8205c2c4dfc271505/vis/grad_modifiers.py#L69-L70
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/compiler/ast.py
python
Mod.getChildNodes
(self)
return self.left, self.right
[]
def getChildNodes(self): return self.left, self.right
[ "def", "getChildNodes", "(", "self", ")", ":", "return", "self", ".", "left", ",", "self", ".", "right" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/compiler/ast.py#L947-L948
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/plat-mac/pimp.py
python
main
()
Minimal commandline tool to drive pimp.
Minimal commandline tool to drive pimp.
[ "Minimal", "commandline", "tool", "to", "drive", "pimp", "." ]
def main(): """Minimal commandline tool to drive pimp.""" import getopt def _help(): print "Usage: pimp [options] -s [package ...] List installed status" print " pimp [options] -l [package ...] Show package information" print " pimp [options] -i package ... Install packages" print " pimp -d Dump database to stdout" print " pimp -V Print version number" print "Options:" print " -v Verbose" print " -f Force installation" print " -D dir Set destination directory" print " (default: %s)" % DEFAULT_INSTALLDIR print " -u url URL for database" sys.exit(1) class _Watcher: def update(self, msg): sys.stderr.write(msg + '\r') return 1 try: opts, args = getopt.getopt(sys.argv[1:], "slifvdD:Vu:") except getopt.GetoptError: _help() if not opts and not args: _help() mode = None force = 0 verbose = 0 prefargs = {} watcher = None for o, a in opts: if o == '-s': if mode: _help() mode = 'status' if o == '-l': if mode: _help() mode = 'list' if o == '-d': if mode: _help() mode = 'dump' if o == '-V': if mode: _help() mode = 'version' if o == '-i': mode = 'install' if o == '-f': force = 1 if o == '-v': verbose = 1 watcher = _Watcher() if o == '-D': prefargs['installDir'] = a if o == '-u': prefargs['pimpDatabase'] = a if not mode: _help() if mode == 'version': print 'Pimp version %s; module name is %s' % (PIMP_VERSION, __name__) else: _run(mode, verbose, force, args, prefargs, watcher)
[ "def", "main", "(", ")", ":", "import", "getopt", "def", "_help", "(", ")", ":", "print", "\"Usage: pimp [options] -s [package ...] List installed status\"", "print", "\" pimp [options] -l [package ...] Show package information\"", "print", "\" pimp [options] -i packa...
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/plat-mac/pimp.py#L1095-L1162
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/cmd.py
python
Cmd.postcmd
(self, stop, line)
return stop
Hook method executed just after a command dispatch is finished.
Hook method executed just after a command dispatch is finished.
[ "Hook", "method", "executed", "just", "after", "a", "command", "dispatch", "is", "finished", "." ]
def postcmd(self, stop, line): """Hook method executed just after a command dispatch is finished.""" return stop
[ "def", "postcmd", "(", "self", ",", "stop", ",", "line", ")", ":", "return", "stop" ]
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/cmd.py#L161-L163
fkie-cad/FACT_core
034ed39cff092b4970f10d3e3ad117ae6baa0192
src/plugins/installer.py
python
AbstractPluginInstaller.build
(self)
Build and install projects that can't be installed through a package manager
Build and install projects that can't be installed through a package manager
[ "Build", "and", "install", "projects", "that", "can", "t", "be", "installed", "through", "a", "package", "manager" ]
def build(self): ''' Build and install projects that can't be installed through a package manager '''
[ "def", "build", "(", "self", ")", ":" ]
https://github.com/fkie-cad/FACT_core/blob/034ed39cff092b4970f10d3e3ad117ae6baa0192/src/plugins/installer.py#L89-L93
akfamily/akshare
590e50eece9ec067da3538c7059fd660b71f1339
akshare/stock/stock_zh_b_sina.py
python
stock_zh_b_daily
( symbol: str = "sh900901", start_date: str = "19900101", end_date: str = "21000118", adjust: str = "", )
新浪财经-B 股-个股的历史行情数据, 大量抓取容易封 IP https://finance.sina.com.cn/realstock/company/sh689009/nc.shtml :param start_date: 20201103; 开始日期 :type start_date: str :param end_date: 20201103; 结束日期 :type end_date: str :param symbol: sh600000 :type symbol: str :param adjust: 默认为空: 返回不复权的数据; qfq: 返回前复权后的数据; hfq: 返回后复权后的数据; hfq-factor: 返回后复权因子; hfq-factor: 返回前复权因子 :type adjust: str :return: specific data :rtype: pandas.DataFrame
新浪财经-B 股-个股的历史行情数据, 大量抓取容易封 IP https://finance.sina.com.cn/realstock/company/sh689009/nc.shtml :param start_date: 20201103; 开始日期 :type start_date: str :param end_date: 20201103; 结束日期 :type end_date: str :param symbol: sh600000 :type symbol: str :param adjust: 默认为空: 返回不复权的数据; qfq: 返回前复权后的数据; hfq: 返回后复权后的数据; hfq-factor: 返回后复权因子; hfq-factor: 返回前复权因子 :type adjust: str :return: specific data :rtype: pandas.DataFrame
[ "新浪财经", "-", "B", "股", "-", "个股的历史行情数据", "大量抓取容易封", "IP", "https", ":", "//", "finance", ".", "sina", ".", "com", ".", "cn", "/", "realstock", "/", "company", "/", "sh689009", "/", "nc", ".", "shtml", ":", "param", "start_date", ":", "20201103", ";",...
def stock_zh_b_daily( symbol: str = "sh900901", start_date: str = "19900101", end_date: str = "21000118", adjust: str = "", ) -> pd.DataFrame: """ 新浪财经-B 股-个股的历史行情数据, 大量抓取容易封 IP https://finance.sina.com.cn/realstock/company/sh689009/nc.shtml :param start_date: 20201103; 开始日期 :type start_date: str :param end_date: 20201103; 结束日期 :type end_date: str :param symbol: sh600000 :type symbol: str :param adjust: 默认为空: 返回不复权的数据; qfq: 返回前复权后的数据; hfq: 返回后复权后的数据; hfq-factor: 返回后复权因子; hfq-factor: 返回前复权因子 :type adjust: str :return: specific data :rtype: pandas.DataFrame """ def _fq_factor(method: str) -> pd.DataFrame: if method == "hfq": res = requests.get(zh_sina_a_stock_hfq_url.format(symbol)) hfq_factor_df = pd.DataFrame( eval(res.text.split("=")[1].split("\n")[0])["data"] ) if hfq_factor_df.shape[0] == 0: raise ValueError("sina hfq factor not available") hfq_factor_df.columns = ["date", "hfq_factor"] hfq_factor_df.index = pd.to_datetime(hfq_factor_df.date) del hfq_factor_df["date"] hfq_factor_df.reset_index(inplace=True) return hfq_factor_df else: res = requests.get(zh_sina_a_stock_qfq_url.format(symbol)) qfq_factor_df = pd.DataFrame( eval(res.text.split("=")[1].split("\n")[0])["data"] ) if qfq_factor_df.shape[0] == 0: raise ValueError("sina hfq factor not available") qfq_factor_df.columns = ["date", "qfq_factor"] qfq_factor_df.index = pd.to_datetime(qfq_factor_df.date) del qfq_factor_df["date"] qfq_factor_df.reset_index(inplace=True) return qfq_factor_df if adjust in ("hfq-factor", "qfq-factor"): return _fq_factor(adjust.split("-")[0]) res = requests.get(zh_sina_a_stock_hist_url.format(symbol)) js_code = py_mini_racer.MiniRacer() js_code.eval(hk_js_decode) dict_list = js_code.call( "d", res.text.split("=")[1].split(";")[0].replace('"', "") ) # 执行js解密代码 data_df = pd.DataFrame(dict_list) data_df.index = pd.to_datetime(data_df["date"]).dt.date del data_df["date"] data_df = data_df.astype("float") r = requests.get(zh_sina_a_stock_amount_url.format(symbol, symbol)) amount_data_json = demjson.decode(r.text[r.text.find("["): r.text.rfind("]") + 1]) amount_data_df = pd.DataFrame(amount_data_json) amount_data_df.index = pd.to_datetime(amount_data_df.date) del amount_data_df["date"] temp_df = pd.merge( data_df, amount_data_df, left_index=True, right_index=True, how="outer" ) temp_df.fillna(method="ffill", inplace=True) temp_df = temp_df.astype(float) temp_df["amount"] = temp_df["amount"] * 10000 temp_df["turnover"] = temp_df["volume"] / temp_df["amount"] temp_df.columns = [ "open", "high", "low", "close", "volume", "outstanding_share", "turnover", ] if adjust == "": temp_df = temp_df[start_date:end_date] temp_df.drop_duplicates(subset=["open", "high", "low", "close", "volume"], inplace=True) temp_df["open"] = round(temp_df["open"], 2) temp_df["high"] = round(temp_df["high"], 2) temp_df["low"] = round(temp_df["low"], 2) temp_df["close"] = round(temp_df["close"], 2) temp_df.dropna(inplace=True) temp_df.drop_duplicates(inplace=True) temp_df.reset_index(inplace=True) return temp_df if adjust == "hfq": res = requests.get(zh_sina_a_stock_hfq_url.format(symbol)) hfq_factor_df = pd.DataFrame( eval(res.text.split("=")[1].split("\n")[0])["data"] ) hfq_factor_df.columns = ["date", "hfq_factor"] hfq_factor_df.index = pd.to_datetime(hfq_factor_df.date) del hfq_factor_df["date"] temp_df = pd.merge( temp_df, hfq_factor_df, left_index=True, right_index=True, how="outer" ) temp_df.fillna(method="ffill", inplace=True) temp_df = temp_df.astype(float) temp_df.dropna(inplace=True) temp_df.drop_duplicates(subset=["open", "high", "low", "close", "volume"], inplace=True) temp_df["open"] = temp_df["open"] * temp_df["hfq_factor"] temp_df["high"] = temp_df["high"] * temp_df["hfq_factor"] temp_df["close"] = temp_df["close"] * temp_df["hfq_factor"] temp_df["low"] = temp_df["low"] * temp_df["hfq_factor"] temp_df = temp_df.iloc[:, :-1] temp_df = temp_df[start_date:end_date] temp_df["open"] = round(temp_df["open"], 2) temp_df["high"] = round(temp_df["high"], 2) temp_df["low"] = round(temp_df["low"], 2) temp_df["close"] = round(temp_df["close"], 2) temp_df.dropna(inplace=True) temp_df.reset_index(inplace=True) return temp_df if adjust == "qfq": res = requests.get(zh_sina_a_stock_qfq_url.format(symbol)) qfq_factor_df = pd.DataFrame( eval(res.text.split("=")[1].split("\n")[0])["data"] ) qfq_factor_df.columns = ["date", "qfq_factor"] qfq_factor_df.index = pd.to_datetime(qfq_factor_df.date) del qfq_factor_df["date"] temp_df = pd.merge( temp_df, qfq_factor_df, left_index=True, right_index=True, how="outer" ) temp_df.fillna(method="ffill", inplace=True) temp_df = temp_df.astype(float) temp_df.dropna(inplace=True) temp_df.drop_duplicates(subset=["open", "high", "low", "close", "volume"], inplace=True) temp_df["open"] = temp_df["open"] / temp_df["qfq_factor"] temp_df["high"] = temp_df["high"] / temp_df["qfq_factor"] temp_df["close"] = temp_df["close"] / temp_df["qfq_factor"] temp_df["low"] = temp_df["low"] / temp_df["qfq_factor"] temp_df = temp_df.iloc[:, :-1] temp_df = temp_df[start_date:end_date] temp_df["open"] = round(temp_df["open"], 2) temp_df["high"] = round(temp_df["high"], 2) temp_df["low"] = round(temp_df["low"], 2) temp_df["close"] = round(temp_df["close"], 2) temp_df.dropna(inplace=True) temp_df.reset_index(inplace=True) return temp_df
[ "def", "stock_zh_b_daily", "(", "symbol", ":", "str", "=", "\"sh900901\"", ",", "start_date", ":", "str", "=", "\"19900101\"", ",", "end_date", ":", "str", "=", "\"21000118\"", ",", "adjust", ":", "str", "=", "\"\"", ",", ")", "->", "pd", ".", "DataFrame...
https://github.com/akfamily/akshare/blob/590e50eece9ec067da3538c7059fd660b71f1339/akshare/stock/stock_zh_b_sina.py#L137-L286
sunpy/sunpy
528579df0a4c938c133bd08971ba75c131b189a7
sunpy/extern/inflect.py
python
engine.plural
(self, text: str, count: Optional[Union[str, int]] = None)
return f"{pre}{plural}{post}"
Return the plural of text. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved.
Return the plural of text.
[ "Return", "the", "plural", "of", "text", "." ]
def plural(self, text: str, count: Optional[Union[str, int]] = None) -> str: """ Return the plural of text. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess( word, self._pl_special_adjective(word, count) or self._pl_special_verb(word, count) or self._plnoun(word, count), ) return f"{pre}{plural}{post}"
[ "def", "plural", "(", "self", ",", "text", ":", "str", ",", "count", ":", "Optional", "[", "Union", "[", "str", ",", "int", "]", "]", "=", "None", ")", "->", "str", ":", "pre", ",", "word", ",", "post", "=", "self", ".", "partition_word", "(", ...
https://github.com/sunpy/sunpy/blob/528579df0a4c938c133bd08971ba75c131b189a7/sunpy/extern/inflect.py#L2323-L2343
fablabnbg/inkscape-silhouette
e0ad65115b4b2b0a5b60dfecd9a3ca03ec1d6bec
silhouette/pyusb-1.0.2/usb/util.py
python
claim_interface
(device, interface)
r"""Explicitly claim an interface. PyUSB users normally do not have to worry about interface claiming, as the library takes care of it automatically. But there are situations where you need deterministic interface claiming. For these uncommon cases, you can use claim_interface. If the interface is already claimed, either through a previously call to claim_interface or internally by the device object, nothing happens.
r"""Explicitly claim an interface.
[ "r", "Explicitly", "claim", "an", "interface", "." ]
def claim_interface(device, interface): r"""Explicitly claim an interface. PyUSB users normally do not have to worry about interface claiming, as the library takes care of it automatically. But there are situations where you need deterministic interface claiming. For these uncommon cases, you can use claim_interface. If the interface is already claimed, either through a previously call to claim_interface or internally by the device object, nothing happens. """ device._ctx.managed_claim_interface(device, interface)
[ "def", "claim_interface", "(", "device", ",", "interface", ")", ":", "device", ".", "_ctx", ".", "managed_claim_interface", "(", "device", ",", "interface", ")" ]
https://github.com/fablabnbg/inkscape-silhouette/blob/e0ad65115b4b2b0a5b60dfecd9a3ca03ec1d6bec/silhouette/pyusb-1.0.2/usb/util.py#L194-L205
spulec/moto
a688c0032596a7dfef122b69a08f2bec3be2e481
moto/route53resolver/models.py
python
Route53ResolverBackend._matched_arn
(self, resource_arn)
Given ARN, raise exception if there is no corresponding resource.
Given ARN, raise exception if there is no corresponding resource.
[ "Given", "ARN", "raise", "exception", "if", "there", "is", "no", "corresponding", "resource", "." ]
def _matched_arn(self, resource_arn): """Given ARN, raise exception if there is no corresponding resource.""" for resolver_endpoint in self.resolver_endpoints.values(): if resolver_endpoint.arn == resource_arn: return for resolver_rule in self.resolver_rules.values(): if resolver_rule.arn == resource_arn: return raise ResourceNotFoundException( f"Resolver endpoint with ID '{resource_arn}' does not exist" )
[ "def", "_matched_arn", "(", "self", ",", "resource_arn", ")", ":", "for", "resolver_endpoint", "in", "self", ".", "resolver_endpoints", ".", "values", "(", ")", ":", "if", "resolver_endpoint", ".", "arn", "==", "resource_arn", ":", "return", "for", "resolver_r...
https://github.com/spulec/moto/blob/a688c0032596a7dfef122b69a08f2bec3be2e481/moto/route53resolver/models.py#L797-L807
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/users/dbaccessors.py
python
get_mobile_user_count
(domain, include_inactive=True)
return sum([ row['value'] for row in get_all_user_rows( domain, include_web_users=False, include_mobile_users=True, include_inactive=include_inactive, count_only=True ) if row ])
[]
def get_mobile_user_count(domain, include_inactive=True): return sum([ row['value'] for row in get_all_user_rows( domain, include_web_users=False, include_mobile_users=True, include_inactive=include_inactive, count_only=True ) if row ])
[ "def", "get_mobile_user_count", "(", "domain", ",", "include_inactive", "=", "True", ")", ":", "return", "sum", "(", "[", "row", "[", "'value'", "]", "for", "row", "in", "get_all_user_rows", "(", "domain", ",", "include_web_users", "=", "False", ",", "includ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/users/dbaccessors.py#L206-L216
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/released/service_hooks/service_hooks_client.py
python
ServiceHooksClient.get_publisher
(self, publisher_id)
return self._deserialize('Publisher', response)
GetPublisher. Get a specific service hooks publisher. :param str publisher_id: ID for a publisher. :rtype: :class:`<Publisher> <azure.devops.v5_1.service_hooks.models.Publisher>`
GetPublisher. Get a specific service hooks publisher. :param str publisher_id: ID for a publisher. :rtype: :class:`<Publisher> <azure.devops.v5_1.service_hooks.models.Publisher>`
[ "GetPublisher", ".", "Get", "a", "specific", "service", "hooks", "publisher", ".", ":", "param", "str", "publisher_id", ":", "ID", "for", "a", "publisher", ".", ":", "rtype", ":", ":", "class", ":", "<Publisher", ">", "<azure", ".", "devops", ".", "v5_1"...
def get_publisher(self, publisher_id): """GetPublisher. Get a specific service hooks publisher. :param str publisher_id: ID for a publisher. :rtype: :class:`<Publisher> <azure.devops.v5_1.service_hooks.models.Publisher>` """ route_values = {} if publisher_id is not None: route_values['publisherId'] = self._serialize.url('publisher_id', publisher_id, 'str') response = self._send(http_method='GET', location_id='1e83a210-5b53-43bc-90f0-d476a4e5d731', version='5.1', route_values=route_values) return self._deserialize('Publisher', response)
[ "def", "get_publisher", "(", "self", ",", "publisher_id", ")", ":", "route_values", "=", "{", "}", "if", "publisher_id", "is", "not", "None", ":", "route_values", "[", "'publisherId'", "]", "=", "self", ".", "_serialize", ".", "url", "(", "'publisher_id'", ...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/released/service_hooks/service_hooks_client.py#L213-L226
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/distlib/_backport/shutil.py
python
_find_unpack_format
(filename)
return None
[]
def _find_unpack_format(filename): for name, info in _UNPACK_FORMATS.items(): for extension in info[0]: if filename.endswith(extension): return name return None
[ "def", "_find_unpack_format", "(", "filename", ")", ":", "for", "name", ",", "info", "in", "_UNPACK_FORMATS", ".", "items", "(", ")", ":", "for", "extension", "in", "info", "[", "0", "]", ":", "if", "filename", ".", "endswith", "(", "extension", ")", "...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/distlib/_backport/shutil.py#L723-L728
trezor/python-trezor
2813522b05cef4e0e545a101f8b3559a3183b45b
trezorlib/firmware.py
python
update
(client, data)
[]
def update(client, data): if client.features.bootloader_mode is False: raise RuntimeError("Device must be in bootloader mode") resp = client.call(messages.FirmwareErase(length=len(data))) # TREZORv1 method if isinstance(resp, messages.Success): resp = client.call(messages.FirmwareUpload(payload=data)) if isinstance(resp, messages.Success): return else: raise RuntimeError("Unexpected result %s" % resp) # TREZORv2 method while isinstance(resp, messages.FirmwareRequest): payload = data[resp.offset : resp.offset + resp.length] digest = pyblake2.blake2s(payload).digest() resp = client.call(messages.FirmwareUpload(payload=payload, hash=digest)) if isinstance(resp, messages.Success): return else: raise RuntimeError("Unexpected message %s" % resp)
[ "def", "update", "(", "client", ",", "data", ")", ":", "if", "client", ".", "features", ".", "bootloader_mode", "is", "False", ":", "raise", "RuntimeError", "(", "\"Device must be in bootloader mode\"", ")", "resp", "=", "client", ".", "call", "(", "messages",...
https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/firmware.py#L412-L435
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/bdb.py
python
Bdb.get_stack
(self, f, t)
return stack, i
Return a list of (frame, lineno) in a stack trace and a size. List starts with original calling frame, if there is one. Size may be number of frames above or below f.
Return a list of (frame, lineno) in a stack trace and a size.
[ "Return", "a", "list", "of", "(", "frame", "lineno", ")", "in", "a", "stack", "trace", "and", "a", "size", "." ]
def get_stack(self, f, t): """Return a list of (frame, lineno) in a stack trace and a size. List starts with original calling frame, if there is one. Size may be number of frames above or below f. """ stack = [] if t and t.tb_frame is f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) if f is self.botframe: break f = f.f_back stack.reverse() i = max(0, len(stack) - 1) while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next if f is None: i = max(0, len(stack) - 1) return stack, i
[ "def", "get_stack", "(", "self", ",", "f", ",", "t", ")", ":", "stack", "=", "[", "]", "if", "t", "and", "t", ".", "tb_frame", "is", "f", ":", "t", "=", "t", ".", "tb_next", "while", "f", "is", "not", "None", ":", "stack", ".", "append", "(",...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/bdb.py#L509-L530
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/internet/posixbase.py
python
PosixReactorBase.connectTCP
(self, host, port, factory, timeout=30, bindAddress=None)
return c
@see: twisted.internet.interfaces.IReactorTCP.connectTCP
[]
def connectTCP(self, host, port, factory, timeout=30, bindAddress=None): """@see: twisted.internet.interfaces.IReactorTCP.connectTCP """ c = tcp.Connector(host, port, factory, timeout, bindAddress, self) c.connect() return c
[ "def", "connectTCP", "(", "self", ",", "host", ",", "port", ",", "factory", ",", "timeout", "=", "30", ",", "bindAddress", "=", "None", ")", ":", "c", "=", "tcp", ".", "Connector", "(", "host", ",", "port", ",", "factory", ",", "timeout", ",", "bin...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/internet/posixbase.py#L422-L427
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/scripts/sshbackdoors/backdoors/shell/pupy/pupy/packages/windows/amd64/psutil/__init__.py
python
Process.nice
(self, value=None)
Get or set process niceness (priority).
Get or set process niceness (priority).
[ "Get", "or", "set", "process", "niceness", "(", "priority", ")", "." ]
def nice(self, value=None): """Get or set process niceness (priority).""" if value is None: return self._proc.nice_get() else: if not self.is_running(): raise NoSuchProcess(self.pid, self._name) self._proc.nice_set(value)
[ "def", "nice", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "self", ".", "_proc", ".", "nice_get", "(", ")", "else", ":", "if", "not", "self", ".", "is_running", "(", ")", ":", "raise", "NoSuchProces...
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/sshbackdoors/backdoors/shell/pupy/pupy/packages/windows/amd64/psutil/__init__.py#L624-L631
openembedded/openembedded-core
9154f71c7267e9731156c1dfd57397103e9e6a2b
meta/lib/oe/recipeutils.py
python
split_var_value
(value, assignment=True)
return outlist
Split a space-separated variable's value into a list of items, taking into account that some of the items might be made up of expressions containing spaces that should not be split. Parameters: value: The string value to split assignment: True to assume that the value represents an assignment statement, False otherwise. If True, and an assignment statement is passed in the first item in the returned list will be the part of the assignment statement up to and including the opening quote character, and the last item will be the closing quote.
Split a space-separated variable's value into a list of items, taking into account that some of the items might be made up of expressions containing spaces that should not be split. Parameters: value: The string value to split assignment: True to assume that the value represents an assignment statement, False otherwise. If True, and an assignment statement is passed in the first item in the returned list will be the part of the assignment statement up to and including the opening quote character, and the last item will be the closing quote.
[ "Split", "a", "space", "-", "separated", "variable", "s", "value", "into", "a", "list", "of", "items", "taking", "into", "account", "that", "some", "of", "the", "items", "might", "be", "made", "up", "of", "expressions", "containing", "spaces", "that", "sho...
def split_var_value(value, assignment=True): """ Split a space-separated variable's value into a list of items, taking into account that some of the items might be made up of expressions containing spaces that should not be split. Parameters: value: The string value to split assignment: True to assume that the value represents an assignment statement, False otherwise. If True, and an assignment statement is passed in the first item in the returned list will be the part of the assignment statement up to and including the opening quote character, and the last item will be the closing quote. """ inexpr = 0 lastchar = None out = [] buf = '' for char in value: if char == '{': if lastchar == '$': inexpr += 1 elif char == '}': inexpr -= 1 elif assignment and char in '"\'' and inexpr == 0: if buf: out.append(buf) out.append(char) char = '' buf = '' elif char.isspace() and inexpr == 0: char = '' if buf: out.append(buf) buf = '' buf += char lastchar = char if buf: out.append(buf) # Join together assignment statement and opening quote outlist = out if assignment: assigfound = False for idx, item in enumerate(out): if '=' in item: assigfound = True if assigfound: if '"' in item or "'" in item: outlist = [' '.join(out[:idx+1])] outlist.extend(out[idx+1:]) break return outlist
[ "def", "split_var_value", "(", "value", ",", "assignment", "=", "True", ")", ":", "inexpr", "=", "0", "lastchar", "=", "None", "out", "=", "[", "]", "buf", "=", "''", "for", "char", "in", "value", ":", "if", "char", "==", "'{'", ":", "if", "lastcha...
https://github.com/openembedded/openembedded-core/blob/9154f71c7267e9731156c1dfd57397103e9e6a2b/meta/lib/oe/recipeutils.py#L85-L139
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.py
python
LockBase.break_lock
(self)
Remove a lock. Useful if a locking thread failed to unlock.
Remove a lock. Useful if a locking thread failed to unlock.
[ "Remove", "a", "lock", ".", "Useful", "if", "a", "locking", "thread", "failed", "to", "unlock", "." ]
def break_lock(self): """ Remove a lock. Useful if a locking thread failed to unlock. """ raise NotImplemented("implement in subclass")
[ "def", "break_lock", "(", "self", ")", ":", "raise", "NotImplemented", "(", "\"implement in subclass\"", ")" ]
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.py#L257-L261
runawayhorse001/LearningApacheSpark
67f3879dce17553195f094f5728b94a01badcf24
pyspark/shuffle.py
python
_get_local_dirs
(sub)
return [os.path.join(d, "python", str(os.getpid()), sub) for d in dirs]
Get all the directories
Get all the directories
[ "Get", "all", "the", "directories" ]
def _get_local_dirs(sub): """ Get all the directories """ path = os.environ.get("SPARK_LOCAL_DIRS", "/tmp") dirs = path.split(",") if len(dirs) > 1: # different order in different processes and instances rnd = random.Random(os.getpid() + id(dirs)) random.shuffle(dirs, rnd.random) return [os.path.join(d, "python", str(os.getpid()), sub) for d in dirs]
[ "def", "_get_local_dirs", "(", "sub", ")", ":", "path", "=", "os", ".", "environ", ".", "get", "(", "\"SPARK_LOCAL_DIRS\"", ",", "\"/tmp\"", ")", "dirs", "=", "path", ".", "split", "(", "\",\"", ")", "if", "len", "(", "dirs", ")", ">", "1", ":", "#...
https://github.com/runawayhorse001/LearningApacheSpark/blob/67f3879dce17553195f094f5728b94a01badcf24/pyspark/shuffle.py#L71-L79
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/provisioningserver/drivers/hardware/virsh.py
python
VirshSSH.get_arch
(self, machine)
return ARCH_FIX.get(arch, arch)
Gets the VM architecture.
Gets the VM architecture.
[ "Gets", "the", "VM", "architecture", "." ]
def get_arch(self, machine): """Gets the VM architecture.""" output = self.get_machine_xml(machine) if output is None: maaslog.error("%s: Failed to get VM architecture", machine) return None doc = etree.XML(output) evaluator = etree.XPathEvaluator(doc) arch = evaluator(XPATH_ARCH)[0] # Fix architectures that need to be referenced by a different # name, that MAAS understands. return ARCH_FIX.get(arch, arch)
[ "def", "get_arch", "(", "self", ",", "machine", ")", ":", "output", "=", "self", ".", "get_machine_xml", "(", "machine", ")", "if", "output", "is", "None", ":", "maaslog", ".", "error", "(", "\"%s: Failed to get VM architecture\"", ",", "machine", ")", "retu...
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/provisioningserver/drivers/hardware/virsh.py#L185-L198
pyroscope/pyrocore
e8ededb6d9f3702ede6cd5396e6b473915637b64
src/pyrocore/torrent/engine.py
python
FieldDefinition.lookup
(cls, name)
return {"matcher": field._matcher} if field else None
Try to find field C{name}. @return: Field descriptions, see C{matching.ConditionParser} for details.
Try to find field C{name}.
[ "Try", "to", "find", "field", "C", "{", "name", "}", "." ]
def lookup(cls, name): """ Try to find field C{name}. @return: Field descriptions, see C{matching.ConditionParser} for details. """ try: field = cls.FIELDS[name] except KeyError: # Is it a custom attribute? field = TorrentProxy.add_manifold_attribute(name) return {"matcher": field._matcher} if field else None
[ "def", "lookup", "(", "cls", ",", "name", ")", ":", "try", ":", "field", "=", "cls", ".", "FIELDS", "[", "name", "]", "except", "KeyError", ":", "# Is it a custom attribute?", "field", "=", "TorrentProxy", ".", "add_manifold_attribute", "(", "name", ")", "...
https://github.com/pyroscope/pyrocore/blob/e8ededb6d9f3702ede6cd5396e6b473915637b64/src/pyrocore/torrent/engine.py#L214-L225
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/data/parsers/pynarcissus/jsparser.py
python
tokenstr
(tt)
return t.upper()
[]
def tokenstr(tt): t = tokens[tt] if re.match(r'^\W', t): return opTypeNames[t] return t.upper()
[ "def", "tokenstr", "(", "tt", ")", ":", "t", "=", "tokens", "[", "tt", "]", "if", "re", ".", "match", "(", "r'^\\W'", ",", "t", ")", ":", "return", "opTypeNames", "[", "t", "]", "return", "t", ".", "upper", "(", ")" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/data/parsers/pynarcissus/jsparser.py#L464-L468
ansible-collections/community.general
3faffe8f47968a2400ba3c896c8901c03001a194
plugins/modules/system/cronvar.py
python
CronVar.write
(self, backup_file=None)
Write the crontab to the system. Saves all information.
Write the crontab to the system. Saves all information.
[ "Write", "the", "crontab", "to", "the", "system", ".", "Saves", "all", "information", "." ]
def write(self, backup_file=None): """ Write the crontab to the system. Saves all information. """ if backup_file: fileh = open(backup_file, 'w') elif self.cron_file: fileh = open(self.cron_file, 'w') else: filed, path = tempfile.mkstemp(prefix='crontab') fileh = os.fdopen(filed, 'w') fileh.write(self.render()) fileh.close() # return if making a backup if backup_file: return # Add the entire crontab back to the user crontab if not self.cron_file: # quoting shell args for now but really this should be two non-shell calls. FIXME (rc, out, err) = self.module.run_command(self._write_execute(path), use_unsafe_shell=True) os.unlink(path) if rc != 0: self.module.fail_json(msg=err)
[ "def", "write", "(", "self", ",", "backup_file", "=", "None", ")", ":", "if", "backup_file", ":", "fileh", "=", "open", "(", "backup_file", ",", "'w'", ")", "elif", "self", ".", "cron_file", ":", "fileh", "=", "open", "(", "self", ".", "cron_file", "...
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/modules/system/cronvar.py#L169-L195
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/core/decorators.py
python
call_highest_priority
(method_name)
return priority_decorator
A decorator for binary special methods to handle _op_priority. Binary special methods in Expr and its subclasses use a special attribute '_op_priority' to determine whose special method will be called to handle the operation. In general, the object having the highest value of '_op_priority' will handle the operation. Expr and subclasses that define custom binary special methods (__mul__, etc.) should decorate those methods with this decorator to add the priority logic. The ``method_name`` argument is the name of the method of the other class that will be called. Use this decorator in the following manner:: # Call other.__rmul__ if other._op_priority > self._op_priority @call_highest_priority('__rmul__') def __mul__(self, other): ... # Call other.__mul__ if other._op_priority > self._op_priority @call_highest_priority('__mul__') def __rmul__(self, other): ...
A decorator for binary special methods to handle _op_priority.
[ "A", "decorator", "for", "binary", "special", "methods", "to", "handle", "_op_priority", "." ]
def call_highest_priority(method_name): """A decorator for binary special methods to handle _op_priority. Binary special methods in Expr and its subclasses use a special attribute '_op_priority' to determine whose special method will be called to handle the operation. In general, the object having the highest value of '_op_priority' will handle the operation. Expr and subclasses that define custom binary special methods (__mul__, etc.) should decorate those methods with this decorator to add the priority logic. The ``method_name`` argument is the name of the method of the other class that will be called. Use this decorator in the following manner:: # Call other.__rmul__ if other._op_priority > self._op_priority @call_highest_priority('__rmul__') def __mul__(self, other): ... # Call other.__mul__ if other._op_priority > self._op_priority @call_highest_priority('__mul__') def __rmul__(self, other): ... """ def priority_decorator(func): @wraps(func) def binary_op_wrapper(self, other): if hasattr(other, '_op_priority'): if other._op_priority > self._op_priority: try: f = getattr(other, method_name) except AttributeError: pass else: return f(self) return func(self, other) return binary_op_wrapper return priority_decorator
[ "def", "call_highest_priority", "(", "method_name", ")", ":", "def", "priority_decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "binary_op_wrapper", "(", "self", ",", "other", ")", ":", "if", "hasattr", "(", "other", ",", "'_op_pri...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/core/decorators.py#L84-L120
wagtail/Willow
31fe99cd4f5988aa4366629f7fcc6f2029b474da
willow/plugins/pillow.py
python
PillowImage.rotate
(self, angle)
return PillowImage(rotated)
Accept a multiple of 90 to pass to the underlying Pillow function to rotate the image.
Accept a multiple of 90 to pass to the underlying Pillow function to rotate the image.
[ "Accept", "a", "multiple", "of", "90", "to", "pass", "to", "the", "underlying", "Pillow", "function", "to", "rotate", "the", "image", "." ]
def rotate(self, angle): """ Accept a multiple of 90 to pass to the underlying Pillow function to rotate the image. """ Image = _PIL_Image() ORIENTATION_TO_TRANSPOSE = { 90: Image.ROTATE_90, 180: Image.ROTATE_180, 270: Image.ROTATE_270, } modulo_angle = angle % 360 # is we're rotating a multiple of 360, it's the same as a no-op if not modulo_angle: return self transpose_code = ORIENTATION_TO_TRANSPOSE.get(modulo_angle) if not transpose_code: raise UnsupportedRotation( "Sorry - we only support right angle rotations - i.e. multiples of 90 degrees" ) # We call "transpose", as it rotates the image, # updating the height and width, whereas using 'rotate' # only changes the contents of the image. rotated = self.image.transpose(transpose_code) return PillowImage(rotated)
[ "def", "rotate", "(", "self", ",", "angle", ")", ":", "Image", "=", "_PIL_Image", "(", ")", "ORIENTATION_TO_TRANSPOSE", "=", "{", "90", ":", "Image", ".", "ROTATE_90", ",", "180", ":", "Image", ".", "ROTATE_180", ",", "270", ":", "Image", ".", "ROTATE_...
https://github.com/wagtail/Willow/blob/31fe99cd4f5988aa4366629f7fcc6f2029b474da/willow/plugins/pillow.py#L73-L104
redhat-imaging/imagefactory
176f6e045e1df049d50f33a924653128d5ab8b27
imgfac/rest/bottle.py
python
MultiDict.__init__
(self, *a, **k)
[]
def __init__(self, *a, **k): self.dict = dict((k, [v]) for (k, v) in dict(*a, **k).items())
[ "def", "__init__", "(", "self", ",", "*", "a", ",", "*", "*", "k", ")", ":", "self", ".", "dict", "=", "dict", "(", "(", "k", ",", "[", "v", "]", ")", "for", "(", "k", ",", "v", ")", "in", "dict", "(", "*", "a", ",", "*", "*", "k", ")...
https://github.com/redhat-imaging/imagefactory/blob/176f6e045e1df049d50f33a924653128d5ab8b27/imgfac/rest/bottle.py#L1819-L1820
datitran/object_detector_app
44e8eddeb931cced5d8cf1e283383c720a5706bf
object_detection/meta_architectures/faster_rcnn_meta_arch.py
python
FasterRCNNMetaArch._sample_box_classifier_minibatch
(self, proposal_boxlist, groundtruth_boxlist, groundtruth_classes_with_background)
return box_list_ops.boolean_mask(proposal_boxlist, sampled_indices)
Samples a mini-batch of proposals to be sent to the box classifier. Helper function for self._postprocess_rpn. Args: proposal_boxlist: A BoxList containing K proposal boxes in absolute coordinates. groundtruth_boxlist: A Boxlist containing N groundtruth object boxes in absolute coordinates. groundtruth_classes_with_background: A tensor with shape `[N, self.num_classes + 1]` representing groundtruth classes. The classes are assumed to be k-hot encoded, and include background as the zero-th class. Returns: a BoxList contained sampled proposals.
Samples a mini-batch of proposals to be sent to the box classifier.
[ "Samples", "a", "mini", "-", "batch", "of", "proposals", "to", "be", "sent", "to", "the", "box", "classifier", "." ]
def _sample_box_classifier_minibatch(self, proposal_boxlist, groundtruth_boxlist, groundtruth_classes_with_background): """Samples a mini-batch of proposals to be sent to the box classifier. Helper function for self._postprocess_rpn. Args: proposal_boxlist: A BoxList containing K proposal boxes in absolute coordinates. groundtruth_boxlist: A Boxlist containing N groundtruth object boxes in absolute coordinates. groundtruth_classes_with_background: A tensor with shape `[N, self.num_classes + 1]` representing groundtruth classes. The classes are assumed to be k-hot encoded, and include background as the zero-th class. Returns: a BoxList contained sampled proposals. """ (cls_targets, cls_weights, _, _, _) = self._detector_target_assigner.assign( proposal_boxlist, groundtruth_boxlist, groundtruth_classes_with_background) # Selects all boxes as candidates if none of them is selected according # to cls_weights. This could happen as boxes within certain IOU ranges # are ignored. If triggered, the selected boxes will still be ignored # during loss computation. cls_weights += tf.to_float(tf.equal(tf.reduce_sum(cls_weights), 0)) positive_indicator = tf.greater(tf.argmax(cls_targets, axis=1), 0) sampled_indices = self._second_stage_sampler.subsample( tf.cast(cls_weights, tf.bool), self._second_stage_batch_size, positive_indicator) return box_list_ops.boolean_mask(proposal_boxlist, sampled_indices)
[ "def", "_sample_box_classifier_minibatch", "(", "self", ",", "proposal_boxlist", ",", "groundtruth_boxlist", ",", "groundtruth_classes_with_background", ")", ":", "(", "cls_targets", ",", "cls_weights", ",", "_", ",", "_", ",", "_", ")", "=", "self", ".", "_detect...
https://github.com/datitran/object_detector_app/blob/44e8eddeb931cced5d8cf1e283383c720a5706bf/object_detection/meta_architectures/faster_rcnn_meta_arch.py#L957-L991
ilius/pyglossary
d599b3beda3ae17642af5debd83bb991148e6425
pyglossary/ui/ui_gtk.py
python
FormatDialog.updateTree
(self)
[]
def updateTree(self): model = self.treev.get_model() model.clear() for desc in self.items: model.append([desc]) if self.activeDesc: self.setCursor(self.activeDesc)
[ "def", "updateTree", "(", "self", ")", ":", "model", "=", "self", ".", "treev", ".", "get_model", "(", ")", "model", ".", "clear", "(", ")", "for", "desc", "in", "self", ".", "items", ":", "model", ".", "append", "(", "[", "desc", "]", ")", "if",...
https://github.com/ilius/pyglossary/blob/d599b3beda3ae17642af5debd83bb991148e6425/pyglossary/ui/ui_gtk.py#L204-L211
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/framework/homo/blocks/has_converged.py
python
Client.__init__
(self, trans_var: HasConvergedTransVar = None)
[]
def __init__(self, trans_var: HasConvergedTransVar = None): if trans_var is None: trans_var = HasConvergedTransVar() self._broadcaster = trans_var.has_converged self._server_parties = trans_var.server_parties
[ "def", "__init__", "(", "self", ",", "trans_var", ":", "HasConvergedTransVar", "=", "None", ")", ":", "if", "trans_var", "is", "None", ":", "trans_var", "=", "HasConvergedTransVar", "(", ")", "self", ".", "_broadcaster", "=", "trans_var", ".", "has_converged",...
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/framework/homo/blocks/has_converged.py#L40-L44
nfvlabs/openmano
b09eabec0a168aeda8adc3ea99f734e45e810205
openvim/utils/RADclass.py
python
ProcessorNode.set_eligible_cores
(self)
return
Set the default eligible cores, this is all cores non used by the host operating system
Set the default eligible cores, this is all cores non used by the host operating system
[ "Set", "the", "default", "eligible", "cores", "this", "is", "all", "cores", "non", "used", "by", "the", "host", "operating", "system" ]
def set_eligible_cores(self): """Set the default eligible cores, this is all cores non used by the host operating system""" not_first = False for iterator in self.cores: if not_first: self.eligible_cores.append(iterator) else: not_first = True return
[ "def", "set_eligible_cores", "(", "self", ")", ":", "not_first", "=", "False", "for", "iterator", "in", "self", ".", "cores", ":", "if", "not_first", ":", "self", ".", "eligible_cores", ".", "append", "(", "iterator", ")", "else", ":", "not_first", "=", ...
https://github.com/nfvlabs/openmano/blob/b09eabec0a168aeda8adc3ea99f734e45e810205/openvim/utils/RADclass.py#L517-L525
rlgraph/rlgraph
428fc136a9a075f29a397495b4226a491a287be2
rlgraph/components/policies/dueling_policy.py
python
DuelingPolicy.get_adapter_outputs
(self, nn_inputs)
return dict( nn_outputs=nn_outputs, adapter_outputs=q_values, advantages=advantages, q_values=q_values )
Args: nn_inputs (any): The input to our neural network. Returns: Dict: nn_outputs: The raw NN outputs. adapter_outputs: The q-values after adding advantages to state values (and subtracting the mean advantage). advantages: q_values:
Args: nn_inputs (any): The input to our neural network.
[ "Args", ":", "nn_inputs", "(", "any", ")", ":", "The", "input", "to", "our", "neural", "network", "." ]
def get_adapter_outputs(self, nn_inputs): """ Args: nn_inputs (any): The input to our neural network. Returns: Dict: nn_outputs: The raw NN outputs. adapter_outputs: The q-values after adding advantages to state values (and subtracting the mean advantage). advantages: q_values: """ nn_outputs = self.get_nn_outputs(nn_inputs) advantages, _, _, _ = self._graph_fn_get_adapter_outputs_and_parameters(nn_outputs) state_values_tmp = self.dense_layer_state_value_stream.call(nn_outputs) state_values = self.state_value_node.call(state_values_tmp) q_values = self._graph_fn_calculate_q_values(state_values, advantages) return dict( nn_outputs=nn_outputs, adapter_outputs=q_values, advantages=advantages, q_values=q_values )
[ "def", "get_adapter_outputs", "(", "self", ",", "nn_inputs", ")", ":", "nn_outputs", "=", "self", ".", "get_nn_outputs", "(", "nn_inputs", ")", "advantages", ",", "_", ",", "_", ",", "_", "=", "self", ".", "_graph_fn_get_adapter_outputs_and_parameters", "(", "...
https://github.com/rlgraph/rlgraph/blob/428fc136a9a075f29a397495b4226a491a287be2/rlgraph/components/policies/dueling_policy.py#L122-L147
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas/datastructures/halfedge/halfedge.py
python
HalfEdge.face_vertices
(self, fkey)
return self.face[fkey]
The vertices of a face. Parameters ---------- fkey : int Identifier of the face. Returns ------- list Ordered vertex identifiers.
The vertices of a face.
[ "The", "vertices", "of", "a", "face", "." ]
def face_vertices(self, fkey): """The vertices of a face. Parameters ---------- fkey : int Identifier of the face. Returns ------- list Ordered vertex identifiers. """ return self.face[fkey]
[ "def", "face_vertices", "(", "self", ",", "fkey", ")", ":", "return", "self", ".", "face", "[", "fkey", "]" ]
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas/datastructures/halfedge/halfedge.py#L2256-L2269
dulwich/dulwich
1f66817d712e3563ce1ff53b1218491a2eae39da
dulwich/protocol.py
python
Protocol.send_cmd
(self, cmd, *args)
Send a command and some arguments to a git server. Only used for the TCP git protocol (git://). Args: cmd: The remote service to access. args: List of arguments to send to remove service.
Send a command and some arguments to a git server.
[ "Send", "a", "command", "and", "some", "arguments", "to", "a", "git", "server", "." ]
def send_cmd(self, cmd, *args): """Send a command and some arguments to a git server. Only used for the TCP git protocol (git://). Args: cmd: The remote service to access. args: List of arguments to send to remove service. """ self.write_pkt_line(format_cmd_pkt(cmd, *args))
[ "def", "send_cmd", "(", "self", ",", "cmd", ",", "*", "args", ")", ":", "self", ".", "write_pkt_line", "(", "format_cmd_pkt", "(", "cmd", ",", "*", "args", ")", ")" ]
https://github.com/dulwich/dulwich/blob/1f66817d712e3563ce1ff53b1218491a2eae39da/dulwich/protocol.py#L341-L350
ManiacalLabs/BiblioPixel
afb993fbbe56e75e7c98f252df402b0f3e83bb6e
bibliopixel/builder/sections.py
python
set_one
(desc, name, value)
Set one section in a Project description
Set one section in a Project description
[ "Set", "one", "section", "in", "a", "Project", "description" ]
def set_one(desc, name, value): """Set one section in a Project description""" old_value = desc.get(name) if old_value is None: raise KeyError('No section "%s"' % name) if value is None: value = type(old_value)() elif name in CLASS_SECTIONS: if isinstance(value, str): value = {'typename': aliases.resolve(value)} elif isinstance(value, type): value = {'typename': class_name.class_name(value)} elif not isinstance(value, dict): raise TypeError('Expected dict, str or type, got "%s"' % value) typename = value.get('typename') if typename: s = 's' if name == 'driver' else '' path = 'bibliopixel.' + name + s importer.import_symbol(typename, path) elif name == 'shape': if not isinstance(value, (list, int, tuple, str)): raise TypeError('Expected shape, got "%s"' % value) elif type(old_value) is not type(value): raise TypeError('Expected %s but got "%s" of type %s' % (type(old_value), value, type(value))) desc[name] = value
[ "def", "set_one", "(", "desc", ",", "name", ",", "value", ")", ":", "old_value", "=", "desc", ".", "get", "(", "name", ")", "if", "old_value", "is", "None", ":", "raise", "KeyError", "(", "'No section \"%s\"'", "%", "name", ")", "if", "value", "is", ...
https://github.com/ManiacalLabs/BiblioPixel/blob/afb993fbbe56e75e7c98f252df402b0f3e83bb6e/bibliopixel/builder/sections.py#L8-L39
analyticalmindsltd/smote_variants
dedbc3d00b266954fedac0ae87775e1643bc920a
smote_variants/_smote_variants.py
python
Evaluation.do_evaluation
(self)
return list(evaluations.values())
Does the evaluation or reads it from file Returns: dict: all metrics
Does the evaluation or reads it from file
[ "Does", "the", "evaluation", "or", "reads", "it", "from", "file" ]
def do_evaluation(self): """ Does the evaluation or reads it from file Returns: dict: all metrics """ if self.n_threads is not None: try: import mkl mkl.set_num_threads(self.n_threads) message = " mkl thread number set to %d successfully" message = message % self.n_threads _logger.info(self.__class__.__name__ + message) except Exception as e: message = " setting mkl thread number didn't succeed" _logger.info(self.__class__.__name__ + message) evaluations = {} if os.path.isfile(os.path.join(self.cache_path, self.filename)): evaluations = pickle.load( open(os.path.join(self.cache_path, self.filename), 'rb')) already_evaluated = np.array([li in evaluations for li in self.labels]) if not np.all(already_evaluated): samp = self.sampling.do_sampling() else: return list(evaluations.values()) # setting random states for i in range(len(self.classifiers)): clf_params = self.classifiers[i].get_params() if 'random_state' in clf_params: clf_params['random_state'] = self.random_state self.classifiers[i] = self.classifiers[i].__class__( **clf_params) if isinstance(self.classifiers[i], CalibratedClassifierCV): clf_params = self.classifiers[i].base_estimator.get_params() clf_params['random_state'] = self.random_state class_inst = self.classifiers[i].base_estimator.__class__ new_inst = class_inst(**clf_params) self.classifiers[i].base_estimator = new_inst for i in range(len(self.classifiers)): if not already_evaluated[i]: message = " do the evaluation %s %s %s" message = message % (self.sampling.db_name, self.sampling.sampler.__name__, self.classifiers[i].__class__.__name__) _logger.info(self.__class__.__name__ + message) all_preds, all_tests, all_folds = [], [], [] minority_class_label = None majority_class_label = None fold_idx = -1 for X_train, y_train, X_test, y_test in samp['sampling']: fold_idx += 1 # X_train[X_train == np.inf]= 0 # X_train[X_train == -np.inf]= 0 # X_test[X_test == np.inf]= 0 # X_test[X_test == -np.inf]= 0 class_labels = np.unique(y_train) min_class_size = np.min( [np.sum(y_train == c) for c in class_labels]) ss = StandardScaler() X_train_trans = ss.fit_transform(X_train) nonzero_var_idx = np.where(ss.var_ > 1e-8)[0] X_test_trans = ss.transform(X_test) enough_minority_samples = min_class_size > 4 y_train_big_enough = len(y_train) > 4 two_classes = len(class_labels) > 1 at_least_one_feature = (len(nonzero_var_idx) > 0) if not enough_minority_samples: message = " not enough minority samples: %d" message = message % min_class_size _logger.warning( self.__class__.__name__ + message) elif not y_train_big_enough: message = (" number of minority training samples is " "not enough: %d") message = message % len(y_train) _logger.warning(self.__class__.__name__ + message) elif not two_classes: message = " there is only 1 class in training data" _logger.warning(self.__class__.__name__ + message) elif not at_least_one_feature: _logger.warning(self.__class__.__name__ + (" no information in features")) else: all_tests.append(y_test) if (minority_class_label is None or majority_class_label is None): class_labels = np.unique(y_train) n_0 = sum(class_labels[0] == y_test) n_1 = sum(class_labels[1] == y_test) if n_0 < n_1: minority_class_label = int(class_labels[0]) majority_class_label = int(class_labels[1]) else: minority_class_label = int(class_labels[1]) majority_class_label = int(class_labels[0]) X_fit = X_train_trans[:, nonzero_var_idx] self.classifiers[i].fit(X_fit, y_train) clf = self.classifiers[i] X_pred = X_test_trans[:, nonzero_var_idx] pred = clf.predict_proba(X_pred) all_preds.append(pred) all_folds.append( np.repeat(fold_idx, len(all_preds[-1]))) if len(all_tests) > 0: all_preds = np.vstack(all_preds) all_tests = np.hstack(all_tests) all_folds = np.hstack(all_folds) evaluations[self.labels[i]] = self.calculate_metrics( all_preds, all_tests, all_folds) else: evaluations[self.labels[i]] = self.calculate_metrics( None, None, None) evaluations[self.labels[i]]['runtime'] = samp['runtime'] sampler_name = self.sampling.sampler.__name__ evaluations[self.labels[i]]['sampler'] = sampler_name clf_name = self.classifiers[i].__class__.__name__ evaluations[self.labels[i]]['classifier'] = clf_name sampler_parameters = self.sampling.sampler_parameters.copy() evaluations[self.labels[i]]['sampler_parameters'] = str( sampler_parameters) evaluations[self.labels[i]]['classifier_parameters'] = str( self.classifiers[i].get_params()) evaluations[self.labels[i]]['sampler_categories'] = str( self.sampling.sampler.categories) evaluations[self.labels[i] ]['db_name'] = self.sampling.folding.db_name evaluations[self.labels[i]]['db_size'] = samp['db_size'] evaluations[self.labels[i]]['db_n_attr'] = samp['db_n_attr'] evaluations[self.labels[i] ]['imbalanced_ratio'] = samp['imbalanced_ratio'] if not np.all(already_evaluated): _logger.info(self.__class__.__name__ + (" dumping to file %s" % self.filename)) random_filename = os.path.join(self.cache_path, str( np.random.randint(1000000)) + '.pickle') pickle.dump(evaluations, open(random_filename, "wb")) os.rename(random_filename, os.path.join( self.cache_path, self.filename)) return list(evaluations.values())
[ "def", "do_evaluation", "(", "self", ")", ":", "if", "self", ".", "n_threads", "is", "not", "None", ":", "try", ":", "import", "mkl", "mkl", ".", "set_num_threads", "(", "self", ".", "n_threads", ")", "message", "=", "\" mkl thread number set to %d successfull...
https://github.com/analyticalmindsltd/smote_variants/blob/dedbc3d00b266954fedac0ae87775e1643bc920a/smote_variants/_smote_variants.py#L19826-L19983
google/closure-linter
c09c885b4e4fec386ff81cebeb8c66c2b0643d49
closure_linter/aliaspass.py
python
AliasPass._ProcessRootContext
(self, root_context)
Processes all goog.scope blocks under the root context.
Processes all goog.scope blocks under the root context.
[ "Processes", "all", "goog", ".", "scope", "blocks", "under", "the", "root", "context", "." ]
def _ProcessRootContext(self, root_context): """Processes all goog.scope blocks under the root context.""" assert root_context.type is ecmametadatapass.EcmaContext.ROOT # Process aliases in statements in the root scope for goog.module-style # aliases. global_alias_map = {} for context in root_context.children: if context.type == ecmametadatapass.EcmaContext.STATEMENT: for statement_child in context.children: if statement_child.type == ecmametadatapass.EcmaContext.VAR: match = scopeutil.MatchModuleAlias(statement_child) if match: # goog.require aliases cannot use further aliases, the symbol is # the second part of match, directly. symbol = match[1] if scopeutil.IsInClosurizedNamespace(symbol, self._closurized_namespaces): global_alias_map[match[0]] = symbol # Process each block to find aliases. for context in root_context.children: self._ProcessBlock(context, global_alias_map)
[ "def", "_ProcessRootContext", "(", "self", ",", "root_context", ")", ":", "assert", "root_context", ".", "type", "is", "ecmametadatapass", ".", "EcmaContext", ".", "ROOT", "# Process aliases in statements in the root scope for goog.module-style", "# aliases.", "global_alias_m...
https://github.com/google/closure-linter/blob/c09c885b4e4fec386ff81cebeb8c66c2b0643d49/closure_linter/aliaspass.py#L179-L202
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/contrib/formtools/wizard/views.py
python
WizardView.get_form_step_files
(self, form)
return form.files
Is used to return the raw form files. You may use this method to manipulate the data.
Is used to return the raw form files. You may use this method to manipulate the data.
[ "Is", "used", "to", "return", "the", "raw", "form", "files", ".", "You", "may", "use", "this", "method", "to", "manipulate", "the", "data", "." ]
def get_form_step_files(self, form): """ Is used to return the raw form files. You may use this method to manipulate the data. """ return form.files
[ "def", "get_form_step_files", "(", "self", ",", "form", ")", ":", "return", "form", ".", "files" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/contrib/formtools/wizard/views.py#L431-L436