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
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Mac/Modules/res/resscan.py
python
ResourcesScanner.makeblacklisttypes
(self)
return [ ]
[]
def makeblacklisttypes(self): return [ ]
[ "def", "makeblacklisttypes", "(", "self", ")", ":", "return", "[", "]" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Mac/Modules/res/resscan.py#L55-L57
aws-solutions/aws-instance-scheduler
d9208ddc4528536f20e14127ea0f49f8c52ea811
source/lambda/configuration/config_admin.py
python
ConfigAdmin.get_period
(self, name, exception_if_not_exists=True)
return {"period": ConfigAdmin._for_output(period)}
Gets a specific period :param name: name of the period :param exception_if_not_exists: set to True to raise an exception if it does not exist :return:
Gets a specific period :param name: name of the period :param exception_if_not_exists: set to True to raise an exception if it does not exist :return:
[ "Gets", "a", "specific", "period", ":", "param", "name", ":", "name", "of", "the", "period", ":", "param", "exception_if_not_exists", ":", "set", "to", "True", "to", "raise", "an", "exception", "if", "it", "does", "not", "exist", ":", "return", ":" ]
def get_period(self, name, exception_if_not_exists=True): """ Gets a specific period :param name: name of the period :param exception_if_not_exists: set to True to raise an exception if it does not exist :return: """ if name is None or len(name) == 0: raise ValueError(ERR_GET_EMPTY_PERIOD_NAME) period = self._get_period(name) if period is None: if exception_if_not_exists: raise ValueError(ERR_GET_PERIOD_NOT_FOUND.format(name)) return None return {"period": ConfigAdmin._for_output(period)}
[ "def", "get_period", "(", "self", ",", "name", ",", "exception_if_not_exists", "=", "True", ")", ":", "if", "name", "is", "None", "or", "len", "(", "name", ")", "==", "0", ":", "raise", "ValueError", "(", "ERR_GET_EMPTY_PERIOD_NAME", ")", "period", "=", ...
https://github.com/aws-solutions/aws-instance-scheduler/blob/d9208ddc4528536f20e14127ea0f49f8c52ea811/source/lambda/configuration/config_admin.py#L242-L256
AliLozano/django-messages-extends
d231b6535e95c31fe26ae33148615961ec07454b
messages_extends/storages.py
python
FallbackStorage._store
(self, messages, response, *args, **kwargs)
return messages
Stores the messages, returning any unstored messages after trying all backends. For each storage backend, any messages not stored are passed on to the next backend.
Stores the messages, returning any unstored messages after trying all backends.
[ "Stores", "the", "messages", "returning", "any", "unstored", "messages", "after", "trying", "all", "backends", "." ]
def _store(self, messages, response, *args, **kwargs): """ Stores the messages, returning any unstored messages after trying all backends. For each storage backend, any messages not stored are passed on to the next backend. """ for storage in self.storages: if messages: messages = storage._store(messages, response, remove_oldest=False) # Even if there are no more messages, continue iterating to ensure # storages which contained messages are flushed. elif storage in self._used_storages: storage._store([], response) self._used_storages.remove(storage) return messages
[ "def", "_store", "(", "self", ",", "messages", ",", "response", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "storage", "in", "self", ".", "storages", ":", "if", "messages", ":", "messages", "=", "storage", ".", "_store", "(", "message...
https://github.com/AliLozano/django-messages-extends/blob/d231b6535e95c31fe26ae33148615961ec07454b/messages_extends/storages.py#L65-L82
qgriffith-zz/OpenEats
9373ce65f838f19fead6f73c9491d2211e770769
list/models.py
python
GroceryList.__unicode__
(self)
return self.title
[]
def __unicode__(self): return self.title
[ "def", "__unicode__", "(", "self", ")", ":", "return", "self", ".", "title" ]
https://github.com/qgriffith-zz/OpenEats/blob/9373ce65f838f19fead6f73c9491d2211e770769/list/models.py#L17-L18
crossbario/autobahn-python
fa9f2da0c5005574e63456a3a04f00e405744014
autobahn/asyncio/component.py
python
Component._is_ssl_error
(self, e)
return isinstance(e, ssl.SSLError)
Internal helper.
Internal helper.
[ "Internal", "helper", "." ]
def _is_ssl_error(self, e): """ Internal helper. """ return isinstance(e, ssl.SSLError)
[ "def", "_is_ssl_error", "(", "self", ",", "e", ")", ":", "return", "isinstance", "(", "e", ",", "ssl", ".", "SSLError", ")" ]
https://github.com/crossbario/autobahn-python/blob/fa9f2da0c5005574e63456a3a04f00e405744014/autobahn/asyncio/component.py#L116-L120
web2py/web2py
095905c4e010a1426c729483d912e270a51b7ba8
gluon/html.py
python
ASSIGNJS
(**kargs)
return XML(s)
Example: ASSIGNJS(var1='1', var2='2') will return the following javascript variables assignations : var var1 = "1"; var var2 = "2"; Args: **kargs: Any keywords arguments and assigned values. Returns: Javascript vars assignations for the key/value passed.
Example: ASSIGNJS(var1='1', var2='2') will return the following javascript variables assignations :
[ "Example", ":", "ASSIGNJS", "(", "var1", "=", "1", "var2", "=", "2", ")", "will", "return", "the", "following", "javascript", "variables", "assignations", ":" ]
def ASSIGNJS(**kargs): """ Example: ASSIGNJS(var1='1', var2='2') will return the following javascript variables assignations : var var1 = "1"; var var2 = "2"; Args: **kargs: Any keywords arguments and assigned values. Returns: Javascript vars assignations for the key/value passed. """ from gluon.serializers import json s = "" for key, value in kargs.items(): s += 'var %s = %s;\n' % (key, json(value)) return XML(s)
[ "def", "ASSIGNJS", "(", "*", "*", "kargs", ")", ":", "from", "gluon", ".", "serializers", "import", "json", "s", "=", "\"\"", "for", "key", ",", "value", "in", "kargs", ".", "items", "(", ")", ":", "s", "+=", "'var %s = %s;\\n'", "%", "(", "key", "...
https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/gluon/html.py#L2860-L2879
mozman/ezdxf
59d0fc2ea63f5cf82293428f5931da7e9f9718e9
src/ezdxf/math/ellipse.py
python
ConstructionEllipse.vertices
(self, params: Iterable[float])
Yields vertices on ellipse for iterable `params` in WCS. Args: params: param values in the range from [0, 2π) in radians, param goes counter clockwise around the extrusion vector, major_axis = local x-axis = 0 rad.
Yields vertices on ellipse for iterable `params` in WCS.
[ "Yields", "vertices", "on", "ellipse", "for", "iterable", "params", "in", "WCS", "." ]
def vertices(self, params: Iterable[float]) -> Iterable[Vec3]: """Yields vertices on ellipse for iterable `params` in WCS. Args: params: param values in the range from [0, 2π) in radians, param goes counter clockwise around the extrusion vector, major_axis = local x-axis = 0 rad. """ center = self.center ratio = self.ratio x_axis = self.major_axis.normalize() y_axis = self.minor_axis.normalize() radius_x = self.major_axis.magnitude radius_y = radius_x * ratio for param in params: x = math.cos(param) * radius_x * x_axis y = math.sin(param) * radius_y * y_axis yield center + x + y
[ "def", "vertices", "(", "self", ",", "params", ":", "Iterable", "[", "float", "]", ")", "->", "Iterable", "[", "Vec3", "]", ":", "center", "=", "self", ".", "center", "ratio", "=", "self", ".", "ratio", "x_axis", "=", "self", ".", "major_axis", ".", ...
https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/src/ezdxf/math/ellipse.py#L329-L348
Dash-Industry-Forum/dash-live-source-simulator
23cb15c35656a731d9f6d78a30f2713eff2ec20d
dashlivesim/cc_inserter/mpdprocessor.py
python
Period.parse
(self)
Parse the node and its children.
Parse the node and its children.
[ "Parse", "the", "node", "and", "its", "children", "." ]
def parse(self): "Parse the node and its children." self.check_and_add_attributes(self.node, ('id', 'start')) for child in self.node.getchildren(): if self.compare_tag(child.tag, 'AdaptationSet'): adaptation_set = AdaptationSet(child) adaptation_set.parse() self.adaptation_sets.append(adaptation_set)
[ "def", "parse", "(", "self", ")", ":", "self", ".", "check_and_add_attributes", "(", "self", ".", "node", ",", "(", "'id'", ",", "'start'", ")", ")", "for", "child", "in", "self", ".", "node", ".", "getchildren", "(", ")", ":", "if", "self", ".", "...
https://github.com/Dash-Industry-Forum/dash-live-source-simulator/blob/23cb15c35656a731d9f6d78a30f2713eff2ec20d/dashlivesim/cc_inserter/mpdprocessor.py#L124-L131
AlvarBer/Persimmon
da08ed854dd0305d7e4684e97ee828acffd76b4d
persimmon/backend/backend.py
python
Backend._exec_graph_parallel
(self)
Execution algorithm, introduces all blocks on a set, when a block is executed it is taken out of the set until the set is empty.
Execution algorithm, introduces all blocks on a set, when a block is executed it is taken out of the set until the set is empty.
[ "Execution", "algorithm", "introduces", "all", "blocks", "on", "a", "set", "when", "a", "block", "is", "executed", "it", "is", "taken", "out", "of", "the", "set", "until", "the", "set", "is", "empty", "." ]
def _exec_graph_parallel(self): """ Execution algorithm, introduces all blocks on a set, when a block is executed it is taken out of the set until the set is empty. """ unseen = set(self.ir.blocks.keys()) # All blocks are unseen at start # All output pins along their respectives values seen = {} # type: Dict[int, Any] while unseen: unseen, seen = self._exec_block(unseen.pop(), unseen, seen) logger.info('Execution done') self.emit('graph_executed')
[ "def", "_exec_graph_parallel", "(", "self", ")", ":", "unseen", "=", "set", "(", "self", ".", "ir", ".", "blocks", ".", "keys", "(", ")", ")", "# All blocks are unseen at start", "# All output pins along their respectives values", "seen", "=", "{", "}", "# type: D...
https://github.com/AlvarBer/Persimmon/blob/da08ed854dd0305d7e4684e97ee828acffd76b4d/persimmon/backend/backend.py#L29-L38
val-iisc/deligan
68451c8923650b9239a87efb3b88f04b6969e54b
src/cifar/params.py
python
read_model_data
(model, filename)
Unpickles and loads parameters into a Lasagne model.
Unpickles and loads parameters into a Lasagne model.
[ "Unpickles", "and", "loads", "parameters", "into", "a", "Lasagne", "model", "." ]
def read_model_data(model, filename): """Unpickles and loads parameters into a Lasagne model.""" filename = os.path.join('./', '%s.%s' % (filename, PARAM_EXTENSION)) with open(filename, 'r') as f: data = pickle.load(f) nn.layers.set_all_param_values(model, data)
[ "def", "read_model_data", "(", "model", ",", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "'./'", ",", "'%s.%s'", "%", "(", "filename", ",", "PARAM_EXTENSION", ")", ")", "with", "open", "(", "filename", ",", "'r'", ")", ...
https://github.com/val-iisc/deligan/blob/68451c8923650b9239a87efb3b88f04b6969e54b/src/cifar/params.py#L18-L23
ninja-ide/ninja-ide
87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0
ninja_ide/core/plugin_manager.py
python
__get_all_plugin_descriptors
()
return [pf for pf in os.listdir(resources.PLUGINS) if pf.endswith(PLUGIN_EXTENSION)]
Returns all the .plugin files
Returns all the .plugin files
[ "Returns", "all", "the", ".", "plugin", "files" ]
def __get_all_plugin_descriptors(): ''' Returns all the .plugin files ''' global PLUGIN_EXTENSION return [pf for pf in os.listdir(resources.PLUGINS) if pf.endswith(PLUGIN_EXTENSION)]
[ "def", "__get_all_plugin_descriptors", "(", ")", ":", "global", "PLUGIN_EXTENSION", "return", "[", "pf", "for", "pf", "in", "os", ".", "listdir", "(", "resources", ".", "PLUGINS", ")", "if", "pf", ".", "endswith", "(", "PLUGIN_EXTENSION", ")", "]" ]
https://github.com/ninja-ide/ninja-ide/blob/87d91131bd19fdc3dcfd91eb97ad1e41c49c60c0/ninja_ide/core/plugin_manager.py#L421-L427
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/sankey/node/_hoverlabel.py
python
Hoverlabel.bordercolor
(self)
return self["bordercolor"]
Sets the border color of the hover labels for this trace. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A list or array of any of the above Returns ------- str|numpy.ndarray
Sets the border color of the hover labels for this trace. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A list or array of any of the above
[ "Sets", "the", "border", "color", "of", "the", "hover", "labels", "for", "this", "trace", ".", "The", "bordercolor", "property", "is", "a", "color", "and", "may", "be", "specified", "as", ":", "-", "A", "hex", "string", "(", "e", ".", "g", ".", "#ff0...
def bordercolor(self): """ Sets the border color of the hover labels for this trace. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen - A list or array of any of the above Returns ------- str|numpy.ndarray """ return self["bordercolor"]
[ "def", "bordercolor", "(", "self", ")", ":", "return", "self", "[", "\"bordercolor\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/sankey/node/_hoverlabel.py#L150-L201
getdock/whitelist
704bb41552f71d1a91ecf35e373d8f0b7434f144
app/user/verifications.py
python
verify_ids
(upload: IDUpload)
[]
def verify_ids(upload: IDUpload) -> str: user = upload.user state = user.transition(ID_PENDING_VERIFICATION) # Make sure that state didn't changed after we reached pending verification state if state != ID_PENDING_VERIFICATION: return state image1 = upload.upload1.to_base64() image2 = upload.upload2.to_base64() try: response = verify( user=user, kyc=False, image1=image1, image2=image2, doc_type=upload.doc_type, doc_state=upload.doc_state, doc_country=upload.doc_country, ) if response.user: apply_response(user, response, False) except IDMError as err: return user.transition(ID_FAILED, details=err.text)
[ "def", "verify_ids", "(", "upload", ":", "IDUpload", ")", "->", "str", ":", "user", "=", "upload", ".", "user", "state", "=", "user", ".", "transition", "(", "ID_PENDING_VERIFICATION", ")", "# Make sure that state didn't changed after we reached pending verification sta...
https://github.com/getdock/whitelist/blob/704bb41552f71d1a91ecf35e373d8f0b7434f144/app/user/verifications.py#L37-L61
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/linux_benchmarks/cloudsuite_web_search_benchmark.py
python
Run
(benchmark_spec)
return results
Run the Web Search benchmark. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects.
Run the Web Search benchmark.
[ "Run", "the", "Web", "Search", "benchmark", "." ]
def Run(benchmark_spec): """Run the Web Search benchmark. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects. """ clients = benchmark_spec.vm_groups['clients'][0] servers = benchmark_spec.vm_groups['servers'][0] benchmark_cmd = ('sudo docker run --rm --net host --name client ' 'cloudsuite/web-search:client %s %d %d %d %d ' % (servers.internal_ip, FLAGS.cloudsuite_web_search_scale, FLAGS.cloudsuite_web_search_ramp_up, FLAGS.cloudsuite_web_search_steady_state, FLAGS.cloudsuite_web_search_ramp_down)) stdout, _ = clients.RemoteCommand(benchmark_cmd, should_log=True) ops_per_sec = re.findall(r'\<metric unit="ops/sec"\>(\d+\.?\d*)', stdout) num_ops_per_sec = float(ops_per_sec[0]) p90 = re.findall(r'\<p90th\>(\d+\.?\d*)', stdout) num_p90 = float(p90[0]) p99 = re.findall(r'\<p99th\>(\d+\.?\d*)', stdout) num_p99 = float(p99[0]) results = [] results.append(sample.Sample('Operations per second', num_ops_per_sec, 'ops/s')) results.append(sample.Sample('90th percentile latency', num_p90, 's')) results.append(sample.Sample('99th percentile latency', num_p99, 's')) return results
[ "def", "Run", "(", "benchmark_spec", ")", ":", "clients", "=", "benchmark_spec", ".", "vm_groups", "[", "'clients'", "]", "[", "0", "]", "servers", "=", "benchmark_spec", ".", "vm_groups", "[", "'servers'", "]", "[", "0", "]", "benchmark_cmd", "=", "(", ...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/linux_benchmarks/cloudsuite_web_search_benchmark.py#L117-L151
serge-sans-paille/pythran
f9f73aa5a965adc4ebcb91a439784dbe9ef911fa
pythran/analyses/ast_matcher.py
python
Placeholder.__init__
(self, identifier, type=None)
Placehorder are identified using an identifier.
Placehorder are identified using an identifier.
[ "Placehorder", "are", "identified", "using", "an", "identifier", "." ]
def __init__(self, identifier, type=None): """ Placehorder are identified using an identifier. """ self.id = identifier self.type = type super(Placeholder, self).__init__()
[ "def", "__init__", "(", "self", ",", "identifier", ",", "type", "=", "None", ")", ":", "self", ".", "id", "=", "identifier", "self", ".", "type", "=", "type", "super", "(", "Placeholder", ",", "self", ")", ".", "__init__", "(", ")" ]
https://github.com/serge-sans-paille/pythran/blob/f9f73aa5a965adc4ebcb91a439784dbe9ef911fa/pythran/analyses/ast_matcher.py#L19-L23
Abjad/abjad
d0646dfbe83db3dc5ab268f76a0950712b87b7fd
abjad/string.py
python
String.to_accent_free_snake_case
(self)
return type(self)(string_)
Changes string to accent-free snake case. .. container:: example >>> abjad.String('Déja vu').to_accent_free_snake_case() 'deja_vu'
Changes string to accent-free snake case.
[ "Changes", "string", "to", "accent", "-", "free", "snake", "case", "." ]
def to_accent_free_snake_case(self) -> "String": """ Changes string to accent-free snake case. .. container:: example >>> abjad.String('Déja vu').to_accent_free_snake_case() 'deja_vu' """ string = self.strip_diacritics() string_ = string.replace(" ", "_") string_ = string_.replace("'", "_") string_ = string_.lower() return type(self)(string_)
[ "def", "to_accent_free_snake_case", "(", "self", ")", "->", "\"String\"", ":", "string", "=", "self", ".", "strip_diacritics", "(", ")", "string_", "=", "string", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", "string_", "=", "string_", ".", "replace", "...
https://github.com/Abjad/abjad/blob/d0646dfbe83db3dc5ab268f76a0950712b87b7fd/abjad/string.py#L1331-L1345
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/algos/evaluator.py
python
Evaluator.__call__
(self, verbose=False)
Evaluate the trajectories performed by the policy. Args: verbose (bool): If true, print information on the standard output.
Evaluate the trajectories performed by the policy.
[ "Evaluate", "the", "trajectories", "performed", "by", "the", "policy", "." ]
def __call__(self, verbose=False): """ Evaluate the trajectories performed by the policy. Args: verbose (bool): If true, print information on the standard output. """ self.evaluate(verbose=verbose)
[ "def", "__call__", "(", "self", ",", "verbose", "=", "False", ")", ":", "self", ".", "evaluate", "(", "verbose", "=", "verbose", ")" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/algos/evaluator.py#L134-L141
hacs/integration
8ad321da6de4bf5ffa06bdaff1802e25edae5705
custom_components/hacs/tasks/load_hacs_repository.py
python
async_setup_task
(hacs: HacsBase, hass: HomeAssistant)
return Task(hacs=hacs, hass=hass)
Set up this task.
Set up this task.
[ "Set", "up", "this", "task", "." ]
async def async_setup_task(hacs: HacsBase, hass: HomeAssistant) -> Task: """Set up this task.""" return Task(hacs=hacs, hass=hass)
[ "async", "def", "async_setup_task", "(", "hacs", ":", "HacsBase", ",", "hass", ":", "HomeAssistant", ")", "->", "Task", ":", "return", "Task", "(", "hacs", "=", "hacs", ",", "hass", "=", "hass", ")" ]
https://github.com/hacs/integration/blob/8ad321da6de4bf5ffa06bdaff1802e25edae5705/custom_components/hacs/tasks/load_hacs_repository.py#L12-L14
respeaker/respeaker_python_library
905a5334ccdc2d474ad973caf6a23d05c65bbb25
respeaker/gpio.py
python
Gpio._sysfs_gpio_value_path
(self)
return SYSFS_GPIO_VALUE_PATH % self.number
Get the file that represent the value of this pin. @rtype: str @return: the path to sysfs value file
Get the file that represent the value of this pin.
[ "Get", "the", "file", "that", "represent", "the", "value", "of", "this", "pin", "." ]
def _sysfs_gpio_value_path(self): """ Get the file that represent the value of this pin. @rtype: str @return: the path to sysfs value file """ return SYSFS_GPIO_VALUE_PATH % self.number
[ "def", "_sysfs_gpio_value_path", "(", "self", ")", ":", "return", "SYSFS_GPIO_VALUE_PATH", "%", "self", ".", "number" ]
https://github.com/respeaker/respeaker_python_library/blob/905a5334ccdc2d474ad973caf6a23d05c65bbb25/respeaker/gpio.py#L227-L234
miyosuda/unreal
31d4886149412fa248f6efa490ab65bd2f425cde
train/experience.py
python
Experience.sample_rp_sequence
(self)
return sampled_frames
Sample 4 successive frames for reward prediction.
Sample 4 successive frames for reward prediction.
[ "Sample", "4", "successive", "frames", "for", "reward", "prediction", "." ]
def sample_rp_sequence(self): """ Sample 4 successive frames for reward prediction. """ if np.random.randint(2) == 0: from_zero = True else: from_zero = False if len(self._zero_reward_indices) == 0: # zero rewards container was empty from_zero = False elif len(self._non_zero_reward_indices) == 0: # non zero rewards container was empty from_zero = True if from_zero: index = np.random.randint(len(self._zero_reward_indices)) end_frame_index = self._zero_reward_indices[index] else: index = np.random.randint(len(self._non_zero_reward_indices)) end_frame_index = self._non_zero_reward_indices[index] start_frame_index = end_frame_index-3 raw_start_frame_index = start_frame_index - self._top_frame_index sampled_frames = [] for i in range(4): frame = self._frames[raw_start_frame_index+i] sampled_frames.append(frame) return sampled_frames
[ "def", "sample_rp_sequence", "(", "self", ")", ":", "if", "np", ".", "random", ".", "randint", "(", "2", ")", "==", "0", ":", "from_zero", "=", "True", "else", ":", "from_zero", "=", "False", "if", "len", "(", "self", ".", "_zero_reward_indices", ")", ...
https://github.com/miyosuda/unreal/blob/31d4886149412fa248f6efa490ab65bd2f425cde/train/experience.py#L113-L145
alephsecurity/abootool
4117b82d07e6b3a80eeab560d2140ae2dcfe2463
log.py
python
E
(msg, *kargs, **kwargs)
[]
def E(msg, *kargs, **kwargs): l.error(msg, *kargs, **kwargs)
[ "def", "E", "(", "msg", ",", "*", "kargs", ",", "*", "*", "kwargs", ")", ":", "l", ".", "error", "(", "msg", ",", "*", "kargs", ",", "*", "*", "kwargs", ")" ]
https://github.com/alephsecurity/abootool/blob/4117b82d07e6b3a80eeab560d2140ae2dcfe2463/log.py#L59-L60
phil-bergmann/tracking_wo_bnw
72ee403de01c472f6eb5cde60b56b86aa6a617c8
src/tracktor/datasets/mot_wrapper.py
python
MOT17PrivateWrapper.__init__
(self, split, dataloader, data_dir)
Initliazes all subset of the dataset. Keyword arguments: split -- the split of the dataset to use dataloader -- args for the MOT_Sequence dataloader
Initliazes all subset of the dataset.
[ "Initliazes", "all", "subset", "of", "the", "dataset", "." ]
def __init__(self, split, dataloader, data_dir): """Initliazes all subset of the dataset. Keyword arguments: split -- the split of the dataset to use dataloader -- args for the MOT_Sequence dataloader """ train_sequences = ['MOT17-02', 'MOT17-04', 'MOT17-05', 'MOT17-09', 'MOT17-10', 'MOT17-11', 'MOT17-13'] test_sequences = ['MOT17-01', 'MOT17-03', 'MOT17-06', 'MOT17-07', 'MOT17-08', 'MOT17-12', 'MOT17-14'] if "train" == split: sequences = train_sequences elif "test" == split: sequences = test_sequences elif "all" == split: sequences = train_sequences + test_sequences elif f"MOT17-{split}" in train_sequences + test_sequences: sequences = [f"MOT17-{split}"] else: raise NotImplementedError("MOT17 split not available.") self._data = [] for s in sequences: self._data.append(MOTSequence(s, data_dir, **dataloader))
[ "def", "__init__", "(", "self", ",", "split", ",", "dataloader", ",", "data_dir", ")", ":", "train_sequences", "=", "[", "'MOT17-02'", ",", "'MOT17-04'", ",", "'MOT17-05'", ",", "'MOT17-09'", ",", "'MOT17-10'", ",", "'MOT17-11'", ",", "'MOT17-13'", "]", "tes...
https://github.com/phil-bergmann/tracking_wo_bnw/blob/72ee403de01c472f6eb5cde60b56b86aa6a617c8/src/tracktor/datasets/mot_wrapper.py#L148-L171
mongodb/pymodm
be1c7b079df4954ef7e79e46f1b4a9ac9510766c
pymodm/queryset.py
python
QuerySet.bulk_create
(self, object_or_objects, retrieve=False, full_clean=False)
return ids
Save Model instances in bulk. :parameters: - `object_or_objects`: A list of MongoModel instances or a single instance. - `retrieve`: Whether to return the saved MongoModel instances. If ``False`` (the default), only the ids will be returned. - `full_clean`: Whether to validate each object by calling the :meth:`~pymodm.MongoModel.full_clean` method before saving. This isn't done by default. :returns: A list of ids for the documents saved, or of the :class:`~pymodm.MongoModel` instances themselves if `retrieve` is ``True``. example:: >>> vacation_ids = Vacation.objects.bulk_create([ ... Vacation(destination='TOKYO', travel_method='PLANE'), ... Vacation(destination='ALGIERS', travel_method='PLANE')]) >>> print(vacation_ids) [ObjectId('578926716e32ab1d6a8dc718'), ObjectId('578926716e32ab1d6a8dc719')]
Save Model instances in bulk.
[ "Save", "Model", "instances", "in", "bulk", "." ]
def bulk_create(self, object_or_objects, retrieve=False, full_clean=False): """Save Model instances in bulk. :parameters: - `object_or_objects`: A list of MongoModel instances or a single instance. - `retrieve`: Whether to return the saved MongoModel instances. If ``False`` (the default), only the ids will be returned. - `full_clean`: Whether to validate each object by calling the :meth:`~pymodm.MongoModel.full_clean` method before saving. This isn't done by default. :returns: A list of ids for the documents saved, or of the :class:`~pymodm.MongoModel` instances themselves if `retrieve` is ``True``. example:: >>> vacation_ids = Vacation.objects.bulk_create([ ... Vacation(destination='TOKYO', travel_method='PLANE'), ... Vacation(destination='ALGIERS', travel_method='PLANE')]) >>> print(vacation_ids) [ObjectId('578926716e32ab1d6a8dc718'), ObjectId('578926716e32ab1d6a8dc719')] """ retrieve = validate_boolean('retrieve', retrieve) full_clean = validate_boolean('full_clean', full_clean) TopLevelMongoModel = _import('pymodm.base.models.TopLevelMongoModel') if isinstance(object_or_objects, TopLevelMongoModel): object_or_objects = [object_or_objects] object_or_objects = validate_list_or_tuple( 'object_or_objects', object_or_objects) if full_clean: for object in object_or_objects: object.full_clean() docs = (obj.to_son() for obj in object_or_objects) ids = self._collection.insert_many(docs).inserted_ids if retrieve: return list(self.raw({'_id': {'$in': ids}})) return ids
[ "def", "bulk_create", "(", "self", ",", "object_or_objects", ",", "retrieve", "=", "False", ",", "full_clean", "=", "False", ")", ":", "retrieve", "=", "validate_boolean", "(", "'retrieve'", ",", "retrieve", ")", "full_clean", "=", "validate_boolean", "(", "'f...
https://github.com/mongodb/pymodm/blob/be1c7b079df4954ef7e79e46f1b4a9ac9510766c/pymodm/queryset.py#L393-L434
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/kombu-4.3.0/kombu/pools.py
python
reset
(*args, **kwargs)
Reset all pools by closing open resources.
Reset all pools by closing open resources.
[ "Reset", "all", "pools", "by", "closing", "open", "resources", "." ]
def reset(*args, **kwargs): """Reset all pools by closing open resources.""" for pool in _all_pools(): try: pool.force_close_all() except Exception: pass for group in _groups: group.clear()
[ "def", "reset", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "pool", "in", "_all_pools", "(", ")", ":", "try", ":", "pool", ".", "force_close_all", "(", ")", "except", "Exception", ":", "pass", "for", "group", "in", "_groups", ":", "...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/kombu-4.3.0/kombu/pools.py#L141-L149
prody/ProDy
b24bbf58aa8fffe463c8548ae50e3955910e5b7f
prody/atomic/atom.py
python
Atom.setFlag
(self, label, value)
Update flag associated with *label*. :raise AttributeError: when *label* is not in use or read-only
Update flag associated with *label*.
[ "Update", "flag", "associated", "with", "*", "label", "*", "." ]
def setFlag(self, label, value): """Update flag associated with *label*. :raise AttributeError: when *label* is not in use or read-only""" if label in PLANTERS: raise AttributeError('flag {0} cannot be changed by user' .format(repr(label))) flags = self._ag._getFlags(label) if flags is None: raise AttributeError('flags with label {0} must be set for ' 'AtomGroup first'.format(repr(label))) flags[self._index] = value
[ "def", "setFlag", "(", "self", ",", "label", ",", "value", ")", ":", "if", "label", "in", "PLANTERS", ":", "raise", "AttributeError", "(", "'flag {0} cannot be changed by user'", ".", "format", "(", "repr", "(", "label", ")", ")", ")", "flags", "=", "self"...
https://github.com/prody/ProDy/blob/b24bbf58aa8fffe463c8548ae50e3955910e5b7f/prody/atomic/atom.py#L180-L192
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
common/lib/sandbox-packages/verifiers/draganddrop.py
python
flat_user_answer
(user_answer)
return result
Convert nested `user_answer` to flat format. {'up': {'first': {'p': 'p_l'}}} to {'up': 'p_l[p][first]'}
Convert nested `user_answer` to flat format.
[ "Convert", "nested", "user_answer", "to", "flat", "format", "." ]
def flat_user_answer(user_answer): """ Convert nested `user_answer` to flat format. {'up': {'first': {'p': 'p_l'}}} to {'up': 'p_l[p][first]'} """ def parse_user_answer(answer): key = list(answer.keys())[0] value = list(answer.values())[0] if isinstance(value, dict): # Make complex value: # Example: # Create like 'p_l[p][first]' from {'first': {'p': 'p_l'} complex_value_list = [] v_value = value while isinstance(v_value, dict): v_key = list(v_value.keys())[0] v_value = list(v_value.values())[0] complex_value_list.append(v_key) complex_value = '{0}'.format(v_value) for i in reversed(complex_value_list): complex_value = '{0}[{1}]'.format(complex_value, i) res = {key: complex_value} return res else: return answer result = [] for answer in user_answer: parse_answer = parse_user_answer(answer) result.append(parse_answer) return result
[ "def", "flat_user_answer", "(", "user_answer", ")", ":", "def", "parse_user_answer", "(", "answer", ")", ":", "key", "=", "list", "(", "answer", ".", "keys", "(", ")", ")", "[", "0", "]", "value", "=", "list", "(", "answer", ".", "values", "(", ")", ...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/lib/sandbox-packages/verifiers/draganddrop.py#L33-L73
isnowfy/pydown
71ecc891868cd2a34b7e5fe662c99474f2d0fd7f
pygments/formatters/terminal256.py
python
EscapeSequence.__init__
(self, fg=None, bg=None, bold=False, underline=False)
[]
def __init__(self, fg=None, bg=None, bold=False, underline=False): self.fg = fg self.bg = bg self.bold = bold self.underline = underline
[ "def", "__init__", "(", "self", ",", "fg", "=", "None", ",", "bg", "=", "None", ",", "bold", "=", "False", ",", "underline", "=", "False", ")", ":", "self", ".", "fg", "=", "fg", "self", ".", "bg", "=", "bg", "self", ".", "bold", "=", "bold", ...
https://github.com/isnowfy/pydown/blob/71ecc891868cd2a34b7e5fe662c99474f2d0fd7f/pygments/formatters/terminal256.py#L36-L40
jquast/x84
11f445bb82e6e895d7cce57d4c6d8572d1981162
x84/sftp.py
python
X84SFTPServer._dummy_dir_stat
(self)
return attr
Stat on our dummy __flagged__ directory.
Stat on our dummy __flagged__ directory.
[ "Stat", "on", "our", "dummy", "__flagged__", "directory", "." ]
def _dummy_dir_stat(self): """ Stat on our dummy __flagged__ directory. """ self.log.debug('_dummy_dir_stat') attr = SFTPAttributes.from_stat( os.stat(self.root)) attr.filename = flagged_dirname return attr
[ "def", "_dummy_dir_stat", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'_dummy_dir_stat'", ")", "attr", "=", "SFTPAttributes", ".", "from_stat", "(", "os", ".", "stat", "(", "self", ".", "root", ")", ")", "attr", ".", "filename", "=",...
https://github.com/jquast/x84/blob/11f445bb82e6e895d7cce57d4c6d8572d1981162/x84/sftp.py#L90-L96
awslabs/aws-servicebroker
c301912e7df3a2f09a9c34d3ae7ffe67c55aa3a0
sample-apps/rds/sample-app/src/pymysql/cursors.py
python
SSCursor.fetchall
(self)
return list(self.fetchall_unbuffered())
Fetch all, as per MySQLdb. Pretty useless for large queries, as it is buffered. See fetchall_unbuffered(), if you want an unbuffered generator version of this method.
Fetch all, as per MySQLdb. Pretty useless for large queries, as it is buffered. See fetchall_unbuffered(), if you want an unbuffered generator version of this method.
[ "Fetch", "all", "as", "per", "MySQLdb", ".", "Pretty", "useless", "for", "large", "queries", "as", "it", "is", "buffered", ".", "See", "fetchall_unbuffered", "()", "if", "you", "want", "an", "unbuffered", "generator", "version", "of", "this", "method", "." ]
def fetchall(self): """ Fetch all, as per MySQLdb. Pretty useless for large queries, as it is buffered. See fetchall_unbuffered(), if you want an unbuffered generator version of this method. """ return list(self.fetchall_unbuffered())
[ "def", "fetchall", "(", "self", ")", ":", "return", "list", "(", "self", ".", "fetchall_unbuffered", "(", ")", ")" ]
https://github.com/awslabs/aws-servicebroker/blob/c301912e7df3a2f09a9c34d3ae7ffe67c55aa3a0/sample-apps/rds/sample-app/src/pymysql/cursors.py#L459-L465
mwaskom/seaborn
77e3b6b03763d24cc99a8134ee9a6f43b32b8e7b
seaborn/_decorators.py
python
_deprecate_positional_args
(f)
return inner_f
Decorator for methods that issues warnings for positional arguments. Using the keyword-only argument syntax in pep 3102, arguments after the * will issue a warning when passed as a positional argument. Parameters ---------- f : function function to check arguments on
Decorator for methods that issues warnings for positional arguments.
[ "Decorator", "for", "methods", "that", "issues", "warnings", "for", "positional", "arguments", "." ]
def _deprecate_positional_args(f): """Decorator for methods that issues warnings for positional arguments. Using the keyword-only argument syntax in pep 3102, arguments after the * will issue a warning when passed as a positional argument. Parameters ---------- f : function function to check arguments on """ sig = signature(f) kwonly_args = [] all_args = [] for name, param in sig.parameters.items(): if param.kind == Parameter.POSITIONAL_OR_KEYWORD: all_args.append(name) elif param.kind == Parameter.KEYWORD_ONLY: kwonly_args.append(name) @wraps(f) def inner_f(*args, **kwargs): extra_args = len(args) - len(all_args) if extra_args > 0: plural = "s" if extra_args > 1 else "" article = "" if plural else "a " warnings.warn( "Pass the following variable{} as {}keyword arg{}: {}. " "From version 0.12, the only valid positional argument " "will be `data`, and passing other arguments without an " "explicit keyword will result in an error or misinterpretation." .format(plural, article, plural, ", ".join(kwonly_args[:extra_args])), FutureWarning ) kwargs.update({k: arg for k, arg in zip(sig.parameters, args)}) return f(**kwargs) return inner_f
[ "def", "_deprecate_positional_args", "(", "f", ")", ":", "sig", "=", "signature", "(", "f", ")", "kwonly_args", "=", "[", "]", "all_args", "=", "[", "]", "for", "name", ",", "param", "in", "sig", ".", "parameters", ".", "items", "(", ")", ":", "if", ...
https://github.com/mwaskom/seaborn/blob/77e3b6b03763d24cc99a8134ee9a6f43b32b8e7b/seaborn/_decorators.py#L8-L47
rcorcs/NatI
fdf014f4292afdc95250add7b6658468043228e1
en/parser/nltk_lite/contrib/paradigm.py
python
Domain.getHorizontalHTML
(self,p_parentSpan=1)
return "<tr>" + ret_string*p_parentSpan + "</tr>"
Return a horizontal html table
Return a horizontal html table
[ "Return", "a", "horizontal", "html", "table" ]
def getHorizontalHTML(self,p_parentSpan=1): """ Return a horizontal html table """ ret_string = "" for item in self.getList(): ret_string += "<td>" + item + "</td>" return "<tr>" + ret_string*p_parentSpan + "</tr>"
[ "def", "getHorizontalHTML", "(", "self", ",", "p_parentSpan", "=", "1", ")", ":", "ret_string", "=", "\"\"", "for", "item", "in", "self", ".", "getList", "(", ")", ":", "ret_string", "+=", "\"<td>\"", "+", "item", "+", "\"</td>\"", "return", "\"<tr>\"", ...
https://github.com/rcorcs/NatI/blob/fdf014f4292afdc95250add7b6658468043228e1/en/parser/nltk_lite/contrib/paradigm.py#L383-L390
vita-epfl/monoloco
f5e82c48e8ee5af352f2c9b1690050f4e02fc1b6
monoloco/utils/iou.py
python
reorder_matches
(matches, boxes, mode='left_rigth')
return [matches[matches_left.index(idx_boxes)] for idx_boxes in ordered_boxes if idx_boxes in matches_left]
Reorder a list of (idx, idx_gt) matches based on position of the detections in the image ordered_boxes = (5, 6, 7, 0, 1, 4, 2, 4) matches = [(0, x), (2,x), (4,x), (3,x), (5,x)] Output --> [(5, x), (0, x), (3, x), (2, x), (5, x)]
Reorder a list of (idx, idx_gt) matches based on position of the detections in the image ordered_boxes = (5, 6, 7, 0, 1, 4, 2, 4) matches = [(0, x), (2,x), (4,x), (3,x), (5,x)] Output --> [(5, x), (0, x), (3, x), (2, x), (5, x)]
[ "Reorder", "a", "list", "of", "(", "idx", "idx_gt", ")", "matches", "based", "on", "position", "of", "the", "detections", "in", "the", "image", "ordered_boxes", "=", "(", "5", "6", "7", "0", "1", "4", "2", "4", ")", "matches", "=", "[", "(", "0", ...
def reorder_matches(matches, boxes, mode='left_rigth'): """ Reorder a list of (idx, idx_gt) matches based on position of the detections in the image ordered_boxes = (5, 6, 7, 0, 1, 4, 2, 4) matches = [(0, x), (2,x), (4,x), (3,x), (5,x)] Output --> [(5, x), (0, x), (3, x), (2, x), (5, x)] """ assert mode == 'left_right' # Order the boxes based on the left-right position in the image and ordered_boxes = np.argsort([box[0] for box in boxes]) # indices of boxes ordered from left to right matches_left = [int(idx) for (idx, _) in matches] return [matches[matches_left.index(idx_boxes)] for idx_boxes in ordered_boxes if idx_boxes in matches_left]
[ "def", "reorder_matches", "(", "matches", ",", "boxes", ",", "mode", "=", "'left_rigth'", ")", ":", "assert", "mode", "==", "'left_right'", "# Order the boxes based on the left-right position in the image and", "ordered_boxes", "=", "np", ".", "argsort", "(", "[", "bo...
https://github.com/vita-epfl/monoloco/blob/f5e82c48e8ee5af352f2c9b1690050f4e02fc1b6/monoloco/utils/iou.py#L86-L100
bsolomon1124/pyfinance
c6fd88ba4fb5c9f083ebc3ff60960a1b4df76c55
pyfinance/returns.py
python
TSeries.rsq_adj
(self, benchmark, **kwargs)
return self.CAPM(benchmark, **kwargs).rsq_adj
Adjusted R-squared. Formula: 1. - ((1. - `self._rsq`) * (n - 1.) / (n - k - 1.)) Parameters ---------- benchmark : {pd.Series, TSeries, pd.DataFrame, np.ndarray} The benchmark securitie(s) to which `self` is compared. **kwargs Passed to pyfinance.ols.OLS(). Returns ------- float
Adjusted R-squared.
[ "Adjusted", "R", "-", "squared", "." ]
def rsq_adj(self, benchmark, **kwargs): """Adjusted R-squared. Formula: 1. - ((1. - `self._rsq`) * (n - 1.) / (n - k - 1.)) Parameters ---------- benchmark : {pd.Series, TSeries, pd.DataFrame, np.ndarray} The benchmark securitie(s) to which `self` is compared. **kwargs Passed to pyfinance.ols.OLS(). Returns ------- float """ return self.CAPM(benchmark, **kwargs).rsq_adj
[ "def", "rsq_adj", "(", "self", ",", "benchmark", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "CAPM", "(", "benchmark", ",", "*", "*", "kwargs", ")", ".", "rsq_adj" ]
https://github.com/bsolomon1124/pyfinance/blob/c6fd88ba4fb5c9f083ebc3ff60960a1b4df76c55/pyfinance/returns.py#L829-L845
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/dyck_word.py
python
DyckWord.number_of_double_rises
(self)
return len(self.positions_of_double_rises())
r""" Return a the number of positions in ``self`` where there are two consecutive `1`'s. EXAMPLES:: sage: DyckWord([1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0]).number_of_double_rises() 2 sage: DyckWord([1, 1, 0, 0]).number_of_double_rises() 1 sage: DyckWord([1, 0, 1, 0]).number_of_double_rises() 0
r""" Return a the number of positions in ``self`` where there are two consecutive `1`'s.
[ "r", "Return", "a", "the", "number", "of", "positions", "in", "self", "where", "there", "are", "two", "consecutive", "1", "s", "." ]
def number_of_double_rises(self) -> int: r""" Return a the number of positions in ``self`` where there are two consecutive `1`'s. EXAMPLES:: sage: DyckWord([1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0]).number_of_double_rises() 2 sage: DyckWord([1, 1, 0, 0]).number_of_double_rises() 1 sage: DyckWord([1, 0, 1, 0]).number_of_double_rises() 0 """ return len(self.positions_of_double_rises())
[ "def", "number_of_double_rises", "(", "self", ")", "->", "int", ":", "return", "len", "(", "self", ".", "positions_of_double_rises", "(", ")", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/dyck_word.py#L1388-L1402
marinho/geraldo
868ebdce67176d9b6205cddc92476f642c783fff
site/newsite/django_1_0/django/utils/_decimal.py
python
Decimal.sqrt
(self, context=None)
return ans._fix(context)
Return the square root of self. Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn)) Should quadratically approach the right answer.
Return the square root of self.
[ "Return", "the", "square", "root", "of", "self", "." ]
def sqrt(self, context=None): """Return the square root of self. Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn)) Should quadratically approach the right answer. """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans if self._isinfinity() and self._sign == 0: return Decimal(self) if not self: #exponent = self._exp / 2, using round_down. #if self._exp < 0: # exp = (self._exp+1) // 2 #else: exp = (self._exp) // 2 if self._sign == 1: #sqrt(-0) = -0 return Decimal( (1, (0,), exp)) else: return Decimal( (0, (0,), exp)) if context is None: context = getcontext() if self._sign == 1: return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') tmp = Decimal(self) expadd = tmp._exp // 2 if tmp._exp & 1: tmp._int += (0,) tmp._exp = 0 else: tmp._exp = 0 context = context._shallow_copy() flags = context._ignore_all_flags() firstprec = context.prec context.prec = 3 if tmp.adjusted() & 1 == 0: ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) ) ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)), context=context), context=context) ans._exp -= 1 + tmp.adjusted() // 2 else: ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) ) ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)), context=context), context=context) ans._exp -= 1 + tmp.adjusted() // 2 #ans is now a linear approximation. Emax, Emin = context.Emax, context.Emin context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin half = Decimal('0.5') maxp = firstprec + 2 rounding = context._set_rounding(ROUND_HALF_EVEN) while 1: context.prec = min(2*context.prec - 2, maxp) ans = half.__mul__(ans.__add__(tmp.__div__(ans, context=context), context=context), context=context) if context.prec == maxp: break #round to the answer's precision-- the only error can be 1 ulp. context.prec = firstprec prevexp = ans.adjusted() ans = ans._round(context=context) #Now, check if the other last digits are better. context.prec = firstprec + 1 # In case we rounded up another digit and we should actually go lower. if prevexp != ans.adjusted(): ans._int += (0,) ans._exp -= 1 lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context) context._set_rounding(ROUND_UP) if lower.__mul__(lower, context=context) > (tmp): ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context) else: upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context) context._set_rounding(ROUND_DOWN) if upper.__mul__(upper, context=context) < tmp: ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context) ans._exp += expadd context.prec = firstprec context.rounding = rounding ans = ans._fix(context) rounding = context._set_rounding_decision(NEVER_ROUND) if not ans.__mul__(ans, context=context) == self: # Only rounded/inexact if here. context._regard_flags(flags) context._raise_error(Rounded) context._raise_error(Inexact) else: #Exact answer, so let's set the exponent right. #if self._exp < 0: # exp = (self._exp +1)// 2 #else: exp = self._exp // 2 context.prec += ans._exp - exp ans = ans._rescale(exp, context=context) context.prec = firstprec context._regard_flags(flags) context.Emax, context.Emin = Emax, Emin return ans._fix(context)
[ "def", "sqrt", "(", "self", ",", "context", "=", "None", ")", ":", "if", "self", ".", "_is_special", ":", "ans", "=", "self", ".", "_check_nans", "(", "context", "=", "context", ")", "if", "ans", ":", "return", "ans", "if", "self", ".", "_isinfinity"...
https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/site/newsite/django_1_0/django/utils/_decimal.py#L1908-L2028
wit-ai/pywit
365b33ac25d503285442e37201dff7bc10dd6ff0
wit/wit.py
python
Wit.create_app_version
(self, app_id, tag_name, headers=None, verbose=None)
return resp
Create a new version of your app. :param app_id: ID of existing app :param tag_name: name of tag
Create a new version of your app. :param app_id: ID of existing app :param tag_name: name of tag
[ "Create", "a", "new", "version", "of", "your", "app", ".", ":", "param", "app_id", ":", "ID", "of", "existing", "app", ":", "param", "tag_name", ":", "name", "of", "tag" ]
def create_app_version(self, app_id, tag_name, headers=None, verbose=None): """ Create a new version of your app. :param app_id: ID of existing app :param tag_name: name of tag """ params = {} headers = headers or {} data = {"tag":tag_name} endpoint = '/apps/' + app_id + "/tags/" if verbose: params['verbose'] = verbose resp = req(self.logger, self.access_token, 'POST', endpoint, params, json=data , headers=headers) return resp
[ "def", "create_app_version", "(", "self", ",", "app_id", ",", "tag_name", ",", "headers", "=", "None", ",", "verbose", "=", "None", ")", ":", "params", "=", "{", "}", "headers", "=", "headers", "or", "{", "}", "data", "=", "{", "\"tag\"", ":", "tag_n...
https://github.com/wit-ai/pywit/blob/365b33ac25d503285442e37201dff7bc10dd6ff0/wit/wit.py#L417-L431
zynga/jasy
8a2ec2c2ca3f6c0f73cba4306e581c89b30f1b18
jasy/js/optimize/BlockReducer.py
python
cleanParens
(node)
Automatically tries to remove superfluous parens which are sometimes added for more clearance and readability but which are not required for parsing and just produce overhead.
Automatically tries to remove superfluous parens which are sometimes added for more clearance and readability but which are not required for parsing and just produce overhead.
[ "Automatically", "tries", "to", "remove", "superfluous", "parens", "which", "are", "sometimes", "added", "for", "more", "clearance", "and", "readability", "but", "which", "are", "not", "required", "for", "parsing", "and", "just", "produce", "overhead", "." ]
def cleanParens(node): """ Automatically tries to remove superfluous parens which are sometimes added for more clearance and readability but which are not required for parsing and just produce overhead. """ parent = node.parent if node.type == "function": # Ignore for direct execution functions. This is required # for parsing e.g. (function(){})(); which does not work # without parens around the function instance other than # priorities might suggest. It only works this way when being # part of assignment/declaration. if parent.type == "call" and parent.parent.type in ("declaration", "assign"): node.parenthesized = False # Need to make sure to not modify in cases where we use a "dot" operator e.g. # var x = (function(){ return 1; }).hide(); elif node.type == "assign" and parent.type == "hook": node.parenthesized = node.rel == "condition" elif getattr(node, "rel", None) == "condition": # inside a condition e.g. while(condition) or for(;condition;) we do not need # parens aroudn an expression node.parenthesized = False elif node.type in jasy.js.parse.Lang.expressions and parent.type == "return": # Returns never need parens around the expression node.parenthesized = False elif node.type in jasy.js.parse.Lang.expressions and parent.type == "list" and parent.parent.type == "call": # Parameters don't need to be wrapped in parans node.parenthesized = False elif node.type in ("new", "string", "number", "boolean") and parent.type == "dot": # Constructs like (new foo.bar.Object).doSomething() # "new" is defined with higher priority than "dot" but in # this case it does not work without parens. Interestingly # the same works without issues when having "new_with_args" # instead like: new foo.bar.Object("param").doSomething() pass elif node.type == "unary_plus" or node.type == "unary_minus": # Prevent unary operators from getting joined with parent # x+(+x) => x++x => FAIL pass elif node.type in jasy.js.parse.Lang.expressions and parent.type in jasy.js.parse.Lang.expressions: prio = jasy.js.parse.Lang.expressionOrder[node.type] parentPrio = jasy.js.parse.Lang.expressionOrder[node.parent.type] # Only higher priorities are optimized. Others are just to complex e.g. # "hello" + (3+4) + "world" is not allowed to be translated to # "hello" + 3+4 + "world" if prio > parentPrio: node.parenthesized = False elif prio == parentPrio: if node.type == "hook": node.parenthesized = False
[ "def", "cleanParens", "(", "node", ")", ":", "parent", "=", "node", ".", "parent", "if", "node", ".", "type", "==", "\"function\"", ":", "# Ignore for direct execution functions. This is required", "# for parsing e.g. (function(){})(); which does not work", "# without parens ...
https://github.com/zynga/jasy/blob/8a2ec2c2ca3f6c0f73cba4306e581c89b30f1b18/jasy/js/optimize/BlockReducer.py#L277-L336
PySimpleGUI/PySimpleGUI
6c0d1fb54f493d45e90180b322fbbe70f7a5af3c
DemoPrograms/Demo_Desktop_Widget_Drive_Usage.py
python
update_window
(window)
[]
def update_window(window): particians = psutil.disk_partitions() for count, part in enumerate(particians): mount = part[0] try: usage = psutil.disk_usage(mount) window[('-NAME-', mount)].update(mount) window[('-PROG-', mount)].update_bar(int(usage.percent)) window[('-%-', mount)].update(f'{usage.percent}%') window[('-STATS-', mount)].update(f'{human_size(usage.used)} / {human_size(usage.total)} = {human_size(usage.free)} free') except: pass
[ "def", "update_window", "(", "window", ")", ":", "particians", "=", "psutil", ".", "disk_partitions", "(", ")", "for", "count", ",", "part", "in", "enumerate", "(", "particians", ")", ":", "mount", "=", "part", "[", "0", "]", "try", ":", "usage", "=", ...
https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/DemoPrograms/Demo_Desktop_Widget_Drive_Usage.py#L24-L35
holoviz/holoviews
cc6b27f01710402fdfee2aeef1507425ca78c91f
holoviews/core/dimension.py
python
ViewableTree.dimension_values
(self, dimension, expanded=True, flat=True)
Return the values along the requested dimension. Concatenates values on all nodes with requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values Whether to return the expanded values, behavior depends on the type of data: * Columnar: If false returns unique values * Geometry: If false returns scalar values per geometry * Gridded: If false returns 1D coordinates flat (bool, optional): Whether to flatten array Returns: NumPy array of values along the requested dimension
Return the values along the requested dimension.
[ "Return", "the", "values", "along", "the", "requested", "dimension", "." ]
def dimension_values(self, dimension, expanded=True, flat=True): """Return the values along the requested dimension. Concatenates values on all nodes with requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values Whether to return the expanded values, behavior depends on the type of data: * Columnar: If false returns unique values * Geometry: If false returns scalar values per geometry * Gridded: If false returns 1D coordinates flat (bool, optional): Whether to flatten array Returns: NumPy array of values along the requested dimension """ dimension = self.get_dimension(dimension, strict=True).name all_dims = self.traverse(lambda x: [d.name for d in x.dimensions()]) if dimension in chain.from_iterable(all_dims): values = [el.dimension_values(dimension) for el in self if dimension in el.dimensions(label=True)] vals = np.concatenate(values) return vals if expanded else util.unique_array(vals) else: return super().dimension_values( dimension, expanded, flat)
[ "def", "dimension_values", "(", "self", ",", "dimension", ",", "expanded", "=", "True", ",", "flat", "=", "True", ")", ":", "dimension", "=", "self", ".", "get_dimension", "(", "dimension", ",", "strict", "=", "True", ")", ".", "name", "all_dims", "=", ...
https://github.com/holoviz/holoviews/blob/cc6b27f01710402fdfee2aeef1507425ca78c91f/holoviews/core/dimension.py#L1407-L1434
windelbouwman/ppci
915c069e0667042c085ec42c78e9e3c9a5295324
ppci/lang/c/codegenerator.py
python
CCodeGenerator.create_function_internal
(self, function)
Create the function and put it into the var_map
Create the function and put it into the var_map
[ "Create", "the", "function", "and", "put", "it", "into", "the", "var_map" ]
def create_function_internal(self, function): """ Create the function and put it into the var_map """ if function.storage_class == "static": binding = ir.Binding.LOCAL else: binding = ir.Binding.GLOBAL # Create ir function: if function.typ.return_type.is_void: ir_function = self.builder.new_procedure(function.name, binding) elif function.typ.return_type.is_struct: # Pass implicit first argument to function when complex type # is returned. ir_function = self.builder.new_procedure(function.name, binding) return_value_address = ir.Parameter("return_value_address", ir.ptr) ir_function.add_parameter(return_value_address) else: return_type = self.get_ir_type(function.typ.return_type) ir_function = self.builder.new_function( function.name, binding, return_type ) self.ir_var_map[function] = ir_function
[ "def", "create_function_internal", "(", "self", ",", "function", ")", ":", "if", "function", ".", "storage_class", "==", "\"static\"", ":", "binding", "=", "ir", ".", "Binding", ".", "LOCAL", "else", ":", "binding", "=", "ir", ".", "Binding", ".", "GLOBAL"...
https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/lang/c/codegenerator.py#L341-L362
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/root_system/cartan_type.py
python
CartanTypeFactory._samples
(self)
return finite_crystallographic + \ [CartanType(t) for t in [["I", 5], ["H", 3], ["H", 4]]] + \ [t.affine() for t in finite_crystallographic if t.is_irreducible()] + \ [CartanType(t) for t in [["BC", 1, 2], ["BC", 5, 2]]] + \ [CartanType(t).dual() for t in [["B", 5, 1], ["C", 4, 1], ["F", 4, 1], ["G", 2, 1],["BC", 1, 2], ["BC", 5, 2]]]
Return a sample of all implemented Cartan types. .. NOTE:: This is intended to be used through :meth:`samples`. EXAMPLES:: sage: CartanType._samples() [['A', 1], ['A', 5], ['B', 1], ['B', 5], ['C', 1], ['C', 5], ['D', 2], ['D', 3], ['D', 5], ['E', 6], ['E', 7], ['E', 8], ['F', 4], ['G', 2], ['I', 5], ['H', 3], ['H', 4], ['A', 1, 1], ['A', 5, 1], ['B', 1, 1], ['B', 5, 1], ['C', 1, 1], ['C', 5, 1], ['D', 3, 1], ['D', 5, 1], ['E', 6, 1], ['E', 7, 1], ['E', 8, 1], ['F', 4, 1], ['G', 2, 1], ['BC', 1, 2], ['BC', 5, 2], ['B', 5, 1]^*, ['C', 4, 1]^*, ['F', 4, 1]^*, ['G', 2, 1]^*, ['BC', 1, 2]^*, ['BC', 5, 2]^*]
Return a sample of all implemented Cartan types.
[ "Return", "a", "sample", "of", "all", "implemented", "Cartan", "types", "." ]
def _samples(self): """ Return a sample of all implemented Cartan types. .. NOTE:: This is intended to be used through :meth:`samples`. EXAMPLES:: sage: CartanType._samples() [['A', 1], ['A', 5], ['B', 1], ['B', 5], ['C', 1], ['C', 5], ['D', 2], ['D', 3], ['D', 5], ['E', 6], ['E', 7], ['E', 8], ['F', 4], ['G', 2], ['I', 5], ['H', 3], ['H', 4], ['A', 1, 1], ['A', 5, 1], ['B', 1, 1], ['B', 5, 1], ['C', 1, 1], ['C', 5, 1], ['D', 3, 1], ['D', 5, 1], ['E', 6, 1], ['E', 7, 1], ['E', 8, 1], ['F', 4, 1], ['G', 2, 1], ['BC', 1, 2], ['BC', 5, 2], ['B', 5, 1]^*, ['C', 4, 1]^*, ['F', 4, 1]^*, ['G', 2, 1]^*, ['BC', 1, 2]^*, ['BC', 5, 2]^*] """ finite_crystallographic = \ [CartanType (t) for t in [['A', 1], ['A', 5], ['B', 1], ['B', 5], ['C', 1], ['C', 5], ['D', 2], ['D', 3], ['D', 5], ["E", 6], ["E", 7], ["E", 8], ["F", 4], ["G", 2]]] # Support for hand constructed Dynkin diagrams as Cartan types is not yet ready enough for including an example here. # from sage.combinat.root_system.dynkin_diagram import DynkinDiagram_class # g = DynkinDiagram_class.an_instance() return finite_crystallographic + \ [CartanType(t) for t in [["I", 5], ["H", 3], ["H", 4]]] + \ [t.affine() for t in finite_crystallographic if t.is_irreducible()] + \ [CartanType(t) for t in [["BC", 1, 2], ["BC", 5, 2]]] + \ [CartanType(t).dual() for t in [["B", 5, 1], ["C", 4, 1], ["F", 4, 1], ["G", 2, 1],["BC", 1, 2], ["BC", 5, 2]]]
[ "def", "_samples", "(", "self", ")", ":", "finite_crystallographic", "=", "[", "CartanType", "(", "t", ")", "for", "t", "in", "[", "[", "'A'", ",", "1", "]", ",", "[", "'A'", ",", "5", "]", ",", "[", "'B'", ",", "1", "]", ",", "[", "'B'", ","...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/root_system/cartan_type.py#L815-L845
ghostop14/sparrow-wifi
4b8289773ea4304872062f65a6ffc9352612b08e
wirelessengine.py
python
WirelessNetwork.getChannelString
(self)
return retVal
[]
def getChannelString(self): if self.bandwidth == 40 and self.secondaryChannel > 0: retVal = str(self.channel) + '+' + str(self.secondaryChannel) else: retVal = str(self.channel) return retVal
[ "def", "getChannelString", "(", "self", ")", ":", "if", "self", ".", "bandwidth", "==", "40", "and", "self", ".", "secondaryChannel", ">", "0", ":", "retVal", "=", "str", "(", "self", ".", "channel", ")", "+", "'+'", "+", "str", "(", "self", ".", "...
https://github.com/ghostop14/sparrow-wifi/blob/4b8289773ea4304872062f65a6ffc9352612b08e/wirelessengine.py#L422-L428
WikiTeam/wikiteam
7f1f9985f667c417501f0dc872ab4fe416b6acda
wikiteam/wikiteam.py
python
getNamespaces
(config={})
return namespacenames
Returns list of namespaces for this wiki
Returns list of namespaces for this wiki
[ "Returns", "list", "of", "namespaces", "for", "this", "wiki" ]
def getNamespaces(config={}): """ Returns list of namespaces for this wiki """ namespaces = [] namespacenames = [] if config['wikiengine'] == 'mediawiki': import mediawiki namespaces, namespacenames = mediawiki.mwGetNamespaces(config=config) return namespacenames
[ "def", "getNamespaces", "(", "config", "=", "{", "}", ")", ":", "namespaces", "=", "[", "]", "namespacenames", "=", "[", "]", "if", "config", "[", "'wikiengine'", "]", "==", "'mediawiki'", ":", "import", "mediawiki", "namespaces", ",", "namespacenames", "=...
https://github.com/WikiTeam/wikiteam/blob/7f1f9985f667c417501f0dc872ab4fe416b6acda/wikiteam/wikiteam.py#L159-L168
wenwei202/terngrad
ec4f75e9a3a1e1c4b2e6494d830fbdfdd2e03ddc
terngrad/inception/slim/ops.py
python
dropout
(inputs, keep_prob=0.5, is_training=True, scope=None)
Returns a dropout layer applied to the input. Args: inputs: the tensor to pass to the Dropout layer. keep_prob: the probability of keeping each input unit. is_training: whether or not the model is in training mode. If so, dropout is applied and values scaled. Otherwise, inputs is returned. scope: Optional scope for name_scope. Returns: a tensor representing the output of the operation.
Returns a dropout layer applied to the input.
[ "Returns", "a", "dropout", "layer", "applied", "to", "the", "input", "." ]
def dropout(inputs, keep_prob=0.5, is_training=True, scope=None): """Returns a dropout layer applied to the input. Args: inputs: the tensor to pass to the Dropout layer. keep_prob: the probability of keeping each input unit. is_training: whether or not the model is in training mode. If so, dropout is applied and values scaled. Otherwise, inputs is returned. scope: Optional scope for name_scope. Returns: a tensor representing the output of the operation. """ if is_training and keep_prob > 0: with tf.name_scope(scope, 'Dropout', [inputs]): return tf.nn.dropout(inputs, keep_prob) else: return inputs
[ "def", "dropout", "(", "inputs", ",", "keep_prob", "=", "0.5", ",", "is_training", "=", "True", ",", "scope", "=", "None", ")", ":", "if", "is_training", "and", "keep_prob", ">", "0", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'Dropout'"...
https://github.com/wenwei202/terngrad/blob/ec4f75e9a3a1e1c4b2e6494d830fbdfdd2e03ddc/terngrad/inception/slim/ops.py#L426-L443
gleeda/memtriage
c24f4859995cccb9d88ccc0118d90693019cc1d5
volatility/volatility/plugins/malware/servicediff.py
python
ServiceDiff.services_from_registry
(addr_space)
return services
Enumerate services from the cached registry hive
Enumerate services from the cached registry hive
[ "Enumerate", "services", "from", "the", "cached", "registry", "hive" ]
def services_from_registry(addr_space): """Enumerate services from the cached registry hive""" services = {} plugin = hivelist.HiveList(addr_space.get_config()) for hive in plugin.calculate(): ## find the SYSTEM hive name = hive.get_name() if not name.lower().endswith("system"): continue ## get the root key hive_space = hive.address_space() root = rawreg.get_root(hive_space) if not root: break ## open the services key key = rawreg.open_key(root, ["ControlSet001", "Services"]) if not key: break ## build a dictionary of the key names for subkey in rawreg.subkeys(key): services[(str(subkey.Name).lower())] = subkey ## we don't need to keep trying break return services
[ "def", "services_from_registry", "(", "addr_space", ")", ":", "services", "=", "{", "}", "plugin", "=", "hivelist", ".", "HiveList", "(", "addr_space", ".", "get_config", "(", ")", ")", "for", "hive", "in", "plugin", ".", "calculate", "(", ")", ":", "## ...
https://github.com/gleeda/memtriage/blob/c24f4859995cccb9d88ccc0118d90693019cc1d5/volatility/volatility/plugins/malware/servicediff.py#L39-L70
Gallopsled/pwntools-write-ups
b7160403288a2d5273e89f115545a4f7fecf32af
2014/defcon-quals/bbgp/doit.py
python
send_pkt
(cmd, payload)
Send a BGP packet
Send a BGP packet
[ "Send", "a", "BGP", "packet" ]
def send_pkt(cmd, payload): """Send a BGP packet""" r.send(flat( "\xff" * 16, p16b(len(payload) + 19), cmd, payload, word_size = 8 ))
[ "def", "send_pkt", "(", "cmd", ",", "payload", ")", ":", "r", ".", "send", "(", "flat", "(", "\"\\xff\"", "*", "16", ",", "p16b", "(", "len", "(", "payload", ")", "+", "19", ")", ",", "cmd", ",", "payload", ",", "word_size", "=", "8", ")", ")" ...
https://github.com/Gallopsled/pwntools-write-ups/blob/b7160403288a2d5273e89f115545a4f7fecf32af/2014/defcon-quals/bbgp/doit.py#L22-L30
sidewalklabs/s2sphere
d1d067e8c06e5fbaf0cc0158bade947b4a03a438
s2sphere/sphere.py
python
SphereInterval.get_complement_center
(self)
[]
def get_complement_center(self): if self.lo() != self.hi(): return self.complement().get_center() else: if self.hi() <= 0: return self.hi() + math.pi else: return self.hi() - math.pi
[ "def", "get_complement_center", "(", "self", ")", ":", "if", "self", ".", "lo", "(", ")", "!=", "self", ".", "hi", "(", ")", ":", "return", "self", ".", "complement", "(", ")", ".", "get_center", "(", ")", "else", ":", "if", "self", ".", "hi", "(...
https://github.com/sidewalklabs/s2sphere/blob/d1d067e8c06e5fbaf0cc0158bade947b4a03a438/s2sphere/sphere.py#L2308-L2315
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Tools/webchecker/webchecker.py
python
MyStringIO.__init__
(self, url, info)
[]
def __init__(self, url, info): self.__url = url self.__info = info StringIO.StringIO.__init__(self)
[ "def", "__init__", "(", "self", ",", "url", ",", "info", ")", ":", "self", ".", "__url", "=", "url", "self", ".", "__info", "=", "info", "StringIO", ".", "StringIO", ".", "__init__", "(", "self", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Tools/webchecker/webchecker.py#L726-L729
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/Rotten-Tomatoes/PyAl/Request/requests/packages/oauthlib/oauth2/draft25/__init__.py
python
Client._add_mac_token
(self, uri, http_method=u'GET', body=None, headers=None, token_placement=AUTH_HEADER)
return uri, headers, body
Add a MAC token to the request authorization header.
Add a MAC token to the request authorization header.
[ "Add", "a", "MAC", "token", "to", "the", "request", "authorization", "header", "." ]
def _add_mac_token(self, uri, http_method=u'GET', body=None, headers=None, token_placement=AUTH_HEADER): """Add a MAC token to the request authorization header.""" headers = prepare_mac_header(self.token, uri, self.key, http_method, headers=headers, body=body, ext=self.ext, hash_algorithm=self.hash_algorithm) return uri, headers, body
[ "def", "_add_mac_token", "(", "self", ",", "uri", ",", "http_method", "=", "u'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "token_placement", "=", "AUTH_HEADER", ")", ":", "headers", "=", "prepare_mac_header", "(", "self", ".", "token...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/Rotten-Tomatoes/PyAl/Request/requests/packages/oauthlib/oauth2/draft25/__init__.py#L110-L116
panpanpandas/ultrafinance
ce3594dbfef747cba0c39f059316df7c208aac40
ultrafinance/dam/hbaseLib.py
python
HBaseLib.deleteTable
(self, tName)
delete table name
delete table name
[ "delete", "table", "name" ]
def deleteTable(self, tName): ''' delete table name ''' if self.__client.isTableEnabled(tName): self.__client.disableTable(tName) self.__client.deleteTable(tName)
[ "def", "deleteTable", "(", "self", ",", "tName", ")", ":", "if", "self", ".", "__client", ".", "isTableEnabled", "(", "tName", ")", ":", "self", ".", "__client", ".", "disableTable", "(", "tName", ")", "self", ".", "__client", ".", "deleteTable", "(", ...
https://github.com/panpanpandas/ultrafinance/blob/ce3594dbfef747cba0c39f059316df7c208aac40/ultrafinance/dam/hbaseLib.py#L31-L36
getnikola/nikola
2da876e9322e42a93f8295f950e336465c6a4ee5
nikola/post.py
python
Post._load_data
(self)
Load data field from metadata.
Load data field from metadata.
[ "Load", "data", "field", "from", "metadata", "." ]
def _load_data(self): """Load data field from metadata.""" self.data = Functionary(lambda: None, self.default_lang) for lang in self.translations: if self.meta[lang].get('data') is not None: self.data[lang] = utils.load_data(self.meta[lang]['data'])
[ "def", "_load_data", "(", "self", ")", ":", "self", ".", "data", "=", "Functionary", "(", "lambda", ":", "None", ",", "self", ".", "default_lang", ")", "for", "lang", "in", "self", ".", "translations", ":", "if", "self", ".", "meta", "[", "lang", "]"...
https://github.com/getnikola/nikola/blob/2da876e9322e42a93f8295f950e336465c6a4ee5/nikola/post.py#L321-L326
openstack/barbican
a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce
barbican/common/policy.py
python
reset
()
[]
def reset(): global ENFORCER if ENFORCER: ENFORCER.clear() ENFORCER = None
[ "def", "reset", "(", ")", ":", "global", "ENFORCER", "if", "ENFORCER", ":", "ENFORCER", ".", "clear", "(", ")", "ENFORCER", "=", "None" ]
https://github.com/openstack/barbican/blob/a9d2b133c8dc3307974f119f9a2b23a4ba82e8ce/barbican/common/policy.py#L33-L37
awkman/pywifi
719baf73d8d32c623dbaf5e9de5d973face152a4
pywifi/_wifiutil_linux.py
python
WifiUtil.scan_results
(self, obj)
return bsses
Get the AP list after scanning.
Get the AP list after scanning.
[ "Get", "the", "AP", "list", "after", "scanning", "." ]
def scan_results(self, obj): """Get the AP list after scanning.""" bsses = [] bsses_summary = self._send_cmd_to_wpas(obj['name'], 'SCAN_RESULTS', True) bsses_summary = bsses_summary[:-1].split('\n') if len(bsses_summary) == 1: return bsses for l in bsses_summary[1:]: values = l.split('\t') bss = Profile() bss.bssid = values[0] bss.freq = int(values[1]) bss.signal = int(values[2]) bss.ssid = values[4] bss.akm = [] if 'WPA-PSK' in values[3]: bss.akm.append(AKM_TYPE_WPAPSK) if 'WPA2-PSK' in values[3]: bss.akm.append(AKM_TYPE_WPA2PSK) if 'WPA-EAP' in values[3]: bss.akm.append(AKM_TYPE_WPA) if 'WPA2-EAP' in values[3]: bss.akm.append(AKM_TYPE_WPA2) bss.auth = AUTH_ALG_OPEN bsses.append(bss) return bsses
[ "def", "scan_results", "(", "self", ",", "obj", ")", ":", "bsses", "=", "[", "]", "bsses_summary", "=", "self", ".", "_send_cmd_to_wpas", "(", "obj", "[", "'name'", "]", ",", "'SCAN_RESULTS'", ",", "True", ")", "bsses_summary", "=", "bsses_summary", "[", ...
https://github.com/awkman/pywifi/blob/719baf73d8d32c623dbaf5e9de5d973face152a4/pywifi/_wifiutil_linux.py#L66-L96
davidcomfort/dash_sample_dashboard
ee0c991142ac33df9945a70205017466a5b3754d
components/printButton.py
python
print_button
()
return printButton
[]
def print_button(): printButton = html.A(['Print PDF'],className="button no-print print",style={'position': "absolute", 'top': '-40', 'right': '0'}) return printButton
[ "def", "print_button", "(", ")", ":", "printButton", "=", "html", ".", "A", "(", "[", "'Print PDF'", "]", ",", "className", "=", "\"button no-print print\"", ",", "style", "=", "{", "'position'", ":", "\"absolute\"", ",", "'top'", ":", "'-40'", ",", "'righ...
https://github.com/davidcomfort/dash_sample_dashboard/blob/ee0c991142ac33df9945a70205017466a5b3754d/components/printButton.py#L3-L5
Kronuz/esprima-python
809cb6e257b1d3d5b0d23f2bca7976e21f02fc3d
esprima/visitor.py
python
Visitor.generic_visit
(self, obj)
return self.visit(self.visit_Object(obj))
[]
def generic_visit(self, obj): return self.visit(self.visit_Object(obj))
[ "def", "generic_visit", "(", "self", ",", "obj", ")", ":", "return", "self", ".", "visit", "(", "self", ".", "visit_Object", "(", "obj", ")", ")" ]
https://github.com/Kronuz/esprima-python/blob/809cb6e257b1d3d5b0d23f2bca7976e21f02fc3d/esprima/visitor.py#L78-L79
llSourcell/AI_in_Medicine_Clinical_Imaging_Classification
fee82c34a83917b47db2e57a90bdb7f9bb4d81e9
src/rotate_images.py
python
mirror_images
(file_path, mirror_direction, lst_imgs)
Mirrors image left or right, based on criteria specified. INPUT file_path: file path to the folder containing images. mirror_direction: criteria for mirroring left or right. lst_imgs: list of image strings. OUTPUT Images mirrored left or right.
Mirrors image left or right, based on criteria specified.
[ "Mirrors", "image", "left", "or", "right", "based", "on", "criteria", "specified", "." ]
def mirror_images(file_path, mirror_direction, lst_imgs): ''' Mirrors image left or right, based on criteria specified. INPUT file_path: file path to the folder containing images. mirror_direction: criteria for mirroring left or right. lst_imgs: list of image strings. OUTPUT Images mirrored left or right. ''' for l in lst_imgs: img = cv2.imread(file_path + str(l) + '.jpeg') img = cv2.flip(img, 1) cv2.imwrite(file_path + str(l) + '_mir' + '.jpeg', img)
[ "def", "mirror_images", "(", "file_path", ",", "mirror_direction", ",", "lst_imgs", ")", ":", "for", "l", "in", "lst_imgs", ":", "img", "=", "cv2", ".", "imread", "(", "file_path", "+", "str", "(", "l", ")", "+", "'.jpeg'", ")", "img", "=", "cv2", "....
https://github.com/llSourcell/AI_in_Medicine_Clinical_Imaging_Classification/blob/fee82c34a83917b47db2e57a90bdb7f9bb4d81e9/src/rotate_images.py#L29-L45
travisgoodspeed/goodfet
1750cc1e8588af5470385e52fa098ca7364c2863
client/GoodFETConsole.py
python
GoodFETConsole.CMDdump
(self,args)
[]
def CMDdump(self,args): file=args[1]; self.client.dump(self.expandfilename(file));
[ "def", "CMDdump", "(", "self", ",", "args", ")", ":", "file", "=", "args", "[", "1", "]", "self", ".", "client", ".", "dump", "(", "self", ".", "expandfilename", "(", "file", ")", ")" ]
https://github.com/travisgoodspeed/goodfet/blob/1750cc1e8588af5470385e52fa098ca7364c2863/client/GoodFETConsole.py#L112-L114
vhf/confusable_homoglyphs
14f43ddd74099520ddcda29fac557c27a28190e6
confusable_homoglyphs/categories.py
python
category
(chr)
return a
Retrieves the unicode category for a unicode character. >>> categories.category('A') 'L' >>> categories.category('τ') 'L' >>> categories.category('-') 'Pd' :param chr: A unicode character :type chr: str :return: The unicode category for a unicode character. :rtype: str
Retrieves the unicode category for a unicode character.
[ "Retrieves", "the", "unicode", "category", "for", "a", "unicode", "character", "." ]
def category(chr): """Retrieves the unicode category for a unicode character. >>> categories.category('A') 'L' >>> categories.category('τ') 'L' >>> categories.category('-') 'Pd' :param chr: A unicode character :type chr: str :return: The unicode category for a unicode character. :rtype: str """ _, a = aliases_categories(chr) return a
[ "def", "category", "(", "chr", ")", ":", "_", ",", "a", "=", "aliases_categories", "(", "chr", ")", "return", "a" ]
https://github.com/vhf/confusable_homoglyphs/blob/14f43ddd74099520ddcda29fac557c27a28190e6/confusable_homoglyphs/categories.py#L60-L76
donnemartin/gitsome
d7c57abc7cb66e9c910a844f15d4536866da3310
xonsh/ply/example/BASIC/basparse.py
python
p_dimitem_single
(p)
dimitem : ID LPAREN INTEGER RPAREN
dimitem : ID LPAREN INTEGER RPAREN
[ "dimitem", ":", "ID", "LPAREN", "INTEGER", "RPAREN" ]
def p_dimitem_single(p): '''dimitem : ID LPAREN INTEGER RPAREN''' p[0] = (p[1], eval(p[3]), 0)
[ "def", "p_dimitem_single", "(", "p", ")", ":", "p", "[", "0", "]", "=", "(", "p", "[", "1", "]", ",", "eval", "(", "p", "[", "3", "]", ")", ",", "0", ")" ]
https://github.com/donnemartin/gitsome/blob/d7c57abc7cb66e9c910a844f15d4536866da3310/xonsh/ply/example/BASIC/basparse.py#L316-L318
GoogleCloudPlatform/appengine-mapreduce
2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6
python/src/mapreduce/input_readers.py
python
_OldAbstractDatastoreInputReader.__str__
(self)
Returns the string representation of this InputReader.
Returns the string representation of this InputReader.
[ "Returns", "the", "string", "representation", "of", "this", "InputReader", "." ]
def __str__(self): """Returns the string representation of this InputReader.""" if self._ns_range is None: return repr(self._key_ranges) else: return repr(self._ns_range)
[ "def", "__str__", "(", "self", ")", ":", "if", "self", ".", "_ns_range", "is", "None", ":", "return", "repr", "(", "self", ".", "_key_ranges", ")", "else", ":", "return", "repr", "(", "self", ".", "_ns_range", ")" ]
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/input_readers.py#L964-L969
ywangd/stash
773d15b8fb3853a65c15fe160bf5584c99437170
bin/mc.py
python
McCmd.help_usage
(self, *args)
prints help about the usage.
prints help about the usage.
[ "prints", "help", "about", "the", "usage", "." ]
def help_usage(self, *args): """prints help about the usage.""" help = """USAGE =============== This guide describes how to use mc. 1.) using filesystem First, you need to connect to a filesystem. Use the 'connect'-command for this. Usage: connect <id> <fsi-name> [args [args ...]] 'id' is a number used to identify the connection in commands. The ID 0 should not be used, as it is used internally. 'fsi-name' is the name of the FSI you want to use (e.g. 'local'). 'args' is passed to the FSI and may contain server, username... Example: connect 1 local >opens the local filesystem. >you can later use this filesystem by passing 1 to commands. connect 2 ftp ftp.example.org 21 YourName YourPswd -s >connects to FTP-server ftp.example.org on port 21 >switch over to SFTP >login as YourName with YourPswd >you can later use this filesystem by passing 2 to commands. If you want to get a list of connected filesystems, use 'connected'. If you want to disconnect, use disconnect <id>. If you want to get a list of aviable FSIs, use help fsis. If you want to see help on a FSI, use help fsi_<name> 2.) Using commands After you are connected, you can use any aviable command. To get a list of aviable commands, type '?' or 'help'. To see the Usage of a command, use 'help <command>'. 3.) Quitting To quit, use the 'exit' command. 4.) Tips You can run shell commands while using mc: !echo test shell python 5.) Additional Info -mc does not transfer file deletions when running a command on the remote fs -mc may behave weird in subdirs """ self.stdout.write(help + "\n")
[ "def", "help_usage", "(", "self", ",", "*", "args", ")", ":", "help", "=", "\"\"\"USAGE\n===============\nThis guide describes how to use mc.\n\n1.) using filesystem\n\tFirst, you need to connect to a filesystem.\n\tUse the 'connect'-command for this.\n\tUsage:\n\t\tconnect <id> <fsi-name> [ar...
https://github.com/ywangd/stash/blob/773d15b8fb3853a65c15fe160bf5584c99437170/bin/mc.py#L616-L659
semontesdeoca/MNPR
8acf9862e38b709eba63a978d35cc658754ec9e9
scripts/coopLib.py
python
getTransforms
(objects, fullPath=False)
return transforms
Get transform nodes of objects Args: objects (list): List of objects fullPath (bool): If full path or not Returns: List of transform nodes
Get transform nodes of objects Args: objects (list): List of objects fullPath (bool): If full path or not Returns: List of transform nodes
[ "Get", "transform", "nodes", "of", "objects", "Args", ":", "objects", "(", "list", ")", ":", "List", "of", "objects", "fullPath", "(", "bool", ")", ":", "If", "full", "path", "or", "not", "Returns", ":", "List", "of", "transform", "nodes" ]
def getTransforms(objects, fullPath=False): """ Get transform nodes of objects Args: objects (list): List of objects fullPath (bool): If full path or not Returns: List of transform nodes """ transforms = [] for node in objects: transforms.append(getTransform(node, fullPath)) return transforms
[ "def", "getTransforms", "(", "objects", ",", "fullPath", "=", "False", ")", ":", "transforms", "=", "[", "]", "for", "node", "in", "objects", ":", "transforms", ".", "append", "(", "getTransform", "(", "node", ",", "fullPath", ")", ")", "return", "transf...
https://github.com/semontesdeoca/MNPR/blob/8acf9862e38b709eba63a978d35cc658754ec9e9/scripts/coopLib.py#L445-L457
YaoZeyuan/ZhihuHelp_archived
a0e4a7acd4512452022ce088fff2adc6f8d30195
src/lib/oauth/zhihu_oauth/zhcls/me.py
python
Me.whispers
(self)
return None
私信列表
私信列表
[ "私信列表" ]
def whispers(self): """ 私信列表 """ return None
[ "def", "whispers", "(", "self", ")", ":", "return", "None" ]
https://github.com/YaoZeyuan/ZhihuHelp_archived/blob/a0e4a7acd4512452022ce088fff2adc6f8d30195/src/lib/oauth/zhihu_oauth/zhcls/me.py#L79-L83
insarlab/MintPy
4357b8c726dec8a3f936770e3f3dda92882685b7
mintpy/image_stitch.py
python
get_corners
(atr)
return S, N, W, E, width, length
Get corners coordinate.
Get corners coordinate.
[ "Get", "corners", "coordinate", "." ]
def get_corners(atr): """Get corners coordinate.""" length = int(atr['LENGTH']) width = int(atr['WIDTH']) W = float(atr['X_FIRST']) N = float(atr['Y_FIRST']) lon_step = float(atr['X_STEP']) lat_step = float(atr['Y_STEP']) S = N + lat_step * length E = W + lon_step * width return S, N, W, E, width, length
[ "def", "get_corners", "(", "atr", ")", ":", "length", "=", "int", "(", "atr", "[", "'LENGTH'", "]", ")", "width", "=", "int", "(", "atr", "[", "'WIDTH'", "]", ")", "W", "=", "float", "(", "atr", "[", "'X_FIRST'", "]", ")", "N", "=", "float", "(...
https://github.com/insarlab/MintPy/blob/4357b8c726dec8a3f936770e3f3dda92882685b7/mintpy/image_stitch.py#L124-L135
flyingpot/pytorch_deephash
fbd94a2cfe1c20ef833eca8cfb1dc7010ae22805
net.py
python
AlexNetPlusLatent.forward
(self, x)
return features, result
[]
def forward(self, x): x = self.features(x) x = x.view(x.size(0), 256 * 6 * 6) x = self.remain(x) x = self.Linear1(x) features = self.sigmoid(x) result = self.Linear2(features) return features, result
[ "def", "forward", "(", "self", ",", "x", ")", ":", "x", "=", "self", ".", "features", "(", "x", ")", "x", "=", "x", ".", "view", "(", "x", ".", "size", "(", "0", ")", ",", "256", "*", "6", "*", "6", ")", "x", "=", "self", ".", "remain", ...
https://github.com/flyingpot/pytorch_deephash/blob/fbd94a2cfe1c20ef833eca8cfb1dc7010ae22805/net.py#L19-L26
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/xbee/switch.py
python
setup_platform
( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, )
Set up the XBee Zigbee switch platform.
Set up the XBee Zigbee switch platform.
[ "Set", "up", "the", "XBee", "Zigbee", "switch", "platform", "." ]
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the XBee Zigbee switch platform.""" zigbee_device = hass.data[DOMAIN] add_entities([XBeeSwitch(XBeeDigitalOutConfig(config), zigbee_device)])
[ "def", "setup_platform", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "ConfigType", ",", "add_entities", ":", "AddEntitiesCallback", ",", "discovery_info", ":", "DiscoveryInfoType", "|", "None", "=", "None", ",", ")", "->", "None", ":", "zigbee_device"...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/xbee/switch.py#L17-L25
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/gui/api_plugins/user.py
python
_GetAllUsernames
()
return sorted(user.username for user in data_store.REL_DB.ReadGRRUsers())
[]
def _GetAllUsernames(): return sorted(user.username for user in data_store.REL_DB.ReadGRRUsers())
[ "def", "_GetAllUsernames", "(", ")", ":", "return", "sorted", "(", "user", ".", "username", "for", "user", "in", "data_store", ".", "REL_DB", ".", "ReadGRRUsers", "(", ")", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_plugins/user.py#L1396-L1397
jupyter/enterprise_gateway
1a529b13f3d9ab94411e4751d4bd35bafd6bbc2e
enterprise_gateway/services/kernels/remotemanager.py
python
RemoteKernelManager._link_dependent_props
(self)
Ensure that RemoteKernelManager, when used as part of an EnterpriseGatewayApp, has certain necessary configuration stay in sync with the app's configuration. When RemoteKernelManager is used independently, this function is a no-op, and default values or configuration set on this class is used.
Ensure that RemoteKernelManager, when used as part of an EnterpriseGatewayApp, has certain necessary configuration stay in sync with the app's configuration.
[ "Ensure", "that", "RemoteKernelManager", "when", "used", "as", "part", "of", "an", "EnterpriseGatewayApp", "has", "certain", "necessary", "configuration", "stay", "in", "sync", "with", "the", "app", "s", "configuration", "." ]
def _link_dependent_props(self): """ Ensure that RemoteKernelManager, when used as part of an EnterpriseGatewayApp, has certain necessary configuration stay in sync with the app's configuration. When RemoteKernelManager is used independently, this function is a no-op, and default values or configuration set on this class is used. """ try: eg_instance = self.parent.parent except AttributeError: return dependent_props = ["authorized_users", "unauthorized_users", "port_range", "impersonation_enabled", "max_kernels_per_user", "env_whitelist", "env_process_whitelist", "yarn_endpoint", "alt_yarn_endpoint", "yarn_endpoint_security_enabled", "conductor_endpoint", "remote_hosts" ] self._links = [directional_link((eg_instance, prop), (self, prop)) for prop in dependent_props]
[ "def", "_link_dependent_props", "(", "self", ")", ":", "try", ":", "eg_instance", "=", "self", ".", "parent", ".", "parent", "except", "AttributeError", ":", "return", "dependent_props", "=", "[", "\"authorized_users\"", ",", "\"unauthorized_users\"", ",", "\"port...
https://github.com/jupyter/enterprise_gateway/blob/1a529b13f3d9ab94411e4751d4bd35bafd6bbc2e/enterprise_gateway/services/kernels/remotemanager.py#L324-L349
simondlevy/AirSimTensorFlow
998fec23f3d717d8aa5d407bfc41c4ad05e2c208
tf_softmax_layer.py
python
inference
(x, xsize, ysize, W_vals=0, b_vals=0)
return output
This is a general-purpose softmax inference layer implementation.
This is a general-purpose softmax inference layer implementation.
[ "This", "is", "a", "general", "-", "purpose", "softmax", "inference", "layer", "implementation", "." ]
def inference(x, xsize, ysize, W_vals=0, b_vals=0): ''' This is a general-purpose softmax inference layer implementation. ''' W_init = tf.constant_initializer(value=W_vals) b_init = tf.constant_initializer(value=b_vals) W = tf.get_variable('W', [xsize, ysize], initializer=W_init) b = tf.get_variable('b', [ysize], initializer=b_init) output = tf.nn.softmax(tf.matmul(x, W) + b) return output
[ "def", "inference", "(", "x", ",", "xsize", ",", "ysize", ",", "W_vals", "=", "0", ",", "b_vals", "=", "0", ")", ":", "W_init", "=", "tf", ".", "constant_initializer", "(", "value", "=", "W_vals", ")", "b_init", "=", "tf", ".", "constant_initializer", ...
https://github.com/simondlevy/AirSimTensorFlow/blob/998fec23f3d717d8aa5d407bfc41c4ad05e2c208/tf_softmax_layer.py#L18-L28
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
chap19/monitor/monitor/monitor/openstack/common/timeutils.py
python
isotime
(at=None, subsecond=False)
return st
Stringify time in ISO 8601 format
Stringify time in ISO 8601 format
[ "Stringify", "time", "in", "ISO", "8601", "format" ]
def isotime(at=None, subsecond=False): """Stringify time in ISO 8601 format""" if not at: at = utcnow() st = at.strftime(_ISO8601_TIME_FORMAT if not subsecond else _ISO8601_TIME_FORMAT_SUBSECOND) tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC' st += ('Z' if tz == 'UTC' else tz) return st
[ "def", "isotime", "(", "at", "=", "None", ",", "subsecond", "=", "False", ")", ":", "if", "not", "at", ":", "at", "=", "utcnow", "(", ")", "st", "=", "at", ".", "strftime", "(", "_ISO8601_TIME_FORMAT", "if", "not", "subsecond", "else", "_ISO8601_TIME_F...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/chap19/monitor/monitor/monitor/openstack/common/timeutils.py#L34-L43
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
istio/datadog_checks/istio/config_models/defaults.py
python
instance_skip_proxy
(field, value)
return False
[]
def instance_skip_proxy(field, value): return False
[ "def", "instance_skip_proxy", "(", "field", ",", "value", ")", ":", "return", "False" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/istio/datadog_checks/istio/config_models/defaults.py#L297-L298
cuthbertLab/music21
bd30d4663e52955ed922c10fdf541419d8c67671
music21/braille/noteGrouping.py
python
NoteGroupingTranscriber.showClefSigns
(self)
Generally, in Braille, clef signs are not used. However, they can be shown for pedagogical purposes or to make a facsimile transcription of the sighted text. If not set but self.brailleElementGrouping.showClefSigns is set, uses that instead. >>> ngt = braille.noteGrouping.NoteGroupingTranscriber() >>> ngt.showClefSigns False >>> beg = braille.segment.BrailleElementGrouping() >>> ngt.brailleElementGrouping = beg >>> ngt.showClefSigns False >>> beg.showClefSigns = True >>> ngt.showClefSigns True >>> ngt.showClefSigns = False >>> ngt.showClefSigns False
Generally, in Braille, clef signs are not used. However, they can be shown for pedagogical purposes or to make a facsimile transcription of the sighted text.
[ "Generally", "in", "Braille", "clef", "signs", "are", "not", "used", ".", "However", "they", "can", "be", "shown", "for", "pedagogical", "purposes", "or", "to", "make", "a", "facsimile", "transcription", "of", "the", "sighted", "text", "." ]
def showClefSigns(self): ''' Generally, in Braille, clef signs are not used. However, they can be shown for pedagogical purposes or to make a facsimile transcription of the sighted text. If not set but self.brailleElementGrouping.showClefSigns is set, uses that instead. >>> ngt = braille.noteGrouping.NoteGroupingTranscriber() >>> ngt.showClefSigns False >>> beg = braille.segment.BrailleElementGrouping() >>> ngt.brailleElementGrouping = beg >>> ngt.showClefSigns False >>> beg.showClefSigns = True >>> ngt.showClefSigns True >>> ngt.showClefSigns = False >>> ngt.showClefSigns False ''' if self._showClefSigns is not None: return self._showClefSigns elif self.brailleElementGrouping is not None: return self.brailleElementGrouping.showClefSigns else: return False
[ "def", "showClefSigns", "(", "self", ")", ":", "if", "self", ".", "_showClefSigns", "is", "not", "None", ":", "return", "self", ".", "_showClefSigns", "elif", "self", ".", "brailleElementGrouping", "is", "not", "None", ":", "return", "self", ".", "brailleEle...
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/braille/noteGrouping.py#L48-L76
qiime2/qiime2
3906f67c70a1321e99e7fc59e79550c2432a8cee
qiime2/core/type/signature.py
python
PipelineSignature.__init__
(self, callable, inputs, parameters, outputs, input_descriptions=None, parameter_descriptions=None, output_descriptions=None)
Parameters ---------- callable : callable Callable with view type annotations on parameters and return. inputs : dict Parameter name to semantic type. parameters : dict Parameter name to primitive type. outputs : list of tuple Each tuple contains the name of the output (str) and its QIIME type. input_descriptions : dict, optional Input name to description string. parameter_descriptions : dict, optional Parameter name to description string. output_descriptions : dict, optional Output name to description string.
[]
def __init__(self, callable, inputs, parameters, outputs, input_descriptions=None, parameter_descriptions=None, output_descriptions=None): """ Parameters ---------- callable : callable Callable with view type annotations on parameters and return. inputs : dict Parameter name to semantic type. parameters : dict Parameter name to primitive type. outputs : list of tuple Each tuple contains the name of the output (str) and its QIIME type. input_descriptions : dict, optional Input name to description string. parameter_descriptions : dict, optional Parameter name to description string. output_descriptions : dict, optional Output name to description string. """ inputs, parameters, outputs, signature_order = \ self._parse_signature(callable, inputs, parameters, outputs, input_descriptions, parameter_descriptions, output_descriptions) self._assert_valid_inputs(inputs) self._assert_valid_parameters(parameters) self._assert_valid_outputs(outputs) self._assert_valid_views(inputs, parameters, outputs) self.inputs = inputs self.parameters = parameters self.outputs = outputs self.signature_order = signature_order
[ "def", "__init__", "(", "self", ",", "callable", ",", "inputs", ",", "parameters", ",", "outputs", ",", "input_descriptions", "=", "None", ",", "parameter_descriptions", "=", "None", ",", "output_descriptions", "=", "None", ")", ":", "inputs", ",", "parameters...
https://github.com/qiime2/qiime2/blob/3906f67c70a1321e99e7fc59e79550c2432a8cee/qiime2/core/type/signature.py#L88-L125
richardaecn/class-balanced-loss
1d7857208a2abc03d84e35a9d5383af8225d4b4d
tpu/models/experimental/distribution_strategy/resnet_preprocessing.py
python
_decode_and_center_crop
(image_bytes, image_size)
return image
Crops to center of image with padding then scales image_size.
Crops to center of image with padding then scales image_size.
[ "Crops", "to", "center", "of", "image", "with", "padding", "then", "scales", "image_size", "." ]
def _decode_and_center_crop(image_bytes, image_size): """Crops to center of image with padding then scales image_size.""" shape = tf.image.extract_jpeg_shape(image_bytes) image_height = shape[0] image_width = shape[1] padded_center_crop_size = tf.cast( ((image_size / (image_size + CROP_PADDING)) * tf.cast(tf.minimum(image_height, image_width), tf.float32)), tf.int32) offset_height = ((image_height - padded_center_crop_size) + 1) // 2 offset_width = ((image_width - padded_center_crop_size) + 1) // 2 crop_window = tf.stack([offset_height, offset_width, padded_center_crop_size, padded_center_crop_size]) image = tf.image.decode_and_crop_jpeg(image_bytes, crop_window, channels=3) image = tf.image.resize_bicubic([image], [image_size, image_size])[0] return image
[ "def", "_decode_and_center_crop", "(", "image_bytes", ",", "image_size", ")", ":", "shape", "=", "tf", ".", "image", ".", "extract_jpeg_shape", "(", "image_bytes", ")", "image_height", "=", "shape", "[", "0", "]", "image_width", "=", "shape", "[", "1", "]", ...
https://github.com/richardaecn/class-balanced-loss/blob/1d7857208a2abc03d84e35a9d5383af8225d4b4d/tpu/models/experimental/distribution_strategy/resnet_preprocessing.py#L108-L126
bspaans/python-mingus
6558cacffeaab4f084a3eedda12b0e86fd24c430
mingus/core/value.py
python
subtract
(value1, value2)
return 1 / (1.0 / value1 - 1.0 / value2)
Return the note value for value1 minus value2. There are no exceptions for producing negative values, which can be useful for taking differences. Example: >>> subtract(quarter, eighth) 8.0
Return the note value for value1 minus value2.
[ "Return", "the", "note", "value", "for", "value1", "minus", "value2", "." ]
def subtract(value1, value2): """Return the note value for value1 minus value2. There are no exceptions for producing negative values, which can be useful for taking differences. Example: >>> subtract(quarter, eighth) 8.0 """ return 1 / (1.0 / value1 - 1.0 / value2)
[ "def", "subtract", "(", "value1", ",", "value2", ")", ":", "return", "1", "/", "(", "1.0", "/", "value1", "-", "1.0", "/", "value2", ")" ]
https://github.com/bspaans/python-mingus/blob/6558cacffeaab4f084a3eedda12b0e86fd24c430/mingus/core/value.py#L135-L145
xiaolonw/TimeCycle
16d33ac0fb0a08105a9ca781c7b1b36898e3b601
utils/torch_util.py
python
BatchTensorToVars.__call__
(self, batch)
return batch_var
[]
def __call__(self, batch): batch_var = {} for key,value in batch.items(): if isinstance(value,torch.Tensor) and not self.use_cuda: batch_var[key] = Variable(value,requires_grad=False) elif isinstance(value,torch.Tensor) and self.use_cuda: batch_var[key] = Variable(value,requires_grad=False).cuda() else: batch_var[key] = value return batch_var
[ "def", "__call__", "(", "self", ",", "batch", ")", ":", "batch_var", "=", "{", "}", "for", "key", ",", "value", "in", "batch", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "torch", ".", "Tensor", ")", "and", "not", "self", ...
https://github.com/xiaolonw/TimeCycle/blob/16d33ac0fb0a08105a9ca781c7b1b36898e3b601/utils/torch_util.py#L63-L72
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py
python
TaskQueueInstance.links
(self)
return self._properties['links']
:returns: The URLs of related resources :rtype: unicode
:returns: The URLs of related resources :rtype: unicode
[ ":", "returns", ":", "The", "URLs", "of", "related", "resources", ":", "rtype", ":", "unicode" ]
def links(self): """ :returns: The URLs of related resources :rtype: unicode """ return self._properties['links']
[ "def", "links", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'links'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py#L579-L584
JacquesLucke/animation_nodes
b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1
animation_nodes/base_types/nodes/base_node.py
python
AnimationNode.iterInputSocketsWithTemplate
(self)
[]
def iterInputSocketsWithTemplate(self): inputsInfo = infoByNode[self.identifier].inputs for socket in self.inputs: yield (socket, inputsInfo[socket.identifier].template)
[ "def", "iterInputSocketsWithTemplate", "(", "self", ")", ":", "inputsInfo", "=", "infoByNode", "[", "self", ".", "identifier", "]", ".", "inputs", "for", "socket", "in", "self", ".", "inputs", ":", "yield", "(", "socket", ",", "inputsInfo", "[", "socket", ...
https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/base_types/nodes/base_node.py#L279-L282
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site.py
python
fixclasspath
()
Adjust the special classpath sys.path entries for Jython. These entries should follow the base virtualenv lib directories.
Adjust the special classpath sys.path entries for Jython. These entries should follow the base virtualenv lib directories.
[ "Adjust", "the", "special", "classpath", "sys", ".", "path", "entries", "for", "Jython", ".", "These", "entries", "should", "follow", "the", "base", "virtualenv", "lib", "directories", "." ]
def fixclasspath(): """Adjust the special classpath sys.path entries for Jython. These entries should follow the base virtualenv lib directories. """ paths = [] classpaths = [] for path in sys.path: if path == '__classpath__' or path.startswith('__pyclasspath__'): classpaths.append(path) else: paths.append(path) sys.path = paths sys.path.extend(classpaths)
[ "def", "fixclasspath", "(", ")", ":", "paths", "=", "[", "]", "classpaths", "=", "[", "]", "for", "path", "in", "sys", ".", "path", ":", "if", "path", "==", "'__classpath__'", "or", "path", ".", "startswith", "(", "'__pyclasspath__'", ")", ":", "classp...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site.py#L646-L658
PaulSonOfLars/tgbot
0ece72778b7772725ab214fe0929daaa2fc7d2d1
tg_bot/modules/warns.py
python
warns
(bot: Bot, update: Update, args: List[str])
[]
def warns(bot: Bot, update: Update, args: List[str]): message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user_id = extract_user(message, args) or update.effective_user.id result = sql.get_warns(user_id, chat.id) if result and result[0] != 0: num_warns, reasons = result limit, soft_warn = sql.get_warn_setting(chat.id) if reasons: text = "This user has {}/{} warnings, for the following reasons:".format(num_warns, limit) for reason in reasons: text += "\n - {}".format(reason) msgs = split_message(text) for msg in msgs: update.effective_message.reply_text(msg) else: update.effective_message.reply_text( "User has {}/{} warnings, but no reasons for any of them.".format(num_warns, limit)) else: update.effective_message.reply_text("This user hasn't got any warnings!")
[ "def", "warns", "(", "bot", ":", "Bot", ",", "update", ":", "Update", ",", "args", ":", "List", "[", "str", "]", ")", ":", "message", "=", "update", ".", "effective_message", "# type: Optional[Message]", "chat", "=", "update", ".", "effective_chat", "# typ...
https://github.com/PaulSonOfLars/tgbot/blob/0ece72778b7772725ab214fe0929daaa2fc7d2d1/tg_bot/modules/warns.py#L176-L198
JulianEberius/SublimePythonIDE
d70e40abc0c9f347af3204c7b910e0d6bfd6e459
server/lib/python2/rope/base/project.py
python
_Project.remove_observer
(self, observer)
Remove a registered `ResourceObserver`
Remove a registered `ResourceObserver`
[ "Remove", "a", "registered", "ResourceObserver" ]
def remove_observer(self, observer): """Remove a registered `ResourceObserver`""" if observer in self.observers: self.observers.remove(observer)
[ "def", "remove_observer", "(", "self", ",", "observer", ")", ":", "if", "observer", "in", "self", ".", "observers", ":", "self", ".", "observers", ".", "remove", "(", "observer", ")" ]
https://github.com/JulianEberius/SublimePythonIDE/blob/d70e40abc0c9f347af3204c7b910e0d6bfd6e459/server/lib/python2/rope/base/project.py#L62-L65
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/groups/abelian_gps/dual_abelian_group.py
python
DualAbelianGroup_class.__str__
(self)
return s
Print method. EXAMPLES:: sage: F = AbelianGroup(3,[5,64,729], names=list("abc")) sage: Fd = F.dual_group(base_ring=CC) sage: print(Fd) DualAbelianGroup( AbelianGroup ( 3, (5, 64, 729) ) )
Print method.
[ "Print", "method", "." ]
def __str__(self): """ Print method. EXAMPLES:: sage: F = AbelianGroup(3,[5,64,729], names=list("abc")) sage: Fd = F.dual_group(base_ring=CC) sage: print(Fd) DualAbelianGroup( AbelianGroup ( 3, (5, 64, 729) ) ) """ s = "DualAbelianGroup( AbelianGroup ( %s, %s ) )"%(self.ngens(), self.gens_orders()) return s
[ "def", "__str__", "(", "self", ")", ":", "s", "=", "\"DualAbelianGroup( AbelianGroup ( %s, %s ) )\"", "%", "(", "self", ".", "ngens", "(", ")", ",", "self", ".", "gens_orders", "(", ")", ")", "return", "s" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/groups/abelian_gps/dual_abelian_group.py#L157-L169
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/south/south/modelsinspector.py
python
add_ignored_fields
(patterns)
Allows you to add some ignore field patterns.
Allows you to add some ignore field patterns.
[ "Allows", "you", "to", "add", "some", "ignore", "field", "patterns", "." ]
def add_ignored_fields(patterns): "Allows you to add some ignore field patterns." assert isinstance(patterns, (list, tuple)) ignored_fields.extend(patterns)
[ "def", "add_ignored_fields", "(", "patterns", ")", ":", "assert", "isinstance", "(", "patterns", ",", "(", "list", ",", "tuple", ")", ")", "ignored_fields", ".", "extend", "(", "patterns", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/south/south/modelsinspector.py#L195-L198
lixinsu/RCZoo
37fcb7962fbd4c751c561d4a0c84173881ea8339
scripts/reader/extract_eval_results.py
python
compare_result
(files)
[]
def compare_result(files): results = {} for ifile in files: print(ifile.split('/')[-1]) save_name = ifile.split('/')[-1].split('.')[0] res = extract_file(ifile) results['%s-EM' % save_name] = [float(ires[1]) for ires in res] results['%s-F1' % save_name] = [float(ires[2]) for ires in res] pd.DataFrame.from_dict(results).to_csv('compare.csv', sep=',')
[ "def", "compare_result", "(", "files", ")", ":", "results", "=", "{", "}", "for", "ifile", "in", "files", ":", "print", "(", "ifile", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "save_name", "=", "ifile", ".", "split", "(", "'/'", ")"...
https://github.com/lixinsu/RCZoo/blob/37fcb7962fbd4c751c561d4a0c84173881ea8339/scripts/reader/extract_eval_results.py#L21-L29
marcoeilers/nagini
a2a19df7d833e67841e03c9885869c3dddef3327
src/nagini_translation/translators/obligation/obligation_info.py
python
PythonLoopObligationInfo.get_prepend_body
(self)
return self._prepend_body
Return statements to be prepended to the loop body.
Return statements to be prepended to the loop body.
[ "Return", "statements", "to", "be", "prepended", "to", "the", "loop", "body", "." ]
def get_prepend_body(self) -> List[Stmt]: """Return statements to be prepended to the loop body.""" return self._prepend_body
[ "def", "get_prepend_body", "(", "self", ")", "->", "List", "[", "Stmt", "]", ":", "return", "self", ".", "_prepend_body" ]
https://github.com/marcoeilers/nagini/blob/a2a19df7d833e67841e03c9885869c3dddef3327/src/nagini_translation/translators/obligation/obligation_info.py#L470-L472
feisuzhu/thbattle
ac0dee1b2d86de7664289cf432b157ef25427ba1
tools/THB.app/Contents/Resources/pycparser.egg/pycparser/c_parser.py
python
CParser.p_expression
(self, p)
expression : assignment_expression | expression COMMA assignment_expression
expression : assignment_expression | expression COMMA assignment_expression
[ "expression", ":", "assignment_expression", "|", "expression", "COMMA", "assignment_expression" ]
def p_expression(self, p): """ expression : assignment_expression | expression COMMA assignment_expression """ if len(p) == 2: p[0] = p[1] else: if not isinstance(p[1], c_ast.ExprList): p[1] = c_ast.ExprList([p[1]], p[1].coord) p[1].exprs.append(p[3]) p[0] = p[1]
[ "def", "p_expression", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "else", ":", "if", "not", "isinstance", "(", "p", "[", "1", "]", ",", "c_ast", ".", "ExprList",...
https://github.com/feisuzhu/thbattle/blob/ac0dee1b2d86de7664289cf432b157ef25427ba1/tools/THB.app/Contents/Resources/pycparser.egg/pycparser/c_parser.py#L1399-L1410
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/idlelib/EditorWindow.py
python
EditorWindow._filename_to_unicode
(self, filename)
convert filename to unicode in order to display it in Tk
convert filename to unicode in order to display it in Tk
[ "convert", "filename", "to", "unicode", "in", "order", "to", "display", "it", "in", "Tk" ]
def _filename_to_unicode(self, filename): """convert filename to unicode in order to display it in Tk""" if isinstance(filename, unicode) or not filename: return filename else: try: return filename.decode(self.filesystemencoding) except UnicodeDecodeError: # XXX try: return filename.decode(self.encoding) except UnicodeDecodeError: # byte-to-byte conversion return filename.decode('iso8859-1')
[ "def", "_filename_to_unicode", "(", "self", ",", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "unicode", ")", "or", "not", "filename", ":", "return", "filename", "else", ":", "try", ":", "return", "filename", ".", "decode", "(", "self", ...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/idlelib/EditorWindow.py#L304-L317
cbfinn/maml_rl
9c8e2ebd741cb0c7b8bf2d040c4caeeb8e06cc95
rllab/regressors/categorical_mlp_regressor.py
python
CategoricalMLPRegressor.__init__
( self, input_shape, output_dim, prob_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=NL.rectify, optimizer=None, use_trust_region=True, step_size=0.01, normalize_inputs=True, name=None, )
:param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. :param use_trust_region: Whether to use trust region constraint. :param step_size: KL divergence constraint for each iteration
:param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. :param use_trust_region: Whether to use trust region constraint. :param step_size: KL divergence constraint for each iteration
[ ":", "param", "input_shape", ":", "Shape", "of", "the", "input", "data", ".", ":", "param", "output_dim", ":", "Dimension", "of", "output", ".", ":", "param", "hidden_sizes", ":", "Number", "of", "hidden", "units", "of", "each", "layer", "of", "the", "me...
def __init__( self, input_shape, output_dim, prob_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=NL.rectify, optimizer=None, use_trust_region=True, step_size=0.01, normalize_inputs=True, name=None, ): """ :param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. :param use_trust_region: Whether to use trust region constraint. :param step_size: KL divergence constraint for each iteration """ Serializable.quick_init(self, locals()) if optimizer is None: if use_trust_region: optimizer = PenaltyLbfgsOptimizer() else: optimizer = LbfgsOptimizer() self.output_dim = output_dim self._optimizer = optimizer if prob_network is None: prob_network = MLP( input_shape=input_shape, output_dim=output_dim, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, output_nonlinearity=NL.softmax, ) l_prob = prob_network.output_layer LasagnePowered.__init__(self, [l_prob]) xs_var = prob_network.input_layer.input_var ys_var = TT.imatrix("ys") old_prob_var = TT.matrix("old_prob") x_mean_var = theano.shared( np.zeros((1,) + input_shape), name="x_mean", broadcastable=(True,) + (False,) * len(input_shape) ) x_std_var = theano.shared( np.ones((1,) + input_shape), name="x_std", broadcastable=(True,) + (False,) * len(input_shape) ) normalized_xs_var = (xs_var - x_mean_var) / x_std_var prob_var = L.get_output(l_prob, {prob_network.input_layer: normalized_xs_var}) old_info_vars = dict(prob=old_prob_var) info_vars = dict(prob=prob_var) dist = self._dist = Categorical(output_dim) mean_kl = TT.mean(dist.kl_sym(old_info_vars, info_vars)) loss = - TT.mean(dist.log_likelihood_sym(ys_var, info_vars)) predicted = special.to_onehot_sym(TT.argmax(prob_var, axis=1), output_dim) self._f_predict = ext.compile_function([xs_var], predicted) self._f_prob = ext.compile_function([xs_var], prob_var) self._prob_network = prob_network self._l_prob = l_prob optimizer_args = dict( loss=loss, target=self, network_outputs=[prob_var], ) if use_trust_region: optimizer_args["leq_constraint"] = (mean_kl, step_size) optimizer_args["inputs"] = [xs_var, ys_var, old_prob_var] else: optimizer_args["inputs"] = [xs_var, ys_var] self._optimizer.update_opt(**optimizer_args) self._use_trust_region = use_trust_region self._name = name self._normalize_inputs = normalize_inputs self._x_mean_var = x_mean_var self._x_std_var = x_std_var
[ "def", "__init__", "(", "self", ",", "input_shape", ",", "output_dim", ",", "prob_network", "=", "None", ",", "hidden_sizes", "=", "(", "32", ",", "32", ")", ",", "hidden_nonlinearity", "=", "NL", ".", "rectify", ",", "optimizer", "=", "None", ",", "use_...
https://github.com/cbfinn/maml_rl/blob/9c8e2ebd741cb0c7b8bf2d040c4caeeb8e06cc95/rllab/regressors/categorical_mlp_regressor.py#L26-L126
scrapinghub/frontera
84f9e1034d2868447db88e865596c0fbb32e70f6
frontera/contrib/messagebus/zeromq/socket_config.py
python
SocketConfig.db_in
(self)
return 'tcp://%s:%d' % (self.ip_addr, self.base_port + 4)
TCP socket for incoming messages
TCP socket for incoming messages
[ "TCP", "socket", "for", "incoming", "messages" ]
def db_in(self): """ TCP socket for incoming messages """ return 'tcp://%s:%d' % (self.ip_addr, self.base_port + 4)
[ "def", "db_in", "(", "self", ")", ":", "return", "'tcp://%s:%d'", "%", "(", "self", ".", "ip_addr", ",", "self", ".", "base_port", "+", "4", ")" ]
https://github.com/scrapinghub/frontera/blob/84f9e1034d2868447db88e865596c0fbb32e70f6/frontera/contrib/messagebus/zeromq/socket_config.py#L53-L57
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail_bak/contrib/modeladmin/views.py
python
InspectView.get_field_label
(self, field_name, field=None)
return label
Return a label to display for a field
Return a label to display for a field
[ "Return", "a", "label", "to", "display", "for", "a", "field" ]
def get_field_label(self, field_name, field=None): """ Return a label to display for a field """ label = None if field is not None: label = getattr(field, 'verbose_name', None) if label is None: label = getattr(field, 'name', None) if label is None: label = field_name return label
[ "def", "get_field_label", "(", "self", ",", "field_name", ",", "field", "=", "None", ")", ":", "label", "=", "None", "if", "field", "is", "not", "None", ":", "label", "=", "getattr", "(", "field", ",", "'verbose_name'", ",", "None", ")", "if", "label",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail_bak/contrib/modeladmin/views.py#L838-L847
benknight/hue-alfred-workflow
4447ba61116caf4a448b50c4bfb866565d66d81e
logic/packages/requests/models.py
python
RequestEncodingMixin.path_url
(self)
return ''.join(url)
Build the path URL to use.
Build the path URL to use.
[ "Build", "the", "path", "URL", "to", "use", "." ]
def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.url) path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return ''.join(url)
[ "def", "path_url", "(", "self", ")", ":", "url", "=", "[", "]", "p", "=", "urlsplit", "(", "self", ".", "url", ")", "path", "=", "p", ".", "path", "if", "not", "path", ":", "path", "=", "'/'", "url", ".", "append", "(", "path", ")", "query", ...
https://github.com/benknight/hue-alfred-workflow/blob/4447ba61116caf4a448b50c4bfb866565d66d81e/logic/packages/requests/models.py#L38-L56
IBM/lale
b4d6829c143a4735b06083a0e6c70d2cca244162
lale/lib/sklearn/stacking_regressor.py
python
_StackingRegressorImpl._concatenate_predictions
(self, X, predictions)
return _concatenate_predictions_pandas(self, X, predictions)
[]
def _concatenate_predictions(self, X, predictions): if not isinstance(X, pd.DataFrame): return super()._concatenate_predictions(X, predictions) return _concatenate_predictions_pandas(self, X, predictions)
[ "def", "_concatenate_predictions", "(", "self", ",", "X", ",", "predictions", ")", ":", "if", "not", "isinstance", "(", "X", ",", "pd", ".", "DataFrame", ")", ":", "return", "super", "(", ")", ".", "_concatenate_predictions", "(", "X", ",", "predictions", ...
https://github.com/IBM/lale/blob/b4d6829c143a4735b06083a0e6c70d2cca244162/lale/lib/sklearn/stacking_regressor.py#L32-L35
rossant/galry
6201fa32fb5c9ef3cea700cc22caf52fb69ebe31
experimental/gallery.py
python
anim
(fig, (t,))
[]
def anim(fig, (t,)): global CURRENT_IMAGE image_last_loaded = pw.current() # Skip if current image in memory is None. if image_last_loaded is None or np.array_equal(image_last_loaded, pw.EMPTY): return # Update only if current displayed image is empty, and current image in # memory is not empty. if (CURRENT_IMAGE is None or np.array_equal(CURRENT_IMAGE, pw.EMPTY)): print "update" CURRENT_IMAGE = pw.current() show_image(fig, CURRENT_IMAGE)
[ "def", "anim", "(", "fig", ",", "(", "t", ",", ")", ")", ":", "global", "CURRENT_IMAGE", "image_last_loaded", "=", "pw", ".", "current", "(", ")", "# Skip if current image in memory is None.", "if", "image_last_loaded", "is", "None", "or", "np", ".", "array_eq...
https://github.com/rossant/galry/blob/6201fa32fb5c9ef3cea700cc22caf52fb69ebe31/experimental/gallery.py#L141-L152
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/external/attr/_funcs.py
python
asdict
( inst, recurse=True, filter=None, dict_factory=dict, retain_collection_types=False, value_serializer=None, )
return rv
Return the ``attrs`` attribute values of *inst* as a dict. Optionally recurse into other ``attrs``-decorated classes. :param inst: Instance of an ``attrs``-decorated class. :param bool recurse: Recurse into classes that are also ``attrs``-decorated. :param callable filter: A callable whose return code determines whether an attribute or element is included (``True``) or dropped (``False``). Is called with the `attr.Attribute` as the first argument and the value as the second argument. :param callable dict_factory: A callable to produce dictionaries from. For example, to produce ordered dictionaries instead of normal Python dictionaries, pass in ``collections.OrderedDict``. :param bool retain_collection_types: Do not convert to ``list`` when encountering an attribute whose type is ``tuple`` or ``set``. Only meaningful if ``recurse`` is ``True``. :param Optional[callable] value_serializer: A hook that is called for every attribute or dict key/value. It receives the current instance, field and value and must return the (updated) value. The hook is run *after* the optional *filter* has been applied. :rtype: return type of *dict_factory* :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. versionadded:: 16.0.0 *dict_factory* .. versionadded:: 16.1.0 *retain_collection_types* .. versionadded:: 20.3.0 *value_serializer*
Return the ``attrs`` attribute values of *inst* as a dict.
[ "Return", "the", "attrs", "attribute", "values", "of", "*", "inst", "*", "as", "a", "dict", "." ]
def asdict( inst, recurse=True, filter=None, dict_factory=dict, retain_collection_types=False, value_serializer=None, ): """ Return the ``attrs`` attribute values of *inst* as a dict. Optionally recurse into other ``attrs``-decorated classes. :param inst: Instance of an ``attrs``-decorated class. :param bool recurse: Recurse into classes that are also ``attrs``-decorated. :param callable filter: A callable whose return code determines whether an attribute or element is included (``True``) or dropped (``False``). Is called with the `attr.Attribute` as the first argument and the value as the second argument. :param callable dict_factory: A callable to produce dictionaries from. For example, to produce ordered dictionaries instead of normal Python dictionaries, pass in ``collections.OrderedDict``. :param bool retain_collection_types: Do not convert to ``list`` when encountering an attribute whose type is ``tuple`` or ``set``. Only meaningful if ``recurse`` is ``True``. :param Optional[callable] value_serializer: A hook that is called for every attribute or dict key/value. It receives the current instance, field and value and must return the (updated) value. The hook is run *after* the optional *filter* has been applied. :rtype: return type of *dict_factory* :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. versionadded:: 16.0.0 *dict_factory* .. versionadded:: 16.1.0 *retain_collection_types* .. versionadded:: 20.3.0 *value_serializer* """ attrs = fields(inst.__class__) rv = dict_factory() for a in attrs: v = getattr(inst, a.name) if filter is not None and not filter(a, v): continue if value_serializer is not None: v = value_serializer(inst, a, v) if recurse is True: if has(v.__class__): rv[a.name] = asdict( v, True, filter, dict_factory, retain_collection_types, value_serializer, ) elif isinstance(v, (tuple, list, set, frozenset)): cf = v.__class__ if retain_collection_types is True else list rv[a.name] = cf( [ _asdict_anything( i, filter, dict_factory, retain_collection_types, value_serializer, ) for i in v ] ) elif isinstance(v, dict): df = dict_factory rv[a.name] = df( ( _asdict_anything( kk, filter, df, retain_collection_types, value_serializer, ), _asdict_anything( vv, filter, df, retain_collection_types, value_serializer, ), ) for kk, vv in iteritems(v) ) else: rv[a.name] = v else: rv[a.name] = v return rv
[ "def", "asdict", "(", "inst", ",", "recurse", "=", "True", ",", "filter", "=", "None", ",", "dict_factory", "=", "dict", ",", "retain_collection_types", "=", "False", ",", "value_serializer", "=", "None", ",", ")", ":", "attrs", "=", "fields", "(", "inst...
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/external/attr/_funcs.py#L10-L109
open-telemetry/opentelemetry-python
f5d872050204685b5ef831d02ec593956820ebe6
opentelemetry-api/src/opentelemetry/trace/__init__.py
python
get_tracer
( instrumenting_module_name: str, instrumenting_library_version: typing.Optional[str] = None, tracer_provider: Optional[TracerProvider] = None, schema_url: typing.Optional[str] = None, )
return tracer_provider.get_tracer( instrumenting_module_name, instrumenting_library_version, schema_url )
Returns a `Tracer` for use by the given instrumentation library. This function is a convenience wrapper for opentelemetry.trace.TracerProvider.get_tracer. If tracer_provider is omitted the current configured one is used.
Returns a `Tracer` for use by the given instrumentation library.
[ "Returns", "a", "Tracer", "for", "use", "by", "the", "given", "instrumentation", "library", "." ]
def get_tracer( instrumenting_module_name: str, instrumenting_library_version: typing.Optional[str] = None, tracer_provider: Optional[TracerProvider] = None, schema_url: typing.Optional[str] = None, ) -> "Tracer": """Returns a `Tracer` for use by the given instrumentation library. This function is a convenience wrapper for opentelemetry.trace.TracerProvider.get_tracer. If tracer_provider is omitted the current configured one is used. """ if tracer_provider is None: tracer_provider = get_tracer_provider() return tracer_provider.get_tracer( instrumenting_module_name, instrumenting_library_version, schema_url )
[ "def", "get_tracer", "(", "instrumenting_module_name", ":", "str", ",", "instrumenting_library_version", ":", "typing", ".", "Optional", "[", "str", "]", "=", "None", ",", "tracer_provider", ":", "Optional", "[", "TracerProvider", "]", "=", "None", ",", "schema_...
https://github.com/open-telemetry/opentelemetry-python/blob/f5d872050204685b5ef831d02ec593956820ebe6/opentelemetry-api/src/opentelemetry/trace/__init__.py#L461-L478
python-mechanize/mechanize
3cd4d19ee701d9aa458fa23b7515c268d3f1cef0
mechanize/_http.py
python
parse_head
(fileobj)
return p()
Return a list of key, value pairs.
Return a list of key, value pairs.
[ "Return", "a", "list", "of", "key", "value", "pairs", "." ]
def parse_head(fileobj): """Return a list of key, value pairs.""" p = HTTPEquivParser(fileobj.read(4096)) return p()
[ "def", "parse_head", "(", "fileobj", ")", ":", "p", "=", "HTTPEquivParser", "(", "fileobj", ".", "read", "(", "4096", ")", ")", "return", "p", "(", ")" ]
https://github.com/python-mechanize/mechanize/blob/3cd4d19ee701d9aa458fa23b7515c268d3f1cef0/mechanize/_http.py#L34-L37
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
source/addons/im_chat/im_chat.py
python
im_chat_session.add_user
(self, cr, uid, uuid, user_id, context=None)
add the given user to the given session
add the given user to the given session
[ "add", "the", "given", "user", "to", "the", "given", "session" ]
def add_user(self, cr, uid, uuid, user_id, context=None): """ add the given user to the given session """ sids = self.search(cr, uid, [('uuid', '=', uuid)], context=context, limit=1) for session in self.browse(cr, uid, sids, context=context): if user_id not in [u.id for u in session.user_ids]: self.write(cr, uid, [session.id], {'user_ids': [(4, user_id)]}, context=context) # notify the all the channel users and anonymous channel notifications = [] for channel_user_id in session.user_ids: info = self.session_info(cr, channel_user_id.id, [session.id], context=context) notifications.append([(cr.dbname, 'im_chat.session', channel_user_id.id), info]) # Anonymous are not notified when a new user is added : cannot exec session_info as uid = None info = self.session_info(cr, openerp.SUPERUSER_ID, [session.id], context=context) notifications.append([session.uuid, info]) self.pool['bus.bus'].sendmany(cr, uid, notifications) # send a message to the conversation user = self.pool['res.users'].read(cr, uid, user_id, ['name'], context=context) self.pool["im_chat.message"].post(cr, uid, uid, session.uuid, "meta", user['name'] + " joined the conversation.", context=context)
[ "def", "add_user", "(", "self", ",", "cr", ",", "uid", ",", "uuid", ",", "user_id", ",", "context", "=", "None", ")", ":", "sids", "=", "self", ".", "search", "(", "cr", ",", "uid", ",", "[", "(", "'uuid'", ",", "'='", ",", "uuid", ")", "]", ...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/source/addons/im_chat/im_chat.py#L117-L134
bslatkin/effectivepython
4ae6f3141291ea137eb29a245bf889dbc8091713
example_code/item_20.py
python
careful_divide
(a: float, b: float)
Divides a by b. Raises: ValueError: When the inputs cannot be divided.
Divides a by b.
[ "Divides", "a", "by", "b", "." ]
def careful_divide(a: float, b: float) -> float: """Divides a by b. Raises: ValueError: When the inputs cannot be divided. """ try: return a / b except ZeroDivisionError as e: raise ValueError('Invalid inputs')
[ "def", "careful_divide", "(", "a", ":", "float", ",", "b", ":", "float", ")", "->", "float", ":", "try", ":", "return", "a", "/", "b", "except", "ZeroDivisionError", "as", "e", ":", "raise", "ValueError", "(", "'Invalid inputs'", ")" ]
https://github.com/bslatkin/effectivepython/blob/4ae6f3141291ea137eb29a245bf889dbc8091713/example_code/item_20.py#L126-L135
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/storage/memory_mixins/paged_memory/pages/list_page.py
python
ListPage._resolve_range
(mo: SimMemoryObject, page_addr: int, page_size)
return start, end
[]
def _resolve_range(mo: SimMemoryObject, page_addr: int, page_size) -> Tuple[int,int]: start = max(mo.base, page_addr) end = min(mo.last_addr + 1, page_addr + page_size) if end <= start: l.warning("Nothing left of the memory object to store in SimPage.") return start, end
[ "def", "_resolve_range", "(", "mo", ":", "SimMemoryObject", ",", "page_addr", ":", "int", ",", "page_size", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "start", "=", "max", "(", "mo", ".", "base", ",", "page_addr", ")", "end", "=", "min", ...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/storage/memory_mixins/paged_memory/pages/list_page.py#L294-L299
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/ext/mapreduce/output_writers.py
python
OutputWriter.finalize
(self, ctx, shard_state)
Finalize writer shard-level state. This should only be called when shard_state.result_status shows success. After finalizing the outputs, it should save per-shard output file info into shard_state.writer_state so that other operations can find the outputs. Args: ctx: an instance of context.Context. shard_state: shard state. ShardState.writer_state can be modified.
Finalize writer shard-level state.
[ "Finalize", "writer", "shard", "-", "level", "state", "." ]
def finalize(self, ctx, shard_state): """Finalize writer shard-level state. This should only be called when shard_state.result_status shows success. After finalizing the outputs, it should save per-shard output file info into shard_state.writer_state so that other operations can find the outputs. Args: ctx: an instance of context.Context. shard_state: shard state. ShardState.writer_state can be modified. """ raise NotImplementedError("finalize() not implemented in %s" % self.__class__)
[ "def", "finalize", "(", "self", ",", "ctx", ",", "shard_state", ")", ":", "raise", "NotImplementedError", "(", "\"finalize() not implemented in %s\"", "%", "self", ".", "__class__", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/ext/mapreduce/output_writers.py#L213-L226