Dataset Viewer
Auto-converted to Parquet Duplicate
id_within_dataset
int64
46
2.71M
snippet
stringlengths
63
481k
tokens
sequencelengths
20
15.6k
language
stringclasses
2 values
nl
stringlengths
1
32.4k
is_duplicated
bool
2 classes
2,449,647
def _get_valid_port(self, port): """ :param port: :return "port/protocol": """ if '/' in port: port, protocol = port.split('/') else: protocol = 'tcp' try: int(port) except ValueError: raise ValueError("{0} ...
[ "def", "_get_valid_port", "(", "self", ",", "port", ")", ":", "if", "'/'", "in", "port", ":", "port", ",", "protocol", "=", "port", ".", "split", "(", "'/'", ")", "else", ":", "protocol", "=", "'tcp'", "try", ":", "int", "(", "port", ")", "except",...
python
:param port: :return "port/protocol":
false
2,144,015
def curve_intersection(c1, c2, grid=16): ''' curve_intersect(c1, c2) yields the parametric distances (t1, t2) such that c1(t1) == c2(t2). The optional parameter grid may specify the number of grid-points to use in the initial search for a start-point (default: 16). ''' from scipy.optimize...
[ "def", "curve_intersection", "(", "c1", ",", "c2", ",", "grid", "=", "16", ")", ":", "from", "scipy", ".", "optimize", "import", "minimize", "from", "neuropythy", ".", "geometry", "import", "segment_intersection_2D", "if", "c1", ".", "coordinates", ".", "sha...
python
curve_intersect(c1, c2) yields the parametric distances (t1, t2) such that c1(t1) == c2(t2). The optional parameter grid may specify the number of grid-points to use in the initial search for a start-point (default: 16).
false
2,158,507
def __init__(self, element_type=None, length=None, content=b''): """Create a HelloElemHeader with the optional parameters below. Args: element_type: One of OFPHET_*. length: Length in bytes of the element, including this header, excluding padding. """ ...
[ "def", "__init__", "(", "self", ",", "element_type", "=", "None", ",", "length", "=", "None", ",", "content", "=", "b''", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "element_type", "=", "element_type", "self", ".", "length", ...
python
Create a HelloElemHeader with the optional parameters below. Args: element_type: One of OFPHET_*. length: Length in bytes of the element, including this header, excluding padding.
false
1,637,871
def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' if _service_is_upstart(name): cmd = 'stop {0}'.format(name) else: cmd = '/sbin/service {0} stop'.format(name) return not __salt__['cmd.retc...
[ "def", "stop", "(", "name", ")", ":", "if", "_service_is_upstart", "(", "name", ")", ":", "cmd", "=", "'stop {0}'", ".", "format", "(", "name", ")", "else", ":", "cmd", "=", "'/sbin/service {0} stop'", ".", "format", "(", "name", ")", "return", "not", ...
python
Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name>
false
2,084,747
def __init__(self, protocol, dataInput): """Initalize the Tahoma Device.""" self.__protocol = protocol self.__raw_data = dataInput self.__active_states = {} debug_output = json.dumps(dataInput) if 'label' not in dataInput.keys(): raise ValueError('No device ...
[ "def", "__init__", "(", "self", ",", "protocol", ",", "dataInput", ")", ":", "self", ".", "__protocol", "=", "protocol", "self", ".", "__raw_data", "=", "dataInput", "self", ".", "__active_states", "=", "{", "}", "debug_output", "=", "json", ".", "dumps", ...
python
Initalize the Tahoma Device.
false
2,049,329
def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. *encoding* determ...
[ "def", "load", "(", "fp", ",", "encoding", "=", "None", ",", "cls", "=", "None", ",", "object_hook", "=", "None", ",", "parse_float", "=", "None", ",", "parse_int", "=", "None", ",", "parse_constant", "=", "None", ",", "object_pairs_hook", "=", "None", ...
python
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. N...
false
2,151,964
def __iadd__(self, target): ''' use this to combine databases ''' assert isinstance(target, RamGraphDB), 'graph databases can only be added to other graph databases' for src, name, dst in target.list_relations(): self.store_relation(src, name, dst) return self
[ "def", "__iadd__", "(", "self", ",", "target", ")", ":", "assert", "isinstance", "(", "target", ",", "RamGraphDB", ")", ",", "'graph databases can only be added to other graph databases'", "for", "src", ",", "name", ",", "dst", "in", "target", ".", "list_relations...
python
use this to combine databases
false
2,242,917
def overall(goback = 0, case = 1): """ To run all over the stock and to find who match the 'case' 'goback' is back to what days ago. 0 is the last day. """ from twseno import twseno for i in twseno().allstock: #timetest(i) try: if case == 1: try: a = goristock(i) ...
[ "def", "overall", "(", "goback", "=", "0", ",", "case", "=", "1", ")", ":", "from", "twseno", "import", "twseno", "for", "i", "in", "twseno", "(", ")", ".", "allstock", ":", "try", ":", "if", "case", "==", "1", ":", "try", ":", "a", "=", "goris...
python
To run all over the stock and to find who match the 'case' 'goback' is back to what days ago. 0 is the last day.
false
2,148,006
def get_default_config(self, jid, node=None): """ Request the default configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.error...
[ "def", "get_default_config", "(", "self", ",", "jid", ",", "node", "=", "None", ")", ":", "iq", "=", "aioxmpp", ".", "stanza", ".", "IQ", "(", "to", "=", "jid", ",", "type_", "=", "aioxmpp", ".", "structs", ".", "IQType", ".", "GET", ")", "iq", "...
python
Request the default configuration of a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :raises aioxmpp.errors.XMPPError: as returned by the service :return: The defau...
false
1,986,334
def _get_basin_depth_term(self, C, sites, period): """ In the case of the base model the basin depth term is switched off. Therefore we return an array of zeros. """ if period < 0.65: f_dz1 = np.zeros(len(sites.vs30), dtype=float) else: f_dz1 = C["...
[ "def", "_get_basin_depth_term", "(", "self", ",", "C", ",", "sites", ",", "period", ")", ":", "if", "period", "<", "0.65", ":", "f_dz1", "=", "np", ".", "zeros", "(", "len", "(", "sites", ".", "vs30", ")", ",", "dtype", "=", "float", ")", "else", ...
python
In the case of the base model the basin depth term is switched off. Therefore we return an array of zeros.
false
2,310,547
def complete(self, match, subject_graph): """Check the completeness of the ring match""" if not CustomPattern.complete(self, match, subject_graph): return False if self.strong: # If the ring is not strong, return False if self.size % 2 == 0: # ...
[ "def", "complete", "(", "self", ",", "match", ",", "subject_graph", ")", ":", "if", "not", "CustomPattern", ".", "complete", "(", "self", ",", "match", ",", "subject_graph", ")", ":", "return", "False", "if", "self", ".", "strong", ":", "if", "self", "...
python
Check the completeness of the ring match
false
1,655,686
def send_command(self, *args, **kwargs): """ Send command to network device retrieve output until router_prompt or expect_string By default this method will keep waiting to receive data until the network device prompt is detected. The current network device prompt will be determined aut...
[ "def", "send_command", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "len", "(", "args", ")", ">=", "2", ":", "expect_string", "=", "args", "[", "1", "]", "else", ":", "expect_string", "=", "kwargs", ".", "get", "(", "\"expect...
python
Send command to network device retrieve output until router_prompt or expect_string By default this method will keep waiting to receive data until the network device prompt is detected. The current network device prompt will be determined automatically. command_string = command to execute ...
false
2,169,025
def stopService(self): """ Gracefully stop the service. Returns: defer.Deferred: a Deferred which is triggered when the service has finished shutting down. """ self._service.factory.stopTrying() yield self._service.factory.stopFactory() ...
[ "def", "stopService", "(", "self", ")", ":", "self", ".", "_service", ".", "factory", ".", "stopTrying", "(", ")", "yield", "self", ".", "_service", ".", "factory", ".", "stopFactory", "(", ")", "yield", "service", ".", "MultiService", ".", "stopService", ...
python
Gracefully stop the service. Returns: defer.Deferred: a Deferred which is triggered when the service has finished shutting down.
false
2,250,747
def __init__(self, meta=None, coordinator=None): """The future associated to a submitted transfer request :type meta: TransferMeta :param meta: The metadata associated to the request. This object is visible to the requester. :type coordinator: TransferCoordinator :p...
[ "def", "__init__", "(", "self", ",", "meta", "=", "None", ",", "coordinator", "=", "None", ")", ":", "self", ".", "_meta", "=", "meta", "self", ".", "_coordinator", "=", "coordinator" ]
python
The future associated to a submitted transfer request :type meta: TransferMeta :param meta: The metadata associated to the request. This object is visible to the requester. :type coordinator: TransferCoordinator :param coordinator: The coordinator associated to the request....
false
2,547,572
def snmp_server_user_username(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") user = ET.SubElement(snmp_server, "user") username = ET.SubElement(user, "...
[ "def", "snmp_server_user_username", "(", "self", ",", "**", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "snmp_server", "=", "ET", ".", "SubElement", "(", "config", ",", "\"snmp-server\"", ",", "xmlns", "=", "\"urn:brocade...
python
Auto Generated Code
false
2,458,274
def log(x, base=None): """ log(x, base=e) Logarithmic function. """ _math = infer_math(x) if base is None: return _math.log(x) elif _math == math: return _math.log(x, base) else: # numpy has no option to set a base return _math.log(x) / _math.log(base)
[ "def", "log", "(", "x", ",", "base", "=", "None", ")", ":", "_math", "=", "infer_math", "(", "x", ")", "if", "base", "is", "None", ":", "return", "_math", ".", "log", "(", "x", ")", "elif", "_math", "==", "math", ":", "return", "_math", ".", "l...
python
log(x, base=e) Logarithmic function.
false
1,904,750
def raw_decrypt(self, ciphertext): """Decrypt raw ciphertext and return raw plaintext. Args: ciphertext (int): (usually from :meth:`EncryptedNumber.ciphertext()`) that is to be Paillier decrypted. Returns: int: Paillier decryption of ciphertext. This is a positi...
[ "def", "raw_decrypt", "(", "self", ",", "ciphertext", ")", ":", "if", "not", "isinstance", "(", "ciphertext", ",", "int", ")", ":", "raise", "TypeError", "(", "'Expected ciphertext to be an int, not: %s'", "%", "type", "(", "ciphertext", ")", ")", "decrypt_to_p"...
python
Decrypt raw ciphertext and return raw plaintext. Args: ciphertext (int): (usually from :meth:`EncryptedNumber.ciphertext()`) that is to be Paillier decrypted. Returns: int: Paillier decryption of ciphertext. This is a positive integer < :attr:`public_key.n`. ...
false
2,532,952
def mutator(*cache_names): """Decorator for ``Document`` methods that change the document. This decorator ensures that the object's caches are kept in sync when changes are made. """ def deco(fn): @wraps(fn) def _fn(self, *args, **kwargs): try: return fn...
[ "def", "mutator", "(", "*", "cache_names", ")", ":", "def", "deco", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "_fn", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "fn", "(", "self", ",", "...
python
Decorator for ``Document`` methods that change the document. This decorator ensures that the object's caches are kept in sync when changes are made.
false
2,595,123
def import_data_dir(target_zip): """ Imports the data specified by param <target_zip>. Renames the data dir if it already exists and unpacks the zip sub dir __data__ directly within the current active product. :param target_zip: string path to the zip file. """ from django_productline.context im...
[ "def", "import_data_dir", "(", "target_zip", ")", ":", "from", "django_productline", ".", "context", "import", "PRODUCT_CONTEXT", "new_data_dir", "=", "'{data_dir}_before_import_{ts}'", ".", "format", "(", "data_dir", "=", "PRODUCT_CONTEXT", ".", "DATA_DIR", ",", "ts"...
python
Imports the data specified by param <target_zip>. Renames the data dir if it already exists and unpacks the zip sub dir __data__ directly within the current active product. :param target_zip: string path to the zip file.
false
2,594,854
def automain(module, *, args=(), kwargs=None): ''' This decorator automatically invokes a function if the module is being run as the "__main__" module. Optionally, provide args or kwargs with which to call the function. If `module` is "__main__", the function is called, and the program is `sys.exit`...
[ "def", "automain", "(", "module", ",", "*", ",", "args", "=", "(", ")", ",", "kwargs", "=", "None", ")", ":", "if", "callable", "(", "module", ")", ":", "raise", "AutomainRequiresModuleError", "(", "module", ")", "if", "module", "==", "'__main__'", "or...
python
This decorator automatically invokes a function if the module is being run as the "__main__" module. Optionally, provide args or kwargs with which to call the function. If `module` is "__main__", the function is called, and the program is `sys.exit`ed with the return value. You can also pass `True` to c...
false
2,162,120
def get_info(df, group, info=['mean', 'std']): """ Aggregate mean and std with the given group. """ agg = df.groupby(group).agg(info) agg.columns = agg.columns.droplevel(0) return agg
[ "def", "get_info", "(", "df", ",", "group", ",", "info", "=", "[", "'mean'", ",", "'std'", "]", ")", ":", "agg", "=", "df", ".", "groupby", "(", "group", ")", ".", "agg", "(", "info", ")", "agg", ".", "columns", "=", "agg", ".", "columns", ".",...
python
Aggregate mean and std with the given group.
false
2,404,918
def store_report(self, payload): """ Save the crash report to a file. Keeping the last `offline_report_limit` files in a cyclical FIFO buffer. The newest crash report always named is 01 """ offline_reports = self.get_offline_reports() if offline_reports: # Inc...
[ "def", "store_report", "(", "self", ",", "payload", ")", ":", "offline_reports", "=", "self", ".", "get_offline_reports", "(", ")", "if", "offline_reports", ":", "for", "ii", ",", "report", "in", "enumerate", "(", "reversed", "(", "offline_reports", ")", ")"...
python
Save the crash report to a file. Keeping the last `offline_report_limit` files in a cyclical FIFO buffer. The newest crash report always named is 01
false
2,617,574
def __init__(self, generator, weak_generator=None, *args, **kwargs): """__init__ :type generator: generator :param generator: The generator object. :type weak_generator: weakref.ref :param weak_generator: Weak reference to a generator. Optional. For other parameters se...
[ "def", "__init__", "(", "self", ",", "generator", ",", "weak_generator", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "generator", "=", "generator", "if", "weak_generator", "is", "None", ":", "weak_generator", "=", "weakref", ...
python
__init__ :type generator: generator :param generator: The generator object. :type weak_generator: weakref.ref :param weak_generator: Weak reference to a generator. Optional. For other parameters see :meth:`WeakGeneratorWrapper.__init__`.
false
2,626,635
def publish(self, value): """ Accepts: list of tuples in the format (ip, port) Returns: unicode """ if not isinstance(value, list): raise ValueError(value) slaves = ['%s:%d' % x for x in value] return unicode(", ".join(slaves))
[ "def", "publish", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "raise", "ValueError", "(", "value", ")", "slaves", "=", "[", "'%s:%d'", "%", "x", "for", "x", "in", "value", "]", "return", "uni...
python
Accepts: list of tuples in the format (ip, port) Returns: unicode
false
2,103,112
def _format_arguments(ctx): """Format all `click.Argument` for a `click.Command`.""" params = [x for x in ctx.command.params if isinstance(x, click.Argument)] for param in params: for line in _format_argument(param): yield line yield ''
[ "def", "_format_arguments", "(", "ctx", ")", ":", "params", "=", "[", "x", "for", "x", "in", "ctx", ".", "command", ".", "params", "if", "isinstance", "(", "x", ",", "click", ".", "Argument", ")", "]", "for", "param", "in", "params", ":", "for", "l...
python
Format all `click.Argument` for a `click.Command`.
false
2,291,624
def _validate_config(self): """ ensure REQUIRED_CONFIG_KEYS are filled """ # exit if no backend specified if not self.backend: return # exit if no required config keys if len(self.REQUIRED_CONFIG_KEYS) < 1: return self.config = self.config or {} ...
[ "def", "_validate_config", "(", "self", ")", ":", "if", "not", "self", ".", "backend", ":", "return", "if", "len", "(", "self", ".", "REQUIRED_CONFIG_KEYS", ")", "<", "1", ":", "return", "self", ".", "config", "=", "self", ".", "config", "or", "{", "...
python
ensure REQUIRED_CONFIG_KEYS are filled
false
1,581,480
def feature_importances_(self): """ Feature importances property .. note:: Feature importance is defined only for tree boosters Feature importance is only defined when the decision tree model is chosen as base learner (`booster=gbtree`). It is not defined for other base...
[ "def", "feature_importances_", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'booster'", ",", "None", ")", "is", "not", "None", "and", "self", ".", "booster", "!=", "'gbtree'", ":", "raise", "AttributeError", "(", "'Feature importance is not defin...
python
Feature importances property .. note:: Feature importance is defined only for tree boosters Feature importance is only defined when the decision tree model is chosen as base learner (`booster=gbtree`). It is not defined for other base learner types, such as linear learners ...
false
2,039,147
def __enter__(self): """Open MemoryFile, write data and return.""" self.fio_memfile = MemoryFile() with self.fio_memfile.open( schema=self.schema, driver=self.driver, crs=self.tile.crs ) as dst: dst.writerecords(self.features) retur...
[ "def", "__enter__", "(", "self", ")", ":", "self", ".", "fio_memfile", "=", "MemoryFile", "(", ")", "with", "self", ".", "fio_memfile", ".", "open", "(", "schema", "=", "self", ".", "schema", ",", "driver", "=", "self", ".", "driver", ",", "crs", "="...
python
Open MemoryFile, write data and return.
false
2,408,247
def retrieve(self, id) : """ Retrieve a single order Returns a single order available to the user, according to the unique order ID provided If the specified order does not exist, the request will return an error :calls: ``get /orders/{id}`` :param int id: Unique identi...
[ "def", "retrieve", "(", "self", ",", "id", ")", ":", "_", ",", "_", ",", "order", "=", "self", ".", "http_client", ".", "get", "(", "\"/orders/{id}\"", ".", "format", "(", "id", "=", "id", ")", ")", "return", "order" ]
python
Retrieve a single order Returns a single order available to the user, according to the unique order ID provided If the specified order does not exist, the request will return an error :calls: ``get /orders/{id}`` :param int id: Unique identifier of a Order. :return: Dictionary ...
false
1,926,585
def reindex(args): """ %prog agpfile assume the component line order is correct, modify coordinates, this is necessary mostly due to manual edits (insert/delete) that disrupts the target coordinates. """ p = OptionParser(reindex.__doc__) p.add_option("--nogaps", default=False, action="s...
[ "def", "reindex", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "reindex", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--nogaps\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Remove all gap lin...
python
%prog agpfile assume the component line order is correct, modify coordinates, this is necessary mostly due to manual edits (insert/delete) that disrupts the target coordinates.
false
1,672,356
def withdraw(self, **params): """Submit a withdraw request. https://www.binance.com/restapipub.html Assumptions: - You must have Withdraw permissions enabled on your API key - You must have withdrawn to the address specified through the website and approved the transaction via...
[ "def", "withdraw", "(", "self", ",", "**", "params", ")", ":", "if", "'asset'", "in", "params", "and", "'name'", "not", "in", "params", ":", "params", "[", "'name'", "]", "=", "params", "[", "'asset'", "]", "res", "=", "self", ".", "_request_withdraw_a...
python
Submit a withdraw request. https://www.binance.com/restapipub.html Assumptions: - You must have Withdraw permissions enabled on your API key - You must have withdrawn to the address specified through the website and approved the transaction via email :param asset: required ...
false
1,854,439
def geo_point_n(arg, n): """Return the Nth point in a single linestring in the geometry. Negative values are counted backwards from the end of the LineString, so that -1 is the last point. Returns NULL if there is no linestring in the geometry Parameters ---------- arg : geometry n : in...
[ "def", "geo_point_n", "(", "arg", ",", "n", ")", ":", "op", "=", "ops", ".", "GeoPointN", "(", "arg", ",", "n", ")", "return", "op", ".", "to_expr", "(", ")" ]
python
Return the Nth point in a single linestring in the geometry. Negative values are counted backwards from the end of the LineString, so that -1 is the last point. Returns NULL if there is no linestring in the geometry Parameters ---------- arg : geometry n : integer Returns ------- ...
false
1,910,018
def _verify_and_add_jwt(): """ This helper method just checks and adds jwt data to the app context. Will not add jwt data if it is already present. Only use in this module """ if not app_context_has_jwt_data(): guard = current_guard() token = guard.read_token_from_header() jw...
[ "def", "_verify_and_add_jwt", "(", ")", ":", "if", "not", "app_context_has_jwt_data", "(", ")", ":", "guard", "=", "current_guard", "(", ")", "token", "=", "guard", ".", "read_token_from_header", "(", ")", "jwt_data", "=", "guard", ".", "extract_jwt_token", "(...
python
This helper method just checks and adds jwt data to the app context. Will not add jwt data if it is already present. Only use in this module
false
1,661,636
def delete_dns_server(self, service_name, deployment_name, dns_server_name): ''' Deletes a DNS server from a deployment. service_name: The name of the service. deployment_name: The name of the deployment. dns_server_name: Name of the DNS serve...
[ "def", "delete_dns_server", "(", "self", ",", "service_name", ",", "deployment_name", ",", "dns_server_name", ")", ":", "_validate_not_none", "(", "'service_name'", ",", "service_name", ")", "_validate_not_none", "(", "'deployment_name'", ",", "deployment_name", ")", ...
python
Deletes a DNS server from a deployment. service_name: The name of the service. deployment_name: The name of the deployment. dns_server_name: Name of the DNS server that you want to delete.
false
2,537,542
def kwe_by_textrank(text, top=10, pos=None, with_weight=False, key_phrase=False): """ :param text: :param top: :param pos: :param with_weight: :param key_phrase: :return: """ if pos is None: pos = ['ns', 'n', 'vn', 'v', 'nr'] tr4k = TextRank4Keyword(allow_speech_tags=pos...
[ "def", "kwe_by_textrank", "(", "text", ",", "top", "=", "10", ",", "pos", "=", "None", ",", "with_weight", "=", "False", ",", "key_phrase", "=", "False", ")", ":", "if", "pos", "is", "None", ":", "pos", "=", "[", "'ns'", ",", "'n'", ",", "'vn'", ...
python
:param text: :param top: :param pos: :param with_weight: :param key_phrase: :return:
false
1,815,054
def url(self, service): '''return URL for a tile''' if service not in TILE_SERVICES: raise TileException('unknown tile service %s' % service) url = string.Template(TILE_SERVICES[service]) (x,y) = self.tile tile_info = TileServiceInfo(x, y, self.zoom) return url.substitute(tile_info)
[ "def", "url", "(", "self", ",", "service", ")", ":", "if", "service", "not", "in", "TILE_SERVICES", ":", "raise", "TileException", "(", "'unknown tile service %s'", "%", "service", ")", "url", "=", "string", ".", "Template", "(", "TILE_SERVICES", "[", "servi...
python
return URL for a tile
false
2,425,978
def request_finished_callback(sender, **kwargs): """This function logs if the user acceses the page""" logger = logging.getLogger(__name__) level = settings.AUTOMATED_LOGGING['loglevel']['request'] user = get_current_user() uri, application, method, status = get_current_environ() excludes = se...
[ "def", "request_finished_callback", "(", "sender", ",", "**", "kwargs", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "level", "=", "settings", ".", "AUTOMATED_LOGGING", "[", "'loglevel'", "]", "[", "'request'", "]", "user", "="...
python
This function logs if the user acceses the page
false
2,615,064
def get_user_application_data_directory(): """ | Returns the user Application directory. | The difference between :func:`get_user_application_data_directory` and :func:`get_system_application_data_directory` definitions is that :func:`get_user_application_data_directory` definition will appe...
[ "def", "get_user_application_data_directory", "(", ")", ":", "system_application_data_directory", "=", "get_system_application_data_directory", "(", ")", "if", "not", "foundations", ".", "common", ".", "path_exists", "(", "system_application_data_directory", ")", ":", "LOGG...
python
| Returns the user Application directory. | The difference between :func:`get_user_application_data_directory` and :func:`get_system_application_data_directory` definitions is that :func:`get_user_application_data_directory` definition will append :attr:`foundations.globals.constants.Constants.provi...
false
1,853,783
def rename(self, new_name, database=None): """ Rename table inside MapD. References to the old table are no longer valid. Parameters ---------- new_name : string database : string Returns ------- renamed : MapDTable """ m ...
[ "def", "rename", "(", "self", ",", "new_name", ",", "database", "=", "None", ")", ":", "m", "=", "ddl", ".", "fully_qualified_re", ".", "match", "(", "new_name", ")", "if", "not", "m", "and", "database", "is", "None", ":", "database", "=", "self", "....
python
Rename table inside MapD. References to the old table are no longer valid. Parameters ---------- new_name : string database : string Returns ------- renamed : MapDTable
false
1,600,342
def to_feature(value): """Convert the given value to Feature if necessary.""" if isinstance(value, FeatureConnector): return value elif utils.is_dtype(value): # tf.int32, tf.string,... return Tensor(shape=(), dtype=tf.as_dtype(value)) elif isinstance(value, dict): return FeaturesDict(value) else:...
[ "def", "to_feature", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "FeatureConnector", ")", ":", "return", "value", "elif", "utils", ".", "is_dtype", "(", "value", ")", ":", "return", "Tensor", "(", "shape", "=", "(", ")", ",", "dtype"...
python
Convert the given value to Feature if necessary.
false
2,386,809
def replace_evict_func(self, func, only_read=False): """ >>> cache = Cache(log_level=logging.WARNING) >>> def evict(dict, evict_number=10): pass >>> cache.replace_evict_func(evict) True >>> def evict_b(dict): pass >>> cache.replace_evict_func(evict_b) Fals...
[ "def", "replace_evict_func", "(", "self", ",", "func", ",", "only_read", "=", "False", ")", ":", "self", ".", "logger", ".", "info", "(", "'Replace the evict function %s ---> %s'", "%", "(", "get_function_signature", "(", "self", ".", "evict_func", ")", ",", "...
python
>>> cache = Cache(log_level=logging.WARNING) >>> def evict(dict, evict_number=10): pass >>> cache.replace_evict_func(evict) True >>> def evict_b(dict): pass >>> cache.replace_evict_func(evict_b) False >>> def evict_c(dict, a, b): pass >>> cache.replace_evi...
false
2,505,049
def scansum(self,seq,threshold = -1000): """ m.scansum(seq,threshold = -1000) -- Sum of scores over every window in the sequence. Returns total, number of matches above threshold, average score, sum of exp(score) """ ll = self.ll sum =...
[ "def", "scansum", "(", "self", ",", "seq", ",", "threshold", "=", "-", "1000", ")", ":", "ll", "=", "self", ".", "ll", "sum", "=", "0", "width", "=", "self", ".", "width", "width_r", "=", "range", "(", "width", ")", "width_rcr", "=", "range", "("...
python
m.scansum(seq,threshold = -1000) -- Sum of scores over every window in the sequence. Returns total, number of matches above threshold, average score, sum of exp(score)
false
1,820,696
def store(self, val, addr): """ Store a VexValue in memory at the specified loaction. :param val: The VexValue of the value to store :param addr: The VexValue of the address to store into :return: None """ self.irsb_c.store(addr.rdt, val.rdt)
[ "def", "store", "(", "self", ",", "val", ",", "addr", ")", ":", "self", ".", "irsb_c", ".", "store", "(", "addr", ".", "rdt", ",", "val", ".", "rdt", ")" ]
python
Store a VexValue in memory at the specified loaction. :param val: The VexValue of the value to store :param addr: The VexValue of the address to store into :return: None
false
2,180,665
def add_hgnc_id(self, genes): """Add the correct hgnc id to a set of genes with hgnc symbols Args: genes(list(dict)): A set of genes with hgnc symbols only """ genes_by_alias = self.genes_by_alias() for gene in genes: id_info = genes_by_alias.get(gene['...
[ "def", "add_hgnc_id", "(", "self", ",", "genes", ")", ":", "genes_by_alias", "=", "self", ".", "genes_by_alias", "(", ")", "for", "gene", "in", "genes", ":", "id_info", "=", "genes_by_alias", ".", "get", "(", "gene", "[", "'hgnc_symbol'", "]", ")", "if",...
python
Add the correct hgnc id to a set of genes with hgnc symbols Args: genes(list(dict)): A set of genes with hgnc symbols only
false
2,268,481
def minus(*args): """Also, converts either to ints or to floats.""" if len(args) == 1: return -to_numeric(args[0]) return to_numeric(args[0]) - to_numeric(args[1])
[ "def", "minus", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "return", "-", "to_numeric", "(", "args", "[", "0", "]", ")", "return", "to_numeric", "(", "args", "[", "0", "]", ")", "-", "to_numeric", "(", "args", "[...
python
Also, converts either to ints or to floats.
false
1,984,501
def _compute_term_4(self, C, mag, R): """ (a16 + a17.*M + a18.*M.*M + a19.*M.*M.*M).*(d(r).^3) """ return ( (C['a16'] + C['a17'] * mag + C['a18'] * np.power(mag, 2) + C['a19'] * np.power(mag, 3)) * np.power(R, 3) )
[ "def", "_compute_term_4", "(", "self", ",", "C", ",", "mag", ",", "R", ")", ":", "return", "(", "(", "C", "[", "'a16'", "]", "+", "C", "[", "'a17'", "]", "*", "mag", "+", "C", "[", "'a18'", "]", "*", "np", ".", "power", "(", "mag", ",", "2"...
python
(a16 + a17.*M + a18.*M.*M + a19.*M.*M.*M).*(d(r).^3)
false
1,885,261
def HandleVerack(self): """Handle the `verack` response.""" m = Message('verack') self.SendSerializedMessage(m) self.leader.NodeCount += 1 self.identifier = self.leader.NodeCount logger.debug(f"{self.prefix} Handshake complete!") self.handshake_complete = True ...
[ "def", "HandleVerack", "(", "self", ")", ":", "m", "=", "Message", "(", "'verack'", ")", "self", ".", "SendSerializedMessage", "(", "m", ")", "self", ".", "leader", ".", "NodeCount", "+=", "1", "self", ".", "identifier", "=", "self", ".", "leader", "."...
python
Handle the `verack` response.
false
2,186,714
def services_list(self, io_handler, specification=None): """ Lists the services in the framework. Possibility to filter on an exact specification. """ # Head of the table headers = ("ID", "Specifications", "Bundle", "Ranking") # Lines references = ( ...
[ "def", "services_list", "(", "self", ",", "io_handler", ",", "specification", "=", "None", ")", ":", "headers", "=", "(", "\"ID\"", ",", "\"Specifications\"", ",", "\"Bundle\"", ",", "\"Ranking\"", ")", "references", "=", "(", "self", ".", "_context", ".", ...
python
Lists the services in the framework. Possibility to filter on an exact specification.
false
2,387,157
def tracking_m2m( sender, instance, action, reverse, model, pk_set, using, **kwargs ): """ m2m_changed callback. The idea is to get the model and the instance of the object being tracked, and the different objects being added/removed. It is then send to the ``_create_tracked_field_m2m`` meth...
[ "def", "tracking_m2m", "(", "sender", ",", "instance", ",", "action", ",", "reverse", ",", "model", ",", "pk_set", ",", "using", ",", "**", "kwargs", ")", ":", "action_event", "=", "{", "'pre_clear'", ":", "'CLEAR'", ",", "'pre_add'", ":", "'ADD'", ",", ...
python
m2m_changed callback. The idea is to get the model and the instance of the object being tracked, and the different objects being added/removed. It is then send to the ``_create_tracked_field_m2m`` method to extract the proper attribute for the TrackedFieldModification.
false
1,620,929
def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, PolicyV1beta1FSGroupStrategyOptions): return False return self.__dict__ == other.__dict__
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "PolicyV1beta1FSGroupStrategyOptions", ")", ":", "return", "False", "return", "self", ".", "__dict__", "==", "other", ".", "__dict__" ]
python
Returns true if both objects are equal
false
2,015,382
def __repr__(self): """ Return a representation of internal state. """ if self._rpc: # Connected state return "%s connected to %s [%s, up %s] via %r" % ( self.__class__.__name__, self.engine_id, self.engine_software, fmt.human_duration(self...
[ "def", "__repr__", "(", "self", ")", ":", "if", "self", ".", "_rpc", ":", "return", "\"%s connected to %s [%s, up %s] via %r\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "engine_id", ",", "self", ".", "engine_software", ",", "fm...
python
Return a representation of internal state.
false
2,693,545
def set(self, key, value): """ Updates the value of the given key in the loaded content. Args: key (str): Key of the property to update. value (str): New value of the property. Return: bool: Indicates whether or not a change was made. """ ...
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "match", "=", "self", ".", "_get_match", "(", "key", "=", "key", ")", "if", "not", "match", ":", "self", ".", "_log", ".", "info", "(", "'\"%s\" does not exist, so it will be added.'", ",", ...
python
Updates the value of the given key in the loaded content. Args: key (str): Key of the property to update. value (str): New value of the property. Return: bool: Indicates whether or not a change was made.
false
2,450,206
def parse(md, model, encoding='utf-8', config=None): """ Translate the Versa Markdown syntax into Versa model relationships md -- markdown source text model -- Versa model to take the output relationship encoding -- character encoding (defaults to UTF-8) Returns: The overall base URI (`@base`)...
[ "def", "parse", "(", "md", ",", "model", ",", "encoding", "=", "'utf-8'", ",", "config", "=", "None", ")", ":", "config", "=", "config", "or", "{", "}", "syntaxtypemap", "=", "{", "}", "if", "config", ".", "get", "(", "'autotype-h1'", ")", ":", "sy...
python
Translate the Versa Markdown syntax into Versa model relationships md -- markdown source text model -- Versa model to take the output relationship encoding -- character encoding (defaults to UTF-8) Returns: The overall base URI (`@base`) specified in the Markdown file, or None >>> from versa.driv...
false
1,928,500
def _scrape_document(self): '''Extract links from the DOM.''' mock_response = self._new_mock_response( self._response, self._get_temp_path('phantom', '.html') ) self._item_session.request = self._request self._item_session.response = mock_response self._proc...
[ "def", "_scrape_document", "(", "self", ")", ":", "mock_response", "=", "self", ".", "_new_mock_response", "(", "self", ".", "_response", ",", "self", ".", "_get_temp_path", "(", "'phantom'", ",", "'.html'", ")", ")", "self", ".", "_item_session", ".", "requ...
python
Extract links from the DOM.
false
2,577,271
def runningstd(t, data, width): """Compute the running standard deviation of a time series. Returns `t_new`, `std_r`. """ ne = len(t) - width t_new = np.zeros(ne) std_r = np.zeros(ne) for i in range(ne): t_new[i] = np.mean(t[i:i+width+1]) std_r[i] = scipy.stats.nan...
[ "def", "runningstd", "(", "t", ",", "data", ",", "width", ")", ":", "ne", "=", "len", "(", "t", ")", "-", "width", "t_new", "=", "np", ".", "zeros", "(", "ne", ")", "std_r", "=", "np", ".", "zeros", "(", "ne", ")", "for", "i", "in", "range", ...
python
Compute the running standard deviation of a time series. Returns `t_new`, `std_r`.
false
1,700,399
def DualDBSystemCronJob(legacy_name=None, stateful=False): """Decorator that creates AFF4 and RELDB cronjobs from a given mixin.""" def Decorator(cls): """Decorator producing 2 classes: legacy style one and a new style one.""" if not legacy_name: raise ValueError("legacy_name has to be provided") ...
[ "def", "DualDBSystemCronJob", "(", "legacy_name", "=", "None", ",", "stateful", "=", "False", ")", ":", "def", "Decorator", "(", "cls", ")", ":", "if", "not", "legacy_name", ":", "raise", "ValueError", "(", "\"legacy_name has to be provided\"", ")", "if", "sta...
python
Decorator that creates AFF4 and RELDB cronjobs from a given mixin.
false
2,518,030
def update_value(self, id_number, new_value, metadata=None): """ Update a canned value :type id_number: int :param id_number: canned value ID number :type new_value: str :param new_value: New canned value value :type metadata: str :param metadata: Optio...
[ "def", "update_value", "(", "self", ",", "id_number", ",", "new_value", ",", "metadata", "=", "None", ")", ":", "data", "=", "{", "'id'", ":", "id_number", ",", "'new_value'", ":", "new_value", "}", "if", "metadata", "is", "not", "None", ":", "data", "...
python
Update a canned value :type id_number: int :param id_number: canned value ID number :type new_value: str :param new_value: New canned value value :type metadata: str :param metadata: Optional metadata :rtype: dict :return: an empty dictionary
false
2,576,172
def load_data_table(table_name, meta_file, meta): """Return the contents and metadata of a given table. Args: table_name(str): Name of the table. meta_file(str): Path to the meta.json file. meta(dict): Contents of meta.json. Returns: tuple(pandas.DataFrame, dict) """ ...
[ "def", "load_data_table", "(", "table_name", ",", "meta_file", ",", "meta", ")", ":", "for", "table", "in", "meta", "[", "'tables'", "]", ":", "if", "table", "[", "'name'", "]", "==", "table_name", ":", "prefix", "=", "os", ".", "path", ".", "dirname",...
python
Return the contents and metadata of a given table. Args: table_name(str): Name of the table. meta_file(str): Path to the meta.json file. meta(dict): Contents of meta.json. Returns: tuple(pandas.DataFrame, dict)
false
2,324,600
def _cdist_scipy(x, y, exponent=1): """Pairwise distance between the points in two sets.""" metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.cdist(x, y, metric=metric) if exponent != 1: distances **= exponent / 2 return distances
[ "def", "_cdist_scipy", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "metric", "=", "'euclidean'", "if", "exponent", "!=", "1", ":", "metric", "=", "'sqeuclidean'", "distances", "=", "_spatial", ".", "distance", ".", "cdist", "(", "x", ",", ...
python
Pairwise distance between the points in two sets.
false
2,011,813
def rotated(self, rotation_center, angle): """Returns a RotatedBox that is obtained by rotating this box around a given center by a given angle. >>> assert RotatedBox([2, 2], 2, 1, 0.1).rotated([1, 1], np.pi/2).approx_equal([0, 2], 2, 1, np.pi/2+0.1) """ rot = np.array([[np.cos(angle), ...
[ "def", "rotated", "(", "self", ",", "rotation_center", ",", "angle", ")", ":", "rot", "=", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "angle", ")", ",", "np", ".", "sin", "(", "angle", ")", "]", ",", "[", "-", "np", ".", "sin",...
python
Returns a RotatedBox that is obtained by rotating this box around a given center by a given angle. >>> assert RotatedBox([2, 2], 2, 1, 0.1).rotated([1, 1], np.pi/2).approx_equal([0, 2], 2, 1, np.pi/2+0.1)
false
2,288,104
def pbm(self): """ Plumbum lazy property """ if not self.disable_rpyc: from plumbum import SshMachine return SshMachine(host=self.private_hostname, user=self.username, keyfile=self.key_filename, ssh_opts=["-o", "UserKnow...
[ "def", "pbm", "(", "self", ")", ":", "if", "not", "self", ".", "disable_rpyc", ":", "from", "plumbum", "import", "SshMachine", "return", "SshMachine", "(", "host", "=", "self", ".", "private_hostname", ",", "user", "=", "self", ".", "username", ",", "key...
python
Plumbum lazy property
false
2,113,928
def generate_contentinfo_from_folder(self, csvwriter, rel_path, filenames): """ Create a topic node row in Content.csv for the folder at `rel_path` and add content node rows for all the files in the `rel_path` folder. """ LOGGER.debug('IN process_folder ' + str(rel_path) + ' ...
[ "def", "generate_contentinfo_from_folder", "(", "self", ",", "csvwriter", ",", "rel_path", ",", "filenames", ")", ":", "LOGGER", ".", "debug", "(", "'IN process_folder '", "+", "str", "(", "rel_path", ")", "+", "' '", "+", "str", "(", "filenames", ")", "...
python
Create a topic node row in Content.csv for the folder at `rel_path` and add content node rows for all the files in the `rel_path` folder.
false
2,044,253
def aggregate(self, start, end): ''' This method encpsualte the metric aggregation logic. Override this method when you inherit this class. By default, it takes the last value. ''' last = self.objects( level='daily', date__lte=self.iso(end), date__...
[ "def", "aggregate", "(", "self", ",", "start", ",", "end", ")", ":", "last", "=", "self", ".", "objects", "(", "level", "=", "'daily'", ",", "date__lte", "=", "self", ".", "iso", "(", "end", ")", ",", "date__gte", "=", "self", ".", "iso", "(", "s...
python
This method encpsualte the metric aggregation logic. Override this method when you inherit this class. By default, it takes the last value.
false
1,861,413
def _read_composites(self, compositor_nodes): """Read (generate) composites.""" keepables = set() for item in compositor_nodes: self._generate_composite(item, keepables) return keepables
[ "def", "_read_composites", "(", "self", ",", "compositor_nodes", ")", ":", "keepables", "=", "set", "(", ")", "for", "item", "in", "compositor_nodes", ":", "self", ".", "_generate_composite", "(", "item", ",", "keepables", ")", "return", "keepables" ]
python
Read (generate) composites.
false
1,990,773
def cli(env, identifier): """Cancel global IP.""" mgr = SoftLayer.NetworkManager(env.client) global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier, name='global ip') if not (env.skip_confirmations or formatting.no_going_back(global_ip_id)): ...
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "global_ip_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_global_ip_ids", ",", "identifier", ",", "nam...
python
Cancel global IP.
false
1,605,309
def is_floating(dtype): """Returns whether this is a (non-quantized, real) floating point type.""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'is_floating'): return dtype.is_floating return np.issubdtype(np.dtype(dtype), np.float)
[ "def", "is_floating", "(", "dtype", ")", ":", "dtype", "=", "tf", ".", "as_dtype", "(", "dtype", ")", "if", "hasattr", "(", "dtype", ",", "'is_floating'", ")", ":", "return", "dtype", ".", "is_floating", "return", "np", ".", "issubdtype", "(", "np", "....
python
Returns whether this is a (non-quantized, real) floating point type.
false
2,328,608
def recursive_index_encode(int_array, max=32767, min=-32768): """Pack an integer array using recursive indexing. :param int_array: the input array of integers :param max: the maximum integer size :param min: the minimum integer size :return the array of integers after recursive index encoding""" ...
[ "def", "recursive_index_encode", "(", "int_array", ",", "max", "=", "32767", ",", "min", "=", "-", "32768", ")", ":", "out_arr", "=", "[", "]", "for", "curr", "in", "int_array", ":", "if", "curr", ">=", "0", ":", "while", "curr", ">=", "max", ":", ...
python
Pack an integer array using recursive indexing. :param int_array: the input array of integers :param max: the maximum integer size :param min: the minimum integer size :return the array of integers after recursive index encoding
false
2,020,415
def _lmowfv1(password): """ [MS-NLMP] v28.0 2016-07-14 3.3.1 NTLM v1 Authentication Same function as LMOWFv1 in document to create a one way hash of the password. Only used in NTLMv1 auth without session security :param password: The password of the user we are trying to authenticate with ...
[ "def", "_lmowfv1", "(", "password", ")", ":", "password", "=", "password", ".", "upper", "(", ")", "lm_pw", "=", "password", "[", "0", ":", "14", "]", "magic_str", "=", "b\"KGS!@#$%\"", "res", "=", "b''", "dobj", "=", "des", ".", "DES", "(", "lm_pw",...
python
[MS-NLMP] v28.0 2016-07-14 3.3.1 NTLM v1 Authentication Same function as LMOWFv1 in document to create a one way hash of the password. Only used in NTLMv1 auth without session security :param password: The password of the user we are trying to authenticate with :return res: A Lan Manager hash of t...
false
2,234,814
def box_add(self, name, url, provider=None, force=False): ''' Adds a box with given name, from given url. force: If True, overwrite an existing box if it exists. ''' force_opt = '--force' if force else None cmd = ['box', 'add', name, url, force_opt] if provider i...
[ "def", "box_add", "(", "self", ",", "name", ",", "url", ",", "provider", "=", "None", ",", "force", "=", "False", ")", ":", "force_opt", "=", "'--force'", "if", "force", "else", "None", "cmd", "=", "[", "'box'", ",", "'add'", ",", "name", ",", "url...
python
Adds a box with given name, from given url. force: If True, overwrite an existing box if it exists.
false
1,810,313
def canPrepare(self, ppReq) -> (bool, str): """ Return whether the batch of requests in the PRE-PREPARE can proceed to the PREPARE step. :param ppReq: any object with identifier and requestId attributes """ if self.has_sent_prepare(ppReq): return False, 'has ...
[ "def", "canPrepare", "(", "self", ",", "ppReq", ")", "->", "(", "bool", ",", "str", ")", ":", "if", "self", ".", "has_sent_prepare", "(", "ppReq", ")", ":", "return", "False", ",", "'has already sent PREPARE for {}'", ".", "format", "(", "ppReq", ")", "r...
python
Return whether the batch of requests in the PRE-PREPARE can proceed to the PREPARE step. :param ppReq: any object with identifier and requestId attributes
false
2,685,079
def _default_pprint(obj, p, cycle): """ The default print function. Used if an object does not provide one and it's none of the builtin objects. """ klass = getattr(obj, '__class__', None) or type(obj) if getattr(klass, '__repr__', None) not in _baseclass_reprs: # A user-provided repr. ...
[ "def", "_default_pprint", "(", "obj", ",", "p", ",", "cycle", ")", ":", "klass", "=", "getattr", "(", "obj", ",", "'__class__'", ",", "None", ")", "or", "type", "(", "obj", ")", "if", "getattr", "(", "klass", ",", "'__repr__'", ",", "None", ")", "n...
python
The default print function. Used if an object does not provide one and it's none of the builtin objects.
false
1,601,135
def QA_util_id2date(idx, client): """ 从数据库中查询 通达信时间 :param idx: 字符串 -- 数据库index :param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取 :return: Str -- 通达信数据库时间 """ coll = client.quantaxis.trade_date temp_str = coll.find_o...
[ "def", "QA_util_id2date", "(", "idx", ",", "client", ")", ":", "coll", "=", "client", ".", "quantaxis", ".", "trade_date", "temp_str", "=", "coll", ".", "find_one", "(", "{", "'num'", ":", "idx", "}", ")", "return", "temp_str", "[", "'date'", "]" ]
python
从数据库中查询 通达信时间 :param idx: 字符串 -- 数据库index :param client: pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取 :return: Str -- 通达信数据库时间
false
2,286,291
def get_isotope_dicts(element='', database='ENDF_VII'): """return a dictionary with list of isotopes found in database and name of database files Parameters: =========== element: string. Name of the element ex: 'Ag' database: string (default is ENDF_VII) Returns: ======== ...
[ "def", "get_isotope_dicts", "(", "element", "=", "''", ",", "database", "=", "'ENDF_VII'", ")", ":", "_file_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "_database_folder", "=", "os", ...
python
return a dictionary with list of isotopes found in database and name of database files Parameters: =========== element: string. Name of the element ex: 'Ag' database: string (default is ENDF_VII) Returns: ======== dictionary with isotopes and files ex: {'Ag': {'isotope...
false
2,149,648
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Operation(key) if key not in Operation._member_map_: extend_enum(Operation, key, default) return Operation[key]
[ "def", "get", "(", "key", ",", "default", "=", "-", "1", ")", ":", "if", "isinstance", "(", "key", ",", "int", ")", ":", "return", "Operation", "(", "key", ")", "if", "key", "not", "in", "Operation", ".", "_member_map_", ":", "extend_enum", "(", "O...
python
Backport support for original codes.
false
2,363,973
def parse_get_list_response(content): """Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names. ...
[ "def", "parse_get_list_response", "(", "content", ")", ":", "try", ":", "tree", "=", "etree", ".", "fromstring", "(", "content", ")", "hrees", "=", "[", "Urn", ".", "separate", "+", "unquote", "(", "urlsplit", "(", "hree", ".", "text", ")", ".", "path"...
python
Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names.
false
2,433,759
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Transaction object for each one, initializing them one at a time, and changing the attrs attribute (which ...
[ "def", "convertDict2Attrs", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "for", "n", ",", "t", "in", "enumerate", "(", "self", ".", "attrs", ")", ":", "try", ":", "params", "=", "self", ".", "params", "except", "AttributeError", "as"...
python
The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Transaction object for each one, initializing them one at a time, and changing the attrs attribute (which just holds a list of plain dictionaries) with a M...
false
1,995,739
def _prepare_atoms(topology, compute_cycles=False): """Compute cycles and add white-/blacklists to atoms.""" atom1 = next(topology.atoms()) has_whitelists = hasattr(atom1, 'whitelist') has_cycles = hasattr(atom1, 'cycles') compute_cycles = compute_cycles and not has_cycles if compute_cycles or ...
[ "def", "_prepare_atoms", "(", "topology", ",", "compute_cycles", "=", "False", ")", ":", "atom1", "=", "next", "(", "topology", ".", "atoms", "(", ")", ")", "has_whitelists", "=", "hasattr", "(", "atom1", ",", "'whitelist'", ")", "has_cycles", "=", "hasatt...
python
Compute cycles and add white-/blacklists to atoms.
false
2,173,889
def _find_bgzip(): """return path to bgzip if found and meets version requirements, else exception""" missing_file_exception = OSError if six.PY2 else FileNotFoundError min_bgzip_version = ".".join(map(str, min_bgzip_version_info)) exe = os.environ.get("SEQREPO_BGZIP_PATH", which("bgzip") or "/usr/bin/b...
[ "def", "_find_bgzip", "(", ")", ":", "missing_file_exception", "=", "OSError", "if", "six", ".", "PY2", "else", "FileNotFoundError", "min_bgzip_version", "=", "\".\"", ".", "join", "(", "map", "(", "str", ",", "min_bgzip_version_info", ")", ")", "exe", "=", ...
python
return path to bgzip if found and meets version requirements, else exception
false
1,619,809
def approxEqual(x, y, *args, **kwargs): """approxEqual(float1, float2[, tol=1e-18, rel=1e-7]) -> True|False approxEqual(obj1, obj2[, *args, **kwargs]) -> True|False Return True if x and y are approximately equal, otherwise False. If x and y are floats, return True if y is within either absolute error ...
[ "def", "approxEqual", "(", "x", ",", "y", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "not", "(", "type", "(", "x", ")", "is", "type", "(", "y", ")", "is", "float", ")", ":", "methodname", "=", "'__approxEqual__'", "for", "a", ",", "...
python
approxEqual(float1, float2[, tol=1e-18, rel=1e-7]) -> True|False approxEqual(obj1, obj2[, *args, **kwargs]) -> True|False Return True if x and y are approximately equal, otherwise False. If x and y are floats, return True if y is within either absolute error tol or relative error rel of x. You can dis...
false
2,161,801
def patch_cmdline_parser(): """ Patches the ``luigi.cmdline_parser.CmdlineParser`` to store the original command line arguments for later processing in the :py:class:`law.config.Config`. """ # store original functions _init = luigi.cmdline_parser.CmdlineParser.__init__ # patch init def ...
[ "def", "patch_cmdline_parser", "(", ")", ":", "_init", "=", "luigi", ".", "cmdline_parser", ".", "CmdlineParser", ".", "__init__", "def", "__init__", "(", "self", ",", "cmdline_args", ")", ":", "_init", "(", "self", ",", "cmdline_args", ")", "self", ".", "...
python
Patches the ``luigi.cmdline_parser.CmdlineParser`` to store the original command line arguments for later processing in the :py:class:`law.config.Config`.
false
2,641,223
def _parse_xml(self, xml): """Extracts objects representing and interacting with the settings in the xml tag. """ vms("Parsing <testing> XML child tag.", 2) self.timeout = get_attrib(xml, "timeout", cast=int) for child in xml: if child.tag == "command": ...
[ "def", "_parse_xml", "(", "self", ",", "xml", ")", ":", "vms", "(", "\"Parsing <testing> XML child tag.\"", ",", "2", ")", "self", ".", "timeout", "=", "get_attrib", "(", "xml", ",", "\"timeout\"", ",", "cast", "=", "int", ")", "for", "child", "in", "xml...
python
Extracts objects representing and interacting with the settings in the xml tag.
false
2,610,847
def svg2png(svg_file_path, png_file_path, dpi=150, inkscape_binpath=None): """ Transform SVG file to PNG file """ return inkscape_export(svg_file_path, png_file_path, export_flag="-e", dpi=dpi, inkscape_binpath=inkscape_binpath)
[ "def", "svg2png", "(", "svg_file_path", ",", "png_file_path", ",", "dpi", "=", "150", ",", "inkscape_binpath", "=", "None", ")", ":", "return", "inkscape_export", "(", "svg_file_path", ",", "png_file_path", ",", "export_flag", "=", "\"-e\"", ",", "dpi", "=", ...
python
Transform SVG file to PNG file
false
2,088,034
def process(self): """Periodic nonblocking processes""" super(NativeBLEVirtualInterface, self).process() if (not self._stream_sm_running) and (not self.reports.empty()): self._stream_data() if (not self._trace_sm_running) and (not self.traces.empty()): self._se...
[ "def", "process", "(", "self", ")", ":", "super", "(", "NativeBLEVirtualInterface", ",", "self", ")", ".", "process", "(", ")", "if", "(", "not", "self", ".", "_stream_sm_running", ")", "and", "(", "not", "self", ".", "reports", ".", "empty", "(", ")",...
python
Periodic nonblocking processes
false
2,186,486
def transport_jsonrpc(self): """ Installs the JSON-RPC transport bundles and instantiates components """ # Install the bundle self.context.install_bundle("pelix.remote.json_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discover...
[ "def", "transport_jsonrpc", "(", "self", ")", ":", "self", ".", "context", ".", "install_bundle", "(", "\"pelix.remote.json_rpc\"", ")", ".", "start", "(", ")", "with", "use_waiting_list", "(", "self", ".", "context", ")", "as", "ipopo", ":", "ipopo", ".", ...
python
Installs the JSON-RPC transport bundles and instantiates components
false
2,421,113
def path_from_keywords(keywords,into='path'): ''' turns keyword pairs into path or filename if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy ''' subdirs = [] def prepare_string(s): s = str(s) s = re.sub('[]...
[ "def", "path_from_keywords", "(", "keywords", ",", "into", "=", "'path'", ")", ":", "subdirs", "=", "[", "]", "def", "prepare_string", "(", "s", ")", ":", "s", "=", "str", "(", "s", ")", "s", "=", "re", ".", "sub", "(", "'[][{},*\"'", "+", "f\"'{os...
python
turns keyword pairs into path or filename if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy
false
1,599,466
def winsorize(row, min_percentile, max_percentile): """ This implementation is based on scipy.stats.mstats.winsorize """ a = row.copy() nan_count = isnan(row).sum() nonnan_count = a.size - nan_count # NOTE: argsort() sorts nans to the end of the array. idx = a.argsort() # Set value...
[ "def", "winsorize", "(", "row", ",", "min_percentile", ",", "max_percentile", ")", ":", "a", "=", "row", ".", "copy", "(", ")", "nan_count", "=", "isnan", "(", "row", ")", ".", "sum", "(", ")", "nonnan_count", "=", "a", ".", "size", "-", "nan_count",...
python
This implementation is based on scipy.stats.mstats.winsorize
false
1,636,680
def create_empty_crl( ca_name, cacert_path=None, ca_filename=None, crl_file=None, digest='sha256'): ''' Create an empty Certificate Revocation List. .. versionadded:: 2015.8.0 ca_name name of the CA cacert_path absolute path to ca certificate...
[ "def", "create_empty_crl", "(", "ca_name", ",", "cacert_path", "=", "None", ",", "ca_filename", "=", "None", ",", "crl_file", "=", "None", ",", "digest", "=", "'sha256'", ")", ":", "set_ca_path", "(", "cacert_path", ")", "if", "not", "ca_filename", ":", "c...
python
Create an empty Certificate Revocation List. .. versionadded:: 2015.8.0 ca_name name of the CA cacert_path absolute path to ca certificates root directory ca_filename alternative filename for the CA .. versionadded:: 2015.5.3 crl_file full path to the CRL ...
false
2,403,720
def add_native_name(self, name): """Add native name. Args: :param name: native name for the current author. :type name: string """ self._ensure_field('name', {}) self.obj['name'].setdefault('native_names', []).append(name)
[ "def", "add_native_name", "(", "self", ",", "name", ")", ":", "self", ".", "_ensure_field", "(", "'name'", ",", "{", "}", ")", "self", ".", "obj", "[", "'name'", "]", ".", "setdefault", "(", "'native_names'", ",", "[", "]", ")", ".", "append", "(", ...
python
Add native name. Args: :param name: native name for the current author. :type name: string
false
2,678,792
def mixin_class(target, cls): """Mix cls content in target.""" for name, field in getmembers(cls): Mixin.mixin(target, field, name)
[ "def", "mixin_class", "(", "target", ",", "cls", ")", ":", "for", "name", ",", "field", "in", "getmembers", "(", "cls", ")", ":", "Mixin", ".", "mixin", "(", "target", ",", "field", ",", "name", ")" ]
python
Mix cls content in target.
false
2,083,001
def get_descriptor_defaults(self, api_info, hostname=None, x_google_api_name=False): """Gets a default configuration for a service. Args: api_info: _ApiInfo object for this service. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. ...
[ "def", "get_descriptor_defaults", "(", "self", ",", "api_info", ",", "hostname", "=", "None", ",", "x_google_api_name", "=", "False", ")", ":", "hostname", "=", "(", "hostname", "or", "util", ".", "get_app_hostname", "(", ")", "or", "api_info", ".", "hostnam...
python
Gets a default configuration for a service. Args: api_info: _ApiInfo object for this service. hostname: string, Hostname of the API, to override the value set on the current service. Defaults to None. Returns: A dictionary with the default configuration.
false
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
3