code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def register_view(self, view): """This method is called by the view, that calls it when it is ready to register itself. Here we connect the 'pressed' signal of the button with a controller's method. Signal 'destroy' for the main window is handled as well.""" # connects the signa...
This method is called by the view, that calls it when it is ready to register itself. Here we connect the 'pressed' signal of the button with a controller's method. Signal 'destroy' for the main window is handled as well.
def openStream(self, source): """Produces a file object from source. source can be either a file object, local filename or a string. """ # Already a file object if hasattr(source, 'read'): stream = source else: stream = BytesIO(source) t...
Produces a file object from source. source can be either a file object, local filename or a string.
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # get original values hslab = 50 # See info in GMPEt_Inslab_...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
def sequence_matcher_similarity(state_a, state_b): """ The `difflib.SequenceMatcher` ratio between the state addresses in the history of the path. :param state_a: The first state to compare :param state_b: The second state to compare """ addrs_a = tuple(state_a.history.bb...
The `difflib.SequenceMatcher` ratio between the state addresses in the history of the path. :param state_a: The first state to compare :param state_b: The second state to compare
def _get(self, target, alias): """ Internal method to get a specific alias. """ if target not in self._aliases: return return self._aliases[target].get(alias)
Internal method to get a specific alias.
def find_block(context, *names): ''' Find the first matching block in the current block_context ''' block_set = context.render_context[BLOCK_CONTEXT_KEY] for name in names: block = block_set.get_block(name) if block is not None: return block raise template.TemplateSy...
Find the first matching block in the current block_context
def request(self, method, url, headers=None, raise_exception=True, **kwargs): """Main method for routing HTTP requests to the configured Vault base_uri. :param method: HTTP method to use with the request. E.g., GET, POST, etc. :type method: str :param url: Partial URL path to send the r...
Main method for routing HTTP requests to the configured Vault base_uri. :param method: HTTP method to use with the request. E.g., GET, POST, etc. :type method: str :param url: Partial URL path to send the request to. This will be joined to the end of the instance's base_uri attribut...
def make_openid_request(arq, keys, issuer, request_object_signing_alg, recv): """ Construct the JWT to be passed by value (the request parameter) or by reference (request_uri). The request will be signed :param arq: The Authorization request :param keys: Keys to use for signing/encrypting. A Ke...
Construct the JWT to be passed by value (the request parameter) or by reference (request_uri). The request will be signed :param arq: The Authorization request :param keys: Keys to use for signing/encrypting. A KeyJar instance :param issuer: Who is signing this JSON Web Token :param request_obj...
def remove_peer(self, peer): """ remove one or multiple peers from PEERS variable :param peer(list or string): """ if type(peer) == list: for x in peer: check_url(x) for i in self.PEERS: if x in i: ...
remove one or multiple peers from PEERS variable :param peer(list or string):
def dynamize_range_key_condition(self, range_key_condition): """ Convert a layer2 range_key_condition parameter into the structure required by Layer1. """ d = None if range_key_condition: d = {} for range_value in range_key_condition: ...
Convert a layer2 range_key_condition parameter into the structure required by Layer1.
def _log_default(self): """Start logging for this application. The default is to log to stdout using a StreaHandler. The log level starts at loggin.WARN, but this can be adjusted by setting the ``log_level`` attribute. """ log = logging.getLogger(self.__class__.__name__)...
Start logging for this application. The default is to log to stdout using a StreaHandler. The log level starts at loggin.WARN, but this can be adjusted by setting the ``log_level`` attribute.
def end_of_history(self, current): # (M->) u'''Move to the end of the input history, i.e., the line currently being entered.''' self.history_cursor = len(self.history) current.set_line(self.history[-1].get_line_text())
u'''Move to the end of the input history, i.e., the line currently being entered.
def modifiedLaplacian(img): ''''LAPM' algorithm (Nayar89)''' M = np.array([-1, 2, -1]) G = cv2.getGaussianKernel(ksize=3, sigma=-1) Lx = cv2.sepFilter2D(src=img, ddepth=cv2.CV_64F, kernelX=M, kernelY=G) Ly = cv2.sepFilter2D(src=img, ddepth=cv2.CV_64F, kernelX=G, kernelY=M) FM = np.abs(Lx) ...
LAPM' algorithm (Nayar89)
def _doActualSave(self, fname, comment, set_ro=False, overwriteRO=False): """ Override this so we can handle case of file not writable, as well as to make our _lastSavedState copy. """ self.debug('Saving, file name given: '+str(fname)+', set_ro: '+\ str(set_ro)+', overwrit...
Override this so we can handle case of file not writable, as well as to make our _lastSavedState copy.
def search_filter(entities, filters): """Read all ``entities`` and locally filter them. This method can be used like so:: entities = EntitySearchMixin(entities, {'name': 'foo'}) In this example, only entities where ``entity.name == 'foo'`` holds true are returned. An arbit...
Read all ``entities`` and locally filter them. This method can be used like so:: entities = EntitySearchMixin(entities, {'name': 'foo'}) In this example, only entities where ``entity.name == 'foo'`` holds true are returned. An arbitrary number of field names and values may be ...
def shareproject(self, project_id, group_id, group_access): """ Allow to share project with group. :param project_id: The ID of a project :param group_id: The ID of a group :param group_access: Level of permissions for sharing :return: True is success """ ...
Allow to share project with group. :param project_id: The ID of a project :param group_id: The ID of a group :param group_access: Level of permissions for sharing :return: True is success
def isrchi(value, ndim, array): """ Search for a given value within an integer array. Return the index of the first matching array entry, or -1 if the key value was not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchi_c.html :param value: Key value to be found in array. ...
Search for a given value within an integer array. Return the index of the first matching array entry, or -1 if the key value was not found. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchi_c.html :param value: Key value to be found in array. :type value: int :param ndim: Dimensio...
def start_after(self, document_fields): """Start query results after a particular document value. The result set will **exclude** the document specified by ``document_fields``. If the current query already has specified a start cursor -- either via this method or :meth:...
Start query results after a particular document value. The result set will **exclude** the document specified by ``document_fields``. If the current query already has specified a start cursor -- either via this method or :meth:`~.firestore_v1beta1.query.Query.start_at` -- this ...
def addTrack(self, track): """ Add a track to be recorded. :param: track: An :class:`aiortc.AudioStreamTrack` or :class:`aiortc.VideoStreamTrack`. """ if track.kind == 'audio': if self.__container.format.name == 'wav': codec_name = 'pcm_s16le' ...
Add a track to be recorded. :param: track: An :class:`aiortc.AudioStreamTrack` or :class:`aiortc.VideoStreamTrack`.
def post(self, request, *args, **kwargs): """ Validates subscription data before creating Subscription message """ # Ensure that we check for the 'data' key in the request object before # attempting to reference it if "data" in request.data: # This is a workaround for...
Validates subscription data before creating Subscription message
def get_slab(self, shift=0, tol=0.1, energy=None): """ This method takes in shift value for the c lattice direction and generates a slab based on the given shift. You should rarely use this method. Instead, it is used by other generation algorithms to obtain all slabs. A...
This method takes in shift value for the c lattice direction and generates a slab based on the given shift. You should rarely use this method. Instead, it is used by other generation algorithms to obtain all slabs. Arg: shift (float): A shift value in Angstrom that determine...
def find_standard_sakefile(settings): """Returns the filename of the appropriate sakefile""" error = settings["error"] if settings["customsake"]: custom = settings["customsake"] if not os.path.isfile(custom): error("Specified sakefile '{}' doesn't exist", custom) sys....
Returns the filename of the appropriate sakefile
def paintEvent(self, event): """Fills the panel background using QPalette.""" if self.isVisible() and self.position != self.Position.FLOATING: # fill background self._background_brush = QBrush(QColor( self.editor.sideareas_color)) self._foreground_pen ...
Fills the panel background using QPalette.
def get_urls(self, **kwargs): """ Ensure the correct host by injecting the current site. """ kwargs["site"] = Site.objects.get(id=current_site_id()) return super(DisplayableSitemap, self).get_urls(**kwargs)
Ensure the correct host by injecting the current site.
def mag_field_motors(RAW_IMU, SENSOR_OFFSETS, ofs, SERVO_OUTPUT_RAW, motor_ofs): '''calculate magnetic field strength from raw magnetometer''' mag_x = RAW_IMU.xmag mag_y = RAW_IMU.ymag mag_z = RAW_IMU.zmag ofs = get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs) if SENSOR_OFFSETS is not None ...
calculate magnetic field strength from raw magnetometer
def bulk_get_or_create(self, data_list): """ data_list is the data to get or create We generate the query and set all the record keys based on passed in queryset Then we loop over each item in the data_list, which has the keys already! No need to generate them. Should save a lot of time...
data_list is the data to get or create We generate the query and set all the record keys based on passed in queryset Then we loop over each item in the data_list, which has the keys already! No need to generate them. Should save a lot of time Use values instead of the whole object, much faster ...
def parse_column_filter(definition): """Parse a `str` of the form 'column>50' Parameters ---------- definition : `str` a column filter definition of the form ``<name><operator><threshold>`` or ``<threshold><operator><name><operator><threshold>``, e.g. ``frequency >= 10``, or ``5...
Parse a `str` of the form 'column>50' Parameters ---------- definition : `str` a column filter definition of the form ``<name><operator><threshold>`` or ``<threshold><operator><name><operator><threshold>``, e.g. ``frequency >= 10``, or ``50 < snr < 100`` Returns ------- ...
def set_states(self, left_state, right_state): """ Checks that the specified paths stay the same over the next `depth` states. """ simgr = self.project.factory.simulation_manager(right_state) simgr.stash(to_stash='right') simgr.active.append(left_state) simgr.sta...
Checks that the specified paths stay the same over the next `depth` states.
def set_token(self, token): """Validate and set token :param token: the token (dict) to set """ if not token: self.token = None return expected_keys = ['token_type', 'refresh_token', 'access_token', 'scope', 'expires_in', 'expires_at'] if not is...
Validate and set token :param token: the token (dict) to set
def mentions_links(uri, s): """ Turns mentions-like strings into HTML links, @uri: /uri/ root for the hashtag-like @s: the #str string you're looking for |@|mentions in -> #str HTML link |<a href="/uri/mention">mention</a>| """ for username, after in mentions_re.findall(s): ...
Turns mentions-like strings into HTML links, @uri: /uri/ root for the hashtag-like @s: the #str string you're looking for |@|mentions in -> #str HTML link |<a href="/uri/mention">mention</a>|
def fix_e271(self, result): """Fix extraneous whitespace around keywords.""" line_index = result['line'] - 1 target = self.source[line_index] offset = result['column'] - 1 fixed = fix_whitespace(target, offset=offset, ...
Fix extraneous whitespace around keywords.
def build_url(base, seg, query=None): """ Create a URL from a list of path segments and an optional dict of query parameters. """ def clean_segment(segment): """ Cleans the segment and encodes to UTF-8 if the segment is unicode. """ segment = segment.strip('/') ...
Create a URL from a list of path segments and an optional dict of query parameters.
def file_list(self, tgt_env): ''' Get file list for the target environment using GitPython ''' files = set() symlinks = {} tree = self.get_tree(tgt_env) if not tree: # Not found, return empty objects return files, symlinks if self.r...
Get file list for the target environment using GitPython
def upload_file(token, channel_name, file_name): """ upload file to a channel """ slack = Slacker(token) slack.files.upload(file_name, channels=channel_name)
upload file to a channel
def consume(self, key, amount=1, rate=None, capacity=None, **kwargs): """Consume an amount for a given key. Non-default rate/capacity can be given to override Throttler defaults. Returns: bool: whether the units could be consumed """ bucket = self.get_bucket(key, ra...
Consume an amount for a given key. Non-default rate/capacity can be given to override Throttler defaults. Returns: bool: whether the units could be consumed
def unlock(self, password): """ The password is used to encrypt this masterpassword. To decrypt the keys stored in the keys database, one must use BIP38, decrypt the masterpassword from the configuration store with the user password, and use the decrypted masterpa...
The password is used to encrypt this masterpassword. To decrypt the keys stored in the keys database, one must use BIP38, decrypt the masterpassword from the configuration store with the user password, and use the decrypted masterpassword to decrypt the BIP38 encrypted pr...
def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=None): """Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file...
Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being emp...
def has_implementation(self, number, arch, abi_list=()): """ Pretty much the intersection of SimLibrary.has_implementation() and SimSyscallLibrary.get(). :param number: The syscall number :param arch: The architecture being worked with, as either a string name or an archinfo...
Pretty much the intersection of SimLibrary.has_implementation() and SimSyscallLibrary.get(). :param number: The syscall number :param arch: The architecture being worked with, as either a string name or an archinfo.Arch :param abi_list: A list of ABI names that could be used ...
def _Backward3_sat_v_P(P, T, x): """Backward equation for region 3 for saturated state, vs=f(P,x) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] x : integer Vapor quality, [-] Returns ------- v : float Specific volume, [m³...
Backward equation for region 3 for saturated state, vs=f(P,x) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] x : integer Vapor quality, [-] Returns ------- v : float Specific volume, [m³/kg] Notes ----- The vapor ...
def batch_query_event_records( self, batch_size: int, filters: List[Tuple[str, Any]] = None, logical_and: bool = True, ) -> Iterator[List[EventRecord]]: """Batch query event records with a given batch size and an optional filter This is a generator fu...
Batch query event records with a given batch size and an optional filter This is a generator function returning each batch to the caller to work with.
def convert_elementwise_add(net, node, module, builder): """Convert an elementwise add layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuil...
Convert an elementwise add layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
def tickets_create_many(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tickets#create-many-tickets" api_path = "/api/v2/tickets/create_many.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/tickets#create-many-tickets
def exec_function(ast, globals_map): """Execute a python code object in the given environment. Args: globals_map: Dictionary to use as the globals context. Returns: locals_map: Dictionary of locals from the environment after execution. """ locals_map = globals_map exec ast in global...
Execute a python code object in the given environment. Args: globals_map: Dictionary to use as the globals context. Returns: locals_map: Dictionary of locals from the environment after execution.
def get(self, block=True, timeout=None, method='pop'): """ If *block* is True, this method blocks until an element can be removed from the deque with the specified *method*. If *block* is False, the function will raise #Empty if no elements are available. # Arguments block (bool): #True to bloc...
If *block* is True, this method blocks until an element can be removed from the deque with the specified *method*. If *block* is False, the function will raise #Empty if no elements are available. # Arguments block (bool): #True to block and wait until an element becomes available, #False otherwi...
def run_pylint(): """run pylint""" from pylint.lint import Run try: Run(sys.argv[1:]) except KeyboardInterrupt: sys.exit(1)
run pylint
def __neighbor_indexes_distance_matrix(self, index_point): """! @brief Return neighbors of the specified object in case of distance matrix. @param[in] index_point (uint): Index point whose neighbors are should be found. @return (list) List of indexes of neighbors in line the conn...
! @brief Return neighbors of the specified object in case of distance matrix. @param[in] index_point (uint): Index point whose neighbors are should be found. @return (list) List of indexes of neighbors in line the connectivity radius.
def _included_frames(frame_list, frame_format): """frame_list should be a list of filenames""" return INCLUDED_FRAMES.format(Nframes=len(frame_list), frame_dir=os.path.dirname(frame_list[0]), frame_format=frame_format)
frame_list should be a list of filenames
def _update_process_resources(self, process, vals): """Updates the resources info in :attr:`processes` dictionary. """ resources = ["cpus"] for r in resources: if not self.processes[process][r]: try: self.processes[process][r] = vals[0]["...
Updates the resources info in :attr:`processes` dictionary.
def publishCommand(self, typeId, deviceId, commandId, msgFormat, data=None, qos=0, on_publish=None): """ Publish a command to a device # Parameters typeId (string) : The type of the device this command is to be published to deviceId (string): The id of the device this command is...
Publish a command to a device # Parameters typeId (string) : The type of the device this command is to be published to deviceId (string): The id of the device this command is to be published to command (string) : The name of the command msgFormat (string) : The format of the com...
def ensure_path_exists(dir_path): """ Make sure that a path exists """ if not os.path.exists(dir_path): os.makedirs(dir_path) return True return False
Make sure that a path exists
def _peek_job(self, pos): """ Return the job currently at position `pos`, but still keep it in the job queue. An IndexError will be raised if that position does not currently exist in the job list. :param int pos: Position of the job to get. :return: The job """ ...
Return the job currently at position `pos`, but still keep it in the job queue. An IndexError will be raised if that position does not currently exist in the job list. :param int pos: Position of the job to get. :return: The job
def translate_key(jsonkey): "helper for translate_*" nombre,pkey,field=ujson.loads(jsonkey) return FieldKey(nombre,tuple(pkey),field)
helper for translate_*
def crc16_nojit(s, crc=0): """CRC16 implementation acording to CCITT standards.""" for ch in bytearray(s): # bytearray's elements are integers in both python 2 and 3 crc = ((crc << 8) & 0xFFFF) ^ _crc16_tab[((crc >> 8) & 0xFF) ^ (ch & 0xFF)] crc &= 0xFFFF return crc
CRC16 implementation acording to CCITT standards.
def get_item_metadata(self, handle): """Return dictionary containing all metadata associated with handle. In other words all the metadata added using the ``add_item_metadata`` method. :param handle: handle for accessing an item before the dataset is frozen ...
Return dictionary containing all metadata associated with handle. In other words all the metadata added using the ``add_item_metadata`` method. :param handle: handle for accessing an item before the dataset is frozen :returns: dictionary containing item metadata
def plotMDS(data, theOrders, theLabels, theColors, theAlphas, theSizes, theMarkers, options): """Plot the MDS data. :param data: the data to plot (MDS values). :param theOrders: the order of the populations to plot. :param theLabels: the names of the populations to plot. :param theColor...
Plot the MDS data. :param data: the data to plot (MDS values). :param theOrders: the order of the populations to plot. :param theLabels: the names of the populations to plot. :param theColors: the colors of the populations to plot. :param theAlphas: the alpha value for the populations to plot. ...
def start(self): """ Make an HTTP request with a specific method """ # TODO : Use Timeout here and _ignore_request_idle from .nurest_session import NURESTSession session = NURESTSession.get_current_session() if self.async: thread = threading.Thread(target=self._make...
Make an HTTP request with a specific method
def get_range(self): """Return the highest and the lowest note in a tuple.""" (min, max) = (100000, -1) for cont in self.bar: for note in cont[2]: if int(note) < int(min): min = note elif int(note) > int(max): ma...
Return the highest and the lowest note in a tuple.
def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None): ''' Make a web call to GoGrid .. versionadded:: 2015.8.0 ''' vm_ = get_configured_provider() apikey = config.get_cloud_config_value( 'apike...
Make a web call to GoGrid .. versionadded:: 2015.8.0
def __query_cmd(self, command, device=None): """Calls a command""" base_url = u'%s&switchcmd=%s' % (self.__homeauto_url_with_sid(), command) if device is None: url = base_url else: url = '%s&ain=%s' % (base_url, device) if self.__debug: print...
Calls a command
def get_container(self, path): """Return single container.""" if not settings.container_permitted(path): raise errors.NotPermittedException( "Access to container \"%s\" is not permitted." % path) return self._get_container(path)
Return single container.
def connect(self): # type: () -> None """ Connect to server Returns: None """ if self.connection_type.lower() == 'ssl': self.server = smtplib.SMTP_SSL(host=self.host, port=self.port, local_hostname=self.local_hostname, ...
Connect to server Returns: None
def get_assessment_admin_session(self): """Gets the ``OsidSession`` associated with the assessment administration service. return: (osid.assessment.AssessmentAdminSession) - an ``AssessmentAdminSession`` raise: OperationFailed - unable to complete request raise: Unimpl...
Gets the ``OsidSession`` associated with the assessment administration service. return: (osid.assessment.AssessmentAdminSession) - an ``AssessmentAdminSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_assessment_admin()`` is ...
def aliases(self): """ Aliases for UBI volume. This propery evaluates to device node itself plus the ``'ubi${INDEX}:${LABEL}'`` string. The latter is used to identify the device in /proc/mounts table, and is not really an alias. """ return ['ubi{}:{}'.format(self.device.p...
Aliases for UBI volume. This propery evaluates to device node itself plus the ``'ubi${INDEX}:${LABEL}'`` string. The latter is used to identify the device in /proc/mounts table, and is not really an alias.
def create(source_name, size, metadata_backend=None, storage_backend=None): """ Creates a thumbnail file and its relevant metadata. Returns a Thumbnail instance. """ if storage_backend is None: storage_backend = backends.storage.get_backend() if metadata_backend is None: metadat...
Creates a thumbnail file and its relevant metadata. Returns a Thumbnail instance.
def validate_arguments(args): """ Validate that the necessary argument for normal or diff analysis are specified. :param: args: Command line arguments namespace """ if args.diff: if not args.output_dir: logger.error('No Output location specified') print_usage() sys.exit(0) # elif not (...
Validate that the necessary argument for normal or diff analysis are specified. :param: args: Command line arguments namespace
def write_bytes(fp, data): """ Write bytes to the file object and returns bytes written. :return: written byte size """ pos = fp.tell() fp.write(data) written = fp.tell() - pos assert written == len(data), 'written=%d, expected=%d' % ( written, len(data) ) return written
Write bytes to the file object and returns bytes written. :return: written byte size
def Serialize(self, writer): """ Serialize full object. Args: writer (neo.IO.BinaryWriter): """ super(SpentCoinState, self).Serialize(writer) writer.WriteUInt256(self.TransactionHash) writer.WriteUInt32(self.TransactionHeight) writer.WriteVar...
Serialize full object. Args: writer (neo.IO.BinaryWriter):
def defBoroCnst(self,BoroCnstArt): ''' Defines the constrained portion of the consumption function as cFuncNowCnst, an attribute of self. Parameters ---------- BoroCnstArt : float or None Borrowing constraint for the minimum allowable assets to end the ...
Defines the constrained portion of the consumption function as cFuncNowCnst, an attribute of self. Parameters ---------- BoroCnstArt : float or None Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borr...
def _validate_response(self, response): """ :param response: requests.models.Response :raises: pybomb.exceptions.InvalidResponseException :raises: pybomb.exceptions.BadRequestException """ try: response.raise_for_status() except HTTPError as http_error...
:param response: requests.models.Response :raises: pybomb.exceptions.InvalidResponseException :raises: pybomb.exceptions.BadRequestException
def from_tibiadata(cls, content, vocation=None): """Builds a highscores object from a TibiaData highscores response. Notes ----- Since TibiaData.com's response doesn't contain any indication of the vocation filter applied, :py:attr:`vocation` can't be determined from the respons...
Builds a highscores object from a TibiaData highscores response. Notes ----- Since TibiaData.com's response doesn't contain any indication of the vocation filter applied, :py:attr:`vocation` can't be determined from the response, so the attribute must be assigned manually. If t...
def list_my(self): """ Find organization that has the current identity as the owner or as the member """ org_list = self.call_contract_command("Registry", "listOrganizations", []) rez_owner = [] rez_member = [] for idx, org_id in enumerate(org_list): (found, org_id,...
Find organization that has the current identity as the owner or as the member
def xmlns(source): """ Returns a map of prefix to namespace for the given XML file. """ namespaces = {} events=("end", "start-ns", "end-ns") for (event, elem) in iterparse(source, events): if event == "start-ns": prefix, ns = elem namespaces[prefix] = ns ...
Returns a map of prefix to namespace for the given XML file.
def target_Orange_table(self): ''' Returns the target table as an Orange example table. :rtype: orange.ExampleTable ''' table, cls_att = self.db.target_table, self.db.target_att if not self.db.orng_tables: return self.convert_table(table, cls_att=cls_att)...
Returns the target table as an Orange example table. :rtype: orange.ExampleTable
def get_attachment(self, project, build_id, timeline_id, record_id, type, name, **kwargs): """GetAttachment. [Preview API] Gets a specific attachment. :param str project: Project ID or project name :param int build_id: The ID of the build. :param str timeline_id: The ID of the ti...
GetAttachment. [Preview API] Gets a specific attachment. :param str project: Project ID or project name :param int build_id: The ID of the build. :param str timeline_id: The ID of the timeline. :param str record_id: The ID of the timeline record. :param str type: The type...
def rewind(self, count): """Rewind index.""" if count > self._index: # pragma: no cover raise ValueError("Can't rewind past beginning!") self._index -= count
Rewind index.
def get_language_from_abbr(self, abbr): """Get language full name from abbreviation.""" for language in self.user_data.languages: if language['language'] == abbr: return language['language_string'] return None
Get language full name from abbreviation.
def collapse_if_tuple(abi): """Converts a tuple from a dict to a parenthesized list of its types. >>> from eth_utils.abi import collapse_if_tuple >>> collapse_if_tuple( ... { ... 'components': [ ... {'name': 'anAddress', 'type': 'address'}, ... {'name': '...
Converts a tuple from a dict to a parenthesized list of its types. >>> from eth_utils.abi import collapse_if_tuple >>> collapse_if_tuple( ... { ... 'components': [ ... {'name': 'anAddress', 'type': 'address'}, ... {'name': 'anInt', 'type': 'uint256'}, ......
def fw_romaji_lt(full, regular): ''' Generates a lookup table with the fullwidth rōmaji characters on the left side, and the regular rōmaji characters as the values. ''' lt = {} for n in range(len(full)): fw = full[n] reg = regular[n] lt[fw] = reg return lt
Generates a lookup table with the fullwidth rōmaji characters on the left side, and the regular rōmaji characters as the values.
def _facet_counts(items): """Returns facet counts as dict. Given the `items()` on the raw dictionary from Elasticsearch this processes it and returns the counts keyed on the facet name provided in the original query. """ facets = {} for name, data in items: facets[name] = FacetResu...
Returns facet counts as dict. Given the `items()` on the raw dictionary from Elasticsearch this processes it and returns the counts keyed on the facet name provided in the original query.
def license(self, value=None): """No arguments: Get the document's license from metadata Argument: Set the document's license in metadata """ if not (value is None): if (self.metadatatype == "native"): self.metadata['license'] = value else: ...
No arguments: Get the document's license from metadata Argument: Set the document's license in metadata
def next(self): """NEXT command. """ code, message = self.command("NEXT") if code != 223: raise NNTPReplyError(code, message) parts = message.split(None, 3) try: article = int(parts[0]) ident = parts[1] except (IndexError, Valu...
NEXT command.
def scroll(self): ''' Perfrom scroll action. Usage: d().scroll(steps=50) # default vertically and forward d().scroll.horiz.forward(steps=100) d().scroll.vert.backward(steps=100) d().scroll.horiz.toBeginning(steps=100, max_swipes=100) d().scroll.vert.toEnd(...
Perfrom scroll action. Usage: d().scroll(steps=50) # default vertically and forward d().scroll.horiz.forward(steps=100) d().scroll.vert.backward(steps=100) d().scroll.horiz.toBeginning(steps=100, max_swipes=100) d().scroll.vert.toEnd(steps=100) d().scroll.horiz.to...
def _get_linked_entities(self) -> Dict[str, Dict[str, Tuple[str, str, List[int]]]]: """ This method gets entities from the current utterance finds which tokens they are linked to. The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these entities later ...
This method gets entities from the current utterance finds which tokens they are linked to. The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these entities later for updating the valid actions and the grammar.
def log(self, *args, **kwargs): """Log a statement from this component""" func = inspect.currentframe().f_back.f_code # Dump the message + the name of this function to the log. if 'exc' in kwargs and kwargs['exc'] is True: exc_type, exc_obj, exc_tb = exc_info() ...
Log a statement from this component
def _fetchSequence(ac, startIndex=None, endIndex=None): """Fetch sequences from NCBI using the eself interface. An interbase interval may be optionally provided with startIndex and endIndex. NCBI eself will return just the requested subsequence, which might greatly reduce payload sizes (especially with...
Fetch sequences from NCBI using the eself interface. An interbase interval may be optionally provided with startIndex and endIndex. NCBI eself will return just the requested subsequence, which might greatly reduce payload sizes (especially with chromosome-scale sequences). When wrapped is True, return ...
def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) # urlpars...
Given a URL that may or may not have a scheme, prepend the given scheme. Does not replace a present scheme with the one provided as an argument. :rtype: str
def _combine_variant_collections(cls, combine_fn, variant_collections, kwargs): """ Create a single VariantCollection from multiple different collections. Parameters ---------- cls : class Should be VariantCollection combine_fn : function Functi...
Create a single VariantCollection from multiple different collections. Parameters ---------- cls : class Should be VariantCollection combine_fn : function Function which takes any number of sets of variants and returns some combination of them (typi...
def eth_call(self, from_, to=None, gas=None, gas_price=None, value=None, data=None, block=BLOCK_TAG_LATEST): """https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_call :param from_: From account address :type from_: str :param to: To account address (o...
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_call :param from_: From account address :type from_: str :param to: To account address (optional) :type to: str :param gas: Gas amount for current transaction (optional) :type gas: int :param gas_price: Gas pr...
def fit_spectrum(self, specFunc, initPars, freePars=None): """ Fit for the free parameters of a spectral function Parameters ---------- specFunc : `~fermipy.spectrum.SpectralFunction` The Spectral Function initPars : `~numpy.ndarray` The initial values o...
Fit for the free parameters of a spectral function Parameters ---------- specFunc : `~fermipy.spectrum.SpectralFunction` The Spectral Function initPars : `~numpy.ndarray` The initial values of the parameters freePars : `~numpy.ndarray` ...
def _initialize(self): """Set up and normalize initial data once input data is specified.""" self.y_transform = self.y - numpy.mean(self.y) self.y_transform /= numpy.std(self.y_transform) self.x_transforms = [numpy.zeros(len(self.y)) for _xi in self.x] self._compute_sorted_indice...
Set up and normalize initial data once input data is specified.
def expr_code(self, expr): """Generate a Python expression for `expr`.""" if "|" in expr: pipes = expr.split("|") code = self.expr_code(pipes[0]) for func in pipes[1:]: self.all_vars.add(func) code = "c_%s(%s)" % (func, code) el...
Generate a Python expression for `expr`.
def delete(self, doc_id: str) -> bool: """Delete a document with id.""" try: self.instance.delete(self.index, self.doc_type, doc_id) except RequestError as ex: logging.error(ex) return False else: return True
Delete a document with id.
def _add_childTnLst(self): """Add `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant. Any existing `p:timing` child element is ruthlessly removed and replaced. """ self.remove(self.get_or_add_timing()) timing = parse_xml(self._childTnLst_timing_xml()) self....
Add `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant. Any existing `p:timing` child element is ruthlessly removed and replaced.
def ipa_substrings(unicode_string, single_char_parsing=False): """ Return a list of (non-empty) substrings of the given string, where each substring is either: 1. the longest Unicode string starting at the current index representing a (known) valid IPA character, or 2. a single Unicode c...
Return a list of (non-empty) substrings of the given string, where each substring is either: 1. the longest Unicode string starting at the current index representing a (known) valid IPA character, or 2. a single Unicode character (which is not IPA valid). If ``single_char_parsing`` is ``Fal...
def cosinebell(n, fraction): """Return a cosine bell spanning n pixels, masking a fraction of pixels Parameters ---------- n : int Number of pixels. fraction : float Length fraction over which the data will be masked. """ mask = np.ones(n) nmasked = int(fraction * n) ...
Return a cosine bell spanning n pixels, masking a fraction of pixels Parameters ---------- n : int Number of pixels. fraction : float Length fraction over which the data will be masked.
def polygons_obb(polygons): """ Find the OBBs for a list of shapely.geometry.Polygons """ rectangles = [None] * len(polygons) transforms = [None] * len(polygons) for i, p in enumerate(polygons): transforms[i], rectangles[i] = polygon_obb(p) return np.array(transforms), np.array(recta...
Find the OBBs for a list of shapely.geometry.Polygons
def sed_or_dryrun(*args, **kwargs): """ Wrapper around Fabric's contrib.files.sed() to give it a dryrun option. http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.sed """ dryrun = get_dryrun(kwargs.get('dryrun')) if 'dryrun' in kwargs: del kwargs['dryrun'] ...
Wrapper around Fabric's contrib.files.sed() to give it a dryrun option. http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.sed
def combined_analysis(using): """ Combine the analysis in ES with the analysis defined in Python. The one in Python takes precedence """ python_analysis = collect_analysis(using) es_analysis = existing_analysis(using) if es_analysis == DOES_NOT_EXIST: return python_analysis # we...
Combine the analysis in ES with the analysis defined in Python. The one in Python takes precedence
def type_map(gtype, fn): """Map fn over all child types of gtype.""" cb = ffi.callback('VipsTypeMap2Fn', fn) return vips_lib.vips_type_map(gtype, cb, ffi.NULL, ffi.NULL)
Map fn over all child types of gtype.
def clean_restricted_chars(path, restricted_chars=restricted_chars): ''' Get path without restricted characters. :param path: path :return: path without restricted characters :rtype: str or unicode (depending on given path) ''' for character in restricted_chars: path = path.replace(...
Get path without restricted characters. :param path: path :return: path without restricted characters :rtype: str or unicode (depending on given path)