repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
bokeh/bokeh
bokeh/util/deprecation.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/deprecation.py#L45-L68
def deprecated(since_or_msg, old=None, new=None, extra=None): """ Issue a nicely formatted deprecation warning. """ if isinstance(since_or_msg, tuple): if old is None or new is None: raise ValueError("deprecated entity and a replacement are required") if len(since_or_msg) != 3 or not all(isinstance(x, int) and x >=0 for x in since_or_msg): raise ValueError("invalid version tuple: %r" % (since_or_msg,)) since = "%d.%d.%d" % since_or_msg message = "%(old)s was deprecated in Bokeh %(since)s and will be removed, use %(new)s instead." message = message % dict(old=old, since=since, new=new) if extra is not None: message += " " + extra.strip() elif isinstance(since_or_msg, six.string_types): if not (old is None and new is None and extra is None): raise ValueError("deprecated(message) signature doesn't allow extra arguments") message = since_or_msg else: raise ValueError("expected a version tuple or string message") warn(message)
[ "def", "deprecated", "(", "since_or_msg", ",", "old", "=", "None", ",", "new", "=", "None", ",", "extra", "=", "None", ")", ":", "if", "isinstance", "(", "since_or_msg", ",", "tuple", ")", ":", "if", "old", "is", "None", "or", "new", "is", "None", ...
Issue a nicely formatted deprecation warning.
[ "Issue", "a", "nicely", "formatted", "deprecation", "warning", "." ]
python
train
hannes-brt/hebel
hebel/pycuda_ops/cudart.py
https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cudart.py#L665-L682
def cudaGetDevice(): """ Get current CUDA device. Return the identifying number of the device currently used to process CUDA operations. Returns ------- dev : int Device number. """ dev = ctypes.c_int() status = _libcudart.cudaGetDevice(ctypes.byref(dev)) cudaCheckStatus(status) return dev.value
[ "def", "cudaGetDevice", "(", ")", ":", "dev", "=", "ctypes", ".", "c_int", "(", ")", "status", "=", "_libcudart", ".", "cudaGetDevice", "(", "ctypes", ".", "byref", "(", "dev", ")", ")", "cudaCheckStatus", "(", "status", ")", "return", "dev", ".", "val...
Get current CUDA device. Return the identifying number of the device currently used to process CUDA operations. Returns ------- dev : int Device number.
[ "Get", "current", "CUDA", "device", "." ]
python
train
mozilla/build-mar
src/mardor/reader.py
https://github.com/mozilla/build-mar/blob/d8c3b3469e55654d31f430cb343fd89392196c4e/src/mardor/reader.py#L228-L237
def productinfo(self): """Return the productversion and channel of this MAR if present.""" if not self.mardata.additional: return None for s in self.mardata.additional.sections: if s.id == 1: return str(s.productversion), str(s.channel) return None
[ "def", "productinfo", "(", "self", ")", ":", "if", "not", "self", ".", "mardata", ".", "additional", ":", "return", "None", "for", "s", "in", "self", ".", "mardata", ".", "additional", ".", "sections", ":", "if", "s", ".", "id", "==", "1", ":", "re...
Return the productversion and channel of this MAR if present.
[ "Return", "the", "productversion", "and", "channel", "of", "this", "MAR", "if", "present", "." ]
python
train
KnorrFG/pyparadigm
pyparadigm/misc.py
https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/misc.py#L70-L87
def display(surface): """Displays a pygame.Surface in the window. in pygame the window is represented through a surface, on which you can draw as on any other pygame.Surface. A refernce to to the screen can be optained via the :py:func:`pygame.display.get_surface` function. To display the contents of the screen surface in the window :py:func:`pygame.display.flip` needs to be called. :py:func:`display` draws the surface onto the screen surface at the postion (0, 0), and then calls :py:func:`flip`. :param surface: the pygame.Surface to display :type surface: pygame.Surface """ screen = pygame.display.get_surface() screen.blit(surface, (0, 0)) pygame.display.flip()
[ "def", "display", "(", "surface", ")", ":", "screen", "=", "pygame", ".", "display", ".", "get_surface", "(", ")", "screen", ".", "blit", "(", "surface", ",", "(", "0", ",", "0", ")", ")", "pygame", ".", "display", ".", "flip", "(", ")" ]
Displays a pygame.Surface in the window. in pygame the window is represented through a surface, on which you can draw as on any other pygame.Surface. A refernce to to the screen can be optained via the :py:func:`pygame.display.get_surface` function. To display the contents of the screen surface in the window :py:func:`pygame.display.flip` needs to be called. :py:func:`display` draws the surface onto the screen surface at the postion (0, 0), and then calls :py:func:`flip`. :param surface: the pygame.Surface to display :type surface: pygame.Surface
[ "Displays", "a", "pygame", ".", "Surface", "in", "the", "window", ".", "in", "pygame", "the", "window", "is", "represented", "through", "a", "surface", "on", "which", "you", "can", "draw", "as", "on", "any", "other", "pygame", ".", "Surface", ".", "A", ...
python
train
saltstack/salt
salt/states/cloud.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cloud.py#L384-L439
def volume_attached(name, server_name, provider=None, **kwargs): ''' Check if a block volume is attached. ''' ret = _check_name(name) if not ret['result']: return ret ret = _check_name(server_name) if not ret['result']: return ret volumes = __salt__['cloud.volume_list'](provider=provider) instance = __salt__['cloud.action']( fun='show_instance', names=server_name ) if name in volumes and volumes[name]['attachments']: volume = volumes[name] ret['comment'] = ( 'Volume {name} is already attached: {attachments}'.format( **volumes[name] ) ) ret['result'] = True return ret elif name not in volumes: ret['comment'] = 'Volume {0} does not exist'.format(name) ret['result'] = False return ret elif not instance: ret['comment'] = 'Server {0} does not exist'.format(server_name) ret['result'] = False return ret elif __opts__['test']: ret['comment'] = 'Volume {0} will be will be attached.'.format( name ) ret['result'] = None return ret response = __salt__['cloud.volume_attach']( provider=provider, names=name, server_name=server_name, **kwargs ) if response: ret['result'] = True ret['comment'] = 'Volume {0} was created'.format(name) ret['changes'] = {'old': volumes[name], 'new': response} else: ret['result'] = False ret['comment'] = 'Volume {0} failed to attach.'.format(name) return ret
[ "def", "volume_attached", "(", "name", ",", "server_name", ",", "provider", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "_check_name", "(", "name", ")", "if", "not", "ret", "[", "'result'", "]", ":", "return", "ret", "ret", "=", "_che...
Check if a block volume is attached.
[ "Check", "if", "a", "block", "volume", "is", "attached", "." ]
python
train
pallets/werkzeug
src/werkzeug/debug/__init__.py
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L337-L350
def display_console(self, request): """Display a standalone shell.""" if 0 not in self.frames: if self.console_init_func is None: ns = {} else: ns = dict(self.console_init_func()) ns.setdefault("app", self.app) self.frames[0] = _ConsoleFrame(ns) is_trusted = bool(self.check_pin_trust(request.environ)) return Response( render_console_html(secret=self.secret, evalex_trusted=is_trusted), mimetype="text/html", )
[ "def", "display_console", "(", "self", ",", "request", ")", ":", "if", "0", "not", "in", "self", ".", "frames", ":", "if", "self", ".", "console_init_func", "is", "None", ":", "ns", "=", "{", "}", "else", ":", "ns", "=", "dict", "(", "self", ".", ...
Display a standalone shell.
[ "Display", "a", "standalone", "shell", "." ]
python
train
Opentrons/opentrons
api/src/opentrons/server/endpoints/serverlib_fallback.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/serverlib_fallback.py#L73-L81
def _set_ignored_version(version): """ Private helper function that writes the most updated API version that was ignored by a user in the app :param version: Most recent ignored API update """ data = {'version': version} with open(filepath, 'w') as data_file: json.dump(data, data_file)
[ "def", "_set_ignored_version", "(", "version", ")", ":", "data", "=", "{", "'version'", ":", "version", "}", "with", "open", "(", "filepath", ",", "'w'", ")", "as", "data_file", ":", "json", ".", "dump", "(", "data", ",", "data_file", ")" ]
Private helper function that writes the most updated API version that was ignored by a user in the app :param version: Most recent ignored API update
[ "Private", "helper", "function", "that", "writes", "the", "most", "updated", "API", "version", "that", "was", "ignored", "by", "a", "user", "in", "the", "app", ":", "param", "version", ":", "Most", "recent", "ignored", "API", "update" ]
python
train
saltstack/salt
salt/engines/libvirt_events.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/libvirt_events.py#L336-L345
def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque): ''' Domain disk change events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'oldSrcPath': old_src, 'newSrcPath': new_src, 'dev': dev, 'reason': _get_libvirt_enum_string('VIR_DOMAIN_EVENT_DISK_', reason) })
[ "def", "_domain_event_disk_change_cb", "(", "conn", ",", "domain", ",", "old_src", ",", "new_src", ",", "dev", ",", "reason", ",", "opaque", ")", ":", "_salt_send_domain_event", "(", "opaque", ",", "conn", ",", "domain", ",", "opaque", "[", "'event'", "]", ...
Domain disk change events handler
[ "Domain", "disk", "change", "events", "handler" ]
python
train
paramiko/paramiko
paramiko/packet.py
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L241-L255
def handshake_timed_out(self): """ Checks if the handshake has timed out. If `start_handshake` wasn't called before the call to this function, the return value will always be `False`. If the handshake completed before a timeout was reached, the return value will be `False` :return: handshake time out status, as a `bool` """ if not self.__timer: return False if self.__handshake_complete: return False return self.__timer_expired
[ "def", "handshake_timed_out", "(", "self", ")", ":", "if", "not", "self", ".", "__timer", ":", "return", "False", "if", "self", ".", "__handshake_complete", ":", "return", "False", "return", "self", ".", "__timer_expired" ]
Checks if the handshake has timed out. If `start_handshake` wasn't called before the call to this function, the return value will always be `False`. If the handshake completed before a timeout was reached, the return value will be `False` :return: handshake time out status, as a `bool`
[ "Checks", "if", "the", "handshake", "has", "timed", "out", "." ]
python
train
phaethon/kamene
kamene/contrib/gsm_um.py
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L2428-L2439
def ptmsiReallocationCommand(PTmsiSignature_presence=0): """P-TMSI REALLOCATION COMMAND Section 9.4.7""" a = TpPd(pd=0x3) b = MessageType(mesType=0x10) # 00010000 c = MobileId() d = RoutingAreaIdentification() e = ForceToStandbyAndSpareHalfOctets() packet = a / b / c / d / e if PTmsiSignature_presence is 1: g = PTmsiSignature(ieiPTS=0x19) packet = packet / g return packet
[ "def", "ptmsiReallocationCommand", "(", "PTmsiSignature_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x10", ")", "# 00010000", "c", "=", "MobileId", "(", ")", "d", "=", "Rou...
P-TMSI REALLOCATION COMMAND Section 9.4.7
[ "P", "-", "TMSI", "REALLOCATION", "COMMAND", "Section", "9", ".", "4", ".", "7" ]
python
train
gem/oq-engine
openquake/hazardlib/probability_map.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/probability_map.py#L222-L245
def convert2(self, imtls, sids): """ Convert a probability map into a composite array of shape (N,) and dtype `imtls.dt`. :param imtls: DictArray instance :param sids: the IDs of the sites we are interested in :returns: an array of curves of shape (N,) """ assert self.shape_z == 1, self.shape_z curves = numpy.zeros(len(sids), imtls.dt) for imt in curves.dtype.names: curves_by_imt = curves[imt] for i, sid in numpy.ndenumerate(sids): try: pcurve = self[sid] except KeyError: pass # the poes will be zeros else: curves_by_imt[i] = pcurve.array[imtls(imt), 0] return curves
[ "def", "convert2", "(", "self", ",", "imtls", ",", "sids", ")", ":", "assert", "self", ".", "shape_z", "==", "1", ",", "self", ".", "shape_z", "curves", "=", "numpy", ".", "zeros", "(", "len", "(", "sids", ")", ",", "imtls", ".", "dt", ")", "for"...
Convert a probability map into a composite array of shape (N,) and dtype `imtls.dt`. :param imtls: DictArray instance :param sids: the IDs of the sites we are interested in :returns: an array of curves of shape (N,)
[ "Convert", "a", "probability", "map", "into", "a", "composite", "array", "of", "shape", "(", "N", ")", "and", "dtype", "imtls", ".", "dt", "." ]
python
train
kubernetes-client/python
kubernetes/client/apis/autoscaling_v2beta1_api.py
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/autoscaling_v2beta1_api.py#L1219-L1243
def replace_namespaced_horizontal_pod_autoscaler(self, name, namespace, body, **kwargs): """ replace the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_horizontal_pod_autoscaler(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V2beta1HorizontalPodAutoscaler body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.replace_namespaced_horizontal_pod_autoscaler_with_http_info(name, namespace, body, **kwargs) else: (data) = self.replace_namespaced_horizontal_pod_autoscaler_with_http_info(name, namespace, body, **kwargs) return data
[ "def", "replace_namespaced_horizontal_pod_autoscaler", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")",...
replace the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_horizontal_pod_autoscaler(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the HorizontalPodAutoscaler (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V2beta1HorizontalPodAutoscaler body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :return: V2beta1HorizontalPodAutoscaler If the method is called asynchronously, returns the request thread.
[ "replace", "the", "specified", "HorizontalPodAutoscaler", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "pass", "async_req", "=", "True", ">>>", "thread", ...
python
train
knipknap/exscript
Exscript/account.py
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/account.py#L105-L121
def acquire(self, signal=True): """ Locks the account. Method has no effect if the constructor argument `needs_lock` wsa set to False. :type signal: bool :param signal: Whether to emit the acquired_event signal. """ if not self.needs_lock: return with self.synclock: while not self.lock.acquire(False): self.synclock.wait() if signal: self.acquired_event(self) self.synclock.notify_all()
[ "def", "acquire", "(", "self", ",", "signal", "=", "True", ")", ":", "if", "not", "self", ".", "needs_lock", ":", "return", "with", "self", ".", "synclock", ":", "while", "not", "self", ".", "lock", ".", "acquire", "(", "False", ")", ":", "self", "...
Locks the account. Method has no effect if the constructor argument `needs_lock` wsa set to False. :type signal: bool :param signal: Whether to emit the acquired_event signal.
[ "Locks", "the", "account", ".", "Method", "has", "no", "effect", "if", "the", "constructor", "argument", "needs_lock", "wsa", "set", "to", "False", "." ]
python
train
astropy/regions
regions/io/ds9/read.py
https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L215-L224
def set_coordsys(self, coordsys): """ Transform coordinate system # TODO: needs expert attention """ if coordsys in self.coordsys_mapping: self.coordsys = self.coordsys_mapping[coordsys] else: self.coordsys = coordsys
[ "def", "set_coordsys", "(", "self", ",", "coordsys", ")", ":", "if", "coordsys", "in", "self", ".", "coordsys_mapping", ":", "self", ".", "coordsys", "=", "self", ".", "coordsys_mapping", "[", "coordsys", "]", "else", ":", "self", ".", "coordsys", "=", "...
Transform coordinate system # TODO: needs expert attention
[ "Transform", "coordinate", "system" ]
python
train
PSPC-SPAC-buyandsell/von_anchor
von_anchor/anchor/issuer.py
https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/anchor/issuer.py#L424-L462
async def create_cred_offer(self, schema_seq_no: int) -> str: """ Create credential offer as Issuer for given schema. Raise CorruptWallet if the wallet has no private key for the corresponding credential definition. Raise WalletState for closed wallet. :param schema_seq_no: schema sequence number :return: credential offer json for use in storing credentials at HolderProver. """ LOGGER.debug('Issuer.create_cred_offer >>> schema_seq_no: %s', schema_seq_no) if not self.wallet.handle: LOGGER.debug('Issuer.create_cred_offer <!< Wallet %s is closed', self.name) raise WalletState('Wallet {} is closed'.format(self.name)) if not self.pool: LOGGER.debug('Issuer.create_cred_offer <!< issuer %s has no pool', self.name) raise AbsentPool('Issuer {} has no pool: cannot create cred offer'.format(self.name)) rv = None cd_id = cred_def_id(self.did, schema_seq_no, self.pool.protocol) try: rv = await anoncreds.issuer_create_credential_offer(self.wallet.handle, cd_id) except IndyError as x_indy: if x_indy.error_code == ErrorCode.WalletNotFoundError: LOGGER.debug( 'Issuer.create_cred_offer <!< did not issue cred definition from wallet %s', self.name) raise CorruptWallet('Cannot create cred offer: did not issue cred definition from wallet {}'.format( self.name)) LOGGER.debug( 'Issuer.create_cred_offer <!< cannot create cred offer, indy error code %s', x_indy.error_code) raise LOGGER.debug('Issuer.create_cred_offer <<< %s', rv) return rv
[ "async", "def", "create_cred_offer", "(", "self", ",", "schema_seq_no", ":", "int", ")", "->", "str", ":", "LOGGER", ".", "debug", "(", "'Issuer.create_cred_offer >>> schema_seq_no: %s'", ",", "schema_seq_no", ")", "if", "not", "self", ".", "wallet", ".", "handl...
Create credential offer as Issuer for given schema. Raise CorruptWallet if the wallet has no private key for the corresponding credential definition. Raise WalletState for closed wallet. :param schema_seq_no: schema sequence number :return: credential offer json for use in storing credentials at HolderProver.
[ "Create", "credential", "offer", "as", "Issuer", "for", "given", "schema", "." ]
python
train
blockstack/blockstack-core
blockstack/lib/fast_sync.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/fast_sync.py#L243-L407
def fast_sync_snapshot(working_dir, export_path, private_key, block_number ): """ Export all the local state for fast-sync. If block_number is given, then the name database at that particular block number will be taken. The exported tarball will be signed with the given private key, and the signature will be appended to the end of the file. Return True if we succeed Return False if not """ db_paths = None found = True tmpdir = None namedb_path = None def _cleanup(path): try: shutil.rmtree(path) except Exception, e: log.exception(e) log.error("Failed to clear directory {}".format(path)) def _log_backup(path): sb = None try: sb = os.stat(path) except Exception, e: log.exception(e) log.error("Failed to stat {}".format(path)) return False log.debug("Copy {} ({} bytes)".format(path, sb.st_size)) def _copy_paths(src_paths, dest_dir): for db_path in src_paths: dest_path = os.path.join(dest_dir, os.path.basename(db_path)) try: _log_backup(db_path) shutil.copy(db_path, dest_path) except Exception, e: log.exception(e) log.error("Failed to copy {} to {}".format(db_path, dest_path)) return False return True def _zonefile_copy_progress(): def inner(src, names): # ugly hack to work around the lack of a `nonlocal` keyword in Python 2.x for name in names: if name.endswith('.txt'): inner.zonefile_count += 1 if inner.zonefile_count % 100 == 0: log.debug("{} zone files copied".format(inner.zonefile_count)) return [] inner.zonefile_count = 0 return inner _zonefile_copy_progress = _zonefile_copy_progress() # make sure we have the apppriate tools tools = ['sqlite3'] for tool in tools: rc = os.system("which {} > /dev/null".format(tool)) if rc != 0: log.error("'{}' command not found".format(tool)) return False if not os.path.exists(working_dir): log.error("No such directory {}".format(working_dir)) return False if block_number is None: # last backup all_blocks = BlockstackDB.get_backup_blocks(virtualchain_hooks, working_dir) if len(all_blocks) == 0: log.error("No backups available") return False block_number = max(all_blocks) log.debug("Snapshot from block {}".format(block_number)) # use a backup database db_paths = BlockstackDB.get_backup_paths(block_number, virtualchain_hooks, working_dir) # include namespace keychains db = virtualchain_hooks.get_db_state(working_dir) namespace_ids = db.get_all_namespace_ids() all_namespace_keychain_paths = [os.path.join(working_dir, '{}.keychain'.format(nsid)) for nsid in namespace_ids] namespace_keychain_paths = filter(lambda nsp: os.path.exists(nsp), all_namespace_keychain_paths) for p in db_paths: if not os.path.exists(p): log.error("Missing file: '%s'" % p) found = False if not found: return False try: tmpdir = tempfile.mkdtemp(prefix='.blockstack-export-') except Exception, e: log.exception(e) return False # copying from backups backups_path = os.path.join(tmpdir, "backups") try: os.makedirs(backups_path) except Exception, e: log.exception(e) log.error("Failed to make directory {}".format(backups_path)) _cleanup(tmpdir) return False rc = _copy_paths(db_paths, backups_path) if not rc: _cleanup(tmpdir) return False # copy over zone files zonefiles_path = os.path.join(working_dir, "zonefiles") dest_path = os.path.join(tmpdir, "zonefiles") try: shutil.copytree(zonefiles_path, dest_path, ignore=_zonefile_copy_progress) except Exception, e: log.exception(e) log.error('Failed to copy {} to {}'.format(zonefiles_path, dest_path)) _cleanup(tmpdir) return False # copy over namespace keychains rc = _copy_paths(namespace_keychain_paths, tmpdir) if not rc: log.error("Failed to copy namespace keychain paths") _cleanup(tmpdir) return False # compress export_path = os.path.abspath(export_path) res = fast_sync_snapshot_compress(tmpdir, export_path) if 'error' in res: log.error("Faield to compress {} to {}: {}".format(tmpdir, export_path, res['error'])) _cleanup(tmpdir) return False log.debug("Wrote {} bytes".format(os.stat(export_path).st_size)) # sign rc = fast_sync_sign_snapshot( export_path, private_key, first=True ) if not rc: log.error("Failed to sign snapshot {}".format(export_path)) return False _cleanup(tmpdir) return True
[ "def", "fast_sync_snapshot", "(", "working_dir", ",", "export_path", ",", "private_key", ",", "block_number", ")", ":", "db_paths", "=", "None", "found", "=", "True", "tmpdir", "=", "None", "namedb_path", "=", "None", "def", "_cleanup", "(", "path", ")", ":"...
Export all the local state for fast-sync. If block_number is given, then the name database at that particular block number will be taken. The exported tarball will be signed with the given private key, and the signature will be appended to the end of the file. Return True if we succeed Return False if not
[ "Export", "all", "the", "local", "state", "for", "fast", "-", "sync", ".", "If", "block_number", "is", "given", "then", "the", "name", "database", "at", "that", "particular", "block", "number", "will", "be", "taken", "." ]
python
train
profitbricks/profitbricks-sdk-python
examples/pb_createDatacenter.py
https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/examples/pb_createDatacenter.py#L443-L663
def main(argv=None): '''Parse command line options and create a server/volume composite.''' if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_name = os.path.basename(sys.argv[0]) program_version = "v%s" % __version__ program_build_date = str(__updated__) program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date) program_shortdesc = __import__('__main__').__doc__.split("\n")[1] program_license = '''%s Created by J. Buchhammer on %s. Copyright 2016 ProfitBricks GmbH. All rights reserved. Licensed under the Apache License 2.0 http://www.apache.org/licenses/LICENSE-2.0 Distributed on an "AS IS" basis without warranties or conditions of any kind, either express or implied. USAGE ''' % (program_shortdesc, str(__date__)) # Setup argument parser parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('-u', '--user', dest='user', help='the login name') parser.add_argument('-p', '--password', dest='password', help='the login password') parser.add_argument('-L', '--Login', dest='loginfile', default=None, help='the login file to use') parser.add_argument('-i', '--infile', dest='infile', default=None, required=True, help='the input file name') parser.add_argument('-D', '--DCname', dest='dcname', default=None, help='new datacenter name') # TODO: add/overwrite image password for creation # parser.add_argument('-P', '--imagepassword', dest='imgpassword', # default=None, help='the image password') parser.add_argument('-v', '--verbose', dest="verbose", action="count", default=0, help="set verbosity level [default: %(default)s]") parser.add_argument('-V', '--version', action='version', version=program_version_message) # Process arguments args = parser.parse_args() global verbose verbose = args.verbose if verbose > 0: print("Verbose mode on") print("start {} with args {}".format(program_name, str(args))) (user, password) = getLogin(args.loginfile, args.user, args.password) if user is None or password is None: raise ValueError("user or password resolved to None") pbclient = ProfitBricksService(user, password) usefile = args.infile print("read dc from {}".format(usefile)) dcdef = read_dc_definition(usefile) if verbose > 0: print("using DC-DEF {}".format(json.dumps(dcdef))) # setup dc: # + create empty dc # + create volumes (unattached), map uuid to servers (custom dict) # + create servers # + create nics # + attach volumes if 'custom' in dcdef and 'id' in dcdef['custom']: dc_id = dcdef['custom']['id'] print("using existing DC w/ id {}".format(str(dc_id))) else: if args.dcname is not None: print("Overwrite DC name w/ '{}'".format(args.dcname)) dcdef['properties']['name'] = args.dcname dc = getDatacenterObject(dcdef) # print("create DC {}".format(str(dc))) response = pbclient.create_datacenter(dc) dc_id = response['id'] if 'custom' not in dcdef: dcdef['custom'] = dict() dcdef['custom']['id'] = dc_id result = wait_for_request(pbclient, response['requestId']) print("wait loop returned {}".format(result)) tmpfile = usefile+".tmp_postdc" write_dc_definition(dcdef, tmpfile) requests = [] print("create Volumes {}".format(str(dc))) # we do NOT consider dangling volumes, only server-attached ones for server in dcdef['entities']['servers']['items']: print("- server {}".format(server['properties']['name'])) if 'volumes' not in server['entities']: print(" server {} has no volumes".format(server['properties']['name'])) continue for volume in server['entities']['volumes']['items']: if 'custom' in volume and 'id' in volume['custom']: vol_id = volume['custom']['id'] print("using existing volume w/ id {}".format(str(vol_id))) else: dcvol = getVolumeObject(volume) print("OBJ: {}".format(str(dcvol))) response = pbclient.create_volume(dc_id, dcvol) volume.update({'custom': {'id': response['id']}}) requests.append(response['requestId']) # end for(volume) # end for(server) if requests: result = wait_for_requests(pbclient, requests, initial_wait=10, scaleup=15) print("wait loop returned {}".format(str(result))) tmpfile = usefile+".tmp_postvol" write_dc_definition(dcdef, tmpfile) else: print("all volumes existed already") requests = [] print("create Servers {}".format(str(dc))) # we do NOT consider dangling volumes, only server-attached ones for server in dcdef['entities']['servers']['items']: print("- server {}".format(server['properties']['name'])) if 'custom' in server and 'id' in server['custom']: srv_id = server['custom']['id'] print("using existing server w/ id {}".format(str(srv_id))) else: dcsrv = getServerObject(server) print("OBJ: {}".format(str(dcsrv))) response = pbclient.create_server(dc_id, dcsrv) server.update({'custom': {'id': response['id']}}) requests.append(response['requestId']) # end for(server) if requests: result = wait_for_requests(pbclient, requests, initial_wait=10, scaleup=15) print("wait loop returned {}".format(str(result))) tmpfile = usefile+".tmp_postsrv" write_dc_definition(dcdef, tmpfile) else: print("all servers existed already") # TODO: only do this if we have lan entities requests = [] # Huuh, looks like we get unpredictable order for LANs! # Nope, order of creation determines the LAN id, # thus we better wait for each request print("create LANs {}".format(str(dc))) for lan in dcdef['entities']['lans']['items']: print("- lan {}".format(lan['properties']['name'])) dclan = getLANObject(lan) print("OBJ: {}".format(str(dclan))) response = pbclient.create_lan(dc_id, dclan) lan.update({'custom': {'id': response['id']}}) result = wait_for_request(pbclient, response['requestId']) print("wait loop returned {}".format(str(result))) # end for(lan) tmpfile = usefile+".tmp_postlan" write_dc_definition(dcdef, tmpfile) requests = [] # Attention: # NICs appear in OS in the order, they are created. # But DCD rearranges the display by ascending MAC addresses. # This does not change the OS order. # MAC may not be available from create response, # thus we wait for each request :-( print("create NICs {}".format(str(dc))) for server in dcdef['entities']['servers']['items']: print("- server {}".format(server['properties']['name'])) srv_id = server['custom']['id'] if 'nics' not in server['entities']: print(" server {} has no NICs".format(server['properties']['name'])) continue macmap = dict() for nic in server['entities']['nics']['items']: dcnic = getNICObject(nic) response = pbclient.create_nic(dc_id, srv_id, dcnic) # print("dcnic response {}".format(str(response))) # mac = response['properties']['mac'] # we don't get it here !? nic_id = response['id'] result = wait_for_request(pbclient, response['requestId']) print("wait loop returned {}".format(str(result))) response = pbclient.get_nic(dc_id, srv_id, nic_id, 2) mac = response['properties']['mac'] print("dcnic has MAC {} for {}".format(mac, nic_id)) macmap[mac] = nic_id # end for(nic) macs = sorted(macmap) print("macs will be displayed by DCD in th following order:") for mac in macs: print("mac {} -> id{}".format(mac, macmap[mac])) # end for(server) tmpfile = usefile+".tmp_postnic" write_dc_definition(dcdef, tmpfile) requests = [] # don't know if we get a race here too, so better wait for each request :-/ print("attach volumes {}".format(str(dc))) for server in dcdef['entities']['servers']['items']: print("- server {}".format(server['properties']['name'])) if 'volumes' not in server['entities']: print(" server {} has no volumes".format(server['properties']['name'])) continue srv_id = server['custom']['id'] for volume in server['entities']['volumes']['items']: print("OBJ: {}".format(volume['properties']['name'])) response = pbclient.attach_volume(dc_id, srv_id, volume['custom']['id']) result = wait_for_request(pbclient, response['requestId']) print("wait loop returned {}".format(str(result))) # end for(volume) # end for(server) tmpfile = usefile+".tmp_postatt" write_dc_definition(dcdef, tmpfile) # TODO: do we need to set boot volume for each server? # looks like it's working without return 0
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "else", ":", "sys", ".", "argv", ".", "extend", "(", "argv", ")", "program_name", "=", "os", ".", "path", ".", "basename", "(", ...
Parse command line options and create a server/volume composite.
[ "Parse", "command", "line", "options", "and", "create", "a", "server", "/", "volume", "composite", "." ]
python
valid
emichael/PyREM
pyrem/task.py
https://github.com/emichael/PyREM/blob/2609249ead197cd9496d164f4998ca9985503579/pyrem/task.py#L133-L149
def stop(self): """Stop a task immediately. Raises: RuntimeError: If the task hasn't been started or has already been stopped. """ if self._status is TaskStatus.STOPPED: return if self._status is not TaskStatus.STARTED: raise RuntimeError("Cannot stop %s in state %s" % (self, self._status)) self._stop() STARTED_TASKS.remove(self) self._status = TaskStatus.STOPPED
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_status", "is", "TaskStatus", ".", "STOPPED", ":", "return", "if", "self", ".", "_status", "is", "not", "TaskStatus", ".", "STARTED", ":", "raise", "RuntimeError", "(", "\"Cannot stop %s in state %s\"...
Stop a task immediately. Raises: RuntimeError: If the task hasn't been started or has already been stopped.
[ "Stop", "a", "task", "immediately", "." ]
python
train
F5Networks/f5-common-python
f5/bigip/tm/ltm/policy.py
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/ltm/policy.py#L64-L79
def _filter_version_specific_options(self, tmos_ver, **kwargs): '''Filter version-specific optional parameters Some optional parameters only exist in v12.1.0 and greater, filter these out for earlier versions to allow backward comatibility. ''' if LooseVersion(tmos_ver) < LooseVersion('12.1.0'): for k, parms in self._meta_data['optional_parameters'].items(): for r in kwargs.get(k, []): for parm in parms: value = r.pop(parm, None) if value is not None: logger.info( "Policy parameter %s:%s is invalid for v%s", k, parm, tmos_ver)
[ "def", "_filter_version_specific_options", "(", "self", ",", "tmos_ver", ",", "*", "*", "kwargs", ")", ":", "if", "LooseVersion", "(", "tmos_ver", ")", "<", "LooseVersion", "(", "'12.1.0'", ")", ":", "for", "k", ",", "parms", "in", "self", ".", "_meta_data...
Filter version-specific optional parameters Some optional parameters only exist in v12.1.0 and greater, filter these out for earlier versions to allow backward comatibility.
[ "Filter", "version", "-", "specific", "optional", "parameters" ]
python
train
cihai/cihai
cihai/conversion.py
https://github.com/cihai/cihai/blob/43b0c2931da18c1ef1ff1cdd71e4b1c5eca24a41/cihai/conversion.py#L114-L124
def euc_to_utf8(euchex): """ Convert EUC hex (e.g. "d2bb") to UTF8 hex (e.g. "e4 b8 80"). """ utf8 = euc_to_python(euchex).encode("utf-8") uf8 = utf8.decode('unicode_escape') uf8 = uf8.encode('latin1') uf8 = uf8.decode('euc-jp') return uf8
[ "def", "euc_to_utf8", "(", "euchex", ")", ":", "utf8", "=", "euc_to_python", "(", "euchex", ")", ".", "encode", "(", "\"utf-8\"", ")", "uf8", "=", "utf8", ".", "decode", "(", "'unicode_escape'", ")", "uf8", "=", "uf8", ".", "encode", "(", "'latin1'", "...
Convert EUC hex (e.g. "d2bb") to UTF8 hex (e.g. "e4 b8 80").
[ "Convert", "EUC", "hex", "(", "e", ".", "g", ".", "d2bb", ")", "to", "UTF8", "hex", "(", "e", ".", "g", ".", "e4", "b8", "80", ")", "." ]
python
train
log2timeline/plaso
plaso/parsers/winevt.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/winevt.py#L181-L217
def _ParseRecords(self, parser_mediator, evt_file): """Parses Windows EventLog (EVT) records. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. evt_file (pyevt.file): Windows EventLog (EVT) file. """ # To handle errors when parsing a Windows EventLog (EVT) file in the most # granular way the following code iterates over every event record. The # call to evt_file.get_record() and access to members of evt_record should # be called within a try-except. for record_index in range(evt_file.number_of_records): if parser_mediator.abort: break try: evt_record = evt_file.get_record(record_index) self._ParseRecord(parser_mediator, record_index, evt_record) except IOError as exception: parser_mediator.ProduceExtractionWarning( 'unable to parse event record: {0:d} with error: {1!s}'.format( record_index, exception)) for record_index in range(evt_file.number_of_recovered_records): if parser_mediator.abort: break try: evt_record = evt_file.get_recovered_record(record_index) self._ParseRecord( parser_mediator, record_index, evt_record, recovered=True) except IOError as exception: parser_mediator.ProduceExtractionWarning(( 'unable to parse recovered event record: {0:d} with error: ' '{1!s}').format(record_index, exception))
[ "def", "_ParseRecords", "(", "self", ",", "parser_mediator", ",", "evt_file", ")", ":", "# To handle errors when parsing a Windows EventLog (EVT) file in the most", "# granular way the following code iterates over every event record. The", "# call to evt_file.get_record() and access to membe...
Parses Windows EventLog (EVT) records. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. evt_file (pyevt.file): Windows EventLog (EVT) file.
[ "Parses", "Windows", "EventLog", "(", "EVT", ")", "records", "." ]
python
train
federico123579/Trading212-API
tradingAPI/low_level.py
https://github.com/federico123579/Trading212-API/blob/0fab20b71a2348e72bbe76071b81f3692128851f/tradingAPI/low_level.py#L131-L166
def login(self, username, password, mode="demo"): """login function""" url = "https://trading212.com/it/login" try: logger.debug(f"visiting %s" % url) self.browser.visit(url) logger.debug(f"connected to %s" % url) except selenium.common.exceptions.WebDriverException: logger.critical("connection timed out") raise try: self.search_name("login[username]").fill(username) self.search_name("login[password]").fill(password) self.css1(path['log']).click() # define a timeout for logging in timeout = time.time() + 30 while not self.elCss(path['logo']): if time.time() > timeout: logger.critical("login failed") raise CredentialsException(username) time.sleep(1) logger.info(f"logged in as {username}") # check if it's a weekend if mode == "demo" and datetime.now().isoweekday() in range(5, 8): timeout = time.time() + 10 while not self.elCss(path['alert-box']): if time.time() > timeout: logger.warning("weekend trading alert-box not closed") break if self.elCss(path['alert-box']): self.css1(path['alert-box']).click() logger.debug("weekend trading alert-box closed") except Exception as e: logger.critical("login failed") raise exceptions.BaseExc(e) return True
[ "def", "login", "(", "self", ",", "username", ",", "password", ",", "mode", "=", "\"demo\"", ")", ":", "url", "=", "\"https://trading212.com/it/login\"", "try", ":", "logger", ".", "debug", "(", "f\"visiting %s\"", "%", "url", ")", "self", ".", "browser", ...
login function
[ "login", "function" ]
python
train
hfaran/progressive
progressive/cursor.py
https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/cursor.py#L46-L49
def newline(self): """Effects a newline by moving the cursor down and clearing""" self.write(self.term.move_down) self.write(self.term.clear_bol)
[ "def", "newline", "(", "self", ")", ":", "self", ".", "write", "(", "self", ".", "term", ".", "move_down", ")", "self", ".", "write", "(", "self", ".", "term", ".", "clear_bol", ")" ]
Effects a newline by moving the cursor down and clearing
[ "Effects", "a", "newline", "by", "moving", "the", "cursor", "down", "and", "clearing" ]
python
train
closeio/quotequail
quotequail/_internal.py
https://github.com/closeio/quotequail/blob/8a3960c033d595b25a8bbc2c340be898e3065b5f/quotequail/_internal.py#L9-L27
def find_pattern_on_line(lines, n, max_wrap_lines): """ Finds a forward/reply pattern within the given lines on text on the given line number and returns a tuple with the type ('reply' or 'forward') and line number of where the pattern ends. The returned line number may be different from the given line number in case the pattern wraps over multiple lines. Returns (None, None) if no pattern was found. """ for typ, regexes in COMPILED_PATTERN_MAP.items(): for regex in regexes: for m in range(max_wrap_lines): match_line = join_wrapped_lines(lines[n:n+1+m]) if match_line.startswith('>'): match_line = match_line[1:].strip() if regex.match(match_line.strip()): return n+m, typ return None, None
[ "def", "find_pattern_on_line", "(", "lines", ",", "n", ",", "max_wrap_lines", ")", ":", "for", "typ", ",", "regexes", "in", "COMPILED_PATTERN_MAP", ".", "items", "(", ")", ":", "for", "regex", "in", "regexes", ":", "for", "m", "in", "range", "(", "max_wr...
Finds a forward/reply pattern within the given lines on text on the given line number and returns a tuple with the type ('reply' or 'forward') and line number of where the pattern ends. The returned line number may be different from the given line number in case the pattern wraps over multiple lines. Returns (None, None) if no pattern was found.
[ "Finds", "a", "forward", "/", "reply", "pattern", "within", "the", "given", "lines", "on", "text", "on", "the", "given", "line", "number", "and", "returns", "a", "tuple", "with", "the", "type", "(", "reply", "or", "forward", ")", "and", "line", "number",...
python
train
deepmind/sonnet
sonnet/python/modules/nets/alexnet.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/alexnet.py#L154-L179
def _calc_min_size(self, conv_layers): """Calculates the minimum size of the input layer. Given a set of convolutional layers, calculate the minimum value of the `input_height` and `input_width`, i.e. such that the output has size 1x1. Assumes snt.VALID padding. Args: conv_layers: List of tuples `(output_channels, (kernel_size, stride), (pooling_size, pooling_stride))` Returns: Minimum value of input height and width. """ input_size = 1 for _, conv_params, max_pooling in reversed(conv_layers): if max_pooling is not None: kernel_size, stride = max_pooling input_size = input_size * stride + (kernel_size - stride) if conv_params is not None: kernel_size, stride = conv_params input_size = input_size * stride + (kernel_size - stride) return input_size
[ "def", "_calc_min_size", "(", "self", ",", "conv_layers", ")", ":", "input_size", "=", "1", "for", "_", ",", "conv_params", ",", "max_pooling", "in", "reversed", "(", "conv_layers", ")", ":", "if", "max_pooling", "is", "not", "None", ":", "kernel_size", ",...
Calculates the minimum size of the input layer. Given a set of convolutional layers, calculate the minimum value of the `input_height` and `input_width`, i.e. such that the output has size 1x1. Assumes snt.VALID padding. Args: conv_layers: List of tuples `(output_channels, (kernel_size, stride), (pooling_size, pooling_stride))` Returns: Minimum value of input height and width.
[ "Calculates", "the", "minimum", "size", "of", "the", "input", "layer", "." ]
python
train
ladybug-tools/ladybug
ladybug/skymodel.py
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/skymodel.py#L823-L1157
def _get_dirint_coeffs(): """ Here be a large multi-dimensional matrix of dirint coefficients. Returns: Array with shape ``(6, 6, 7, 5)``. Ordering is ``[kt_prime_bin, zenith_bin, delta_kt_prime_bin, w_bin]`` """ coeffs = [[0 for i in range(6)] for j in range(6)] coeffs[0][0] = [ [0.385230, 0.385230, 0.385230, 0.462880, 0.317440], [0.338390, 0.338390, 0.221270, 0.316730, 0.503650], [0.235680, 0.235680, 0.241280, 0.157830, 0.269440], [0.830130, 0.830130, 0.171970, 0.841070, 0.457370], [0.548010, 0.548010, 0.478000, 0.966880, 1.036370], [0.548010, 0.548010, 1.000000, 3.012370, 1.976540], [0.582690, 0.582690, 0.229720, 0.892710, 0.569950]] coeffs[0][1] = [ [0.131280, 0.131280, 0.385460, 0.511070, 0.127940], [0.223710, 0.223710, 0.193560, 0.304560, 0.193940], [0.229970, 0.229970, 0.275020, 0.312730, 0.244610], [0.090100, 0.184580, 0.260500, 0.687480, 0.579440], [0.131530, 0.131530, 0.370190, 1.380350, 1.052270], [1.116250, 1.116250, 0.928030, 3.525490, 2.316920], [0.090100, 0.237000, 0.300040, 0.812470, 0.664970]] coeffs[0][2] = [ [0.587510, 0.130000, 0.400000, 0.537210, 0.832490], [0.306210, 0.129830, 0.204460, 0.500000, 0.681640], [0.224020, 0.260620, 0.334080, 0.501040, 0.350470], [0.421540, 0.753970, 0.750660, 3.706840, 0.983790], [0.706680, 0.373530, 1.245670, 0.864860, 1.992630], [4.864400, 0.117390, 0.265180, 0.359180, 3.310820], [0.392080, 0.493290, 0.651560, 1.932780, 0.898730]] coeffs[0][3] = [ [0.126970, 0.126970, 0.126970, 0.126970, 0.126970], [0.810820, 0.810820, 0.810820, 0.810820, 0.810820], [3.241680, 2.500000, 2.291440, 2.291440, 2.291440], [4.000000, 3.000000, 2.000000, 0.975430, 1.965570], [12.494170, 12.494170, 8.000000, 5.083520, 8.792390], [21.744240, 21.744240, 21.744240, 21.744240, 21.744240], [3.241680, 12.494170, 1.620760, 1.375250, 2.331620]] coeffs[0][4] = [ [0.126970, 0.126970, 0.126970, 0.126970, 0.126970], [0.810820, 0.810820, 0.810820, 0.810820, 0.810820], [3.241680, 2.500000, 2.291440, 2.291440, 2.291440], [4.000000, 3.000000, 2.000000, 0.975430, 1.965570], [12.494170, 12.494170, 8.000000, 5.083520, 8.792390], [21.744240, 21.744240, 21.744240, 21.744240, 21.744240], [3.241680, 12.494170, 1.620760, 1.375250, 2.331620]] coeffs[0][5] = [ [0.126970, 0.126970, 0.126970, 0.126970, 0.126970], [0.810820, 0.810820, 0.810820, 0.810820, 0.810820], [3.241680, 2.500000, 2.291440, 2.291440, 2.291440], [4.000000, 3.000000, 2.000000, 0.975430, 1.965570], [12.494170, 12.494170, 8.000000, 5.083520, 8.792390], [21.744240, 21.744240, 21.744240, 21.744240, 21.744240], [3.241680, 12.494170, 1.620760, 1.375250, 2.331620]] coeffs[1][0] = [ [0.337440, 0.337440, 0.969110, 1.097190, 1.116080], [0.337440, 0.337440, 0.969110, 1.116030, 0.623900], [0.337440, 0.337440, 1.530590, 1.024420, 0.908480], [0.584040, 0.584040, 0.847250, 0.914940, 1.289300], [0.337440, 0.337440, 0.310240, 1.435020, 1.852830], [0.337440, 0.337440, 1.015010, 1.097190, 2.117230], [0.337440, 0.337440, 0.969110, 1.145730, 1.476400]] coeffs[1][1] = [ [0.300000, 0.300000, 0.700000, 1.100000, 0.796940], [0.219870, 0.219870, 0.526530, 0.809610, 0.649300], [0.386650, 0.386650, 0.119320, 0.576120, 0.685460], [0.746730, 0.399830, 0.470970, 0.986530, 0.785370], [0.575420, 0.936700, 1.649200, 1.495840, 1.335590], [1.319670, 4.002570, 1.276390, 2.644550, 2.518670], [0.665190, 0.678910, 1.012360, 1.199940, 0.986580]] coeffs[1][2] = [ [0.378870, 0.974060, 0.500000, 0.491880, 0.665290], [0.105210, 0.263470, 0.407040, 0.553460, 0.582590], [0.312900, 0.345240, 1.144180, 0.854790, 0.612280], [0.119070, 0.365120, 0.560520, 0.793720, 0.802600], [0.781610, 0.837390, 1.270420, 1.537980, 1.292950], [1.152290, 1.152290, 1.492080, 1.245370, 2.177100], [0.424660, 0.529550, 0.966910, 1.033460, 0.958730]] coeffs[1][3] = [ [0.310590, 0.714410, 0.252450, 0.500000, 0.607600], [0.975190, 0.363420, 0.500000, 0.400000, 0.502800], [0.175580, 0.196250, 0.476360, 1.072470, 0.490510], [0.719280, 0.698620, 0.657770, 1.190840, 0.681110], [0.426240, 1.464840, 0.678550, 1.157730, 0.978430], [2.501120, 1.789130, 1.387090, 2.394180, 2.394180], [0.491640, 0.677610, 0.685610, 1.082400, 0.735410]] coeffs[1][4] = [ [0.597000, 0.500000, 0.300000, 0.310050, 0.413510], [0.314790, 0.336310, 0.400000, 0.400000, 0.442460], [0.166510, 0.460440, 0.552570, 1.000000, 0.461610], [0.401020, 0.559110, 0.403630, 1.016710, 0.671490], [0.400360, 0.750830, 0.842640, 1.802600, 1.023830], [3.315300, 1.510380, 2.443650, 1.638820, 2.133990], [0.530790, 0.745850, 0.693050, 1.458040, 0.804500]] coeffs[1][5] = [ [0.597000, 0.500000, 0.300000, 0.310050, 0.800920], [0.314790, 0.336310, 0.400000, 0.400000, 0.237040], [0.166510, 0.460440, 0.552570, 1.000000, 0.581990], [0.401020, 0.559110, 0.403630, 1.016710, 0.898570], [0.400360, 0.750830, 0.842640, 1.802600, 3.400390], [3.315300, 1.510380, 2.443650, 1.638820, 2.508780], [0.204340, 1.157740, 2.003080, 2.622080, 1.409380]] coeffs[2][0] = [ [1.242210, 1.242210, 1.242210, 1.242210, 1.242210], [0.056980, 0.056980, 0.656990, 0.656990, 0.925160], [0.089090, 0.089090, 1.040430, 1.232480, 1.205300], [1.053850, 1.053850, 1.399690, 1.084640, 1.233340], [1.151540, 1.151540, 1.118290, 1.531640, 1.411840], [1.494980, 1.494980, 1.700000, 1.800810, 1.671600], [1.018450, 1.018450, 1.153600, 1.321890, 1.294670]] coeffs[2][1] = [ [0.700000, 0.700000, 1.023460, 0.700000, 0.945830], [0.886300, 0.886300, 1.333620, 0.800000, 1.066620], [0.902180, 0.902180, 0.954330, 1.126690, 1.097310], [1.095300, 1.075060, 1.176490, 1.139470, 1.096110], [1.201660, 1.201660, 1.438200, 1.256280, 1.198060], [1.525850, 1.525850, 1.869160, 1.985410, 1.911590], [1.288220, 1.082810, 1.286370, 1.166170, 1.119330]] coeffs[2][2] = [ [0.600000, 1.029910, 0.859890, 0.550000, 0.813600], [0.604450, 1.029910, 0.859890, 0.656700, 0.928840], [0.455850, 0.750580, 0.804930, 0.823000, 0.911000], [0.526580, 0.932310, 0.908620, 0.983520, 0.988090], [1.036110, 1.100690, 0.848380, 1.035270, 1.042380], [1.048440, 1.652720, 0.900000, 2.350410, 1.082950], [0.817410, 0.976160, 0.861300, 0.974780, 1.004580]] coeffs[2][3] = [ [0.782110, 0.564280, 0.600000, 0.600000, 0.665740], [0.894480, 0.680730, 0.541990, 0.800000, 0.669140], [0.487460, 0.818950, 0.841830, 0.872540, 0.709040], [0.709310, 0.872780, 0.908480, 0.953290, 0.844350], [0.863920, 0.947770, 0.876220, 1.078750, 0.936910], [1.280350, 0.866720, 0.769790, 1.078750, 0.975130], [0.725420, 0.869970, 0.868810, 0.951190, 0.829220]] coeffs[2][4] = [ [0.791750, 0.654040, 0.483170, 0.409000, 0.597180], [0.566140, 0.948990, 0.971820, 0.653570, 0.718550], [0.648710, 0.637730, 0.870510, 0.860600, 0.694300], [0.637630, 0.767610, 0.925670, 0.990310, 0.847670], [0.736380, 0.946060, 1.117590, 1.029340, 0.947020], [1.180970, 0.850000, 1.050000, 0.950000, 0.888580], [0.700560, 0.801440, 0.961970, 0.906140, 0.823880]] coeffs[2][5] = [ [0.500000, 0.500000, 0.586770, 0.470550, 0.629790], [0.500000, 0.500000, 1.056220, 1.260140, 0.658140], [0.500000, 0.500000, 0.631830, 0.842620, 0.582780], [0.554710, 0.734730, 0.985820, 0.915640, 0.898260], [0.712510, 1.205990, 0.909510, 1.078260, 0.885610], [1.899260, 1.559710, 1.000000, 1.150000, 1.120390], [0.653880, 0.793120, 0.903320, 0.944070, 0.796130]] coeffs[3][0] = [ [1.000000, 1.000000, 1.050000, 1.170380, 1.178090], [0.960580, 0.960580, 1.059530, 1.179030, 1.131690], [0.871470, 0.871470, 0.995860, 1.141910, 1.114600], [1.201590, 1.201590, 0.993610, 1.109380, 1.126320], [1.065010, 1.065010, 0.828660, 0.939970, 1.017930], [1.065010, 1.065010, 0.623690, 1.119620, 1.132260], [1.071570, 1.071570, 0.958070, 1.114130, 1.127110]] coeffs[3][1] = [ [0.950000, 0.973390, 0.852520, 1.092200, 1.096590], [0.804120, 0.913870, 0.980990, 1.094580, 1.042420], [0.737540, 0.935970, 0.999940, 1.056490, 1.050060], [1.032980, 1.034540, 0.968460, 1.032080, 1.015780], [0.900000, 0.977210, 0.945960, 1.008840, 0.969960], [0.600000, 0.750000, 0.750000, 0.844710, 0.899100], [0.926800, 0.965030, 0.968520, 1.044910, 1.032310]] coeffs[3][2] = [ [0.850000, 1.029710, 0.961100, 1.055670, 1.009700], [0.818530, 0.960010, 0.996450, 1.081970, 1.036470], [0.765380, 0.953500, 0.948260, 1.052110, 1.000140], [0.775610, 0.909610, 0.927800, 0.987800, 0.952100], [1.000990, 0.881880, 0.875950, 0.949100, 0.893690], [0.902370, 0.875960, 0.807990, 0.942410, 0.917920], [0.856580, 0.928270, 0.946820, 1.032260, 0.972990]] coeffs[3][3] = [ [0.750000, 0.857930, 0.983800, 1.056540, 0.980240], [0.750000, 0.987010, 1.013730, 1.133780, 1.038250], [0.800000, 0.947380, 1.012380, 1.091270, 0.999840], [0.800000, 0.914550, 0.908570, 0.999190, 0.915230], [0.778540, 0.800590, 0.799070, 0.902180, 0.851560], [0.680190, 0.317410, 0.507680, 0.388910, 0.646710], [0.794920, 0.912780, 0.960830, 1.057110, 0.947950]] coeffs[3][4] = [ [0.750000, 0.833890, 0.867530, 1.059890, 0.932840], [0.979700, 0.971470, 0.995510, 1.068490, 1.030150], [0.858850, 0.987920, 1.043220, 1.108700, 1.044900], [0.802400, 0.955110, 0.911660, 1.045070, 0.944470], [0.884890, 0.766210, 0.885390, 0.859070, 0.818190], [0.615680, 0.700000, 0.850000, 0.624620, 0.669300], [0.835570, 0.946150, 0.977090, 1.049350, 0.979970]] coeffs[3][5] = [ [0.689220, 0.809600, 0.900000, 0.789500, 0.853990], [0.854660, 0.852840, 0.938200, 0.923110, 0.955010], [0.938600, 0.932980, 1.010390, 1.043950, 1.041640], [0.843620, 0.981300, 0.951590, 0.946100, 0.966330], [0.694740, 0.814690, 0.572650, 0.400000, 0.726830], [0.211370, 0.671780, 0.416340, 0.297290, 0.498050], [0.843540, 0.882330, 0.911760, 0.898420, 0.960210]] coeffs[4][0] = [ [1.054880, 1.075210, 1.068460, 1.153370, 1.069220], [1.000000, 1.062220, 1.013470, 1.088170, 1.046200], [0.885090, 0.993530, 0.942590, 1.054990, 1.012740], [0.920000, 0.950000, 0.978720, 1.020280, 0.984440], [0.850000, 0.908500, 0.839940, 0.985570, 0.962180], [0.800000, 0.800000, 0.810080, 0.950000, 0.961550], [1.038590, 1.063200, 1.034440, 1.112780, 1.037800]] coeffs[4][1] = [ [1.017610, 1.028360, 1.058960, 1.133180, 1.045620], [0.920000, 0.998970, 1.033590, 1.089030, 1.022060], [0.912370, 0.949930, 0.979770, 1.020420, 0.981770], [0.847160, 0.935300, 0.930540, 0.955050, 0.946560], [0.880260, 0.867110, 0.874130, 0.972650, 0.883420], [0.627150, 0.627150, 0.700000, 0.774070, 0.845130], [0.973700, 1.006240, 1.026190, 1.071960, 1.017240]] coeffs[4][2] = [ [1.028710, 1.017570, 1.025900, 1.081790, 1.024240], [0.924980, 0.985500, 1.014100, 1.092210, 0.999610], [0.828570, 0.934920, 0.994950, 1.024590, 0.949710], [0.900810, 0.901330, 0.928830, 0.979570, 0.913100], [0.761030, 0.845150, 0.805360, 0.936790, 0.853460], [0.626400, 0.546750, 0.730500, 0.850000, 0.689050], [0.957630, 0.985480, 0.991790, 1.050220, 0.987900]] coeffs[4][3] = [ [0.992730, 0.993880, 1.017150, 1.059120, 1.017450], [0.975610, 0.987160, 1.026820, 1.075440, 1.007250], [0.871090, 0.933190, 0.974690, 0.979840, 0.952730], [0.828750, 0.868090, 0.834920, 0.905510, 0.871530], [0.781540, 0.782470, 0.767910, 0.764140, 0.795890], [0.743460, 0.693390, 0.514870, 0.630150, 0.715660], [0.934760, 0.957870, 0.959640, 0.972510, 0.981640]] coeffs[4][4] = [ [0.965840, 0.941240, 0.987100, 1.022540, 1.011160], [0.988630, 0.994770, 0.976590, 0.950000, 1.034840], [0.958200, 1.018080, 0.974480, 0.920000, 0.989870], [0.811720, 0.869090, 0.812020, 0.850000, 0.821050], [0.682030, 0.679480, 0.632450, 0.746580, 0.738550], [0.668290, 0.445860, 0.500000, 0.678920, 0.696510], [0.926940, 0.953350, 0.959050, 0.876210, 0.991490]] coeffs[4][5] = [ [0.948940, 0.997760, 0.850000, 0.826520, 0.998470], [1.017860, 0.970000, 0.850000, 0.700000, 0.988560], [1.000000, 0.950000, 0.850000, 0.606240, 0.947260], [1.000000, 0.746140, 0.751740, 0.598390, 0.725230], [0.922210, 0.500000, 0.376800, 0.517110, 0.548630], [0.500000, 0.450000, 0.429970, 0.404490, 0.539940], [0.960430, 0.881630, 0.775640, 0.596350, 0.937680]] coeffs[5][0] = [ [1.030000, 1.040000, 1.000000, 1.000000, 1.049510], [1.050000, 0.990000, 0.990000, 0.950000, 0.996530], [1.050000, 0.990000, 0.990000, 0.820000, 0.971940], [1.050000, 0.790000, 0.880000, 0.820000, 0.951840], [1.000000, 0.530000, 0.440000, 0.710000, 0.928730], [0.540000, 0.470000, 0.500000, 0.550000, 0.773950], [1.038270, 0.920180, 0.910930, 0.821140, 1.034560]] coeffs[5][1] = [ [1.041020, 0.997520, 0.961600, 1.000000, 1.035780], [0.948030, 0.980000, 0.900000, 0.950360, 0.977460], [0.950000, 0.977250, 0.869270, 0.800000, 0.951680], [0.951870, 0.850000, 0.748770, 0.700000, 0.883850], [0.900000, 0.823190, 0.727450, 0.600000, 0.839870], [0.850000, 0.805020, 0.692310, 0.500000, 0.788410], [1.010090, 0.895270, 0.773030, 0.816280, 1.011680]] coeffs[5][2] = [ [1.022450, 1.004600, 0.983650, 1.000000, 1.032940], [0.943960, 0.999240, 0.983920, 0.905990, 0.978150], [0.936240, 0.946480, 0.850000, 0.850000, 0.930320], [0.816420, 0.885000, 0.644950, 0.817650, 0.865310], [0.742960, 0.765690, 0.561520, 0.700000, 0.827140], [0.643870, 0.596710, 0.474460, 0.600000, 0.651200], [0.971740, 0.940560, 0.714880, 0.864380, 1.001650]] coeffs[5][3] = [ [0.995260, 0.977010, 1.000000, 1.000000, 1.035250], [0.939810, 0.975250, 0.939980, 0.950000, 0.982550], [0.876870, 0.879440, 0.850000, 0.900000, 0.917810], [0.873480, 0.873450, 0.751470, 0.850000, 0.863040], [0.761470, 0.702360, 0.638770, 0.750000, 0.783120], [0.734080, 0.650000, 0.600000, 0.650000, 0.715660], [0.942160, 0.919100, 0.770340, 0.731170, 0.995180]] coeffs[5][4] = [ [0.952560, 0.916780, 0.920000, 0.900000, 1.005880], [0.928620, 0.994420, 0.900000, 0.900000, 0.983720], [0.913070, 0.850000, 0.850000, 0.800000, 0.924280], [0.868090, 0.807170, 0.823550, 0.600000, 0.844520], [0.769570, 0.719870, 0.650000, 0.550000, 0.733500], [0.580250, 0.650000, 0.600000, 0.500000, 0.628850], [0.904770, 0.852650, 0.708370, 0.493730, 0.949030]] coeffs[5][5] = [ [0.911970, 0.800000, 0.800000, 0.800000, 0.956320], [0.912620, 0.682610, 0.750000, 0.700000, 0.950110], [0.653450, 0.659330, 0.700000, 0.600000, 0.856110], [0.648440, 0.600000, 0.641120, 0.500000, 0.695780], [0.570000, 0.550000, 0.598800, 0.400000, 0.560150], [0.475230, 0.500000, 0.518640, 0.339970, 0.520230], [0.743440, 0.592190, 0.603060, 0.316930, 0.794390]] return coeffs
[ "def", "_get_dirint_coeffs", "(", ")", ":", "coeffs", "=", "[", "[", "0", "for", "i", "in", "range", "(", "6", ")", "]", "for", "j", "in", "range", "(", "6", ")", "]", "coeffs", "[", "0", "]", "[", "0", "]", "=", "[", "[", "0.385230", ",", ...
Here be a large multi-dimensional matrix of dirint coefficients. Returns: Array with shape ``(6, 6, 7, 5)``. Ordering is ``[kt_prime_bin, zenith_bin, delta_kt_prime_bin, w_bin]``
[ "Here", "be", "a", "large", "multi", "-", "dimensional", "matrix", "of", "dirint", "coefficients", "." ]
python
train
elbow-jason/Uno-deprecated
uno/decorators.py
https://github.com/elbow-jason/Uno-deprecated/blob/4ad07d7b84e5b6e3e2b2c89db69448906f24b4e4/uno/decorators.py#L11-L27
def change_return_type(f): """ Converts the returned value of wrapped function to the type of the first arg or to the type specified by a kwarg key return_type's value. """ @wraps(f) def wrapper(*args, **kwargs): if kwargs.has_key('return_type'): return_type = kwargs['return_type'] kwargs.pop('return_type') return return_type(f(*args, **kwargs)) elif len(args) > 0: return_type = type(args[0]) return return_type(f(*args, **kwargs)) else: return f(*args, **kwargs) return wrapper
[ "def", "change_return_type", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "has_key", "(", "'return_type'", ")", ":", "return_type", "=", "kwargs", "[", ...
Converts the returned value of wrapped function to the type of the first arg or to the type specified by a kwarg key return_type's value.
[ "Converts", "the", "returned", "value", "of", "wrapped", "function", "to", "the", "type", "of", "the", "first", "arg", "or", "to", "the", "type", "specified", "by", "a", "kwarg", "key", "return_type", "s", "value", "." ]
python
train
CamDavidsonPilon/lifelines
lifelines/fitters/cox_time_varying_fitter.py
https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/fitters/cox_time_varying_fitter.py#L612-L668
def print_summary(self, decimals=2, **kwargs): """ Print summary statistics describing the fit, the coefficients, and the error bounds. Parameters ----------- decimals: int, optional (default=2) specify the number of decimal places to show kwargs: print additional meta data in the output (useful to provide model names, dataset names, etc.) when comparing multiple outputs. """ # Print information about data first justify = string_justify(18) print(self) print("{} = '{}'".format(justify("event col"), self.event_col)) if self.weights_col: print("{} = '{}'".format(justify("weights col"), self.weights_col)) if self.strata: print("{} = {}".format(justify("strata"), self.strata)) if self.penalizer > 0: print("{} = {}".format(justify("penalizer"), self.penalizer)) print("{} = {}".format(justify("number of subjects"), self._n_unique)) print("{} = {}".format(justify("number of periods"), self._n_examples)) print("{} = {}".format(justify("number of events"), self.event_observed.sum())) print("{} = {:.{prec}f}".format(justify("log-likelihood"), self._log_likelihood, prec=decimals)) print("{} = {} UTC".format(justify("time fit was run"), self._time_fit_was_called)) for k, v in kwargs.items(): print("{} = {}\n".format(justify(k), v)) print(end="\n") print("---") df = self.summary # Significance codes last print( df.to_string( float_format=format_floats(decimals), formatters={"p": format_p_value(decimals), "exp(coef)": format_exp_floats(decimals)}, ) ) # Significance code explanation print("---") print( "Log-likelihood ratio test = {:.{prec}f} on {} df, -log2(p)={:.{prec}f}".format( *self._compute_likelihood_ratio_test(), prec=decimals ) )
[ "def", "print_summary", "(", "self", ",", "decimals", "=", "2", ",", "*", "*", "kwargs", ")", ":", "# Print information about data first", "justify", "=", "string_justify", "(", "18", ")", "print", "(", "self", ")", "print", "(", "\"{} = '{}'\"", ".", "forma...
Print summary statistics describing the fit, the coefficients, and the error bounds. Parameters ----------- decimals: int, optional (default=2) specify the number of decimal places to show kwargs: print additional meta data in the output (useful to provide model names, dataset names, etc.) when comparing multiple outputs.
[ "Print", "summary", "statistics", "describing", "the", "fit", "the", "coefficients", "and", "the", "error", "bounds", "." ]
python
train
Azure/azure-cosmos-table-python
azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py
https://github.com/Azure/azure-cosmos-table-python/blob/a7b618f6bddc465c9fdf899ea2971dfe4d04fcf0/azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py#L335-L369
def get_table_service_stats(self, timeout=None): ''' Retrieves statistics related to replication for the Table service. It is only available when read-access geo-redundant replication is enabled for the storage account. With geo-redundant replication, Azure Storage maintains your data durable in two locations. In both locations, Azure Storage constantly maintains multiple healthy replicas of your data. The location where you read, create, update, or delete data is the primary storage account location. The primary location exists in the region you choose at the time you create an account via the Azure Management Azure classic portal, for example, North Central US. The location to which your data is replicated is the secondary location. The secondary location is automatically determined based on the location of the primary; it is in a second data center that resides in the same region as the primary location. Read-only access is available from the secondary location, if read-access geo-redundant replication is enabled for your storage account. :param int timeout: The timeout parameter is expressed in seconds. :return: The table service stats. :rtype: :class:`~azure.storage.common.models.ServiceStats` ''' request = HTTPRequest() request.method = 'GET' request.host_locations = self._get_host_locations(primary=False, secondary=True) request.path = '/' request.query = { 'restype': 'service', 'comp': 'stats', 'timeout': _int_to_str(timeout), } return self._perform_request(request, _convert_xml_to_service_stats)
[ "def", "get_table_service_stats", "(", "self", ",", "timeout", "=", "None", ")", ":", "request", "=", "HTTPRequest", "(", ")", "request", ".", "method", "=", "'GET'", "request", ".", "host_locations", "=", "self", ".", "_get_host_locations", "(", "primary", ...
Retrieves statistics related to replication for the Table service. It is only available when read-access geo-redundant replication is enabled for the storage account. With geo-redundant replication, Azure Storage maintains your data durable in two locations. In both locations, Azure Storage constantly maintains multiple healthy replicas of your data. The location where you read, create, update, or delete data is the primary storage account location. The primary location exists in the region you choose at the time you create an account via the Azure Management Azure classic portal, for example, North Central US. The location to which your data is replicated is the secondary location. The secondary location is automatically determined based on the location of the primary; it is in a second data center that resides in the same region as the primary location. Read-only access is available from the secondary location, if read-access geo-redundant replication is enabled for your storage account. :param int timeout: The timeout parameter is expressed in seconds. :return: The table service stats. :rtype: :class:`~azure.storage.common.models.ServiceStats`
[ "Retrieves", "statistics", "related", "to", "replication", "for", "the", "Table", "service", ".", "It", "is", "only", "available", "when", "read", "-", "access", "geo", "-", "redundant", "replication", "is", "enabled", "for", "the", "storage", "account", "." ]
python
train
ptcryan/hydrawiser
hydrawiser/core.py
https://github.com/ptcryan/hydrawiser/blob/53acafb08b5cee0f6628414044b9b9f9a0b15e50/hydrawiser/core.py#L132-L161
def suspend_zone(self, days, zone=None): """ Suspend or unsuspend a zone or all zones for an amount of time. :param days: Number of days to suspend the zone(s) :type days: int :param zone: The zone to suspend. If no zone is specified then suspend all zones :type zone: int or None :returns: The response from set_zones() or None if there was an error. :rtype: None or string """ if zone is None: zone_cmd = 'suspendall' relay_id = None else: if zone < 0 or zone > (len(self.relays) - 1): return None else: zone_cmd = 'suspend' relay_id = self.relays[zone]['relay_id'] # If days is 0 then remove suspension if days <= 0: time_cmd = 0 else: # 1 day = 60 * 60 * 24 seconds = 86400 time_cmd = time.mktime(time.localtime()) + (days * 86400) return set_zones(self._user_token, zone_cmd, relay_id, time_cmd)
[ "def", "suspend_zone", "(", "self", ",", "days", ",", "zone", "=", "None", ")", ":", "if", "zone", "is", "None", ":", "zone_cmd", "=", "'suspendall'", "relay_id", "=", "None", "else", ":", "if", "zone", "<", "0", "or", "zone", ">", "(", "len", "(",...
Suspend or unsuspend a zone or all zones for an amount of time. :param days: Number of days to suspend the zone(s) :type days: int :param zone: The zone to suspend. If no zone is specified then suspend all zones :type zone: int or None :returns: The response from set_zones() or None if there was an error. :rtype: None or string
[ "Suspend", "or", "unsuspend", "a", "zone", "or", "all", "zones", "for", "an", "amount", "of", "time", "." ]
python
train
PaloAltoNetworks/pancloud
pancloud/logging.py
https://github.com/PaloAltoNetworks/pancloud/blob/c51e4c8aca3c988c60f062291007534edcb55285/pancloud/logging.py#L298-L330
def write(self, vendor_id=None, log_type=None, json=None, **kwargs): """Write log records to the Logging Service. This API requires a JSON array in its request body, each element of which represents a single log record. Log records are provided as JSON objects. Every log record must include the primary timestamp field that you identified when you registered your app. Every log record must also identify the log type. Args: vendor_id (str): Vendor ID. log_type (str): Log type. json (list): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_write.py`` example. """ path = "/logging-service/v1/logs/{}/{}".format( vendor_id, log_type ) r = self._httpclient.request( method="POST", url=self.url, json=json, path=path, **kwargs ) return r
[ "def", "write", "(", "self", ",", "vendor_id", "=", "None", ",", "log_type", "=", "None", ",", "json", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "\"/logging-service/v1/logs/{}/{}\"", ".", "format", "(", "vendor_id", ",", "log_type", ")...
Write log records to the Logging Service. This API requires a JSON array in its request body, each element of which represents a single log record. Log records are provided as JSON objects. Every log record must include the primary timestamp field that you identified when you registered your app. Every log record must also identify the log type. Args: vendor_id (str): Vendor ID. log_type (str): Log type. json (list): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response: Requests Response() object. Examples: Refer to ``logging_write.py`` example.
[ "Write", "log", "records", "to", "the", "Logging", "Service", "." ]
python
train
cjdrake/pyeda
pyeda/boolalg/expr.py
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/boolalg/expr.py#L136-L180
def exprvar(name, index=None): r"""Return a unique Expression variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``exprvar`` function returns a unique Boolean variable instance represented by a logic expression. Variable instances may be used to symbolically construct larger expressions. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``exprvar`` function will always return the same variable: >>> exprvar('a', 0) is exprvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(exprvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = exprvar(('push', 'fifo')) >>> fifo_pop = exprvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.exprvars` function. """ bvar = boolfunc.var(name, index) try: var = _LITS[bvar.uniqid] except KeyError: var = _LITS[bvar.uniqid] = Variable(bvar) return var
[ "def", "exprvar", "(", "name", ",", "index", "=", "None", ")", ":", "bvar", "=", "boolfunc", ".", "var", "(", "name", ",", "index", ")", "try", ":", "var", "=", "_LITS", "[", "bvar", ".", "uniqid", "]", "except", "KeyError", ":", "var", "=", "_LI...
r"""Return a unique Expression variable. A Boolean *variable* is an abstract numerical quantity that may assume any value in the set :math:`B = \{0, 1\}`. The ``exprvar`` function returns a unique Boolean variable instance represented by a logic expression. Variable instances may be used to symbolically construct larger expressions. A variable is defined by one or more *names*, and zero or more *indices*. Multiple names establish hierarchical namespaces, and multiple indices group several related variables. If the ``name`` parameter is a single ``str``, it will be converted to ``(name, )``. The ``index`` parameter is optional; when empty, it will be converted to an empty tuple ``()``. If the ``index`` parameter is a single ``int``, it will be converted to ``(index, )``. Given identical names and indices, the ``exprvar`` function will always return the same variable: >>> exprvar('a', 0) is exprvar('a', 0) True To create several single-letter variables: >>> a, b, c, d = map(exprvar, 'abcd') To create variables with multiple names (inner-most first): >>> fifo_push = exprvar(('push', 'fifo')) >>> fifo_pop = exprvar(('pop', 'fifo')) .. seealso:: For creating arrays of variables with incremental indices, use the :func:`pyeda.boolalg.bfarray.exprvars` function.
[ "r", "Return", "a", "unique", "Expression", "variable", "." ]
python
train
praekeltfoundation/molo.commenting
molo/commenting/admin.py
https://github.com/praekeltfoundation/molo.commenting/blob/94549bd75e4a5c5b3db43149e32d636330b3969c/molo/commenting/admin.py#L156-L170
def change_view(self, request, object_id, form_url='', extra_context=None): """ Override change view to add extra context enabling moderate tool. """ context = { 'has_moderate_tool': True } if extra_context: context.update(extra_context) return super(AdminModeratorMixin, self).change_view( request=request, object_id=object_id, form_url=form_url, extra_context=context )
[ "def", "change_view", "(", "self", ",", "request", ",", "object_id", ",", "form_url", "=", "''", ",", "extra_context", "=", "None", ")", ":", "context", "=", "{", "'has_moderate_tool'", ":", "True", "}", "if", "extra_context", ":", "context", ".", "update"...
Override change view to add extra context enabling moderate tool.
[ "Override", "change", "view", "to", "add", "extra", "context", "enabling", "moderate", "tool", "." ]
python
train
splunk/splunk-sdk-python
splunklib/client.py
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2690-L2699
def is_done(self): """Indicates whether this job finished running. :return: ``True`` if the job is done, ``False`` if not. :rtype: ``boolean`` """ if not self.is_ready(): return False done = (self._state.content['isDone'] == '1') return done
[ "def", "is_done", "(", "self", ")", ":", "if", "not", "self", ".", "is_ready", "(", ")", ":", "return", "False", "done", "=", "(", "self", ".", "_state", ".", "content", "[", "'isDone'", "]", "==", "'1'", ")", "return", "done" ]
Indicates whether this job finished running. :return: ``True`` if the job is done, ``False`` if not. :rtype: ``boolean``
[ "Indicates", "whether", "this", "job", "finished", "running", "." ]
python
train
ioam/lancet
lancet/launch.py
https://github.com/ioam/lancet/blob/1fbbf88fa0e8974ff9ed462e3cb11722ddebdd6e/lancet/launch.py#L1019-L1051
def _review_all(self, launchers): """ Runs the review process for all the launchers. """ # Run review of launch args if necessary if self.launch_args is not None: proceed = self.review_args(self.launch_args, show_repr=True, heading='Meta Arguments') if not proceed: return False reviewers = [self.review_args, self.review_command, self.review_launcher] for (count, launcher) in enumerate(launchers): # Run reviews for all launchers if desired... if not all(reviewer(launcher) for reviewer in reviewers): print("\n == Aborting launch ==") return False # But allow the user to skip these extra reviews if len(launchers)!= 1 and count < len(launchers)-1: skip_remaining = self.input_options(['Y', 'n','quit'], '\nSkip remaining reviews?', default='y') if skip_remaining == 'y': break elif skip_remaining == 'quit': return False if self.input_options(['y','N'], 'Execute?', default='n') != 'y': return False else: return self._launch_all(launchers)
[ "def", "_review_all", "(", "self", ",", "launchers", ")", ":", "# Run review of launch args if necessary", "if", "self", ".", "launch_args", "is", "not", "None", ":", "proceed", "=", "self", ".", "review_args", "(", "self", ".", "launch_args", ",", "show_repr", ...
Runs the review process for all the launchers.
[ "Runs", "the", "review", "process", "for", "all", "the", "launchers", "." ]
python
valid
junaruga/rpm-py-installer
install.py
https://github.com/junaruga/rpm-py-installer/blob/12f45feb0ba533dec8d0d16ef1e9b7fb8cfbd4ed/install.py#L1761-L1767
def sh_e_out(cls, cmd, **kwargs): """Run the command. and returns the stdout.""" cmd_kwargs = { 'stdout': subprocess.PIPE, } cmd_kwargs.update(kwargs) return cls.sh_e(cmd, **cmd_kwargs)[0]
[ "def", "sh_e_out", "(", "cls", ",", "cmd", ",", "*", "*", "kwargs", ")", ":", "cmd_kwargs", "=", "{", "'stdout'", ":", "subprocess", ".", "PIPE", ",", "}", "cmd_kwargs", ".", "update", "(", "kwargs", ")", "return", "cls", ".", "sh_e", "(", "cmd", "...
Run the command. and returns the stdout.
[ "Run", "the", "command", ".", "and", "returns", "the", "stdout", "." ]
python
train
gem/oq-engine
openquake/hazardlib/sourceconverter.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/sourceconverter.py#L80-L97
def collect(cls, sources): """ :param sources: dictionaries with a key 'tectonicRegion' :returns: an ordered list of SourceGroup instances """ source_stats_dict = {} for src in sources: trt = src['tectonicRegion'] if trt not in source_stats_dict: source_stats_dict[trt] = SourceGroup(trt) sg = source_stats_dict[trt] if not sg.sources: # we append just one source per SourceGroup, so that # the memory occupation is insignificant sg.sources.append(src) # return SourceGroups, ordered by TRT string return sorted(source_stats_dict.values())
[ "def", "collect", "(", "cls", ",", "sources", ")", ":", "source_stats_dict", "=", "{", "}", "for", "src", "in", "sources", ":", "trt", "=", "src", "[", "'tectonicRegion'", "]", "if", "trt", "not", "in", "source_stats_dict", ":", "source_stats_dict", "[", ...
:param sources: dictionaries with a key 'tectonicRegion' :returns: an ordered list of SourceGroup instances
[ ":", "param", "sources", ":", "dictionaries", "with", "a", "key", "tectonicRegion", ":", "returns", ":", "an", "ordered", "list", "of", "SourceGroup", "instances" ]
python
train
mbj4668/pyang
pyang/translators/schemanode.py
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/schemanode.py#L152-L155
def annot(self, node): """Add `node` as an annotation of the receiver.""" self.annots.append(node) node.parent = self
[ "def", "annot", "(", "self", ",", "node", ")", ":", "self", ".", "annots", ".", "append", "(", "node", ")", "node", ".", "parent", "=", "self" ]
Add `node` as an annotation of the receiver.
[ "Add", "node", "as", "an", "annotation", "of", "the", "receiver", "." ]
python
train
dade-ai/snipy
snipy/decotool.py
https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/decotool.py#L85-L114
def bindargs(fun, *argsbind, **kwbind): """ _ = bind.placeholder # unbound placeholder (arg) f = bind(fun, _, _, arg3, kw=kw1, kw2=kw2), f(arg1, arg2) :param fun: :param argsbind: :param kwbind: :return: """ assert argsbind argsb = list(argsbind) iargs = [i for i in range(len(argsbind)) if argsbind[i] is bind.placeholder] # iargs = [a is bind.placeholder for a in argsbind] @functools.wraps(fun) def wrapped(*args, **kwargs): kws = kwbind.copy() args_this = [a for a in argsb] for i, arg in zip(iargs, args): args_this[i] = arg args_this.extend(args[len(iargs):]) # kwargs.update(kwbind) kws.update(kwargs) # return fun(*argsb, **kws) return fun(*args_this, **kws) return wrapped
[ "def", "bindargs", "(", "fun", ",", "*", "argsbind", ",", "*", "*", "kwbind", ")", ":", "assert", "argsbind", "argsb", "=", "list", "(", "argsbind", ")", "iargs", "=", "[", "i", "for", "i", "in", "range", "(", "len", "(", "argsbind", ")", ")", "i...
_ = bind.placeholder # unbound placeholder (arg) f = bind(fun, _, _, arg3, kw=kw1, kw2=kw2), f(arg1, arg2) :param fun: :param argsbind: :param kwbind: :return:
[ "_", "=", "bind", ".", "placeholder", "#", "unbound", "placeholder", "(", "arg", ")", "f", "=", "bind", "(", "fun", "_", "_", "arg3", "kw", "=", "kw1", "kw2", "=", "kw2", ")", "f", "(", "arg1", "arg2", ")", ":", "param", "fun", ":", ":", "param...
python
valid
Kozea/cairocffi
cairocffi/context.py
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1456-L1471
def in_fill(self, x, y): """Tests whether the given point is inside the area that would be affected by a :meth:`fill` operation given the current path and filling parameters. Surface dimensions and clipping are not taken into account. See :meth:`fill`, :meth:`set_fill_rule` and :meth:`fill_preserve`. :param x: X coordinate of the point to test :param y: Y coordinate of the point to test :type x: float :type y: float :returns: A boolean. """ return bool(cairo.cairo_in_fill(self._pointer, x, y))
[ "def", "in_fill", "(", "self", ",", "x", ",", "y", ")", ":", "return", "bool", "(", "cairo", ".", "cairo_in_fill", "(", "self", ".", "_pointer", ",", "x", ",", "y", ")", ")" ]
Tests whether the given point is inside the area that would be affected by a :meth:`fill` operation given the current path and filling parameters. Surface dimensions and clipping are not taken into account. See :meth:`fill`, :meth:`set_fill_rule` and :meth:`fill_preserve`. :param x: X coordinate of the point to test :param y: Y coordinate of the point to test :type x: float :type y: float :returns: A boolean.
[ "Tests", "whether", "the", "given", "point", "is", "inside", "the", "area", "that", "would", "be", "affected", "by", "a", ":", "meth", ":", "fill", "operation", "given", "the", "current", "path", "and", "filling", "parameters", ".", "Surface", "dimensions", ...
python
train
SiLab-Bonn/basil
basil/HL/SussProber.py
https://github.com/SiLab-Bonn/basil/blob/99052482d9334dd1f5598eb2d2fb4d5399a32291/basil/HL/SussProber.py#L27-L32
def move_position(self, dx, dy, speed=None): ''' Move chuck relative to actual position in um''' if speed: self._intf.write('MoveChuckPosition %1.1f %1.1f R Y %d' % (dx, dy, speed)) else: self._intf.write('MoveChuckPosition %1.1f %1.1f R Y' % (dx, dy))
[ "def", "move_position", "(", "self", ",", "dx", ",", "dy", ",", "speed", "=", "None", ")", ":", "if", "speed", ":", "self", ".", "_intf", ".", "write", "(", "'MoveChuckPosition %1.1f %1.1f R Y %d'", "%", "(", "dx", ",", "dy", ",", "speed", ")", ")", ...
Move chuck relative to actual position in um
[ "Move", "chuck", "relative", "to", "actual", "position", "in", "um" ]
python
train
batiste/django-page-cms
pages/utils.py
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/utils.py#L139-L154
def slugify(value, allow_unicode=False): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. Copyright: https://docs.djangoproject.com/en/1.9/_modules/django/utils/text/#slugify TODO: replace after stopping support for Django 1.8 """ value = force_text(value) if allow_unicode: value = unicodedata.normalize('NFKC', value) value = re.sub('[^\w\s-]', '', value, flags=re.U).strip().lower() return mark_safe(re.sub('[-\s]+', '-', value, flags=re.U)) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii') value = re.sub('[^\w\s-]', '', value).strip().lower() return mark_safe(re.sub('[-\s]+', '-', value))
[ "def", "slugify", "(", "value", ",", "allow_unicode", "=", "False", ")", ":", "value", "=", "force_text", "(", "value", ")", "if", "allow_unicode", ":", "value", "=", "unicodedata", ".", "normalize", "(", "'NFKC'", ",", "value", ")", "value", "=", "re", ...
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. Copyright: https://docs.djangoproject.com/en/1.9/_modules/django/utils/text/#slugify TODO: replace after stopping support for Django 1.8
[ "Convert", "to", "ASCII", "if", "allow_unicode", "is", "False", ".", "Convert", "spaces", "to", "hyphens", ".", "Remove", "characters", "that", "aren", "t", "alphanumerics", "underscores", "or", "hyphens", ".", "Convert", "to", "lowercase", ".", "Also", "strip...
python
train
robertpeteuil/multi-cloud-control
mcc/core.py
https://github.com/robertpeteuil/multi-cloud-control/blob/f1565af1c0b6ed465ff312d3ccc592ba0609f4a2/mcc/core.py#L115-L132
def config_cred(config, providers): """Read credentials from configfile.""" expected = ['aws', 'azure', 'gcp', 'alicloud'] cred = {} to_remove = [] for item in providers: if any(item.startswith(itemb) for itemb in expected): try: cred[item] = dict(list(config[item].items())) except KeyError as e: print("No credentials section in config file for {} -" " provider will be skipped.".format(e)) to_remove.append(item) else: print("Unsupported provider: '{}' listed in config - ignoring" .format(item)) to_remove.append(item) return cred, to_remove
[ "def", "config_cred", "(", "config", ",", "providers", ")", ":", "expected", "=", "[", "'aws'", ",", "'azure'", ",", "'gcp'", ",", "'alicloud'", "]", "cred", "=", "{", "}", "to_remove", "=", "[", "]", "for", "item", "in", "providers", ":", "if", "any...
Read credentials from configfile.
[ "Read", "credentials", "from", "configfile", "." ]
python
train
twilio/twilio-python
twilio/rest/trunking/v1/trunk/terminating_sip_domain.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/trunking/v1/trunk/terminating_sip_domain.py#L309-L323
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: TerminatingSipDomainContext for this TerminatingSipDomainInstance :rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainContext """ if self._context is None: self._context = TerminatingSipDomainContext( self._version, trunk_sid=self._solution['trunk_sid'], sid=self._solution['sid'], ) return self._context
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "TerminatingSipDomainContext", "(", "self", ".", "_version", ",", "trunk_sid", "=", "self", ".", "_solution", "[", "'trunk_sid'", "]", ...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: TerminatingSipDomainContext for this TerminatingSipDomainInstance :rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainContext
[ "Generate", "an", "instance", "context", "for", "the", "instance", "the", "context", "is", "capable", "of", "performing", "various", "actions", ".", "All", "instance", "actions", "are", "proxied", "to", "the", "context" ]
python
train
danilobellini/audiolazy
audiolazy/lazy_analysis.py
https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_analysis.py#L865-L1143
def stft(func=None, **kwparams): """ Short Time Fourier Transform block processor / phase vocoder wrapper. This function can be used in many ways: * Directly as a signal processor builder, wrapping a spectrum block/grain processor function; * Directly as a decorator to a block processor; * Called without the ``func`` parameter for a partial evalution style changing the defaults. See the examples below for more information about these use cases. The resulting function performs a full block-by-block analysis/synthesis phase vocoder keeping this sequence of actions: 1. Blockenize the signal with the given ``size`` and ``hop``; 2. Lazily apply the given ``wnd`` window to each block; 3. Perform the 5 actions calling their functions in order: a. ``before``: Pre-processing; b. ``transform``: A transform like the FFT; c. ``func``: the positional parameter with the single block processor; d. ``inverse_transform``: inverse FFT; e. ``after``: Post-processing. 4. Overlap-add with the ``ola`` overlap-add strategy. The given ``ola`` would deal with its own window application and normalization. Any parameter from steps 3 and 4 can be set to ``None`` to skip it from the full process, without changing the other [sub]steps. The parameters defaults are based on the Numpy FFT subpackage. Parameters ---------- func : The block/grain processor function that receives a transformed block in the frequency domain (the ``transform`` output) and should return the processed data (it will be the first ``inverse_transform`` input). This parameter shouldn't appear when this function is used as a decorator. size : Block size for the STFT process, in samples. hop : Duration in samples between two blocks. Defaults to the ``size`` value. transform : Function that receives the windowed block (in time domain) and the ``size`` as two positional inputs and should return the block (in frequency domain). Defaults to ``numpy.fft.rfft``, which outputs a Numpy 1D array with length equals to ``size // 2 + 1``. inverse_transform : Function that receives the processed block (in frequency domain) and the ``size`` as two positional inputs and should return the block (in time domain). Defaults to ``numpy.fft.irfft``. wnd : Window function to be called as ``wnd(size)`` or window iterable with length equals to ``size``. The windowing/apodization values are used before taking the FFT of each block. Defaults to None, which means no window should be applied (same behavior of a rectangular window). before : Function to be applied just before taking the transform, after the windowing. Defaults to the ``numpy.fft.ifftshift``, which, together with the ``after`` default, puts the time reference at the ``size // 2`` index of the block, centralizing it for the FFT (e.g. blocks ``[0, 1, 0]`` and ``[0, 0, 1, 0]`` would have zero phase). To disable this realignment, just change both ``before=None`` and ``after=None`` keywords. after : Function to be applied just after the inverse transform, before calling the overlap-add (as well as before its windowing, if any). Defaults to the ``numpy.fft.fftshift`` function, which undo the changes done by the default ``before`` pre-processing for block phase alignment. To avoid the default time-domain realignment, set both ``before=None`` and ``after=None`` keywords. ola : Overlap-add strategy. Uses the ``overlap_add`` default strategy when not given. The strategy should allow at least size and hop keyword arguments, besides a first positional argument for the iterable with blocks. If ``ola=None``, the result from using the STFT processor will be the ``Stream`` of blocks that would be the overlap-add input. ola_* : Extra keyword parameters for the overlap-add strategy, if any. The extra ``ola_`` prefix is removed when calling it. See the overlap-add strategy docs for more information about the valid parameters. Returns ------- A function with the same parameters above, besides ``func``, which is replaced by the signal input (if func was given). The parameters used when building the function should be seen as defaults that can be changed when calling the resulting function with the respective keyword arguments. Examples -------- Let's process something: >>> my_signal = Stream(.1, .3, -.1, -.3, .5, .4, .3) Wrapping directly the processor function: >>> processor_w = stft(abs, size=64) >>> sig = my_signal.copy() # Any iterable >>> processor_w(sig) <audiolazy.lazy_stream.Stream object at 0x...> >>> peek200_w = _.peek(200) # Needs Numpy >>> type(peek200_w[0]).__name__ # Result is a signal (numpy.float64 data) 'float64' Keyword parameters in a partial evaluation style (can be reassigned): >>> stft64 = stft(size=64) # Same to ``stft`` but with other defaults >>> processor_p = stft64(abs) >>> sig = my_signal.copy() # Any iterable >>> processor_p(sig) <audiolazy.lazy_stream.Stream object at 0x...> >>> _.peek(200) == peek200_w # This should do the same thing True As a decorator, this time with other windowing configuration: >>> stft64hann = stft64(wnd=window.hann, ola_wnd=window.hann) >>> @stft64hann # stft(...) can also be used as an anonymous decorator ... def processor_d(blk): ... return abs(blk) >>> processor_d(sig) # This leads to a different result <audiolazy.lazy_stream.Stream object at 0x...> >>> _.peek(200) == peek200_w False You can also use other iterables as input, and keep the parameters to be passed afterwards, as well as change transform calculation: >>> stft_no_zero_phase = stft(before=None, after=None) >>> stft_no_wnd = stft_no_zero_phase(ola=overlap_add.list, ola_wnd=None, ... ola_normalize=False) >>> on_blocks = stft_no_wnd(transform=None, inverse_transform=None) >>> processor_a = on_blocks(reversed, hop=4) # Reverse >>> processor_a([1, 2, 3, 4, 5], size=4, hop=2) <audiolazy.lazy_stream.Stream object at 0x...> >>> list(_) # From blocks [1, 2, 3, 4] and [3, 4, 5, 0.0] [4.0, 3.0, 2.0, 6, 4, 3] >>> processor_a([1, 2, 3, 4, 5], size=4) # Default hop instead <audiolazy.lazy_stream.Stream object at 0x...> >>> list(_) # No overlap, blocks [1, 2, 3, 4] and [5, 0.0, 0.0, 0.0] [4, 3, 2, 1, 0.0, 0.0, 0.0, 5] >>> processor_a([1, 2, 3, 4, 5]) # Size was never given Traceback (most recent call last): ... TypeError: Missing 'size' argument For analysis only, one can set ``ola=None``: >>> from numpy.fft import ifftshift # [1, 2, 3, 4, 5] -> [3, 4, 5, 1, 2] >>> analyzer = stft(ifftshift, ola=None, size=8, hop=2) >>> sig = Stream(1, 0, -1, 0) # A pi/2 rad/sample cosine signal >>> result = analyzer(sig) >>> result <audiolazy.lazy_stream.Stream object at 0x...> Let's see the result contents. That processing "rotates" the frequencies, converting the original ``[0, 0, 4, 0, 0]`` real FFT block to a ``[4, 0, 0, 0, 0]`` block, which means the block cosine was moved to a DC-only signal keeping original energy/integral: >>> result.take() array([ 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]) >>> result.take() # From [0, 0, -4, 0, 0] to [-4, 0, 0, 0, 0] array([-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5]) Note ---- Parameters should be passed as keyword arguments. The only exception is ``func`` for this function and ``sig`` for the returned function, which are always the first positional argument, ald also the one that shouldn't appear when using this function as a decorator. Hint ---- 1. When using Numpy FFT, one can keep data in place and return the changed input block to save time; 2. Actually, there's nothing in this function that imposes FFT or Numpy besides the default values. One can still use this even for other transforms that have nothing to do with the Fourier Transform. See Also -------- overlap_add : Overlap-add algorithm for an iterable (e.g. a Stream instance) of blocks (sequences such as lists or Numpy arrays). It's also a StrategyDict. window : Window/apodization/tapering functions for a given size as a StrategyDict. """ # Using as a decorator or to "replicate" this function with other defaults if func is None: cfi = chain.from_iterable mix_dict = lambda *dicts: dict(cfi(iteritems(d) for d in dicts)) result = lambda f=None, **new_kws: stft(f, **mix_dict(kwparams, new_kws)) return result # Using directly @tostream @wraps(func) def wrapper(sig, **kwargs): kws = kwparams.copy() kws.update(kwargs) if "size" not in kws: raise TypeError("Missing 'size' argument") if "hop" in kws and kws["hop"] > kws["size"]: raise ValueError("Hop value can't be higher than size") blk_params = {"size": kws.pop("size")} blk_params["hop"] = kws.pop("hop", None) ola_params = blk_params.copy() # Size and hop blk_params["wnd"] = kws.pop("wnd", None) ola = kws.pop("ola", overlap_add) class NotSpecified(object): pass for name in ["transform", "inverse_transform", "before", "after"]: blk_params[name] = kws.pop(name, NotSpecified) for k, v in kws.items(): if k.startswith("ola_"): if ola is not None: ola_params[k[len("ola_"):]] = v else: raise TypeError("Extra '{}' argument with no overlap-add " "strategy".format(k)) else: raise TypeError("Unknown '{}' extra argument".format(k)) def blk_gen(size, hop, wnd, transform, inverse_transform, before, after): if transform is NotSpecified: from numpy.fft import rfft as transform if inverse_transform is NotSpecified: from numpy.fft import irfft as inverse_transform if before is NotSpecified: from numpy.fft import ifftshift as before if after is NotSpecified: from numpy.fft import fftshift as after # Find the right windowing function to be applied if callable(wnd) and not isinstance(wnd, Stream): wnd = wnd(size) if isinstance(wnd, Iterable): wnd = list(wnd) if len(wnd) != size: raise ValueError("Incompatible window size") elif wnd is not None: raise TypeError("Window should be an iterable or a callable") # Pad size lambdas trans = transform and (lambda blk: transform(blk, size)) itrans = inverse_transform and (lambda blk: inverse_transform(blk, size)) # Continuation style calling funcs = [f for f in [before, trans, func, itrans, after] if f is not None] process = lambda blk: reduce(lambda data, f: f(data), funcs, blk) if wnd is None: for blk in Stream(sig).blocks(size=size, hop=hop): yield process(blk) else: blk_with_wnd = wnd[:] mul = operator.mul for blk in Stream(sig).blocks(size=size, hop=hop): blk_with_wnd[:] = xmap(mul, blk, wnd) yield process(blk_with_wnd) if ola is None: return blk_gen(**blk_params) else: return ola(blk_gen(**blk_params), **ola_params) return wrapper
[ "def", "stft", "(", "func", "=", "None", ",", "*", "*", "kwparams", ")", ":", "# Using as a decorator or to \"replicate\" this function with other defaults", "if", "func", "is", "None", ":", "cfi", "=", "chain", ".", "from_iterable", "mix_dict", "=", "lambda", "*"...
Short Time Fourier Transform block processor / phase vocoder wrapper. This function can be used in many ways: * Directly as a signal processor builder, wrapping a spectrum block/grain processor function; * Directly as a decorator to a block processor; * Called without the ``func`` parameter for a partial evalution style changing the defaults. See the examples below for more information about these use cases. The resulting function performs a full block-by-block analysis/synthesis phase vocoder keeping this sequence of actions: 1. Blockenize the signal with the given ``size`` and ``hop``; 2. Lazily apply the given ``wnd`` window to each block; 3. Perform the 5 actions calling their functions in order: a. ``before``: Pre-processing; b. ``transform``: A transform like the FFT; c. ``func``: the positional parameter with the single block processor; d. ``inverse_transform``: inverse FFT; e. ``after``: Post-processing. 4. Overlap-add with the ``ola`` overlap-add strategy. The given ``ola`` would deal with its own window application and normalization. Any parameter from steps 3 and 4 can be set to ``None`` to skip it from the full process, without changing the other [sub]steps. The parameters defaults are based on the Numpy FFT subpackage. Parameters ---------- func : The block/grain processor function that receives a transformed block in the frequency domain (the ``transform`` output) and should return the processed data (it will be the first ``inverse_transform`` input). This parameter shouldn't appear when this function is used as a decorator. size : Block size for the STFT process, in samples. hop : Duration in samples between two blocks. Defaults to the ``size`` value. transform : Function that receives the windowed block (in time domain) and the ``size`` as two positional inputs and should return the block (in frequency domain). Defaults to ``numpy.fft.rfft``, which outputs a Numpy 1D array with length equals to ``size // 2 + 1``. inverse_transform : Function that receives the processed block (in frequency domain) and the ``size`` as two positional inputs and should return the block (in time domain). Defaults to ``numpy.fft.irfft``. wnd : Window function to be called as ``wnd(size)`` or window iterable with length equals to ``size``. The windowing/apodization values are used before taking the FFT of each block. Defaults to None, which means no window should be applied (same behavior of a rectangular window). before : Function to be applied just before taking the transform, after the windowing. Defaults to the ``numpy.fft.ifftshift``, which, together with the ``after`` default, puts the time reference at the ``size // 2`` index of the block, centralizing it for the FFT (e.g. blocks ``[0, 1, 0]`` and ``[0, 0, 1, 0]`` would have zero phase). To disable this realignment, just change both ``before=None`` and ``after=None`` keywords. after : Function to be applied just after the inverse transform, before calling the overlap-add (as well as before its windowing, if any). Defaults to the ``numpy.fft.fftshift`` function, which undo the changes done by the default ``before`` pre-processing for block phase alignment. To avoid the default time-domain realignment, set both ``before=None`` and ``after=None`` keywords. ola : Overlap-add strategy. Uses the ``overlap_add`` default strategy when not given. The strategy should allow at least size and hop keyword arguments, besides a first positional argument for the iterable with blocks. If ``ola=None``, the result from using the STFT processor will be the ``Stream`` of blocks that would be the overlap-add input. ola_* : Extra keyword parameters for the overlap-add strategy, if any. The extra ``ola_`` prefix is removed when calling it. See the overlap-add strategy docs for more information about the valid parameters. Returns ------- A function with the same parameters above, besides ``func``, which is replaced by the signal input (if func was given). The parameters used when building the function should be seen as defaults that can be changed when calling the resulting function with the respective keyword arguments. Examples -------- Let's process something: >>> my_signal = Stream(.1, .3, -.1, -.3, .5, .4, .3) Wrapping directly the processor function: >>> processor_w = stft(abs, size=64) >>> sig = my_signal.copy() # Any iterable >>> processor_w(sig) <audiolazy.lazy_stream.Stream object at 0x...> >>> peek200_w = _.peek(200) # Needs Numpy >>> type(peek200_w[0]).__name__ # Result is a signal (numpy.float64 data) 'float64' Keyword parameters in a partial evaluation style (can be reassigned): >>> stft64 = stft(size=64) # Same to ``stft`` but with other defaults >>> processor_p = stft64(abs) >>> sig = my_signal.copy() # Any iterable >>> processor_p(sig) <audiolazy.lazy_stream.Stream object at 0x...> >>> _.peek(200) == peek200_w # This should do the same thing True As a decorator, this time with other windowing configuration: >>> stft64hann = stft64(wnd=window.hann, ola_wnd=window.hann) >>> @stft64hann # stft(...) can also be used as an anonymous decorator ... def processor_d(blk): ... return abs(blk) >>> processor_d(sig) # This leads to a different result <audiolazy.lazy_stream.Stream object at 0x...> >>> _.peek(200) == peek200_w False You can also use other iterables as input, and keep the parameters to be passed afterwards, as well as change transform calculation: >>> stft_no_zero_phase = stft(before=None, after=None) >>> stft_no_wnd = stft_no_zero_phase(ola=overlap_add.list, ola_wnd=None, ... ola_normalize=False) >>> on_blocks = stft_no_wnd(transform=None, inverse_transform=None) >>> processor_a = on_blocks(reversed, hop=4) # Reverse >>> processor_a([1, 2, 3, 4, 5], size=4, hop=2) <audiolazy.lazy_stream.Stream object at 0x...> >>> list(_) # From blocks [1, 2, 3, 4] and [3, 4, 5, 0.0] [4.0, 3.0, 2.0, 6, 4, 3] >>> processor_a([1, 2, 3, 4, 5], size=4) # Default hop instead <audiolazy.lazy_stream.Stream object at 0x...> >>> list(_) # No overlap, blocks [1, 2, 3, 4] and [5, 0.0, 0.0, 0.0] [4, 3, 2, 1, 0.0, 0.0, 0.0, 5] >>> processor_a([1, 2, 3, 4, 5]) # Size was never given Traceback (most recent call last): ... TypeError: Missing 'size' argument For analysis only, one can set ``ola=None``: >>> from numpy.fft import ifftshift # [1, 2, 3, 4, 5] -> [3, 4, 5, 1, 2] >>> analyzer = stft(ifftshift, ola=None, size=8, hop=2) >>> sig = Stream(1, 0, -1, 0) # A pi/2 rad/sample cosine signal >>> result = analyzer(sig) >>> result <audiolazy.lazy_stream.Stream object at 0x...> Let's see the result contents. That processing "rotates" the frequencies, converting the original ``[0, 0, 4, 0, 0]`` real FFT block to a ``[4, 0, 0, 0, 0]`` block, which means the block cosine was moved to a DC-only signal keeping original energy/integral: >>> result.take() array([ 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]) >>> result.take() # From [0, 0, -4, 0, 0] to [-4, 0, 0, 0, 0] array([-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5]) Note ---- Parameters should be passed as keyword arguments. The only exception is ``func`` for this function and ``sig`` for the returned function, which are always the first positional argument, ald also the one that shouldn't appear when using this function as a decorator. Hint ---- 1. When using Numpy FFT, one can keep data in place and return the changed input block to save time; 2. Actually, there's nothing in this function that imposes FFT or Numpy besides the default values. One can still use this even for other transforms that have nothing to do with the Fourier Transform. See Also -------- overlap_add : Overlap-add algorithm for an iterable (e.g. a Stream instance) of blocks (sequences such as lists or Numpy arrays). It's also a StrategyDict. window : Window/apodization/tapering functions for a given size as a StrategyDict.
[ "Short", "Time", "Fourier", "Transform", "block", "processor", "/", "phase", "vocoder", "wrapper", "." ]
python
train
lordmauve/lepton
examples/games/bonk/controls.py
https://github.com/lordmauve/lepton/blob/bf03f2c20ea8c51ade632f692d0a21e520fbba7c/examples/games/bonk/controls.py#L95-L100
def configure_keys(self): """Configure key map""" self.active_functions = set() self.key2func = {} for funcname, key in self.key_map.items(): self.key2func[key] = getattr(self, funcname)
[ "def", "configure_keys", "(", "self", ")", ":", "self", ".", "active_functions", "=", "set", "(", ")", "self", ".", "key2func", "=", "{", "}", "for", "funcname", ",", "key", "in", "self", ".", "key_map", ".", "items", "(", ")", ":", "self", ".", "k...
Configure key map
[ "Configure", "key", "map" ]
python
train
erikrose/more-itertools
more_itertools/more.py
https://github.com/erikrose/more-itertools/blob/6a91b4e25c8e12fcf9fc2b53cf8ee0fba293e6f9/more_itertools/more.py#L334-L345
def _collate(*iterables, key=lambda a: a, reverse=False): """Helper for ``collate()``, called when the user is using the ``reverse`` or ``key`` keyword arguments on Python versions below 3.5. """ min_or_max = partial(max if reverse else min, key=itemgetter(0)) peekables = [peekable(it) for it in iterables] peekables = [p for p in peekables if p] # Kill empties. while peekables: _, p = min_or_max((key(p.peek()), p) for p in peekables) yield next(p) peekables = [x for x in peekables if x]
[ "def", "_collate", "(", "*", "iterables", ",", "key", "=", "lambda", "a", ":", "a", ",", "reverse", "=", "False", ")", ":", "min_or_max", "=", "partial", "(", "max", "if", "reverse", "else", "min", ",", "key", "=", "itemgetter", "(", "0", ")", ")",...
Helper for ``collate()``, called when the user is using the ``reverse`` or ``key`` keyword arguments on Python versions below 3.5.
[ "Helper", "for", "collate", "()", "called", "when", "the", "user", "is", "using", "the", "reverse", "or", "key", "keyword", "arguments", "on", "Python", "versions", "below", "3", ".", "5", "." ]
python
train
Calysto/calysto
calysto/ai/conx.py
https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L2128-L2136
def activationFunctionASIG(self, x): """ Determine the activation of a node based on that nodes net input. """ def act(v): if v < -15.0: return 0.0 elif v > 15.0: return 1.0 else: return 1.0 / (1.0 + Numeric.exp(-v)) return Numeric.array(list(map(act, x)), 'f')
[ "def", "activationFunctionASIG", "(", "self", ",", "x", ")", ":", "def", "act", "(", "v", ")", ":", "if", "v", "<", "-", "15.0", ":", "return", "0.0", "elif", "v", ">", "15.0", ":", "return", "1.0", "else", ":", "return", "1.0", "/", "(", "1.0", ...
Determine the activation of a node based on that nodes net input.
[ "Determine", "the", "activation", "of", "a", "node", "based", "on", "that", "nodes", "net", "input", "." ]
python
train
ChristopherRabotin/bungiesearch
bungiesearch/utils.py
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/utils.py#L90-L103
def create_indexed_document(index_instance, model_items, action): ''' Creates the document that will be passed into the bulk index function. Either a list of serialized objects to index, or a a dictionary specifying the primary keys of items to be delete. ''' data = [] if action == 'delete': for pk in model_items: data.append({'_id': pk, '_op_type': action}) else: for doc in model_items: if index_instance.matches_indexing_condition(doc): data.append(index_instance.serialize_object(doc)) return data
[ "def", "create_indexed_document", "(", "index_instance", ",", "model_items", ",", "action", ")", ":", "data", "=", "[", "]", "if", "action", "==", "'delete'", ":", "for", "pk", "in", "model_items", ":", "data", ".", "append", "(", "{", "'_id'", ":", "pk"...
Creates the document that will be passed into the bulk index function. Either a list of serialized objects to index, or a a dictionary specifying the primary keys of items to be delete.
[ "Creates", "the", "document", "that", "will", "be", "passed", "into", "the", "bulk", "index", "function", ".", "Either", "a", "list", "of", "serialized", "objects", "to", "index", "or", "a", "a", "dictionary", "specifying", "the", "primary", "keys", "of", ...
python
train
rytilahti/python-eq3bt
eq3bt/eq3btsmart.py
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L314-L324
def window_open_config(self, temperature, duration): """Configures the window open behavior. The duration is specified in 5 minute increments.""" _LOGGER.debug("Window open config, temperature: %s duration: %s", temperature, duration) self._verify_temperature(temperature) if duration.seconds < 0 and duration.seconds > 3600: raise ValueError value = struct.pack('BBB', PROP_WINDOW_OPEN_CONFIG, int(temperature * 2), int(duration.seconds / 300)) self._conn.make_request(PROP_WRITE_HANDLE, value)
[ "def", "window_open_config", "(", "self", ",", "temperature", ",", "duration", ")", ":", "_LOGGER", ".", "debug", "(", "\"Window open config, temperature: %s duration: %s\"", ",", "temperature", ",", "duration", ")", "self", ".", "_verify_temperature", "(", "temperatu...
Configures the window open behavior. The duration is specified in 5 minute increments.
[ "Configures", "the", "window", "open", "behavior", ".", "The", "duration", "is", "specified", "in", "5", "minute", "increments", "." ]
python
train
catherinedevlin/ddl-generator
ddlgenerator/console.py
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/console.py#L72-L112
def generate(args=None, namespace=None, file=None): """ Genereate DDL from data sources named. :args: String or list of strings to be parsed for arguments :namespace: Namespace to extract arguments from :file: Write to this open file object (default stdout) """ if hasattr(args, 'split'): args = args.split() args = parser.parse_args(args, namespace) set_logging(args) logging.info(str(args)) if args.dialect in ('pg', 'pgsql', 'postgres'): args.dialect = 'postgresql' if args.dialect.startswith('dj'): args.dialect = 'django' elif args.dialect.startswith('sqla'): args.dialect = 'sqlalchemy' if args.dialect not in dialect_names: raise NotImplementedError('First arg must be one of: %s' % ", ".join(dialect_names)) if args.dialect == 'sqlalchemy': print(sqla_head, file=file) for datafile in args.datafile: if is_sqlalchemy_url.search(datafile): table_names_for_insert = [] for tbl in sqlalchemy_table_sources(datafile): t = generate_one(tbl, args, table_name=tbl.generator.name, file=file) if t.data: table_names_for_insert.append(tbl.generator.name) if args.inserts and args.dialect == 'sqlalchemy': print(sqla_inserter_call(table_names_for_insert), file=file) if t and args.inserts: for seq_update in emit_db_sequence_updates(t.source.db_engine): if args.dialect == 'sqlalchemy': print(' conn.execute("%s")' % seq_update, file=file) elif args.dialect == 'postgresql': print(seq_update, file=file) else: generate_one(datafile, args, file=file)
[ "def", "generate", "(", "args", "=", "None", ",", "namespace", "=", "None", ",", "file", "=", "None", ")", ":", "if", "hasattr", "(", "args", ",", "'split'", ")", ":", "args", "=", "args", ".", "split", "(", ")", "args", "=", "parser", ".", "pars...
Genereate DDL from data sources named. :args: String or list of strings to be parsed for arguments :namespace: Namespace to extract arguments from :file: Write to this open file object (default stdout)
[ "Genereate", "DDL", "from", "data", "sources", "named", "." ]
python
train
openego/eDisGo
edisgo/flex_opt/check_tech_constraints.py
https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/flex_opt/check_tech_constraints.py#L314-L408
def mv_voltage_deviation(network, voltage_levels='mv_lv'): """ Checks for voltage stability issues in MV grid. Parameters ---------- network : :class:`~.grid.network.Network` voltage_levels : :obj:`str` Specifies which allowed voltage deviations to use. Possible options are: * 'mv_lv' This is the default. The allowed voltage deviation for nodes in the MV grid is the same as for nodes in the LV grid. Further load and feed-in case are not distinguished. * 'mv' Use this to handle allowed voltage deviations in the MV and LV grid differently. Here, load and feed-in case are differentiated as well. Returns ------- :obj:`dict` Dictionary with :class:`~.grid.grids.MVGrid` as key and a :pandas:`pandas.DataFrame<dataframe>` with its critical nodes, sorted descending by voltage deviation, as value. Index of the dataframe are all nodes (of type :class:`~.grid.components.Generator`, :class:`~.grid.components.Load`, etc.) with over-voltage issues. Columns are 'v_mag_pu' containing the maximum voltage deviation as float and 'time_index' containing the corresponding time step the over-voltage occured in as :pandas:`pandas.Timestamp<timestamp>`. Notes ----- Over-voltage is determined based on allowed voltage deviations defined in the config file 'config_grid_expansion' in section 'grid_expansion_allowed_voltage_deviations'. """ crit_nodes = {} v_dev_allowed_per_case = {} v_dev_allowed_per_case['feedin_case_lower'] = 0.9 v_dev_allowed_per_case['load_case_upper'] = 1.1 offset = network.config[ 'grid_expansion_allowed_voltage_deviations']['hv_mv_trafo_offset'] control_deviation = network.config[ 'grid_expansion_allowed_voltage_deviations'][ 'hv_mv_trafo_control_deviation'] if voltage_levels == 'mv_lv': v_dev_allowed_per_case['feedin_case_upper'] = \ 1 + offset + control_deviation + network.config[ 'grid_expansion_allowed_voltage_deviations'][ 'mv_lv_feedin_case_max_v_deviation'] v_dev_allowed_per_case['load_case_lower'] = \ 1 + offset - control_deviation - network.config[ 'grid_expansion_allowed_voltage_deviations'][ 'mv_lv_load_case_max_v_deviation'] elif voltage_levels == 'mv': v_dev_allowed_per_case['feedin_case_upper'] = \ 1 + offset + control_deviation + network.config[ 'grid_expansion_allowed_voltage_deviations'][ 'mv_feedin_case_max_v_deviation'] v_dev_allowed_per_case['load_case_lower'] = \ 1 + offset - control_deviation - network.config[ 'grid_expansion_allowed_voltage_deviations'][ 'mv_load_case_max_v_deviation'] else: raise ValueError( 'Specified mode {} is not a valid option.'.format(voltage_levels)) # maximum allowed apparent power of station in each time step v_dev_allowed_upper = \ network.timeseries.timesteps_load_feedin_case.case.apply( lambda _: v_dev_allowed_per_case['{}_upper'.format(_)]) v_dev_allowed_lower = \ network.timeseries.timesteps_load_feedin_case.case.apply( lambda _: v_dev_allowed_per_case['{}_lower'.format(_)]) nodes = network.mv_grid.graph.nodes() crit_nodes_grid = _voltage_deviation( network, nodes, v_dev_allowed_upper, v_dev_allowed_lower, voltage_level='mv') if not crit_nodes_grid.empty: crit_nodes[network.mv_grid] = crit_nodes_grid.sort_values( by=['v_mag_pu'], ascending=False) logger.debug( '==> {} node(s) in MV grid has/have voltage issues.'.format( crit_nodes[network.mv_grid].shape[0])) else: logger.debug('==> No voltage issues in MV grid.') return crit_nodes
[ "def", "mv_voltage_deviation", "(", "network", ",", "voltage_levels", "=", "'mv_lv'", ")", ":", "crit_nodes", "=", "{", "}", "v_dev_allowed_per_case", "=", "{", "}", "v_dev_allowed_per_case", "[", "'feedin_case_lower'", "]", "=", "0.9", "v_dev_allowed_per_case", "["...
Checks for voltage stability issues in MV grid. Parameters ---------- network : :class:`~.grid.network.Network` voltage_levels : :obj:`str` Specifies which allowed voltage deviations to use. Possible options are: * 'mv_lv' This is the default. The allowed voltage deviation for nodes in the MV grid is the same as for nodes in the LV grid. Further load and feed-in case are not distinguished. * 'mv' Use this to handle allowed voltage deviations in the MV and LV grid differently. Here, load and feed-in case are differentiated as well. Returns ------- :obj:`dict` Dictionary with :class:`~.grid.grids.MVGrid` as key and a :pandas:`pandas.DataFrame<dataframe>` with its critical nodes, sorted descending by voltage deviation, as value. Index of the dataframe are all nodes (of type :class:`~.grid.components.Generator`, :class:`~.grid.components.Load`, etc.) with over-voltage issues. Columns are 'v_mag_pu' containing the maximum voltage deviation as float and 'time_index' containing the corresponding time step the over-voltage occured in as :pandas:`pandas.Timestamp<timestamp>`. Notes ----- Over-voltage is determined based on allowed voltage deviations defined in the config file 'config_grid_expansion' in section 'grid_expansion_allowed_voltage_deviations'.
[ "Checks", "for", "voltage", "stability", "issues", "in", "MV", "grid", "." ]
python
train
reingart/gui2py
gui/controls/gridview.py
https://github.com/reingart/gui2py/blob/aca0a05f6fcde55c94ad7cc058671a06608b01a4/gui/controls/gridview.py#L291-L296
def UpdateValues(self, grid): "Update all displayed values" # This sends an event to the grid table to update all of the values msg = gridlib.GridTableMessage(self, gridlib.GRIDTABLE_REQUEST_VIEW_GET_VALUES) grid.ProcessTableMessage(msg)
[ "def", "UpdateValues", "(", "self", ",", "grid", ")", ":", "# This sends an event to the grid table to update all of the values\r", "msg", "=", "gridlib", ".", "GridTableMessage", "(", "self", ",", "gridlib", ".", "GRIDTABLE_REQUEST_VIEW_GET_VALUES", ")", "grid", ".", "...
Update all displayed values
[ "Update", "all", "displayed", "values" ]
python
test
phoebe-project/phoebe2
phoebe/backend/mesh.py
https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L1353-L1363
def visibilities(self): """ Return the array of visibilities, where each item is a scalar/float between 0 (completely hidden/invisible) and 1 (completely visible). (Nx1) """ if self._visibilities is not None: return self._visibilities else: return np.ones(self.Ntriangles)
[ "def", "visibilities", "(", "self", ")", ":", "if", "self", ".", "_visibilities", "is", "not", "None", ":", "return", "self", ".", "_visibilities", "else", ":", "return", "np", ".", "ones", "(", "self", ".", "Ntriangles", ")" ]
Return the array of visibilities, where each item is a scalar/float between 0 (completely hidden/invisible) and 1 (completely visible). (Nx1)
[ "Return", "the", "array", "of", "visibilities", "where", "each", "item", "is", "a", "scalar", "/", "float", "between", "0", "(", "completely", "hidden", "/", "invisible", ")", "and", "1", "(", "completely", "visible", ")", "." ]
python
train
rwl/pylon
contrib/cvxopf.py
https://github.com/rwl/pylon/blob/916514255db1ae1661406f0283df756baf960d14/contrib/cvxopf.py#L114-L118
def _update_case(self, bs, ln, gn, base_mva, Bf, Pfinj, Va, Pg, lmbda): """ Calculates the result attribute values. """ for i, bus in enumerate(bs): bus.v_angle = Va[i] * 180.0 / pi
[ "def", "_update_case", "(", "self", ",", "bs", ",", "ln", ",", "gn", ",", "base_mva", ",", "Bf", ",", "Pfinj", ",", "Va", ",", "Pg", ",", "lmbda", ")", ":", "for", "i", ",", "bus", "in", "enumerate", "(", "bs", ")", ":", "bus", ".", "v_angle", ...
Calculates the result attribute values.
[ "Calculates", "the", "result", "attribute", "values", "." ]
python
train
ToucanToco/toucan-data-sdk
toucan_data_sdk/utils/decorators.py
https://github.com/ToucanToco/toucan-data-sdk/blob/c3ca874e1b64f4bdcc2edda750a72d45d1561d8a/toucan_data_sdk/utils/decorators.py#L158-L182
def log(logger=None, start_message='Starting...', end_message='Done...'): """ Basic log decorator Can be used as : - @log (with default logger) - @log(mylogger) - @log(start_message='Hello !", logger=mylogger, end_message='Bye !') """ def actual_log(f, real_logger=logger): logger = real_logger or _logger @wraps(f) def timed(*args, **kwargs): logger.info(f'{f.__name__} - {start_message}') start = time.time() res = f(*args, **kwargs) end = time.time() logger.info(f'{f.__name__} - {end_message} (took {end - start:.2f}s)') return res return timed if callable(logger): return actual_log(logger, real_logger=None) return actual_log
[ "def", "log", "(", "logger", "=", "None", ",", "start_message", "=", "'Starting...'", ",", "end_message", "=", "'Done...'", ")", ":", "def", "actual_log", "(", "f", ",", "real_logger", "=", "logger", ")", ":", "logger", "=", "real_logger", "or", "_logger",...
Basic log decorator Can be used as : - @log (with default logger) - @log(mylogger) - @log(start_message='Hello !", logger=mylogger, end_message='Bye !')
[ "Basic", "log", "decorator", "Can", "be", "used", "as", ":", "-" ]
python
test
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L646-L651
def strseq(object, convert, join=joinseq): """Recursively walk a sequence, stringifying each element.""" if type(object) in [types.ListType, types.TupleType]: return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object)) else: return convert(object)
[ "def", "strseq", "(", "object", ",", "convert", ",", "join", "=", "joinseq", ")", ":", "if", "type", "(", "object", ")", "in", "[", "types", ".", "ListType", ",", "types", ".", "TupleType", "]", ":", "return", "join", "(", "map", "(", "lambda", "o"...
Recursively walk a sequence, stringifying each element.
[ "Recursively", "walk", "a", "sequence", "stringifying", "each", "element", "." ]
python
train
tensorflow/tensorboard
tensorboard/compat/tensorflow_stub/io/gfile.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/compat/tensorflow_stub/io/gfile.py#L463-L510
def walk(top, topdown=True, onerror=None): """Recursive directory tree generator for directories. Args: top: string, a Directory name topdown: bool, Traverse pre order if True, post order if False. onerror: optional handler for errors. Should be a function, it will be called with the error as argument. Rethrowing the error aborts the walk. Errors that happen while listing directories are ignored. Yields: Each yield is a 3-tuple: the pathname of a directory, followed by lists of all its subdirectories and leaf files. (dirname, [subdirname, subdirname, ...], [filename, filename, ...]) as strings """ top = compat.as_str_any(top) fs = get_filesystem(top) try: listing = listdir(top) except errors.NotFoundError as err: if onerror: onerror(err) else: return files = [] subdirs = [] for item in listing: full_path = fs.join(top, compat.as_str_any(item)) if isdir(full_path): subdirs.append(item) else: files.append(item) here = (top, subdirs, files) if topdown: yield here for subdir in subdirs: joined_subdir = fs.join(top, compat.as_str_any(subdir)) for subitem in walk(joined_subdir, topdown, onerror=onerror): yield subitem if not topdown: yield here
[ "def", "walk", "(", "top", ",", "topdown", "=", "True", ",", "onerror", "=", "None", ")", ":", "top", "=", "compat", ".", "as_str_any", "(", "top", ")", "fs", "=", "get_filesystem", "(", "top", ")", "try", ":", "listing", "=", "listdir", "(", "top"...
Recursive directory tree generator for directories. Args: top: string, a Directory name topdown: bool, Traverse pre order if True, post order if False. onerror: optional handler for errors. Should be a function, it will be called with the error as argument. Rethrowing the error aborts the walk. Errors that happen while listing directories are ignored. Yields: Each yield is a 3-tuple: the pathname of a directory, followed by lists of all its subdirectories and leaf files. (dirname, [subdirname, subdirname, ...], [filename, filename, ...]) as strings
[ "Recursive", "directory", "tree", "generator", "for", "directories", "." ]
python
train
CalebBell/thermo
thermo/eos.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L480-L551
def volume_solutions(T, P, b, delta, epsilon, a_alpha, quick=True): r'''Solution of this form of the cubic EOS in terms of volumes. Returns three values, all with some complex part. Parameters ---------- T : float Temperature, [K] P : float Pressure, [Pa] b : float Coefficient calculated by EOS-specific method, [m^3/mol] delta : float Coefficient calculated by EOS-specific method, [m^3/mol] epsilon : float Coefficient calculated by EOS-specific method, [m^6/mol^2] a_alpha : float Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] quick : bool, optional Whether to use a SymPy cse-derived expression (3x faster) or individual formulas Returns ------- Vs : list[float] Three possible molar volumes, [m^3/mol] Notes ----- Using explicit formulas, as can be derived in the following example, is faster than most numeric root finding techniques, and finds all values explicitly. It takes several seconds. >>> from sympy import * >>> P, T, V, R, b, a, delta, epsilon, alpha = symbols('P, T, V, R, b, a, delta, epsilon, alpha') >>> Tc, Pc, omega = symbols('Tc, Pc, omega') >>> CUBIC = R*T/(V-b) - a*alpha/(V*V + delta*V + epsilon) - P >>> #solve(CUBIC, V) ''' if quick: x0 = 1./P x1 = P*b x2 = R*T x3 = P*delta x4 = x1 + x2 - x3 x5 = x0*x4 x6 = a_alpha*b x7 = epsilon*x1 x8 = epsilon*x2 x9 = x0*x0 x10 = P*epsilon x11 = delta*x1 x12 = delta*x2 x13 = 3.*a_alpha x14 = 3.*x10 x15 = 3.*x11 x16 = 3.*x12 x17 = -x1 - x2 + x3 x18 = x0*x17*x17 x19 = ((-13.5*x0*(x6 + x7 + x8) - 4.5*x4*x9*(-a_alpha - x10 + x11 + x12) + ((x9*(-4.*x0*(-x13 - x14 + x15 + x16 + x18)**3 + (-9.*x0*x17*(a_alpha + x10 - x11 - x12) + 2.*x17*x17*x17*x9 - 27.*(x6 + x7 + x8))**2))+0j)**0.5*0.5 - x4**3*x9*x0)+0j)**(1./3.) x20 = x13 + x14 - x15 - x16 - x18 x22 = 2.*x5 x24 = 1.7320508075688772j + 1. x25 = 4.*x0*x20/x19 x26 = -1.7320508075688772j + 1. return [(x0*x20/x19 - x19 + x5)/3., (x19*x24 + x22 - x25/x24)/6., (x19*x26 + x22 - x25/x26)/6.] else: return [-(-3*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P + (-P*b + P*delta - R*T)**2/P**2)/(3*(sqrt(-4*(-3*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P + (-P*b + P*delta - R*T)**2/P**2)**3 + (27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/P - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P**2 + 2*(-P*b + P*delta - R*T)**3/P**3)**2)/2 + 27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/(2*P) - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/(2*P**2) + (-P*b + P*delta - R*T)**3/P**3)**(1/3)) - (sqrt(-4*(-3*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P + (-P*b + P*delta - R*T)**2/P**2)**3 + (27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/P - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P**2 + 2*(-P*b + P*delta - R*T)**3/P**3)**2)/2 + 27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/(2*P) - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/(2*P**2) + (-P*b + P*delta - R*T)**3/P**3)**(1/3)/3 - (-P*b + P*delta - R*T)/(3*P), -(-3*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P + (-P*b + P*delta - R*T)**2/P**2)/(3*(-1/2 - sqrt(3)*1j/2)*(sqrt(-4*(-3*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P + (-P*b + P*delta - R*T)**2/P**2)**3 + (27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/P - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P**2 + 2*(-P*b + P*delta - R*T)**3/P**3)**2)/2 + 27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/(2*P) - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/(2*P**2) + (-P*b + P*delta - R*T)**3/P**3)**(1/3)) - (-1/2 - sqrt(3)*1j/2)*(sqrt(-4*(-3*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P + (-P*b + P*delta - R*T)**2/P**2)**3 + (27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/P - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P**2 + 2*(-P*b + P*delta - R*T)**3/P**3)**2)/2 + 27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/(2*P) - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/(2*P**2) + (-P*b + P*delta - R*T)**3/P**3)**(1/3)/3 - (-P*b + P*delta - R*T)/(3*P), -(-3*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P + (-P*b + P*delta - R*T)**2/P**2)/(3*(-1/2 + sqrt(3)*1j/2)*(sqrt(-4*(-3*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P + (-P*b + P*delta - R*T)**2/P**2)**3 + (27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/P - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P**2 + 2*(-P*b + P*delta - R*T)**3/P**3)**2)/2 + 27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/(2*P) - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/(2*P**2) + (-P*b + P*delta - R*T)**3/P**3)**(1/3)) - (-1/2 + sqrt(3)*1j/2)*(sqrt(-4*(-3*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P + (-P*b + P*delta - R*T)**2/P**2)**3 + (27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/P - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/P**2 + 2*(-P*b + P*delta - R*T)**3/P**3)**2)/2 + 27*(-P*b*epsilon - R*T*epsilon - a_alpha*b)/(2*P) - 9*(-P*b + P*delta - R*T)*(-P*b*delta + P*epsilon - R*T*delta + a_alpha)/(2*P**2) + (-P*b + P*delta - R*T)**3/P**3)**(1/3)/3 - (-P*b + P*delta - R*T)/(3*P)]
[ "def", "volume_solutions", "(", "T", ",", "P", ",", "b", ",", "delta", ",", "epsilon", ",", "a_alpha", ",", "quick", "=", "True", ")", ":", "if", "quick", ":", "x0", "=", "1.", "/", "P", "x1", "=", "P", "*", "b", "x2", "=", "R", "*", "T", "...
r'''Solution of this form of the cubic EOS in terms of volumes. Returns three values, all with some complex part. Parameters ---------- T : float Temperature, [K] P : float Pressure, [Pa] b : float Coefficient calculated by EOS-specific method, [m^3/mol] delta : float Coefficient calculated by EOS-specific method, [m^3/mol] epsilon : float Coefficient calculated by EOS-specific method, [m^6/mol^2] a_alpha : float Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] quick : bool, optional Whether to use a SymPy cse-derived expression (3x faster) or individual formulas Returns ------- Vs : list[float] Three possible molar volumes, [m^3/mol] Notes ----- Using explicit formulas, as can be derived in the following example, is faster than most numeric root finding techniques, and finds all values explicitly. It takes several seconds. >>> from sympy import * >>> P, T, V, R, b, a, delta, epsilon, alpha = symbols('P, T, V, R, b, a, delta, epsilon, alpha') >>> Tc, Pc, omega = symbols('Tc, Pc, omega') >>> CUBIC = R*T/(V-b) - a*alpha/(V*V + delta*V + epsilon) - P >>> #solve(CUBIC, V)
[ "r", "Solution", "of", "this", "form", "of", "the", "cubic", "EOS", "in", "terms", "of", "volumes", ".", "Returns", "three", "values", "all", "with", "some", "complex", "part", "." ]
python
valid
knipknap/exscript
Exscript/protocols/osguesser.py
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/osguesser.py#L54-L65
def set(self, key, value, confidence=100): """ Defines the given value with the given confidence, unless the same value is already defined with a higher confidence level. """ if value is None: return if key in self.info: old_confidence, old_value = self.info.get(key) if old_confidence >= confidence: return self.info[key] = (confidence, value)
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "confidence", "=", "100", ")", ":", "if", "value", "is", "None", ":", "return", "if", "key", "in", "self", ".", "info", ":", "old_confidence", ",", "old_value", "=", "self", ".", "info", "."...
Defines the given value with the given confidence, unless the same value is already defined with a higher confidence level.
[ "Defines", "the", "given", "value", "with", "the", "given", "confidence", "unless", "the", "same", "value", "is", "already", "defined", "with", "a", "higher", "confidence", "level", "." ]
python
train
ThreatConnect-Inc/tcex
tcex/tcex.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex.py#L860-L889
def s(self, data, errors='strict'): """Decode value using correct Python 2/3 method. This method is intended to replace the :py:meth:`~tcex.tcex.TcEx.to_string` method with better logic to handle poorly encoded unicode data in Python2 and still work in Python3. Args: data (any): Data to ve validated and (de)encoded errors (string): What method to use when dealing with errors. Returns: (string): Return decoded data """ try: if data is None or isinstance(data, (int, list, dict)): pass # Do nothing with these types elif isinstance(data, unicode): try: data.decode('utf-8') except UnicodeEncodeError: # 2to3 converts unicode to str # 2to3 converts unicode to str data = str(data.encode('utf-8').strip(), errors=errors) self.log.warning(u'Encoding poorly encoded string ({})'.format(data)) except AttributeError: pass # Python 3 can't decode a str else: data = str(data, 'utf-8', errors=errors) # 2to3 converts unicode to str except NameError: pass # Can't decode str in Python 3 return data
[ "def", "s", "(", "self", ",", "data", ",", "errors", "=", "'strict'", ")", ":", "try", ":", "if", "data", "is", "None", "or", "isinstance", "(", "data", ",", "(", "int", ",", "list", ",", "dict", ")", ")", ":", "pass", "# Do nothing with these types"...
Decode value using correct Python 2/3 method. This method is intended to replace the :py:meth:`~tcex.tcex.TcEx.to_string` method with better logic to handle poorly encoded unicode data in Python2 and still work in Python3. Args: data (any): Data to ve validated and (de)encoded errors (string): What method to use when dealing with errors. Returns: (string): Return decoded data
[ "Decode", "value", "using", "correct", "Python", "2", "/", "3", "method", "." ]
python
train
genialis/resolwe
resolwe/flow/elastic_indexes/base.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/elastic_indexes/base.py#L61-L66
def get_owner_names_value(self, obj): """Extract owners' names.""" return [ self._get_user(user) for user in get_users_with_permission(obj, get_full_perm('owner', obj)) ]
[ "def", "get_owner_names_value", "(", "self", ",", "obj", ")", ":", "return", "[", "self", ".", "_get_user", "(", "user", ")", "for", "user", "in", "get_users_with_permission", "(", "obj", ",", "get_full_perm", "(", "'owner'", ",", "obj", ")", ")", "]" ]
Extract owners' names.
[ "Extract", "owners", "names", "." ]
python
train
ktbyers/netmiko
netmiko/cisco_base_connection.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/cisco_base_connection.py#L41-L51
def config_mode(self, config_command="config term", pattern=""): """ Enter into configuration mode on remote device. Cisco IOS devices abbreviate the prompt at 20 chars in config mode """ if not pattern: pattern = re.escape(self.base_prompt[:16]) return super(CiscoBaseConnection, self).config_mode( config_command=config_command, pattern=pattern )
[ "def", "config_mode", "(", "self", ",", "config_command", "=", "\"config term\"", ",", "pattern", "=", "\"\"", ")", ":", "if", "not", "pattern", ":", "pattern", "=", "re", ".", "escape", "(", "self", ".", "base_prompt", "[", ":", "16", "]", ")", "retur...
Enter into configuration mode on remote device. Cisco IOS devices abbreviate the prompt at 20 chars in config mode
[ "Enter", "into", "configuration", "mode", "on", "remote", "device", "." ]
python
train
googleapis/google-cloud-python
trace/google/cloud/trace/_gapic.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/trace/google/cloud/trace/_gapic.py#L245-L258
def _dict_mapping_to_pb(mapping, proto_type): """ Convert a dict to protobuf. Args: mapping (dict): A dict that needs to be converted to protobuf. proto_type (str): The type of the Protobuf. Returns: An instance of the specified protobuf. """ converted_pb = getattr(trace_pb2, proto_type)() ParseDict(mapping, converted_pb) return converted_pb
[ "def", "_dict_mapping_to_pb", "(", "mapping", ",", "proto_type", ")", ":", "converted_pb", "=", "getattr", "(", "trace_pb2", ",", "proto_type", ")", "(", ")", "ParseDict", "(", "mapping", ",", "converted_pb", ")", "return", "converted_pb" ]
Convert a dict to protobuf. Args: mapping (dict): A dict that needs to be converted to protobuf. proto_type (str): The type of the Protobuf. Returns: An instance of the specified protobuf.
[ "Convert", "a", "dict", "to", "protobuf", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py#L501-L511
def ip_rtm_config_load_sharing(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:brocade.com:mgmt:brocade-rtm") load_sharing = ET.SubElement(rtm_config, "load-sharing") load_sharing.text = kwargs.pop('load_sharing') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "ip_rtm_config_load_sharing", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ip", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ip\"", ",", "xmlns", "=", "\"urn:brocade.com:mgmt:b...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
duguyue100/minesweeper
minesweeper/gui.py
https://github.com/duguyue100/minesweeper/blob/38b1910f4c34d0275ac10a300285aba6f1d91d61/minesweeper/gui.py#L46-L62
def init_ui(self): """Setup control widget UI.""" self.control_layout = QHBoxLayout() self.setLayout(self.control_layout) self.reset_button = QPushButton() self.reset_button.setFixedSize(40, 40) self.reset_button.setIcon(QtGui.QIcon(WIN_PATH)) self.game_timer = QLCDNumber() self.game_timer.setStyleSheet("QLCDNumber {color: red;}") self.game_timer.setFixedWidth(100) self.move_counter = QLCDNumber() self.move_counter.setStyleSheet("QLCDNumber {color: red;}") self.move_counter.setFixedWidth(100) self.control_layout.addWidget(self.game_timer) self.control_layout.addWidget(self.reset_button) self.control_layout.addWidget(self.move_counter)
[ "def", "init_ui", "(", "self", ")", ":", "self", ".", "control_layout", "=", "QHBoxLayout", "(", ")", "self", ".", "setLayout", "(", "self", ".", "control_layout", ")", "self", ".", "reset_button", "=", "QPushButton", "(", ")", "self", ".", "reset_button",...
Setup control widget UI.
[ "Setup", "control", "widget", "UI", "." ]
python
train
klahnakoski/pyLibrary
mo_threads/queues.py
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_threads/queues.py#L72-L96
def add(self, value, timeout=None, force=False): """ :param value: ADDED THE THE QUEUE :param timeout: HOW LONG TO WAIT FOR QUEUE TO NOT BE FULL :param force: ADD TO QUEUE, EVEN IF FULL (USE ONLY WHEN CONSUMER IS RETURNING WORK TO THE QUEUE) :return: self """ with self.lock: if value is THREAD_STOP: # INSIDE THE lock SO THAT EXITING WILL RELEASE wait() self.queue.append(value) self.closed.go() return if not force: self._wait_for_queue_space(timeout=timeout) if self.closed and not self.allow_add_after_close: Log.error("Do not add to closed queue") else: if self.unique: if value not in self.queue: self.queue.append(value) else: self.queue.append(value) return self
[ "def", "add", "(", "self", ",", "value", ",", "timeout", "=", "None", ",", "force", "=", "False", ")", ":", "with", "self", ".", "lock", ":", "if", "value", "is", "THREAD_STOP", ":", "# INSIDE THE lock SO THAT EXITING WILL RELEASE wait()", "self", ".", "queu...
:param value: ADDED THE THE QUEUE :param timeout: HOW LONG TO WAIT FOR QUEUE TO NOT BE FULL :param force: ADD TO QUEUE, EVEN IF FULL (USE ONLY WHEN CONSUMER IS RETURNING WORK TO THE QUEUE) :return: self
[ ":", "param", "value", ":", "ADDED", "THE", "THE", "QUEUE", ":", "param", "timeout", ":", "HOW", "LONG", "TO", "WAIT", "FOR", "QUEUE", "TO", "NOT", "BE", "FULL", ":", "param", "force", ":", "ADD", "TO", "QUEUE", "EVEN", "IF", "FULL", "(", "USE", "O...
python
train
saltstack/salt
salt/crypt.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/crypt.py#L1406-L1426
def encrypt(self, data): ''' encrypt data with AES-CBC and sign it with HMAC-SHA256 ''' aes_key, hmac_key = self.keys pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE if six.PY2: data = data + pad * chr(pad) else: data = data + salt.utils.stringutils.to_bytes(pad * chr(pad)) iv_bytes = os.urandom(self.AES_BLOCK_SIZE) if HAS_M2: cypher = EVP.Cipher(alg='aes_192_cbc', key=aes_key, iv=iv_bytes, op=1, padding=False) encr = cypher.update(data) encr += cypher.final() else: cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes) encr = cypher.encrypt(data) data = iv_bytes + encr sig = hmac.new(hmac_key, data, hashlib.sha256).digest() return data + sig
[ "def", "encrypt", "(", "self", ",", "data", ")", ":", "aes_key", ",", "hmac_key", "=", "self", ".", "keys", "pad", "=", "self", ".", "AES_BLOCK_SIZE", "-", "len", "(", "data", ")", "%", "self", ".", "AES_BLOCK_SIZE", "if", "six", ".", "PY2", ":", "...
encrypt data with AES-CBC and sign it with HMAC-SHA256
[ "encrypt", "data", "with", "AES", "-", "CBC", "and", "sign", "it", "with", "HMAC", "-", "SHA256" ]
python
train
ondryaso/pi-rc522
pirc522/util.py
https://github.com/ondryaso/pi-rc522/blob/9d9103e9701c105ba2348155e91f21ef338c4bd3/pirc522/util.py#L99-L122
def rewrite(self, block_address, new_bytes): """ Rewrites block with new bytes, keeping the old ones if None is passed. Tag and auth must be set - does auth. Returns error state. """ if not self.is_tag_set_auth(): return True error = self.do_auth(block_address) if not error: (error, data) = self.rfid.read(block_address) if not error: for i in range(len(new_bytes)): if new_bytes[i] != None: if self.debug: print("Changing pos " + str(i) + " with current value " + str(data[i]) + " to " + str(new_bytes[i])) data[i] = new_bytes[i] error = self.rfid.write(block_address, data) if self.debug: print("Writing " + str(data) + " to " + self.sector_string(block_address)) return error
[ "def", "rewrite", "(", "self", ",", "block_address", ",", "new_bytes", ")", ":", "if", "not", "self", ".", "is_tag_set_auth", "(", ")", ":", "return", "True", "error", "=", "self", ".", "do_auth", "(", "block_address", ")", "if", "not", "error", ":", "...
Rewrites block with new bytes, keeping the old ones if None is passed. Tag and auth must be set - does auth. Returns error state.
[ "Rewrites", "block", "with", "new", "bytes", "keeping", "the", "old", "ones", "if", "None", "is", "passed", ".", "Tag", "and", "auth", "must", "be", "set", "-", "does", "auth", ".", "Returns", "error", "state", "." ]
python
train
juju/charm-helpers
charmhelpers/core/kernel_factory/centos.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/kernel_factory/centos.py#L5-L12
def persistent_modprobe(module): """Load a kernel module and configure for auto-load on reboot.""" if not os.path.exists('/etc/rc.modules'): open('/etc/rc.modules', 'a') os.chmod('/etc/rc.modules', 111) with open('/etc/rc.modules', 'r+') as modules: if module not in modules.read(): modules.write('modprobe %s\n' % module)
[ "def", "persistent_modprobe", "(", "module", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "'/etc/rc.modules'", ")", ":", "open", "(", "'/etc/rc.modules'", ",", "'a'", ")", "os", ".", "chmod", "(", "'/etc/rc.modules'", ",", "111", ")", "w...
Load a kernel module and configure for auto-load on reboot.
[ "Load", "a", "kernel", "module", "and", "configure", "for", "auto", "-", "load", "on", "reboot", "." ]
python
train
idlesign/uwsgiconf
uwsgiconf/utils.py
https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/utils.py#L316-L331
def cmd_reload(self, force=False, workers_only=False, workers_chain=False): """Reloads uWSGI master process, workers. :param bool force: Use forced (brutal) reload instead of a graceful one. :param bool workers_only: Reload only workers. :param bool workers_chain: Run chained workers reload (one after another, instead of destroying all of them in bulk). """ if workers_chain: return self.send_command(b'c') if workers_only: return self.send_command(b'R' if force else b'r') return self.send_command(b'R' if force else b'r')
[ "def", "cmd_reload", "(", "self", ",", "force", "=", "False", ",", "workers_only", "=", "False", ",", "workers_chain", "=", "False", ")", ":", "if", "workers_chain", ":", "return", "self", ".", "send_command", "(", "b'c'", ")", "if", "workers_only", ":", ...
Reloads uWSGI master process, workers. :param bool force: Use forced (brutal) reload instead of a graceful one. :param bool workers_only: Reload only workers. :param bool workers_chain: Run chained workers reload (one after another, instead of destroying all of them in bulk).
[ "Reloads", "uWSGI", "master", "process", "workers", "." ]
python
train
quantumlib/Cirq
cirq/linalg/operator_spaces.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/operator_spaces.py#L52-L66
def expand_matrix_in_orthogonal_basis( m: np.ndarray, basis: Dict[str, np.ndarray], ) -> value.LinearDict[str]: """Computes coefficients of expansion of m in basis. We require that basis be orthogonal w.r.t. the Hilbert-Schmidt inner product. We do not require that basis be orthonormal. Note that Pauli basis (I, X, Y, Z) is orthogonal, but not orthonormal. """ return value.LinearDict({ name: (hilbert_schmidt_inner_product(b, m) / hilbert_schmidt_inner_product(b, b)) for name, b in basis.items() })
[ "def", "expand_matrix_in_orthogonal_basis", "(", "m", ":", "np", ".", "ndarray", ",", "basis", ":", "Dict", "[", "str", ",", "np", ".", "ndarray", "]", ",", ")", "->", "value", ".", "LinearDict", "[", "str", "]", ":", "return", "value", ".", "LinearDic...
Computes coefficients of expansion of m in basis. We require that basis be orthogonal w.r.t. the Hilbert-Schmidt inner product. We do not require that basis be orthonormal. Note that Pauli basis (I, X, Y, Z) is orthogonal, but not orthonormal.
[ "Computes", "coefficients", "of", "expansion", "of", "m", "in", "basis", "." ]
python
train
signetlabdei/sem
sem/cli.py
https://github.com/signetlabdei/sem/blob/5077dd7a6d15644a18790bb6fde320e905f0fef0/sem/cli.py#L286-L335
def merge(move, output_dir, sources): """ Merge multiple results folder into one, by copying the results over to a new folder. For a faster operation (which on the other hand destroys the campaign data if interrupted), the move option can be used to directly move results to the new folder. """ # Get paths for all campaign JSONS jsons = [] for s in sources: filename = "%s.json" % os.path.split(s)[1] jsons += [os.path.join(s, filename)] # Check that the configuration for all campaigns is the same reference_config = TinyDB(jsons[0]).table('config') for j in jsons[1:]: for i, j in zip(reference_config.all(), TinyDB(j).table('config').all()): assert i == j # Create folders for new results directory filename = "%s.json" % os.path.split(output_dir)[1] output_json = os.path.join(output_dir, filename) output_data = os.path.join(output_dir, 'data') os.makedirs(output_data) # Create new database db = TinyDB(output_json) db.table('config').insert_multiple(reference_config.all()) # Import results from all databases to the new JSON file for s in sources: filename = "%s.json" % os.path.split(s)[1] current_db = TinyDB(os.path.join(s, filename)) db.table('results').insert_multiple(current_db.table('results').all()) # Copy or move results to new data folder for s in sources: for r in glob.glob(os.path.join(s, 'data/*')): basename = os.path.basename(r) if move: shutil.move(r, os.path.join(output_data, basename)) else: shutil.copytree(r, os.path.join(output_data, basename)) if move: for s in sources: shutil.rmtree(os.path.join(s, 'data/*')) shutil.rmtree(os.path.join(s, "%s.json" % os.path.split(s)[1])) shutil.rmtree(s)
[ "def", "merge", "(", "move", ",", "output_dir", ",", "sources", ")", ":", "# Get paths for all campaign JSONS", "jsons", "=", "[", "]", "for", "s", "in", "sources", ":", "filename", "=", "\"%s.json\"", "%", "os", ".", "path", ".", "split", "(", "s", ")",...
Merge multiple results folder into one, by copying the results over to a new folder. For a faster operation (which on the other hand destroys the campaign data if interrupted), the move option can be used to directly move results to the new folder.
[ "Merge", "multiple", "results", "folder", "into", "one", "by", "copying", "the", "results", "over", "to", "a", "new", "folder", "." ]
python
train
automl/HpBandSter
hpbandster/core/master.py
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/master.py#L248-L269
def job_callback(self, job): """ method to be called when a job has finished this will do some book keeping and call the user defined new_result_callback if one was specified """ self.logger.debug('job_callback for %s started'%str(job.id)) with self.thread_cond: self.logger.debug('job_callback for %s got condition'%str(job.id)) self.num_running_jobs -= 1 if not self.result_logger is None: self.result_logger(job) self.iterations[job.id[0]].register_result(job) self.config_generator.new_result(job) if self.num_running_jobs <= self.job_queue_sizes[0]: self.logger.debug("HBMASTER: Trying to run another job!") self.thread_cond.notify() self.logger.debug('job_callback for %s finished'%str(job.id))
[ "def", "job_callback", "(", "self", ",", "job", ")", ":", "self", ".", "logger", ".", "debug", "(", "'job_callback for %s started'", "%", "str", "(", "job", ".", "id", ")", ")", "with", "self", ".", "thread_cond", ":", "self", ".", "logger", ".", "debu...
method to be called when a job has finished this will do some book keeping and call the user defined new_result_callback if one was specified
[ "method", "to", "be", "called", "when", "a", "job", "has", "finished" ]
python
train
LogicalDash/LiSE
ELiDE/ELiDE/card.py
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/card.py#L462-L471
def scroll_deck_y(self, decknum, scroll_y): """Move a deck up or down.""" if decknum >= len(self.decks): raise IndexError("I have no deck at {}".format(decknum)) if decknum >= len(self.deck_y_hint_offsets): self.deck_y_hint_offsets = list(self.deck_y_hint_offsets) + [0] * ( decknum - len(self.deck_y_hint_offsets) + 1 ) self.deck_y_hint_offsets[decknum] += scroll_y self._trigger_layout()
[ "def", "scroll_deck_y", "(", "self", ",", "decknum", ",", "scroll_y", ")", ":", "if", "decknum", ">=", "len", "(", "self", ".", "decks", ")", ":", "raise", "IndexError", "(", "\"I have no deck at {}\"", ".", "format", "(", "decknum", ")", ")", "if", "dec...
Move a deck up or down.
[ "Move", "a", "deck", "up", "or", "down", "." ]
python
train
sosreport/sos
sos/plugins/__init__.py
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1135-L1152
def add_udev_info(self, device, attrs=False): """Collect udevadm info output for a given device :param device: A string or list of strings of device names or sysfs paths. E.G. either '/sys/class/scsi_host/host0' or '/dev/sda' is valid. :param attrs: If True, run udevadm with the --attribute-walk option. """ udev_cmd = 'udevadm info' if attrs: udev_cmd += ' -a' if isinstance(device, six.string_types): device = [device] for dev in device: self._log_debug("collecting udev info for: %s" % dev) self._add_cmd_output('%s %s' % (udev_cmd, dev))
[ "def", "add_udev_info", "(", "self", ",", "device", ",", "attrs", "=", "False", ")", ":", "udev_cmd", "=", "'udevadm info'", "if", "attrs", ":", "udev_cmd", "+=", "' -a'", "if", "isinstance", "(", "device", ",", "six", ".", "string_types", ")", ":", "dev...
Collect udevadm info output for a given device :param device: A string or list of strings of device names or sysfs paths. E.G. either '/sys/class/scsi_host/host0' or '/dev/sda' is valid. :param attrs: If True, run udevadm with the --attribute-walk option.
[ "Collect", "udevadm", "info", "output", "for", "a", "given", "device" ]
python
train
googledatalab/pydatalab
google/datalab/utils/facets/base_generic_feature_statistics_generator.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_generic_feature_statistics_generator.py#L288-L305
def _PopulateQuantilesHistogram(self, hist, nums): """Fills in the histogram with quantile information from the provided array. Args: hist: A Histogram proto message to fill in. nums: A list of numbers to create a quantiles histogram from. """ if not nums: return num_quantile_buckets = 10 quantiles_to_get = [ x * 100 / num_quantile_buckets for x in range(num_quantile_buckets + 1) ] quantiles = np.percentile(nums, quantiles_to_get) hist.type = self.histogram_proto.QUANTILES quantiles_sample_count = float(len(nums)) / num_quantile_buckets for low, high in zip(quantiles, quantiles[1:]): hist.buckets.add( low_value=low, high_value=high, sample_count=quantiles_sample_count)
[ "def", "_PopulateQuantilesHistogram", "(", "self", ",", "hist", ",", "nums", ")", ":", "if", "not", "nums", ":", "return", "num_quantile_buckets", "=", "10", "quantiles_to_get", "=", "[", "x", "*", "100", "/", "num_quantile_buckets", "for", "x", "in", "range...
Fills in the histogram with quantile information from the provided array. Args: hist: A Histogram proto message to fill in. nums: A list of numbers to create a quantiles histogram from.
[ "Fills", "in", "the", "histogram", "with", "quantile", "information", "from", "the", "provided", "array", ".", "Args", ":", "hist", ":", "A", "Histogram", "proto", "message", "to", "fill", "in", ".", "nums", ":", "A", "list", "of", "numbers", "to", "crea...
python
train
nugget/python-insteonplm
insteonplm/plm.py
https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L139-L153
def connection_lost(self, exc): """Reestablish the connection to the transport. Called when asyncio.Protocol loses the network connection. """ if exc is None: _LOGGER.warning('End of file received from Insteon Modem') else: _LOGGER.warning('Lost connection to Insteon Modem: %s', exc) self.transport = None asyncio.ensure_future(self.pause_writing(), loop=self.loop) if self._connection_lost_callback: self._connection_lost_callback()
[ "def", "connection_lost", "(", "self", ",", "exc", ")", ":", "if", "exc", "is", "None", ":", "_LOGGER", ".", "warning", "(", "'End of file received from Insteon Modem'", ")", "else", ":", "_LOGGER", ".", "warning", "(", "'Lost connection to Insteon Modem: %s'", ",...
Reestablish the connection to the transport. Called when asyncio.Protocol loses the network connection.
[ "Reestablish", "the", "connection", "to", "the", "transport", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/trax/rlax/ppo.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/rlax/ppo.py#L649-L695
def ppo_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, predicted_values, padded_actions, padded_rewards, reward_mask, gamma=0.99, lambda_=0.95, epsilon=0.2): """PPO objective, with an eventual minus sign, given predictions.""" B, T = padded_rewards.shape # pylint: disable=invalid-name assert (B, T) == padded_actions.shape assert (B, T) == reward_mask.shape _, _, A = log_probab_actions_old.shape # pylint: disable=invalid-name assert (B, T + 1, 1) == predicted_values.shape assert (B, T + 1, A) == log_probab_actions_old.shape assert (B, T + 1, A) == log_probab_actions_new.shape # (B, T) td_deltas = deltas( np.squeeze(predicted_values, axis=2), # (B, T+1) padded_rewards, reward_mask, gamma=gamma) # (B, T) advantages = gae_advantages( td_deltas, reward_mask, lambda_=lambda_, gamma=gamma) # (B, T) ratios = compute_probab_ratios(log_probab_actions_new, log_probab_actions_old, padded_actions, reward_mask) assert (B, T) == ratios.shape # (B, T) objective = clipped_objective( ratios, advantages, reward_mask, epsilon=epsilon) assert (B, T) == objective.shape # () average_objective = np.sum(objective) / np.sum(reward_mask) # Loss is negative objective. return -average_objective
[ "def", "ppo_loss_given_predictions", "(", "log_probab_actions_new", ",", "log_probab_actions_old", ",", "predicted_values", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ",", "lambda_", "=", "0.95", ",", "epsilon", "=", ...
PPO objective, with an eventual minus sign, given predictions.
[ "PPO", "objective", "with", "an", "eventual", "minus", "sign", "given", "predictions", "." ]
python
train
westonplatter/fast_arrow
fast_arrow/resources/stock_marketdata.py
https://github.com/westonplatter/fast_arrow/blob/514cbca4994f52a97222058167830a302e313d04/fast_arrow/resources/stock_marketdata.py#L22-L34
def quotes_by_instrument_urls(cls, client, urls): """ fetch and return results """ instruments = ",".join(urls) params = {"instruments": instruments} url = "https://api.robinhood.com/marketdata/quotes/" data = client.get(url, params=params) results = data["results"] while "next" in data and data["next"]: data = client.get(data["next"]) results.extend(data["results"]) return results
[ "def", "quotes_by_instrument_urls", "(", "cls", ",", "client", ",", "urls", ")", ":", "instruments", "=", "\",\"", ".", "join", "(", "urls", ")", "params", "=", "{", "\"instruments\"", ":", "instruments", "}", "url", "=", "\"https://api.robinhood.com/marketdata/...
fetch and return results
[ "fetch", "and", "return", "results" ]
python
train
ArchiveTeam/wpull
wpull/url.py
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/url.py#L700-L740
def flatten_path(path, flatten_slashes=False): '''Flatten an absolute URL path by removing the dot segments. :func:`urllib.parse.urljoin` has some support for removing dot segments, but it is conservative and only removes them as needed. Arguments: path (str): The URL path. flatten_slashes (bool): If True, consecutive slashes are removed. The path returned will always have a leading slash. ''' # Based on posixpath.normpath # Fast path if not path or path == '/': return '/' # Take off leading slash if path[0] == '/': path = path[1:] parts = path.split('/') new_parts = collections.deque() for part in parts: if part == '.' or (flatten_slashes and not part): continue elif part != '..': new_parts.append(part) elif new_parts: new_parts.pop() # If the filename is empty string if flatten_slashes and path.endswith('/') or not len(new_parts): new_parts.append('') # Put back leading slash new_parts.appendleft('') return '/'.join(new_parts)
[ "def", "flatten_path", "(", "path", ",", "flatten_slashes", "=", "False", ")", ":", "# Based on posixpath.normpath", "# Fast path", "if", "not", "path", "or", "path", "==", "'/'", ":", "return", "'/'", "# Take off leading slash", "if", "path", "[", "0", "]", "...
Flatten an absolute URL path by removing the dot segments. :func:`urllib.parse.urljoin` has some support for removing dot segments, but it is conservative and only removes them as needed. Arguments: path (str): The URL path. flatten_slashes (bool): If True, consecutive slashes are removed. The path returned will always have a leading slash.
[ "Flatten", "an", "absolute", "URL", "path", "by", "removing", "the", "dot", "segments", "." ]
python
train
pyca/pyopenssl
src/OpenSSL/_util.py
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/src/OpenSSL/_util.py#L127-L147
def text_to_bytes_and_warn(label, obj): """ If ``obj`` is text, emit a warning that it should be bytes instead and try to convert it to bytes automatically. :param str label: The name of the parameter from which ``obj`` was taken (so a developer can easily find the source of the problem and correct it). :return: If ``obj`` is the text string type, a ``bytes`` object giving the UTF-8 encoding of that text is returned. Otherwise, ``obj`` itself is returned. """ if isinstance(obj, text_type): warnings.warn( _TEXT_WARNING.format(label), category=DeprecationWarning, stacklevel=3 ) return obj.encode('utf-8') return obj
[ "def", "text_to_bytes_and_warn", "(", "label", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "text_type", ")", ":", "warnings", ".", "warn", "(", "_TEXT_WARNING", ".", "format", "(", "label", ")", ",", "category", "=", "DeprecationWarning", ",...
If ``obj`` is text, emit a warning that it should be bytes instead and try to convert it to bytes automatically. :param str label: The name of the parameter from which ``obj`` was taken (so a developer can easily find the source of the problem and correct it). :return: If ``obj`` is the text string type, a ``bytes`` object giving the UTF-8 encoding of that text is returned. Otherwise, ``obj`` itself is returned.
[ "If", "obj", "is", "text", "emit", "a", "warning", "that", "it", "should", "be", "bytes", "instead", "and", "try", "to", "convert", "it", "to", "bytes", "automatically", "." ]
python
test
log2timeline/plaso
plaso/parsers/winreg_plugins/mrulistex.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/winreg_plugins/mrulistex.py#L40-L59
def Match(self, registry_key): """Determines if a Windows Registry key matches the filter. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. Returns: bool: True if the Windows Registry key matches the filter. """ key_path_upper = registry_key.path.upper() # Prevent this filter matching non-string MRUListEx values. for ignore_key_path_suffix in self._IGNORE_KEY_PATH_SUFFIXES: if key_path_upper.endswith(ignore_key_path_suffix): return False for ignore_key_path_segment in self._IGNORE_KEY_PATH_SEGMENTS: if ignore_key_path_segment in key_path_upper: return False return super(MRUListExStringRegistryKeyFilter, self).Match(registry_key)
[ "def", "Match", "(", "self", ",", "registry_key", ")", ":", "key_path_upper", "=", "registry_key", ".", "path", ".", "upper", "(", ")", "# Prevent this filter matching non-string MRUListEx values.", "for", "ignore_key_path_suffix", "in", "self", ".", "_IGNORE_KEY_PATH_S...
Determines if a Windows Registry key matches the filter. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. Returns: bool: True if the Windows Registry key matches the filter.
[ "Determines", "if", "a", "Windows", "Registry", "key", "matches", "the", "filter", "." ]
python
train
swharden/SWHLab
swhlab/command.py
https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/command.py#L23-L64
def processArgs(): """check out the arguments and figure out what to do.""" if len(sys.argv)<2: print("\n\nERROR:") print("this script requires arguments!") print('try "python command.py info"') return if sys.argv[1]=='info': print("import paths:\n ","\n ".join(sys.path)) print() print("python version:",sys.version) print("SWHLab path:",__file__) print("SWHLab version:",swhlab.__version__) return if sys.argv[1]=='glanceFolder': abfFolder=swhlab.common.gui_getFolder() if not abfFolder or not os.path.isdir(abfFolder): print("bad path") return fnames=sorted(glob.glob(abfFolder+"/*.abf")) outFolder=tempfile.gettempdir()+"/swhlab/" if os.path.exists(outFolder): shutil.rmtree(outFolder) os.mkdir(outFolder) outFile=outFolder+"/index.html" out='<html><body>' out+='<h2>%s</h2>'%abfFolder for i,fname in enumerate(fnames): print("\n\n### PROCESSING %d of %d"%(i,len(fnames))) saveAs=os.path.join(os.path.dirname(outFolder),os.path.basename(fname))+".png" out+='<br><br><br><code>%s</code><br>'%os.path.abspath(fname) out+='<a href="%s"><img src="%s"></a><br>'%(saveAs,saveAs) swhlab.analysis.glance.processAbf(fname,saveAs) out+='</body></html>' with open(outFile,'w') as f: f.write(out) webbrowser.open_new_tab(outFile) return print("\n\nERROR:\nI'm not sure how to process these arguments!") print(sys.argv)
[ "def", "processArgs", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "<", "2", ":", "print", "(", "\"\\n\\nERROR:\"", ")", "print", "(", "\"this script requires arguments!\"", ")", "print", "(", "'try \"python command.py info\"'", ")", "return", "if...
check out the arguments and figure out what to do.
[ "check", "out", "the", "arguments", "and", "figure", "out", "what", "to", "do", "." ]
python
valid
xsleonard/pystmark
pystmark.py
https://github.com/xsleonard/pystmark/blob/329ccae1a7c8d57f28fa72cd8dbbee3e39413ed6/pystmark.py#L123-L138
def send_batch(messages, api_key=None, secure=None, test=None, **request_args): '''Send a batch of messages. :param messages: Messages to send. :type message: A list of `dict` or :class:`Message` :param api_key: Your Postmark API key. Required, if `test` is not `True`. :param secure: Use the https scheme for the Postmark API. Defaults to `True` :param test: Use the Postmark Test API. Defaults to `False`. :param \*\*request_args: Keyword arguments to pass to :func:`requests.request`. :rtype: :class:`BatchSendResponse` ''' return _default_pyst_batch_sender.send(messages=messages, api_key=api_key, secure=secure, test=test, **request_args)
[ "def", "send_batch", "(", "messages", ",", "api_key", "=", "None", ",", "secure", "=", "None", ",", "test", "=", "None", ",", "*", "*", "request_args", ")", ":", "return", "_default_pyst_batch_sender", ".", "send", "(", "messages", "=", "messages", ",", ...
Send a batch of messages. :param messages: Messages to send. :type message: A list of `dict` or :class:`Message` :param api_key: Your Postmark API key. Required, if `test` is not `True`. :param secure: Use the https scheme for the Postmark API. Defaults to `True` :param test: Use the Postmark Test API. Defaults to `False`. :param \*\*request_args: Keyword arguments to pass to :func:`requests.request`. :rtype: :class:`BatchSendResponse`
[ "Send", "a", "batch", "of", "messages", "." ]
python
train
wavycloud/pyboto3
pyboto3/ec2.py
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/ec2.py#L14547-L15213
def run_instances(DryRun=None, ImageId=None, MinCount=None, MaxCount=None, KeyName=None, SecurityGroups=None, SecurityGroupIds=None, UserData=None, InstanceType=None, Placement=None, KernelId=None, RamdiskId=None, BlockDeviceMappings=None, Monitoring=None, SubnetId=None, DisableApiTermination=None, InstanceInitiatedShutdownBehavior=None, PrivateIpAddress=None, Ipv6Addresses=None, Ipv6AddressCount=None, ClientToken=None, AdditionalInfo=None, NetworkInterfaces=None, IamInstanceProfile=None, EbsOptimized=None, TagSpecifications=None): """ Launches the specified number of instances using an AMI for which you have permissions. You can specify a number of options, or leave the default options. The following rules apply: To ensure faster instance launches, break up large requests into smaller batches. For example, create 5 separate launch requests for 100 instances each instead of 1 launch request for 500 instances. An instance is ready for you to use when it's in the running state. You can check the state of your instance using DescribeInstances . You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and Tagging Your Amazon EC2 Resources . Linux instances have access to the public key of the key pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure access without passwords. For more information, see Key Pairs in the Amazon Elastic Compute Cloud User Guide . For troubleshooting, see What To Do If An Instance Immediately Terminates , and Troubleshooting Connecting to Your Instance in the Amazon Elastic Compute Cloud User Guide . See also: AWS API Documentation :example: response = client.run_instances( DryRun=True|False, ImageId='string', MinCount=123, MaxCount=123, KeyName='string', SecurityGroups=[ 'string', ], SecurityGroupIds=[ 'string', ], UserData='string', InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'f1.2xlarge'|'f1.16xlarge', Placement={ 'AvailabilityZone': 'string', 'GroupName': 'string', 'Tenancy': 'default'|'dedicated'|'host', 'HostId': 'string', 'Affinity': 'string' }, KernelId='string', RamdiskId='string', BlockDeviceMappings=[ { 'VirtualName': 'string', 'DeviceName': 'string', 'Ebs': { 'SnapshotId': 'string', 'VolumeSize': 123, 'DeleteOnTermination': True|False, 'VolumeType': 'standard'|'io1'|'gp2'|'sc1'|'st1', 'Iops': 123, 'Encrypted': True|False }, 'NoDevice': 'string' }, ], Monitoring={ 'Enabled': True|False }, SubnetId='string', DisableApiTermination=True|False, InstanceInitiatedShutdownBehavior='stop'|'terminate', PrivateIpAddress='string', Ipv6Addresses=[ { 'Ipv6Address': 'string' }, ], Ipv6AddressCount=123, ClientToken='string', AdditionalInfo='string', NetworkInterfaces=[ { 'NetworkInterfaceId': 'string', 'DeviceIndex': 123, 'SubnetId': 'string', 'Description': 'string', 'PrivateIpAddress': 'string', 'Groups': [ 'string', ], 'DeleteOnTermination': True|False, 'PrivateIpAddresses': [ { 'PrivateIpAddress': 'string', 'Primary': True|False }, ], 'SecondaryPrivateIpAddressCount': 123, 'AssociatePublicIpAddress': True|False, 'Ipv6Addresses': [ { 'Ipv6Address': 'string' }, ], 'Ipv6AddressCount': 123 }, ], IamInstanceProfile={ 'Arn': 'string', 'Name': 'string' }, EbsOptimized=True|False, TagSpecifications=[ { 'ResourceType': 'customer-gateway'|'dhcp-options'|'image'|'instance'|'internet-gateway'|'network-acl'|'network-interface'|'reserved-instances'|'route-table'|'snapshot'|'spot-instances-request'|'subnet'|'security-group'|'volume'|'vpc'|'vpn-connection'|'vpn-gateway', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ] ) :type DryRun: boolean :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . :type ImageId: string :param ImageId: [REQUIRED] The ID of the AMI, which you can get by calling DescribeImages . :type MinCount: integer :param MinCount: [REQUIRED] The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see How many instances can I run in Amazon EC2 in the Amazon EC2 General FAQ. :type MaxCount: integer :param MaxCount: [REQUIRED] The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see How many instances can I run in Amazon EC2 in the Amazon EC2 FAQ. :type KeyName: string :param KeyName: The name of the key pair. You can create a key pair using CreateKeyPair or ImportKeyPair . Warning If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. :type SecurityGroups: list :param SecurityGroups: [EC2-Classic, default VPC] One or more security group names. For a nondefault VPC, you must use security group IDs instead. Default: Amazon EC2 uses the default security group. (string) -- :type SecurityGroupIds: list :param SecurityGroupIds: One or more security group IDs. You can create a security group using CreateSecurityGroup . Default: Amazon EC2 uses the default security group. (string) -- :type UserData: string :param UserData: The user data to make available to the instance. For more information, see Running Commands on Your Linux Instance at Launch (Linux) and Adding User Data (Windows). If you are using an AWS SDK or command line tool, Base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide Base64-encoded text. This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation. :type InstanceType: string :param InstanceType: The instance type. For more information, see Instance Types in the Amazon Elastic Compute Cloud User Guide . Default: m1.small :type Placement: dict :param Placement: The placement for the instance. AvailabilityZone (string) --The Availability Zone of the instance. GroupName (string) --The name of the placement group the instance is in (for cluster compute instances). Tenancy (string) --The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the ImportInstance command. HostId (string) --The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the ImportInstance command. Affinity (string) --The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the ImportInstance command. :type KernelId: string :param KernelId: The ID of the kernel. Warning We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see PV-GRUB in the Amazon Elastic Compute Cloud User Guide . :type RamdiskId: string :param RamdiskId: The ID of the RAM disk. Warning We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see PV-GRUB in the Amazon Elastic Compute Cloud User Guide . :type BlockDeviceMappings: list :param BlockDeviceMappings: The block device mapping. Warning Supplying both a snapshot ID and an encryption value as arguments for block-device mapping results in an error. This is because only blank volumes can be encrypted on start, and these are not created from a snapshot. If a snapshot is the basis for the volume, it contains data by definition and its encryption status cannot be changed using this action. (dict) --Describes a block device mapping. VirtualName (string) --The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 .The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. DeviceName (string) --The device name exposed to the instance (for example, /dev/sdh or xvdh ). Ebs (dict) --Parameters used to automatically set up EBS volumes when the instance is launched. SnapshotId (string) --The ID of the snapshot. VolumeSize (integer) --The size of the volume, in GiB. Constraints: 1-16384 for General Purpose SSD (gp2 ), 4-16384 for Provisioned IOPS SSD (io1 ), 500-16384 for Throughput Optimized HDD (st1 ), 500-16384 for Cold HDD (sc1 ), and 1-1024 for Magnetic (standard ) volumes. If you specify a snapshot, the volume size must be equal to or larger than the snapshot size. Default: If you're creating the volume from a snapshot and don't specify a volume size, the default is the snapshot size. DeleteOnTermination (boolean) --Indicates whether the EBS volume is deleted on instance termination. VolumeType (string) --The volume type: gp2 , io1 , st1 , sc1 , or standard . Default: standard Iops (integer) --The number of I/O operations per second (IOPS) that the volume supports. For io1 , this represents the number of IOPS that are provisioned for the volume. For gp2 , this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. For more information about General Purpose SSD baseline performance, I/O credits, and bursting, see Amazon EBS Volume Types in the Amazon Elastic Compute Cloud User Guide . Constraint: Range is 100-20000 IOPS for io1 volumes and 100-10000 IOPS for gp2 volumes. Condition: This parameter is required for requests to create io1 volumes; it is not used in requests to create gp2 , st1 , sc1 , or standard volumes. Encrypted (boolean) --Indicates whether the EBS volume is encrypted. Encrypted Amazon EBS volumes may only be attached to instances that support Amazon EBS encryption. NoDevice (string) --Suppresses the specified device included in the block device mapping of the AMI. :type Monitoring: dict :param Monitoring: The monitoring for the instance. Enabled (boolean) -- [REQUIRED]Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. :type SubnetId: string :param SubnetId: [EC2-VPC] The ID of the subnet to launch the instance into. :type DisableApiTermination: boolean :param DisableApiTermination: If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute to false after launch, use ModifyInstanceAttribute . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. Default: false :type InstanceInitiatedShutdownBehavior: string :param InstanceInitiatedShutdownBehavior: Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). Default: stop :type PrivateIpAddress: string :param PrivateIpAddress: [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. :type Ipv6Addresses: list :param Ipv6Addresses: [EC2-VPC] Specify one or more IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. (dict) --Describes an IPv6 address. Ipv6Address (string) --The IPv6 address. :type Ipv6AddressCount: integer :param Ipv6AddressCount: [EC2-VPC] A number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. :type ClientToken: string :param ClientToken: Unique, case-sensitive identifier you provide to ensure the idempotency of the request. For more information, see Ensuring Idempotency . Constraints: Maximum 64 ASCII characters :type AdditionalInfo: string :param AdditionalInfo: Reserved. :type NetworkInterfaces: list :param NetworkInterfaces: One or more network interfaces. (dict) --Describes a network interface. NetworkInterfaceId (string) --The ID of the network interface. DeviceIndex (integer) --The index of the device on the instance for the network interface attachment. If you are specifying a network interface in a RunInstances request, you must provide the device index. SubnetId (string) --The ID of the subnet associated with the network string. Applies only if creating a network interface when launching an instance. Description (string) --The description of the network interface. Applies only if creating a network interface when launching an instance. PrivateIpAddress (string) --The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a RunInstances request. Groups (list) --The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. (string) -- DeleteOnTermination (boolean) --If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. PrivateIpAddresses (list) --One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a RunInstances request. (dict) --Describes a secondary private IPv4 address for a network interface. PrivateIpAddress (string) -- [REQUIRED]The private IPv4 addresses. Primary (boolean) --Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. SecondaryPrivateIpAddressCount (integer) --The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a RunInstances request. AssociatePublicIpAddress (boolean) --Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . Ipv6Addresses (list) --One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. (dict) --Describes an IPv6 address. Ipv6Address (string) --The IPv6 address. Ipv6AddressCount (integer) --A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. :type IamInstanceProfile: dict :param IamInstanceProfile: The IAM instance profile. Arn (string) --The Amazon Resource Name (ARN) of the instance profile. Name (string) --The name of the instance profile. :type EbsOptimized: boolean :param EbsOptimized: Indicates whether the instance is optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. Default: false :type TagSpecifications: list :param TagSpecifications: The tags to apply to the resources during launch. You can tag instances and volumes. The specified tags are applied to all instances or volumes that are created during launch. (dict) --The tags to apply to a resource when the resource is being created. ResourceType (string) --The type of resource to tag. Currently, the resource types that support tagging on creation are instance and volume . Tags (list) --The tags to apply to the resource. (dict) --Describes a tag. Key (string) --The key of the tag. Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: Value (string) --The value of the tag. Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. :rtype: dict :return: { 'ReservationId': 'string', 'OwnerId': 'string', 'RequesterId': 'string', 'Groups': [ { 'GroupName': 'string', 'GroupId': 'string' }, ], 'Instances': [ { 'InstanceId': 'string', 'ImageId': 'string', 'State': { 'Code': 123, 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' }, 'PrivateDnsName': 'string', 'PublicDnsName': 'string', 'StateTransitionReason': 'string', 'KeyName': 'string', 'AmiLaunchIndex': 123, 'ProductCodes': [ { 'ProductCodeId': 'string', 'ProductCodeType': 'devpay'|'marketplace' }, ], 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'f1.2xlarge'|'f1.16xlarge', 'LaunchTime': datetime(2015, 1, 1), 'Placement': { 'AvailabilityZone': 'string', 'GroupName': 'string', 'Tenancy': 'default'|'dedicated'|'host', 'HostId': 'string', 'Affinity': 'string' }, 'KernelId': 'string', 'RamdiskId': 'string', 'Platform': 'Windows', 'Monitoring': { 'State': 'disabled'|'disabling'|'enabled'|'pending' }, 'SubnetId': 'string', 'VpcId': 'string', 'PrivateIpAddress': 'string', 'PublicIpAddress': 'string', 'StateReason': { 'Code': 'string', 'Message': 'string' }, 'Architecture': 'i386'|'x86_64', 'RootDeviceType': 'ebs'|'instance-store', 'RootDeviceName': 'string', 'BlockDeviceMappings': [ { 'DeviceName': 'string', 'Ebs': { 'VolumeId': 'string', 'Status': 'attaching'|'attached'|'detaching'|'detached', 'AttachTime': datetime(2015, 1, 1), 'DeleteOnTermination': True|False } }, ], 'VirtualizationType': 'hvm'|'paravirtual', 'InstanceLifecycle': 'spot'|'scheduled', 'SpotInstanceRequestId': 'string', 'ClientToken': 'string', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ], 'SecurityGroups': [ { 'GroupName': 'string', 'GroupId': 'string' }, ], 'SourceDestCheck': True|False, 'Hypervisor': 'ovm'|'xen', 'NetworkInterfaces': [ { 'NetworkInterfaceId': 'string', 'SubnetId': 'string', 'VpcId': 'string', 'Description': 'string', 'OwnerId': 'string', 'Status': 'available'|'attaching'|'in-use'|'detaching', 'MacAddress': 'string', 'PrivateIpAddress': 'string', 'PrivateDnsName': 'string', 'SourceDestCheck': True|False, 'Groups': [ { 'GroupName': 'string', 'GroupId': 'string' }, ], 'Attachment': { 'AttachmentId': 'string', 'DeviceIndex': 123, 'Status': 'attaching'|'attached'|'detaching'|'detached', 'AttachTime': datetime(2015, 1, 1), 'DeleteOnTermination': True|False }, 'Association': { 'PublicIp': 'string', 'PublicDnsName': 'string', 'IpOwnerId': 'string' }, 'PrivateIpAddresses': [ { 'PrivateIpAddress': 'string', 'PrivateDnsName': 'string', 'Primary': True|False, 'Association': { 'PublicIp': 'string', 'PublicDnsName': 'string', 'IpOwnerId': 'string' } }, ], 'Ipv6Addresses': [ { 'Ipv6Address': 'string' }, ] }, ], 'IamInstanceProfile': { 'Arn': 'string', 'Id': 'string' }, 'EbsOptimized': True|False, 'SriovNetSupport': 'string', 'EnaSupport': True|False }, ] } :returns: DryRun (boolean) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . ImageId (string) -- [REQUIRED] The ID of the AMI, which you can get by calling DescribeImages . MinCount (integer) -- [REQUIRED] The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see How many instances can I run in Amazon EC2 in the Amazon EC2 General FAQ. MaxCount (integer) -- [REQUIRED] The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see How many instances can I run in Amazon EC2 in the Amazon EC2 FAQ. KeyName (string) -- The name of the key pair. You can create a key pair using CreateKeyPair or ImportKeyPair . Warning If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. SecurityGroups (list) -- [EC2-Classic, default VPC] One or more security group names. For a nondefault VPC, you must use security group IDs instead. Default: Amazon EC2 uses the default security group. (string) -- SecurityGroupIds (list) -- One or more security group IDs. You can create a security group using CreateSecurityGroup . Default: Amazon EC2 uses the default security group. (string) -- UserData (string) -- The user data to make available to the instance. For more information, see Running Commands on Your Linux Instance at Launch (Linux) and Adding User Data (Windows). If you are using an AWS SDK or command line tool, Base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide Base64-encoded text. This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation. InstanceType (string) -- The instance type. For more information, see Instance Types in the Amazon Elastic Compute Cloud User Guide . Default: m1.small Placement (dict) -- The placement for the instance. AvailabilityZone (string) --The Availability Zone of the instance. GroupName (string) --The name of the placement group the instance is in (for cluster compute instances). Tenancy (string) --The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the ImportInstance command. HostId (string) --The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the ImportInstance command. Affinity (string) --The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the ImportInstance command. KernelId (string) -- The ID of the kernel. Warning We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see PV-GRUB in the Amazon Elastic Compute Cloud User Guide . RamdiskId (string) -- The ID of the RAM disk. Warning We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see PV-GRUB in the Amazon Elastic Compute Cloud User Guide . BlockDeviceMappings (list) -- The block device mapping. Warning Supplying both a snapshot ID and an encryption value as arguments for block-device mapping results in an error. This is because only blank volumes can be encrypted on start, and these are not created from a snapshot. If a snapshot is the basis for the volume, it contains data by definition and its encryption status cannot be changed using this action. (dict) --Describes a block device mapping. VirtualName (string) --The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 .The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. DeviceName (string) --The device name exposed to the instance (for example, /dev/sdh or xvdh ). Ebs (dict) --Parameters used to automatically set up EBS volumes when the instance is launched. SnapshotId (string) --The ID of the snapshot. VolumeSize (integer) --The size of the volume, in GiB. Constraints: 1-16384 for General Purpose SSD (gp2 ), 4-16384 for Provisioned IOPS SSD (io1 ), 500-16384 for Throughput Optimized HDD (st1 ), 500-16384 for Cold HDD (sc1 ), and 1-1024 for Magnetic (standard ) volumes. If you specify a snapshot, the volume size must be equal to or larger than the snapshot size. Default: If you're creating the volume from a snapshot and don't specify a volume size, the default is the snapshot size. DeleteOnTermination (boolean) --Indicates whether the EBS volume is deleted on instance termination. VolumeType (string) --The volume type: gp2 , io1 , st1 , sc1 , or standard . Default: standard Iops (integer) --The number of I/O operations per second (IOPS) that the volume supports. For io1 , this represents the number of IOPS that are provisioned for the volume. For gp2 , this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. For more information about General Purpose SSD baseline performance, I/O credits, and bursting, see Amazon EBS Volume Types in the Amazon Elastic Compute Cloud User Guide . Constraint: Range is 100-20000 IOPS for io1 volumes and 100-10000 IOPS for gp2 volumes. Condition: This parameter is required for requests to create io1 volumes; it is not used in requests to create gp2 , st1 , sc1 , or standard volumes. Encrypted (boolean) --Indicates whether the EBS volume is encrypted. Encrypted Amazon EBS volumes may only be attached to instances that support Amazon EBS encryption. NoDevice (string) --Suppresses the specified device included in the block device mapping of the AMI. Monitoring (dict) -- The monitoring for the instance. Enabled (boolean) -- [REQUIRED]Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. SubnetId (string) -- [EC2-VPC] The ID of the subnet to launch the instance into. DisableApiTermination (boolean) -- If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute to false after launch, use ModifyInstanceAttribute . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. Default: false InstanceInitiatedShutdownBehavior (string) -- Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). Default: stop PrivateIpAddress (string) -- [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. Ipv6Addresses (list) -- [EC2-VPC] Specify one or more IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. (dict) --Describes an IPv6 address. Ipv6Address (string) --The IPv6 address. Ipv6AddressCount (integer) -- [EC2-VPC] A number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. ClientToken (string) -- Unique, case-sensitive identifier you provide to ensure the idempotency of the request. For more information, see Ensuring Idempotency . Constraints: Maximum 64 ASCII characters AdditionalInfo (string) -- Reserved. NetworkInterfaces (list) -- One or more network interfaces. (dict) --Describes a network interface. NetworkInterfaceId (string) --The ID of the network interface. DeviceIndex (integer) --The index of the device on the instance for the network interface attachment. If you are specifying a network interface in a RunInstances request, you must provide the device index. SubnetId (string) --The ID of the subnet associated with the network string. Applies only if creating a network interface when launching an instance. Description (string) --The description of the network interface. Applies only if creating a network interface when launching an instance. PrivateIpAddress (string) --The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a RunInstances request. Groups (list) --The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. (string) -- DeleteOnTermination (boolean) --If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. PrivateIpAddresses (list) --One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a RunInstances request. (dict) --Describes a secondary private IPv4 address for a network interface. PrivateIpAddress (string) -- [REQUIRED]The private IPv4 addresses. Primary (boolean) --Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. SecondaryPrivateIpAddressCount (integer) --The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a RunInstances request. AssociatePublicIpAddress (boolean) --Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . Ipv6Addresses (list) --One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. (dict) --Describes an IPv6 address. Ipv6Address (string) --The IPv6 address. Ipv6AddressCount (integer) --A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. IamInstanceProfile (dict) -- The IAM instance profile. Arn (string) --The Amazon Resource Name (ARN) of the instance profile. Name (string) --The name of the instance profile. EbsOptimized (boolean) -- Indicates whether the instance is optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. Default: false TagSpecifications (list) -- The tags to apply to the resources during launch. You can tag instances and volumes. The specified tags are applied to all instances or volumes that are created during launch. (dict) --The tags to apply to a resource when the resource is being created. ResourceType (string) --The type of resource to tag. Currently, the resource types that support tagging on creation are instance and volume . Tags (list) --The tags to apply to the resource. (dict) --Describes a tag. Key (string) --The key of the tag. Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: Value (string) --The value of the tag. Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. """ pass
[ "def", "run_instances", "(", "DryRun", "=", "None", ",", "ImageId", "=", "None", ",", "MinCount", "=", "None", ",", "MaxCount", "=", "None", ",", "KeyName", "=", "None", ",", "SecurityGroups", "=", "None", ",", "SecurityGroupIds", "=", "None", ",", "User...
Launches the specified number of instances using an AMI for which you have permissions. You can specify a number of options, or leave the default options. The following rules apply: To ensure faster instance launches, break up large requests into smaller batches. For example, create 5 separate launch requests for 100 instances each instead of 1 launch request for 500 instances. An instance is ready for you to use when it's in the running state. You can check the state of your instance using DescribeInstances . You can tag instances and EBS volumes during launch, after launch, or both. For more information, see CreateTags and Tagging Your Amazon EC2 Resources . Linux instances have access to the public key of the key pair at boot. You can use this key to provide secure access to the instance. Amazon EC2 public images use this feature to provide secure access without passwords. For more information, see Key Pairs in the Amazon Elastic Compute Cloud User Guide . For troubleshooting, see What To Do If An Instance Immediately Terminates , and Troubleshooting Connecting to Your Instance in the Amazon Elastic Compute Cloud User Guide . See also: AWS API Documentation :example: response = client.run_instances( DryRun=True|False, ImageId='string', MinCount=123, MaxCount=123, KeyName='string', SecurityGroups=[ 'string', ], SecurityGroupIds=[ 'string', ], UserData='string', InstanceType='t1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'f1.2xlarge'|'f1.16xlarge', Placement={ 'AvailabilityZone': 'string', 'GroupName': 'string', 'Tenancy': 'default'|'dedicated'|'host', 'HostId': 'string', 'Affinity': 'string' }, KernelId='string', RamdiskId='string', BlockDeviceMappings=[ { 'VirtualName': 'string', 'DeviceName': 'string', 'Ebs': { 'SnapshotId': 'string', 'VolumeSize': 123, 'DeleteOnTermination': True|False, 'VolumeType': 'standard'|'io1'|'gp2'|'sc1'|'st1', 'Iops': 123, 'Encrypted': True|False }, 'NoDevice': 'string' }, ], Monitoring={ 'Enabled': True|False }, SubnetId='string', DisableApiTermination=True|False, InstanceInitiatedShutdownBehavior='stop'|'terminate', PrivateIpAddress='string', Ipv6Addresses=[ { 'Ipv6Address': 'string' }, ], Ipv6AddressCount=123, ClientToken='string', AdditionalInfo='string', NetworkInterfaces=[ { 'NetworkInterfaceId': 'string', 'DeviceIndex': 123, 'SubnetId': 'string', 'Description': 'string', 'PrivateIpAddress': 'string', 'Groups': [ 'string', ], 'DeleteOnTermination': True|False, 'PrivateIpAddresses': [ { 'PrivateIpAddress': 'string', 'Primary': True|False }, ], 'SecondaryPrivateIpAddressCount': 123, 'AssociatePublicIpAddress': True|False, 'Ipv6Addresses': [ { 'Ipv6Address': 'string' }, ], 'Ipv6AddressCount': 123 }, ], IamInstanceProfile={ 'Arn': 'string', 'Name': 'string' }, EbsOptimized=True|False, TagSpecifications=[ { 'ResourceType': 'customer-gateway'|'dhcp-options'|'image'|'instance'|'internet-gateway'|'network-acl'|'network-interface'|'reserved-instances'|'route-table'|'snapshot'|'spot-instances-request'|'subnet'|'security-group'|'volume'|'vpc'|'vpn-connection'|'vpn-gateway', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ] ) :type DryRun: boolean :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . :type ImageId: string :param ImageId: [REQUIRED] The ID of the AMI, which you can get by calling DescribeImages . :type MinCount: integer :param MinCount: [REQUIRED] The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see How many instances can I run in Amazon EC2 in the Amazon EC2 General FAQ. :type MaxCount: integer :param MaxCount: [REQUIRED] The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see How many instances can I run in Amazon EC2 in the Amazon EC2 FAQ. :type KeyName: string :param KeyName: The name of the key pair. You can create a key pair using CreateKeyPair or ImportKeyPair . Warning If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. :type SecurityGroups: list :param SecurityGroups: [EC2-Classic, default VPC] One or more security group names. For a nondefault VPC, you must use security group IDs instead. Default: Amazon EC2 uses the default security group. (string) -- :type SecurityGroupIds: list :param SecurityGroupIds: One or more security group IDs. You can create a security group using CreateSecurityGroup . Default: Amazon EC2 uses the default security group. (string) -- :type UserData: string :param UserData: The user data to make available to the instance. For more information, see Running Commands on Your Linux Instance at Launch (Linux) and Adding User Data (Windows). If you are using an AWS SDK or command line tool, Base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide Base64-encoded text. This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation. :type InstanceType: string :param InstanceType: The instance type. For more information, see Instance Types in the Amazon Elastic Compute Cloud User Guide . Default: m1.small :type Placement: dict :param Placement: The placement for the instance. AvailabilityZone (string) --The Availability Zone of the instance. GroupName (string) --The name of the placement group the instance is in (for cluster compute instances). Tenancy (string) --The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the ImportInstance command. HostId (string) --The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the ImportInstance command. Affinity (string) --The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the ImportInstance command. :type KernelId: string :param KernelId: The ID of the kernel. Warning We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see PV-GRUB in the Amazon Elastic Compute Cloud User Guide . :type RamdiskId: string :param RamdiskId: The ID of the RAM disk. Warning We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see PV-GRUB in the Amazon Elastic Compute Cloud User Guide . :type BlockDeviceMappings: list :param BlockDeviceMappings: The block device mapping. Warning Supplying both a snapshot ID and an encryption value as arguments for block-device mapping results in an error. This is because only blank volumes can be encrypted on start, and these are not created from a snapshot. If a snapshot is the basis for the volume, it contains data by definition and its encryption status cannot be changed using this action. (dict) --Describes a block device mapping. VirtualName (string) --The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 .The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. DeviceName (string) --The device name exposed to the instance (for example, /dev/sdh or xvdh ). Ebs (dict) --Parameters used to automatically set up EBS volumes when the instance is launched. SnapshotId (string) --The ID of the snapshot. VolumeSize (integer) --The size of the volume, in GiB. Constraints: 1-16384 for General Purpose SSD (gp2 ), 4-16384 for Provisioned IOPS SSD (io1 ), 500-16384 for Throughput Optimized HDD (st1 ), 500-16384 for Cold HDD (sc1 ), and 1-1024 for Magnetic (standard ) volumes. If you specify a snapshot, the volume size must be equal to or larger than the snapshot size. Default: If you're creating the volume from a snapshot and don't specify a volume size, the default is the snapshot size. DeleteOnTermination (boolean) --Indicates whether the EBS volume is deleted on instance termination. VolumeType (string) --The volume type: gp2 , io1 , st1 , sc1 , or standard . Default: standard Iops (integer) --The number of I/O operations per second (IOPS) that the volume supports. For io1 , this represents the number of IOPS that are provisioned for the volume. For gp2 , this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. For more information about General Purpose SSD baseline performance, I/O credits, and bursting, see Amazon EBS Volume Types in the Amazon Elastic Compute Cloud User Guide . Constraint: Range is 100-20000 IOPS for io1 volumes and 100-10000 IOPS for gp2 volumes. Condition: This parameter is required for requests to create io1 volumes; it is not used in requests to create gp2 , st1 , sc1 , or standard volumes. Encrypted (boolean) --Indicates whether the EBS volume is encrypted. Encrypted Amazon EBS volumes may only be attached to instances that support Amazon EBS encryption. NoDevice (string) --Suppresses the specified device included in the block device mapping of the AMI. :type Monitoring: dict :param Monitoring: The monitoring for the instance. Enabled (boolean) -- [REQUIRED]Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. :type SubnetId: string :param SubnetId: [EC2-VPC] The ID of the subnet to launch the instance into. :type DisableApiTermination: boolean :param DisableApiTermination: If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute to false after launch, use ModifyInstanceAttribute . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. Default: false :type InstanceInitiatedShutdownBehavior: string :param InstanceInitiatedShutdownBehavior: Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). Default: stop :type PrivateIpAddress: string :param PrivateIpAddress: [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. :type Ipv6Addresses: list :param Ipv6Addresses: [EC2-VPC] Specify one or more IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. (dict) --Describes an IPv6 address. Ipv6Address (string) --The IPv6 address. :type Ipv6AddressCount: integer :param Ipv6AddressCount: [EC2-VPC] A number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. :type ClientToken: string :param ClientToken: Unique, case-sensitive identifier you provide to ensure the idempotency of the request. For more information, see Ensuring Idempotency . Constraints: Maximum 64 ASCII characters :type AdditionalInfo: string :param AdditionalInfo: Reserved. :type NetworkInterfaces: list :param NetworkInterfaces: One or more network interfaces. (dict) --Describes a network interface. NetworkInterfaceId (string) --The ID of the network interface. DeviceIndex (integer) --The index of the device on the instance for the network interface attachment. If you are specifying a network interface in a RunInstances request, you must provide the device index. SubnetId (string) --The ID of the subnet associated with the network string. Applies only if creating a network interface when launching an instance. Description (string) --The description of the network interface. Applies only if creating a network interface when launching an instance. PrivateIpAddress (string) --The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a RunInstances request. Groups (list) --The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. (string) -- DeleteOnTermination (boolean) --If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. PrivateIpAddresses (list) --One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a RunInstances request. (dict) --Describes a secondary private IPv4 address for a network interface. PrivateIpAddress (string) -- [REQUIRED]The private IPv4 addresses. Primary (boolean) --Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. SecondaryPrivateIpAddressCount (integer) --The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a RunInstances request. AssociatePublicIpAddress (boolean) --Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . Ipv6Addresses (list) --One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. (dict) --Describes an IPv6 address. Ipv6Address (string) --The IPv6 address. Ipv6AddressCount (integer) --A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. :type IamInstanceProfile: dict :param IamInstanceProfile: The IAM instance profile. Arn (string) --The Amazon Resource Name (ARN) of the instance profile. Name (string) --The name of the instance profile. :type EbsOptimized: boolean :param EbsOptimized: Indicates whether the instance is optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. Default: false :type TagSpecifications: list :param TagSpecifications: The tags to apply to the resources during launch. You can tag instances and volumes. The specified tags are applied to all instances or volumes that are created during launch. (dict) --The tags to apply to a resource when the resource is being created. ResourceType (string) --The type of resource to tag. Currently, the resource types that support tagging on creation are instance and volume . Tags (list) --The tags to apply to the resource. (dict) --Describes a tag. Key (string) --The key of the tag. Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: Value (string) --The value of the tag. Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters. :rtype: dict :return: { 'ReservationId': 'string', 'OwnerId': 'string', 'RequesterId': 'string', 'Groups': [ { 'GroupName': 'string', 'GroupId': 'string' }, ], 'Instances': [ { 'InstanceId': 'string', 'ImageId': 'string', 'State': { 'Code': 123, 'Name': 'pending'|'running'|'shutting-down'|'terminated'|'stopping'|'stopped' }, 'PrivateDnsName': 'string', 'PublicDnsName': 'string', 'StateTransitionReason': 'string', 'KeyName': 'string', 'AmiLaunchIndex': 123, 'ProductCodes': [ { 'ProductCodeId': 'string', 'ProductCodeType': 'devpay'|'marketplace' }, ], 'InstanceType': 't1.micro'|'t2.nano'|'t2.micro'|'t2.small'|'t2.medium'|'t2.large'|'t2.xlarge'|'t2.2xlarge'|'m1.small'|'m1.medium'|'m1.large'|'m1.xlarge'|'m3.medium'|'m3.large'|'m3.xlarge'|'m3.2xlarge'|'m4.large'|'m4.xlarge'|'m4.2xlarge'|'m4.4xlarge'|'m4.10xlarge'|'m4.16xlarge'|'m2.xlarge'|'m2.2xlarge'|'m2.4xlarge'|'cr1.8xlarge'|'r3.large'|'r3.xlarge'|'r3.2xlarge'|'r3.4xlarge'|'r3.8xlarge'|'r4.large'|'r4.xlarge'|'r4.2xlarge'|'r4.4xlarge'|'r4.8xlarge'|'r4.16xlarge'|'x1.16xlarge'|'x1.32xlarge'|'i2.xlarge'|'i2.2xlarge'|'i2.4xlarge'|'i2.8xlarge'|'i3.large'|'i3.xlarge'|'i3.2xlarge'|'i3.4xlarge'|'i3.8xlarge'|'i3.16xlarge'|'hi1.4xlarge'|'hs1.8xlarge'|'c1.medium'|'c1.xlarge'|'c3.large'|'c3.xlarge'|'c3.2xlarge'|'c3.4xlarge'|'c3.8xlarge'|'c4.large'|'c4.xlarge'|'c4.2xlarge'|'c4.4xlarge'|'c4.8xlarge'|'cc1.4xlarge'|'cc2.8xlarge'|'g2.2xlarge'|'g2.8xlarge'|'cg1.4xlarge'|'p2.xlarge'|'p2.8xlarge'|'p2.16xlarge'|'d2.xlarge'|'d2.2xlarge'|'d2.4xlarge'|'d2.8xlarge'|'f1.2xlarge'|'f1.16xlarge', 'LaunchTime': datetime(2015, 1, 1), 'Placement': { 'AvailabilityZone': 'string', 'GroupName': 'string', 'Tenancy': 'default'|'dedicated'|'host', 'HostId': 'string', 'Affinity': 'string' }, 'KernelId': 'string', 'RamdiskId': 'string', 'Platform': 'Windows', 'Monitoring': { 'State': 'disabled'|'disabling'|'enabled'|'pending' }, 'SubnetId': 'string', 'VpcId': 'string', 'PrivateIpAddress': 'string', 'PublicIpAddress': 'string', 'StateReason': { 'Code': 'string', 'Message': 'string' }, 'Architecture': 'i386'|'x86_64', 'RootDeviceType': 'ebs'|'instance-store', 'RootDeviceName': 'string', 'BlockDeviceMappings': [ { 'DeviceName': 'string', 'Ebs': { 'VolumeId': 'string', 'Status': 'attaching'|'attached'|'detaching'|'detached', 'AttachTime': datetime(2015, 1, 1), 'DeleteOnTermination': True|False } }, ], 'VirtualizationType': 'hvm'|'paravirtual', 'InstanceLifecycle': 'spot'|'scheduled', 'SpotInstanceRequestId': 'string', 'ClientToken': 'string', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ], 'SecurityGroups': [ { 'GroupName': 'string', 'GroupId': 'string' }, ], 'SourceDestCheck': True|False, 'Hypervisor': 'ovm'|'xen', 'NetworkInterfaces': [ { 'NetworkInterfaceId': 'string', 'SubnetId': 'string', 'VpcId': 'string', 'Description': 'string', 'OwnerId': 'string', 'Status': 'available'|'attaching'|'in-use'|'detaching', 'MacAddress': 'string', 'PrivateIpAddress': 'string', 'PrivateDnsName': 'string', 'SourceDestCheck': True|False, 'Groups': [ { 'GroupName': 'string', 'GroupId': 'string' }, ], 'Attachment': { 'AttachmentId': 'string', 'DeviceIndex': 123, 'Status': 'attaching'|'attached'|'detaching'|'detached', 'AttachTime': datetime(2015, 1, 1), 'DeleteOnTermination': True|False }, 'Association': { 'PublicIp': 'string', 'PublicDnsName': 'string', 'IpOwnerId': 'string' }, 'PrivateIpAddresses': [ { 'PrivateIpAddress': 'string', 'PrivateDnsName': 'string', 'Primary': True|False, 'Association': { 'PublicIp': 'string', 'PublicDnsName': 'string', 'IpOwnerId': 'string' } }, ], 'Ipv6Addresses': [ { 'Ipv6Address': 'string' }, ] }, ], 'IamInstanceProfile': { 'Arn': 'string', 'Id': 'string' }, 'EbsOptimized': True|False, 'SriovNetSupport': 'string', 'EnaSupport': True|False }, ] } :returns: DryRun (boolean) -- Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation . ImageId (string) -- [REQUIRED] The ID of the AMI, which you can get by calling DescribeImages . MinCount (integer) -- [REQUIRED] The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see How many instances can I run in Amazon EC2 in the Amazon EC2 General FAQ. MaxCount (integer) -- [REQUIRED] The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above MinCount . Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see How many instances can I run in Amazon EC2 in the Amazon EC2 FAQ. KeyName (string) -- The name of the key pair. You can create a key pair using CreateKeyPair or ImportKeyPair . Warning If you do not specify a key pair, you can't connect to the instance unless you choose an AMI that is configured to allow users another way to log in. SecurityGroups (list) -- [EC2-Classic, default VPC] One or more security group names. For a nondefault VPC, you must use security group IDs instead. Default: Amazon EC2 uses the default security group. (string) -- SecurityGroupIds (list) -- One or more security group IDs. You can create a security group using CreateSecurityGroup . Default: Amazon EC2 uses the default security group. (string) -- UserData (string) -- The user data to make available to the instance. For more information, see Running Commands on Your Linux Instance at Launch (Linux) and Adding User Data (Windows). If you are using an AWS SDK or command line tool, Base64-encoding is performed for you, and you can load the text from a file. Otherwise, you must provide Base64-encoded text. This value will be base64 encoded automatically. Do not base64 encode this value prior to performing the operation. InstanceType (string) -- The instance type. For more information, see Instance Types in the Amazon Elastic Compute Cloud User Guide . Default: m1.small Placement (dict) -- The placement for the instance. AvailabilityZone (string) --The Availability Zone of the instance. GroupName (string) --The name of the placement group the instance is in (for cluster compute instances). Tenancy (string) --The tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the ImportInstance command. HostId (string) --The ID of the Dedicated Host on which the instance resides. This parameter is not supported for the ImportInstance command. Affinity (string) --The affinity setting for the instance on the Dedicated Host. This parameter is not supported for the ImportInstance command. KernelId (string) -- The ID of the kernel. Warning We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see PV-GRUB in the Amazon Elastic Compute Cloud User Guide . RamdiskId (string) -- The ID of the RAM disk. Warning We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see PV-GRUB in the Amazon Elastic Compute Cloud User Guide . BlockDeviceMappings (list) -- The block device mapping. Warning Supplying both a snapshot ID and an encryption value as arguments for block-device mapping results in an error. This is because only blank volumes can be encrypted on start, and these are not created from a snapshot. If a snapshot is the basis for the volume, it contains data by definition and its encryption status cannot be changed using this action. (dict) --Describes a block device mapping. VirtualName (string) --The virtual device name (ephemeral N). Instance store volumes are numbered starting from 0. An instance type with 2 available instance store volumes can specify mappings for ephemeral0 and ephemeral1 .The number of available instance store volumes depends on the instance type. After you connect to the instance, you must mount the volume. Constraints: For M3 instances, you must specify instance store volumes in the block device mapping for the instance. When you launch an M3 instance, we ignore any instance store volumes specified in the block device mapping for the AMI. DeviceName (string) --The device name exposed to the instance (for example, /dev/sdh or xvdh ). Ebs (dict) --Parameters used to automatically set up EBS volumes when the instance is launched. SnapshotId (string) --The ID of the snapshot. VolumeSize (integer) --The size of the volume, in GiB. Constraints: 1-16384 for General Purpose SSD (gp2 ), 4-16384 for Provisioned IOPS SSD (io1 ), 500-16384 for Throughput Optimized HDD (st1 ), 500-16384 for Cold HDD (sc1 ), and 1-1024 for Magnetic (standard ) volumes. If you specify a snapshot, the volume size must be equal to or larger than the snapshot size. Default: If you're creating the volume from a snapshot and don't specify a volume size, the default is the snapshot size. DeleteOnTermination (boolean) --Indicates whether the EBS volume is deleted on instance termination. VolumeType (string) --The volume type: gp2 , io1 , st1 , sc1 , or standard . Default: standard Iops (integer) --The number of I/O operations per second (IOPS) that the volume supports. For io1 , this represents the number of IOPS that are provisioned for the volume. For gp2 , this represents the baseline performance of the volume and the rate at which the volume accumulates I/O credits for bursting. For more information about General Purpose SSD baseline performance, I/O credits, and bursting, see Amazon EBS Volume Types in the Amazon Elastic Compute Cloud User Guide . Constraint: Range is 100-20000 IOPS for io1 volumes and 100-10000 IOPS for gp2 volumes. Condition: This parameter is required for requests to create io1 volumes; it is not used in requests to create gp2 , st1 , sc1 , or standard volumes. Encrypted (boolean) --Indicates whether the EBS volume is encrypted. Encrypted Amazon EBS volumes may only be attached to instances that support Amazon EBS encryption. NoDevice (string) --Suppresses the specified device included in the block device mapping of the AMI. Monitoring (dict) -- The monitoring for the instance. Enabled (boolean) -- [REQUIRED]Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. SubnetId (string) -- [EC2-VPC] The ID of the subnet to launch the instance into. DisableApiTermination (boolean) -- If you set this parameter to true , you can't terminate the instance using the Amazon EC2 console, CLI, or API; otherwise, you can. To change this attribute to false after launch, use ModifyInstanceAttribute . Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate , you can terminate the instance by running the shutdown command from the instance. Default: false InstanceInitiatedShutdownBehavior (string) -- Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). Default: stop PrivateIpAddress (string) -- [EC2-VPC] The primary IPv4 address. You must specify a value from the IPv4 address range of the subnet. Only one private IP address can be designated as primary. You can't specify this option if you've specified the option to designate a private IP address as the primary IP address in a network interface specification. You cannot specify this option if you're launching more than one instance in the request. Ipv6Addresses (list) -- [EC2-VPC] Specify one or more IPv6 addresses from the range of the subnet to associate with the primary network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. (dict) --Describes an IPv6 address. Ipv6Address (string) --The IPv6 address. Ipv6AddressCount (integer) -- [EC2-VPC] A number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. ClientToken (string) -- Unique, case-sensitive identifier you provide to ensure the idempotency of the request. For more information, see Ensuring Idempotency . Constraints: Maximum 64 ASCII characters AdditionalInfo (string) -- Reserved. NetworkInterfaces (list) -- One or more network interfaces. (dict) --Describes a network interface. NetworkInterfaceId (string) --The ID of the network interface. DeviceIndex (integer) --The index of the device on the instance for the network interface attachment. If you are specifying a network interface in a RunInstances request, you must provide the device index. SubnetId (string) --The ID of the subnet associated with the network string. Applies only if creating a network interface when launching an instance. Description (string) --The description of the network interface. Applies only if creating a network interface when launching an instance. PrivateIpAddress (string) --The private IPv4 address of the network interface. Applies only if creating a network interface when launching an instance. You cannot specify this option if you're launching more than one instance in a RunInstances request. Groups (list) --The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance. (string) -- DeleteOnTermination (boolean) --If set to true , the interface is deleted when the instance is terminated. You can specify true only if creating a new network interface when launching an instance. PrivateIpAddresses (list) --One or more private IPv4 addresses to assign to the network interface. Only one private IPv4 address can be designated as primary. You cannot specify this option if you're launching more than one instance in a RunInstances request. (dict) --Describes a secondary private IPv4 address for a network interface. PrivateIpAddress (string) -- [REQUIRED]The private IPv4 addresses. Primary (boolean) --Indicates whether the private IPv4 address is the primary private IPv4 address. Only one IPv4 address can be designated as primary. SecondaryPrivateIpAddressCount (integer) --The number of secondary private IPv4 addresses. You can't specify this option and specify more than one private IP address using the private IP addresses option. You cannot specify this option if you're launching more than one instance in a RunInstances request. AssociatePublicIpAddress (boolean) --Indicates whether to assign a public IPv4 address to an instance you launch in a VPC. The public IP address can only be assigned to a network interface for eth0, and can only be assigned to a new network interface, not an existing one. You cannot specify more than one network interface in the request. If launching into a default subnet, the default value is true . Ipv6Addresses (list) --One or more IPv6 addresses to assign to the network interface. You cannot specify this option and the option to assign a number of IPv6 addresses in the same request. You cannot specify this option if you've specified a minimum number of instances to launch. (dict) --Describes an IPv6 address. Ipv6Address (string) --The IPv6 address. Ipv6AddressCount (integer) --A number of IPv6 addresses to assign to the network interface. Amazon EC2 chooses the IPv6 addresses from the range of the subnet. You cannot specify this option and the option to assign specific IPv6 addresses in the same request. You can specify this option if you've specified a minimum number of instances to launch. IamInstanceProfile (dict) -- The IAM instance profile. Arn (string) --The Amazon Resource Name (ARN) of the instance profile. Name (string) --The name of the instance profile. EbsOptimized (boolean) -- Indicates whether the instance is optimized for EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance. Default: false TagSpecifications (list) -- The tags to apply to the resources during launch. You can tag instances and volumes. The specified tags are applied to all instances or volumes that are created during launch. (dict) --The tags to apply to a resource when the resource is being created. ResourceType (string) --The type of resource to tag. Currently, the resource types that support tagging on creation are instance and volume . Tags (list) --The tags to apply to the resource. (dict) --Describes a tag. Key (string) --The key of the tag. Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: Value (string) --The value of the tag. Constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters.
[ "Launches", "the", "specified", "number", "of", "instances", "using", "an", "AMI", "for", "which", "you", "have", "permissions", ".", "You", "can", "specify", "a", "number", "of", "options", "or", "leave", "the", "default", "options", ".", "The", "following"...
python
train
alanjds/drf-nested-routers
rest_framework_nested/viewsets.py
https://github.com/alanjds/drf-nested-routers/blob/8c48cae40522612debaca761503b4e1a6f1cdba4/rest_framework_nested/viewsets.py#L2-L13
def get_queryset(self): """ Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() if hasattr(self.serializer_class, 'parent_lookup_kwargs'): orm_filters = {} for query_param, field_name in self.serializer_class.parent_lookup_kwargs.items(): orm_filters[field_name] = self.kwargs[query_param] return queryset.filter(**orm_filters) return queryset
[ "def", "get_queryset", "(", "self", ")", ":", "queryset", "=", "super", "(", "NestedViewSetMixin", ",", "self", ")", ".", "get_queryset", "(", ")", "if", "hasattr", "(", "self", ".", "serializer_class", ",", "'parent_lookup_kwargs'", ")", ":", "orm_filters", ...
Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`.
[ "Filter", "the", "QuerySet", "based", "on", "its", "parents", "as", "defined", "in", "the", "serializer_class", ".", "parent_lookup_kwargs", "." ]
python
train
farshidce/touchworks-python
touchworks/api/http.py
https://github.com/farshidce/touchworks-python/blob/ea8f93a0f4273de1317a318e945a571f5038ba62/touchworks/api/http.py#L139-L161
def get_token(self, appname, username, password): """ get the security token by connecting to TouchWorks API """ ext_exception = TouchWorksException( TouchWorksErrorMessages.GET_TOKEN_FAILED_ERROR) data = {'Username': username, 'Password': password} resp = self._http_request(TouchWorksEndPoints.GET_TOKEN, data) try: logger.debug('token : %s' % resp) if not resp.text: raise ext_exception try: uuid.UUID(resp.text, version=4) return SecurityToken(resp.text) except ValueError: logger.error('response was not valid uuid string. %s' % resp.text) raise ext_exception except Exception as ex: logger.exception(ex) raise ext_exception
[ "def", "get_token", "(", "self", ",", "appname", ",", "username", ",", "password", ")", ":", "ext_exception", "=", "TouchWorksException", "(", "TouchWorksErrorMessages", ".", "GET_TOKEN_FAILED_ERROR", ")", "data", "=", "{", "'Username'", ":", "username", ",", "'...
get the security token by connecting to TouchWorks API
[ "get", "the", "security", "token", "by", "connecting", "to", "TouchWorks", "API" ]
python
train
pypa/pipenv
pipenv/vendor/pep517/_in_process.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/_in_process.py#L43-L54
def get_requires_for_build_wheel(config_settings): """Invoke the optional get_requires_for_build_wheel hook Returns [] if the hook is not defined. """ backend = _build_backend() try: hook = backend.get_requires_for_build_wheel except AttributeError: return [] else: return hook(config_settings)
[ "def", "get_requires_for_build_wheel", "(", "config_settings", ")", ":", "backend", "=", "_build_backend", "(", ")", "try", ":", "hook", "=", "backend", ".", "get_requires_for_build_wheel", "except", "AttributeError", ":", "return", "[", "]", "else", ":", "return"...
Invoke the optional get_requires_for_build_wheel hook Returns [] if the hook is not defined.
[ "Invoke", "the", "optional", "get_requires_for_build_wheel", "hook" ]
python
train
inasafe/inasafe
safe/gui/tools/wizard/wizard_help.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/wizard_help.py#L63-L66
def restore_button_state(self): """Helper to restore button state.""" self.parent.pbnNext.setEnabled(self.next_button_state) self.parent.pbnBack.setEnabled(self.back_button_state)
[ "def", "restore_button_state", "(", "self", ")", ":", "self", ".", "parent", ".", "pbnNext", ".", "setEnabled", "(", "self", ".", "next_button_state", ")", "self", ".", "parent", ".", "pbnBack", ".", "setEnabled", "(", "self", ".", "back_button_state", ")" ]
Helper to restore button state.
[ "Helper", "to", "restore", "button", "state", "." ]
python
train
zhebrak/raftos
raftos/state.py
https://github.com/zhebrak/raftos/blob/0d6f9e049b526279b1035f597291a96cf50c9b40/raftos/state.py#L260-L267
async def execute_command(self, command): """Write to log & send AppendEntries RPC""" self.apply_future = asyncio.Future(loop=self.loop) entry = self.log.write(self.storage.term, command) asyncio.ensure_future(self.append_entries(), loop=self.loop) await self.apply_future
[ "async", "def", "execute_command", "(", "self", ",", "command", ")", ":", "self", ".", "apply_future", "=", "asyncio", ".", "Future", "(", "loop", "=", "self", ".", "loop", ")", "entry", "=", "self", ".", "log", ".", "write", "(", "self", ".", "stora...
Write to log & send AppendEntries RPC
[ "Write", "to", "log", "&", "send", "AppendEntries", "RPC" ]
python
train
nigma/django-easy-pdf
easy_pdf/views.py
https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/views.py#L47-L61
def get_pdf_response(self, context, **response_kwargs): """ Renders PDF document and prepares response. :returns: Django HTTP response :rtype: :class:`django.http.HttpResponse` """ return render_to_pdf_response( request=self.request, template=self.get_template_names(), context=context, using=self.template_engine, filename=self.get_pdf_filename(), **self.get_pdf_kwargs() )
[ "def", "get_pdf_response", "(", "self", ",", "context", ",", "*", "*", "response_kwargs", ")", ":", "return", "render_to_pdf_response", "(", "request", "=", "self", ".", "request", ",", "template", "=", "self", ".", "get_template_names", "(", ")", ",", "cont...
Renders PDF document and prepares response. :returns: Django HTTP response :rtype: :class:`django.http.HttpResponse`
[ "Renders", "PDF", "document", "and", "prepares", "response", "." ]
python
train
dfm/celerite
celerite/celerite.py
https://github.com/dfm/celerite/blob/ad3f471f06b18d233f3dab71bb1c20a316173cae/celerite/celerite.py#L97-L139
def compute(self, t, yerr=1.123e-12, check_sorted=True, A=None, U=None, V=None): """ Compute the extended form of the covariance matrix and factorize Args: x (array[n]): The independent coordinates of the data points. This array must be _sorted_ in ascending order. yerr (Optional[float or array[n]]): The measurement uncertainties for the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix. (default: ``1.123e-12``) check_sorted (bool): If ``True``, ``x`` will be checked to make sure that it is properly sorted. If ``False``, the coordinates will be assumed to be in the correct order. Raises: ValueError: For un-sorted data or mismatched dimensions. solver.LinAlgError: For non-positive definite matrices. """ t = np.atleast_1d(t) if check_sorted and np.any(np.diff(t) < 0.0): raise ValueError("the input coordinates must be sorted") if check_sorted and len(t.shape) > 1: raise ValueError("dimension mismatch") self._t = t self._yerr = np.empty_like(self._t) self._yerr[:] = yerr (alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag) = self.kernel.coefficients self._A = np.empty(0) if A is None else A self._U = np.empty((0, 0)) if U is None else U self._V = np.empty((0, 0)) if V is None else V self.solver.compute( self.kernel.jitter, alpha_real, beta_real, alpha_complex_real, alpha_complex_imag, beta_complex_real, beta_complex_imag, self._A, self._U, self._V, t, self._yerr**2 ) self.dirty = False
[ "def", "compute", "(", "self", ",", "t", ",", "yerr", "=", "1.123e-12", ",", "check_sorted", "=", "True", ",", "A", "=", "None", ",", "U", "=", "None", ",", "V", "=", "None", ")", ":", "t", "=", "np", ".", "atleast_1d", "(", "t", ")", "if", "...
Compute the extended form of the covariance matrix and factorize Args: x (array[n]): The independent coordinates of the data points. This array must be _sorted_ in ascending order. yerr (Optional[float or array[n]]): The measurement uncertainties for the data points at coordinates ``x``. These values will be added in quadrature to the diagonal of the covariance matrix. (default: ``1.123e-12``) check_sorted (bool): If ``True``, ``x`` will be checked to make sure that it is properly sorted. If ``False``, the coordinates will be assumed to be in the correct order. Raises: ValueError: For un-sorted data or mismatched dimensions. solver.LinAlgError: For non-positive definite matrices.
[ "Compute", "the", "extended", "form", "of", "the", "covariance", "matrix", "and", "factorize" ]
python
train
senaite/senaite.core
bika/lims/content/client.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/client.py#L234-L239
def getCountry(self, default=None): """Return the Country from the Physical or Postal Address """ physical_address = self.getPhysicalAddress().get("country", default) postal_address = self.getPostalAddress().get("country", default) return physical_address or postal_address
[ "def", "getCountry", "(", "self", ",", "default", "=", "None", ")", ":", "physical_address", "=", "self", ".", "getPhysicalAddress", "(", ")", ".", "get", "(", "\"country\"", ",", "default", ")", "postal_address", "=", "self", ".", "getPostalAddress", "(", ...
Return the Country from the Physical or Postal Address
[ "Return", "the", "Country", "from", "the", "Physical", "or", "Postal", "Address" ]
python
train
scheibler/khard
khard/carddav_object.py
https://github.com/scheibler/khard/blob/0f69430c2680f1ff5f073a977a3c5b753b96cc17/khard/carddav_object.py#L415-L431
def get_email_addresses(self): """ : returns: dict of type and email address list :rtype: dict(str, list(str)) """ email_dict = {} for child in self.vcard.getChildren(): if child.name == "EMAIL": type = helpers.list_to_string( self._get_types_for_vcard_object(child, "internet"), ", ") if type not in email_dict: email_dict[type] = [] email_dict[type].append(child.value) # sort email address lists for email_list in email_dict.values(): email_list.sort() return email_dict
[ "def", "get_email_addresses", "(", "self", ")", ":", "email_dict", "=", "{", "}", "for", "child", "in", "self", ".", "vcard", ".", "getChildren", "(", ")", ":", "if", "child", ".", "name", "==", "\"EMAIL\"", ":", "type", "=", "helpers", ".", "list_to_s...
: returns: dict of type and email address list :rtype: dict(str, list(str))
[ ":", "returns", ":", "dict", "of", "type", "and", "email", "address", "list", ":", "rtype", ":", "dict", "(", "str", "list", "(", "str", "))" ]
python
test
juju/charm-helpers
charmhelpers/core/host.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L897-L923
def chownr(path, owner, group, follow_links=True, chowntopdir=False): """Recursively change user and group ownership of files and directories in given path. Doesn't chown path itself by default, only its children. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. :param bool follow_links: Also follow and chown links if True :param bool chowntopdir: Also chown path itself if True """ uid = pwd.getpwnam(owner).pw_uid gid = grp.getgrnam(group).gr_gid if follow_links: chown = os.chown else: chown = os.lchown if chowntopdir: broken_symlink = os.path.lexists(path) and not os.path.exists(path) if not broken_symlink: chown(path, uid, gid) for root, dirs, files in os.walk(path, followlinks=follow_links): for name in dirs + files: full = os.path.join(root, name) broken_symlink = os.path.lexists(full) and not os.path.exists(full) if not broken_symlink: chown(full, uid, gid)
[ "def", "chownr", "(", "path", ",", "owner", ",", "group", ",", "follow_links", "=", "True", ",", "chowntopdir", "=", "False", ")", ":", "uid", "=", "pwd", ".", "getpwnam", "(", "owner", ")", ".", "pw_uid", "gid", "=", "grp", ".", "getgrnam", "(", "...
Recursively change user and group ownership of files and directories in given path. Doesn't chown path itself by default, only its children. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. :param bool follow_links: Also follow and chown links if True :param bool chowntopdir: Also chown path itself if True
[ "Recursively", "change", "user", "and", "group", "ownership", "of", "files", "and", "directories", "in", "given", "path", ".", "Doesn", "t", "chown", "path", "itself", "by", "default", "only", "its", "children", "." ]
python
train
jonathf/chaospy
chaospy/poly/collection/linalg.py
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/linalg.py#L125-L154
def dot(poly1, poly2): """ Dot product of polynomial vectors. Args: poly1 (Poly) : left part of product. poly2 (Poly) : right part of product. Returns: (Poly) : product of poly1 and poly2. Examples: >>> poly = cp.prange(3, 1) >>> print(poly) [1, q0, q0^2] >>> print(cp.dot(poly, numpy.arange(3))) 2q0^2+q0 >>> print(cp.dot(poly, poly)) q0^4+q0^2+1 """ if not isinstance(poly1, Poly) and not isinstance(poly2, Poly): return numpy.dot(poly1, poly2) poly1 = Poly(poly1) poly2 = Poly(poly2) poly = poly1*poly2 if numpy.prod(poly1.shape) <= 1 or numpy.prod(poly2.shape) <= 1: return poly return chaospy.poly.sum(poly, 0)
[ "def", "dot", "(", "poly1", ",", "poly2", ")", ":", "if", "not", "isinstance", "(", "poly1", ",", "Poly", ")", "and", "not", "isinstance", "(", "poly2", ",", "Poly", ")", ":", "return", "numpy", ".", "dot", "(", "poly1", ",", "poly2", ")", "poly1",...
Dot product of polynomial vectors. Args: poly1 (Poly) : left part of product. poly2 (Poly) : right part of product. Returns: (Poly) : product of poly1 and poly2. Examples: >>> poly = cp.prange(3, 1) >>> print(poly) [1, q0, q0^2] >>> print(cp.dot(poly, numpy.arange(3))) 2q0^2+q0 >>> print(cp.dot(poly, poly)) q0^4+q0^2+1
[ "Dot", "product", "of", "polynomial", "vectors", "." ]
python
train
seznam/shelter
shelter/core/processes.py
https://github.com/seznam/shelter/blob/c652b0ff1cca70158f8fc97d9210c1fa5961ac1c/shelter/core/processes.py#L68-L110
def run(self): """ Child process. Repeatedly call :meth:`loop` method every :attribute:`interval` seconds. """ setproctitle.setproctitle("{:s}: {:s}".format( self.context.config.name, self.__class__.__name__)) self.logger.info( "Worker '%s' has been started with pid %d", self.__class__.__name__, os.getpid()) # Register SIGINT handler which will exit service process def sigint_handler(unused_signum, unused_frame): """ Exit service process when SIGINT is reached. """ self.stop() signal.signal(signal.SIGINT, sigint_handler) # Initialize logging self.context.config.configure_logging() # Initialize child self.context.initialize_child(SERVICE_PROCESS, process=self) next_loop_time = 0 while 1: # Exit if pid of the parent process has changed (parent process # has exited and init is new parent) or if stop flag is set. if os.getppid() != self._parent_pid or self._stop_event.is_set(): break # Repeatedly call loop method. After first call set ready flag. if time.time() >= next_loop_time: try: self.loop() except Exception: self.logger.exception( "Worker '%s' failed", self.__class__.__name__) else: if not next_loop_time and not self.ready: self._ready.value = True next_loop_time = time.time() + self.interval else: time.sleep(0.25)
[ "def", "run", "(", "self", ")", ":", "setproctitle", ".", "setproctitle", "(", "\"{:s}: {:s}\"", ".", "format", "(", "self", ".", "context", ".", "config", ".", "name", ",", "self", ".", "__class__", ".", "__name__", ")", ")", "self", ".", "logger", "....
Child process. Repeatedly call :meth:`loop` method every :attribute:`interval` seconds.
[ "Child", "process", ".", "Repeatedly", "call", ":", "meth", ":", "loop", "method", "every", ":", "attribute", ":", "interval", "seconds", "." ]
python
train
davgeo/clear
clear/renamer.py
https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/renamer.py#L302-L378
def _MoveFileToLibrary(self, oldPath, newPath): """ Move file from old file path to new file path. This follows certain conditions: - If file already exists at destination do rename inplace. - If file destination is on same file system and doesn't exist rename and move. - If source and destination are on different file systems do rename in-place, and if forceCopy is true copy to dest and move orig to archive directory. Parameters ---------- oldPath : string Old file path. newPath : string New file path. Returns ---------- boolean If old and new file paths are the same or if the new file path already exists this returns False. If file rename is skipped for any reason this returns None otherwise if rename completes okay it returns True. """ if oldPath == newPath: return False goodlogging.Log.Info("RENAMER", "PROCESSING FILE: {0}".format(oldPath)) if os.path.exists(newPath): goodlogging.Log.Info("RENAMER", "File skipped - file aleady exists in TV library at {0}".format(newPath)) return False newDir = os.path.dirname(newPath) os.makedirs(newDir, exist_ok=True) try: os.rename(oldPath, newPath) except OSError as ex: if ex.errno is errno.EXDEV: goodlogging.Log.Info("RENAMER", "Simple rename failed - source and destination exist on different file systems") goodlogging.Log.Info("RENAMER", "Renaming file in-place") newFileName = os.path.basename(newPath) origFileDir = os.path.dirname(oldPath) renameFilePath = os.path.join(origFileDir, newFileName) if oldPath != renameFilePath: renameFilePath = util.CheckPathExists(renameFilePath) goodlogging.Log.Info("RENAMER", "Renaming from {0} to {1}".format(oldPath, renameFilePath)) else: goodlogging.Log.Info("RENAMER", "File already has the correct name ({0})".format(newFileName)) try: os.rename(oldPath, renameFilePath) except Exception as ex2: goodlogging.Log.Info("RENAMER", "File rename skipped - Exception ({0}): {1}".format(ex2.args[0], ex2.args[1])) else: if self._forceCopy is True: goodlogging.Log.Info("RENAMER", "Copying file to new file system {0} to {1}".format(renameFilePath, newPath)) try: shutil.copy2(renameFilePath, newPath) except shutil.Error as ex3: err = ex3.args[0] goodlogging.Log.Info("RENAMER", "File copy failed - Shutil Error: {0}".format(err)) else: util.ArchiveProcessedFile(renameFilePath, self._archiveDir) return True else: goodlogging.Log.Info("RENAMER", "File copy skipped - copying between file systems is disabled (enabling this functionality is slow)") else: goodlogging.Log.Info("RENAMER", "File rename skipped - Exception ({0}): {1}".format(ex.args[0], ex.args[1])) except Exception as ex: goodlogging.Log.Info("RENAMER", "File rename skipped - Exception ({0}): {1}".format(ex.args[0], ex.args[1])) else: goodlogging.Log.Info("RENAMER", "RENAME COMPLETE: {0}".format(newPath)) return True
[ "def", "_MoveFileToLibrary", "(", "self", ",", "oldPath", ",", "newPath", ")", ":", "if", "oldPath", "==", "newPath", ":", "return", "False", "goodlogging", ".", "Log", ".", "Info", "(", "\"RENAMER\"", ",", "\"PROCESSING FILE: {0}\"", ".", "format", "(", "ol...
Move file from old file path to new file path. This follows certain conditions: - If file already exists at destination do rename inplace. - If file destination is on same file system and doesn't exist rename and move. - If source and destination are on different file systems do rename in-place, and if forceCopy is true copy to dest and move orig to archive directory. Parameters ---------- oldPath : string Old file path. newPath : string New file path. Returns ---------- boolean If old and new file paths are the same or if the new file path already exists this returns False. If file rename is skipped for any reason this returns None otherwise if rename completes okay it returns True.
[ "Move", "file", "from", "old", "file", "path", "to", "new", "file", "path", ".", "This", "follows", "certain", "conditions", ":" ]
python
train
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L2551-L2564
def migrate(self, uuid, desturi): """ Migrate a vm to another node :param uuid: uuid of the kvm container (same as the used in create) :param desturi: the uri of the destination node :return: """ args = { 'uuid': uuid, 'desturi': desturi, } self._migrate_action_chk.check(args) self._client.sync('kvm.migrate', args)
[ "def", "migrate", "(", "self", ",", "uuid", ",", "desturi", ")", ":", "args", "=", "{", "'uuid'", ":", "uuid", ",", "'desturi'", ":", "desturi", ",", "}", "self", ".", "_migrate_action_chk", ".", "check", "(", "args", ")", "self", ".", "_client", "."...
Migrate a vm to another node :param uuid: uuid of the kvm container (same as the used in create) :param desturi: the uri of the destination node :return:
[ "Migrate", "a", "vm", "to", "another", "node", ":", "param", "uuid", ":", "uuid", "of", "the", "kvm", "container", "(", "same", "as", "the", "used", "in", "create", ")", ":", "param", "desturi", ":", "the", "uri", "of", "the", "destination", "node", ...
python
train