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
Jiramew/spoon
a301f8e9fe6956b44b02861a3931143b987693b0
spoon_server/database/redis_wrapper.py
python
RedisWrapper.zremrangebyrank
(self, name, low, high)
[]
def zremrangebyrank(self, name, low, high): self._connection.zremrangebyrank(name, low, high)
[ "def", "zremrangebyrank", "(", "self", ",", "name", ",", "low", ",", "high", ")", ":", "self", ".", "_connection", ".", "zremrangebyrank", "(", "name", ",", "low", ",", "high", ")" ]
https://github.com/Jiramew/spoon/blob/a301f8e9fe6956b44b02861a3931143b987693b0/spoon_server/database/redis_wrapper.py#L57-L58
Louis-me/appiumn_auto
950a7853e412ce37855ed006bbaa845ca19c9463
Common/operateElement.py
python
operate_click
(mOperate,cts)
[]
def operate_click(mOperate,cts): if mOperate["find_type"] == common.find_element_by_id or mOperate["find_type"] == common.find_element_by_name or mOperate["find_type"] == common.find_element_by_xpath: elements_by(mOperate, cts).click() if mOperate["find_type"] == common.find_elements_by_id or mOperate["find_type"] == common.find_elements_by_name: elements_by(mOperate, cts)[mOperate["index"]].click() # 记录运行过程中的一些系统日志,比如闪退会造成自动化测试停止 if common.SELENIUM_APPIUM == common.APPIUM: # errorLog.get_error(log=mOperate["log"], devices=mOperate["devices"]) pass
[ "def", "operate_click", "(", "mOperate", ",", "cts", ")", ":", "if", "mOperate", "[", "\"find_type\"", "]", "==", "common", ".", "find_element_by_id", "or", "mOperate", "[", "\"find_type\"", "]", "==", "common", ".", "find_element_by_name", "or", "mOperate", "...
https://github.com/Louis-me/appiumn_auto/blob/950a7853e412ce37855ed006bbaa845ca19c9463/Common/operateElement.py#L46-L54
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/lib2to3/pytree.py
python
generate_matches
(patterns, nodes)
Generator yielding matches for a sequence of patterns and nodes. Args: patterns: a sequence of patterns nodes: a sequence of nodes Yields: (count, results) tuples where: count: the entire sequence of patterns matches nodes[:count]; results: dict containing named submatches.
Generator yielding matches for a sequence of patterns and nodes.
[ "Generator", "yielding", "matches", "for", "a", "sequence", "of", "patterns", "and", "nodes", "." ]
def generate_matches(patterns, nodes): """ Generator yielding matches for a sequence of patterns and nodes. Args: patterns: a sequence of patterns nodes: a sequence of nodes Yields: (count, results) tuples where: count: the entire sequence of patterns matches nodes[:count]; results: dict containing named submatches. """ if not patterns: yield 0, {} else: p, rest = patterns[0], patterns[1:] for c0, r0 in p.generate_matches(nodes): if not rest: yield c0, r0 else: for c1, r1 in generate_matches(rest, nodes[c0:]): r = {} r.update(r0) r.update(r1) yield c0 + c1, r
[ "def", "generate_matches", "(", "patterns", ",", "nodes", ")", ":", "if", "not", "patterns", ":", "yield", "0", ",", "{", "}", "else", ":", "p", ",", "rest", "=", "patterns", "[", "0", "]", ",", "patterns", "[", "1", ":", "]", "for", "c0", ",", ...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/lib2to3/pytree.py#L862-L887
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/blackbird/media_player.py
python
BlackbirdZone.update
(self)
Retrieve latest state.
Retrieve latest state.
[ "Retrieve", "latest", "state", "." ]
def update(self): """Retrieve latest state.""" state = self._blackbird.zone_status(self._zone_id) if not state: return self._attr_state = STATE_ON if state.power else STATE_OFF idx = state.av if idx in self._source_id_name: self._attr_source = self._source_id_name[idx] else: self._attr_source = None
[ "def", "update", "(", "self", ")", ":", "state", "=", "self", ".", "_blackbird", ".", "zone_status", "(", "self", ".", "_zone_id", ")", "if", "not", "state", ":", "return", "self", ".", "_attr_state", "=", "STATE_ON", "if", "state", ".", "power", "else...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/blackbird/media_player.py#L160-L170
huuuuusy/Mask-RCNN-Shiny
b59944ae08fda8dfc19d27a22acd59f94d8beb4f
mrcnn/utils.py
python
Dataset.source_image_link
(self, image_id)
return self.image_info[image_id]["path"]
Returns the path or URL to the image. Override this to return a URL to the image if it's availble online for easy debugging.
Returns the path or URL to the image. Override this to return a URL to the image if it's availble online for easy debugging.
[ "Returns", "the", "path", "or", "URL", "to", "the", "image", ".", "Override", "this", "to", "return", "a", "URL", "to", "the", "image", "if", "it", "s", "availble", "online", "for", "easy", "debugging", "." ]
def source_image_link(self, image_id): """Returns the path or URL to the image. Override this to return a URL to the image if it's availble online for easy debugging. """ return self.image_info[image_id]["path"]
[ "def", "source_image_link", "(", "self", ",", "image_id", ")", ":", "return", "self", ".", "image_info", "[", "image_id", "]", "[", "\"path\"", "]" ]
https://github.com/huuuuusy/Mask-RCNN-Shiny/blob/b59944ae08fda8dfc19d27a22acd59f94d8beb4f/mrcnn/utils.py#L353-L358
scikit-image/scikit-image
ed642e2bc822f362504d24379dee94978d6fa9de
skimage/transform/pyramids.py
python
pyramid_laplacian
(image, max_layer=-1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False, *, channel_axis=-1)
Yield images of the laplacian pyramid formed by the input image. Each layer contains the difference between the downsampled and the downsampled, smoothed image:: layer = resize(prev_layer) - smooth(resize(prev_layer)) Note that the first image of the pyramid will be the difference between the original, unscaled image and its smoothed version. The total number of images is `max_layer + 1`. In case all layers are computed, the last image is either a one-pixel image or the image where the reduction does not change its shape. Parameters ---------- image : ndarray Input image. max_layer : int, optional Number of layers for the pyramid. 0th layer is the original image. Default is -1 which builds all possible layers. downscale : float, optional Downscale factor. sigma : float, optional Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which corresponds to a filter mask twice the size of the scale factor that covers more than 99% of the Gaussian distribution. order : int, optional Order of splines used in interpolation of downsampling. See `skimage.transform.warp` for detail. mode : {'reflect', 'constant', 'edge', 'symmetric', 'wrap'}, optional The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to 'constant'. cval : float, optional Value to fill past edges of input if mode is 'constant'. multichannel : bool, optional Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. This argument is deprecated: specify `channel_axis` instead. preserve_range : bool, optional Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see https://scikit-image.org/docs/dev/user_guide/data_types.html channel_axis : int or None, optional If None, the image is assumed to be a grayscale (single channel) image. Otherwise, this parameter indicates which axis of the array corresponds to channels. .. versionadded:: 0.19 ``channel_axis`` was added in 0.19. Returns ------- pyramid : generator Generator yielding pyramid layers as float images. References ---------- .. [1] http://persci.mit.edu/pub_pdfs/pyramid83.pdf .. [2] http://sepwww.stanford.edu/data/media/public/sep/morgan/texturematch/paper_html/node3.html
Yield images of the laplacian pyramid formed by the input image.
[ "Yield", "images", "of", "the", "laplacian", "pyramid", "formed", "by", "the", "input", "image", "." ]
def pyramid_laplacian(image, max_layer=-1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False, *, channel_axis=-1): """Yield images of the laplacian pyramid formed by the input image. Each layer contains the difference between the downsampled and the downsampled, smoothed image:: layer = resize(prev_layer) - smooth(resize(prev_layer)) Note that the first image of the pyramid will be the difference between the original, unscaled image and its smoothed version. The total number of images is `max_layer + 1`. In case all layers are computed, the last image is either a one-pixel image or the image where the reduction does not change its shape. Parameters ---------- image : ndarray Input image. max_layer : int, optional Number of layers for the pyramid. 0th layer is the original image. Default is -1 which builds all possible layers. downscale : float, optional Downscale factor. sigma : float, optional Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which corresponds to a filter mask twice the size of the scale factor that covers more than 99% of the Gaussian distribution. order : int, optional Order of splines used in interpolation of downsampling. See `skimage.transform.warp` for detail. mode : {'reflect', 'constant', 'edge', 'symmetric', 'wrap'}, optional The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to 'constant'. cval : float, optional Value to fill past edges of input if mode is 'constant'. multichannel : bool, optional Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. This argument is deprecated: specify `channel_axis` instead. preserve_range : bool, optional Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see https://scikit-image.org/docs/dev/user_guide/data_types.html channel_axis : int or None, optional If None, the image is assumed to be a grayscale (single channel) image. Otherwise, this parameter indicates which axis of the array corresponds to channels. .. versionadded:: 0.19 ``channel_axis`` was added in 0.19. Returns ------- pyramid : generator Generator yielding pyramid layers as float images. References ---------- .. [1] http://persci.mit.edu/pub_pdfs/pyramid83.pdf .. [2] http://sepwww.stanford.edu/data/media/public/sep/morgan/texturematch/paper_html/node3.html """ _check_factor(downscale) # cast to float for consistent data type in pyramid image = convert_to_float(image, preserve_range) if sigma is None: # automatically determine sigma which covers > 99% of distribution sigma = 2 * downscale / 6.0 current_shape = image.shape smoothed_image = _smooth(image, sigma, mode, cval, channel_axis) yield image - smoothed_image if channel_axis is not None: channel_axis = channel_axis % image.ndim shape_without_channels = list(current_shape) shape_without_channels.pop(channel_axis) shape_without_channels = tuple(shape_without_channels) else: shape_without_channels = current_shape # build downsampled images until max_layer is reached or downscale process # does not change image size if max_layer == -1: max_layer = math.ceil(math.log(max(shape_without_channels), downscale)) for layer in range(max_layer): if channel_axis is not None: out_shape = tuple( math.ceil(d / float(downscale)) if ax != channel_axis else d for ax, d in enumerate(current_shape) ) else: out_shape = tuple(math.ceil(d / float(downscale)) for d in current_shape) resized_image = resize(smoothed_image, out_shape, order=order, mode=mode, cval=cval, anti_aliasing=False) smoothed_image = _smooth(resized_image, sigma, mode, cval, channel_axis) current_shape = resized_image.shape yield resized_image - smoothed_image
[ "def", "pyramid_laplacian", "(", "image", ",", "max_layer", "=", "-", "1", ",", "downscale", "=", "2", ",", "sigma", "=", "None", ",", "order", "=", "1", ",", "mode", "=", "'reflect'", ",", "cval", "=", "0", ",", "multichannel", "=", "False", ",", ...
https://github.com/scikit-image/scikit-image/blob/ed642e2bc822f362504d24379dee94978d6fa9de/skimage/transform/pyramids.py#L270-L378
scanny/python-pptx
71d1ca0b2b3b9178d64cdab565e8503a25a54e0b
pptx/chart/data.py
python
_BaseDataPoint.number_format
(self)
return number_format
The formatting template string that determines how the value of this data point is formatted, both in the chart and in the Excel spreadsheet; for example '#,##0.0'. If not specified for this data point, it is inherited from the parent series data object.
The formatting template string that determines how the value of this data point is formatted, both in the chart and in the Excel spreadsheet; for example '#,##0.0'. If not specified for this data point, it is inherited from the parent series data object.
[ "The", "formatting", "template", "string", "that", "determines", "how", "the", "value", "of", "this", "data", "point", "is", "formatted", "both", "in", "the", "chart", "and", "in", "the", "Excel", "spreadsheet", ";", "for", "example", "#", "##0", ".", "0",...
def number_format(self): """ The formatting template string that determines how the value of this data point is formatted, both in the chart and in the Excel spreadsheet; for example '#,##0.0'. If not specified for this data point, it is inherited from the parent series data object. """ number_format = self._number_format if number_format is None: return self._series_data.number_format return number_format
[ "def", "number_format", "(", "self", ")", ":", "number_format", "=", "self", ".", "_number_format", "if", "number_format", "is", "None", ":", "return", "self", ".", "_series_data", ".", "number_format", "return", "number_format" ]
https://github.com/scanny/python-pptx/blob/71d1ca0b2b3b9178d64cdab565e8503a25a54e0b/pptx/chart/data.py#L243-L253
spywhere/Javatar
e273ec40c209658247a71b109bb90cd126984a29
core/build_system.py
python
_BuildSystem.reset
(self)
Reset the instance variables to clear the build
Reset the instance variables to clear the build
[ "Reset", "the", "instance", "variables", "to", "clear", "the", "build" ]
def reset(self): """ Reset the instance variables to clear the build """ self.failed = False self.building = False self.builders = [] self.create_log = False self.finish_callback = None self.cancel_callback = None
[ "def", "reset", "(", "self", ")", ":", "self", ".", "failed", "=", "False", "self", ".", "building", "=", "False", "self", ".", "builders", "=", "[", "]", "self", ".", "create_log", "=", "False", "self", ".", "finish_callback", "=", "None", "self", "...
https://github.com/spywhere/Javatar/blob/e273ec40c209658247a71b109bb90cd126984a29/core/build_system.py#L28-L37
conjure-up/conjure-up
d2bf8ab8e71ff01321d0e691a8d3e3833a047678
conjureup/ui/views/destroy.py
python
DestroyView._build_footer
(self)
return footer_pile
[]
def _build_footer(self): footer_pile = Pile([ Padding.line_break(""), Color.frame_footer( Columns([ ('fixed', 2, Text("")), ('fixed', 13, self._build_buttons()) ])) ]) return footer_pile
[ "def", "_build_footer", "(", "self", ")", ":", "footer_pile", "=", "Pile", "(", "[", "Padding", ".", "line_break", "(", "\"\"", ")", ",", "Color", ".", "frame_footer", "(", "Columns", "(", "[", "(", "'fixed'", ",", "2", ",", "Text", "(", "\"\"", ")",...
https://github.com/conjure-up/conjure-up/blob/d2bf8ab8e71ff01321d0e691a8d3e3833a047678/conjureup/ui/views/destroy.py#L48-L57
francisck/DanderSpritz_docs
86bb7caca5a957147f120b18bb5c31f299914904
Python/Core/Lib/lib2to3/pytree.py
python
BasePattern.__new__
(cls, *args, **kwds)
return object.__new__(cls)
Constructor that prevents BasePattern from being instantiated.
Constructor that prevents BasePattern from being instantiated.
[ "Constructor", "that", "prevents", "BasePattern", "from", "being", "instantiated", "." ]
def __new__(cls, *args, **kwds): """Constructor that prevents BasePattern from being instantiated.""" return object.__new__(cls)
[ "def", "__new__", "(", "cls", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "return", "object", ".", "__new__", "(", "cls", ")" ]
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/lib2to3/pytree.py#L460-L462
gcovr/gcovr
09e89b5287fa5a11408a208cb34aea0efd19d4f5
gcovr/gcov.py
python
process_datafile
(filename, covdata, options, toerase)
r"""Run gcovr in a suitable directory to collect coverage from gcda files. Params: filename (path): the path to a gcda or gcno file covdata (dict, mutable): the global covdata dictionary options (object): the configuration options namespace toerase (set, mutable): files that should be deleted later workdir (path or None): the per-thread work directory Returns: Nothing. Finding a suitable working directory is tricky. The coverage files (gcda and gcno) are stored next to object (.o) files. However, gcov needs to also resolve the source file name. The relative source file paths in the coverage data are relative to the gcc working directory. Therefore, gcov must be invoked in the same directory as gcc. How to find that directory? By various heuristics. This is complicated by the problem that the build process tells gcc where to run, where the sources are, and where to put the object files. We only know the object files and have to work everything out in reverse. If present, the *workdir* argument is always tried first. Ideally, the build process only runs gcc from *one* directory and the user can provide this directory as the ``--object-directory``. If it exists, we try that path as a workdir, If the path is relative, it is resolved relative to the gcovr cwd and the object file location. We next try the ``--root`` directory. TODO: should probably also be the gcovr start directory. If none of those work, we assume that the object files are in a subdirectory of the gcc working directory, i.e. we can walk the directory tree upwards. All of this works fine unless gcc was invoked like ``gcc -o ../path``, i.e. the object files are in a sibling directory. TODO: So far there is no good way to address this case.
r"""Run gcovr in a suitable directory to collect coverage from gcda files.
[ "r", "Run", "gcovr", "in", "a", "suitable", "directory", "to", "collect", "coverage", "from", "gcda", "files", "." ]
def process_datafile(filename, covdata, options, toerase): r"""Run gcovr in a suitable directory to collect coverage from gcda files. Params: filename (path): the path to a gcda or gcno file covdata (dict, mutable): the global covdata dictionary options (object): the configuration options namespace toerase (set, mutable): files that should be deleted later workdir (path or None): the per-thread work directory Returns: Nothing. Finding a suitable working directory is tricky. The coverage files (gcda and gcno) are stored next to object (.o) files. However, gcov needs to also resolve the source file name. The relative source file paths in the coverage data are relative to the gcc working directory. Therefore, gcov must be invoked in the same directory as gcc. How to find that directory? By various heuristics. This is complicated by the problem that the build process tells gcc where to run, where the sources are, and where to put the object files. We only know the object files and have to work everything out in reverse. If present, the *workdir* argument is always tried first. Ideally, the build process only runs gcc from *one* directory and the user can provide this directory as the ``--object-directory``. If it exists, we try that path as a workdir, If the path is relative, it is resolved relative to the gcovr cwd and the object file location. We next try the ``--root`` directory. TODO: should probably also be the gcovr start directory. If none of those work, we assume that the object files are in a subdirectory of the gcc working directory, i.e. we can walk the directory tree upwards. All of this works fine unless gcc was invoked like ``gcc -o ../path``, i.e. the object files are in a sibling directory. TODO: So far there is no good way to address this case. """ logger = Logger(options.verbose) logger.verbose_msg("Processing file: {}", filename) abs_filename = os.path.abspath(filename) errors = [] potential_wd = [] if options.objdir: potential_wd = find_potential_working_directories_via_objdir( abs_filename, options.objdir, error=errors.append ) # no objdir was specified or objdir didn't exist consider_parent_directories = not potential_wd # Always add the root directory potential_wd.append(options.root_dir) if consider_parent_directories: wd = os.path.dirname(abs_filename) while wd != potential_wd[-1]: potential_wd.append(wd) wd = os.path.dirname(wd) for wd in potential_wd: done = run_gcov_and_process_files( abs_filename, covdata, options=options, logger=logger, toerase=toerase, error=errors.append, chdir=wd, ) if options.delete: if not abs_filename.endswith("gcno"): toerase.add(abs_filename) if done: return logger.warn( "GCOV produced the following errors processing {filename}:\n" "\t{errors}\n" "\t(gcovr could not infer a working directory that resolved it.)", filename=filename, errors="\n\t".join(errors), )
[ "def", "process_datafile", "(", "filename", ",", "covdata", ",", "options", ",", "toerase", ")", ":", "logger", "=", "Logger", "(", "options", ".", "verbose", ")", "logger", ".", "verbose_msg", "(", "\"Processing file: {}\"", ",", "filename", ")", "abs_filenam...
https://github.com/gcovr/gcovr/blob/09e89b5287fa5a11408a208cb34aea0efd19d4f5/gcovr/gcov.py#L255-L350
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_glusterfs_persistent_volume_source.py
python
V1GlusterfsPersistentVolumeSource.endpoints_namespace
(self, endpoints_namespace)
Sets the endpoints_namespace of this V1GlusterfsPersistentVolumeSource. EndpointsNamespace is the namespace that contains Glusterfs endpoint. If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501 :param endpoints_namespace: The endpoints_namespace of this V1GlusterfsPersistentVolumeSource. # noqa: E501 :type: str
Sets the endpoints_namespace of this V1GlusterfsPersistentVolumeSource.
[ "Sets", "the", "endpoints_namespace", "of", "this", "V1GlusterfsPersistentVolumeSource", "." ]
def endpoints_namespace(self, endpoints_namespace): """Sets the endpoints_namespace of this V1GlusterfsPersistentVolumeSource. EndpointsNamespace is the namespace that contains Glusterfs endpoint. If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod # noqa: E501 :param endpoints_namespace: The endpoints_namespace of this V1GlusterfsPersistentVolumeSource. # noqa: E501 :type: str """ self._endpoints_namespace = endpoints_namespace
[ "def", "endpoints_namespace", "(", "self", ",", "endpoints_namespace", ")", ":", "self", ".", "_endpoints_namespace", "=", "endpoints_namespace" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_glusterfs_persistent_volume_source.py#L105-L114
koursaros-ai/nboost
38123ba9ad52d33afd844a38b46ca702a00cfa6c
nboost/plugins/rerank/transformers.py
python
PtTransformersRerankPlugin.get_logits
(self, query: str, choices: List[str])
:param query: :param choices: :return: logits
:param query: :param choices: :return: logits
[ ":", "param", "query", ":", ":", "param", "choices", ":", ":", "return", ":", "logits" ]
def get_logits(self, query: str, choices: List[str]): """ :param query: :param choices: :return: logits """ input_ids, attention_mask, token_type_ids = self.encode(query, choices) with torch.no_grad(): logits = self.rerank_model(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)[0] logits = logits.detach().cpu().numpy() return logits
[ "def", "get_logits", "(", "self", ",", "query", ":", "str", ",", "choices", ":", "List", "[", "str", "]", ")", ":", "input_ids", ",", "attention_mask", ",", "token_type_ids", "=", "self", ".", "encode", "(", "query", ",", "choices", ")", "with", "torch...
https://github.com/koursaros-ai/nboost/blob/38123ba9ad52d33afd844a38b46ca702a00cfa6c/nboost/plugins/rerank/transformers.py#L37-L51
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_node_system_info.py
python
V1NodeSystemInfo.container_runtime_version
(self, container_runtime_version)
Sets the container_runtime_version of this V1NodeSystemInfo. ContainerRuntime Version reported by the node through runtime remote API (e.g. docker://1.5.0). # noqa: E501 :param container_runtime_version: The container_runtime_version of this V1NodeSystemInfo. # noqa: E501 :type: str
Sets the container_runtime_version of this V1NodeSystemInfo.
[ "Sets", "the", "container_runtime_version", "of", "this", "V1NodeSystemInfo", "." ]
def container_runtime_version(self, container_runtime_version): """Sets the container_runtime_version of this V1NodeSystemInfo. ContainerRuntime Version reported by the node through runtime remote API (e.g. docker://1.5.0). # noqa: E501 :param container_runtime_version: The container_runtime_version of this V1NodeSystemInfo. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and container_runtime_version is None: # noqa: E501 raise ValueError("Invalid value for `container_runtime_version`, must not be `None`") # noqa: E501 self._container_runtime_version = container_runtime_version
[ "def", "container_runtime_version", "(", "self", ",", "container_runtime_version", ")", ":", "if", "self", ".", "local_vars_configuration", ".", "client_side_validation", "and", "container_runtime_version", "is", "None", ":", "# noqa: E501", "raise", "ValueError", "(", ...
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_node_system_info.py#L152-L163
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventTypeArg.is_no_expiration_link_gen_create_report
(self)
return self._tag == 'no_expiration_link_gen_create_report'
Check if the union tag is ``no_expiration_link_gen_create_report``. :rtype: bool
Check if the union tag is ``no_expiration_link_gen_create_report``.
[ "Check", "if", "the", "union", "tag", "is", "no_expiration_link_gen_create_report", "." ]
def is_no_expiration_link_gen_create_report(self): """ Check if the union tag is ``no_expiration_link_gen_create_report``. :rtype: bool """ return self._tag == 'no_expiration_link_gen_create_report'
[ "def", "is_no_expiration_link_gen_create_report", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'no_expiration_link_gen_create_report'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L41695-L41701
pgmpy/pgmpy
24279929a28082ea994c52f3d165ca63fc56b02b
pgmpy/models/ClusterGraph.py
python
ClusterGraph.get_cardinality
(self, node=None)
Returns the cardinality of the node Parameters ---------- node: any hashable python object (optional) The node whose cardinality we want. If node is not specified returns a dictionary with the given variable as keys and their respective cardinality as values. Returns ------- int or dict : If node is specified returns the cardinality of the node. If node is not specified returns a dictionary with the given variable as keys and their respective cardinality as values. Examples -------- >>> from pgmpy.models import ClusterGraph >>> from pgmpy.factors.discrete import DiscreteFactor >>> student = ClusterGraph() >>> factor = DiscreteFactor(['Alice', 'Bob'], cardinality=[2, 2], ... values=np.random.rand(4)) >>> student.add_node(('Alice', 'Bob')) >>> student.add_factors(factor) >>> student.get_cardinality() defaultdict(<class 'int'>, {'Alice': 2, 'Bob': 2}) >>> student.get_cardinality(node='Alice') 2
Returns the cardinality of the node
[ "Returns", "the", "cardinality", "of", "the", "node" ]
def get_cardinality(self, node=None): """ Returns the cardinality of the node Parameters ---------- node: any hashable python object (optional) The node whose cardinality we want. If node is not specified returns a dictionary with the given variable as keys and their respective cardinality as values. Returns ------- int or dict : If node is specified returns the cardinality of the node. If node is not specified returns a dictionary with the given variable as keys and their respective cardinality as values. Examples -------- >>> from pgmpy.models import ClusterGraph >>> from pgmpy.factors.discrete import DiscreteFactor >>> student = ClusterGraph() >>> factor = DiscreteFactor(['Alice', 'Bob'], cardinality=[2, 2], ... values=np.random.rand(4)) >>> student.add_node(('Alice', 'Bob')) >>> student.add_factors(factor) >>> student.get_cardinality() defaultdict(<class 'int'>, {'Alice': 2, 'Bob': 2}) >>> student.get_cardinality(node='Alice') 2 """ if node: for factor in self.factors: for variable, cardinality in zip(factor.scope(), factor.cardinality): if node == variable: return cardinality else: cardinalities = defaultdict(int) for factor in self.factors: for variable, cardinality in zip(factor.scope(), factor.cardinality): cardinalities[variable] = cardinality return cardinalities
[ "def", "get_cardinality", "(", "self", ",", "node", "=", "None", ")", ":", "if", "node", ":", "for", "factor", "in", "self", ".", "factors", ":", "for", "variable", ",", "cardinality", "in", "zip", "(", "factor", ".", "scope", "(", ")", ",", "factor"...
https://github.com/pgmpy/pgmpy/blob/24279929a28082ea994c52f3d165ca63fc56b02b/pgmpy/models/ClusterGraph.py#L215-L259
mongodb/pymodm
be1c7b079df4954ef7e79e46f1b4a9ac9510766c
pymodm/fields.py
python
IntegerField.__init__
(self, verbose_name=None, mongo_name=None, min_value=None, max_value=None, **kwargs)
:parameters: - `verbose_name`: A human-readable name for the Field. - `mongo_name`: The name of this field when stored in MongoDB. - `min_value`: The minimum value that can be stored in this field. - `max_value`: The maximum value that can be stored in this field. .. seealso:: constructor for :class:`~pymodm.base.fields.MongoBaseField`
:parameters: - `verbose_name`: A human-readable name for the Field. - `mongo_name`: The name of this field when stored in MongoDB. - `min_value`: The minimum value that can be stored in this field. - `max_value`: The maximum value that can be stored in this field.
[ ":", "parameters", ":", "-", "verbose_name", ":", "A", "human", "-", "readable", "name", "for", "the", "Field", ".", "-", "mongo_name", ":", "The", "name", "of", "this", "field", "when", "stored", "in", "MongoDB", ".", "-", "min_value", ":", "The", "mi...
def __init__(self, verbose_name=None, mongo_name=None, min_value=None, max_value=None, **kwargs): """ :parameters: - `verbose_name`: A human-readable name for the Field. - `mongo_name`: The name of this field when stored in MongoDB. - `min_value`: The minimum value that can be stored in this field. - `max_value`: The maximum value that can be stored in this field. .. seealso:: constructor for :class:`~pymodm.base.fields.MongoBaseField` """ super(IntegerField, self).__init__(verbose_name=verbose_name, mongo_name=mongo_name, **kwargs) self.validators.append( validators.together( validators.validator_for_func(int), validators.validator_for_min_max(min_value, max_value)))
[ "def", "__init__", "(", "self", ",", "verbose_name", "=", "None", ",", "mongo_name", "=", "None", ",", "min_value", "=", "None", ",", "max_value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "IntegerField", ",", "self", ")", ".", "_...
https://github.com/mongodb/pymodm/blob/be1c7b079df4954ef7e79e46f1b4a9ac9510766c/pymodm/fields.py#L108-L126
rigetti/pyquil
36987ecb78d5dc85d299dd62395b7669a1cedd5a
pyquil/quantum_processor/_base.py
python
AbstractQuantumProcessor.qubits
(self)
A sorted list of qubits in the quantum_processor topology.
A sorted list of qubits in the quantum_processor topology.
[ "A", "sorted", "list", "of", "qubits", "in", "the", "quantum_processor", "topology", "." ]
def qubits(self) -> List[int]: """ A sorted list of qubits in the quantum_processor topology. """
[ "def", "qubits", "(", "self", ")", "->", "List", "[", "int", "]", ":" ]
https://github.com/rigetti/pyquil/blob/36987ecb78d5dc85d299dd62395b7669a1cedd5a/pyquil/quantum_processor/_base.py#L29-L32
Kozea/cairocffi
2473d1bb82a52ca781edec595a95951509db2969
cairocffi/pixbuf.py
python
decode_to_pixbuf
(image_data, width=None, height=None)
return Pixbuf(pixbuf), format_name
Decode an image from memory with GDK-PixBuf. The file format is detected automatically. :param image_data: A byte string :param width: Integer width in pixels or None :param height: Integer height in pixels or None :returns: A tuple of a new :class:`PixBuf` object and the name of the detected image format. :raises: :exc:`ImageLoadingError` if the image data is invalid or in an unsupported format.
Decode an image from memory with GDK-PixBuf. The file format is detected automatically.
[ "Decode", "an", "image", "from", "memory", "with", "GDK", "-", "PixBuf", ".", "The", "file", "format", "is", "detected", "automatically", "." ]
def decode_to_pixbuf(image_data, width=None, height=None): """Decode an image from memory with GDK-PixBuf. The file format is detected automatically. :param image_data: A byte string :param width: Integer width in pixels or None :param height: Integer height in pixels or None :returns: A tuple of a new :class:`PixBuf` object and the name of the detected image format. :raises: :exc:`ImageLoadingError` if the image data is invalid or in an unsupported format. """ loader = ffi.gc( gdk_pixbuf.gdk_pixbuf_loader_new(), gobject.g_object_unref) error = ffi.new('GError **') if width and height: gdk_pixbuf.gdk_pixbuf_loader_set_size(loader, width, height) handle_g_error(error, gdk_pixbuf.gdk_pixbuf_loader_write( loader, image_data, len(image_data), error)) handle_g_error(error, gdk_pixbuf.gdk_pixbuf_loader_close(loader, error)) format_ = gdk_pixbuf.gdk_pixbuf_loader_get_format(loader) format_name = ( ffi.string(gdk_pixbuf.gdk_pixbuf_format_get_name(format_)) .decode('ascii') if format_ != ffi.NULL else None) pixbuf = gdk_pixbuf.gdk_pixbuf_loader_get_pixbuf(loader) if pixbuf == ffi.NULL: # pragma: no cover raise ImageLoadingError('Not enough image data (got a NULL pixbuf.)') return Pixbuf(pixbuf), format_name
[ "def", "decode_to_pixbuf", "(", "image_data", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "loader", "=", "ffi", ".", "gc", "(", "gdk_pixbuf", ".", "gdk_pixbuf_loader_new", "(", ")", ",", "gobject", ".", "g_object_unref", ")", "error", ...
https://github.com/Kozea/cairocffi/blob/2473d1bb82a52ca781edec595a95951509db2969/cairocffi/pixbuf.py#L78-L111
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/html5lib/_inputstream.py
python
HTMLUnicodeInputStream.position
(self)
return (line + 1, col)
Returns (line, col) of the current position in the stream.
Returns (line, col) of the current position in the stream.
[ "Returns", "(", "line", "col", ")", "of", "the", "current", "position", "in", "the", "stream", "." ]
def position(self): """Returns (line, col) of the current position in the stream.""" line, col = self._position(self.chunkOffset) return (line + 1, col)
[ "def", "position", "(", "self", ")", ":", "line", ",", "col", "=", "self", ".", "_position", "(", "self", ".", "chunkOffset", ")", "return", "(", "line", "+", "1", ",", "col", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/html5lib/_inputstream.py#L229-L232
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/scripts/texi2html.py
python
TexinfoParser.open_minus
(self)
[]
def open_minus(self): self.write('-')
[ "def", "open_minus", "(", "self", ")", ":", "self", ".", "write", "(", "'-'", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/scripts/texi2html.py#L591-L591
ewels/MultiQC
9b953261d3d684c24eef1827a5ce6718c847a5af
multiqc/modules/deeptools/bamPEFragmentSizeDistribution.py
python
bamPEFragmentSizeDistributionMixin.parse_bamPEFragmentSizeDistribution
(self)
return len(self.deeptools_bamPEFragmentSizeDistribution)
Find bamPEFragmentSize output. Supports the --outRawFragmentLengths option
Find bamPEFragmentSize output. Supports the --outRawFragmentLengths option
[ "Find", "bamPEFragmentSize", "output", ".", "Supports", "the", "--", "outRawFragmentLengths", "option" ]
def parse_bamPEFragmentSizeDistribution(self): """Find bamPEFragmentSize output. Supports the --outRawFragmentLengths option""" self.deeptools_bamPEFragmentSizeDistribution = dict() for f in self.find_log_files("deeptools/bamPEFragmentSizeDistribution", filehandles=False): parsed_data = self.parseBamPEFDistributionFile(f) for k, v in parsed_data.items(): if k in self.deeptools_bamPEFragmentSizeDistribution: log.warning("Replacing duplicate sample {}.".format(k)) self.deeptools_bamPEFragmentSizeDistribution[k] = v if len(parsed_data) > 0: self.add_data_source(f, section="bamPEFragmentSizeDistribution") self.deeptools_bamPEFragmentSizeDistribution = self.ignore_samples(self.deeptools_bamPEFragmentSizeDistribution) if len(self.deeptools_bamPEFragmentSizeDistribution) > 0: # Write data to file self.write_data_file(self.deeptools_bamPEFragmentSizeDistribution, "deeptools_frag_size_dist") config = { "id": "fragment_size_distribution_plot", "title": "deeptools: Fragment Size Distribution Plot", "ylab": "Occurrence", "xlab": "Fragment Size (bp)", "smooth_points": 50, "xmax": 1000, "xDecimals": False, "tt_label": "<b>Fragment Size (bp) {point.x}</b>: {point.y} Occurrence", } self.add_section( name="Fragment size distribution", anchor="fragment_size_distribution", description="Distribution of paired-end fragment sizes", plot=linegraph.plot(self.deeptools_bamPEFragmentSizeDistribution, config), ) return len(self.deeptools_bamPEFragmentSizeDistribution)
[ "def", "parse_bamPEFragmentSizeDistribution", "(", "self", ")", ":", "self", ".", "deeptools_bamPEFragmentSizeDistribution", "=", "dict", "(", ")", "for", "f", "in", "self", ".", "find_log_files", "(", "\"deeptools/bamPEFragmentSizeDistribution\"", ",", "filehandles", "...
https://github.com/ewels/MultiQC/blob/9b953261d3d684c24eef1827a5ce6718c847a5af/multiqc/modules/deeptools/bamPEFragmentSizeDistribution.py#L14-L50
markj3d/Red9_StudioPack
1d40a8bf84c45ce7eaefdd9ccfa3cdbeb1471919
core/Red9_Audio.py
python
AudioNode.endTime
(self)
return (self.endFrame / r9General.getCurrentFPS()) * 1000
: PRO_PACK : Maya end time of the sound node in milliseconds
: PRO_PACK : Maya end time of the sound node in milliseconds
[ ":", "PRO_PACK", ":", "Maya", "end", "time", "of", "the", "sound", "node", "in", "milliseconds" ]
def endTime(self): ''' : PRO_PACK : Maya end time of the sound node in milliseconds ''' return (self.endFrame / r9General.getCurrentFPS()) * 1000
[ "def", "endTime", "(", "self", ")", ":", "return", "(", "self", ".", "endFrame", "/", "r9General", ".", "getCurrentFPS", "(", ")", ")", "*", "1000" ]
https://github.com/markj3d/Red9_StudioPack/blob/1d40a8bf84c45ce7eaefdd9ccfa3cdbeb1471919/core/Red9_Audio.py#L749-L753
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
python
TimeoutFactory.callLater
(self, period, func)
return reactor.callLater(period, func)
Wrapper around L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>} for test purpose.
Wrapper around L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>} for test purpose.
[ "Wrapper", "around", "L", "{", "reactor", ".", "callLater<twisted", ".", "internet", ".", "interfaces", ".", "IReactorTime", ".", "callLater", ">", "}", "for", "test", "purpose", "." ]
def callLater(self, period, func): """ Wrapper around L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>} for test purpose. """ from twisted.internet import reactor return reactor.callLater(period, func)
[ "def", "callLater", "(", "self", ",", "period", ",", "func", ")", ":", "from", "twisted", ".", "internet", "import", "reactor", "return", "reactor", ".", "callLater", "(", "period", ",", "func", ")" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py#L569-L576
TurboGears/tg2
f40a82d016d70ce560002593b4bb8f83b57f87b3
tg/configurator/base.py
python
Configurator.update_blueprint
(self, config)
Add options from ``config`` to the configuration blueprint.
Add options from ``config`` to the configuration blueprint.
[ "Add", "options", "from", "config", "to", "the", "configuration", "blueprint", "." ]
def update_blueprint(self, config): """Add options from ``config`` to the configuration blueprint.""" self._blueprint.update(config)
[ "def", "update_blueprint", "(", "self", ",", "config", ")", ":", "self", ".", "_blueprint", ".", "update", "(", "config", ")" ]
https://github.com/TurboGears/tg2/blob/f40a82d016d70ce560002593b4bb8f83b57f87b3/tg/configurator/base.py#L41-L43
ninthDevilHAUNSTER/ArknightsAutoHelper
a27a930502d6e432368d9f62595a1d69a992f4e6
vendor/penguin_client/penguin_client/api/_deprecated_ap_is_api.py
python
DeprecatedAPIsApi.get_zone_by_zone_id_using_get_with_http_info
(self, zone_id, **kwargs)
return self.api_client.call_api( '/api/zones/{zoneId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Zone', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
Get zone by zone ID # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_zone_by_zone_id_using_get_with_http_info(zone_id, async_req=True) >>> result = thread.get() :param async_req bool :param str zone_id: zoneId (required) :param bool i18n: i18n :return: Zone If the method is called asynchronously, returns the request thread.
Get zone by zone ID # noqa: E501
[ "Get", "zone", "by", "zone", "ID", "#", "noqa", ":", "E501" ]
def get_zone_by_zone_id_using_get_with_http_info(self, zone_id, **kwargs): # noqa: E501 """Get zone by zone ID # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_zone_by_zone_id_using_get_with_http_info(zone_id, async_req=True) >>> result = thread.get() :param async_req bool :param str zone_id: zoneId (required) :param bool i18n: i18n :return: Zone If the method is called asynchronously, returns the request thread. """ all_params = ['zone_id', 'i18n'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_zone_by_zone_id_using_get" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'zone_id' is set if ('zone_id' not in params or params['zone_id'] is None): raise ValueError("Missing the required parameter `zone_id` when calling `get_zone_by_zone_id_using_get`") # noqa: E501 collection_formats = {} path_params = {} if 'zone_id' in params: path_params['zoneId'] = params['zone_id'] # noqa: E501 query_params = [] if 'i18n' in params: query_params.append(('i18n', params['i18n'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json;charset=UTF-8']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 return self.api_client.call_api( '/api/zones/{zoneId}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='Zone', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
[ "def", "get_zone_by_zone_id_using_get_with_http_info", "(", "self", ",", "zone_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "all_params", "=", "[", "'zone_id'", ",", "'i18n'", "]", "# noqa: E501", "all_params", ".", "append", "(", "'async_req'", ")", ...
https://github.com/ninthDevilHAUNSTER/ArknightsAutoHelper/blob/a27a930502d6e432368d9f62595a1d69a992f4e6/vendor/penguin_client/penguin_client/api/_deprecated_ap_is_api.py#L883-L956
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/collections/__init__.py
python
UserString.ljust
(self, width, *args)
return self.__class__(self.data.ljust(width, *args))
[]
def ljust(self, width, *args): return self.__class__(self.data.ljust(width, *args))
[ "def", "ljust", "(", "self", ",", "width", ",", "*", "args", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "data", ".", "ljust", "(", "width", ",", "*", "args", ")", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/collections/__init__.py#L1206-L1207
keras-team/keras-contrib
3fc5ef709e061416f4bc8a92ca3750c824b5d2b0
keras_contrib/layers/crf.py
python
CRF.get_energy
(self, y_true, input_energy, mask)
return total_energy
Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3
Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3
[ "Energy", "=", "a1", "y1", "+", "u1", "y1", "+", "y1", "U", "y2", "+", "u2", "y2", "+", "y2", "U", "y3", "+", "u3", "y3", "+", "an", "y3" ]
def get_energy(self, y_true, input_energy, mask): """Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3 """ input_energy = K.sum(input_energy * y_true, 2) # (B, T) # (B, T-1) chain_energy = K.sum(K.dot(y_true[:, :-1, :], self.chain_kernel) * y_true[:, 1:, :], 2) if mask is not None: mask = K.cast(mask, K.floatx()) # (B, T-1), mask[:,:-1]*mask[:,1:] makes it work with any padding chain_mask = mask[:, :-1] * mask[:, 1:] input_energy = input_energy * mask chain_energy = chain_energy * chain_mask total_energy = K.sum(input_energy, -1) + K.sum(chain_energy, -1) # (B, ) return total_energy
[ "def", "get_energy", "(", "self", ",", "y_true", ",", "input_energy", ",", "mask", ")", ":", "input_energy", "=", "K", ".", "sum", "(", "input_energy", "*", "y_true", ",", "2", ")", "# (B, T)", "# (B, T-1)", "chain_energy", "=", "K", ".", "sum", "(", "...
https://github.com/keras-team/keras-contrib/blob/3fc5ef709e061416f4bc8a92ca3750c824b5d2b0/keras_contrib/layers/crf.py#L416-L432
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/ZSI-2.0-py2.7.egg/ZSI/schema.py
python
_GetPyobjWrapper.WrapImmutable
(cls, pyobj, what)
return newobj
return a wrapper for pyobj, with typecode attribute set. Parameters: pyobj -- instance of builtin type (immutable) what -- typecode describing the data
return a wrapper for pyobj, with typecode attribute set. Parameters: pyobj -- instance of builtin type (immutable) what -- typecode describing the data
[ "return", "a", "wrapper", "for", "pyobj", "with", "typecode", "attribute", "set", ".", "Parameters", ":", "pyobj", "--", "instance", "of", "builtin", "type", "(", "immutable", ")", "what", "--", "typecode", "describing", "the", "data" ]
def WrapImmutable(cls, pyobj, what): '''return a wrapper for pyobj, with typecode attribute set. Parameters: pyobj -- instance of builtin type (immutable) what -- typecode describing the data ''' d = cls.types_dict if type(pyobj) is bool: pyclass = d[int] elif d.has_key(type(pyobj)) is True: pyclass = d[type(pyobj)] else: raise TypeError,\ 'Expecting a built-in type in %s (got %s).' %( d.keys(),type(pyobj)) newobj = pyclass(pyobj) newobj.typecode = what return newobj
[ "def", "WrapImmutable", "(", "cls", ",", "pyobj", ",", "what", ")", ":", "d", "=", "cls", ".", "types_dict", "if", "type", "(", "pyobj", ")", "is", "bool", ":", "pyclass", "=", "d", "[", "int", "]", "elif", "d", ".", "has_key", "(", "type", "(", ...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/ZSI-2.0-py2.7.egg/ZSI/schema.py#L302-L320
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/cherrypy/wsgiserver/wsgiserver2.py
python
format_exc
(limit=None)
Like print_exc() but return a string. Backport for Python 2.3.
Like print_exc() but return a string. Backport for Python 2.3.
[ "Like", "print_exc", "()", "but", "return", "a", "string", ".", "Backport", "for", "Python", "2", ".", "3", "." ]
def format_exc(limit=None): """Like print_exc() but return a string. Backport for Python 2.3.""" try: etype, value, tb = sys.exc_info() return ''.join(traceback.format_exception(etype, value, tb, limit)) finally: etype = value = tb = None
[ "def", "format_exc", "(", "limit", "=", "None", ")", ":", "try", ":", "etype", ",", "value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "return", "''", ".", "join", "(", "traceback", ".", "format_exception", "(", "etype", ",", "value", ",", ...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/cherrypy/wsgiserver/wsgiserver2.py#L119-L125
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/physics/mechanics/jointsmethod.py
python
JointsMethod.loads
(self)
return self._loads
List of loads on the system.
List of loads on the system.
[ "List", "of", "loads", "on", "the", "system", "." ]
def loads(self): """List of loads on the system.""" return self._loads
[ "def", "loads", "(", "self", ")", ":", "return", "self", ".", "_loads" ]
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/physics/mechanics/jointsmethod.py#L98-L100
mozilla/zamboni
14b1a44658e47b9f048962fa52dbf00a3beaaf30
lib/es/management/commands/reindex.py
python
run_indexing
(index, index_name, ids)
Index the objects. - index: name of the index Note: `ignore_result=False` is required for the chord to work and trigger the callback.
Index the objects.
[ "Index", "the", "objects", "." ]
def run_indexing(index, index_name, ids): """Index the objects. - index: name of the index Note: `ignore_result=False` is required for the chord to work and trigger the callback. """ indexer = INDEXER_MAP[index_name] indexer.run_indexing(ids, ES, index=index)
[ "def", "run_indexing", "(", "index", ",", "index_name", ",", "ids", ")", ":", "indexer", "=", "INDEXER_MAP", "[", "index_name", "]", "indexer", ".", "run_indexing", "(", "ids", ",", "ES", ",", "index", "=", "index", ")" ]
https://github.com/mozilla/zamboni/blob/14b1a44658e47b9f048962fa52dbf00a3beaaf30/lib/es/management/commands/reindex.py#L156-L166
SebKuzminsky/pycam
55e3129f518e470040e79bb00515b4bfcf36c172
pycam/Gui/__init__.py
python
BaseUI.load_startup_workspace
(self)
return self.load_workspace_from_file(filename, remember_uri=False, default_content=DEFAULT_WORKSPACE)
[]
def load_startup_workspace(self): filename = pycam.Gui.Settings.get_workspace_filename() return self.load_workspace_from_file(filename, remember_uri=False, default_content=DEFAULT_WORKSPACE)
[ "def", "load_startup_workspace", "(", "self", ")", ":", "filename", "=", "pycam", ".", "Gui", ".", "Settings", ".", "get_workspace_filename", "(", ")", "return", "self", ".", "load_workspace_from_file", "(", "filename", ",", "remember_uri", "=", "False", ",", ...
https://github.com/SebKuzminsky/pycam/blob/55e3129f518e470040e79bb00515b4bfcf36c172/pycam/Gui/__init__.py#L215-L218
deepgully/me
f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0
libs/sqlalchemy/sql/elements.py
python
_find_columns
(clause)
return cols
locate Column objects within the given expression.
locate Column objects within the given expression.
[ "locate", "Column", "objects", "within", "the", "given", "expression", "." ]
def _find_columns(clause): """locate Column objects within the given expression.""" cols = util.column_set() traverse(clause, {}, {'column': cols.add}) return cols
[ "def", "_find_columns", "(", "clause", ")", ":", "cols", "=", "util", ".", "column_set", "(", ")", "traverse", "(", "clause", ",", "{", "}", ",", "{", "'column'", ":", "cols", ".", "add", "}", ")", "return", "cols" ]
https://github.com/deepgully/me/blob/f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0/libs/sqlalchemy/sql/elements.py#L3268-L3273
deepgully/me
f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0
libs/sqlalchemy/orm/events.py
python
AttributeEvents.set
(self, target, value, oldvalue, initiator)
Receive a scalar set event. :param target: the object instance receiving the event. If the listener is registered with ``raw=True``, this will be the :class:`.InstanceState` object. :param value: the value being set. If this listener is registered with ``retval=True``, the listener function must return this value, or a new value which replaces it. :param oldvalue: the previous value being replaced. This may also be the symbol ``NEVER_SET`` or ``NO_VALUE``. If the listener is registered with ``active_history=True``, the previous value of the attribute will be loaded from the database if the existing value is currently unloaded or expired. :param initiator: An instance of :class:`.attributes.Event` representing the initiation of the event. May be modified from it's original value by backref handlers in order to control chained event propagation. .. versionchanged:: 0.9.0 the ``initiator`` argument is now passed as a :class:`.attributes.Event` object, and may be modified by backref handlers within a chain of backref-linked events. :return: if the event was registered with ``retval=True``, the given value, or a new effective value, should be returned.
Receive a scalar set event.
[ "Receive", "a", "scalar", "set", "event", "." ]
def set(self, target, value, oldvalue, initiator): """Receive a scalar set event. :param target: the object instance receiving the event. If the listener is registered with ``raw=True``, this will be the :class:`.InstanceState` object. :param value: the value being set. If this listener is registered with ``retval=True``, the listener function must return this value, or a new value which replaces it. :param oldvalue: the previous value being replaced. This may also be the symbol ``NEVER_SET`` or ``NO_VALUE``. If the listener is registered with ``active_history=True``, the previous value of the attribute will be loaded from the database if the existing value is currently unloaded or expired. :param initiator: An instance of :class:`.attributes.Event` representing the initiation of the event. May be modified from it's original value by backref handlers in order to control chained event propagation. .. versionchanged:: 0.9.0 the ``initiator`` argument is now passed as a :class:`.attributes.Event` object, and may be modified by backref handlers within a chain of backref-linked events. :return: if the event was registered with ``retval=True``, the given value, or a new effective value, should be returned. """
[ "def", "set", "(", "self", ",", "target", ",", "value", ",", "oldvalue", ",", "initiator", ")", ":" ]
https://github.com/deepgully/me/blob/f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0/libs/sqlalchemy/orm/events.py#L1682-L1710
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy_utils/types/password.py
python
Password.__eq__
(self, value)
return False
[]
def __eq__(self, value): if self.hash is None or value is None: # Ensure that we don't continue comparison if one of us is None. return self.hash is value if isinstance(value, Password): # Comparing 2 hashes isn't very useful; but this equality # method breaks otherwise. return value.hash == self.hash if self.context is None: # Compare 2 hashes again as we don't know how to validate. return value == self if isinstance(value, (six.string_types, six.binary_type)): valid, new = self.context.verify_and_update(value, self.hash) if valid and new: # New hash was calculated due to various reasons; stored one # wasn't optimal, etc. self.hash = new # The hash should be bytes. if isinstance(self.hash, six.string_types): self.hash = self.hash.encode('utf8') self.changed() return valid return False
[ "def", "__eq__", "(", "self", ",", "value", ")", ":", "if", "self", ".", "hash", "is", "None", "or", "value", "is", "None", ":", "# Ensure that we don't continue comparison if one of us is None.", "return", "self", ".", "hash", "is", "value", "if", "isinstance",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy_utils/types/password.py#L45-L73
ambakick/Person-Detection-and-Tracking
f925394ac29b5cf321f1ce89a71b193381519a0b
utils/visualization_utils.py
python
draw_keypoints_on_image
(image, keypoints, color='red', radius=2, use_normalized_coordinates=True)
Draws keypoints on an image. Args: image: a PIL.Image object. keypoints: a numpy array with shape [num_keypoints, 2]. color: color to draw the keypoints with. Default is red. radius: keypoint radius. Default value is 2. use_normalized_coordinates: if True (default), treat keypoint values as relative to the image. Otherwise treat them as absolute.
Draws keypoints on an image.
[ "Draws", "keypoints", "on", "an", "image", "." ]
def draw_keypoints_on_image(image, keypoints, color='red', radius=2, use_normalized_coordinates=True): """Draws keypoints on an image. Args: image: a PIL.Image object. keypoints: a numpy array with shape [num_keypoints, 2]. color: color to draw the keypoints with. Default is red. radius: keypoint radius. Default value is 2. use_normalized_coordinates: if True (default), treat keypoint values as relative to the image. Otherwise treat them as absolute. """ draw = ImageDraw.Draw(image) im_width, im_height = image.size keypoints_x = [k[1] for k in keypoints] keypoints_y = [k[0] for k in keypoints] if use_normalized_coordinates: keypoints_x = tuple([im_width * x for x in keypoints_x]) keypoints_y = tuple([im_height * y for y in keypoints_y]) for keypoint_x, keypoint_y in zip(keypoints_x, keypoints_y): draw.ellipse([(keypoint_x - radius, keypoint_y - radius), (keypoint_x + radius, keypoint_y + radius)], outline=color, fill=color)
[ "def", "draw_keypoints_on_image", "(", "image", ",", "keypoints", ",", "color", "=", "'red'", ",", "radius", "=", "2", ",", "use_normalized_coordinates", "=", "True", ")", ":", "draw", "=", "ImageDraw", ".", "Draw", "(", "image", ")", "im_width", ",", "im_...
https://github.com/ambakick/Person-Detection-and-Tracking/blob/f925394ac29b5cf321f1ce89a71b193381519a0b/utils/visualization_utils.py#L480-L505
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/pickletools.py
python
read_uint1
(f)
r""" >>> import StringIO >>> read_uint1(StringIO.StringIO('\xff')) 255
r""" >>> import StringIO >>> read_uint1(StringIO.StringIO('\xff')) 255
[ "r", ">>>", "import", "StringIO", ">>>", "read_uint1", "(", "StringIO", ".", "StringIO", "(", "\\", "xff", "))", "255" ]
def read_uint1(f): r""" >>> import StringIO >>> read_uint1(StringIO.StringIO('\xff')) 255 """ data = f.read(1) if data: return ord(data) raise ValueError("not enough data in stream to read uint1")
[ "def", "read_uint1", "(", "f", ")", ":", "data", "=", "f", ".", "read", "(", "1", ")", "if", "data", ":", "return", "ord", "(", "data", ")", "raise", "ValueError", "(", "\"not enough data in stream to read uint1\"", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/pickletools.py#L201-L211
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/bin/tendenci.py
python
Command.create_parser
(self, command_name=None)
return parser
[]
def create_parser(self, command_name=None): if command_name is None: prog = None else: # hack the prog name as reported to ArgumentParser to include the command prog = "%s %s" % (prog_name(), command_name) parser = ArgumentParser( description=getattr(self, 'description', None), add_help=False, prog=prog ) self.add_arguments(parser) return parser
[ "def", "create_parser", "(", "self", ",", "command_name", "=", "None", ")", ":", "if", "command_name", "is", "None", ":", "prog", "=", "None", "else", ":", "# hack the prog name as reported to ArgumentParser to include the command", "prog", "=", "\"%s %s\"", "%", "(...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/bin/tendenci.py#L28-L39
Symbo1/wsltools
0b6e536fc85c707a1c81f0296c4e91ca835396a1
wsltools/utils/faker/providers/address/pt_BR/__init__.py
python
Provider.bairro
(self)
return self.random_element(self.bairros)
Randomly returns a bairro (neighborhood) name. The names were taken from the city of Belo Horizonte - Minas Gerais :example 'Serra'
Randomly returns a bairro (neighborhood) name. The names were taken from the city of Belo Horizonte - Minas Gerais
[ "Randomly", "returns", "a", "bairro", "(", "neighborhood", ")", "name", ".", "The", "names", "were", "taken", "from", "the", "city", "of", "Belo", "Horizonte", "-", "Minas", "Gerais" ]
def bairro(self): """ Randomly returns a bairro (neighborhood) name. The names were taken from the city of Belo Horizonte - Minas Gerais :example 'Serra' """ return self.random_element(self.bairros)
[ "def", "bairro", "(", "self", ")", ":", "return", "self", ".", "random_element", "(", "self", ".", "bairros", ")" ]
https://github.com/Symbo1/wsltools/blob/0b6e536fc85c707a1c81f0296c4e91ca835396a1/wsltools/utils/faker/providers/address/pt_BR/__init__.py#L293-L300
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/thorium/calc.py
python
__virtual__
()
return HAS_STATS
The statistics module must be pip installed
The statistics module must be pip installed
[ "The", "statistics", "module", "must", "be", "pip", "installed" ]
def __virtual__(): """ The statistics module must be pip installed """ return HAS_STATS
[ "def", "__virtual__", "(", ")", ":", "return", "HAS_STATS" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/thorium/calc.py#L19-L23
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3/s3import.py
python
S3Importer._decode_data
(field, value)
Try to decode string data into their original type Args: field: the Field instance value: the stringified value TODO: Replace this by ordinary decoder
Try to decode string data into their original type
[ "Try", "to", "decode", "string", "data", "into", "their", "original", "type" ]
def _decode_data(field, value): """ Try to decode string data into their original type Args: field: the Field instance value: the stringified value TODO: Replace this by ordinary decoder """ if field.type == "string" or \ field.type == "password" or \ field.type == "upload" or \ field.type == "text": return value elif field.type == "integer" or \ field.type == "id": return int(value) elif field.type == "double" or \ field.type == "decimal": return float(value) elif field.type == "boolean": if value and not str(value)[:1].upper() in ["F", "0"]: return "T" else: return "F" elif field.type == "date": return value # @todo fix this to get a date elif field.type == "time": return value # @todo fix this to get a time elif field.type == "datetime": return value # @todo fix this to get a datetime else: return value
[ "def", "_decode_data", "(", "field", ",", "value", ")", ":", "if", "field", ".", "type", "==", "\"string\"", "or", "field", ".", "type", "==", "\"password\"", "or", "field", ".", "type", "==", "\"upload\"", "or", "field", ".", "type", "==", "\"text\"", ...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3import.py#L1537-L1572
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/number_field/number_field_rel.py
python
NumberField_relative.subfields
(self, degree=0, name=None)
return ans
Return all subfields of this relative number field self of the given degree, or of all possible degrees if degree is 0. The subfields are returned as absolute fields together with an embedding into self. For the case of the field itself, the reverse isomorphism is also provided. EXAMPLES:: sage: PQ.<X> = QQ[] sage: F.<a, b> = NumberField([X^2 - 2, X^2 - 3]) sage: PF.<Y> = F[] sage: K.<c> = F.extension(Y^2 - (1 + a)*(a + b)*a*b) sage: K.subfields(2) [ (Number Field in c0 with defining polynomial x^2 - 24*x + 96, Ring morphism: From: Number Field in c0 with defining polynomial x^2 - 24*x + 96 To: Number Field in c with defining polynomial Y^2 + (-2*b - 3)*a - 2*b - 6 over its base field Defn: c0 |--> -4*b + 12, None), (Number Field in c1 with defining polynomial x^2 - 24*x + 120, Ring morphism: From: Number Field in c1 with defining polynomial x^2 - 24*x + 120 To: Number Field in c with defining polynomial Y^2 + (-2*b - 3)*a - 2*b - 6 over its base field Defn: c1 |--> 2*b*a + 12, None), (Number Field in c2 with defining polynomial x^2 - 24*x + 72, Ring morphism: From: Number Field in c2 with defining polynomial x^2 - 24*x + 72 To: Number Field in c with defining polynomial Y^2 + (-2*b - 3)*a - 2*b - 6 over its base field Defn: c2 |--> -6*a + 12, None) ] sage: K.subfields(8, 'w') [ (Number Field in w0 with defining polynomial x^8 - 12*x^6 + 36*x^4 - 36*x^2 + 9, Ring morphism: From: Number Field in w0 with defining polynomial x^8 - 12*x^6 + 36*x^4 - 36*x^2 + 9 To: Number Field in c with defining polynomial Y^2 + (-2*b - 3)*a - 2*b - 6 over its base field Defn: w0 |--> (-1/2*b*a + 1/2*b + 1/2)*c, Relative number field morphism: From: Number Field in c with defining polynomial Y^2 + (-2*b - 3)*a - 2*b - 6 over its base field To: Number Field in w0 with defining polynomial x^8 - 12*x^6 + 36*x^4 - 36*x^2 + 9 Defn: c |--> -1/3*w0^7 + 4*w0^5 - 12*w0^3 + 11*w0 a |--> 1/3*w0^6 - 10/3*w0^4 + 5*w0^2 b |--> -2/3*w0^6 + 7*w0^4 - 14*w0^2 + 6) ] sage: K.subfields(3) []
Return all subfields of this relative number field self of the given degree, or of all possible degrees if degree is 0. The subfields are returned as absolute fields together with an embedding into self. For the case of the field itself, the reverse isomorphism is also provided.
[ "Return", "all", "subfields", "of", "this", "relative", "number", "field", "self", "of", "the", "given", "degree", "or", "of", "all", "possible", "degrees", "if", "degree", "is", "0", ".", "The", "subfields", "are", "returned", "as", "absolute", "fields", ...
def subfields(self, degree=0, name=None): """ Return all subfields of this relative number field self of the given degree, or of all possible degrees if degree is 0. The subfields are returned as absolute fields together with an embedding into self. For the case of the field itself, the reverse isomorphism is also provided. EXAMPLES:: sage: PQ.<X> = QQ[] sage: F.<a, b> = NumberField([X^2 - 2, X^2 - 3]) sage: PF.<Y> = F[] sage: K.<c> = F.extension(Y^2 - (1 + a)*(a + b)*a*b) sage: K.subfields(2) [ (Number Field in c0 with defining polynomial x^2 - 24*x + 96, Ring morphism: From: Number Field in c0 with defining polynomial x^2 - 24*x + 96 To: Number Field in c with defining polynomial Y^2 + (-2*b - 3)*a - 2*b - 6 over its base field Defn: c0 |--> -4*b + 12, None), (Number Field in c1 with defining polynomial x^2 - 24*x + 120, Ring morphism: From: Number Field in c1 with defining polynomial x^2 - 24*x + 120 To: Number Field in c with defining polynomial Y^2 + (-2*b - 3)*a - 2*b - 6 over its base field Defn: c1 |--> 2*b*a + 12, None), (Number Field in c2 with defining polynomial x^2 - 24*x + 72, Ring morphism: From: Number Field in c2 with defining polynomial x^2 - 24*x + 72 To: Number Field in c with defining polynomial Y^2 + (-2*b - 3)*a - 2*b - 6 over its base field Defn: c2 |--> -6*a + 12, None) ] sage: K.subfields(8, 'w') [ (Number Field in w0 with defining polynomial x^8 - 12*x^6 + 36*x^4 - 36*x^2 + 9, Ring morphism: From: Number Field in w0 with defining polynomial x^8 - 12*x^6 + 36*x^4 - 36*x^2 + 9 To: Number Field in c with defining polynomial Y^2 + (-2*b - 3)*a - 2*b - 6 over its base field Defn: w0 |--> (-1/2*b*a + 1/2*b + 1/2)*c, Relative number field morphism: From: Number Field in c with defining polynomial Y^2 + (-2*b - 3)*a - 2*b - 6 over its base field To: Number Field in w0 with defining polynomial x^8 - 12*x^6 + 36*x^4 - 36*x^2 + 9 Defn: c |--> -1/3*w0^7 + 4*w0^5 - 12*w0^3 + 11*w0 a |--> 1/3*w0^6 - 10/3*w0^4 + 5*w0^2 b |--> -2/3*w0^6 + 7*w0^4 - 14*w0^2 + 6) ] sage: K.subfields(3) [] """ if name is None: name = self.variable_name() abs = self.absolute_field(name) from_abs, to_abs = abs.structure() abs_subfields = abs.subfields(degree=degree) ans = [] for K, from_K, to_K in abs_subfields: from_K = K.hom([from_abs(from_K(K.gen()))]) if to_K is not None: to_K = RelativeNumberFieldHomomorphism_from_abs(self.Hom(K), to_K*to_abs) ans.append((K, from_K, to_K)) ans = Sequence(ans, immutable=True, cr=ans!=[]) return ans
[ "def", "subfields", "(", "self", ",", "degree", "=", "0", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "variable_name", "(", ")", "abs", "=", "self", ".", "absolute_field", "(", "name", ")", "from_a...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/number_field/number_field_rel.py#L382-L437
openid/python-openid
afa6adacbe1a41d8f614c8bce2264dfbe9e76489
openid/store/filestore.py
python
_removeIfPresent
(filename)
Attempt to remove a file, returning whether the file existed at the time of the call. six.text_type -> bool
Attempt to remove a file, returning whether the file existed at the time of the call.
[ "Attempt", "to", "remove", "a", "file", "returning", "whether", "the", "file", "existed", "at", "the", "time", "of", "the", "call", "." ]
def _removeIfPresent(filename): """Attempt to remove a file, returning whether the file existed at the time of the call. six.text_type -> bool """ try: os.unlink(filename) except OSError as why: if why.errno == ENOENT: # Someone beat us to it, but it's gone, so that's OK return 0 else: raise else: # File was present return 1
[ "def", "_removeIfPresent", "(", "filename", ")", ":", "try", ":", "os", ".", "unlink", "(", "filename", ")", "except", "OSError", "as", "why", ":", "if", "why", ".", "errno", "==", "ENOENT", ":", "# Someone beat us to it, but it's gone, so that's OK", "return", ...
https://github.com/openid/python-openid/blob/afa6adacbe1a41d8f614c8bce2264dfbe9e76489/openid/store/filestore.py#L43-L59
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/opcodes_base.py
python
_AutoOpParamSlots._GetSlots
(mcs, attrs)
return [pname for (pname, _, _, _) in params]
Build the slots out of OP_PARAMS.
Build the slots out of OP_PARAMS.
[ "Build", "the", "slots", "out", "of", "OP_PARAMS", "." ]
def _GetSlots(mcs, attrs): """Build the slots out of OP_PARAMS. """ # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams params = attrs.setdefault("OP_PARAMS", []) # Use parameter names as slots return [pname for (pname, _, _, _) in params]
[ "def", "_GetSlots", "(", "mcs", ",", "attrs", ")", ":", "# Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams", "params", "=", "attrs", ".", "setdefault", "(", "\"OP_PARAMS\"", ",", "[", "]", ")", "# Use parameter names as slots", "return", "[", "pname"...
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/opcodes_base.py#L153-L161
d4nj1/TLPUI
83e41298674cac7487dd4f4d64f8552617d40b6c
tlpui/uihelper.py
python
get_flag_image
(locale: str)
return Gtk.Image().new_from_pixbuf(flagpixbuf)
Fetch flag image from icons folder.
Fetch flag image from icons folder.
[ "Fetch", "flag", "image", "from", "icons", "folder", "." ]
def get_flag_image(locale: str) -> Gtk.Image: """Fetch flag image from icons folder.""" flagpixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(f"{settings.icondir}flags/{locale}.png", width=16, height=16) return Gtk.Image().new_from_pixbuf(flagpixbuf)
[ "def", "get_flag_image", "(", "locale", ":", "str", ")", "->", "Gtk", ".", "Image", ":", "flagpixbuf", "=", "GdkPixbuf", ".", "Pixbuf", ".", "new_from_file_at_size", "(", "f\"{settings.icondir}flags/{locale}.png\"", ",", "width", "=", "16", ",", "height", "=", ...
https://github.com/d4nj1/TLPUI/blob/83e41298674cac7487dd4f4d64f8552617d40b6c/tlpui/uihelper.py#L33-L36
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/arithgroup/arithgroup_perm.py
python
sl2z_word_problem
(A)
return output
r""" Given an element of `{\rm SL}_2(\ZZ)`, express it as a word in the generators L = [1,1,0,1] and R = [1,0,1,1]. The return format is a list of pairs ``(a,b)``, where ``a = 0`` or ``1`` denoting ``L`` or ``R`` respectively, and ``b`` is an integer exponent. See also the function :func:`eval_sl2z_word`. EXAMPLES:: sage: from sage.modular.arithgroup.arithgroup_perm import eval_sl2z_word, sl2z_word_problem sage: m = SL2Z([1,0,0,1]) sage: eval_sl2z_word(sl2z_word_problem(m)) == m True sage: m = SL2Z([0,-1,1,0]) sage: eval_sl2z_word(sl2z_word_problem(m)) == m True sage: m = SL2Z([7,8,-50,-57]) sage: eval_sl2z_word(sl2z_word_problem(m)) == m True
r""" Given an element of `{\rm SL}_2(\ZZ)`, express it as a word in the generators L = [1,1,0,1] and R = [1,0,1,1].
[ "r", "Given", "an", "element", "of", "{", "\\", "rm", "SL", "}", "_2", "(", "\\", "ZZ", ")", "express", "it", "as", "a", "word", "in", "the", "generators", "L", "=", "[", "1", "1", "0", "1", "]", "and", "R", "=", "[", "1", "0", "1", "1", ...
def sl2z_word_problem(A): r""" Given an element of `{\rm SL}_2(\ZZ)`, express it as a word in the generators L = [1,1,0,1] and R = [1,0,1,1]. The return format is a list of pairs ``(a,b)``, where ``a = 0`` or ``1`` denoting ``L`` or ``R`` respectively, and ``b`` is an integer exponent. See also the function :func:`eval_sl2z_word`. EXAMPLES:: sage: from sage.modular.arithgroup.arithgroup_perm import eval_sl2z_word, sl2z_word_problem sage: m = SL2Z([1,0,0,1]) sage: eval_sl2z_word(sl2z_word_problem(m)) == m True sage: m = SL2Z([0,-1,1,0]) sage: eval_sl2z_word(sl2z_word_problem(m)) == m True sage: m = SL2Z([7,8,-50,-57]) sage: eval_sl2z_word(sl2z_word_problem(m)) == m True """ A = SL2Z(A) output=[] ## If A00 is zero if A[0,0]==0: c=A[1,1] if c != 1: A=A*Lm**(c-1)*Rm*Lmi output.extend([(0,1-c),(1,-1),(0,1)]) else: A=A*Rm*Lmi output.extend([(1,-1),(0,1)]) if A[0,0]<0: # Make sure A00 is positive A=SL2Z(-1)*A output.extend([(1,-1), (0,1), (1,-1), (0,1), (1,-1), (0,1)]) if A[0,1]<0: # if A01 is negative make it positive n=(-A[0,1]/A[0,0]).ceil() #n s.t. 0 <= A[0,1]+n*A[0,0] < A[0,0] A=A*Lm**n output.append((0, -n)) ## At this point A00>0 and A01>=0 while not (A[0,0]==0 or A[0,1]==0): if A[0,0]>A[0,1]: n=(A[0,0]/A[0,1]).floor() A=A*SL2Z([1,0,-n,1]) output.append((1, n)) else: #A[0,0]<=A[0,1] n=(A[0,1]/A[0,0]).floor() A=A*SL2Z([1,-n,0,1]) output.append((0, n)) if A==SL2Z(1): pass #done, so don't add R^0 elif A[0,0]==0: c=A[1,1] if c != 1: A=A*Lm**(c-1)*Rm*Lmi output.extend([(0,1-c),(1,-1),(0, 1)]) else: A=A*Rm*Lmi output.extend([(1,-1),(0,1)]) else: c=A[1,0] if c: A=A*Rm**(-c) output.append((1,c)) output.reverse() return output
[ "def", "sl2z_word_problem", "(", "A", ")", ":", "A", "=", "SL2Z", "(", "A", ")", "output", "=", "[", "]", "## If A00 is zero", "if", "A", "[", "0", ",", "0", "]", "==", "0", ":", "c", "=", "A", "[", "1", ",", "1", "]", "if", "c", "!=", "1",...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/arithgroup/arithgroup_perm.py#L122-L195
haiwen/seahub
e92fcd44e3e46260597d8faa9347cb8222b8b10d
seahub/two_factor/views/utils.py
python
ExtraSessionStorage._set_validated_step_data
(self, validated_step_data)
[]
def _set_validated_step_data(self, validated_step_data): self.data[self.validated_step_data_key] = validated_step_data
[ "def", "_set_validated_step_data", "(", "self", ",", "validated_step_data", ")", ":", "self", ".", "data", "[", "self", ".", "validated_step_data_key", "]", "=", "validated_step_data" ]
https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/seahub/two_factor/views/utils.py#L33-L34
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_endpoint_conditions.py
python
V1EndpointConditions.serving
(self)
return self._serving
Gets the serving of this V1EndpointConditions. # noqa: E501 serving is identical to ready except that it is set regardless of the terminating state of endpoints. This condition should be set to true for a ready endpoint that is terminating. If nil, consumers should defer to the ready condition. This field can be enabled with the EndpointSliceTerminatingCondition feature gate. # noqa: E501 :return: The serving of this V1EndpointConditions. # noqa: E501 :rtype: bool
Gets the serving of this V1EndpointConditions. # noqa: E501
[ "Gets", "the", "serving", "of", "this", "V1EndpointConditions", ".", "#", "noqa", ":", "E501" ]
def serving(self): """Gets the serving of this V1EndpointConditions. # noqa: E501 serving is identical to ready except that it is set regardless of the terminating state of endpoints. This condition should be set to true for a ready endpoint that is terminating. If nil, consumers should defer to the ready condition. This field can be enabled with the EndpointSliceTerminatingCondition feature gate. # noqa: E501 :return: The serving of this V1EndpointConditions. # noqa: E501 :rtype: bool """ return self._serving
[ "def", "serving", "(", "self", ")", ":", "return", "self", ".", "_serving" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_endpoint_conditions.py#L89-L97
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/pip/_internal/configuration.py
python
Configuration.save
(self)
Save the currentin-memory state.
Save the currentin-memory state.
[ "Save", "the", "currentin", "-", "memory", "state", "." ]
def save(self): # type: () -> None """Save the currentin-memory state. """ self._ensure_have_load_only() for fname, parser in self._modified_parsers: logger.info("Writing to %s", fname) # Ensure directory exists. ensure_dir(os.path.dirname(fname)) with open(fname, "w") as f: parser.write(f)
[ "def", "save", "(", "self", ")", ":", "# type: () -> None", "self", ".", "_ensure_have_load_only", "(", ")", "for", "fname", ",", "parser", "in", "self", ".", "_modified_parsers", ":", "logger", ".", "info", "(", "\"Writing to %s\"", ",", "fname", ")", "# En...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/pip/_internal/configuration.py#L204-L217
00nanhai/captchacker2
7609141b51ff0cf3329608b8101df967cb74752f
svm.py
python
svm_model.get_sv_indices
(self)
return sv_indices[:total_sv]
[]
def get_sv_indices(self): total_sv = self.get_nr_sv() sv_indices = (c_int * total_sv)() libsvm.svm_get_sv_indices(self, sv_indices) return sv_indices[:total_sv]
[ "def", "get_sv_indices", "(", "self", ")", ":", "total_sv", "=", "self", ".", "get_nr_sv", "(", ")", "sv_indices", "=", "(", "c_int", "*", "total_sv", ")", "(", ")", "libsvm", ".", "svm_get_sv_indices", "(", "self", ",", "sv_indices", ")", "return", "sv_...
https://github.com/00nanhai/captchacker2/blob/7609141b51ff0cf3329608b8101df967cb74752f/svm.py#L262-L266
ryu577/pyray
860b71463e2729a85b1319b5c3571c0b8f3ba50c
pyray/shapes/twod/plane.py
python
xzplane
(draw, r, y, shift = np.array([1000, 1000, 0, 0]), scale = 300)
Draws an x-z plane on the draw object of an image.
Draws an x-z plane on the draw object of an image.
[ "Draws", "an", "x", "-", "z", "plane", "on", "the", "draw", "object", "of", "an", "image", "." ]
def xzplane(draw, r, y, shift = np.array([1000, 1000, 0, 0]), scale = 300): """ Draws an x-z plane on the draw object of an image. """ extent = 2.8 pln = np.array( [ [-extent,y,0], [extent,y,0], [extent,y,extent*2], [-extent,y,extent*2] ] ) pln = np.dot(pln, np.transpose(r)) pln = pln * scale + shift[:3] draw.polygon([(pln[0][0],pln[0][1]),(pln[1][0],pln[1][1]),(pln[2][0],pln[2][1]),(pln[3][0],pln[3][1])], (0,102,255,70))
[ "def", "xzplane", "(", "draw", ",", "r", ",", "y", ",", "shift", "=", "np", ".", "array", "(", "[", "1000", ",", "1000", ",", "0", ",", "0", "]", ")", ",", "scale", "=", "300", ")", ":", "extent", "=", "2.8", "pln", "=", "np", ".", "array",...
https://github.com/ryu577/pyray/blob/860b71463e2729a85b1319b5c3571c0b8f3ba50c/pyray/shapes/twod/plane.py#L33-L48
Ciphey/Ciphey
4e5cc80a3cfdd5361ddb2d99322ed9b3ba54dc90
ciphey/basemods/Searchers/ausearch.py
python
PriorityWorkQueue.get_work_chunk
(self)
return self._queues.pop(best_priority)
Returns the best work for now
Returns the best work for now
[ "Returns", "the", "best", "work", "for", "now" ]
def get_work_chunk(self) -> List[T]: """Returns the best work for now""" if len(self._sorted_priorities) == 0: return [] best_priority = self._sorted_priorities.pop(0) return self._queues.pop(best_priority)
[ "def", "get_work_chunk", "(", "self", ")", "->", "List", "[", "T", "]", ":", "if", "len", "(", "self", ".", "_sorted_priorities", ")", "==", "0", ":", "return", "[", "]", "best_priority", "=", "self", ".", "_sorted_priorities", ".", "pop", "(", "0", ...
https://github.com/Ciphey/Ciphey/blob/4e5cc80a3cfdd5361ddb2d99322ed9b3ba54dc90/ciphey/basemods/Searchers/ausearch.py#L165-L170
trailofbits/manticore
b050fdf0939f6c63f503cdf87ec0ab159dd41159
manticore/native/cpu/x86.py
python
X86Cpu.CMP
(cpu, src1, src2)
Compares two operands. Compares the first source operand with the second source operand and sets the status flags in the EFLAGS register according to the results. The comparison is performed by subtracting the second operand from the first operand and then setting the status flags in the same manner as the SUB instruction. When an immediate value is used as an operand, it is sign-extended to the length of the first operand:: temp = SRC1 - SignExtend(SRC2); ModifyStatusFlags; (* Modify status flags in the same manner as the SUB instruction*) The CF, OF, SF, ZF, AF, and PF flags are set according to the result. :param cpu: current CPU. :param dest: destination operand. :param src: source operand.
Compares two operands.
[ "Compares", "two", "operands", "." ]
def CMP(cpu, src1, src2): """ Compares two operands. Compares the first source operand with the second source operand and sets the status flags in the EFLAGS register according to the results. The comparison is performed by subtracting the second operand from the first operand and then setting the status flags in the same manner as the SUB instruction. When an immediate value is used as an operand, it is sign-extended to the length of the first operand:: temp = SRC1 - SignExtend(SRC2); ModifyStatusFlags; (* Modify status flags in the same manner as the SUB instruction*) The CF, OF, SF, ZF, AF, and PF flags are set according to the result. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ arg0 = src1.read() arg1 = Operators.SEXTEND(src2.read(), src2.size, src1.size) # Affected Flags o..szapc cpu._calculate_CMP_flags(src1.size, arg0 - arg1, arg0, arg1)
[ "def", "CMP", "(", "cpu", ",", "src1", ",", "src2", ")", ":", "arg0", "=", "src1", ".", "read", "(", ")", "arg1", "=", "Operators", ".", "SEXTEND", "(", "src2", ".", "read", "(", ")", ",", "src2", ".", "size", ",", "src1", ".", "size", ")", "...
https://github.com/trailofbits/manticore/blob/b050fdf0939f6c63f503cdf87ec0ab159dd41159/manticore/native/cpu/x86.py#L1397-L1420
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_surface.py
python
Surface.connectgaps
(self)
return self["connectgaps"]
Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. The 'connectgaps' property must be specified as a bool (either True, or False) Returns ------- bool
Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. The 'connectgaps' property must be specified as a bool (either True, or False)
[ "Determines", "whether", "or", "not", "gaps", "(", "i", ".", "e", ".", "{", "nan", "}", "or", "missing", "values", ")", "in", "the", "z", "data", "are", "filled", "in", ".", "The", "connectgaps", "property", "must", "be", "specified", "as", "a", "boo...
def connectgaps(self): """ Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. The 'connectgaps' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["connectgaps"]
[ "def", "connectgaps", "(", "self", ")", ":", "return", "self", "[", "\"connectgaps\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_surface.py#L528-L540
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/cachecontrol/controller.py
python
CacheController.__init__
(self, cache=None, cache_etags=True, serializer=None)
[]
def __init__(self, cache=None, cache_etags=True, serializer=None): self.cache = cache or DictCache() self.cache_etags = cache_etags self.serializer = serializer or Serializer()
[ "def", "__init__", "(", "self", ",", "cache", "=", "None", ",", "cache_etags", "=", "True", ",", "serializer", "=", "None", ")", ":", "self", ".", "cache", "=", "cache", "or", "DictCache", "(", ")", "self", ".", "cache_etags", "=", "cache_etags", "self...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/cachecontrol/controller.py#L33-L36
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/sklearn/cluster/k_means_.py
python
KMeans._transform
(self, X)
return euclidean_distances(X, self.cluster_centers_)
guts of transform method; no input validation
guts of transform method; no input validation
[ "guts", "of", "transform", "method", ";", "no", "input", "validation" ]
def _transform(self, X): """guts of transform method; no input validation""" return euclidean_distances(X, self.cluster_centers_)
[ "def", "_transform", "(", "self", ",", "X", ")", ":", "return", "euclidean_distances", "(", "X", ",", "self", ".", "cluster_centers_", ")" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/cluster/k_means_.py#L934-L936
amymcgovern/pyparrot
bf4775ec1199b282e4edde1e4a8e018dcc8725e0
pyparrot/utils/vlc.py
python
MediaPlayer.get_full_title_descriptions
(self)
return info
Get the full description of available titles. @return: the titles list @version: LibVLC 3.0.0 and later.
Get the full description of available titles.
[ "Get", "the", "full", "description", "of", "available", "titles", "." ]
def get_full_title_descriptions(self): '''Get the full description of available titles. @return: the titles list @version: LibVLC 3.0.0 and later. ''' titleDescription_pp = ctypes.POINTER(TitleDescription)() n = libvlc_media_player_get_full_title_descriptions(self, ctypes.byref(titleDescription_pp)) info = ctypes.cast(ctypes.titleDescription_pp, ctypes.POINTER(ctypes.POINTER(TitleDescription) * n)) return info
[ "def", "get_full_title_descriptions", "(", "self", ")", ":", "titleDescription_pp", "=", "ctypes", ".", "POINTER", "(", "TitleDescription", ")", "(", ")", "n", "=", "libvlc_media_player_get_full_title_descriptions", "(", "self", ",", "ctypes", ".", "byref", "(", "...
https://github.com/amymcgovern/pyparrot/blob/bf4775ec1199b282e4edde1e4a8e018dcc8725e0/pyparrot/utils/vlc.py#L3227-L3235
ConsenSys/ethjsonrpc
fe525bdcd889924687ba1646fc46cef329410e22
ethjsonrpc/client.py
python
EthJsonRpc.db_getHex
(self, db_name, key)
return self._call('db_getHex', [db_name, key])
https://github.com/ethereum/wiki/wiki/JSON-RPC#db_gethex TESTED
https://github.com/ethereum/wiki/wiki/JSON-RPC#db_gethex
[ "https", ":", "//", "github", ".", "com", "/", "ethereum", "/", "wiki", "/", "wiki", "/", "JSON", "-", "RPC#db_gethex" ]
def db_getHex(self, db_name, key): ''' https://github.com/ethereum/wiki/wiki/JSON-RPC#db_gethex TESTED ''' warnings.warn('deprecated', DeprecationWarning) return self._call('db_getHex', [db_name, key])
[ "def", "db_getHex", "(", "self", ",", "db_name", ",", "key", ")", ":", "warnings", ".", "warn", "(", "'deprecated'", ",", "DeprecationWarning", ")", "return", "self", ".", "_call", "(", "'db_getHex'", ",", "[", "db_name", ",", "key", "]", ")" ]
https://github.com/ConsenSys/ethjsonrpc/blob/fe525bdcd889924687ba1646fc46cef329410e22/ethjsonrpc/client.py#L616-L623
benedekrozemberczki/ClusterGCN
718d17ff588a65792fd821a1fe2af0f646e49ebd
src/clustering.py
python
ClusteringMachine.random_clustering
(self)
Random clustering the nodes.
Random clustering the nodes.
[ "Random", "clustering", "the", "nodes", "." ]
def random_clustering(self): """ Random clustering the nodes. """ self.clusters = [cluster for cluster in range(self.args.cluster_number)] self.cluster_membership = {node: random.choice(self.clusters) for node in self.graph.nodes()}
[ "def", "random_clustering", "(", "self", ")", ":", "self", ".", "clusters", "=", "[", "cluster", "for", "cluster", "in", "range", "(", "self", ".", "args", ".", "cluster_number", ")", "]", "self", ".", "cluster_membership", "=", "{", "node", ":", "random...
https://github.com/benedekrozemberczki/ClusterGCN/blob/718d17ff588a65792fd821a1fe2af0f646e49ebd/src/clustering.py#L45-L50
pygae/clifford
0b6cffb9a6d44ecb7a666f6b08b1788fc94a0ab6
clifford/tools/g3c/object_fitting.py
python
fit_circle
(point_list)
return layout.MultiVector(val_fit_circle(np.array([p.value for p in point_list])))
Performs Leo Dorsts circle fitting technique
Performs Leo Dorsts circle fitting technique
[ "Performs", "Leo", "Dorsts", "circle", "fitting", "technique" ]
def fit_circle(point_list): """ Performs Leo Dorsts circle fitting technique """ return layout.MultiVector(val_fit_circle(np.array([p.value for p in point_list])))
[ "def", "fit_circle", "(", "point_list", ")", ":", "return", "layout", ".", "MultiVector", "(", "val_fit_circle", "(", "np", ".", "array", "(", "[", "p", ".", "value", "for", "p", "in", "point_list", "]", ")", ")", ")" ]
https://github.com/pygae/clifford/blob/0b6cffb9a6d44ecb7a666f6b08b1788fc94a0ab6/clifford/tools/g3c/object_fitting.py#L66-L70
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
example/pyctp2/trader/trade_command.py
python
OpenInstruction.__init__
(self,order,position)
[]
def __init__(self,order,position): Instruction.__init__(self,order,position,1002)
[ "def", "__init__", "(", "self", ",", "order", ",", "position", ")", ":", "Instruction", ".", "__init__", "(", "self", ",", "order", ",", "position", ",", "1002", ")" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/pyctp2/trader/trade_command.py#L236-L237
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/shared_set_service/client.py
python
SharedSetServiceClient.common_folder_path
(folder: str,)
return "folders/{folder}".format(folder=folder,)
Return a fully-qualified folder string.
Return a fully-qualified folder string.
[ "Return", "a", "fully", "-", "qualified", "folder", "string", "." ]
def common_folder_path(folder: str,) -> str: """Return a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,)
[ "def", "common_folder_path", "(", "folder", ":", "str", ",", ")", "->", "str", ":", "return", "\"folders/{folder}\"", ".", "format", "(", "folder", "=", "folder", ",", ")" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/shared_set_service/client.py#L205-L207
dpp/simply_lift
cf49f7dcce81c7f1557314dd0f0bb08aaedc73da
elyxer.py
python
PostLayout.number
(self, layout)
Generate a number and place it before the text
Generate a number and place it before the text
[ "Generate", "a", "number", "and", "place", "it", "before", "the", "text" ]
def number(self, layout): "Generate a number and place it before the text" layout.partkey.addtoclabel(layout)
[ "def", "number", "(", "self", ",", "layout", ")", ":", "layout", ".", "partkey", ".", "addtoclabel", "(", "layout", ")" ]
https://github.com/dpp/simply_lift/blob/cf49f7dcce81c7f1557314dd0f0bb08aaedc73da/elyxer.py#L5491-L5493
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/geometry/polygon.py
python
Triangle.vertices
(self)
return self.args
The triangle's vertices Returns ======= vertices : tuple Each element in the tuple is a Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy.geometry import Triangle, Point >>> t = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t.vertices (Point2D(0, 0), Point2D(4, 0), Point2D(4, 3))
The triangle's vertices
[ "The", "triangle", "s", "vertices" ]
def vertices(self): """The triangle's vertices Returns ======= vertices : tuple Each element in the tuple is a Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy.geometry import Triangle, Point >>> t = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t.vertices (Point2D(0, 0), Point2D(4, 0), Point2D(4, 3)) """ return self.args
[ "def", "vertices", "(", "self", ")", ":", "return", "self", ".", "args" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/geometry/polygon.py#L2102-L2125
kylebebak/Requester
4a9f9f051fa5fc951a8f7ad098a328261ca2db97
deps/requests/models.py
python
Response.ok
(self)
return True
Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``.
Returns True if :attr:`status_code` is less than 400.
[ "Returns", "True", "if", ":", "attr", ":", "status_code", "is", "less", "than", "400", "." ]
def ok(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ try: self.raise_for_status() except HTTPError: return False return True
[ "def", "ok", "(", "self", ")", ":", "try", ":", "self", ".", "raise_for_status", "(", ")", "except", "HTTPError", ":", "return", "False", "return", "True" ]
https://github.com/kylebebak/Requester/blob/4a9f9f051fa5fc951a8f7ad098a328261ca2db97/deps/requests/models.py#L688-L700
hsokooti/RegNet
28a8b6132677bb58e9fc811c0dd15d78913c7e86
functions/setting/setting_utils.py
python
get_global_step
(setting, requested_global_step, current_experiment)
return global_step
get the global step of saver in order to load the requested network model: 'Last': search in the saved_folder to find the last network model 'Auto': use the global step defined in the function load_global_step_from_predefined_list() '#Number' : otherwise the number that is requested will be used. :param setting: :param requested_global_step: :param current_experiment: :return: global_step
get the global step of saver in order to load the requested network model: 'Last': search in the saved_folder to find the last network model 'Auto': use the global step defined in the function load_global_step_from_predefined_list() '#Number' : otherwise the number that is requested will be used. :param setting: :param requested_global_step: :param current_experiment: :return: global_step
[ "get", "the", "global", "step", "of", "saver", "in", "order", "to", "load", "the", "requested", "network", "model", ":", "Last", ":", "search", "in", "the", "saved_folder", "to", "find", "the", "last", "network", "model", "Auto", ":", "use", "the", "glob...
def get_global_step(setting, requested_global_step, current_experiment): """ get the global step of saver in order to load the requested network model: 'Last': search in the saved_folder to find the last network model 'Auto': use the global step defined in the function load_global_step_from_predefined_list() '#Number' : otherwise the number that is requested will be used. :param setting: :param requested_global_step: :param current_experiment: :return: global_step """ model_folder = address_generator(setting, 'ModelFolder', current_experiment=current_experiment) saved_folder = model_folder + 'Saved/' if requested_global_step == 'Last': saved_itr_list = [] for file in os.listdir(saved_folder): if file.endswith('meta'): saved_itr_list.append(int(os.path.splitext(file.rsplit('-')[1])[0])) global_step = str(max(saved_itr_list)) logging.info('Loading Network:' + current_experiment + ', GlobalStepLoad=' + global_step) elif requested_global_step == 'Auto': global_step = load_global_step_from_predefined_list(current_experiment) logging.info('Loading Network:' + current_experiment + ', GlobalStepLoad=' + global_step) else: global_step = requested_global_step return global_step
[ "def", "get_global_step", "(", "setting", ",", "requested_global_step", ",", "current_experiment", ")", ":", "model_folder", "=", "address_generator", "(", "setting", ",", "'ModelFolder'", ",", "current_experiment", "=", "current_experiment", ")", "saved_folder", "=", ...
https://github.com/hsokooti/RegNet/blob/28a8b6132677bb58e9fc811c0dd15d78913c7e86/functions/setting/setting_utils.py#L858-L885
rackerlabs/mimic
efd34108b6aa3eb7ecd26e22f1aa155c14a7885e
mimic/canned_responses/fastly.py
python
FastlyResponse.create_version
(self, service_id)
return create_version
Returns POST service with response json. :return: a JSON-serializable dictionary matching the format of the JSON response for fastly_client.create_version() ("/service/version") request.
Returns POST service with response json.
[ "Returns", "POST", "service", "with", "response", "json", "." ]
def create_version(self, service_id): """ Returns POST service with response json. :return: a JSON-serializable dictionary matching the format of the JSON response for fastly_client.create_version() ("/service/version") request. """ create_version = { 'service_id': service_id, 'number': 1} return create_version
[ "def", "create_version", "(", "self", ",", "service_id", ")", ":", "create_version", "=", "{", "'service_id'", ":", "service_id", ",", "'number'", ":", "1", "}", "return", "create_version" ]
https://github.com/rackerlabs/mimic/blob/efd34108b6aa3eb7ecd26e22f1aa155c14a7885e/mimic/canned_responses/fastly.py#L129-L141
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/keystone/keystone/openstack/common/jsonutils.py
python
to_primitive
(value, convert_instances=False, level=0)
Convert a complex object into primitives. Handy for JSON serialization. We can optionally handle instances, but since this is a recursive function, we could have cyclical data structures. To handle cyclical data structures we could track the actual objects visited in a set, but not all objects are hashable. Instead we just track the depth of the object inspections and don't go too deep. Therefore, convert_instances=True is lossy ... be aware.
Convert a complex object into primitives.
[ "Convert", "a", "complex", "object", "into", "primitives", "." ]
def to_primitive(value, convert_instances=False, level=0): """Convert a complex object into primitives. Handy for JSON serialization. We can optionally handle instances, but since this is a recursive function, we could have cyclical data structures. To handle cyclical data structures we could track the actual objects visited in a set, but not all objects are hashable. Instead we just track the depth of the object inspections and don't go too deep. Therefore, convert_instances=True is lossy ... be aware. """ nasty = [inspect.ismodule, inspect.isclass, inspect.ismethod, inspect.isfunction, inspect.isgeneratorfunction, inspect.isgenerator, inspect.istraceback, inspect.isframe, inspect.iscode, inspect.isbuiltin, inspect.isroutine, inspect.isabstract] for test in nasty: if test(value): return unicode(value) # value of itertools.count doesn't get caught by inspects # above and results in infinite loop when list(value) is called. if type(value) == itertools.count: return unicode(value) # FIXME(vish): Workaround for LP bug 852095. Without this workaround, # tests that raise an exception in a mocked method that # has a @wrap_exception with a notifier will fail. If # we up the dependency to 0.5.4 (when it is released) we # can remove this workaround. if getattr(value, '__module__', None) == 'mox': return 'mock' if level > 3: return '?' # The try block may not be necessary after the class check above, # but just in case ... try: # It's not clear why xmlrpclib created their own DateTime type, but # for our purposes, make it a datetime type which is explicitly # handled if isinstance(value, xmlrpclib.DateTime): value = datetime.datetime(*tuple(value.timetuple())[:6]) if isinstance(value, (list, tuple)): o = [] for v in value: o.append(to_primitive(v, convert_instances=convert_instances, level=level)) return o elif isinstance(value, dict): o = {} for k, v in value.iteritems(): o[k] = to_primitive(v, convert_instances=convert_instances, level=level) return o elif isinstance(value, datetime.datetime): return timeutils.strtime(value) elif hasattr(value, 'iteritems'): return to_primitive(dict(value.iteritems()), convert_instances=convert_instances, level=level + 1) elif hasattr(value, '__iter__'): return to_primitive(list(value), convert_instances=convert_instances, level=level) elif convert_instances and hasattr(value, '__dict__'): # Likely an instance of something. Watch for cycles. # Ignore class member vars. return to_primitive(value.__dict__, convert_instances=convert_instances, level=level + 1) else: return value except TypeError, e: # Class objects are tricky since they may define something like # __iter__ defined but it isn't callable as list(). return unicode(value)
[ "def", "to_primitive", "(", "value", ",", "convert_instances", "=", "False", ",", "level", "=", "0", ")", ":", "nasty", "=", "[", "inspect", ".", "ismodule", ",", "inspect", ".", "isclass", ",", "inspect", ".", "ismethod", ",", "inspect", ".", "isfunctio...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/keystone/keystone/openstack/common/jsonutils.py#L45-L126
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1alpha1_flow_schema_list.py
python
V1alpha1FlowSchemaList.__ne__
(self, other)
return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
Returns true if both objects are not equal
[ "Returns", "true", "if", "both", "objects", "are", "not", "equal" ]
def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1alpha1FlowSchemaList): return True return self.to_dict() != other.to_dict()
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "V1alpha1FlowSchemaList", ")", ":", "return", "True", "return", "self", ".", "to_dict", "(", ")", "!=", "other", ".", "to_dict", "(", ")" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1alpha1_flow_schema_list.py#L200-L205
openembedded/openembedded-core
9154f71c7267e9731156c1dfd57397103e9e6a2b
meta/lib/oeqa/runtime/cases/multilib.py
python
MultilibTest.test_check_multilib_libc
(self)
Check that a multilib image has both 32-bit and 64-bit libc in.
Check that a multilib image has both 32-bit and 64-bit libc in.
[ "Check", "that", "a", "multilib", "image", "has", "both", "32", "-", "bit", "and", "64", "-", "bit", "libc", "in", "." ]
def test_check_multilib_libc(self): """ Check that a multilib image has both 32-bit and 64-bit libc in. """ self.archtest("/lib/libc.so.6", "ELF32") self.archtest("/lib64/libc.so.6", "ELF64")
[ "def", "test_check_multilib_libc", "(", "self", ")", ":", "self", ".", "archtest", "(", "\"/lib/libc.so.6\"", ",", "\"ELF32\"", ")", "self", ".", "archtest", "(", "\"/lib64/libc.so.6\"", ",", "\"ELF64\"", ")" ]
https://github.com/openembedded/openembedded-core/blob/9154f71c7267e9731156c1dfd57397103e9e6a2b/meta/lib/oeqa/runtime/cases/multilib.py#L37-L42
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/distributed/static/js/distributed/perseus/ke/build/clean-exercises.py
python
main
()
Handle running this program from the command-line.
Handle running this program from the command-line.
[ "Handle", "running", "this", "program", "from", "the", "command", "-", "line", "." ]
def main(): """Handle running this program from the command-line.""" # Handle parsing the program arguments arg_parser = argparse.ArgumentParser( description='Clean up HTML exercise files.') arg_parser.add_argument('html_files', nargs='+', help='The HTML exercise files to clean up.') args = arg_parser.parse_args() for filename in args.html_files: # Parse the HTML tree. The parser in lint_i18n_strings properly # handles utf-8, which the default lxml parser doesn't. :-( html_tree = lxml.html.html5parser.parse( filename, parser=lint_i18n_strings.PARSER) with open(filename, 'w') as f: f.write(lint_i18n_strings.get_page_html(html_tree))
[ "def", "main", "(", ")", ":", "# Handle parsing the program arguments", "arg_parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Clean up HTML exercise files.'", ")", "arg_parser", ".", "add_argument", "(", "'html_files'", ",", "nargs", "=", "'...
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/distributed/static/js/distributed/perseus/ke/build/clean-exercises.py#L13-L30
titusjan/argos
5a9c31a8a9a2ca825bbf821aa1e685740e3682d7
argos/inspector/pgplugins/pgctis.py
python
AbstractRangeCti.calculateRange
(self)
Calculates the range depending on the config settings.
Calculates the range depending on the config settings.
[ "Calculates", "the", "range", "depending", "on", "the", "config", "settings", "." ]
def calculateRange(self): """ Calculates the range depending on the config settings. """ if not self.autoRangeCti or not self.autoRangeCti.configValue: return (self.rangeMinCti.data, self.rangeMaxCti.data) else: rangeFunction = self._rangeFunctions[self.autoRangeMethod] if self.subsampleCti is None: return rangeFunction() else: return rangeFunction(self.subsampleCti.configValue)
[ "def", "calculateRange", "(", "self", ")", ":", "if", "not", "self", ".", "autoRangeCti", "or", "not", "self", ".", "autoRangeCti", ".", "configValue", ":", "return", "(", "self", ".", "rangeMinCti", ".", "data", ",", "self", ".", "rangeMaxCti", ".", "da...
https://github.com/titusjan/argos/blob/5a9c31a8a9a2ca825bbf821aa1e685740e3682d7/argos/inspector/pgplugins/pgctis.py#L353-L364
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/polys/densetools.py
python
dup_primitive
(f, K)
Compute content and the primitive form of ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x = ring("x", ZZ) >>> f = 6*x**2 + 8*x + 12 >>> R.dup_primitive(f) (2, 3*x**2 + 4*x + 6) >>> R, x = ring("x", QQ) >>> f = 6*x**2 + 8*x + 12 >>> R.dup_primitive(f) (2, 3*x**2 + 4*x + 6)
Compute content and the primitive form of ``f`` in ``K[x]``.
[ "Compute", "content", "and", "the", "primitive", "form", "of", "f", "in", "K", "[", "x", "]", "." ]
def dup_primitive(f, K): """ Compute content and the primitive form of ``f`` in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ, QQ >>> R, x = ring("x", ZZ) >>> f = 6*x**2 + 8*x + 12 >>> R.dup_primitive(f) (2, 3*x**2 + 4*x + 6) >>> R, x = ring("x", QQ) >>> f = 6*x**2 + 8*x + 12 >>> R.dup_primitive(f) (2, 3*x**2 + 4*x + 6) """ if not f: return K.zero, f cont = dup_content(f, K) if K.is_one(cont): return cont, f else: return cont, dup_quo_ground(f, cont, K)
[ "def", "dup_primitive", "(", "f", ",", "K", ")", ":", "if", "not", "f", ":", "return", "K", ".", "zero", ",", "f", "cont", "=", "dup_content", "(", "f", ",", "K", ")", "if", "K", ".", "is_one", "(", "cont", ")", ":", "return", "cont", ",", "f...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/polys/densetools.py#L660-L690
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/utilities/GlobalPreferences.py
python
pref_skip_redraws_requested_only_by_Qt
()
return res
If enabled, GLPane paintGL calls not requested by our own gl_update calls are skipped, as an optimization. See comments where used for details and status. Default value depends on platform as of 080516.
If enabled, GLPane paintGL calls not requested by our own gl_update calls are skipped, as an optimization. See comments where used for details and status. Default value depends on platform as of 080516.
[ "If", "enabled", "GLPane", "paintGL", "calls", "not", "requested", "by", "our", "own", "gl_update", "calls", "are", "skipped", "as", "an", "optimization", ".", "See", "comments", "where", "used", "for", "details", "and", "status", ".", "Default", "value", "d...
def pref_skip_redraws_requested_only_by_Qt(): #bruce 080516 moved this here, revised default to be off on Windows """ If enabled, GLPane paintGL calls not requested by our own gl_update calls are skipped, as an optimization. See comments where used for details and status. Default value depends on platform as of 080516. """ if sys.platform == "win32": # Windows -- enabling this causes bugs on at least one system choice = Choice_boolean_False else: # non-Windows -- no known bugs as of 080516 #bruce 080512 made this True, revised prefs_key choice = Choice_boolean_True res = debug_pref("GLPane: skip redraws requested only by Qt?", choice, non_debug = True, #bruce 080130 prefs_key = "GLPane: skip redraws requested only by Qt?" ) return res
[ "def", "pref_skip_redraws_requested_only_by_Qt", "(", ")", ":", "#bruce 080516 moved this here, revised default to be off on Windows", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "# Windows -- enabling this causes bugs on at least one system", "choice", "=", "Choice_boolean...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/utilities/GlobalPreferences.py#L434-L453
Cadene/tensorflow-model-zoo.torch
990b10ffc22d4c8eacb2a502f20415b4f70c74c2
models/research/object_detection/utils/np_box_ops.py
python
intersection
(boxes1, boxes2)
return intersect_heights * intersect_widths
Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area
Compute pairwise intersection areas between boxes.
[ "Compute", "pairwise", "intersection", "areas", "between", "boxes", "." ]
def intersection(boxes1, boxes2): """Compute pairwise intersection areas between boxes. Args: boxes1: a numpy array with shape [N, 4] holding N boxes boxes2: a numpy array with shape [M, 4] holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ [y_min1, x_min1, y_max1, x_max1] = np.split(boxes1, 4, axis=1) [y_min2, x_min2, y_max2, x_max2] = np.split(boxes2, 4, axis=1) all_pairs_min_ymax = np.minimum(y_max1, np.transpose(y_max2)) all_pairs_max_ymin = np.maximum(y_min1, np.transpose(y_min2)) intersect_heights = np.maximum( np.zeros(all_pairs_max_ymin.shape), all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = np.minimum(x_max1, np.transpose(x_max2)) all_pairs_max_xmin = np.maximum(x_min1, np.transpose(x_min2)) intersect_widths = np.maximum( np.zeros(all_pairs_max_xmin.shape), all_pairs_min_xmax - all_pairs_max_xmin) return intersect_heights * intersect_widths
[ "def", "intersection", "(", "boxes1", ",", "boxes2", ")", ":", "[", "y_min1", ",", "x_min1", ",", "y_max1", ",", "x_max1", "]", "=", "np", ".", "split", "(", "boxes1", ",", "4", ",", "axis", "=", "1", ")", "[", "y_min2", ",", "x_min2", ",", "y_ma...
https://github.com/Cadene/tensorflow-model-zoo.torch/blob/990b10ffc22d4c8eacb2a502f20415b4f70c74c2/models/research/object_detection/utils/np_box_ops.py#L37-L60
autonomousvision/differentiable_volumetric_rendering
5a190104b9f8143125beed714d33f265f5006f30
im2mesh/dvr/models/depth_function.py
python
DepthFunction.run_Bisection_method
(d_low, d_high, n_secant_steps, ray0_masked, ray_direction_masked, decoder, c, logit_tau)
return d_pred
Runs the bisection method for interval [d_low, d_high]. Args: d_low (tensor): start values for the interval d_high (tensor): end values for the interval n_secant_steps (int): number of steps ray0_masked (tensor): masked ray start points ray_direction_masked (tensor): masked ray direction vectors decoder (nn.Module): decoder model to evaluate point occupancies c (tensor): latent conditioned code c logit_tau (float): threshold value in logits
Runs the bisection method for interval [d_low, d_high].
[ "Runs", "the", "bisection", "method", "for", "interval", "[", "d_low", "d_high", "]", "." ]
def run_Bisection_method(d_low, d_high, n_secant_steps, ray0_masked, ray_direction_masked, decoder, c, logit_tau): ''' Runs the bisection method for interval [d_low, d_high]. Args: d_low (tensor): start values for the interval d_high (tensor): end values for the interval n_secant_steps (int): number of steps ray0_masked (tensor): masked ray start points ray_direction_masked (tensor): masked ray direction vectors decoder (nn.Module): decoder model to evaluate point occupancies c (tensor): latent conditioned code c logit_tau (float): threshold value in logits ''' d_pred = (d_low + d_high) / 2. for i in range(n_secant_steps): p_mid = ray0_masked + d_pred.unsqueeze(-1) * ray_direction_masked with torch.no_grad(): f_mid = decoder(p_mid, c, batchwise=False, only_occupancy=True) - logit_tau ind_low = f_mid < 0 d_low[ind_low] = d_pred[ind_low] d_high[ind_low == 0] = d_pred[ind_low == 0] d_pred = 0.5 * (d_low + d_high) return d_pred
[ "def", "run_Bisection_method", "(", "d_low", ",", "d_high", ",", "n_secant_steps", ",", "ray0_masked", ",", "ray_direction_masked", ",", "decoder", ",", "c", ",", "logit_tau", ")", ":", "d_pred", "=", "(", "d_low", "+", "d_high", ")", "/", "2.", "for", "i"...
https://github.com/autonomousvision/differentiable_volumetric_rendering/blob/5a190104b9f8143125beed714d33f265f5006f30/im2mesh/dvr/models/depth_function.py#L116-L140
JulianEberius/SublimePythonIDE
d70e40abc0c9f347af3204c7b910e0d6bfd6e459
server/lib/python2/rope/refactor/occurrences.py
python
Finder.find_occurrences
(self, resource=None, pymodule=None)
Generate `Occurrence` instances
Generate `Occurrence` instances
[ "Generate", "Occurrence", "instances" ]
def find_occurrences(self, resource=None, pymodule=None): """Generate `Occurrence` instances""" tools = _OccurrenceToolsCreator(self.pycore, resource=resource, pymodule=pymodule, docs=self.docs) for offset in self._textual_finder.find_offsets(tools.source_code): occurrence = Occurrence(tools, offset) for filter in self.filters: result = filter(occurrence) if result is None: continue if result: yield occurrence break
[ "def", "find_occurrences", "(", "self", ",", "resource", "=", "None", ",", "pymodule", "=", "None", ")", ":", "tools", "=", "_OccurrenceToolsCreator", "(", "self", ".", "pycore", ",", "resource", "=", "resource", ",", "pymodule", "=", "pymodule", ",", "doc...
https://github.com/JulianEberius/SublimePythonIDE/blob/d70e40abc0c9f347af3204c7b910e0d6bfd6e459/server/lib/python2/rope/refactor/occurrences.py#L29-L41
tdozat/Parser-v1
0739216129cd39d69997d28cbc4133b360ea3934
lib/models/rnn.py
python
_dynamic_rnn_loop
( cell, inputs, initial_state, ff_keep_prob, recur_keep_prob, parallel_iterations, swap_memory, sequence_length=None)
return (final_outputs, final_state)
Internal implementation of Dynamic RNN. Args: cell: An instance of RNNCell. inputs: A `Tensor` of shape [time, batch_size, depth]. initial_state: A `Tensor` of shape [batch_size, depth]. parallel_iterations: Positive Python int. swap_memory: A Python boolean sequence_length: (optional) An `int32` `Tensor` of shape [batch_size]. Returns: Tuple (final_outputs, final_state). final_outputs: A `Tensor` of shape [time, batch_size, depth]`. final_state: A `Tensor` of shape [batch_size, depth]. Raises: ValueError: If the input depth cannot be inferred via shape inference from the inputs.
Internal implementation of Dynamic RNN.
[ "Internal", "implementation", "of", "Dynamic", "RNN", "." ]
def _dynamic_rnn_loop( cell, inputs, initial_state, ff_keep_prob, recur_keep_prob, parallel_iterations, swap_memory, sequence_length=None): """Internal implementation of Dynamic RNN. Args: cell: An instance of RNNCell. inputs: A `Tensor` of shape [time, batch_size, depth]. initial_state: A `Tensor` of shape [batch_size, depth]. parallel_iterations: Positive Python int. swap_memory: A Python boolean sequence_length: (optional) An `int32` `Tensor` of shape [batch_size]. Returns: Tuple (final_outputs, final_state). final_outputs: A `Tensor` of shape [time, batch_size, depth]`. final_state: A `Tensor` of shape [batch_size, depth]. Raises: ValueError: If the input depth cannot be inferred via shape inference from the inputs. """ state = initial_state assert isinstance(parallel_iterations, int), "parallel_iterations must be int" # Construct an initial output input_shape = array_ops.shape(inputs) (time_steps, batch_size, _) = array_ops.unpack(input_shape, 3) inputs_got_shape = inputs.get_shape().with_rank(3) (const_time_steps, const_batch_size, const_depth) = inputs_got_shape.as_list() if const_depth is None: raise ValueError( "Input size (depth of inputs) must be accessible via shape inference, " "but saw value None.") # Prepare dynamic conditional copying of state & output zero_output = array_ops.zeros( array_ops.pack([batch_size, cell.output_size]), inputs.dtype) if sequence_length is not None: min_sequence_length = math_ops.reduce_min(sequence_length) max_sequence_length = math_ops.reduce_max(sequence_length) time = array_ops.constant(0, dtype=dtypes.int32, name="time") with ops.op_scope([], "dynamic_rnn") as scope: base_name = scope output_ta = tensor_array_ops.TensorArray( dtype=inputs.dtype, size=time_steps, tensor_array_name=base_name + "output") input_ta = tensor_array_ops.TensorArray( dtype=inputs.dtype, size=time_steps, tensor_array_name=base_name + "input") if isinstance(ff_keep_prob, ops.Tensor) or ff_keep_prob < 1: inputs = nn_ops.dropout(inputs, ff_keep_prob, noise_shape=array_ops.pack([1, batch_size, const_depth])) input_ta = input_ta.unpack(inputs) if isinstance(recur_keep_prob, ops.Tensor) or recur_keep_prob < 1: ones = array_ops.ones(array_ops.pack([batch_size, cell.output_size]), inputs.dtype) state_dropout = nn_ops.dropout(ones, recur_keep_prob) state_dropout = array_ops.concat(1, [ones] * (cell.state_size // cell.output_size - 1) + [state_dropout]) else: state_dropout = 1. def _time_step(time, state, output_ta_t): """Take a time step of the dynamic RNN. Args: time: int32 scalar Tensor. state: Vector. output_ta_t: `TensorArray`, the output with existing flow. Returns: The tuple (time + 1, new_state, output_ta_t with updated flow). """ input_t = input_ta.read(time) # Restore some shape information input_t.set_shape([const_batch_size, const_depth]) call_cell = lambda: cell(input_t, state*state_dropout) if sequence_length is not None: (output, new_state) = _rnn_step( time=time, sequence_length=sequence_length, min_sequence_length=min_sequence_length, max_sequence_length=max_sequence_length, zero_output=zero_output, state=state, call_cell=call_cell, skip_conditionals=True) else: (output, new_state) = call_cell() output_ta_t = output_ta_t.write(time, output) return (time + 1, new_state, output_ta_t) (_, final_state, output_final_ta) = control_flow_ops.while_loop( cond=lambda time, _1, _2: time < time_steps, body=_time_step, loop_vars=(time, state, output_ta), parallel_iterations=parallel_iterations, swap_memory=swap_memory) final_outputs = output_final_ta.pack() # Restore some shape information final_outputs.set_shape([ const_time_steps, const_batch_size, cell.output_size]) return (final_outputs, final_state)
[ "def", "_dynamic_rnn_loop", "(", "cell", ",", "inputs", ",", "initial_state", ",", "ff_keep_prob", ",", "recur_keep_prob", ",", "parallel_iterations", ",", "swap_memory", ",", "sequence_length", "=", "None", ")", ":", "state", "=", "initial_state", "assert", "isin...
https://github.com/tdozat/Parser-v1/blob/0739216129cd39d69997d28cbc4133b360ea3934/lib/models/rnn.py#L557-L672
llSourcell/AI_For_Music_Composition
795f8879158b238e7dc78d07e4451dcf54a2126c
musegan/utils/midi_io.py
python
save_midi
(filepath, phrases, config)
Save a batch of phrases to a single MIDI file. Arguments --------- filepath : str Path to save the image grid. phrases : list of np.array Phrase arrays to be saved. All arrays must have the same shape. pause : int Length of pauses (in timestep) to be inserted between phrases. Default to 0.
Save a batch of phrases to a single MIDI file.
[ "Save", "a", "batch", "of", "phrases", "to", "a", "single", "MIDI", "file", "." ]
def save_midi(filepath, phrases, config): """ Save a batch of phrases to a single MIDI file. Arguments --------- filepath : str Path to save the image grid. phrases : list of np.array Phrase arrays to be saved. All arrays must have the same shape. pause : int Length of pauses (in timestep) to be inserted between phrases. Default to 0. """ if not np.issubdtype(phrases.dtype, np.bool_): raise TypeError("Support only binary-valued piano-rolls") reshaped = phrases.reshape(-1, phrases.shape[1] * phrases.shape[2], phrases.shape[3], phrases.shape[4]) pad_width = ((0, 0), (0, config['pause_between_samples']), (config['lowest_pitch'], 128 - config['lowest_pitch'] - config['num_pitch']), (0, 0)) padded = np.pad(reshaped, pad_width, 'constant') pianorolls = padded.reshape(-1, padded.shape[2], padded.shape[3]) write_midi(filepath, pianorolls, config['programs'], config['is_drums'], tempo=config['tempo'])
[ "def", "save_midi", "(", "filepath", ",", "phrases", ",", "config", ")", ":", "if", "not", "np", ".", "issubdtype", "(", "phrases", ".", "dtype", ",", "np", ".", "bool_", ")", ":", "raise", "TypeError", "(", "\"Support only binary-valued piano-rolls\"", ")",...
https://github.com/llSourcell/AI_For_Music_Composition/blob/795f8879158b238e7dc78d07e4451dcf54a2126c/musegan/utils/midi_io.py#L57-L84
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/util/volume.py
python
cubic_feet_to_cubic_meter
(cubic_feet: float)
return cubic_feet * 0.0283168466
Convert a volume measurement in cubic feet to cubic meter.
Convert a volume measurement in cubic feet to cubic meter.
[ "Convert", "a", "volume", "measurement", "in", "cubic", "feet", "to", "cubic", "meter", "." ]
def cubic_feet_to_cubic_meter(cubic_feet: float) -> float: """Convert a volume measurement in cubic feet to cubic meter.""" return cubic_feet * 0.0283168466
[ "def", "cubic_feet_to_cubic_meter", "(", "cubic_feet", ":", "float", ")", "->", "float", ":", "return", "cubic_feet", "*", "0.0283168466" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/util/volume.py#L42-L44
DataXujing/YOLO-V3-Tensorflow
20562d0c22965a904c6648997b66dfdf1c96be4d
utils/eval_utils.py
python
calc_iou
(pred_boxes, true_boxes)
return iou
Maintain an efficient way to calculate the ios matrix using the numpy broadcast tricks. shape_info: pred_boxes: [N, 4] true_boxes: [V, 4] return: IoU matrix: shape: [N, V]
Maintain an efficient way to calculate the ios matrix using the numpy broadcast tricks. shape_info: pred_boxes: [N, 4] true_boxes: [V, 4] return: IoU matrix: shape: [N, V]
[ "Maintain", "an", "efficient", "way", "to", "calculate", "the", "ios", "matrix", "using", "the", "numpy", "broadcast", "tricks", ".", "shape_info", ":", "pred_boxes", ":", "[", "N", "4", "]", "true_boxes", ":", "[", "V", "4", "]", "return", ":", "IoU", ...
def calc_iou(pred_boxes, true_boxes): ''' Maintain an efficient way to calculate the ios matrix using the numpy broadcast tricks. shape_info: pred_boxes: [N, 4] true_boxes: [V, 4] return: IoU matrix: shape: [N, V] ''' # [N, 1, 4] pred_boxes = np.expand_dims(pred_boxes, -2) # [1, V, 4] true_boxes = np.expand_dims(true_boxes, 0) # [N, 1, 2] & [1, V, 2] ==> [N, V, 2] intersect_mins = np.maximum(pred_boxes[..., :2], true_boxes[..., :2]) intersect_maxs = np.minimum(pred_boxes[..., 2:], true_boxes[..., 2:]) intersect_wh = np.maximum(intersect_maxs - intersect_mins, 0.) # shape: [N, V] intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] # shape: [N, 1, 2] pred_box_wh = pred_boxes[..., 2:] - pred_boxes[..., :2] # shape: [N, 1] pred_box_area = pred_box_wh[..., 0] * pred_box_wh[..., 1] # [1, V, 2] true_boxes_wh = true_boxes[..., 2:] - true_boxes[..., :2] # [1, V] true_boxes_area = true_boxes_wh[..., 0] * true_boxes_wh[..., 1] # shape: [N, V] iou = intersect_area / (pred_box_area + true_boxes_area - intersect_area + 1e-10) return iou
[ "def", "calc_iou", "(", "pred_boxes", ",", "true_boxes", ")", ":", "# [N, 1, 4]", "pred_boxes", "=", "np", ".", "expand_dims", "(", "pred_boxes", ",", "-", "2", ")", "# [1, V, 4]", "true_boxes", "=", "np", ".", "expand_dims", "(", "true_boxes", ",", "0", "...
https://github.com/DataXujing/YOLO-V3-Tensorflow/blob/20562d0c22965a904c6648997b66dfdf1c96be4d/utils/eval_utils.py#L13-L45
blockcypher/explorer
3cb07c58ed6573964921e343fce01552accdf958
emails/trigger.py
python
send_and_log
(subject, body_template, to_user=None, to_email=None, to_name=None, body_context={}, from_name=None, from_email=None, cc_name=None, cc_email=None, replyto_name=None, replyto_email=None, fkey_objs={})
return se
Send and log an email
Send and log an email
[ "Send", "and", "log", "an", "email" ]
def send_and_log(subject, body_template, to_user=None, to_email=None, to_name=None, body_context={}, from_name=None, from_email=None, cc_name=None, cc_email=None, replyto_name=None, replyto_email=None, fkey_objs={}): """ Send and log an email """ # TODO: find a better way to handle the circular dependency from emails.models import SentEmail assert subject assert body_template assert to_email or to_user if to_user: to_email = to_user.email to_name = to_user.get_full_name() if not from_email: from_name, from_email = split_email_header(POSTMARK_SENDER) body_context_modified = body_context.copy() body_context_modified['BASE_URL'] = BASE_URL unsub_code = simple_pw_generator(num_chars=10) verif_code = simple_pw_generator(num_chars=10) body_context_modified['unsub_code'] = unsub_code body_context_modified['verif_code'] = verif_code # Generate html body html_body = render_to_string('emails/'+body_template, body_context_modified) send_dict = { 'html_body': html_body, 'from_info': cat_email_header(from_name, from_email), 'to_info': cat_email_header(to_name, to_email), 'subject': subject, # may be overwritten below } if cc_email: send_dict['cc_info'] = cat_email_header(cc_name, cc_email) if replyto_email: send_dict['replyto_info'] = cat_email_header(replyto_name, replyto_email) else: send_dict['replyto_info'] = 'BlockCypher <contact@blockcypher.com>' if EMAIL_DEV_PREFIX: send_dict['subject'] += ' [DEV]' else: # send_dict['bcc_info'] = ','.join([POSTMARK_SENDER, ]) pass # Log everything se = SentEmail.objects.create( from_email=from_email, from_name=from_name, to_email=to_email, to_name=to_name, cc_name=cc_name, cc_email=cc_email, body_template=body_template, body_context=body_context, subject=subject, unsub_code=unsub_code, verif_code=verif_code, auth_user=fkey_objs.get('auth_user', to_user), address_subscription=fkey_objs.get('address_subscription'), transaction_event=fkey_objs.get('transaction_event'), address_forwarding=fkey_objs.get('address_forwarding'), ) postmark_send(**send_dict) return se
[ "def", "send_and_log", "(", "subject", ",", "body_template", ",", "to_user", "=", "None", ",", "to_email", "=", "None", ",", "to_name", "=", "None", ",", "body_context", "=", "{", "}", ",", "from_name", "=", "None", ",", "from_email", "=", "None", ",", ...
https://github.com/blockcypher/explorer/blob/3cb07c58ed6573964921e343fce01552accdf958/emails/trigger.py#L45-L118
khalim19/gimp-plugin-export-layers
b37255f2957ad322f4d332689052351cdea6e563
export_layers/pygimplib/_lib/future/future/backports/http/cookiejar.py
python
CookieJar.__len__
(self)
return i
Return number of contained cookies.
Return number of contained cookies.
[ "Return", "number", "of", "contained", "cookies", "." ]
def __len__(self): """Return number of contained cookies.""" i = 0 for cookie in self: i = i + 1 return i
[ "def", "__len__", "(", "self", ")", ":", "i", "=", "0", "for", "cookie", "in", "self", ":", "i", "=", "i", "+", "1", "return", "i" ]
https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/pygimplib/_lib/future/future/backports/http/cookiejar.py#L1734-L1738
rhiever/reddit-analysis
0fc309c9091cf2b219c2e664b6cf17b39141e2ef
redditanalysis/__init__.py
python
tokenize
(text)
Return individual tokens from a block of text.
Return individual tokens from a block of text.
[ "Return", "individual", "tokens", "from", "a", "block", "of", "text", "." ]
def tokenize(text): """Return individual tokens from a block of text.""" def normalized_tokens(token): """Yield lower-case tokens from the given token.""" for sub in TOKEN_RE.findall(token): if sub: yield sub.lower() for token in text.split(): # first split on whitespace if URL_RE.search(token): # Ignore invalid tokens continue for sub_token in normalized_tokens(token): if sub_token.endswith("'s"): # Fix possessive form sub_token = sub_token[:-2] yield sub_token
[ "def", "tokenize", "(", "text", ")", ":", "def", "normalized_tokens", "(", "token", ")", ":", "\"\"\"Yield lower-case tokens from the given token.\"\"\"", "for", "sub", "in", "TOKEN_RE", ".", "findall", "(", "token", ")", ":", "if", "sub", ":", "yield", "sub", ...
https://github.com/rhiever/reddit-analysis/blob/0fc309c9091cf2b219c2e664b6cf17b39141e2ef/redditanalysis/__init__.py#L149-L163
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/patched/notpip/_vendor/requests/cookies.py
python
RequestsCookieJar.copy
(self)
return new_cj
Return a copy of this RequestsCookieJar.
Return a copy of this RequestsCookieJar.
[ "Return", "a", "copy", "of", "this", "RequestsCookieJar", "." ]
def copy(self): """Return a copy of this RequestsCookieJar.""" new_cj = RequestsCookieJar() new_cj.set_policy(self.get_policy()) new_cj.update(self) return new_cj
[ "def", "copy", "(", "self", ")", ":", "new_cj", "=", "RequestsCookieJar", "(", ")", "new_cj", ".", "set_policy", "(", "self", ".", "get_policy", "(", ")", ")", "new_cj", ".", "update", "(", "self", ")", "return", "new_cj" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/patched/notpip/_vendor/requests/cookies.py#L414-L419
dipu-bd/lightnovel-crawler
eca7a71f217ce7a6b0a54d2e2afb349571871880
sources/en/n/novelcake.py
python
NovelCake.read_novel_info
(self)
Get novel title, autor, cover etc
Get novel title, autor, cover etc
[ "Get", "novel", "title", "autor", "cover", "etc" ]
def read_novel_info(self): '''Get novel title, autor, cover etc''' logger.debug('Visiting %s', self.novel_url) soup = self.get_soup(self.novel_url) possible_title = soup.select_one('.post-title h1') for span in possible_title.select('span'): span.extract() # end for self.novel_title = possible_title.text.strip() logger.info('Novel title: %s', self.novel_title) self.novel_cover = self.absolute_url( soup.select_one('.summary_image a img')['data-src']) logger.info('Novel cover: %s', self.novel_cover) self.novel_author = ' '.join([ a.text.strip() for a in soup.select('.author-content a[href*="series-author"]') ]) logger.info('%s', self.novel_author) self.novel_id = soup.select_one('#manga-chapters-holder')['data-id'] logger.info('Novel id: %s', self.novel_id) response = self.submit_form(chapter_list_url, data={ 'action': 'manga_get_chapters', 'manga': self.novel_id, }) soup = self.make_soup(response) for a in reversed(soup.select(".wp-manga-chapter a")): chap_id = len(self.chapters) + 1 vol_id = 1 + len(self.chapters) // 100 if chap_id % 100 == 1: self.volumes.append({"id": vol_id}) # end if self.chapters.append( { "id": chap_id, "volume": vol_id, "title": a.text.strip(), "url": self.absolute_url(a["href"]), } )
[ "def", "read_novel_info", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Visiting %s'", ",", "self", ".", "novel_url", ")", "soup", "=", "self", ".", "get_soup", "(", "self", ".", "novel_url", ")", "possible_title", "=", "soup", ".", "select_one", ...
https://github.com/dipu-bd/lightnovel-crawler/blob/eca7a71f217ce7a6b0a54d2e2afb349571871880/sources/en/n/novelcake.py#L35-L78
ducksboard/libsaas
615981a3336f65be9d51ae95a48aed9ad3bd1c3c
libsaas/services/googlespreadsheets/resource.py
python
SpreadsheetsResource.create
(self, obj)
return request, parsers.parse_xml
Create a new resource. :var obj: a Python object representing the resource to be created, usually in the same as returned from `get`. Refer to the upstream documentation for details.
Create a new resource.
[ "Create", "a", "new", "resource", "." ]
def create(self, obj): """ Create a new resource. :var obj: a Python object representing the resource to be created, usually in the same as returned from `get`. Refer to the upstream documentation for details. """ self.require_collection() request = http.Request('POST', self.get_url(), self.wrap_object(obj)) return request, parsers.parse_xml
[ "def", "create", "(", "self", ",", "obj", ")", ":", "self", ".", "require_collection", "(", ")", "request", "=", "http", ".", "Request", "(", "'POST'", ",", "self", ".", "get_url", "(", ")", ",", "self", ".", "wrap_object", "(", "obj", ")", ")", "r...
https://github.com/ducksboard/libsaas/blob/615981a3336f65be9d51ae95a48aed9ad3bd1c3c/libsaas/services/googlespreadsheets/resource.py#L18-L29
roam-qgis/Roam
6bfa836a2735f611b7f26de18ae4a4581f7e83ef
ext_libs/cx_Freeze/hooks.py
python
load_Numeric
(finder, module)
the Numeric module optionally loads the dotblas module; ignore the error if this modules does not exist.
the Numeric module optionally loads the dotblas module; ignore the error if this modules does not exist.
[ "the", "Numeric", "module", "optionally", "loads", "the", "dotblas", "module", ";", "ignore", "the", "error", "if", "this", "modules", "does", "not", "exist", "." ]
def load_Numeric(finder, module): """the Numeric module optionally loads the dotblas module; ignore the error if this modules does not exist.""" module.IgnoreName("dotblas")
[ "def", "load_Numeric", "(", "finder", ",", "module", ")", ":", "module", ".", "IgnoreName", "(", "\"dotblas\"", ")" ]
https://github.com/roam-qgis/Roam/blob/6bfa836a2735f611b7f26de18ae4a4581f7e83ef/ext_libs/cx_Freeze/hooks.py#L275-L278
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/jinja2/utils.py
python
LRUCache.__reversed__
(self)
return iter(tuple(self._queue))
Iterate over the values in the cache dict, oldest items coming first.
Iterate over the values in the cache dict, oldest items coming first.
[ "Iterate", "over", "the", "values", "in", "the", "cache", "dict", "oldest", "items", "coming", "first", "." ]
def __reversed__(self): """Iterate over the values in the cache dict, oldest items coming first. """ return iter(tuple(self._queue))
[ "def", "__reversed__", "(", "self", ")", ":", "return", "iter", "(", "tuple", "(", "self", ".", "_queue", ")", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/jinja2/utils.py#L474-L478
ucfopen/canvasapi
3f1a71e23c86a49dbaa6e84f6c0e81c297b86e36
canvasapi/folder.py
python
Folder.create_folder
(self, name, **kwargs)
return Folder(self._requester, response.json())
Creates a folder within this folder. :calls: `POST /api/v1/folders/:folder_id/folders \ <https://canvas.instructure.com/doc/api/files.html#method.folders.create>`_ :param name: The name of the folder. :type name: str :rtype: :class:`canvasapi.folder.Folder`
Creates a folder within this folder.
[ "Creates", "a", "folder", "within", "this", "folder", "." ]
def create_folder(self, name, **kwargs): """ Creates a folder within this folder. :calls: `POST /api/v1/folders/:folder_id/folders \ <https://canvas.instructure.com/doc/api/files.html#method.folders.create>`_ :param name: The name of the folder. :type name: str :rtype: :class:`canvasapi.folder.Folder` """ response = self._requester.request( "POST", "folders/{}/folders".format(self.id), name=name, _kwargs=combine_kwargs(**kwargs), ) return Folder(self._requester, response.json())
[ "def", "create_folder", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "_requester", ".", "request", "(", "\"POST\"", ",", "\"folders/{}/folders\"", ".", "format", "(", "self", ".", "id", ")", ",", "name", "=...
https://github.com/ucfopen/canvasapi/blob/3f1a71e23c86a49dbaa6e84f6c0e81c297b86e36/canvasapi/folder.py#L36-L53
wummel/patool
723006abd43d0926581b11df0cd37e46a30525eb
patoolib/programs/rar.py
python
list_rar
(archive, compression, cmd, verbosity, interactive, password=None)
return cmdlist
List a RAR archive.
List a RAR archive.
[ "List", "a", "RAR", "archive", "." ]
def list_rar (archive, compression, cmd, verbosity, interactive, password=None): """List a RAR archive.""" cmdlist = [cmd] if verbosity > 1: cmdlist.append('v') else: cmdlist.append('l') if not interactive: cmdlist.extend(['-p-', '-y']) if password: cmdlist.append('-p%s' % password) cmdlist.extend(['--', archive]) return cmdlist
[ "def", "list_rar", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "password", "=", "None", ")", ":", "cmdlist", "=", "[", "cmd", "]", "if", "verbosity", ">", "1", ":", "cmdlist", ".", "append", "(", "'v'", ...
https://github.com/wummel/patool/blob/723006abd43d0926581b11df0cd37e46a30525eb/patoolib/programs/rar.py#L29-L41
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pip/_vendor/requests/models.py
python
Response.json
(self, **kwargs)
return complexjson.loads(self.text, **kwargs)
Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
Returns the json-encoded content of a response, if any.
[ "Returns", "the", "json", "-", "encoded", "content", "of", "a", "response", "if", "any", "." ]
def json(self, **kwargs): """Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads( self.content.decode(encoding), **kwargs ) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return complexjson.loads(self.text, **kwargs)
[ "def", "json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "encoding", "and", "self", ".", "content", "and", "len", "(", "self", ".", "content", ")", ">", "3", ":", "# No encoding set. JSON RFC 4627 section 3 states we should ex...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pip/_vendor/requests/models.py#L803-L826
phonopy/phonopy
816586d0ba8177482ecf40e52f20cbdee2260d51
phonopy/interface/qe.py
python
PwscfIn._set_nat
(self)
[]
def _set_nat(self): self._tags["nat"] = int(self._values[0])
[ "def", "_set_nat", "(", "self", ")", ":", "self", ".", "_tags", "[", "\"nat\"", "]", "=", "int", "(", "self", ".", "_values", "[", "0", "]", ")" ]
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/interface/qe.py#L285-L286
yt-project/yt
dc7b24f9b266703db4c843e329c6c8644d47b824
yt/fields/derived_field.py
python
ValidateGridType.__init__
(self)
This validator ensures that the data handed to the field is an actual grid patch, not a covering grid of any kind.
This validator ensures that the data handed to the field is an actual grid patch, not a covering grid of any kind.
[ "This", "validator", "ensures", "that", "the", "data", "handed", "to", "the", "field", "is", "an", "actual", "grid", "patch", "not", "a", "covering", "grid", "of", "any", "kind", "." ]
def __init__(self): """ This validator ensures that the data handed to the field is an actual grid patch, not a covering grid of any kind. """ FieldValidator.__init__(self)
[ "def", "__init__", "(", "self", ")", ":", "FieldValidator", ".", "__init__", "(", "self", ")" ]
https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/fields/derived_field.py#L568-L573
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/data/parsers/pynarcissus/jsparser.py
python
Variables
(t, x)
return n
[]
def Variables(t, x): n = Node(t) while True: t.mustMatch(IDENTIFIER) n2 = Node(t) n2.name = n2.value if t.match(ASSIGN): if t.token.assignOp: raise t.newSyntaxError("Invalid variable initialization") n2.initializer = Expression(t, x, COMMA) n2.readOnly = not not (n.type_ == CONST) n.append(n2) x.varDecls.append(n2) if not t.match(COMMA): break return n
[ "def", "Variables", "(", "t", ",", "x", ")", ":", "n", "=", "Node", "(", "t", ")", "while", "True", ":", "t", ".", "mustMatch", "(", "IDENTIFIER", ")", "n2", "=", "Node", "(", "t", ")", "n2", ".", "name", "=", "n2", ".", "value", "if", "t", ...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/data/parsers/pynarcissus/jsparser.py#L766-L780
google/clusterfuzz
f358af24f414daa17a3649b143e71ea71871ef59
src/clusterfuzz/_internal/datastore/data_types.py
python
Testcase._ensure_metadata_is_cached
(self)
Ensure that the metadata for this has been cached.
Ensure that the metadata for this has been cached.
[ "Ensure", "that", "the", "metadata", "for", "this", "has", "been", "cached", "." ]
def _ensure_metadata_is_cached(self): """Ensure that the metadata for this has been cached.""" if hasattr(self, 'metadata_cache'): return try: cache = json_utils.loads(self.additional_metadata) except (TypeError, ValueError): cache = {} setattr(self, 'metadata_cache', cache)
[ "def", "_ensure_metadata_is_cached", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'metadata_cache'", ")", ":", "return", "try", ":", "cache", "=", "json_utils", ".", "loads", "(", "self", ".", "additional_metadata", ")", "except", "(", "TypeErr...
https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/clusterfuzz/_internal/datastore/data_types.py#L655-L665
Zulko/easyAI
a5cbd0b600ebbeadc3730df9e7a211d7643cff8b
easyAI/AI/NonRecursiveNegamax.py
python
StateObject.swap_alpha_beta
(self)
[]
def swap_alpha_beta(self): (self.alpha, self.beta) = (self.beta, self.alpha)
[ "def", "swap_alpha_beta", "(", "self", ")", ":", "(", "self", ".", "alpha", ",", "self", ".", "beta", ")", "=", "(", "self", ".", "beta", ",", "self", ".", "alpha", ")" ]
https://github.com/Zulko/easyAI/blob/a5cbd0b600ebbeadc3730df9e7a211d7643cff8b/easyAI/AI/NonRecursiveNegamax.py#L55-L56
uqfoundation/multiprocess
028cc73f02655e6451d92e5147d19d8c10aebe50
py3.8/multiprocess/util.py
python
get_logger
()
return _logger
Returns logger used by multiprocess
Returns logger used by multiprocess
[ "Returns", "logger", "used", "by", "multiprocess" ]
def get_logger(): ''' Returns logger used by multiprocess ''' global _logger import logging logging._acquireLock() try: if not _logger: _logger = logging.getLogger(LOGGER_NAME) _logger.propagate = 0 # XXX multiprocessing should cleanup before logging if hasattr(atexit, 'unregister'): atexit.unregister(_exit_function) atexit.register(_exit_function) else: atexit._exithandlers.remove((_exit_function, (), {})) atexit._exithandlers.append((_exit_function, (), {})) finally: logging._releaseLock() return _logger
[ "def", "get_logger", "(", ")", ":", "global", "_logger", "import", "logging", "logging", ".", "_acquireLock", "(", ")", "try", ":", "if", "not", "_logger", ":", "_logger", "=", "logging", ".", "getLogger", "(", "LOGGER_NAME", ")", "_logger", ".", "propagat...
https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py3.8/multiprocess/util.py#L60-L85
Qirky/FoxDot
76318f9630bede48ff3994146ed644affa27bfa4
FoxDot/lib/OSC3.py
python
OSCStreamingServer.stop
(self)
Stop the server thread and close the socket.
Stop the server thread and close the socket.
[ "Stop", "the", "server", "thread", "and", "close", "the", "socket", "." ]
def stop(self): """ Stop the server thread and close the socket. """ self.running = False self._server_thread.join() self.server_close()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "running", "=", "False", "self", ".", "_server_thread", ".", "join", "(", ")", "self", ".", "server_close", "(", ")" ]
https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/OSC3.py#L2672-L2676