nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
Azure/azure-cli
6c1b085a0910c6c2139006fcbd8ade44006eb6dd
src/azure-cli/azure/cli/command_modules/batch/_command_type.py
python
BatchArgumentTree._is_silent
(self, name)
return arg['path'] in pformat.SILENT_PARAMETERS or full_path in pformat.SILENT_PARAMETERS
Whether argument should not be exposed
Whether argument should not be exposed
[ "Whether", "argument", "should", "not", "be", "exposed" ]
def _is_silent(self, name): """Whether argument should not be exposed""" arg = self._arg_tree[name] full_path = full_name(arg) return arg['path'] in pformat.SILENT_PARAMETERS or full_path in pformat.SILENT_PARAMETERS
[ "def", "_is_silent", "(", "self", ",", "name", ")", ":", "arg", "=", "self", ".", "_arg_tree", "[", "name", "]", "full_path", "=", "full_name", "(", "arg", ")", "return", "arg", "[", "'path'", "]", "in", "pformat", ".", "SILENT_PARAMETERS", "or", "full...
https://github.com/Azure/azure-cli/blob/6c1b085a0910c6c2139006fcbd8ade44006eb6dd/src/azure-cli/azure/cli/command_modules/batch/_command_type.py#L202-L206
tenzir/threatbus
a26096e7b61b3eddf25c445d40a6cd2ea4420558
plugins/backbones/threatbus_rabbitmq/threatbus_rabbitmq/plugin.py
python
provision
( topic: str, msg: Union[Indicator, Sighting, SnapshotEnvelope, SnapshotRequest] )
Provisions the given `msg` to all subscribers of `topic`. @param topic The topic string to use for provisioning @param msg The message to provision
Provisions the given `msg` to all subscribers of `topic`.
[ "Provisions", "the", "given", "msg", "to", "all", "subscribers", "of", "topic", "." ]
def provision( topic: str, msg: Union[Indicator, Sighting, SnapshotEnvelope, SnapshotRequest] ): """ Provisions the given `msg` to all subscribers of `topic`. @param topic The topic string to use for provisioning @param msg The message to provision """ global subscriptions, lock, logger lock.acquire() for t in filter(lambda t: str(topic).startswith(str(t)), subscriptions.keys()): for outq in subscriptions[t]: outq.put(msg) lock.release() logger.debug(f"Relayed message from RabbitMQ: {msg}")
[ "def", "provision", "(", "topic", ":", "str", ",", "msg", ":", "Union", "[", "Indicator", ",", "Sighting", ",", "SnapshotEnvelope", ",", "SnapshotRequest", "]", ")", ":", "global", "subscriptions", ",", "lock", ",", "logger", "lock", ".", "acquire", "(", ...
https://github.com/tenzir/threatbus/blob/a26096e7b61b3eddf25c445d40a6cd2ea4420558/plugins/backbones/threatbus_rabbitmq/threatbus_rabbitmq/plugin.py#L24-L38
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/server/portal/portalsessionhandler.py
python
PortalSessionHandler.data_out
(self, session, **kwargs)
Called by server for having the portal relay messages and data to the correct session protocol. Args: session (Session): Session sending data. Keyword Args: kwargs (any): Each key is a command instruction to the protocol on the form key = [[args],{kwargs}]. This will call a method send_<key> on the protocol. If no such method exixts, it sends the data to a method send_default.
Called by server for having the portal relay messages and data to the correct session protocol.
[ "Called", "by", "server", "for", "having", "the", "portal", "relay", "messages", "and", "data", "to", "the", "correct", "session", "protocol", "." ]
def data_out(self, session, **kwargs): """ Called by server for having the portal relay messages and data to the correct session protocol. Args: session (Session): Session sending data. Keyword Args: kwargs (any): Each key is a command instruction to the protocol on the form key = [[args],{kwargs}]. This will call a method send_<key> on the protocol. If no such method exixts, it sends the data to a method send_default. """ # from evennia.server.profiling.timetrace import timetrace # DEBUG # text = timetrace(text, "portalsessionhandler.data_out") # DEBUG # distribute outgoing data to the correct session methods. if session: for cmdname, (cmdargs, cmdkwargs) in kwargs.items(): funcname = "send_%s" % cmdname.strip().lower() if hasattr(session, funcname): # better to use hassattr here over try..except # - avoids hiding AttributeErrors in the call. try: getattr(session, funcname)(*cmdargs, **cmdkwargs) except Exception: log_trace() else: try: # note that send_default always takes cmdname # as arg too. session.send_default(cmdname, *cmdargs, **cmdkwargs) except Exception: log_trace()
[ "def", "data_out", "(", "self", ",", "session", ",", "*", "*", "kwargs", ")", ":", "# from evennia.server.profiling.timetrace import timetrace # DEBUG", "# text = timetrace(text, \"portalsessionhandler.data_out\") # DEBUG", "# distribute outgoing data to the correct session methods.", ...
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/server/portal/portalsessionhandler.py#L428-L463
osirislab/CTF-Solutions
bc0650f327823c1511b31f4d9bcda35248f2fb34
BkP2017/rsa-buffet/Arithmetic.py
python
bitlength
(x)
return n
Calculates the bitlength of x
Calculates the bitlength of x
[ "Calculates", "the", "bitlength", "of", "x" ]
def bitlength(x): ''' Calculates the bitlength of x ''' assert x >= 0 n = 0 while x > 0: n = n+1 x = x>>1 return n
[ "def", "bitlength", "(", "x", ")", ":", "assert", "x", ">=", "0", "n", "=", "0", "while", "x", ">", "0", ":", "n", "=", "n", "+", "1", "x", "=", "x", ">>", "1", "return", "n" ]
https://github.com/osirislab/CTF-Solutions/blob/bc0650f327823c1511b31f4d9bcda35248f2fb34/BkP2017/rsa-buffet/Arithmetic.py#L44-L53
apache/libcloud
90971e17bfd7b6bb97b2489986472c531cc8e140
libcloud/compute/drivers/outscale.py
python
OutscaleNodeDriver.ex_list_nets_access_points
( self, net_access_point_ids: List[str] = None, net_ids: List[str] = None, service_names: List[str] = None, states: List[str] = None, tag_keys: List[str] = None, tag_values: List[str] = None, tags: List[str] = None, dry_run: bool = False, )
return response.json()
Describes one or more Net access points. :param net_access_point_ids: The IDs of the Net access points. :type net_access_point_ids: ``list`` of ``str`` :param net_ids: The IDs of the Nets. :type net_ids: ``list`` of ``str`` :param service_names: The The names of the prefix lists corresponding to the services. For more information, see DescribePrefixLists: https://docs.outscale.com/api#describeprefixlists :type service_names: ``list`` of ``str`` :param states: The states of the Net access points (pending | available | deleting | deleted). :type states: ``list`` of ``str`` :param tag_keys: The keys of the tags associated with the Net access points. :type tag_keys: ``list`` of ``str`` :param tag_values: The values of the tags associated with the Net access points. :type tag_values: ``list`` of ``str`` :param tags: The key/value combination of the tags associated with the Net access points, in the following format: "Filters":{"Tags":["TAGKEY=TAGVALUE"]}. :type tags: ``list`` of ``str`` :param dry_run: If true, checks whether you have the required permissions to perform the action. :type dry_run: ``bool`` :return: A list of Net Access Points :rtype: ``list`` of ``dict``
Describes one or more Net access points.
[ "Describes", "one", "or", "more", "Net", "access", "points", "." ]
def ex_list_nets_access_points( self, net_access_point_ids: List[str] = None, net_ids: List[str] = None, service_names: List[str] = None, states: List[str] = None, tag_keys: List[str] = None, tag_values: List[str] = None, tags: List[str] = None, dry_run: bool = False, ): """ Describes one or more Net access points. :param net_access_point_ids: The IDs of the Net access points. :type net_access_point_ids: ``list`` of ``str`` :param net_ids: The IDs of the Nets. :type net_ids: ``list`` of ``str`` :param service_names: The The names of the prefix lists corresponding to the services. For more information, see DescribePrefixLists: https://docs.outscale.com/api#describeprefixlists :type service_names: ``list`` of ``str`` :param states: The states of the Net access points (pending | available | deleting | deleted). :type states: ``list`` of ``str`` :param tag_keys: The keys of the tags associated with the Net access points. :type tag_keys: ``list`` of ``str`` :param tag_values: The values of the tags associated with the Net access points. :type tag_values: ``list`` of ``str`` :param tags: The key/value combination of the tags associated with the Net access points, in the following format: "Filters":{"Tags":["TAGKEY=TAGVALUE"]}. :type tags: ``list`` of ``str`` :param dry_run: If true, checks whether you have the required permissions to perform the action. :type dry_run: ``bool`` :return: A list of Net Access Points :rtype: ``list`` of ``dict`` """ action = "ReadNetAccessPoints" data = {"DryRun": dry_run, "Filters": {}} if net_access_point_ids is not None: data["Filters"].update({"NetAccessPointIds": net_access_point_ids}) if net_ids is not None: data["Filters"].update({"NetIds": net_ids}) if service_names is not None: data["Filters"].update({"ServiceNames": service_names}) if states is not None: data["Filters"].update({"States": states}) if tag_keys is not None: data["Filters"].update({"TagKeys": tag_keys}) if tag_values is not None: data["Filters"].update({"TagValues": tag_values}) if tags is not None: data["Filters"].update({"Tags": tags}) response = self._call_api(action, json.dumps(data)) if response.status_code == 200: return response.json()["NetAccessPoints"] return response.json()
[ "def", "ex_list_nets_access_points", "(", "self", ",", "net_access_point_ids", ":", "List", "[", "str", "]", "=", "None", ",", "net_ids", ":", "List", "[", "str", "]", "=", "None", ",", "service_names", ":", "List", "[", "str", "]", "=", "None", ",", "...
https://github.com/apache/libcloud/blob/90971e17bfd7b6bb97b2489986472c531cc8e140/libcloud/compute/drivers/outscale.py#L4913-L4982
bobbui/json-logging-python
efbe367527203a88e0fec9f81ccb2f1e9252b1bf
json_logging/framework_base.py
python
BaseResponseInfoExtractor.get_content_type
(self, response)
get response's MIME/media type :param response: response object
get response's MIME/media type
[ "get", "response", "s", "MIME", "/", "media", "type" ]
def get_content_type(self, response): """ get response's MIME/media type :param response: response object """ raise NotImplementedError
[ "def", "get_content_type", "(", "self", ",", "response", ")", ":", "raise", "NotImplementedError" ]
https://github.com/bobbui/json-logging-python/blob/efbe367527203a88e0fec9f81ccb2f1e9252b1bf/json_logging/framework_base.py#L151-L157
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/_php_runtime.py
python
_run_file
(file_path, globals_, script_dir=_SCRIPT_DIR)
Execute the file at the specified path with the passed-in globals.
Execute the file at the specified path with the passed-in globals.
[ "Execute", "the", "file", "at", "the", "specified", "path", "with", "the", "passed", "-", "in", "globals", "." ]
def _run_file(file_path, globals_, script_dir=_SCRIPT_DIR): """Execute the file at the specified path with the passed-in globals.""" script_name = os.path.basename(file_path) sys.path = _SYS_PATH_ADDITIONS[script_name] + sys.path if 'google' in sys.modules: del sys.modules['google'] script_dir = _SCRIPT_TO_DIR.get(script_name, script_dir) script_name = _BOOTSTAP_NAME_TO_REAL_NAME.get(script_name, script_name) script_path = os.path.join(script_dir, script_name) execfile(script_path, globals_)
[ "def", "_run_file", "(", "file_path", ",", "globals_", ",", "script_dir", "=", "_SCRIPT_DIR", ")", ":", "script_name", "=", "os", ".", "path", ".", "basename", "(", "file_path", ")", "sys", ".", "path", "=", "_SYS_PATH_ADDITIONS", "[", "script_name", "]", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/_php_runtime.py#L176-L193
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/qark/qark/lib/plyj/parser.py
python
ClassParser.p_formal_parameter_list_opt2
(self, p)
formal_parameter_list_opt : empty
formal_parameter_list_opt : empty
[ "formal_parameter_list_opt", ":", "empty" ]
def p_formal_parameter_list_opt2(self, p): '''formal_parameter_list_opt : empty''' p[0] = []
[ "def", "p_formal_parameter_list_opt2", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "[", "]" ]
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/qark/qark/lib/plyj/parser.py#L1488-L1490
chen3feng/blade-build
360b4c9ddb9087fb811af3aef2830301cf48805e
src/blade/target_tags.py
python
_convert_expression
(expr, func_name)
return ''.join(tokens), None
Convert a filter expression into a python expression.
Convert a filter expression into a python expression.
[ "Convert", "a", "filter", "expression", "into", "a", "python", "expression", "." ]
def _convert_expression(expr, func_name): """Convert a filter expression into a python expression.""" tokens = [] stack = [] for pos, token in _token_iter(expr): if token is None: error = 'Invalid expression: "%s"' % expr[pos:] return None, error if token.isspace(): continue if token == '(': tokens.append(token) stack.append(('(', pos)) elif token == ')': if stack: tokens.append(token) stack.pop() else: error = 'Unbalanced ")": "%s"' % (expr[pos:]) return None, error elif token in ('not', 'and', 'or'): tokens.append(' %s ' % token) else: scope, names = token.split(':') names = names.split(',') args = ', '.join(['"%s:%s"' % (scope, name) for name in names]) tokens.append('%s(%s)' % (func_name, args)) if stack: error = 'Unbalanced "(": "%s"' % expr[stack[-1][1]:] return None, error return ''.join(tokens), None
[ "def", "_convert_expression", "(", "expr", ",", "func_name", ")", ":", "tokens", "=", "[", "]", "stack", "=", "[", "]", "for", "pos", ",", "token", "in", "_token_iter", "(", "expr", ")", ":", "if", "token", "is", "None", ":", "error", "=", "'Invalid ...
https://github.com/chen3feng/blade-build/blob/360b4c9ddb9087fb811af3aef2830301cf48805e/src/blade/target_tags.py#L39-L70
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
nltk/featstruct.py
python
Feature.display
(self)
return self._display
Custom display location: can be prefix, or slash.
Custom display location: can be prefix, or slash.
[ "Custom", "display", "location", ":", "can", "be", "prefix", "or", "slash", "." ]
def display(self): """Custom display location: can be prefix, or slash.""" return self._display
[ "def", "display", "(", "self", ")", ":", "return", "self", ".", "_display" ]
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/featstruct.py#L1809-L1811
exodrifter/unity-python
bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d
Lib/lib2to3/pytree.py
python
Node.pre_order
(self)
Return a pre-order iterator for the tree.
Return a pre-order iterator for the tree.
[ "Return", "a", "pre", "-", "order", "iterator", "for", "the", "tree", "." ]
def pre_order(self): """Return a pre-order iterator for the tree.""" yield self for child in self.children: for node in child.pre_order(): yield node
[ "def", "pre_order", "(", "self", ")", ":", "yield", "self", "for", "child", "in", "self", ".", "children", ":", "for", "node", "in", "child", ".", "pre_order", "(", ")", ":", "yield", "node" ]
https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/lib2to3/pytree.py#L301-L306
glitchdotcom/WebPutty
4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7
ziplibs/flask/app.py
python
Flask.create_url_adapter
(self, request)
return self.url_map.bind_to_environ(request.environ, server_name=self.config['SERVER_NAME'])
Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. .. versionadded:: 0.6
Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly.
[ "Creates", "a", "URL", "adapter", "for", "the", "given", "request", ".", "The", "URL", "adapter", "is", "created", "at", "a", "point", "where", "the", "request", "context", "is", "not", "yet", "set", "up", "so", "the", "request", "is", "passed", "explici...
def create_url_adapter(self, request): """Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. .. versionadded:: 0.6 """ return self.url_map.bind_to_environ(request.environ, server_name=self.config['SERVER_NAME'])
[ "def", "create_url_adapter", "(", "self", ",", "request", ")", ":", "return", "self", ".", "url_map", ".", "bind_to_environ", "(", "request", ".", "environ", ",", "server_name", "=", "self", ".", "config", "[", "'SERVER_NAME'", "]", ")" ]
https://github.com/glitchdotcom/WebPutty/blob/4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7/ziplibs/flask/app.py#L747-L755
deepjyoti30/ytmdl
0227541f303739a01e27a6d74499229d9bf44f84
ytmdl/yt.py
python
get_youtube_streams
(url)
return url
Get both audio & video stream urls for youtube using youtube-dl. PS: I don't know how youtube-dl does the magic
Get both audio & video stream urls for youtube using youtube-dl.
[ "Get", "both", "audio", "&", "video", "stream", "urls", "for", "youtube", "using", "youtube", "-", "dl", "." ]
def get_youtube_streams(url): """Get both audio & video stream urls for youtube using youtube-dl. PS: I don't know how youtube-dl does the magic """ cli = "youtube-dl -g {}".format(url) output, error = utility.exe(cli) stream_urls = output.split("\n") url = stream_urls[1] return url
[ "def", "get_youtube_streams", "(", "url", ")", ":", "cli", "=", "\"youtube-dl -g {}\"", ".", "format", "(", "url", ")", "output", ",", "error", "=", "utility", ".", "exe", "(", "cli", ")", "stream_urls", "=", "output", ".", "split", "(", "\"\\n\"", ")", ...
https://github.com/deepjyoti30/ytmdl/blob/0227541f303739a01e27a6d74499229d9bf44f84/ytmdl/yt.py#L24-L34
kovidgoyal/calibre
2b41671370f2a9eb1109b9ae901ccf915f1bd0c8
src/calibre/devices/winusb.py
python
get_usb_info
(usbdev, debug=False)
return ans
The USB info (manufacturer/product names and serial number) Requires communication with the hub the device is connected to. :param usbdev: A usb device as returned by :function:`scan_usb_devices`
The USB info (manufacturer/product names and serial number) Requires communication with the hub the device is connected to.
[ "The", "USB", "info", "(", "manufacturer", "/", "product", "names", "and", "serial", "number", ")", "Requires", "communication", "with", "the", "hub", "the", "device", "is", "connected", "to", "." ]
def get_usb_info(usbdev, debug=False): # {{{ ''' The USB info (manufacturer/product names and serial number) Requires communication with the hub the device is connected to. :param usbdev: A usb device as returned by :function:`scan_usb_devices` ''' ans = {} hub_map = {devinfo.DevInst:path for devinfo, path in DeviceSet(guid=GUID_DEVINTERFACE_USB_HUB).interfaces()} for parent in iterancestors(usbdev.devinst): parent_path = hub_map.get(parent) if parent_path is not None: break else: if debug: prints('Cannot get USB info as parent of device is not a HUB or device has no parent (was probably disconnected)') return ans for devlist, devinfo in DeviceSet(guid=GUID_DEVINTERFACE_USB_DEVICE).devices(): if devinfo.DevInst == usbdev.devinst: device_port = get_device_registry_property(devlist, byref(devinfo), SPDRP_ADDRESS)[1] break else: return ans if not device_port: if debug: prints('Cannot get usb info as the SPDRP_ADDRESS property is not present in the registry (can happen with broken USB hub drivers)') return ans handle = CreateFile(parent_path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, None, OPEN_EXISTING, 0, None) try: buf, dd = get_device_descriptor(handle, device_port) if dd.idVendor == usbdev.vendor_id and dd.idProduct == usbdev.product_id and dd.bcdDevice == usbdev.bcd: # Dont need to read language since we only care about english names # buf, langs = get_device_languages(handle, device_port) # print(111, langs) for index, name in ((dd.iManufacturer, 'manufacturer'), (dd.iProduct, 'product'), (dd.iSerialNumber, 'serial_number')): if index: try: buf, ans[name] = get_device_string(handle, device_port, index, buf=buf) except OSError as err: if debug: # Note that I have observed that this fails # randomly after some time of my Kindle being # connected. Disconnecting and reconnecting causes # it to start working again. prints('Failed to read %s from device, with error: [%d] %s' % (name, err.winerror, as_unicode(err))) finally: CloseHandle(handle) return ans
[ "def", "get_usb_info", "(", "usbdev", ",", "debug", "=", "False", ")", ":", "# {{{", "ans", "=", "{", "}", "hub_map", "=", "{", "devinfo", ".", "DevInst", ":", "path", "for", "devinfo", ",", "path", "in", "DeviceSet", "(", "guid", "=", "GUID_DEVINTERFA...
https://github.com/kovidgoyal/calibre/blob/2b41671370f2a9eb1109b9ae901ccf915f1bd0c8/src/calibre/devices/winusb.py#L879-L925
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/nova/nova/compute/cells_api.py
python
ComputeCellsAPI._cell_read_only
(self, cell_name)
return False
Is the target cell in a read-only mode?
Is the target cell in a read-only mode?
[ "Is", "the", "target", "cell", "in", "a", "read", "-", "only", "mode?" ]
def _cell_read_only(self, cell_name): """Is the target cell in a read-only mode?""" # FIXME(comstud): Add support for this. return False
[ "def", "_cell_read_only", "(", "self", ",", "cell_name", ")", ":", "# FIXME(comstud): Add support for this.", "return", "False" ]
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/compute/cells_api.py#L97-L100
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
docker/oso-host-monitoring/src/vendor/prometheus_client/core.py
python
_LabelWrapper.labels
(self, *labelvalues)
Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels('get', '/').inc() c.labels('post', '/submit').inc() Labels can also be provided as a dict: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels({'method': 'get', 'endpoint': '/'}).inc() c.labels({'method': 'post', 'endpoint': '/submit'}).inc() See the best practices on [naming](http://prometheus.io/docs/practices/naming/) and [labels](http://prometheus.io/docs/practices/instrumentation/#use-labels).
Return the child for the given labelset.
[ "Return", "the", "child", "for", "the", "given", "labelset", "." ]
def labels(self, *labelvalues): '''Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels('get', '/').inc() c.labels('post', '/submit').inc() Labels can also be provided as a dict: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels({'method': 'get', 'endpoint': '/'}).inc() c.labels({'method': 'post', 'endpoint': '/submit'}).inc() See the best practices on [naming](http://prometheus.io/docs/practices/naming/) and [labels](http://prometheus.io/docs/practices/instrumentation/#use-labels). ''' if len(labelvalues) == 1 and type(labelvalues[0]) == dict: if sorted(labelvalues[0].keys()) != sorted(self._labelnames): raise ValueError('Incorrect label names') labelvalues = tuple([unicode(labelvalues[0][l]) for l in self._labelnames]) else: if len(labelvalues) != len(self._labelnames): raise ValueError('Incorrect label count') labelvalues = tuple([unicode(l) for l in labelvalues]) with self._lock: if labelvalues not in self._metrics: self._metrics[labelvalues] = self._wrappedClass(self._name, self._labelnames, labelvalues, **self._kwargs) return self._metrics[labelvalues]
[ "def", "labels", "(", "self", ",", "*", "labelvalues", ")", ":", "if", "len", "(", "labelvalues", ")", "==", "1", "and", "type", "(", "labelvalues", "[", "0", "]", ")", "==", "dict", ":", "if", "sorted", "(", "labelvalues", "[", "0", "]", ".", "k...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/docker/oso-host-monitoring/src/vendor/prometheus_client/core.py#L256-L290
chaostoolkit/chaostoolkit-kubernetes
4fe9b65209d849efd4c97e99d9eb31fde38a8c84
chaosk8s/crd/actions.py
python
replace_custom_object
( group: str, version: str, plural: str, name: str, ns: str = "default", force: bool = False, resource: Dict[str, Any] = None, resource_as_yaml_file: str = None, secrets: Secrets = None, )
Replace a custom object in the given namespace. The resource must be the new version to apply. Read more about custom resources here: https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/
Replace a custom object in the given namespace. The resource must be the new version to apply.
[ "Replace", "a", "custom", "object", "in", "the", "given", "namespace", ".", "The", "resource", "must", "be", "the", "new", "version", "to", "apply", "." ]
def replace_custom_object( group: str, version: str, plural: str, name: str, ns: str = "default", force: bool = False, resource: Dict[str, Any] = None, resource_as_yaml_file: str = None, secrets: Secrets = None, ) -> Dict[str, Any]: """ Replace a custom object in the given namespace. The resource must be the new version to apply. Read more about custom resources here: https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/ """ # noqa: E501 api = client.CustomObjectsApi(create_k8s_api_client(secrets)) body = load_body(resource, resource_as_yaml_file) try: r = api.replace_namespaced_custom_object( group, version, ns, plural, name, body, force=force, _preload_content=False ) return json.loads(r.data) except ApiException as x: raise ActivityFailed( f"Failed to replace custom resource object: '{x.reason}' {x.body}" )
[ "def", "replace_custom_object", "(", "group", ":", "str", ",", "version", ":", "str", ",", "plural", ":", "str", ",", "name", ":", "str", ",", "ns", ":", "str", "=", "\"default\"", ",", "force", ":", "bool", "=", "False", ",", "resource", ":", "Dict"...
https://github.com/chaostoolkit/chaostoolkit-kubernetes/blob/4fe9b65209d849efd4c97e99d9eb31fde38a8c84/chaosk8s/crd/actions.py#L175-L204
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
openM
(*args)
return _idaapi.openM(*args)
openM(file) -> FILE *
openM(file) -> FILE *
[ "openM", "(", "file", ")", "-", ">", "FILE", "*" ]
def openM(*args): """ openM(file) -> FILE * """ return _idaapi.openM(*args)
[ "def", "openM", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "openM", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L25344-L25348
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/django/core/management/commands/shell.py
python
Command._ipython_pre_100
(self)
Start IPython pre-1.0.0
Start IPython pre-1.0.0
[ "Start", "IPython", "pre", "-", "1", ".", "0", ".", "0" ]
def _ipython_pre_100(self): """Start IPython pre-1.0.0""" from IPython.frontend.terminal.ipapp import TerminalIPythonApp app = TerminalIPythonApp.instance() app.initialize(argv=[]) app.start()
[ "def", "_ipython_pre_100", "(", "self", ")", ":", "from", "IPython", ".", "frontend", ".", "terminal", ".", "ipapp", "import", "TerminalIPythonApp", "app", "=", "TerminalIPythonApp", ".", "instance", "(", ")", "app", ".", "initialize", "(", "argv", "=", "[",...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/core/management/commands/shell.py#L28-L33
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/gridspec.py
python
GridSpecBase.set_height_ratios
(self, height_ratios)
Set the relative heights of the rows. *height_ratios* must be of length *nrows*. Each row gets a relative height of ``height_ratios[i] / sum(height_ratios)``.
Set the relative heights of the rows.
[ "Set", "the", "relative", "heights", "of", "the", "rows", "." ]
def set_height_ratios(self, height_ratios): """ Set the relative heights of the rows. *height_ratios* must be of length *nrows*. Each row gets a relative height of ``height_ratios[i] / sum(height_ratios)``. """ if height_ratios is None: height_ratios = [1] * self._nrows elif len(height_ratios) != self._nrows: raise ValueError('Expected the given number of height ratios to ' 'match the number of rows of the grid') self._row_height_ratios = height_ratios
[ "def", "set_height_ratios", "(", "self", ",", "height_ratios", ")", ":", "if", "height_ratios", "is", "None", ":", "height_ratios", "=", "[", "1", "]", "*", "self", ".", "_nrows", "elif", "len", "(", "height_ratios", ")", "!=", "self", ".", "_nrows", ":"...
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/gridspec.py#L123-L135
py2neo-org/py2neo
2e46bbf4d622f53282e796ffc521fc4bc6d0b60d
py2neo/__init__.py
python
ConnectionProfile.host
(self)
return self.address.host
The host name or IP address of the remote server. If unspecified, and uninfluenced by environment variables, this will default to ``'localhost'``.
The host name or IP address of the remote server. If unspecified, and uninfluenced by environment variables, this will default to ``'localhost'``.
[ "The", "host", "name", "or", "IP", "address", "of", "the", "remote", "server", ".", "If", "unspecified", "and", "uninfluenced", "by", "environment", "variables", "this", "will", "default", "to", "localhost", "." ]
def host(self): """ The host name or IP address of the remote server. If unspecified, and uninfluenced by environment variables, this will default to ``'localhost'``. """ return self.address.host
[ "def", "host", "(", "self", ")", ":", "return", "self", ".", "address", ".", "host" ]
https://github.com/py2neo-org/py2neo/blob/2e46bbf4d622f53282e796ffc521fc4bc6d0b60d/py2neo/__init__.py#L375-L380
beerfactory/hbmqtt
07c4c70f061003f208ad7e510b6e8fce4d7b3a6c
hbmqtt/version.py
python
get_version
(version=None)
return str(main + sub)
Returns a PEP 386-compliant version number from VERSION.
Returns a PEP 386-compliant version number from VERSION.
[ "Returns", "a", "PEP", "386", "-", "compliant", "version", "number", "from", "VERSION", "." ]
def get_version(version=None): "Returns a PEP 386-compliant version number from VERSION." if version is None: from hbmqtt import VERSION as version else: assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases parts = 2 if version[2] == 0 else 3 main = '.'.join(str(x) for x in version[:parts]) sub = '' if version[3] == 'alpha' and version[4] == 0: git_changeset = get_git_changeset() if git_changeset: sub = '.dev%s' % git_changeset elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[version[3]] + str(version[4]) return str(main + sub)
[ "def", "get_version", "(", "version", "=", "None", ")", ":", "if", "version", "is", "None", ":", "from", "hbmqtt", "import", "VERSION", "as", "version", "else", ":", "assert", "len", "(", "version", ")", "==", "5", "assert", "version", "[", "3", "]", ...
https://github.com/beerfactory/hbmqtt/blob/07c4c70f061003f208ad7e510b6e8fce4d7b3a6c/hbmqtt/version.py#L10-L36
HypoX64/DeepMosaics
b311aaac319439a0a1e8004b4a64c4222c55f38c
util/data.py
python
normalize
(data)
return (data.astype(np.float32)/255.0-0.5)/0.5
normalize to -1 ~ 1
normalize to -1 ~ 1
[ "normalize", "to", "-", "1", "~", "1" ]
def normalize(data): ''' normalize to -1 ~ 1 ''' return (data.astype(np.float32)/255.0-0.5)/0.5
[ "def", "normalize", "(", "data", ")", ":", "return", "(", "data", ".", "astype", "(", "np", ".", "float32", ")", "/", "255.0", "-", "0.5", ")", "/", "0.5" ]
https://github.com/HypoX64/DeepMosaics/blob/b311aaac319439a0a1e8004b4a64c4222c55f38c/util/data.py#L17-L21
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/whoosh/query/qcore.py
python
Query.estimate_size
(self, ixreader)
Returns an estimate of how many documents this query could potentially match (for example, the estimated size of a simple term query is the document frequency of the term). It is permissible to overestimate, but not to underestimate.
Returns an estimate of how many documents this query could potentially match (for example, the estimated size of a simple term query is the document frequency of the term). It is permissible to overestimate, but not to underestimate.
[ "Returns", "an", "estimate", "of", "how", "many", "documents", "this", "query", "could", "potentially", "match", "(", "for", "example", "the", "estimated", "size", "of", "a", "simple", "term", "query", "is", "the", "document", "frequency", "of", "the", "term...
def estimate_size(self, ixreader): """Returns an estimate of how many documents this query could potentially match (for example, the estimated size of a simple term query is the document frequency of the term). It is permissible to overestimate, but not to underestimate. """ raise NotImplementedError
[ "def", "estimate_size", "(", "self", ",", "ixreader", ")", ":", "raise", "NotImplementedError" ]
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/whoosh/query/qcore.py#L486-L492
robhagemans/pcbasic
c3a043b46af66623a801e18a38175be077251ada
docsrc/man.py
python
makeman
()
Convert HTML sources to manfile.
Convert HTML sources to manfile.
[ "Convert", "HTML", "sources", "to", "manfile", "." ]
def makeman(): """Convert HTML sources to manfile.""" title_html = '<h1>pcbasic</h1><p>%s</p>\n' % SETUP_DATA['description'] desc_html = '<h3>Description</h2><p>%s</p>\n' % SETUP_DATA['long_description'] options_html = open(OPTIONS_HTML).read() examples_html = open(EXAMPLE_HTML).read() more_html = open(MORE_HTML).read() man_html = ''.join((title_html, desc_html, options_html, examples_html, more_html)) try: os.mkdir(DOC_PATH) except EnvironmentError: # already there, ignore pass # output manfile with gzip.open(MAN_FILE, 'w') as manfile: manfile.write(_html_to_man(man_html).encode('utf-8'))
[ "def", "makeman", "(", ")", ":", "title_html", "=", "'<h1>pcbasic</h1><p>%s</p>\\n'", "%", "SETUP_DATA", "[", "'description'", "]", "desc_html", "=", "'<h3>Description</h2><p>%s</p>\\n'", "%", "SETUP_DATA", "[", "'long_description'", "]", "options_html", "=", "open", ...
https://github.com/robhagemans/pcbasic/blob/c3a043b46af66623a801e18a38175be077251ada/docsrc/man.py#L84-L99
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/combinatorics/fp_groups.py
python
simplify_presentation
(*args, change_gens=False)
return gens, rels
For an instance of `FpGroup`, return a simplified isomorphic copy of the group (e.g. remove redundant generators or relators). Alternatively, a list of generators and relators can be passed in which case the simplified lists will be returned. By default, the generators of the group are unchanged. If you would like to remove redundant generators, set the keyword argument `change_gens = True`.
For an instance of `FpGroup`, return a simplified isomorphic copy of the group (e.g. remove redundant generators or relators). Alternatively, a list of generators and relators can be passed in which case the simplified lists will be returned.
[ "For", "an", "instance", "of", "FpGroup", "return", "a", "simplified", "isomorphic", "copy", "of", "the", "group", "(", "e", ".", "g", ".", "remove", "redundant", "generators", "or", "relators", ")", ".", "Alternatively", "a", "list", "of", "generators", "...
def simplify_presentation(*args, change_gens=False): ''' For an instance of `FpGroup`, return a simplified isomorphic copy of the group (e.g. remove redundant generators or relators). Alternatively, a list of generators and relators can be passed in which case the simplified lists will be returned. By default, the generators of the group are unchanged. If you would like to remove redundant generators, set the keyword argument `change_gens = True`. ''' if len(args) == 1: if not isinstance(args[0], FpGroup): raise TypeError("The argument must be an instance of FpGroup") G = args[0] gens, rels = simplify_presentation(G.generators, G.relators, change_gens=change_gens) if gens: return FpGroup(gens[0].group, rels) return FpGroup(FreeGroup([]), []) elif len(args) == 2: gens, rels = args[0][:], args[1][:] if not gens: return gens, rels identity = gens[0].group.identity else: if len(args) == 0: m = "Not enough arguments" else: m = "Too many arguments" raise RuntimeError(m) prev_gens = [] prev_rels = [] while not set(prev_rels) == set(rels): prev_rels = rels while change_gens and not set(prev_gens) == set(gens): prev_gens = gens gens, rels = elimination_technique_1(gens, rels, identity) rels = _simplify_relators(rels, identity) if change_gens: syms = [g.array_form[0][0] for g in gens] F = free_group(syms)[0] identity = F.identity gens = F.generators subs = dict(zip(syms, gens)) for j, r in enumerate(rels): a = r.array_form rel = identity for sym, p in a: rel = rel*subs[sym]**p rels[j] = rel return gens, rels
[ "def", "simplify_presentation", "(", "*", "args", ",", "change_gens", "=", "False", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "if", "not", "isinstance", "(", "args", "[", "0", "]", ",", "FpGroup", ")", ":", "raise", "TypeError", "(", ...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/combinatorics/fp_groups.py#L947-L1001
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/external/creddump7/framework/newobj.py
python
Obj.values
(self)
return valdict
Return a dictionary of this object's members and their values
Return a dictionary of this object's members and their values
[ "Return", "a", "dictionary", "of", "this", "object", "s", "members", "and", "their", "values" ]
def values(self): """Return a dictionary of this object's members and their values""" valdict = {} for k in self.members(): valdict[k] = getattr(self, k) return valdict
[ "def", "values", "(", "self", ")", ":", "valdict", "=", "{", "}", "for", "k", "in", "self", ".", "members", "(", ")", ":", "valdict", "[", "k", "]", "=", "getattr", "(", "self", ",", "k", ")", "return", "valdict" ]
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/external/creddump7/framework/newobj.py#L123-L129
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/providers/aws/aws_nfs_service.py
python
AwsEfsCommands.GetFiler
(self, token)
return file_systems[0]
Returns the filer using the creation token or None.
Returns the filer using the creation token or None.
[ "Returns", "the", "filer", "using", "the", "creation", "token", "or", "None", "." ]
def GetFiler(self, token): """Returns the filer using the creation token or None.""" args = ['describe-file-systems', '--creation-token', token] response = self._IssueAwsCommand(args) file_systems = response['FileSystems'] if not file_systems: return None assert len(file_systems) < 2, 'Too many file systems.' return file_systems[0]
[ "def", "GetFiler", "(", "self", ",", "token", ")", ":", "args", "=", "[", "'describe-file-systems'", ",", "'--creation-token'", ",", "token", "]", "response", "=", "self", ".", "_IssueAwsCommand", "(", "args", ")", "file_systems", "=", "response", "[", "'Fil...
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/providers/aws/aws_nfs_service.py#L186-L194
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/preview/sync/service/document/document_permission.py
python
DocumentPermissionList.__repr__
(self)
return '<Twilio.Preview.Sync.DocumentPermissionList>'
Provide a friendly representation :returns: Machine friendly representation :rtype: str
Provide a friendly representation
[ "Provide", "a", "friendly", "representation" ]
def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Preview.Sync.DocumentPermissionList>'
[ "def", "__repr__", "(", "self", ")", ":", "return", "'<Twilio.Preview.Sync.DocumentPermissionList>'" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/preview/sync/service/document/document_permission.py#L147-L154
Netflix/brutal
13052ddbaf873acd9c9dac54b19a42ab7b70f7a9
brutal/protocols/core.py
python
ProtocolBackend.handle_event
(self, event)
takes events, tags them with the current backend, and places them on bot event_queue
takes events, tags them with the current backend, and places them on bot event_queue
[ "takes", "events", "tags", "them", "with", "the", "current", "backend", "and", "places", "them", "on", "bot", "event_queue" ]
def handle_event(self, event): """ takes events, tags them with the current backend, and places them on bot event_queue """ if isinstance(event, Event): event.source_client = self event.source_client_id = self.id self.bot.new_event(event) elif isinstance(event, dict): event['client'] = self event['client_id'] = self.id self.bot.new_event(event) else: self.log.error('invalid Event passed to {0}')
[ "def", "handle_event", "(", "self", ",", "event", ")", ":", "if", "isinstance", "(", "event", ",", "Event", ")", ":", "event", ".", "source_client", "=", "self", "event", ".", "source_client_id", "=", "self", ".", "id", "self", ".", "bot", ".", "new_ev...
https://github.com/Netflix/brutal/blob/13052ddbaf873acd9c9dac54b19a42ab7b70f7a9/brutal/protocols/core.py#L48-L61
ioflo/ioflo
177ac656d7c4ff801aebb0d8b401db365a5248ce
ioflo/aio/tcp/serving.py
python
Acceptor.accept
(self)
return (cs, ca)
Accept new connection nonblocking Returns duple (cs, ca) of connected socket and connected host address Otherwise if no new connection returns (None, None)
Accept new connection nonblocking Returns duple (cs, ca) of connected socket and connected host address Otherwise if no new connection returns (None, None)
[ "Accept", "new", "connection", "nonblocking", "Returns", "duple", "(", "cs", "ca", ")", "of", "connected", "socket", "and", "connected", "host", "address", "Otherwise", "if", "no", "new", "connection", "returns", "(", "None", "None", ")" ]
def accept(self): """ Accept new connection nonblocking Returns duple (cs, ca) of connected socket and connected host address Otherwise if no new connection returns (None, None) """ # accept new virtual connected socket created from server socket try: cs, ca = self.ss.accept() # virtual connection (socket, host address) except socket.error as ex: if ex.errno in (errno.EAGAIN, errno.EWOULDBLOCK): return (None, None) # nothing yet emsg = ("socket.error = {0}: server at {1} while " "accepting \n".format(ex, self.ha)) console.profuse(emsg) raise # re-raise return (cs, ca)
[ "def", "accept", "(", "self", ")", ":", "# accept new virtual connected socket created from server socket", "try", ":", "cs", ",", "ca", "=", "self", ".", "ss", ".", "accept", "(", ")", "# virtual connection (socket, host address)", "except", "socket", ".", "error", ...
https://github.com/ioflo/ioflo/blob/177ac656d7c4ff801aebb0d8b401db365a5248ce/ioflo/aio/tcp/serving.py#L674-L691
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/plugins/trustedcoin/qt.py
python
Plugin.auth_dialog
(self, window)
return pw.get_amount()
[]
def auth_dialog(self, window): d = WindowModalDialog(window, _("Authorization")) vbox = QVBoxLayout(d) pw = AmountEdit(None, is_int = True) msg = _('Please enter your Google Authenticator code') vbox.addWidget(QLabel(msg)) grid = QGridLayout() grid.setSpacing(8) grid.addWidget(QLabel(_('Code')), 1, 0) grid.addWidget(pw, 1, 1) vbox.addLayout(grid) msg = _('If you have lost your second factor, you need to restore your wallet from seed in order to request a new code.') label = QLabel(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addLayout(Buttons(CancelButton(d), OkButton(d))) if not d.exec_(): return return pw.get_amount()
[ "def", "auth_dialog", "(", "self", ",", "window", ")", ":", "d", "=", "WindowModalDialog", "(", "window", ",", "_", "(", "\"Authorization\"", ")", ")", "vbox", "=", "QVBoxLayout", "(", "d", ")", "pw", "=", "AmountEdit", "(", "None", ",", "is_int", "=",...
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/plugins/trustedcoin/qt.py#L109-L127
XKNX/xknx
1deeeb3dc0978aebacf14492a84e1f1eaf0970ed
xknx/devices/cover.py
python
Cover.position_reached
(self)
return self.travelcalculator.position_reached()
Return if cover has reached its final position.
Return if cover has reached its final position.
[ "Return", "if", "cover", "has", "reached", "its", "final", "position", "." ]
def position_reached(self) -> bool: """Return if cover has reached its final position.""" return self.travelcalculator.position_reached()
[ "def", "position_reached", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "travelcalculator", ".", "position_reached", "(", ")" ]
https://github.com/XKNX/xknx/blob/1deeeb3dc0978aebacf14492a84e1f1eaf0970ed/xknx/devices/cover.py#L321-L323
wishinlife/SyncY
71597eb523cc411e5f41558570d3814d52cfe92e
v2.6.0-src/files/syncy.py
python
SyncY.__del__
(self)
[]
def __del__(self): if self.__class__.oldSTDERR is not None: sys.stderr.flush() sys.stderr.close() sys.stderr = self.__class__.oldSTDERR sys.stdout = self.__class__.oldSTDOUT if os.path.exists(__PIDFILE__): with open(__PIDFILE__, 'r') as pidh: lckpid = pidh.read() if os.getpid() == int(lckpid): os.remove(__PIDFILE__)
[ "def", "__del__", "(", "self", ")", ":", "if", "self", ".", "__class__", ".", "oldSTDERR", "is", "not", "None", ":", "sys", ".", "stderr", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "close", "(", ")", "sys", ".", "stderr", "=", "self", "....
https://github.com/wishinlife/SyncY/blob/71597eb523cc411e5f41558570d3814d52cfe92e/v2.6.0-src/files/syncy.py#L363-L373
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/sklearn/svm/base.py
python
_fit_liblinear
(X, y, C, fit_intercept, intercept_scaling, class_weight, penalty, dual, verbose, max_iter, tol, random_state=None, multi_class='ovr', loss='logistic_regression', epsilon=0.1, sample_weight=None)
return coef_, intercept_, n_iter_
Used by Logistic Regression (and CV) and LinearSVC. Preprocessing is done in this function before supplying it to liblinear. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. y : array-like, shape (n_samples,) Target vector relative to X C : float Inverse of cross-validation parameter. Lower the C, the more the penalization. fit_intercept : bool Whether or not to fit the intercept, that is to add a intercept term to the decision function. intercept_scaling : float LibLinear internally penalizes the intercept and this term is subject to regularization just like the other terms of the feature vector. In order to avoid this, one should increase the intercept_scaling. such that the feature vector becomes [x, intercept_scaling]. class_weight : {dict, 'balanced'}, optional Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` penalty : str, {'l1', 'l2'} The norm of the penalty used in regularization. dual : bool Dual or primal formulation, verbose : int Set verbose to any positive number for verbosity. max_iter : int Number of iterations. tol : float Stopping condition. random_state : int seed, RandomState instance, or None (default) The seed of the pseudo random number generator to use when shuffling the data. multi_class : str, {'ovr', 'crammer_singer'} `ovr` trains n_classes one-vs-rest classifiers, while `crammer_singer` optimizes a joint objective over all classes. While `crammer_singer` is interesting from an theoretical perspective as it is consistent it is seldom used in practice and rarely leads to better accuracy and is more expensive to compute. If `crammer_singer` is chosen, the options loss, penalty and dual will be ignored. loss : str, {'logistic_regression', 'hinge', 'squared_hinge', 'epsilon_insensitive', 'squared_epsilon_insensitive} The loss function used to fit the model. epsilon : float, optional (default=0.1) Epsilon parameter in the epsilon-insensitive loss function. Note that the value of this parameter depends on the scale of the target variable y. If unsure, set epsilon=0. sample_weight: array-like, optional Weights assigned to each sample. Returns ------- coef_ : ndarray, shape (n_features, n_features + 1) The coefficient vector got by minimizing the objective function. intercept_ : float The intercept term added to the vector. n_iter_ : int Maximum number of iterations run across all classes.
Used by Logistic Regression (and CV) and LinearSVC.
[ "Used", "by", "Logistic", "Regression", "(", "and", "CV", ")", "and", "LinearSVC", "." ]
def _fit_liblinear(X, y, C, fit_intercept, intercept_scaling, class_weight, penalty, dual, verbose, max_iter, tol, random_state=None, multi_class='ovr', loss='logistic_regression', epsilon=0.1, sample_weight=None): """Used by Logistic Regression (and CV) and LinearSVC. Preprocessing is done in this function before supplying it to liblinear. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. y : array-like, shape (n_samples,) Target vector relative to X C : float Inverse of cross-validation parameter. Lower the C, the more the penalization. fit_intercept : bool Whether or not to fit the intercept, that is to add a intercept term to the decision function. intercept_scaling : float LibLinear internally penalizes the intercept and this term is subject to regularization just like the other terms of the feature vector. In order to avoid this, one should increase the intercept_scaling. such that the feature vector becomes [x, intercept_scaling]. class_weight : {dict, 'balanced'}, optional Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` penalty : str, {'l1', 'l2'} The norm of the penalty used in regularization. dual : bool Dual or primal formulation, verbose : int Set verbose to any positive number for verbosity. max_iter : int Number of iterations. tol : float Stopping condition. random_state : int seed, RandomState instance, or None (default) The seed of the pseudo random number generator to use when shuffling the data. multi_class : str, {'ovr', 'crammer_singer'} `ovr` trains n_classes one-vs-rest classifiers, while `crammer_singer` optimizes a joint objective over all classes. While `crammer_singer` is interesting from an theoretical perspective as it is consistent it is seldom used in practice and rarely leads to better accuracy and is more expensive to compute. If `crammer_singer` is chosen, the options loss, penalty and dual will be ignored. loss : str, {'logistic_regression', 'hinge', 'squared_hinge', 'epsilon_insensitive', 'squared_epsilon_insensitive} The loss function used to fit the model. epsilon : float, optional (default=0.1) Epsilon parameter in the epsilon-insensitive loss function. Note that the value of this parameter depends on the scale of the target variable y. If unsure, set epsilon=0. sample_weight: array-like, optional Weights assigned to each sample. Returns ------- coef_ : ndarray, shape (n_features, n_features + 1) The coefficient vector got by minimizing the objective function. intercept_ : float The intercept term added to the vector. n_iter_ : int Maximum number of iterations run across all classes. """ if loss not in ['epsilon_insensitive', 'squared_epsilon_insensitive']: enc = LabelEncoder() y_ind = enc.fit_transform(y) classes_ = enc.classes_ if len(classes_) < 2: raise ValueError("This solver needs samples of at least 2 classes" " in the data, but the data contains only one" " class: %r" % classes_[0]) class_weight_ = compute_class_weight(class_weight, classes_, y) else: class_weight_ = np.empty(0, dtype=np.float64) y_ind = y liblinear.set_verbosity_wrap(verbose) rnd = check_random_state(random_state) if verbose: print('[LibLinear]', end='') # LinearSVC breaks when intercept_scaling is <= 0 bias = -1.0 if fit_intercept: if intercept_scaling <= 0: raise ValueError("Intercept scaling is %r but needs to be greater than 0." " To disable fitting an intercept," " set fit_intercept=False." % intercept_scaling) else: bias = intercept_scaling libsvm.set_verbosity_wrap(verbose) libsvm_sparse.set_verbosity_wrap(verbose) liblinear.set_verbosity_wrap(verbose) # LibLinear wants targets as doubles, even for classification y_ind = np.asarray(y_ind, dtype=np.float64).ravel() if sample_weight is None: sample_weight = np.ones(X.shape[0]) else: sample_weight = np.array(sample_weight, dtype=np.float64, order='C') check_consistent_length(sample_weight, X) solver_type = _get_liblinear_solver_type(multi_class, penalty, loss, dual) raw_coef_, n_iter_ = liblinear.train_wrap( X, y_ind, sp.isspmatrix(X), solver_type, tol, bias, C, class_weight_, max_iter, rnd.randint(np.iinfo('i').max), epsilon, sample_weight) # Regarding rnd.randint(..) in the above signature: # seed for srand in range [0..INT_MAX); due to limitations in Numpy # on 32-bit platforms, we can't get to the UINT_MAX limit that # srand supports n_iter_ = max(n_iter_) if n_iter_ >= max_iter and verbose > 0: warnings.warn("Liblinear failed to converge, increase " "the number of iterations.", ConvergenceWarning) if fit_intercept: coef_ = raw_coef_[:, :-1] intercept_ = intercept_scaling * raw_coef_[:, -1] else: coef_ = raw_coef_ intercept_ = 0. return coef_, intercept_, n_iter_
[ "def", "_fit_liblinear", "(", "X", ",", "y", ",", "C", ",", "fit_intercept", ",", "intercept_scaling", ",", "class_weight", ",", "penalty", ",", "dual", ",", "verbose", ",", "max_iter", ",", "tol", ",", "random_state", "=", "None", ",", "multi_class", "=",...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/svm/base.py#L775-L929
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/Toggl-Time-Tracking/alp/request/requests/packages/oauthlib/common.py
python
decode_params_utf8
(params)
return decoded
Ensures that all parameters in a list of 2-element tuples are decoded to unicode using UTF-8.
Ensures that all parameters in a list of 2-element tuples are decoded to unicode using UTF-8.
[ "Ensures", "that", "all", "parameters", "in", "a", "list", "of", "2", "-", "element", "tuples", "are", "decoded", "to", "unicode", "using", "UTF", "-", "8", "." ]
def decode_params_utf8(params): """Ensures that all parameters in a list of 2-element tuples are decoded to unicode using UTF-8. """ decoded = [] for k, v in params: decoded.append(( k.decode('utf-8') if isinstance(k, str) else k, v.decode('utf-8') if isinstance(v, str) else v)) return decoded
[ "def", "decode_params_utf8", "(", "params", ")", ":", "decoded", "=", "[", "]", "for", "k", ",", "v", "in", "params", ":", "decoded", ".", "append", "(", "(", "k", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "k", ",", "str", ")", ...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/Toggl-Time-Tracking/alp/request/requests/packages/oauthlib/common.py#L57-L66
jhpyle/docassemble
b90c84e57af59aa88b3404d44d0b125c70f832cc
docassemble_base/docassemble/base/functions.py
python
defined
(var)
return True
Returns true if the variable has already been defined. Otherwise, returns false.
Returns true if the variable has already been defined. Otherwise, returns false.
[ "Returns", "true", "if", "the", "variable", "has", "already", "been", "defined", ".", "Otherwise", "returns", "false", "." ]
def defined(var): """Returns true if the variable has already been defined. Otherwise, returns false.""" str(var) if not isinstance(var, str): raise Exception("defined() must be given a string") if not re.search(r'[A-Za-z][A-Za-z0-9\_]*', var): raise Exception("defined() must be given a valid Python variable name") try: eval(var, {}) return True except: pass frame = inspect.stack()[1][0] components = components_of(var) if len(components) == 0 or len(components[0]) < 2: raise Exception("defined: variable " + repr(var) + " is not a valid variable name") variable = components[0][1] the_user_dict = frame.f_locals while variable not in the_user_dict: frame = frame.f_back if frame is None: return False if 'user_dict' in frame.f_locals: the_user_dict = eval('user_dict', frame.f_locals) if variable in the_user_dict: break else: return False else: the_user_dict = frame.f_locals if variable not in the_user_dict: #logmessage("Returning False1") return False if len(components) == 1: return True cum_variable = '' for elem in components: if elem[0] == 'name': cum_variable += elem[1] continue if elem[0] == 'attr': to_eval = "hasattr(" + cum_variable + ", " + repr(elem[1]) + ")" cum_variable += '.' + elem[1] elif elem[0] == 'index': try: the_index = eval(elem[1], the_user_dict) except: #logmessage("Returning False2") return False try: the_cum = eval(cum_variable, the_user_dict) except: #logmessage("Returning False2.5") return False if hasattr(the_cum, 'instanceName') and hasattr(the_cum, 'elements'): if isinstance(the_index, int): to_eval = 'len(' + cum_variable + '.elements) > ' + str(the_index) else: to_eval = elem[1] + " in " + cum_variable + ".elements" else: if isinstance(the_index, int): to_eval = 'len(' + cum_variable + ') > ' + str(the_index) else: to_eval = elem[1] + " in " + cum_variable cum_variable += '[' + elem[1] + ']' try: result = eval(to_eval, the_user_dict) except Exception as err: #logmessage("Returning False3 after " + to_eval + ": " + str(err)) return False if result: continue #logmessage("Returning False4") return False return True
[ "def", "defined", "(", "var", ")", ":", "str", "(", "var", ")", "if", "not", "isinstance", "(", "var", ",", "str", ")", ":", "raise", "Exception", "(", "\"defined() must be given a string\"", ")", "if", "not", "re", ".", "search", "(", "r'[A-Za-z][A-Za-z0-...
https://github.com/jhpyle/docassemble/blob/b90c84e57af59aa88b3404d44d0b125c70f832cc/docassemble_base/docassemble/base/functions.py#L3934-L4008
frappe/frappe
b64cab6867dfd860f10ccaf41a4ec04bc890b583
frappe/core/doctype/user/user.py
python
get_active_users
()
return frappe.db.sql("""select count(*) from `tabUser` where enabled = 1 and user_type != 'Website User' and name not in ({}) and hour(timediff(now(), last_active)) < 72""".format(", ".join(["%s"]*len(STANDARD_USERS))), STANDARD_USERS)[0][0]
Returns No. of system users who logged in, in the last 3 days
Returns No. of system users who logged in, in the last 3 days
[ "Returns", "No", ".", "of", "system", "users", "who", "logged", "in", "in", "the", "last", "3", "days" ]
def get_active_users(): """Returns No. of system users who logged in, in the last 3 days""" return frappe.db.sql("""select count(*) from `tabUser` where enabled = 1 and user_type != 'Website User' and name not in ({}) and hour(timediff(now(), last_active)) < 72""".format(", ".join(["%s"]*len(STANDARD_USERS))), STANDARD_USERS)[0][0]
[ "def", "get_active_users", "(", ")", ":", "return", "frappe", ".", "db", ".", "sql", "(", "\"\"\"select count(*) from `tabUser`\n\t\twhere enabled = 1 and user_type != 'Website User'\n\t\tand name not in ({})\n\t\tand hour(timediff(now(), last_active)) < 72\"\"\"", ".", "format", "(", ...
https://github.com/frappe/frappe/blob/b64cab6867dfd860f10ccaf41a4ec04bc890b583/frappe/core/doctype/user/user.py#L884-L889
ray-project/ray
703c1610348615dcb8c2d141a0c46675084660f5
python/ray/tune/web_server.py
python
TuneClient.get_all_trials
(self, timeout=None)
return self._deserialize(response)
Returns a list of all trials' information.
Returns a list of all trials' information.
[ "Returns", "a", "list", "of", "all", "trials", "information", "." ]
def get_all_trials(self, timeout=None): """Returns a list of all trials' information.""" response = requests.get(urljoin(self._path, "trials"), timeout=timeout) return self._deserialize(response)
[ "def", "get_all_trials", "(", "self", ",", "timeout", "=", "None", ")", ":", "response", "=", "requests", ".", "get", "(", "urljoin", "(", "self", ".", "_path", ",", "\"trials\"", ")", ",", "timeout", "=", "timeout", ")", "return", "self", ".", "_deser...
https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/python/ray/tune/web_server.py#L38-L41
yidao620c/core-algorithm
73f249e00d0e57eb2cea5a4c527ad7ae89ae7c08
algorithms/ch01structure/tree/bisearch_tree.py
python
inOrderWalkNode
(node)
中序遍历二叉搜索树,从小到大输出元素
中序遍历二叉搜索树,从小到大输出元素
[ "中序遍历二叉搜索树,从小到大输出元素" ]
def inOrderWalkNode(node): """中序遍历二叉搜索树,从小到大输出元素""" if node: inOrderWalkNode(node.left) print(node.key), inOrderWalkNode(node.right)
[ "def", "inOrderWalkNode", "(", "node", ")", ":", "if", "node", ":", "inOrderWalkNode", "(", "node", ".", "left", ")", "print", "(", "node", ".", "key", ")", ",", "inOrderWalkNode", "(", "node", ".", "right", ")" ]
https://github.com/yidao620c/core-algorithm/blob/73f249e00d0e57eb2cea5a4c527ad7ae89ae7c08/algorithms/ch01structure/tree/bisearch_tree.py#L30-L35
yandex/yandex-tank
b41bcc04396c4ed46fc8b28a261197320854fd33
yandextank/plugins/JMeter/reader.py
python
JMeterStatAggregator.__init__
(self, source)
[]
def __init__(self, source): self.worker = agg.Worker({"allThreads": ["max"]}, False) self.source = source
[ "def", "__init__", "(", "self", ",", "source", ")", ":", "self", ".", "worker", "=", "agg", ".", "Worker", "(", "{", "\"allThreads\"", ":", "[", "\"max\"", "]", "}", ",", "False", ")", "self", ".", "source", "=", "source" ]
https://github.com/yandex/yandex-tank/blob/b41bcc04396c4ed46fc8b28a261197320854fd33/yandextank/plugins/JMeter/reader.py#L138-L140
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractMytranslationsOrg.py
python
extractMytranslationsOrg
(item)
return False
Parser for 'mytranslations.org'
Parser for 'mytranslations.org'
[ "Parser", "for", "mytranslations", ".", "org" ]
def extractMytranslationsOrg(item): ''' Parser for 'mytranslations.org' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
[ "def", "extractMytranslationsOrg", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"preview\"", "in", ...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractMytranslationsOrg.py#L2-L21
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/landing_page_view_service/client.py
python
LandingPageViewServiceClient._get_default_mtls_endpoint
(api_endpoint)
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint.
Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint.
[ "Convert", "api", "endpoint", "to", "mTLS", "endpoint", ".", "Convert", "*", ".", "sandbox", ".", "googleapis", ".", "com", "and", "*", ".", "googleapis", ".", "com", "to", "*", ".", "mtls", ".", "sandbox", ".", "googleapis", ".", "com", "and", "*", ...
def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
[ "def", "_get_default_mtls_endpoint", "(", "api_endpoint", ")", ":", "if", "not", "api_endpoint", ":", "return", "api_endpoint", "mtls_endpoint_re", "=", "re", ".", "compile", "(", "r\"(?P<name>[^.]+)(?P<mtls>\\.mtls)?(?P<sandbox>\\.sandbox)?(?P<googledomain>\\.googleapis\\.com)?\...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/landing_page_view_service/client.py#L79-L105
IntelAI/models
1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c
models/object_detection/tensorflow/rfcn/inference/fp32/eval_util.py
python
write_metrics
(metrics, global_step, summary_dir)
Write metrics to a summary directory. Args: metrics: A dictionary containing metric names and values. global_step: Global step at which the metrics are computed. summary_dir: Directory to write tensorflow summaries to.
Write metrics to a summary directory.
[ "Write", "metrics", "to", "a", "summary", "directory", "." ]
def write_metrics(metrics, global_step, summary_dir): """Write metrics to a summary directory. Args: metrics: A dictionary containing metric names and values. global_step: Global step at which the metrics are computed. summary_dir: Directory to write tensorflow summaries to. """ logging.info('Writing metrics to tf summary.') summary_writer = tf.compat.v1.summary.FileWriterCache.get(summary_dir) for key in sorted(metrics): summary = tf.compat.v1.Summary(value=[ tf.compat.v1.Summary.Value(tag=key, simple_value=metrics[key]), ]) summary_writer.add_summary(summary, global_step) logging.info('%s: %f', key, metrics[key]) logging.info('Metrics written to tf summary.')
[ "def", "write_metrics", "(", "metrics", ",", "global_step", ",", "summary_dir", ")", ":", "logging", ".", "info", "(", "'Writing metrics to tf summary.'", ")", "summary_writer", "=", "tf", ".", "compat", ".", "v1", ".", "summary", ".", "FileWriterCache", ".", ...
https://github.com/IntelAI/models/blob/1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c/models/object_detection/tensorflow/rfcn/inference/fp32/eval_util.py#L53-L69
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gui/widgets/fanchart2way.py
python
FanChart2WayWidget.cell_address_under_cursor_asc
(self, rads, radius)
return generation, selected
Determine the cell address in the fan under the cursor position x and y. None if outside of diagram
Determine the cell address in the fan under the cursor position x and y. None if outside of diagram
[ "Determine", "the", "cell", "address", "in", "the", "fan", "under", "the", "cursor", "position", "x", "and", "y", ".", "None", "if", "outside", "of", "diagram" ]
def cell_address_under_cursor_asc(self, rads, radius): """ Determine the cell address in the fan under the cursor position x and y. None if outside of diagram """ generation, selected = None, None for gen in range(self.generations_asc): radiusin, radiusout = self.get_radiusinout_for_gen_asc(gen) if radiusin <= radius <= radiusout: generation = gen break # find what person is in this position: if not (generation is None) and generation > 0: selected = FanChartWidget.personpos_at_angle(self, generation, rads) if (generation is None or selected is None): return None return generation, selected
[ "def", "cell_address_under_cursor_asc", "(", "self", ",", "rads", ",", "radius", ")", ":", "generation", ",", "selected", "=", "None", ",", "None", "for", "gen", "in", "range", "(", "self", ".", "generations_asc", ")", ":", "radiusin", ",", "radiusout", "=...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/widgets/fanchart2way.py#L574-L593
truenas/middleware
b11ec47d6340324f5a32287ffb4012e5d709b934
src/middlewared/middlewared/plugins/iscsi.py
python
iSCSITargetAuthorizedInitiator.do_update
(self, id, data)
return await self.get_instance(id)
Update iSCSI initiator of `id`.
Update iSCSI initiator of `id`.
[ "Update", "iSCSI", "initiator", "of", "id", "." ]
async def do_update(self, id, data): """ Update iSCSI initiator of `id`. """ old = await self.get_instance(id) new = old.copy() new.update(data) await self.compress(new) await self.middleware.call( 'datastore.update', self._config.datastore, id, new, {'prefix': self._config.datastore_prefix}) await self._service_change('iscsitarget', 'reload') return await self.get_instance(id)
[ "async", "def", "do_update", "(", "self", ",", "id", ",", "data", ")", ":", "old", "=", "await", "self", ".", "get_instance", "(", "id", ")", "new", "=", "old", ".", "copy", "(", ")", "new", ".", "update", "(", "data", ")", "await", "self", ".", ...
https://github.com/truenas/middleware/blob/b11ec47d6340324f5a32287ffb4012e5d709b934/src/middlewared/middlewared/plugins/iscsi.py#L968-L984
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
lvar_locator_t.is_scattered
(self, *args)
return _idaapi.lvar_locator_t_is_scattered(self, *args)
is_scattered(self) -> bool
is_scattered(self) -> bool
[ "is_scattered", "(", "self", ")", "-", ">", "bool" ]
def is_scattered(self, *args): """ is_scattered(self) -> bool """ return _idaapi.lvar_locator_t_is_scattered(self, *args)
[ "def", "is_scattered", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "lvar_locator_t_is_scattered", "(", "self", ",", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L35771-L35775
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py-rest/scripts/cpdb.py
python
console.cmd_vars
(self, *args)
-2|vars|Show variables
-2|vars|Show variables
[ "-", "2|vars|Show", "variables" ]
def cmd_vars(self, *args): '''-2|vars|Show variables''' print ("variables\r\n" + "-" * 79) for i, j in self.configvars.items(): value = self.parfmt(repr(getattr(self, j)), 52) print ("| %20s | %52s |" % (i, value[0])) for k in value[1:]: print ("| %20s | %52s |" % ("", k)) if len(value) > 1: print("| %20s | %52s |" % ("", "")) print ("-" * 79)
[ "def", "cmd_vars", "(", "self", ",", "*", "args", ")", ":", "print", "(", "\"variables\\r\\n\"", "+", "\"-\"", "*", "79", ")", "for", "i", ",", "j", "in", "self", ".", "configvars", ".", "items", "(", ")", ":", "value", "=", "self", ".", "parfmt", ...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py-rest/scripts/cpdb.py#L379-L388
PaddlePaddle/PaddleDetection
635e3e0a80f3d05751cdcfca8af04ee17c601a92
ppdet/modeling/backbones/swin_transformer.py
python
window_reverse
(windows, window_size, H, W)
return x
Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C)
Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C)
[ "Args", ":", "windows", ":", "(", "num_windows", "*", "B", "window_size", "window_size", "C", ")", "window_size", "(", "int", ")", ":", "Window", "size", "H", "(", "int", ")", ":", "Height", "of", "image", "W", "(", "int", ")", ":", "Width", "of", ...
def window_reverse(windows, window_size, H, W): """ Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) """ B = int(windows.shape[0] / (H * W / window_size / window_size)) x = windows.reshape( [B, H // window_size, W // window_size, window_size, window_size, -1]) x = x.transpose([0, 1, 3, 2, 4, 5]).reshape([B, H, W, -1]) return x
[ "def", "window_reverse", "(", "windows", ",", "window_size", ",", "H", ",", "W", ")", ":", "B", "=", "int", "(", "windows", ".", "shape", "[", "0", "]", "/", "(", "H", "*", "W", "/", "window_size", "/", "window_size", ")", ")", "x", "=", "windows...
https://github.com/PaddlePaddle/PaddleDetection/blob/635e3e0a80f3d05751cdcfca8af04ee17c601a92/ppdet/modeling/backbones/swin_transformer.py#L121-L135
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
source/addons/share/wizard/share_wizard.py
python
share_wizard._cleanup_action_context
(self, context_str, user_id)
return result
Returns a dict representing the context_str evaluated (safe_eval) as a dict where items that are not useful for shared actions have been removed. If the evaluation of context_str as a dict fails, context_str is returned unaltered. :param user_id: the integer uid to be passed as 'uid' in the evaluation context
Returns a dict representing the context_str evaluated (safe_eval) as a dict where items that are not useful for shared actions have been removed. If the evaluation of context_str as a dict fails, context_str is returned unaltered.
[ "Returns", "a", "dict", "representing", "the", "context_str", "evaluated", "(", "safe_eval", ")", "as", "a", "dict", "where", "items", "that", "are", "not", "useful", "for", "shared", "actions", "have", "been", "removed", ".", "If", "the", "evaluation", "of"...
def _cleanup_action_context(self, context_str, user_id): """Returns a dict representing the context_str evaluated (safe_eval) as a dict where items that are not useful for shared actions have been removed. If the evaluation of context_str as a dict fails, context_str is returned unaltered. :param user_id: the integer uid to be passed as 'uid' in the evaluation context """ result = False if context_str: try: context = safe_eval(context_str, tools.UnquoteEvalContext(), nocopy=True) result = dict(context) for key in context: # Remove all context keys that seem to toggle default # filters based on the current user, as it makes no sense # for shared users, who would not see any data by default. if key and key.startswith('search_default_') and 'user_id' in key: result.pop(key) except Exception: # Note: must catch all exceptions, as UnquoteEvalContext may cause many # different exceptions, as it shadows builtins. _logger.debug("Failed to cleanup action context as it does not parse server-side", exc_info=True) result = context_str return result
[ "def", "_cleanup_action_context", "(", "self", ",", "context_str", ",", "user_id", ")", ":", "result", "=", "False", "if", "context_str", ":", "try", ":", "context", "=", "safe_eval", "(", "context_str", ",", "tools", ".", "UnquoteEvalContext", "(", ")", ","...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/source/addons/share/wizard/share_wizard.py#L305-L330
nortikin/sverchok
7b460f01317c15f2681bfa3e337c5e7346f3711b
nodes/generator/box_mk2.py
python
SvBoxNodeMk2.draw_buttons_ext
(self, context, layout)
draw buttons on the N-panel
draw buttons on the N-panel
[ "draw", "buttons", "on", "the", "N", "-", "panel" ]
def draw_buttons_ext(self, context, layout): '''draw buttons on the N-panel''' layout.prop(self, "origin", expand=True) layout.label(text="Simplify Output:") layout.prop(self, "correct_output", expand=True) layout.separator() layout.label(text="List Match:") layout.prop(self, "list_match_global", text="Global Match", expand=False) layout.label(text="Output Numpy:") r = layout.row() for i in range(3): r.prop(self, "out_np", index=i, text=socket_names[i], toggle=True)
[ "def", "draw_buttons_ext", "(", "self", ",", "context", ",", "layout", ")", ":", "layout", ".", "prop", "(", "self", ",", "\"origin\"", ",", "expand", "=", "True", ")", "layout", ".", "label", "(", "text", "=", "\"Simplify Output:\"", ")", "layout", ".",...
https://github.com/nortikin/sverchok/blob/7b460f01317c15f2681bfa3e337c5e7346f3711b/nodes/generator/box_mk2.py#L328-L341
ahmetcemturan/SFACT
7576e29ba72b33e5058049b77b7b558875542747
fabmetheus_utilities/gcodec.py
python
DistanceFeedRate.addFlowRateLine
(self, flowRate)
Add a flow rate line.
Add a flow rate line.
[ "Add", "a", "flow", "rate", "line", "." ]
def addFlowRateLine(self, flowRate): 'Add a flow rate line.' self.output.write('M108 S%s\n' % euclidean.getFourSignificantFigures(flowRate))
[ "def", "addFlowRateLine", "(", "self", ",", "flowRate", ")", ":", "self", ".", "output", ".", "write", "(", "'M108 S%s\\n'", "%", "euclidean", ".", "getFourSignificantFigures", "(", "flowRate", ")", ")" ]
https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/fabmetheus_utilities/gcodec.py#L268-L270
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/nodes/data/array/projection.py
python
ProjectionData.get_pdos
(self, **kwargs)
return out_list
Retrieves all the pdos arrays corresponding to the input kwargs :param kwargs: inputs describing the orbitals associated with the pdos arrays :return: a list of tuples containing the orbital, energy array and pdos array associated with all orbitals that correspond to kwargs
Retrieves all the pdos arrays corresponding to the input kwargs
[ "Retrieves", "all", "the", "pdos", "arrays", "corresponding", "to", "the", "input", "kwargs" ]
def get_pdos(self, **kwargs): """ Retrieves all the pdos arrays corresponding to the input kwargs :param kwargs: inputs describing the orbitals associated with the pdos arrays :return: a list of tuples containing the orbital, energy array and pdos array associated with all orbitals that correspond to kwargs """ retrieve_indices, all_orbitals = self._find_orbitals_and_indices(**kwargs) out_list = [( all_orbitals[i], self.get_array(f'pdos_{self._from_index_to_arrayname(i)}'), self.get_array(f'energy_{self._from_index_to_arrayname(i)}') ) for i in retrieve_indices] return out_list
[ "def", "get_pdos", "(", "self", ",", "*", "*", "kwargs", ")", ":", "retrieve_indices", ",", "all_orbitals", "=", "self", ".", "_find_orbitals_and_indices", "(", "*", "*", "kwargs", ")", "out_list", "=", "[", "(", "all_orbitals", "[", "i", "]", ",", "self...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/nodes/data/array/projection.py#L123-L138
osirislab/Fentanyl
6635ec80bade773125c3444bf8ab1bb0761f4aec
main.py
python
undo
()
[]
def undo(): if ftl.undo() is None: print "Nothing to undo"
[ "def", "undo", "(", ")", ":", "if", "ftl", ".", "undo", "(", ")", "is", "None", ":", "print", "\"Nothing to undo\"" ]
https://github.com/osirislab/Fentanyl/blob/6635ec80bade773125c3444bf8ab1bb0761f4aec/main.py#L97-L99
coinbase/coinbase-python
497c28158f529e8c7d0228521b4386a890baf088
coinbase/wallet/client.py
python
Client.commit_withdrawal
(self, account_id, withdrawal_id, **params)
return self._make_api_object(response, Withdrawal)
https://developers.coinbase.com/api/v2#commit-a-withdrawal
https://developers.coinbase.com/api/v2#commit-a-withdrawal
[ "https", ":", "//", "developers", ".", "coinbase", ".", "com", "/", "api", "/", "v2#commit", "-", "a", "-", "withdrawal" ]
def commit_withdrawal(self, account_id, withdrawal_id, **params): """https://developers.coinbase.com/api/v2#commit-a-withdrawal""" response = self._post( 'v2', 'accounts', account_id, 'withdrawals', withdrawal_id, 'commit', data=params) return self._make_api_object(response, Withdrawal)
[ "def", "commit_withdrawal", "(", "self", ",", "account_id", ",", "withdrawal_id", ",", "*", "*", "params", ")", ":", "response", "=", "self", ".", "_post", "(", "'v2'", ",", "'accounts'", ",", "account_id", ",", "'withdrawals'", ",", "withdrawal_id", ",", ...
https://github.com/coinbase/coinbase-python/blob/497c28158f529e8c7d0228521b4386a890baf088/coinbase/wallet/client.py#L534-L539
privacyidea/privacyidea
9490c12ddbf77a34ac935b082d09eb583dfafa2c
privacyidea/lib/eventhandler/responsemangler.py
python
ResponseManglerEventHandler.allowed_positions
(cls)
return ["post"]
This returns the allowed positions of the event handler definition. The ResponseMangler can only be located at the "post" position :return: list of allowed positions
This returns the allowed positions of the event handler definition. The ResponseMangler can only be located at the "post" position
[ "This", "returns", "the", "allowed", "positions", "of", "the", "event", "handler", "definition", ".", "The", "ResponseMangler", "can", "only", "be", "located", "at", "the", "post", "position" ]
def allowed_positions(cls): """ This returns the allowed positions of the event handler definition. The ResponseMangler can only be located at the "post" position :return: list of allowed positions """ return ["post"]
[ "def", "allowed_positions", "(", "cls", ")", ":", "return", "[", "\"post\"", "]" ]
https://github.com/privacyidea/privacyidea/blob/9490c12ddbf77a34ac935b082d09eb583dfafa2c/privacyidea/lib/eventhandler/responsemangler.py#L60-L67
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/xml/dom/expatbuilder.py
python
parseFragment
(file, context, namespaces=True)
return result
Parse a fragment of a document, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. 'file' may be either a file name or an open file object.
Parse a fragment of a document, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment.
[ "Parse", "a", "fragment", "of", "a", "document", "given", "the", "context", "from", "which", "it", "was", "originally", "extracted", ".", "context", "should", "be", "the", "parent", "of", "the", "node", "(", "s", ")", "which", "are", "in", "the", "fragme...
def parseFragment(file, context, namespaces=True): """Parse a fragment of a document, given the context from which it was originally extracted. context should be the parent of the node(s) which are in the fragment. 'file' may be either a file name or an open file object. """ if namespaces: builder = FragmentBuilderNS(context) else: builder = FragmentBuilder(context) if isinstance(file, StringTypes): fp = open(file, 'rb') try: result = builder.parseFile(fp) finally: fp.close() else: result = builder.parseFile(file) return result
[ "def", "parseFragment", "(", "file", ",", "context", ",", "namespaces", "=", "True", ")", ":", "if", "namespaces", ":", "builder", "=", "FragmentBuilderNS", "(", "context", ")", "else", ":", "builder", "=", "FragmentBuilder", "(", "context", ")", "if", "is...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/xml/dom/expatbuilder.py#L943-L963
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/core/management/commands/compilemessages.py
python
Command.handle
(self, **options)
[]
def handle(self, **options): locale = options['locale'] exclude = options['exclude'] self.verbosity = options['verbosity'] if options['fuzzy']: self.program_options = self.program_options + ['-f'] if find_command(self.program) is None: raise CommandError("Can't find %s. Make sure you have GNU gettext " "tools 0.15 or newer installed." % self.program) basedirs = [os.path.join('conf', 'locale'), 'locale'] if os.environ.get('DJANGO_SETTINGS_MODULE'): from django.conf import settings basedirs.extend(upath(path) for path in settings.LOCALE_PATHS) # Walk entire tree, looking for locale directories for dirpath, dirnames, filenames in os.walk('.', topdown=True): for dirname in dirnames: if dirname == 'locale': basedirs.append(os.path.join(dirpath, dirname)) # Gather existing directories. basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs))) if not basedirs: raise CommandError("This script should be run from the Django Git " "checkout or your project or app tree, or with " "the settings module specified.") # Build locale list all_locales = [] for basedir in basedirs: locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % basedir)) all_locales.extend(map(os.path.basename, locale_dirs)) # Account for excluded locales locales = locale or all_locales locales = set(locales) - set(exclude) for basedir in basedirs: if locales: dirs = [os.path.join(basedir, l, 'LC_MESSAGES') for l in locales] else: dirs = [basedir] locations = [] for ldir in dirs: for dirpath, dirnames, filenames in os.walk(ldir): locations.extend((dirpath, f) for f in filenames if f.endswith('.po')) if locations: self.compile_messages(locations)
[ "def", "handle", "(", "self", ",", "*", "*", "options", ")", ":", "locale", "=", "options", "[", "'locale'", "]", "exclude", "=", "options", "[", "'exclude'", "]", "self", ".", "verbosity", "=", "options", "[", "'verbosity'", "]", "if", "options", "[",...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/core/management/commands/compilemessages.py#L53-L103
Yelp/paasta
6c08c04a577359509575c794b973ea84d72accf9
paasta_tools/cli/cmds/cook_image.py
python
paasta_cook_image
(args, service=None, soa_dir=None)
Build a docker image
Build a docker image
[ "Build", "a", "docker", "image" ]
def paasta_cook_image(args, service=None, soa_dir=None): """Build a docker image""" if not service: service = args.service if service.startswith("services-"): service = service.split("services-", 1)[1] if not soa_dir: soa_dir = args.yelpsoa_config_root validate_service_name(service, soa_dir) run_env = os.environ.copy() default_tag = "paasta-cook-image-{}-{}".format(service, get_username()) tag = run_env.get("DOCKER_TAG", default_tag) run_env["DOCKER_TAG"] = tag if not makefile_responds_to("cook-image"): print( "ERROR: local-run now requires a cook-image target to be present in the Makefile. See" "http://paasta.readthedocs.io/en/latest/about/contract.html", file=sys.stderr, ) return 1 try: cmd = "make cook-image" returncode, output = _run( cmd, env=run_env, log=True, component="build", service=service, loglevel="debug", ) if returncode != 0: _log( service=service, line="ERROR: make cook-image failed for %s." % service, component="build", level="event", ) else: action_details = {"tag": tag} _log_audit( action="cook-image", action_details=action_details, service=service ) return returncode except KeyboardInterrupt: print("\nProcess interrupted by the user. Cancelling.", file=sys.stderr) return 2
[ "def", "paasta_cook_image", "(", "args", ",", "service", "=", "None", ",", "soa_dir", "=", "None", ")", ":", "if", "not", "service", ":", "service", "=", "args", ".", "service", "if", "service", ".", "startswith", "(", "\"services-\"", ")", ":", "service...
https://github.com/Yelp/paasta/blob/6c08c04a577359509575c794b973ea84d72accf9/paasta_tools/cli/cmds/cook_image.py#L60-L109
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/core/base/expression.py
python
ScalarExpression.expr
(self)
Return expression on this expression.
Return expression on this expression.
[ "Return", "expression", "on", "this", "expression", "." ]
def expr(self): """Return expression on this expression.""" if self._constructed: return _GeneralExpressionData.expr.fget(self) raise ValueError( "Accessing the expression of expression '%s' " "before the Expression has been constructed (there " "is currently no value to return)." % (self.name))
[ "def", "expr", "(", "self", ")", ":", "if", "self", ".", "_constructed", ":", "return", "_GeneralExpressionData", ".", "expr", ".", "fget", "(", "self", ")", "raise", "ValueError", "(", "\"Accessing the expression of expression '%s' \"", "\"before the Expression has b...
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/core/base/expression.py#L393-L401
cgre-aachen/gempy
6ad16c46fc6616c9f452fba85d31ce32decd8b10
gempy/core/data.py
python
AdditionalData.update_structure
(self)
Update fields dependent on input data sucha as structure and universal kriging grade
Update fields dependent on input data sucha as structure and universal kriging grade
[ "Update", "fields", "dependent", "on", "input", "data", "sucha", "as", "structure", "and", "universal", "kriging", "grade" ]
def update_structure(self): """ Update fields dependent on input data sucha as structure and universal kriging grade """ self.structure_data.update_structure_from_input() if len(self.kriging_data.df.loc['values', 'drift equations']) < \ self.structure_data.df.loc['values', 'number series']: self.kriging_data.set_u_grade()
[ "def", "update_structure", "(", "self", ")", ":", "self", ".", "structure_data", ".", "update_structure_from_input", "(", ")", "if", "len", "(", "self", ".", "kriging_data", ".", "df", ".", "loc", "[", "'values'", ",", "'drift equations'", "]", ")", "<", "...
https://github.com/cgre-aachen/gempy/blob/6ad16c46fc6616c9f452fba85d31ce32decd8b10/gempy/core/data.py#L1355-L1362
henkelis/sonospy
841f52010fd6e1e932d8f1a8896ad4e5a0667b8a
web2py/gluon/sneaky2.py
python
Sneaky.__init__
(self, bind_addr, wsgi_app, numthreads = 10, server_name = SERVER_NAME, max_threads = None, request_queue_size = None, timeout = 10, shutdown_timeout = 5, numprocesses=1, dispatcherport=8765)
Example:: s = Sneaky('127.0.0.1:8000',test_wsgi_app,100) s.start() :bind_addr can be ('127.0.0.1',8000) or '127.0.0.1:8000' :wsgi_app is a generic WSGI application :numthreads is the min number of threads (10 by default) :server_name ("Skeaky" by default) :max_threads is the max number of threads or None (default) should be a multiple of numthreads :request_queue_size if set to None (default) adjusts automatically :timeout on socket IO in seconds (10 secs default) :shotdown_timeout in seconds (5 secs default)
Example::
[ "Example", "::" ]
def __init__(self, bind_addr, wsgi_app, numthreads = 10, server_name = SERVER_NAME, max_threads = None, request_queue_size = None, timeout = 10, shutdown_timeout = 5, numprocesses=1, dispatcherport=8765): """ Example:: s = Sneaky('127.0.0.1:8000',test_wsgi_app,100) s.start() :bind_addr can be ('127.0.0.1',8000) or '127.0.0.1:8000' :wsgi_app is a generic WSGI application :numthreads is the min number of threads (10 by default) :server_name ("Skeaky" by default) :max_threads is the max number of threads or None (default) should be a multiple of numthreads :request_queue_size if set to None (default) adjusts automatically :timeout on socket IO in seconds (10 secs default) :shotdown_timeout in seconds (5 secs default) """ if isinstance(bind_addr,str): bind_addr = bind_addr.split(':') self.address = bind_addr[0] self.port = bind_addr[1] self.request_queue_size = request_queue_size self.shutdown_timeout = shutdown_timeout self.ssl_interface = None self.numprocesses = numprocesses Worker.dispatcherport=dispatcherport Worker.wsgi_apps.append(wsgi_app) Worker.server_name = server_name Worker.server_port = bind_addr[1] Worker.min_threads = numthreads Worker.max_threads = max_threads Worker.timeout = timeout
[ "def", "__init__", "(", "self", ",", "bind_addr", ",", "wsgi_app", ",", "numthreads", "=", "10", ",", "server_name", "=", "SERVER_NAME", ",", "max_threads", "=", "None", ",", "request_queue_size", "=", "None", ",", "timeout", "=", "10", ",", "shutdown_timeou...
https://github.com/henkelis/sonospy/blob/841f52010fd6e1e932d8f1a8896ad4e5a0667b8a/web2py/gluon/sneaky2.py#L366-L406
everydo/ztq
0237239626c9662ffa47879b590a534b2287c5d1
ztq_worker/ztq_worker/command_execute.py
python
cancel_transform
(pid, timestamp)
取消 转换
取消 转换
[ "取消", "转换" ]
def cancel_transform(pid, timestamp): """ 取消 转换 """ kill(pid)
[ "def", "cancel_transform", "(", "pid", ",", "timestamp", ")", ":", "kill", "(", "pid", ")" ]
https://github.com/everydo/ztq/blob/0237239626c9662ffa47879b590a534b2287c5d1/ztq_worker/ztq_worker/command_execute.py#L97-L99
django-parler/django-parler
577ca2f4a80713a9272c48db30e914a4d9332358
parler/managers.py
python
TranslatableQuerySet._clone
(self)
return c
[]
def _clone(self): c = super()._clone() c._language = self._language return c
[ "def", "_clone", "(", "self", ")", ":", "c", "=", "super", "(", ")", ".", "_clone", "(", ")", "c", ".", "_language", "=", "self", ".", "_language", "return", "c" ]
https://github.com/django-parler/django-parler/blob/577ca2f4a80713a9272c48db30e914a4d9332358/parler/managers.py#L26-L29
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/flatnotebook.py
python
FNBRendererVC71.DrawTab
(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus)
Draws a tab using the `VC71` style. :param `pageContainer`: an instance of :class:`FlatNotebook`; :param `dc`: an instance of :class:`wx.DC`; :param `posx`: the x position of the tab; :param `tabIdx`: the index of the tab; :param `tabWidth`: the tab's width; :param `tabHeight`: the tab's height; :param `btnStatus`: the status of the 'X' button inside this tab.
Draws a tab using the `VC71` style.
[ "Draws", "a", "tab", "using", "the", "VC71", "style", "." ]
def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus): """ Draws a tab using the `VC71` style. :param `pageContainer`: an instance of :class:`FlatNotebook`; :param `dc`: an instance of :class:`wx.DC`; :param `posx`: the x position of the tab; :param `tabIdx`: the index of the tab; :param `tabWidth`: the tab's width; :param `tabHeight`: the tab's height; :param `btnStatus`: the status of the 'X' button inside this tab. """ # Visual studio 7.1 style borderPen = wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNSHADOW)) pc = pageContainer dc.SetPen((tabIdx == pc.GetSelection() and [wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE))] or [borderPen])[0]) dc.SetBrush((tabIdx == pc.GetSelection() and [wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE))] or [wx.Brush(wx.Colour(247, 243, 233))])[0]) if tabIdx == pc.GetSelection(): posy = (pc.HasAGWFlag(FNB_BOTTOM) and [0] or [VERTICAL_BORDER_PADDING])[0] tabH = (pc.HasAGWFlag(FNB_BOTTOM) and [tabHeight - 5] or [tabHeight - 3])[0] dc.DrawRectangle(posx, posy, tabWidth, tabH) # Draw a black line on the left side of the # rectangle dc.SetPen(wx.BLACK_PEN) blackLineY1 = VERTICAL_BORDER_PADDING blackLineY2 = tabH dc.DrawLine(posx + tabWidth, blackLineY1, posx + tabWidth, blackLineY2) # To give the tab more 3D look we do the following # In case the tab is on top, # Draw a thick white line on topof the rectangle # Otherwise, draw a thin (1 pixel) black line at the bottom pen = wx.Pen((pc.HasAGWFlag(FNB_BOTTOM) and [wx.BLACK] or [wx.WHITE])[0]) dc.SetPen(pen) whiteLinePosY = (pc.HasAGWFlag(FNB_BOTTOM) and [blackLineY2] or [VERTICAL_BORDER_PADDING ])[0] dc.DrawLine(posx , whiteLinePosY, posx + tabWidth + 1, whiteLinePosY) # Draw a white vertical line to the left of the tab dc.SetPen(wx.WHITE_PEN) if not pc.HasAGWFlag(FNB_BOTTOM): blackLineY2 += 1 dc.DrawLine(posx, blackLineY1, posx, blackLineY2) else: # We dont draw a rectangle for non selected tabs, but only # vertical line on the left blackLineY1 = (pc.HasAGWFlag(FNB_BOTTOM) and [VERTICAL_BORDER_PADDING + 2] or [VERTICAL_BORDER_PADDING + 1])[0] blackLineY2 = pc.GetSize().y - 5 dc.DrawLine(posx + tabWidth, blackLineY1, posx + tabWidth, blackLineY2) # ----------------------------------- # Text and image drawing # ----------------------------------- # Text drawing offset from the left border of the # rectangle # The width of the images are 16 pixels padding = pc.GetParent().GetPadding() hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1 imageYCoord = (pc.HasAGWFlag(FNB_BOTTOM) and [5] or [8])[0] if hasImage: textOffset = 2*pc._pParent._nPadding + 16 else: textOffset = pc._pParent._nPadding if tabIdx != pc.GetSelection(): # Set the text background to be like the vertical lines dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour()) if hasImage: imageXOffset = textOffset - 16 - padding pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc, posx + imageXOffset, imageYCoord, wx.IMAGELIST_DRAW_TRANSPARENT, True) pageTextColour = pc._pParent.GetPageTextColour(tabIdx) if pageTextColour is not None: dc.SetTextForeground(pageTextColour) dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord) # draw 'x' on tab (if enabled) if pc.HasAGWFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection(): textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx)) tabCloseButtonXCoord = posx + textOffset + textWidth + 1 # take a bitmap from the position of the 'x' button (the x on tab button) # this bitmap will be used later to delete old buttons tabCloseButtonYCoord = imageYCoord x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16) # Draw the tab self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus)
[ "def", "DrawTab", "(", "self", ",", "pageContainer", ",", "dc", ",", "posx", ",", "tabIdx", ",", "tabWidth", ",", "tabHeight", ",", "btnStatus", ")", ":", "# Visual studio 7.1 style", "borderPen", "=", "wx", ".", "Pen", "(", "wx", ".", "SystemSettings", "....
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/flatnotebook.py#L2801-L2908
kubeflow/pipelines
bea751c9259ff0ae85290f873170aae89284ba8e
backend/api/python_http_client/kfp_server_api/api/pipeline_service_api.py
python
PipelineServiceApi.delete_pipeline_version
(self, version_id, **kwargs)
return self.delete_pipeline_version_with_http_info(version_id, **kwargs)
Deletes a pipeline version by pipeline version ID. If the deleted pipeline version is the default pipeline version, the pipeline's default version changes to the pipeline's most recent pipeline version. If there are no remaining pipeline versions, the pipeline will have no default version. Examines the run_service_api.ipynb notebook to learn more about creating a run using a pipeline version (https://github.com/kubeflow/pipelines/blob/master/tools/benchmarks/run_service_api.ipynb). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_pipeline_version(version_id, async_req=True) >>> result = thread.get() :param version_id: The ID of the pipeline version to be deleted. (required) :type version_id: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object
Deletes a pipeline version by pipeline version ID. If the deleted pipeline version is the default pipeline version, the pipeline's default version changes to the pipeline's most recent pipeline version. If there are no remaining pipeline versions, the pipeline will have no default version. Examines the run_service_api.ipynb notebook to learn more about creating a run using a pipeline version (https://github.com/kubeflow/pipelines/blob/master/tools/benchmarks/run_service_api.ipynb). # noqa: E501
[ "Deletes", "a", "pipeline", "version", "by", "pipeline", "version", "ID", ".", "If", "the", "deleted", "pipeline", "version", "is", "the", "default", "pipeline", "version", "the", "pipeline", "s", "default", "version", "changes", "to", "the", "pipeline", "s", ...
def delete_pipeline_version(self, version_id, **kwargs): # noqa: E501 """Deletes a pipeline version by pipeline version ID. If the deleted pipeline version is the default pipeline version, the pipeline's default version changes to the pipeline's most recent pipeline version. If there are no remaining pipeline versions, the pipeline will have no default version. Examines the run_service_api.ipynb notebook to learn more about creating a run using a pipeline version (https://github.com/kubeflow/pipelines/blob/master/tools/benchmarks/run_service_api.ipynb). # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_pipeline_version(version_id, async_req=True) >>> result = thread.get() :param version_id: The ID of the pipeline version to be deleted. (required) :type version_id: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True return self.delete_pipeline_version_with_http_info(version_id, **kwargs)
[ "def", "delete_pipeline_version", "(", "self", ",", "version_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "return", "self", ".", "delete_pipeline_version_with_http_info", "(", "version_id", ",",...
https://github.com/kubeflow/pipelines/blob/bea751c9259ff0ae85290f873170aae89284ba8e/backend/api/python_http_client/kfp_server_api/api/pipeline_service_api.py#L413-L439
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/inceptionresnetv2.py
python
Mixed_7a.__init__
(self)
[]
def __init__(self): super(Mixed_7a, self).__init__() self.branch0 = nn.Sequential( BasicConv2d(1088, 256, kernel_size=1, stride=1), BasicConv2d(256, 384, kernel_size=3, stride=2) ) self.branch1 = nn.Sequential( BasicConv2d(1088, 256, kernel_size=1, stride=1), BasicConv2d(256, 288, kernel_size=3, stride=2) ) self.branch2 = nn.Sequential( BasicConv2d(1088, 256, kernel_size=1, stride=1), BasicConv2d(256, 288, kernel_size=3, stride=1, padding=1), BasicConv2d(288, 320, kernel_size=3, stride=2) ) self.branch3 = nn.MaxPool2d(3, stride=2)
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "Mixed_7a", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "branch0", "=", "nn", ".", "Sequential", "(", "BasicConv2d", "(", "1088", ",", "256", ",", "kernel_size", "=", "1", ",", "...
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/inceptionresnetv2.py#L173-L192
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/site-packages/pkg_resources/__init__.py
python
VersionConflict.with_context
(self, required_by)
return ContextualVersionConflict(*args)
If required_by is non-empty, return a version of self that is a ContextualVersionConflict.
If required_by is non-empty, return a version of self that is a ContextualVersionConflict.
[ "If", "required_by", "is", "non", "-", "empty", "return", "a", "version", "of", "self", "that", "is", "a", "ContextualVersionConflict", "." ]
def with_context(self, required_by): """ If required_by is non-empty, return a version of self that is a ContextualVersionConflict. """ if not required_by: return self args = self.args + (required_by,) return ContextualVersionConflict(*args)
[ "def", "with_context", "(", "self", ",", "required_by", ")", ":", "if", "not", "required_by", ":", "return", "self", "args", "=", "self", ".", "args", "+", "(", "required_by", ",", ")", "return", "ContextualVersionConflict", "(", "*", "args", ")" ]
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pkg_resources/__init__.py#L348-L356
django-oscar/django-oscar-accounts
8a6dc3b42306979779f048b4d3ed0a9fd4a2f794
src/oscar_accounts/dashboard/views.py
python
AccountCreateView.form_valid
(self, form)
return http.HttpResponseRedirect( reverse('accounts_dashboard:accounts-detail', kwargs={'pk': account.id}))
[]
def form_valid(self, form): account = form.save() # Load transaction source = form.get_source_account() amount = form.cleaned_data['initial_amount'] try: facade.transfer(source, account, amount, user=self.request.user, description=_("Creation of account")) except exceptions.AccountException as e: messages.error( self.request, _("Account created but unable to load funds onto new " "account: %s") % e) else: messages.success( self.request, _("New account created with code '%s'") % account.code) return http.HttpResponseRedirect( reverse('accounts_dashboard:accounts-detail', kwargs={'pk': account.id}))
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "account", "=", "form", ".", "save", "(", ")", "# Load transaction", "source", "=", "form", ".", "get_source_account", "(", ")", "amount", "=", "form", ".", "cleaned_data", "[", "'initial_amount'", "...
https://github.com/django-oscar/django-oscar-accounts/blob/8a6dc3b42306979779f048b4d3ed0a9fd4a2f794/src/oscar_accounts/dashboard/views.py#L92-L112
google/trax
d6cae2067dedd0490b78d831033607357e975015
trax/layers/research/sparsity.py
python
FavorAttention.forward
(self, inputs)
return renormalized_attention, mask
[]
def forward(self, inputs): query, key, value, mask = inputs if self._use_approximate_softmax: query_prime = self.nonnegative_softmax_kernel_feature_creator(query, True) key_prime = self.nonnegative_softmax_kernel_feature_creator(key, False) else: query_prime = self.relu(query) + self._numerical_stabilizer key_prime = self.relu(key) + self._numerical_stabilizer mask_batch_1_length = jnp.reshape( mask, [key.shape[0] // self._n_heads, 1, key.shape[1]]).astype( jnp.float32) mask_heads = mask_batch_1_length + jnp.zeros((1, self._n_heads, 1)) key_prime *= jnp.reshape(mask_heads, [key.shape[0], key.shape[1], 1]) w = self.bidirectional_numerator(jnp.moveaxis(query_prime, 1, 0), jnp.moveaxis(key_prime, 1, 0), jnp.moveaxis(value, 1, 0)) r = self.bidirectional_denominator(jnp.moveaxis(query_prime, 1, 0), jnp.moveaxis(key_prime, 1, 0)) w = jnp.moveaxis(w, 0, 1) r = jnp.moveaxis(r, 0, 1) r = jnp.reciprocal(r) r = jnp.expand_dims(r, len(r.shape)) renormalized_attention = w * r return renormalized_attention, mask
[ "def", "forward", "(", "self", ",", "inputs", ")", ":", "query", ",", "key", ",", "value", ",", "mask", "=", "inputs", "if", "self", ".", "_use_approximate_softmax", ":", "query_prime", "=", "self", ".", "nonnegative_softmax_kernel_feature_creator", "(", "quer...
https://github.com/google/trax/blob/d6cae2067dedd0490b78d831033607357e975015/trax/layers/research/sparsity.py#L911-L935
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/pythonwin/pywin/framework/app.py
python
CheckCreateDefaultGUI
()
return rc
Checks and creates if necessary a default GUI environment.
Checks and creates if necessary a default GUI environment.
[ "Checks", "and", "creates", "if", "necessary", "a", "default", "GUI", "environment", "." ]
def CheckCreateDefaultGUI(): """Checks and creates if necessary a default GUI environment. """ rc = HaveGoodGUI() if not rc: CreateDefaultGUI() return rc
[ "def", "CheckCreateDefaultGUI", "(", ")", ":", "rc", "=", "HaveGoodGUI", "(", ")", "if", "not", "rc", ":", "CreateDefaultGUI", "(", ")", "return", "rc" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/pythonwin/pywin/framework/app.py#L399-L405
ring04h/wyportmap
c4201e2313504e780a7f25238eba2a2d3223e739
libnmap/objects/host.py
python
NmapHost.os_fingerprint
(self)
return rval
Returns the fingerprint of the scanned system. :return: string
Returns the fingerprint of the scanned system.
[ "Returns", "the", "fingerprint", "of", "the", "scanned", "system", "." ]
def os_fingerprint(self): """ Returns the fingerprint of the scanned system. :return: string """ rval = '' if self.os is not None: rval = "\n".join(self.os.fingerprints) return rval
[ "def", "os_fingerprint", "(", "self", ")", ":", "rval", "=", "''", "if", "self", ".", "os", "is", "not", "None", ":", "rval", "=", "\"\\n\"", ".", "join", "(", "self", ".", "os", ".", "fingerprints", ")", "return", "rval" ]
https://github.com/ring04h/wyportmap/blob/c4201e2313504e780a7f25238eba2a2d3223e739/libnmap/objects/host.py#L333-L342
Guanghan/lighttrack
a980585acb4189da12f5d3dec68b5c3cd1b69de9
detector/detector_utils.py
python
compute_ap
(recall, precision)
return ap
Compute the average precision, given the recall and precision curves. Code originally from https://github.com/rbgirshick/py-faster-rcnn. # Arguments recall: The recall curve (list). precision: The precision curve (list). # Returns The average precision as computed in py-faster-rcnn.
Compute the average precision, given the recall and precision curves. Code originally from https://github.com/rbgirshick/py-faster-rcnn.
[ "Compute", "the", "average", "precision", "given", "the", "recall", "and", "precision", "curves", ".", "Code", "originally", "from", "https", ":", "//", "github", ".", "com", "/", "rbgirshick", "/", "py", "-", "faster", "-", "rcnn", "." ]
def compute_ap(recall, precision): """ Compute the average precision, given the recall and precision curves. Code originally from https://github.com/rbgirshick/py-faster-rcnn. # Arguments recall: The recall curve (list). precision: The precision curve (list). # Returns The average precision as computed in py-faster-rcnn. """ # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.0], recall, [1.0])) mpre = np.concatenate(([0.0], precision, [0.0])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap
[ "def", "compute_ap", "(", "recall", ",", "precision", ")", ":", "# correct AP calculation", "# first append sentinel values at the end", "mrec", "=", "np", ".", "concatenate", "(", "(", "[", "0.0", "]", ",", "recall", ",", "[", "1.0", "]", ")", ")", "mpre", ...
https://github.com/Guanghan/lighttrack/blob/a980585acb4189da12f5d3dec68b5c3cd1b69de9/detector/detector_utils.py#L124-L149
s-leger/archipack
5a6243bf1edf08a6b429661ce291dacb551e5f8a
pygeos/geomgraph.py
python
DirectedEdgeStar._computeDepths
(self, start: int, end: int, startDepth: int)
return currDepth
* Compute the DirectedEdge depths for a subsequence of the edge array. * * @return the last depth assigned (from the R side of the last edge visited)
* Compute the DirectedEdge depths for a subsequence of the edge array. * *
[ "*", "Compute", "the", "DirectedEdge", "depths", "for", "a", "subsequence", "of", "the", "edge", "array", ".", "*", "*" ]
def _computeDepths(self, start: int, end: int, startDepth: int) -> int: """ * Compute the DirectedEdge depths for a subsequence of the edge array. * * @return the last depth assigned (from the R side of the last edge visited) """ currDepth = startDepth for i in range(start, end): de = self.edges[i] de.setEdgeDepths(Position.RIGHT, currDepth) currDepth = de.getDepth(Position.LEFT) return currDepth
[ "def", "_computeDepths", "(", "self", ",", "start", ":", "int", ",", "end", ":", "int", ",", "startDepth", ":", "int", ")", "->", "int", ":", "currDepth", "=", "startDepth", "for", "i", "in", "range", "(", "start", ",", "end", ")", ":", "de", "=", ...
https://github.com/s-leger/archipack/blob/5a6243bf1edf08a6b429661ce291dacb551e5f8a/pygeos/geomgraph.py#L2221-L2233
ambakick/Person-Detection-and-Tracking
f925394ac29b5cf321f1ce89a71b193381519a0b
meta_architectures/faster_rcnn_meta_arch.py
python
FasterRCNNMetaArch._loss_rpn
(self, rpn_box_encodings, rpn_objectness_predictions_with_background, anchors, groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list)
return loss_dict
Computes scalar RPN loss tensors. Uses self._proposal_target_assigner to obtain regression and classification targets for the first stage RPN, samples a "minibatch" of anchors to participate in the loss computation, and returns the RPN losses. Args: rpn_box_encodings: A 4-D float tensor of shape [batch_size, num_anchors, self._box_coder.code_size] containing predicted proposal box encodings. rpn_objectness_predictions_with_background: A 2-D float tensor of shape [batch_size, num_anchors, 2] containing objectness predictions (logits) for each of the anchors with 0 corresponding to background and 1 corresponding to object. anchors: A 2-D tensor of shape [num_anchors, 4] representing anchors for the first stage RPN. Note that `num_anchors` can differ depending on whether the model is created in training or inference mode. groundtruth_boxlists: A list of BoxLists containing coordinates of the groundtruth boxes. groundtruth_classes_with_background_list: A list of 2-D one-hot (or k-hot) tensors of shape [num_boxes, num_classes+1] containing the class targets with the 0th index assumed to map to the background class. groundtruth_weights_list: A list of 1-D tf.float32 tensors of shape [num_boxes] containing weights for groundtruth boxes. Returns: a dictionary mapping loss keys (`first_stage_localization_loss`, `first_stage_objectness_loss`) to scalar tensors representing corresponding loss values.
Computes scalar RPN loss tensors.
[ "Computes", "scalar", "RPN", "loss", "tensors", "." ]
def _loss_rpn(self, rpn_box_encodings, rpn_objectness_predictions_with_background, anchors, groundtruth_boxlists, groundtruth_classes_with_background_list, groundtruth_weights_list): """Computes scalar RPN loss tensors. Uses self._proposal_target_assigner to obtain regression and classification targets for the first stage RPN, samples a "minibatch" of anchors to participate in the loss computation, and returns the RPN losses. Args: rpn_box_encodings: A 4-D float tensor of shape [batch_size, num_anchors, self._box_coder.code_size] containing predicted proposal box encodings. rpn_objectness_predictions_with_background: A 2-D float tensor of shape [batch_size, num_anchors, 2] containing objectness predictions (logits) for each of the anchors with 0 corresponding to background and 1 corresponding to object. anchors: A 2-D tensor of shape [num_anchors, 4] representing anchors for the first stage RPN. Note that `num_anchors` can differ depending on whether the model is created in training or inference mode. groundtruth_boxlists: A list of BoxLists containing coordinates of the groundtruth boxes. groundtruth_classes_with_background_list: A list of 2-D one-hot (or k-hot) tensors of shape [num_boxes, num_classes+1] containing the class targets with the 0th index assumed to map to the background class. groundtruth_weights_list: A list of 1-D tf.float32 tensors of shape [num_boxes] containing weights for groundtruth boxes. Returns: a dictionary mapping loss keys (`first_stage_localization_loss`, `first_stage_objectness_loss`) to scalar tensors representing corresponding loss values. """ with tf.name_scope('RPNLoss'): (batch_cls_targets, batch_cls_weights, batch_reg_targets, batch_reg_weights, _) = target_assigner.batch_assign_targets( self._proposal_target_assigner, box_list.BoxList(anchors), groundtruth_boxlists, len(groundtruth_boxlists) * [None], groundtruth_weights_list) batch_cls_targets = tf.squeeze(batch_cls_targets, axis=2) def _minibatch_subsample_fn(inputs): cls_targets, cls_weights = inputs return self._first_stage_sampler.subsample( tf.cast(cls_weights, tf.bool), self._first_stage_minibatch_size, tf.cast(cls_targets, tf.bool)) batch_sampled_indices = tf.to_float(shape_utils.static_or_dynamic_map_fn( _minibatch_subsample_fn, [batch_cls_targets, batch_cls_weights], dtype=tf.bool, parallel_iterations=self._parallel_iterations, back_prop=True)) # Normalize by number of examples in sampled minibatch normalizer = tf.reduce_sum(batch_sampled_indices, axis=1) batch_one_hot_targets = tf.one_hot( tf.to_int32(batch_cls_targets), depth=2) sampled_reg_indices = tf.multiply(batch_sampled_indices, batch_reg_weights) localization_losses = self._first_stage_localization_loss( rpn_box_encodings, batch_reg_targets, weights=sampled_reg_indices) objectness_losses = self._first_stage_objectness_loss( rpn_objectness_predictions_with_background, batch_one_hot_targets, weights=batch_sampled_indices) localization_loss = tf.reduce_mean( tf.reduce_sum(localization_losses, axis=1) / normalizer) objectness_loss = tf.reduce_mean( tf.reduce_sum(objectness_losses, axis=1) / normalizer) localization_loss = tf.multiply(self._first_stage_loc_loss_weight, localization_loss, name='localization_loss') objectness_loss = tf.multiply(self._first_stage_obj_loss_weight, objectness_loss, name='objectness_loss') loss_dict = {localization_loss.op.name: localization_loss, objectness_loss.op.name: objectness_loss} return loss_dict
[ "def", "_loss_rpn", "(", "self", ",", "rpn_box_encodings", ",", "rpn_objectness_predictions_with_background", ",", "anchors", ",", "groundtruth_boxlists", ",", "groundtruth_classes_with_background_list", ",", "groundtruth_weights_list", ")", ":", "with", "tf", ".", "name_sc...
https://github.com/ambakick/Person-Detection-and-Tracking/blob/f925394ac29b5cf321f1ce89a71b193381519a0b/meta_architectures/faster_rcnn_meta_arch.py#L1616-L1694
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/download.py
python
_copy_dist_from_dir
(link_path, location)
Copy distribution files in `link_path` to `location`. Invoked when user requests to install a local directory. E.g.: pip install . pip install ~/dev/git-repos/python-prompt-toolkit
Copy distribution files in `link_path` to `location`.
[ "Copy", "distribution", "files", "in", "link_path", "to", "location", "." ]
def _copy_dist_from_dir(link_path, location): """Copy distribution files in `link_path` to `location`. Invoked when user requests to install a local directory. E.g.: pip install . pip install ~/dev/git-repos/python-prompt-toolkit """ # Note: This is currently VERY SLOW if you have a lot of data in the # directory, because it copies everything with `shutil.copytree`. # What it should really do is build an sdist and install that. # See https://github.com/pypa/pip/issues/2195 if os.path.isdir(location): rmtree(location) # build an sdist setup_py = 'setup.py' sdist_args = [sys.executable] sdist_args.append('-c') sdist_args.append(SETUPTOOLS_SHIM % setup_py) sdist_args.append('sdist') sdist_args += ['--dist-dir', location] logger.info('Running setup.py sdist for %s', link_path) with indent_log(): call_subprocess(sdist_args, cwd=link_path, show_stdout=False) # unpack sdist into `location` sdist = os.path.join(location, os.listdir(location)[0]) logger.info('Unpacking sdist %s into %s', sdist, location) unpack_file(sdist, location, content_type=None, link=None)
[ "def", "_copy_dist_from_dir", "(", "link_path", ",", "location", ")", ":", "# Note: This is currently VERY SLOW if you have a lot of data in the", "# directory, because it copies everything with `shutil.copytree`.", "# What it should really do is build an sdist and install that.", "# See https...
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_internal/download.py#L770-L803
q1x/zabbix-gnomes
a3f62f567bedbd66df24247b0c8803567d9e5c0e
zgetevent.py
python
get_terminal_height
(fd=1)
return height
Returns height of terminal if it is a tty, 999 otherwise :param fd: file descriptor (default: 1=stdout)
Returns height of terminal if it is a tty, 999 otherwise
[ "Returns", "height", "of", "terminal", "if", "it", "is", "a", "tty", "999", "otherwise" ]
def get_terminal_height(fd=1): """ Returns height of terminal if it is a tty, 999 otherwise :param fd: file descriptor (default: 1=stdout) """ if os.isatty(fd): height = get_terminal_size(fd)[0] else: height = 999 return height
[ "def", "get_terminal_height", "(", "fd", "=", "1", ")", ":", "if", "os", ".", "isatty", "(", "fd", ")", ":", "height", "=", "get_terminal_size", "(", "fd", ")", "[", "0", "]", "else", ":", "height", "=", "999", "return", "height" ]
https://github.com/q1x/zabbix-gnomes/blob/a3f62f567bedbd66df24247b0c8803567d9e5c0e/zgetevent.py#L102-L113
shiyanhui/Young
184d2d85831b0c54db1002fad9ac1bce98738bf6
app/community/document.py
python
TopicDocument.get_topic_number
(node_id=None)
统计某节点下共有多少话题
统计某节点下共有多少话题
[ "统计某节点下共有多少话题" ]
def get_topic_number(node_id=None): '''统计某节点下共有多少话题''' if node_id: count = yield TopicDocument.find({ 'nodes': DBRef( NodeDocument.meta['collection'], ObjectId(node_id) ) }).count() else: count = yield TopicDocument.count() raise gen.Return(count)
[ "def", "get_topic_number", "(", "node_id", "=", "None", ")", ":", "if", "node_id", ":", "count", "=", "yield", "TopicDocument", ".", "find", "(", "{", "'nodes'", ":", "DBRef", "(", "NodeDocument", ".", "meta", "[", "'collection'", "]", ",", "ObjectId", "...
https://github.com/shiyanhui/Young/blob/184d2d85831b0c54db1002fad9ac1bce98738bf6/app/community/document.py#L347-L360
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/glance/glance/store/__init__.py
python
delete_from_backend
(context, uri, **kwargs)
Removes chunks of data from backend specified by uri
Removes chunks of data from backend specified by uri
[ "Removes", "chunks", "of", "data", "from", "backend", "specified", "by", "uri" ]
def delete_from_backend(context, uri, **kwargs): """Removes chunks of data from backend specified by uri""" loc = location.get_location_from_uri(uri) store = get_store_from_uri(context, uri, loc) try: return store.delete(loc) except NotImplementedError: raise exception.StoreDeleteNotSupported
[ "def", "delete_from_backend", "(", "context", ",", "uri", ",", "*", "*", "kwargs", ")", ":", "loc", "=", "location", ".", "get_location_from_uri", "(", "uri", ")", "store", "=", "get_store_from_uri", "(", "context", ",", "uri", ",", "loc", ")", "try", ":...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/glance/glance/store/__init__.py#L231-L239
fofix/fofix
7730d1503c66562b901f62b33a5bd46c3d5e5c34
fofix/game/song/song.py
python
Song.refreshVolumes
(self)
Refresh the miss volume after a pause
Refresh the miss volume after a pause
[ "Refresh", "the", "miss", "volume", "after", "a", "pause" ]
def refreshVolumes(self): """ Refresh the miss volume after a pause """ if self.singleTrackSong: # force single-track miss volume setting instead self.missVolume = self.engine.config.get("audio", "single_track_miss_volume") else: self.missVolume = self.engine.config.get("audio", "miss_volume") self.activeVolume = self.engine.config.get("audio", "guitarvol") self.backVolume = self.engine.config.get("audio", "songvol")
[ "def", "refreshVolumes", "(", "self", ")", ":", "if", "self", ".", "singleTrackSong", ":", "# force single-track miss volume setting instead", "self", ".", "missVolume", "=", "self", ".", "engine", ".", "config", ".", "get", "(", "\"audio\"", ",", "\"single_track_...
https://github.com/fofix/fofix/blob/7730d1503c66562b901f62b33a5bd46c3d5e5c34/fofix/game/song/song.py#L1957-L1965
locuslab/deq
1fb7059d6d89bb26d16da80ab9489dcc73fc5472
MDEQ-Vision/tools/seg_train.py
python
parse_args
()
return args
[]
def parse_args(): parser = argparse.ArgumentParser(description='Train segmentation network') parser.add_argument('--cfg', help='experiment configure file name', required=True, type=str) parser.add_argument('--modelDir', help='model directory', type=str, default='') parser.add_argument('--logDir', help='log directory', type=str, default='') parser.add_argument('--dataDir', help='data directory', type=str, default='') parser.add_argument('--testModel', help='testModel', type=str, default='') parser.add_argument('--percent', help='percentage of training data to use', type=float, default=1.0) parser.add_argument("--local_rank", type=int, default=0) parser.add_argument('opts', help="Modify config options using the command-line", default=None, nargs=argparse.REMAINDER) args = parser.parse_args() update_config(config, args) return args
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Train segmentation network'", ")", "parser", ".", "add_argument", "(", "'--cfg'", ",", "help", "=", "'experiment configure file name'", ",", "required", ...
https://github.com/locuslab/deq/blob/1fb7059d6d89bb26d16da80ab9489dcc73fc5472/MDEQ-Vision/tools/seg_train.py#L34-L70
spender-sandbox/cuckoo-modified
eb93ef3d41b8fee51b4330306dcd315d8101e021
lib/cuckoo/common/office/pyparsing.py
python
pyparsing_common.stripHTMLTags
(s, l, tokens)
return pyparsing_common._html_stripper.transformString(tokens[0])
Parse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>' td,td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page'
Parse action to remove HTML tags from web page HTML source
[ "Parse", "action", "to", "remove", "HTML", "tags", "from", "web", "page", "HTML", "source" ]
def stripHTMLTags(s, l, tokens): """ Parse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>' td,td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page' """ return pyparsing_common._html_stripper.transformString(tokens[0])
[ "def", "stripHTMLTags", "(", "s", ",", "l", ",", "tokens", ")", ":", "return", "pyparsing_common", ".", "_html_stripper", ".", "transformString", "(", "tokens", "[", "0", "]", ")" ]
https://github.com/spender-sandbox/cuckoo-modified/blob/eb93ef3d41b8fee51b4330306dcd315d8101e021/lib/cuckoo/common/office/pyparsing.py#L5601-L5613
jinfagang/alfred
dd7420d1410f82f9dadf07a30b6fad5a71168001
alfred/dl/torch/train/fastai_optim.py
python
OptimWrapper.__getstate__
(self)
return self.opt.__getstate__()
[]
def __getstate__(self): return self.opt.__getstate__()
[ "def", "__getstate__", "(", "self", ")", ":", "return", "self", ".", "opt", ".", "__getstate__", "(", ")" ]
https://github.com/jinfagang/alfred/blob/dd7420d1410f82f9dadf07a30b6fad5a71168001/alfred/dl/torch/train/fastai_optim.py#L197-L198
qiniu/python-sdk
c160e086d4cb5591f389f2891f6da09b3451951c
qiniu/auth.py
python
Auth.__init__
(self, access_key, secret_key)
初始化Auth类
初始化Auth类
[ "初始化Auth类" ]
def __init__(self, access_key, secret_key): """初始化Auth类""" self.__checkKey(access_key, secret_key) self.__access_key = access_key self.__secret_key = b(secret_key)
[ "def", "__init__", "(", "self", ",", "access_key", ",", "secret_key", ")", ":", "self", ".", "__checkKey", "(", "access_key", ",", "secret_key", ")", "self", ".", "__access_key", "=", "access_key", "self", ".", "__secret_key", "=", "b", "(", "secret_key", ...
https://github.com/qiniu/python-sdk/blob/c160e086d4cb5591f389f2891f6da09b3451951c/qiniu/auth.py#L52-L56
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
ingest_feed_lambda/numpy/lib/type_check.py
python
isrealobj
(x)
return not iscomplexobj(x)
Return True if x is a not complex type or an array of complex numbers. The type of the input is checked, not the value. So even if the input has an imaginary part equal to zero, `isrealobj` evaluates to False if the data type is complex. Parameters ---------- x : any The input can be of any type and shape. Returns ------- y : bool The return value, False if `x` is of a complex type. See Also -------- iscomplexobj, isreal Examples -------- >>> np.isrealobj(1) True >>> np.isrealobj(1+0j) False >>> np.isrealobj([3, 1+0j, True]) False
Return True if x is a not complex type or an array of complex numbers.
[ "Return", "True", "if", "x", "is", "a", "not", "complex", "type", "or", "an", "array", "of", "complex", "numbers", "." ]
def isrealobj(x): """ Return True if x is a not complex type or an array of complex numbers. The type of the input is checked, not the value. So even if the input has an imaginary part equal to zero, `isrealobj` evaluates to False if the data type is complex. Parameters ---------- x : any The input can be of any type and shape. Returns ------- y : bool The return value, False if `x` is of a complex type. See Also -------- iscomplexobj, isreal Examples -------- >>> np.isrealobj(1) True >>> np.isrealobj(1+0j) False >>> np.isrealobj([3, 1+0j, True]) False """ return not iscomplexobj(x)
[ "def", "isrealobj", "(", "x", ")", ":", "return", "not", "iscomplexobj", "(", "x", ")" ]
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/ingest_feed_lambda/numpy/lib/type_check.py#L291-L323
facelessuser/BracketHighlighter
223ffd4ceafd58686503e3328934c039e959a88c
bh_regions.py
python
get_bracket_regions
(settings, minimap)
Get styled regions for brackets to use.
Get styled regions for brackets to use.
[ "Get", "styled", "regions", "for", "brackets", "to", "use", "." ]
def get_bracket_regions(settings, minimap): """Get styled regions for brackets to use.""" icon_path = "Packages/BracketHighlighter/icons" styles = settings.get("bracket_styles", DEFAULT_STYLES) user_styles = settings.get("user_bracket_styles", {}) # Merge user styles with default style object for key, value in user_styles.items(): if key not in styles: styles[key] = value else: entry = styles[key] for subkey, subvalue in value.items(): entry[subkey] = subvalue # Make sure default and unmatched styles in styles for key, value in DEFAULT_STYLES.items(): if key not in styles: styles[key] = value continue for k, v in value.items(): if k not in styles[key]: styles[key][k] = v # Initialize styles default_settings = styles["default"] for k, v in styles.items(): yield k, StyleDefinition(k, v, default_settings, icon_path, minimap)
[ "def", "get_bracket_regions", "(", "settings", ",", "minimap", ")", ":", "icon_path", "=", "\"Packages/BracketHighlighter/icons\"", "styles", "=", "settings", ".", "get", "(", "\"bracket_styles\"", ",", "DEFAULT_STYLES", ")", "user_styles", "=", "settings", ".", "ge...
https://github.com/facelessuser/BracketHighlighter/blob/223ffd4ceafd58686503e3328934c039e959a88c/bh_regions.py#L129-L157
zvtvz/zvt
054bf8a3e7a049df7087c324fa87e8effbaf5bdc
src/zvt/factors/algorithm.py
python
macd
( s: pd.Series, slow: int = 26, fast: int = 12, n: int = 9, return_type: str = "df", normal: bool = False, count_live_dead: bool = False, )
[]
def macd( s: pd.Series, slow: int = 26, fast: int = 12, n: int = 9, return_type: str = "df", normal: bool = False, count_live_dead: bool = False, ): # 短期均线 ema_fast = ema(s, window=fast) # 长期均线 ema_slow = ema(s, window=slow) # 短期均线 - 长期均线 = 趋势的力度 diff: pd.Series = ema_fast - ema_slow # 力度均线 dea: pd.Series = diff.ewm(span=n, adjust=False).mean() # 力度 的变化 m: pd.Series = (diff - dea) * 2 # normal it if normal: diff = diff / s dea = dea / s m = m / s if count_live_dead: live = (diff > dea).apply(lambda x: live_or_dead(x)) bull = (diff > 0) & (dea > 0) live_count = live * (live.groupby((live != live.shift()).cumsum()).cumcount() + 1) if return_type == "se": if count_live_dead: return diff, dea, m, live, bull, live_count return diff, dea, m else: if count_live_dead: return pd.DataFrame( {"diff": diff, "dea": dea, "macd": m, "live": live, "bull": bull, "live_count": live_count} ) return pd.DataFrame({"diff": diff, "dea": dea, "macd": m})
[ "def", "macd", "(", "s", ":", "pd", ".", "Series", ",", "slow", ":", "int", "=", "26", ",", "fast", ":", "int", "=", "12", ",", "n", ":", "int", "=", "9", ",", "return_type", ":", "str", "=", "\"df\"", ",", "normal", ":", "bool", "=", "False"...
https://github.com/zvtvz/zvt/blob/054bf8a3e7a049df7087c324fa87e8effbaf5bdc/src/zvt/factors/algorithm.py#L30-L72
weechat/scripts
99ec0e7eceefabb9efb0f11ec26d45d6e8e84335
python/urlserver.py
python
urlserver_server_fd_cb
(data, fd)
return weechat.WEECHAT_RC_OK
Callback for server socket.
Callback for server socket.
[ "Callback", "for", "server", "socket", "." ]
def urlserver_server_fd_cb(data, fd): """Callback for server socket.""" global urlserver, urlserver_settings if not urlserver['socket']: return weechat.WEECHAT_RC_OK conn, addr = urlserver['socket'].accept() if urlserver_settings['debug'] == 'on': weechat.prnt('', 'urlserver: connection from %s' % str(addr)) if urlserver_settings['http_allowed_ips'] and \ not re.match(urlserver_settings['http_allowed_ips'], addr[0]): if urlserver_settings['debug'] == 'on': weechat.prnt('', 'urlserver: IP not allowed') conn.close() return weechat.WEECHAT_RC_OK data = None try: conn.settimeout(0.3) data = conn.recv(4096).decode('utf-8') data = data.replace('\r\n', '\n') except: return weechat.WEECHAT_RC_OK replysent = False sort = '-time' referer = re.search('^Referer:', data, re.MULTILINE | re.IGNORECASE) m = re.search('^GET /(.*) HTTP/.*$', data, re.MULTILINE) if m: url = m.group(1) if urlserver_settings['debug'] == 'on': weechat.prnt('', 'urlserver: %s' % m.group(0)) if 'favicon.' in url: urlserver_server_reply(conn, '200 OK', '', urlserver_server_favicon(), mimetype='image/x-icon') replysent = True else: # check if prefix is ok (if prefix defined in settings) prefixok = True if urlserver_settings['http_url_prefix']: if url.startswith(urlserver_settings['http_url_prefix']): url = url[len(urlserver_settings['http_url_prefix']):] if url.startswith('/'): url = url[1:] else: prefixok = False # prefix ok, go on with url if prefixok: if url.startswith('sort='): # sort asked for list of urls sort = url[5:] url = '' if url: # short url, read base62 key and redirect to page number = -1 try: number = base62_decode(url) except: pass if number >= 0 and number in urlserver['urls']: authok = ( urlserver_settings['http_auth_redirect'] != 'on' or urlserver_check_auth(data) ) if authok: # if we have a referer in request, use meta for # redirection (so that referer is not sent) # otherwise, we can make redirection with HTTP 302 if referer: urlserver_server_reply( conn, '200 OK', '', '<meta name="referrer" content="never">\n' '<meta http-equiv="refresh" content="0; ' 'url=%s">' % urlserver['urls'][number][3]) else: conn.sendall( 'HTTP/1.1 302\r\n' 'Location: {}\r\n\r\n' .format(urlserver['urls'][number][3]) .encode('utf-8')) else: urlserver_server_reply_auth_required(conn) replysent = True else: # page with list of urls if urlserver_check_auth(data): urlserver_server_reply_list(conn, sort) else: urlserver_server_reply_auth_required(conn) replysent = True else: if urlserver_settings['debug'] == 'on': weechat.prnt('', 'urlserver: prefix missing') if not replysent: urlserver_server_reply(conn, '404 Not found', '', '<html>\n' '<head><title>Page not found</title></head>\n' '<body><h1>Page not found</h1></body>\n' '</html>') conn.close() return weechat.WEECHAT_RC_OK
[ "def", "urlserver_server_fd_cb", "(", "data", ",", "fd", ")", ":", "global", "urlserver", ",", "urlserver_settings", "if", "not", "urlserver", "[", "'socket'", "]", ":", "return", "weechat", ".", "WEECHAT_RC_OK", "conn", ",", "addr", "=", "urlserver", "[", "...
https://github.com/weechat/scripts/blob/99ec0e7eceefabb9efb0f11ec26d45d6e8e84335/python/urlserver.py#L637-L736
dansanderson/picotool
d8c51e58416f8010dc8c0fba3df5f0424b5bb852
pico8/lua/lua.py
python
LuaMinifyWriter.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._name_factory = MinifyNameFactory()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_name_factory", "=", "MinifyNameFactory", "(", ")" ]
https://github.com/dansanderson/picotool/blob/d8c51e58416f8010dc8c0fba3df5f0424b5bb852/pico8/lua/lua.py#L1339-L1341
selimsef/dfdc_deepfake_challenge
89c6290490bac96b29193a4061b3db9dd3933e36
training/datasets/classifier_dataset.py
python
blackout_convex_hull
(img)
[]
def blackout_convex_hull(img): try: rect = detector(img)[0] sp = predictor(img, rect) landmarks = np.array([[p.x, p.y] for p in sp.parts()]) outline = landmarks[[*range(17), *range(26, 16, -1)]] Y, X = skimage.draw.polygon(outline[:, 1], outline[:, 0]) cropped_img = np.zeros(img.shape[:2], dtype=np.uint8) cropped_img[Y, X] = 1 # if random.random() > 0.5: # img[cropped_img == 0] = 0 # #leave only face # return img y, x = measure.centroid(cropped_img) y = int(y) x = int(x) first = random.random() > 0.5 if random.random() > 0.5: if first: cropped_img[:y, :] = 0 else: cropped_img[y:, :] = 0 else: if first: cropped_img[:, :x] = 0 else: cropped_img[:, x:] = 0 img[cropped_img > 0] = 0 except Exception as e: pass
[ "def", "blackout_convex_hull", "(", "img", ")", ":", "try", ":", "rect", "=", "detector", "(", "img", ")", "[", "0", "]", "sp", "=", "predictor", "(", "img", ",", "rect", ")", "landmarks", "=", "np", ".", "array", "(", "[", "[", "p", ".", "x", ...
https://github.com/selimsef/dfdc_deepfake_challenge/blob/89c6290490bac96b29193a4061b3db9dd3933e36/training/datasets/classifier_dataset.py#L54-L85
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/calendar.py
python
isleap
(year)
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Return True for leap years, False for non-leap years.
Return True for leap years, False for non-leap years.
[ "Return", "True", "for", "leap", "years", "False", "for", "non", "-", "leap", "years", "." ]
def isleap(year): """Return True for leap years, False for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
[ "def", "isleap", "(", "year", ")", ":", "return", "year", "%", "4", "==", "0", "and", "(", "year", "%", "100", "!=", "0", "or", "year", "%", "400", "==", "0", ")" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/calendar.py#L97-L99
OpenWaterAnalytics/pyswmm
a73409b2a9ebf4131ba42fc4c03a69453fc29d9a
pyswmm/links.py
python
Link.volume
(self)
return self._model.getLinkResult(self._linkid, LinkResults.newVolume.value)
Get Link Results for Volume. If Simulation is not running this method will raise a warning and return 0. :return: Parameter Value :rtype: float Examples: >>> from pyswmm import Simulation, Links >>> >>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim: ... c1c2 = Links(sim)["C1:C2"] ... for step in sim: ... print c1c2.volume >>> 0 >>> 1.2 >>> 1.5 >>> 1.9 >>> 1.2
Get Link Results for Volume.
[ "Get", "Link", "Results", "for", "Volume", "." ]
def volume(self): """ Get Link Results for Volume. If Simulation is not running this method will raise a warning and return 0. :return: Parameter Value :rtype: float Examples: >>> from pyswmm import Simulation, Links >>> >>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim: ... c1c2 = Links(sim)["C1:C2"] ... for step in sim: ... print c1c2.volume >>> 0 >>> 1.2 >>> 1.5 >>> 1.9 >>> 1.2 """ return self._model.getLinkResult(self._linkid, LinkResults.newVolume.value)
[ "def", "volume", "(", "self", ")", ":", "return", "self", ".", "_model", ".", "getLinkResult", "(", "self", ".", "_linkid", ",", "LinkResults", ".", "newVolume", ".", "value", ")" ]
https://github.com/OpenWaterAnalytics/pyswmm/blob/a73409b2a9ebf4131ba42fc4c03a69453fc29d9a/pyswmm/links.py#L668-L693
skggm/skggm
46797d526bfd1c1717831463f17d9a752882c1b2
inverse_covariance/metrics.py
python
ebic
(covariance, precision, n_samples, n_features, gamma=0)
return ( -2.0 * l_theta + precision_nnz * np.log(n_samples) + 4.0 * precision_nnz * np.log(n_features) * gamma )
Extended Bayesian Information Criteria for model selection. When using path mode, use this as an alternative to cross-validation for finding lambda. See: "Extended Bayesian Information Criteria for Gaussian Graphical Models" R. Foygel and M. Drton, NIPS 2010 Parameters ---------- covariance : 2D ndarray (n_features, n_features) Maximum Likelihood Estimator of covariance (sample covariance) precision : 2D ndarray (n_features, n_features) The precision matrix of the model to be tested n_samples : int Number of examples. n_features : int Dimension of an example. lam: (float) Threshold value for precision matrix. This should be lambda scaling used to obtain this estimate. gamma : (float) \in (0, 1) Choice of gamma=0 leads to classical BIC Positive gamma leads to stronger penalization of large graphs. Returns ------- ebic score (float). Caller should minimized this score.
Extended Bayesian Information Criteria for model selection.
[ "Extended", "Bayesian", "Information", "Criteria", "for", "model", "selection", "." ]
def ebic(covariance, precision, n_samples, n_features, gamma=0): """ Extended Bayesian Information Criteria for model selection. When using path mode, use this as an alternative to cross-validation for finding lambda. See: "Extended Bayesian Information Criteria for Gaussian Graphical Models" R. Foygel and M. Drton, NIPS 2010 Parameters ---------- covariance : 2D ndarray (n_features, n_features) Maximum Likelihood Estimator of covariance (sample covariance) precision : 2D ndarray (n_features, n_features) The precision matrix of the model to be tested n_samples : int Number of examples. n_features : int Dimension of an example. lam: (float) Threshold value for precision matrix. This should be lambda scaling used to obtain this estimate. gamma : (float) \in (0, 1) Choice of gamma=0 leads to classical BIC Positive gamma leads to stronger penalization of large graphs. Returns ------- ebic score (float). Caller should minimized this score. """ l_theta = -np.sum(covariance * precision) + fast_logdet(precision) l_theta *= n_features / 2. # is something goes wrong with fast_logdet, return large value if np.isinf(l_theta) or np.isnan(l_theta): return 1e10 mask = np.abs(precision.flat) > np.finfo(precision.dtype).eps precision_nnz = (np.sum(mask) - n_features) / 2.0 # lower off diagonal tri return ( -2.0 * l_theta + precision_nnz * np.log(n_samples) + 4.0 * precision_nnz * np.log(n_features) * gamma )
[ "def", "ebic", "(", "covariance", ",", "precision", ",", "n_samples", ",", "n_features", ",", "gamma", "=", "0", ")", ":", "l_theta", "=", "-", "np", ".", "sum", "(", "covariance", "*", "precision", ")", "+", "fast_logdet", "(", "precision", ")", "l_th...
https://github.com/skggm/skggm/blob/46797d526bfd1c1717831463f17d9a752882c1b2/inverse_covariance/metrics.py#L79-L130
dickreuter/Poker
b7642f0277e267e1a44eab957c4c7d1d8f50f4ee
poker/vboxapi/__init__.py
python
VirtualBoxManager.interruptWaitEvents
(self)
return self.platform.interruptWaitEvents()
See PlatformBase::interruptWaitEvents().
See PlatformBase::interruptWaitEvents().
[ "See", "PlatformBase", "::", "interruptWaitEvents", "()", "." ]
def interruptWaitEvents(self): """ See PlatformBase::interruptWaitEvents(). """ return self.platform.interruptWaitEvents()
[ "def", "interruptWaitEvents", "(", "self", ")", ":", "return", "self", ".", "platform", ".", "interruptWaitEvents", "(", ")" ]
https://github.com/dickreuter/Poker/blob/b7642f0277e267e1a44eab957c4c7d1d8f50f4ee/poker/vboxapi/__init__.py#L1111-L1113
nfvlabs/openmano
b09eabec0a168aeda8adc3ea99f734e45e810205
openmano/openmanoclient.py
python
openmanoclient.list_scenarios
(self, all_tenants=False, **kwargs)
return self._list_item("scenarios", all_tenants, kwargs)
Obtain a list of scenarios Params: can be filtered by 'uuid','name','description','public', "tenant_id" Return: Raises an exception on error Obtain a dictionary with format {'scenarios':[{scenario1_info},{scenario2_info},...]}}
Obtain a list of scenarios Params: can be filtered by 'uuid','name','description','public', "tenant_id" Return: Raises an exception on error Obtain a dictionary with format {'scenarios':[{scenario1_info},{scenario2_info},...]}}
[ "Obtain", "a", "list", "of", "scenarios", "Params", ":", "can", "be", "filtered", "by", "uuid", "name", "description", "public", "tenant_id", "Return", ":", "Raises", "an", "exception", "on", "error", "Obtain", "a", "dictionary", "with", "format", "{", "scen...
def list_scenarios(self, all_tenants=False, **kwargs): '''Obtain a list of scenarios Params: can be filtered by 'uuid','name','description','public', "tenant_id" Return: Raises an exception on error Obtain a dictionary with format {'scenarios':[{scenario1_info},{scenario2_info},...]}} ''' return self._list_item("scenarios", all_tenants, kwargs)
[ "def", "list_scenarios", "(", "self", ",", "all_tenants", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_list_item", "(", "\"scenarios\"", ",", "all_tenants", ",", "kwargs", ")" ]
https://github.com/nfvlabs/openmano/blob/b09eabec0a168aeda8adc3ea99f734e45e810205/openmano/openmanoclient.py#L671-L677
taehoonlee/tensornets
c9b1d78f806892193efdebee2789a47fd148b984
tensornets/contrib_layers/rev_block_lib.py
python
RevBlock._forward
(self, x1, x2)
Run forward through the reversible layers.
Run forward through the reversible layers.
[ "Run", "forward", "through", "the", "reversible", "layers", "." ]
def _forward(self, x1, x2): """Run forward through the reversible layers.""" side_inputs = [self.f_side_input, self.g_side_input] flat_side_inputs = nest.flatten(side_inputs) def _forward_wrap(x1_, x2_, *flat_side_inputs): f_side, g_side = nest.pack_sequence_as(side_inputs, flat_side_inputs) return _rev_block_forward( x1_, x2_, self.f, self.g, num_layers=self.num_layers, f_side_input=f_side, g_side_input=g_side, gate_outputs=self._use_efficient_backprop) @custom_gradient.custom_gradient def _forward_with_custom_grad(*args): out = _forward_wrap(*args) # pylint: disable=no-value-for-parameter grad_fn = self._make_efficient_grad_fn(args, out) return out, grad_fn if self._use_efficient_backprop: return _forward_with_custom_grad(x1, x2, *flat_side_inputs) else: return _forward_wrap(x1, x2, *flat_side_inputs)
[ "def", "_forward", "(", "self", ",", "x1", ",", "x2", ")", ":", "side_inputs", "=", "[", "self", ".", "f_side_input", ",", "self", ".", "g_side_input", "]", "flat_side_inputs", "=", "nest", ".", "flatten", "(", "side_inputs", ")", "def", "_forward_wrap", ...
https://github.com/taehoonlee/tensornets/blob/c9b1d78f806892193efdebee2789a47fd148b984/tensornets/contrib_layers/rev_block_lib.py#L335-L362
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/orthopolys.py
python
dup_spherical_bessel_fn
(n, K)
return dup_lshift(seq[n], 1, K)
Low-level implementation of fn(n, x)
Low-level implementation of fn(n, x)
[ "Low", "-", "level", "implementation", "of", "fn", "(", "n", "x", ")" ]
def dup_spherical_bessel_fn(n, K): """ Low-level implementation of fn(n, x) """ seq = [[K.one], [K.one, K.zero]] for i in xrange(2, n + 1): a = dup_mul_ground(dup_lshift(seq[-1], 1, K), K(2*i - 1), K) seq.append(dup_sub(a, seq[-2], K)) return dup_lshift(seq[n], 1, K)
[ "def", "dup_spherical_bessel_fn", "(", "n", ",", "K", ")", ":", "seq", "=", "[", "[", "K", ".", "one", "]", ",", "[", "K", ".", "one", ",", "K", ".", "zero", "]", "]", "for", "i", "in", "xrange", "(", "2", ",", "n", "+", "1", ")", ":", "a...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/orthopolys.py#L260-L268
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/py_compile.py
python
PyCompileError.__str__
(self)
return self.msg
[]
def __str__(self): return self.msg
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "msg" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/py_compile.py#L61-L62
pmbarrett314/curses-menu
574d2b32db937be9442ce9140c42368668bd7d77
cursesmenu/items/submenu_item.py
python
SubmenuItem.submenu
(self)
return self._submenu
Get the submenu associated with this item.
Get the submenu associated with this item.
[ "Get", "the", "submenu", "associated", "with", "this", "item", "." ]
def submenu(self) -> Optional[CursesMenu]: """Get the submenu associated with this item.""" return self._submenu
[ "def", "submenu", "(", "self", ")", "->", "Optional", "[", "CursesMenu", "]", ":", "return", "self", ".", "_submenu" ]
https://github.com/pmbarrett314/curses-menu/blob/574d2b32db937be9442ce9140c42368668bd7d77/cursesmenu/items/submenu_item.py#L44-L46
carpedm20/SPIRAL-tensorflow
2cca458f5d0d856c7bb73e877eea24906eda522f
models/policy.py
python
Policy.__init__
(self, args, env, scope_name, image_shape, action_sizes, data_format)
[]
def __init__(self, args, env, scope_name, image_shape, action_sizes, data_format): self.args = args scale = args.scale self.lstm_size = args.lstm_size if data_format == 'channels_first' and args.dynamic_channel: self.image_shape = list(image_shape[-1:] + image_shape[:-1]) else: self.image_shape = list(image_shape) self.action_sizes = action_sizes self.data_format = data_format action_num = len(action_sizes) with tf.variable_scope(scope_name) as scope: # [B, max_time, H, W, C] self.x = x = tf.placeholder( tf.float32, [None, None] + self.image_shape, name='x') # last is only used for summary x = x[:,:env.episode_length] # Flatten multiple episodes # XXX: important difference from openai/universe-starter-agent x_shape = tf.shape(x) batch_size, max_time = x_shape[0], x_shape[1] # [B, max_time, action_num] self.ac = ac = tf.placeholder( tf.float32, [None, None, action_num], name='ac') if args.conditional: # [B, max_time, H, W, C] self.c = c = tf.placeholder( tf.float32, [None, None] + self.image_shape, name='c') # TODO: need to get confirmed from the authors x = tf.concat([x, c], axis=-1) x_shape = list(self.image_shape) x_shape[-1] = int(x.get_shape()[-1]) self.z = None else: self.c = None x_shape = self.image_shape # [B, max_time, z_dim] self.z = z = tf.placeholder( tf.float32, [None, None, self.args.z_dim], name='z') z_enc = mlp( z, self.lstm_size, name="z_enc") x = tf.reshape(x, [-1] + x_shape) ac = tf.reshape(ac, [-1, action_num]) if data_format == 'channels_first' and args.dynamic_channel: x = tf.transpose(x, [0, 3, 1, 2]) ################################ # Beginning of policy network ################################ a_enc = mlp( tf.expand_dims(ac, -1), int(16), name="a_enc") a_concat = tf.reshape( a_enc, [-1, int(16) * action_num]) a_fc = tl.dense( a_concat, int(32), activation=tf.nn.relu, name="a_concat_fc") # [B, 1, 1, 32] a_expand = tf.expand_dims(tf.expand_dims(a_fc, 1), 1) if data_format == 'channels_first' and args.dynamic_channel: a_expand = tf.transpose(a_expand, [0, 3, 1, 2]) x_enc = tl.conv2d( x, int(32), 5, padding='same', activation=tf.nn.relu, data_format=self.data_format, name="x_c_enc" if args.conditional else "x_enc") add = x_enc + a_expand for idx in range(int(3)): add = tl.conv2d( add, int(32), 4, strides=(2, 2), padding='valid', activation=tf.nn.relu, data_format=self.data_format, name="add_enc_{}".format(idx)) for idx in range(int(8*scale)): add = res_block( add, 32, 3, self.data_format, name="encoder_res_{}".format(idx)) flat = tl.flatten(add) out = tl.dense( flat, self.lstm_size, activation=tf.nn.relu, name="flat_fc") # [batch_size, max_time, ...] flat_out = tl.flatten(out) lstm_in_shape = [batch_size, max_time, flat_out.get_shape()[-1]] lstm_in = tf.reshape(flat_out, lstm_in_shape, name="lstm_in") if not self.args.conditional: lstm_in += z_enc self.lstm = tc.BasicLSTMCell(self.lstm_size, state_is_tuple=True) def make_init(batch_size): c_init = np.zeros((batch_size, self.lstm.state_size.c), np.float32) h_init = np.zeros((batch_size, self.lstm.state_size.h), np.float32) return [c_init, h_init] self.state_init = ut.misc.keydefaultdict(make_init) c_in = tf.placeholder( tf.float32, [None, self.lstm.state_size.c], name="lstm_c_in") h_in = tf.placeholder( tf.float32, [None, self.lstm.state_size.h], name="lstm_h_in") self.state_in = [c_in, h_in] state_in = tc.LSTMStateTuple(c_in, h_in) lstm_out, lstm_state = tf.nn.dynamic_rnn( self.lstm, # [batch_size, max_time, ...] lstm_in, # [batch_size, cell.state_size] initial_state=state_in, time_major=False) # [bach_size, max_time, action_size] self.one_hot_samples, self.samples, self.logits = self.decoder( tf.nn.relu(lstm_out), self.action_sizes, self.data_format, self.lstm_size, scale) lstm_c, lstm_h = lstm_state self.state_out = [lstm_c, lstm_h] self.vf = tl.dense( lstm_out, 1, activation=None, name="value")[:,:,0] #kernel_initializer=normalized_columns_initializer(1.0))[:,:,0] self.var_list = tf.trainable_variables(scope=scope_name)
[ "def", "__init__", "(", "self", ",", "args", ",", "env", ",", "scope_name", ",", "image_shape", ",", "action_sizes", ",", "data_format", ")", ":", "self", ".", "args", "=", "args", "scale", "=", "args", ".", "scale", "self", ".", "lstm_size", "=", "arg...
https://github.com/carpedm20/SPIRAL-tensorflow/blob/2cca458f5d0d856c7bb73e877eea24906eda522f/models/policy.py#L12-L173