code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def visit_BitVecSub(self, expression, *operands): """ a - 0 ==> 0 (a + b) - b ==> a (b + a) - b ==> a """ left = expression.operands[0] right = expression.operands[1] if isinstance(left, BitVecAdd): if self._same_constant(left.operands[0], ri...
a - 0 ==> 0 (a + b) - b ==> a (b + a) - b ==> a
def serialize(self, content): """ Serialize to JSONP. :return string: serializaed JSONP """ content = super(JSONPEmitter, self).serialize(content) callback = self.request.GET.get('callback', 'callback') return u'%s(%s)' % (callback, content)
Serialize to JSONP. :return string: serializaed JSONP
def set_privkey_compressed(privkey, compressed=True): """ Make sure the private key given is compressed or not compressed """ if len(privkey) != 64 and len(privkey) != 66: raise ValueError("expected 32-byte private key as a hex string") # compressed? if compressed and len(privkey) == 64...
Make sure the private key given is compressed or not compressed
def dump(self): """Prints out the contents of the import map.""" for modpath in sorted(self.map): title = 'Imports in %s' % modpath print('\n' + title + '\n' + '-'*len(title)) for name, value in sorted(self.map.get(modpath, {}).items()): print(' %s ->...
Prints out the contents of the import map.
def element_at(index): """Create a transducer which obtains the item at the specified index.""" if index < 0: raise IndexError("element_at used with illegal index {}".format(index)) def element_at_transducer(reducer): return ElementAt(reducer, index) return element_at_transducer
Create a transducer which obtains the item at the specified index.
def classinstances(cls): """Return all instances of the current class JB_Gui will not return the instances of subclasses A subclass will only return the instances that have the same type as the subclass. So it won\'t return instances of further subclasses. :returns: all instnac...
Return all instances of the current class JB_Gui will not return the instances of subclasses A subclass will only return the instances that have the same type as the subclass. So it won\'t return instances of further subclasses. :returns: all instnaces of the current class :rty...
def setWidth(self, typeID, width): """setWidth(string, double) -> None Sets the width in m of vehicles of this type. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_WIDTH, typeID, width)
setWidth(string, double) -> None Sets the width in m of vehicles of this type.
def _ExtractContentSettingsExceptions(self, exceptions_dict, parser_mediator): """Extracts site specific events. Args: exceptions_dict (dict): Permission exceptions data from Preferences file. parser_mediator (ParserMediator): mediates interactions between parsers and other components, su...
Extracts site specific events. Args: exceptions_dict (dict): Permission exceptions data from Preferences file. parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs.
def decode(self, encoded_packet): """Decode a transmitted package.""" b64 = False if not isinstance(encoded_packet, binary_types): encoded_packet = encoded_packet.encode('utf-8') elif not isinstance(encoded_packet, bytes): encoded_packet = bytes(encoded_packet) ...
Decode a transmitted package.
def _process_request(self, request, client_address): """Actually processes the request.""" try: self.finish_request(request, client_address) except Exception: self.handle_error(request, client_address) finally: self.shutdown_request(request)
Actually processes the request.
def get_task_runner(local_task_job): """ Get the task runner that can be used to run the given job. :param local_task_job: The LocalTaskJob associated with the TaskInstance that needs to be executed. :type local_task_job: airflow.jobs.LocalTaskJob :return: The task runner to use to run the ...
Get the task runner that can be used to run the given job. :param local_task_job: The LocalTaskJob associated with the TaskInstance that needs to be executed. :type local_task_job: airflow.jobs.LocalTaskJob :return: The task runner to use to run the task. :rtype: airflow.task.task_runner.base_t...
def read(cls, proto): """ Calls :meth:`~nupic.bindings.regions.PyRegion.PyRegion.readFromProto` on subclass after converting proto to specific type using :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getSchema`. :param proto: PyRegionProto capnproto object """ regionImpl = proto.regionIm...
Calls :meth:`~nupic.bindings.regions.PyRegion.PyRegion.readFromProto` on subclass after converting proto to specific type using :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getSchema`. :param proto: PyRegionProto capnproto object
def timeline(self, timeline="home", max_id=None, min_id=None, since_id=None, limit=None): """ Fetch statuses, most recent ones first. `timeline` can be 'home', 'local', 'public', 'tag/hashtag' or 'list/id'. See the following functions documentation for what those do. Local hashtag timeli...
Fetch statuses, most recent ones first. `timeline` can be 'home', 'local', 'public', 'tag/hashtag' or 'list/id'. See the following functions documentation for what those do. Local hashtag timelines are supported via the `timeline_hashtag()`_ function. The default timeline is the "home" ...
def align(s1,s2,test=False,seqfmt='dna', psm=None,pmm=None,pgo=None,pge=None, matrix=None, outscore=False): """ Creates pairwise local alignment between seqeunces. Get the visualization and alignment scores. :param s1: seqeunce 1 :param s2: seqeunce 2 REF: htt...
Creates pairwise local alignment between seqeunces. Get the visualization and alignment scores. :param s1: seqeunce 1 :param s2: seqeunce 2 REF: http://biopython.org/DIST/docs/api/Bio.pairwise2-module.html The match parameters are: CODE DESCRIPTION x No parameters. Identical c...
def bind_top_down(lower, upper, __fval=None, **fval): """Bind 2 layers for building. When the upper layer is added as a payload of the lower layer, all the arguments # noqa: E501 will be applied to them. ex: >>> bind_top_down(Ether, SNAP, type=0x1234) >>> Ether()/SNAP() <Ether ...
Bind 2 layers for building. When the upper layer is added as a payload of the lower layer, all the arguments # noqa: E501 will be applied to them. ex: >>> bind_top_down(Ether, SNAP, type=0x1234) >>> Ether()/SNAP() <Ether type=0x1234 |<SNAP |>>
def unsplit_query(query): """ Create a query string using the tuple query with a format as the one returned by split_query() """ def unsplit_assignment((x, y)): if (x is not None) and (y is not None): return x + '=' + y elif x is not None: return x eli...
Create a query string using the tuple query with a format as the one returned by split_query()
def autoExpand(self, level=None): """ Returns whether or not to expand for the inputed level. :param level | <int> || None :return <bool> """ return self._autoExpand.get(level, self._autoExpand.get(None, False))
Returns whether or not to expand for the inputed level. :param level | <int> || None :return <bool>
def get(self, url): """ Do a GET request """ r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT) self._check_response(r, 200) return r.json()
Do a GET request
def destroy(name, call=None): ''' To destroy a VM from the VMware environment CLI Example: .. code-block:: bash salt-cloud -d vmname salt-cloud --destroy vmname salt-cloud -a destroy vmname ''' if call == 'function': raise SaltCloudSystemExit( 'The ...
To destroy a VM from the VMware environment CLI Example: .. code-block:: bash salt-cloud -d vmname salt-cloud --destroy vmname salt-cloud -a destroy vmname
def _get_dependency_order(g, node_list): """Return list of nodes as close as possible to the ordering in node_list, but with child nodes earlier in the list than parents.""" access_ = accessibility(g) deps = dict((k, set(v) - set([k])) for k, v in access_.iteritems()) nodes = node_list + list(set(g....
Return list of nodes as close as possible to the ordering in node_list, but with child nodes earlier in the list than parents.
def computeRange(corners): """ Determine the range spanned by an array of pixel positions. """ x = corners[:, 0] y = corners[:, 1] _xrange = (np.minimum.reduce(x), np.maximum.reduce(x)) _yrange = (np.minimum.reduce(y), np.maximum.reduce(y)) return _xrange, _yrange
Determine the range spanned by an array of pixel positions.
def parallel_starfeatures_lcdir(lcdir, outdir, lc_catalog_pickle, neighbor_radius_arcsec, fileglob=None, maxobjects=None, deredd...
This runs parallel star feature extraction for a directory of LCs. Parameters ---------- lcdir : list of str The directory to search for light curves. outdir : str The output directory where the results will be placed. lc_catalog_pickle : str The path to a catalog contain...
def _convert_iterable(self, iterable): """Converts elements returned by an iterable into instances of self._wrapper """ # Return original if _wrapper isn't callable if not callable(self._wrapper): return iterable return [self._wrapper(x) for x in iterable]
Converts elements returned by an iterable into instances of self._wrapper
def list_pools(self): """Fetches a list of all floating IP pools. :returns: List of FloatingIpPool objects """ search_opts = {'router:external': True} return [FloatingIpPool(pool) for pool in self.client.list_networks(**search_opts).get('networks')]
Fetches a list of all floating IP pools. :returns: List of FloatingIpPool objects
def max_age(self, value): """ Set the MaxAge of the response. :type value: int :param value: the MaxAge option """ option = Option() option.number = defines.OptionRegistry.MAX_AGE.number option.value = int(value) self.del_option_by_number(defines....
Set the MaxAge of the response. :type value: int :param value: the MaxAge option
def get_possible_initializer_keys( cls, use_peepholes=False, use_batch_norm_h=True, use_batch_norm_x=False, use_batch_norm_c=False): """Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates:...
Returns the keys the dictionary of variable initializers may contain. The set of all possible initializer keys are: w_gates: weight for gates b_gates: bias of gates w_f_diag: weight for prev_cell -> forget gate peephole w_i_diag: weight for prev_cell -> input gate peephole w_o_diag:...
def all_coarse_grains_for_blackbox(blackbox): """Generator over all |CoarseGrains| for the given blackbox. If a box has multiple outputs, those outputs are partitioned into the same coarse-grain macro-element. """ for partition in all_partitions(blackbox.output_indices): for grouping in all...
Generator over all |CoarseGrains| for the given blackbox. If a box has multiple outputs, those outputs are partitioned into the same coarse-grain macro-element.
def minion_sign_in_payload(self): ''' Generates the payload used to authenticate with the master server. This payload consists of the passed in id_ and the ssh public key to encrypt the AES key sent back from the master. :return: Payload dictionary :rtype: dict '...
Generates the payload used to authenticate with the master server. This payload consists of the passed in id_ and the ssh public key to encrypt the AES key sent back from the master. :return: Payload dictionary :rtype: dict
def plot_sections(self, fout_dir=".", **kws_usr): """Plot groups of GOs which have been placed in sections.""" kws_plt, _ = self._get_kws_plt(None, **kws_usr) PltGroupedGos(self).plot_sections(fout_dir, **kws_plt)
Plot groups of GOs which have been placed in sections.
def hexedit(x): """Run external hex editor on a packet or bytes. Set editor in conf.prog.hexedit""" x = bytes(x) fname = get_temp_file() with open(fname,"wb") as f: f.write(x) subprocess.call([conf.prog.hexedit, fname]) with open(fname, "rb") as f: x = f.read() return x
Run external hex editor on a packet or bytes. Set editor in conf.prog.hexedit
def metadata(self): """Get metadata information in XML format.""" params = { self.PCTYPE: self.CTYPE_XML } response = self.call(self.CGI_BUG, params) return response
Get metadata information in XML format.
def build_option_parser(parser): """Hook to add global options.""" parser.add_argument( "--os-data-processing-api-version", metavar="<data-processing-api-version>", default=utils.env( 'OS_DATA_PROCESSING_API_VERSION', default=DEFAULT_DATA_PROCESSING_API_VERSION), ...
Hook to add global options.
def reducing(reducer, init=UNSET): """Create a reducing transducer with the given reducer. Args: reducer: A two-argument function which will be used to combine the partial cumulative result in the first argument with the next item from the input stream in the second argument. ...
Create a reducing transducer with the given reducer. Args: reducer: A two-argument function which will be used to combine the partial cumulative result in the first argument with the next item from the input stream in the second argument. Returns: A reducing transducer: A singl...
def adsSyncReadReqEx2( port, address, index_group, index_offset, data_type, return_ctypes=False ): # type: (int, AmsAddr, int, int, Type, bool) -> Any """Read data synchronous from an ADS-device. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: lo...
Read data synchronous from an ADS-device. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr :param int index_group: PLC storage area, according to the INDEXGROUP constants :param int index_offset: PLC storage address ...
def infer_call(self, context=None): """infer a Call node by trying to guess what the function returns""" callcontext = contextmod.copy_context(context) callcontext.callcontext = contextmod.CallContext( args=self.args, keywords=self.keywords ) callcontext.boundnode = None if context is no...
infer a Call node by trying to guess what the function returns
def _get_cache_key(self): """ The cache key is a string of concatenated sorted names and values. """ keys = list(self.params.keys()) keys.sort() cache_key = str() for key in keys: if key != "api_sig" and key != "api_key" and key != "sk": ...
The cache key is a string of concatenated sorted names and values.
def checkQueryRange(self, start, end): """ Checks to ensure that the query range is valid within this reference. If not, raise ReferenceRangeErrorException. """ condition = ( (start < 0 or end > self.getLength()) or start > end or start == end) if ...
Checks to ensure that the query range is valid within this reference. If not, raise ReferenceRangeErrorException.
def taskfile_created_data(file_, role): """Return the data for created date :param file_: the file that holds the data :type file_: :class:`jukeboxcore.djadapter.models.File` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the created date :rtype: depending...
Return the data for created date :param file_: the file that holds the data :type file_: :class:`jukeboxcore.djadapter.models.File` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the created date :rtype: depending on role :raises: None
def path(self): """Return the file path abstracted from VCS.""" if (self.source_file.startswith('a/') and self.target_file.startswith('b/')): filepath = self.source_file[2:] elif (self.source_file.startswith('a/') and self.target_file == '/dev/null'): ...
Return the file path abstracted from VCS.
def add_prefix(self, ncname: str) -> None: """ Look up ncname and add it to the prefix map if necessary @param ncname: name to add """ if ncname not in self.prefixmap: uri = cu.expand_uri(ncname + ':', self.curi_maps) if uri and '://' in uri: self...
Look up ncname and add it to the prefix map if necessary @param ncname: name to add
def _ensure_create_ha_compliant(self, router, router_type): """To be called in create_router() BEFORE router is created in DB.""" details = router.pop(ha.DETAILS, {}) if details == ATTR_NOT_SPECIFIED: details = {} res = {ha.ENABLED: router.pop(ha.ENABLED, ATTR_NOT_SPECIFIED),...
To be called in create_router() BEFORE router is created in DB.
def person_details(self, person_id, standardize=False): """Get a detailed person object :param person_id: String corresponding to the person's id. >>> instructor = d.person('jhs878sfd03b38b0d463b16320b5e438') """ resp = self._request(path.join(ENDPOINTS['DETAILS'], ...
Get a detailed person object :param person_id: String corresponding to the person's id. >>> instructor = d.person('jhs878sfd03b38b0d463b16320b5e438')
def get_start_time(self): """ Determines when has this process started running. @rtype: win32.SYSTEMTIME @return: Process start time. """ if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION ...
Determines when has this process started running. @rtype: win32.SYSTEMTIME @return: Process start time.
def get(cls, name, raise_exc=True): """ Get the element by name. Does an exact match by element type. :param str name: name of element :param bool raise_exc: optionally disable exception. :raises ElementNotFound: if element does not exist :rtype: Element ...
Get the element by name. Does an exact match by element type. :param str name: name of element :param bool raise_exc: optionally disable exception. :raises ElementNotFound: if element does not exist :rtype: Element
def nth(lst, n): """Return the nth item in the list.""" expect_type(n, (String, Number), unit=None) if isinstance(n, String): if n.value.lower() == 'first': i = 0 elif n.value.lower() == 'last': i = -1 else: raise ValueError("Invalid index %r" % (...
Return the nth item in the list.
def get_file(self, fp, headers=None, cb=None, num_cb=10, torrent=False, version_id=None, override_num_retries=None, response_headers=None, callback=None): """ Retrieves a file from an S3 Key :type fp: file :param fp: File pointer to put the data into ...
Retrieves a file from an S3 Key :type fp: file :param fp: File pointer to put the data into :type headers: string :param: headers to send when retrieving the files :type cb: function :param cb: a callback function that will be called to report progre...
def act(self, event, *args, **kwargs): """ Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins. *args and **kwargs will be passed directly to the plugin's hook functions :param samtranslator.plugins.LifeCycleEvents event: Event ...
Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins. *args and **kwargs will be passed directly to the plugin's hook functions :param samtranslator.plugins.LifeCycleEvents event: Event to act upon :return: Nothing :raises ValueE...
def estimate_maximum_read_length(fastq_file, quality_format="fastq-sanger", nreads=1000): """ estimate average read length of a fastq file """ in_handle = SeqIO.parse(open_fastq(fastq_file), quality_format) lengths = [] for _ in range(nreads): try: ...
estimate average read length of a fastq file
def set_attribute(self, element, attribute, value): """ :Description: Modify the given attribute of the target element. :param element: Element for browser instance to target. :type element: WebElement :param attribute: Attribute of target element to modify. :type attribu...
:Description: Modify the given attribute of the target element. :param element: Element for browser instance to target. :type element: WebElement :param attribute: Attribute of target element to modify. :type attribute: string :param value: Value of target element's attribute to ...
def remove_translation(self, context_id, translation_id): """Removes a translation entry from a tunnel context. :param int context_id: The id-value representing the context instance. :param int translation_id: The id-value representing the translation. :return bool: True if translation ...
Removes a translation entry from a tunnel context. :param int context_id: The id-value representing the context instance. :param int translation_id: The id-value representing the translation. :return bool: True if translation entry removal was successful.
def put(self, data, block=True): """ If there is space it sends data to server If no space in the queue It returns the request in every 10 millisecond until there will be space in the queue. """ self.start(test_connection=False) while True: respon...
If there is space it sends data to server If no space in the queue It returns the request in every 10 millisecond until there will be space in the queue.
def createFile( self, fileName, desiredAccess, shareMode, creationDisposition, flagsAndAttributes, dokanFileInfo, ): """Creates a file. :param fileName: name of file to create :type fileName: ctypes.c_wchar_p :param desiredAcce...
Creates a file. :param fileName: name of file to create :type fileName: ctypes.c_wchar_p :param desiredAccess: desired access flags :type desiredAccess: ctypes.c_ulong :param shareMode: share mode flags :type shareMode: ctypes.c_ulong :param creationDisposition: ...
def column_names(self): """ Returns the column names. Returns ------- out : list[string] Column names of the SFrame. """ if self._is_vertex_frame(): return self.__graph__.__proxy__.get_vertex_fields() elif self._is_edge_frame(): ...
Returns the column names. Returns ------- out : list[string] Column names of the SFrame.
def set_value(self, instance, value, parent=None): """ Set prop value :param instance: :param value: :param parent: :return: """ self.resolve_base(instance) value = self.deserialize(value, parent) instance.values[self.alias] = value ...
Set prop value :param instance: :param value: :param parent: :return:
def query_file(self, path, fetchall=False, **params): """Like Database.query, but takes a filename to load a query from.""" with self.get_connection() as conn: return conn.query_file(path, fetchall, **params)
Like Database.query, but takes a filename to load a query from.
def get_saved_rules(conf_file=None): ''' Return a data structure of the rules in the conf file CLI Example: .. code-block:: bash salt '*' nftables.get_saved_rules ''' if _conf() and not conf_file: conf_file = _conf() with salt.utils.files.fopen(conf_file) as fp_: ...
Return a data structure of the rules in the conf file CLI Example: .. code-block:: bash salt '*' nftables.get_saved_rules
def _broadcast_shapes(s1, s2): """Given array shapes `s1` and `s2`, compute the shape of the array that would result from broadcasting them together.""" n1 = len(s1) n2 = len(s2) n = max(n1, n2) res = [1] * n for i in range(n): if i >= n1: c1 = 1 else: ...
Given array shapes `s1` and `s2`, compute the shape of the array that would result from broadcasting them together.
def to_type(self, dtype: type, *cols, **kwargs): """ Convert colums values to a given type in the main dataframe :param dtype: a type to convert to: ex: ``str`` :type dtype: type :param \*cols: names of the colums :type \*cols: str, at least one :param \...
Convert colums values to a given type in the main dataframe :param dtype: a type to convert to: ex: ``str`` :type dtype: type :param \*cols: names of the colums :type \*cols: str, at least one :param \*\*kwargs: keyword arguments for ``df.astype`` :type \*\*kwar...
def get_formfield(model, field): """ Return the formfied associate to the field of the model """ class_field = model._meta.get_field(field) if hasattr(class_field, "field"): formfield = class_field.field.formfield() else: formfield = class_field.formfield() # Otherwise ...
Return the formfied associate to the field of the model
def get_toolbar_buttons(self): """Return toolbar buttons list.""" buttons = [] # Code to add the stop button if self.stop_button is None: self.stop_button = create_toolbutton( self, text=_("Stop"),...
Return toolbar buttons list.
def shrink(self, fraction=0.85): """Shrink the triangle polydata in the representation of the input mesh. Example: .. code-block:: python from vtkplotter import * pot = load(datadir + 'shapes/teapot.vtk').shrink(0.75) s = Sphere(r=0.2).pos(0,...
Shrink the triangle polydata in the representation of the input mesh. Example: .. code-block:: python from vtkplotter import * pot = load(datadir + 'shapes/teapot.vtk').shrink(0.75) s = Sphere(r=0.2).pos(0,0,-0.5) show(pot, s) ...
def add_replica(self, partition_name, count=1): """Increase the replication-factor for a partition. The replication-group to add to is determined as follows: 1. Find all replication-groups that have brokers not already replicating the partition. 2. Of these, find...
Increase the replication-factor for a partition. The replication-group to add to is determined as follows: 1. Find all replication-groups that have brokers not already replicating the partition. 2. Of these, find replication-groups that have fewer than the ...
def eval_gpr(expr, knockouts): """evaluate compiled ast of gene_reaction_rule with knockouts Parameters ---------- expr : Expression The ast of the gene reaction rule knockouts : DictList, set Set of genes that are knocked out Returns ------- bool True if the ge...
evaluate compiled ast of gene_reaction_rule with knockouts Parameters ---------- expr : Expression The ast of the gene reaction rule knockouts : DictList, set Set of genes that are knocked out Returns ------- bool True if the gene reaction rule is true with the give...
def _is_valid_datatype(datatype_instance): """ Returns true if datatype_instance is a valid datatype object and false otherwise. """ # Remap so we can still use the python types for the simple cases global _simple_type_remap if datatype_instance in _simple_type_remap: return True #...
Returns true if datatype_instance is a valid datatype object and false otherwise.
def twitch_receive_messages(self): """ Call this function to process everything received by the socket This needs to be called frequently enough (~10s) Twitch logs off users not replying to ping commands. :return: list of chat messages received. Each message is a dict ...
Call this function to process everything received by the socket This needs to be called frequently enough (~10s) Twitch logs off users not replying to ping commands. :return: list of chat messages received. Each message is a dict with the keys ['channel', 'username', 'message']
def create_from_tuple(cls, volume): """ Create instance from tuple. :param volume: tuple in one one of the following forms: target | source,target | source,target,mode :return: instance of Volume """ if isinstance(volume, six.string_types): return Volume(targe...
Create instance from tuple. :param volume: tuple in one one of the following forms: target | source,target | source,target,mode :return: instance of Volume
def roll(self, count=0, func=sum): '''Roll some dice! :param count: [0] Return list of sums :param func: [sum] Apply func to list of individual die rolls func([]) :return: A single sum or list of ``count`` sums ''' if count: return [func([die.roll() for die in...
Roll some dice! :param count: [0] Return list of sums :param func: [sum] Apply func to list of individual die rolls func([]) :return: A single sum or list of ``count`` sums
def get_tuple(nuplet, index, default=None): """ :param tuple nuplet: A tuple :param int index: An index :param default: An optional default value :return: ``nuplet[index]`` if defined, else ``default`` (possibly ``None``) """ if nuplet is None: return default try:...
:param tuple nuplet: A tuple :param int index: An index :param default: An optional default value :return: ``nuplet[index]`` if defined, else ``default`` (possibly ``None``)
def _get_property_values_with_defaults(self, classname, property_values): """Return the property values for the class, with default values applied where needed.""" # To uphold OrientDB semantics, make a new dict with all property values set # to their default values, which are None if no default...
Return the property values for the class, with default values applied where needed.
def get_objects_from_from_queues(self): """ Get objects from "from" queues and add them. :return: True if we got something in the queue, False otherwise. :rtype: bool """ _t0 = time.time() had_some_objects = False for module in self.modules_manager.get_external_i...
Get objects from "from" queues and add them. :return: True if we got something in the queue, False otherwise. :rtype: bool
def act(self): """ Carries out the action associated with Stop button """ g = get_root(self).globals g.clog.debug('Stop pressed') # Stop exposure meter # do this first, so timer doesn't also try to enable idle mode g.info.timer.stop() def stop_in...
Carries out the action associated with Stop button
def p_propertyDeclaration_3(p): """propertyDeclaration_3 : dataType propertyName array ';'""" p[0] = CIMProperty(p[2], None, type=p[1], is_array=True, array_size=p[3])
propertyDeclaration_3 : dataType propertyName array ';
def send_feedback(self, document_id: str, feedback: List[Field]) -> dict: """Send feedback to the model. This method takes care of sending feedback related to document specified by document_id. Feedback consists of ground truth values for the document specified as a list of Field instances. ...
Send feedback to the model. This method takes care of sending feedback related to document specified by document_id. Feedback consists of ground truth values for the document specified as a list of Field instances. >>> from las import ApiClient >>> api_client = ApiClient(endpoint='<api ...
def estimate(data, fit_offset="mean", fit_profile="tilt", border_px=0, from_mask=None, ret_mask=False): """Estimate the background value of an image Parameters ---------- data: np.ndarray Data from which to compute the background value fit_profile: str The type of backg...
Estimate the background value of an image Parameters ---------- data: np.ndarray Data from which to compute the background value fit_profile: str The type of background profile to fit: - "offset": offset only - "poly2o": 2D 2nd order polynomial with mixed terms ...
def password_attributes_max_retry(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") password_attributes = ET.SubElement(config, "password-attributes", xmlns="urn:brocade.com:mgmt:brocade-aaa") max_retry = ET.SubElement(password_attributes, "max-retry") ...
Auto Generated Code
def push(self, x): """ Push an I{object} onto the stack. @param x: An object to push. @type x: L{Frame} @return: The pushed frame. @rtype: L{Frame} """ if isinstance(x, Frame): frame = x else: frame = Frame(x) self.s...
Push an I{object} onto the stack. @param x: An object to push. @type x: L{Frame} @return: The pushed frame. @rtype: L{Frame}
def delete(self, session, commit=True, soft=True): """ Delete a row from the DB. :param session: flask_sqlalchemy session object :param commit: whether to issue the commit :param soft: whether this is a soft delete (i.e., update time_removed) """ if soft: ...
Delete a row from the DB. :param session: flask_sqlalchemy session object :param commit: whether to issue the commit :param soft: whether this is a soft delete (i.e., update time_removed)
def last_version(): """ Fetch the last version from pypi and return it. On successful fetch from pypi, the response is cached 24h, on error, it is cached 10 min. :return: the last django-cas-server version :rtype: unicode """ try: last_update, version, success = last...
Fetch the last version from pypi and return it. On successful fetch from pypi, the response is cached 24h, on error, it is cached 10 min. :return: the last django-cas-server version :rtype: unicode
def load_tab_data(self): """Preload all data that for the tabs that will be displayed.""" for tab in self._tabs.values(): if tab.load and not tab.data_loaded: try: tab._data = tab.get_context_data(self.request) except Exception: ...
Preload all data that for the tabs that will be displayed.
def disabled(name): ''' Disable the RDP service ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} stat = __salt__['rdp.status']() if stat: if __opts__['test']: ret['result'] = None ret['comment'] = 'RDP will ...
Disable the RDP service
def assign_reads_to_database(query, database_fasta, out_path, params=None): """Assign a set of query sequences to a reference database database_fasta_fp: absolute file path to the reference database query_fasta_fp: absolute file path to query sequences output_fp: absolute file path of the file to be ou...
Assign a set of query sequences to a reference database database_fasta_fp: absolute file path to the reference database query_fasta_fp: absolute file path to query sequences output_fp: absolute file path of the file to be output params: dict of BWA specific parameters. * Specify which algor...
def get_changes(self, checks=None, imports=None, resources=None, task_handle=taskhandle.NullTaskHandle()): """Get the changes needed by this restructuring `resources` can be a list of `rope.base.resources.File`\s to apply the restructuring on. If `None`, the restructuring w...
Get the changes needed by this restructuring `resources` can be a list of `rope.base.resources.File`\s to apply the restructuring on. If `None`, the restructuring will be applied to all python files. `checks` argument has been deprecated. Use the `args` argument of the constr...
def split_by_idxs(self, train_idx, valid_idx): "Split the data between `train_idx` and `valid_idx`." return self.split_by_list(self[train_idx], self[valid_idx])
Split the data between `train_idx` and `valid_idx`.
def check_reaction_consistency(database, solver, exchange=set(), checked=set(), zeromass=set(), weights={}): """Check inconsistent reactions by minimizing mass residuals Return a reaction iterable, and compound iterable. The reaction iterable yields reaction ids and mass resi...
Check inconsistent reactions by minimizing mass residuals Return a reaction iterable, and compound iterable. The reaction iterable yields reaction ids and mass residuals. The compound iterable yields compound ids and mass assignments. Each compound is assigned a mass of at least one, and the masses ar...
def minkowski_distance(x, y, p=2): """ Calculates the minkowski distance between two points. :param x: the first point :param y: the second point :param p: the order of the minkowski algorithm. If *p=1* it is equal to the manhatten distance, if *p=2* it is equal to the euclidian dis...
Calculates the minkowski distance between two points. :param x: the first point :param y: the second point :param p: the order of the minkowski algorithm. If *p=1* it is equal to the manhatten distance, if *p=2* it is equal to the euclidian distance. The higher the order, the closer it conv...
async def connect(self, client_id, conn_string): """Connect to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.connect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to ...
Connect to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.connect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to the underlying device adapter to connect. Raises: ...
def isNumber(self, value): """ Validate whether a value is a number or not """ try: str(value) float(value) return True except ValueError: return False
Validate whether a value is a number or not
def _step(self, dataset): '''Advance the state of the optimizer by one step. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A dataset for optimizing the model. Returns ------- train_monitors : dict A dictionar...
Advance the state of the optimizer by one step. Parameters ---------- dataset : :class:`Dataset <downhill.dataset.Dataset>` A dataset for optimizing the model. Returns ------- train_monitors : dict A dictionary mapping monitor names to values.
def get_centroids(self, ridx): """ :returns: array of centroids for the given rupture index """ centroids = [] with h5py.File(self.source_file, "r") as hdf5: for idx in ridx: trace = "{:s}/{:s}".format(self.idx_set["sec"], str(idx)) cen...
:returns: array of centroids for the given rupture index
def extract_params(): """Extract request params.""" uri = _get_uri_from_request(request) http_method = request.method headers = dict(request.headers) if 'wsgi.input' in headers: del headers['wsgi.input'] if 'wsgi.errors' in headers: del headers['wsgi.errors'] # Werkzeug, and...
Extract request params.
def pack(self, value=None): r"""Pack the value as a binary representation. Considering an example with UBInt8 class, that inherits from GenericType: >>> from pyof.foundation.basic_types import UBInt8 >>> objectA = UBInt8(1) >>> objectB = 5 >>> objectA.pack() ...
r"""Pack the value as a binary representation. Considering an example with UBInt8 class, that inherits from GenericType: >>> from pyof.foundation.basic_types import UBInt8 >>> objectA = UBInt8(1) >>> objectB = 5 >>> objectA.pack() b'\x01' >>> objectA.pac...
def register(self, resource=None, **meta): """ Add resource to the API. :param resource: Resource class for registration :param **meta: Redefine Meta options for the resource :return adrest.views.Resource: Generated resource. """ if resource is None: def wr...
Add resource to the API. :param resource: Resource class for registration :param **meta: Redefine Meta options for the resource :return adrest.views.Resource: Generated resource.
def split (s, delimter, trim = True, limit = 0): # pragma: no cover """ Split a string using a single-character delimter @params: `s`: the string `delimter`: the single-character delimter `trim`: whether to trim each part. Default: True @examples: ```python ret = split("'a,b',c", ",") # ret ==...
Split a string using a single-character delimter @params: `s`: the string `delimter`: the single-character delimter `trim`: whether to trim each part. Default: True @examples: ```python ret = split("'a,b',c", ",") # ret == ["'a,b'", "c"] # ',' inside quotes will be recognized. ``` @returns...
def make_unique_str(num_chars=20): """make a random string of characters for a temp filename""" chars = 'abcdefghigklmnopqrstuvwxyz' all_chars = chars + chars.upper() + '01234567890' picks = list(all_chars) return ''.join([choice(picks) for i in range(num_chars)])
make a random string of characters for a temp filename
def create(self, file_or_path, **kwargs): """ Creates an upload for the given file or path. """ opened = False if isinstance(file_or_path, str_type()): file_or_path = open(file_or_path, 'rb') opened = True elif not getattr(file_or_path, 'read', Fa...
Creates an upload for the given file or path.
def data_worker(**kwargs): """ Function to be spawned concurrently, consume data keys from input queue, and push the resulting dataframes to output map """ if kwargs is not None: if "function" in kwargs: function = kwargs["function"] else: Exception("Invalid a...
Function to be spawned concurrently, consume data keys from input queue, and push the resulting dataframes to output map
def add_repo(self, repo): """Add ``repo`` to this team. :param str repo: (required), form: 'user/repo' :returns: bool """ url = self._build_url('repos', repo, base_url=self._api) return self._boolean(self._put(url), 204, 404)
Add ``repo`` to this team. :param str repo: (required), form: 'user/repo' :returns: bool
def polfit_residuals_with_sigma_rejection( x, y, deg, times_sigma_reject, color='b', size=75, xlim=None, ylim=None, xlabel=None, ylabel=None, title=None, use_r=None, geometry=(0,0,640,480), debugplot=0): """Polynomial fit with iterative rejection of points. ...
Polynomial fit with iterative rejection of points. This function makes use of function polfit_residuals for display purposes. Parameters ---------- x : 1d numpy array, float X coordinates of the data being fitted. y : 1d numpy array, float Y coordinates of the data being fitted...
def _get_devices_by_activation_state(self, state): '''Get a list of bigips by activation statue. :param state: str -- state to filter the returned list of devices :returns: list -- list of devices that are in the given state ''' devices_with_state = [] for device in sel...
Get a list of bigips by activation statue. :param state: str -- state to filter the returned list of devices :returns: list -- list of devices that are in the given state
def _compute_mean(self, C, f0, f1, f2, SC, mag, rrup, idxs, mean, scale_fac): """ Compute mean value (for a set of indexes) without site amplification terms. This is equation (5), p. 2191, without S term. """ mean[idxs] = (C['c1'] + C['...
Compute mean value (for a set of indexes) without site amplification terms. This is equation (5), p. 2191, without S term.