text
stringlengths
81
112k
A wrapper over Model.post() that handles the case where a Library has a PairedBarcode and the user may have supplied the PairedBarcode in the form of index1-index2, i.e. GATTTCCA-GGCGTCGA. This isn't the PairedBarcode's record name or a record ID, thus Model.post() won't be able to figure out ...
Calls the SequencingRequest's get_library_barcode_sequence_hash server-side endpoint to create a hash of the form {LibraryID -> barcode_sequence} for all Libraries on the SequencingRequest. Args: inverse: `bool`. True means to inverse the key and value pairs such that the barcode ...
Generates a dict. where each key is a Library ID on the SequencingRequest and each value is the associated SequencingResult. Libraries that aren't yet with a SequencingResult are not inlcuded in the dict. def library_sequencing_results(self): """ Generates a dict. where each key is a Li...
Unarchives the user with the specified user ID. Args: user_id: `int`. The ID of the user to unarchive. Returns: `NoneType`: None. def unarchive_user(self, user_id): """Unarchives the user with the specified user ID. Args: user_id: `int`. The ID of ...
Removes the user's existing API key, if present, and sets the current instance's 'api_key' attribute to the empty string. Returns: `NoneType`: None. def remove_api_key(self): """ Removes the user's existing API key, if present, and sets the current instance's 'api_key' ...
basesWave: Bases wavelength must be at rest def generate_synthObs(self, bases_wave, bases_flux, basesCoeff, Av_star, z_star, sigma_star, resample_range = None, resample_int = 1): '''basesWave: Bases wavelength must be at rest''' nbases = basesCoeff.shape[0] bases_w...
Processes the current transaction Sends an HTTP request to the PAYDUNYA API server def _process(self, resource=None, data={}): """Processes the current transaction Sends an HTTP request to the PAYDUNYA API server """ # use object's data if no data is passed _data = dat...
Add a custom HTTP header to the client's request headers def add_header(self, header): """Add a custom HTTP header to the client's request headers""" if type(header) is dict: self._headers.update(header) else: raise ValueError( "Dictionary expected, got '...
Generate changelog from commit messages. def changelog_cli(ctx): # type: () -> None """ Generate changelog from commit messages. """ if ctx.invoked_subcommand: return from peltak.core import shell from . import logic shell.cprint(logic.changelog())
Convert the Argument object to a tuple use in :meth:`~argparse.ArgumentParser.add_argument` calls on the parser def convert_to_argument(self): ''' Convert the Argument object to a tuple use in :meth:`~argparse.ArgumentParser.add_argument` calls on the parser ''' field_list = [ ...
Return the default generated name to store value on the parser for this option. eg. An option *['-s', '--use-ssl']* will generate the *use_ssl* name Returns: str: the default name of the option def get_default_name(self): ''' Return the default generated name to store valu...
Construct filename based on the attributes. Parameters ---------- base_dir : Path path of the root directory. If specified, the return value is a Path, with base_dir / sub-XXX / (ses-XXX /) modality / filename otherwise the return value is a string. m...
Select elements of the TSV, using python filter and map. Parameters ---------- filter_lambda : function function to filter the tsv rows (the function needs to return True/False) map_lambda : function function to select the tsv columns Returns ---...
Authenticate application and get token bearer. Isogeo API uses oAuth 2.0 protocol (https://tools.ietf.org/html/rfc6749) see: http://help.isogeo.com/api/fr/authentication/groupsapps.html :param str client_id: application oAuth2 identifier :param str client_secret: application oAuth2 sec...
Check API Bearer token validity. Isogeo ID delivers authentication bearers which are valid during a certain time. So this decorator checks the validity of the token comparing with actual datetime (UTC) and renews it if necessary. See: http://tools.ietf.org/html/rfc6750#section-2 ...
Search within the resources shared to the application. It's the main method to use. :param str token: API auth token - DEPRECATED: token is now automatically included :param str query: search terms and semantic filters. Equivalent of **q** parameter in Isogeo API. It could be a simple...
Get complete or partial metadata about one specific resource. :param str token: API auth token :param str id_resource: metadata UUID to get :param list include: subresources that should be included. Must be a list of strings. Available values: 'isogeo.SUBRESOURCES' :param str p...
Get information about shares which feed the application. :param str token: API auth token :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). def shares(self, token: dict = None, prot: str = "https") -> dict: """Get information about shares which feed th...
Get information about a specific share and its applications. :param str token: API auth token :param str share_id: share UUID :param bool augment: option to improve API response by adding some tags on the fly. :param str prot: https [DEFAULT] or http (use it only for d...
Get information about licenses owned by a specific workgroup. :param str token: API auth token :param str owner_id: workgroup UUID :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). def licenses( self, token: dict = None, owner_id: str = None, p...
Get details about a specific license. :param str token: API auth token :param str license_id: license UUID :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). def license(self, license_id: str, token: dict = None, prot: str = "https") -> dict: ""...
Get list of available thesauri. :param str token: API auth token :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). def thesauri(self, token: dict = None, prot: str = "https") -> dict: """Get list of available thesauri. :param str token: API au...
Get a thesaurus. :param str token: API auth token :param str thez_id: thesaurus UUID :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). def thesaurus( self, token: dict = None, thez_id: str = "1616597fbc4348c8b11ef9d59cf594c8", ...
Search for keywords within a specific thesaurus. :param str token: API auth token :param str thez_id: thesaurus UUID :param str query: search terms :param int offset: pagination start :param str order_by: sort criteria. Available values : - count.group, ...
Download hosted resource. :param str token: API auth token :param dict resource_link: link dictionary :param bool encode_clean: option to ensure a clean filename and avoid OS errors :param str proxy_url: proxy to use to download :param str prot: https [DEFAULT] or http ...
Get resource exported into XML ISO 19139. :param str token: API auth token :param str id_resource: metadata UUID to export :param str proxy_url: proxy to use to download :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). def xml19139( se...
Add shares list to the tags attributes in search results. :param dict tags: tags dictionary from a search request def add_tags_shares(self, tags: dict = dict()): """Add shares list to the tags attributes in search results. :param dict tags: tags dictionary from a search request """ ...
Get information about the application declared on Isogeo. :param str token: API auth token :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). def get_app_properties(self, token: dict = None, prot: str = "https"): """Get information about the application...
Get environment directives which represent INSPIRE limitations. :param str token: API auth token :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). def get_directives(self, token: dict = None, prot: str = "https") -> dict: """Get environment directives ...
Get available coordinate systems in Isogeo API. :param str token: API auth token :param str srs_code: code of a specific coordinate system :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). def get_coordinate_systems( self, token: dict = None, s...
Get formats. :param str token: API auth token :param str format_code: code of a specific format :param str prot: https [DEFAULT] or http (use it only for dev and tracking needs). def get_formats( self, token: dict = None, format_code: str = None, prot: str = "https" ) -> d...
Parses boolean value :param v: Input string :param default: Default value if exceptions=False :param exceptions: Raise exception on error or not :return: bool def parse_bool(v, default=None, exceptions: bool=True) -> bool: """ Parses boolean value :param v: Input string :param default: ...
Parses datetime :param v: Input string :param default: Default value if exceptions=False :param tz: Default pytz timezone or None if utc :param exceptions: Raise exception on error or not :return: datetime def parse_datetime(v, default=None, tz=None, exceptions: bool=True) -> datetime: """ ...
Converts a string to a boolean (see CONVERTERS). There is a converter function for each column type. Boolean strings are independent of case. Values interpreted as True are: "yes", "true", "on", "1". values interpreted as False are "no", "false", "off", "0". Any other value will result in a ValueError....
Given the file header line (or one provided when the object is instantiated) this method populates the ``self._converters`` array, a list of type converters indexed by the column name. :param hdr: The header line. :raises: ContentError for any formatting problems :raises: Unkno...
Search datasets within uData portal. def search_datasets( self, license=None, format=None, query=None, featured=None, owner=None, organization=None, badge=None, reuses=None, page_size=20, x_fields=None, ): """Search dat...
Get different filters values as dicts. def get_filters_values(self): """Get different filters values as dicts.""" # DATASETS -- # badges self._DST_BADGES = requests.get(self.base_url + "datasets/badges/").json() # licences self._DST_LICENSES = { l.get("id"): ...
Deploy the app to AppEngine. Args: app_id (str): AppEngine App ID. Overrides config value app_id if given. version (str): AppEngine project version. Overrides config values if given. promote (bool): If set to **True** promote the current remote app versio...
Run devserver. Args: port (int): Port on which the app will be served. admin_port (int): Port on which the admin interface is served. clear (bool): If set to **True**, clear the datastore on startup. def devserver(port, admin_port, clear): # type: (i...
Setup AppEngine SDK on CircleCI def setup_ci(): # type: () -> None """ Setup AppEngine SDK on CircleCI """ gcloud_path = shell.run('which gcloud', capture=True).stdout.strip() sdk_path = normpath(join(gcloud_path, '../../platform/google_appengine')) gcloud_cmd = gcloud_path + ' --quiet' if not...
Mark function as experimental. Args: fn (FunctionType): The command function to decorate. def mark_experimental(fn): # type: (FunctionType) -> FunctionType """ Mark function as experimental. Args: fn (FunctionType): The command function to decorate. """ ...
Mark command as deprecated. Args: replaced_by (str): The command that deprecated this command and should be used instead. def mark_deprecated(replaced_by): # type: (Text) -> FunctionType """ Mark command as deprecated. Args: replaced_by (str): The command that ...
Split the given iterable into batches. Args: iterable (Iterable[Any]): The iterable you want to split into batches. batch_size (int): The size of each bach. The last batch will be probably smaller (if the number of elements cannot be equally divided. Returns...
Dump data to a YAML string/file. Args: data (YamlData): The data to serialize as YAML. stream (TextIO): The file-like object to save to. If given, this function will write the resulting YAML to that stream. Returns: str: The YAML string. def yaml_du...
Clear result cache on the given function. If the function has no cached result, this call will do nothing. Args: fn (FunctionType): The function whose cache should be cleared. def clear(cls, fn): # type: (FunctionType) -> None """ Clear result cache on the ...
Start working on a new feature by branching off develop. This will create a new branch off develop called feature/<name>. Args: name (str): The name of the new feature. def start(name): # type: (str) -> None """ Start working on a new feature by branching off develop. This wi...
Update the feature with updates committed to develop. This will merge current develop into the current branch. def update(): # type: () -> None """ Update the feature with updates committed to develop. This will merge current develop into the current branch. """ branch = git.current_branch(re...
Merge current feature branch into develop. def finish(): # type: () -> None """ Merge current feature branch into develop. """ pretend = context.get('pretend', False) if not pretend and (git.staged() or git.unstaged()): log.err( "You have uncommitted changes in your repo!\n" ...
Cleanup a remotely merged branch. def merged(): # type: () -> None """ Cleanup a remotely merged branch. """ base_branch = common.get_base_branch() branch = git.current_branch(refresh=True) common.assert_branch_type('task') # Pull feature branch with the merged task common.git_checkout(ba...
Call a Mutagen function with appropriate error handling. `action` is a string describing what the function is trying to do, and `path` is the relevant filename. The rest of the arguments describe the callable to invoke. We require at least Mutagen 1.33, where `IOError` is *never* used, neither for...
Try to covert val to out_type but never raise an exception. If the value can't be converted, then a sensible default value is returned. out_type should be bool, int, or unicode; otherwise, the value is just passed through. def _safe_cast(out_type, val): """Try to covert val to out_type but never raise ...
Unpack image data from a WM/Picture tag. Return a tuple containing the MIME type, the raw image data, a type indicator, and the image's description. This function is treated as "untrusted" and could throw all manner of exceptions (out-of-bounds, etc.). We should clean this up sometime so that the f...
Pack image data for a WM/Picture tag. def _pack_asf_image(mime, data, type=3, description=""): """Pack image data for a WM/Picture tag. """ tag_data = struct.pack('<bi', type, len(data)) tag_data += mime.encode("utf-16-le") + b'\x00\x00' tag_data += description.encode("utf-16-le") + b'\x00\x00' ...
Convert a Sound Check bytestring value to a (gain, peak) tuple as used by ReplayGain. def _sc_decode(soundcheck): """Convert a Sound Check bytestring value to a (gain, peak) tuple as used by ReplayGain. """ # We decode binary data. If one of the formats gives us a text # string, interpret it as...
Encode ReplayGain gain/peak values as a Sound Check string. def _sc_encode(gain, peak): """Encode ReplayGain gain/peak values as a Sound Check string. """ # SoundCheck stores the peak value as the actual value of the # sample, rather than the percentage of full scale that RG uses, so # we do a simp...
Return the MIME type of the image data (a bytestring). def image_mime_type(data): """Return the MIME type of the image data (a bytestring). """ # This checks for a jpeg file with only the magic bytes (unrecognized by # imghdr.what). imghdr.what returns none for that type of file, so # _wider_test_j...
Given a raw value stored on a Mutagen object, decode and return the represented value. def deserialize(self, mutagen_value): """Given a raw value stored on a Mutagen object, decode and return the represented value. """ if self.suffix and isinstance(mutagen_value, six.text_type) ...
Assign the value for the field using this style. def set(self, mutagen_file, value): """Assign the value for the field using this style. """ self.store(mutagen_file, self.serialize(value))
Convert the external Python value to a type that is suitable for storing in a Mutagen file object. def serialize(self, value): """Convert the external Python value to a type that is suitable for storing in a Mutagen file object. """ if isinstance(value, float) and self.as_type i...
Get a list of all values for the field using this style. def get_list(self, mutagen_file): """Get a list of all values for the field using this style. """ return [self.deserialize(item) for item in self.fetch(mutagen_file)]
Set all values for the field using this style. `values` should be an iterable. def set_list(self, mutagen_file, values): """Set all values for the field using this style. `values` should be an iterable. """ self.store(mutagen_file, [self.serialize(value) for value in values])
Convert APIC frame into Image. def deserialize(self, apic_frame): """Convert APIC frame into Image.""" return Image(data=apic_frame.data, desc=apic_frame.desc, type=apic_frame.type)
Return an APIC frame populated with data from ``image``. def serialize(self, image): """Return an APIC frame populated with data from ``image``. """ assert isinstance(image, Image) frame = mutagen.id3.Frames[self.key]() frame.data = image.data frame.mime = image.mime_typ...
Turn a Image into a base64 encoded FLAC picture block. def serialize(self, image): """Turn a Image into a base64 encoded FLAC picture block. """ pic = mutagen.flac.Picture() pic.data = image.data pic.type = image.type_index pic.mime = image.mime_type pic.desc = i...
``pictures`` is a list of mutagen.flac.Picture instances. def store(self, mutagen_file, pictures): """``pictures`` is a list of mutagen.flac.Picture instances. """ mutagen_file.clear_pictures() for pic in pictures: mutagen_file.add_picture(pic)
Turn a Image into a mutagen.flac.Picture. def serialize(self, image): """Turn a Image into a mutagen.flac.Picture. """ pic = mutagen.flac.Picture() pic.data = image.data pic.type = image.type_index pic.mime = image.mime_type pic.desc = image.desc or u'' r...
Remove all images from the file. def delete(self, mutagen_file): """Remove all images from the file. """ for cover_tag in self.TAG_NAMES.values(): try: del mutagen_file[cover_tag] except KeyError: pass
Yields the list of storage styles of this field that can handle the MediaFile's format. def styles(self, mutagen_file): """Yields the list of storage styles of this field that can handle the MediaFile's format. """ for style in self._styles: if mutagen_file.__class__...
Get an appropriate "null" value for this field's type. This is used internally when setting the field to None. def _none_value(self): """Get an appropriate "null" value for this field's type. This is used internally when setting the field to None. """ if self.out_type == int: ...
Get a 3-item sequence representing the date consisting of a year, month, and day number. Each number is either an integer or None. def _get_date_tuple(self, mediafile): """Get a 3-item sequence representing the date consisting of a year, month, and day number. Each number is either an i...
Set the value of the field given a year, month, and day number. Each number can be an integer or None to indicate an unset component. def _set_date_tuple(self, mediafile, year, month=None, day=None): """Set the value of the field given a year, month, and day number. Each number can be a...
Write the object's tags back to the file. May throw `UnreadableFileError`. def save(self): """Write the object's tags back to the file. May throw `UnreadableFileError`. """ # Possibly save the tags to ID3v2.3. kwargs = {} if self.id3v23: id3 = self.mg...
Get the names of all writable properties that reflect metadata tags (i.e., those that are instances of :class:`MediaField`). def fields(cls): """Get the names of all writable properties that reflect metadata tags (i.e., those that are instances of :class:`MediaField`). "...
Get a sort key for a field name that determines the order fields should be written in. Fields names are kept unchanged, unless they are instances of :class:`DateItemField`, in which case `year`, `month`, and `day` are replaced by `date0`, `date1`, and `date2`, respectively, to m...
Get the names of all writable metadata fields, sorted in the order that they should be written. This is a lexicographic order, except for instances of :class:`DateItemField`, which are sorted in year-month-day order. def sorted_fields(cls): """Get the names of all writable meta...
Add a field to store custom tags. :param name: the name of the property the field is accessed through. It must not already exist on this class. :param descriptor: an instance of :class:`MediaField`. def add_field(cls, name, descriptor): """Add a field to store custom tags...
Set all field values from a dictionary. For any key in `dict` that is also a field to store tags the method retrieves the corresponding value from `dict` and updates the `MediaFile`. If a key has the value `None`, the corresponding property is deleted from the `MediaFile`. def update(s...
The audio's sample rate (an int). def samplerate(self): """The audio's sample rate (an int).""" if hasattr(self.mgfile.info, 'sample_rate'): return self.mgfile.info.sample_rate elif self.type == 'opus': # Opus is always 48kHz internally. return 48000 ...
The number of bits per sample in the audio encoding (an int). Only available for certain file formats (zero where unavailable). def bitdepth(self): """The number of bits per sample in the audio encoding (an int). Only available for certain file formats (zero where unavailable). ...
The number of channels in the audio (an int). def channels(self): """The number of channels in the audio (an int).""" if hasattr(self.mgfile.info, 'channels'): return self.mgfile.info.channels return 0
The number of bits per seconds used in the audio coding (an int). If this is provided explicitly by the compressed file format, this is a precise reflection of the encoding. Otherwise, it is estimated from the on-disk file size. In this case, some imprecision is possible because the file...
Reads a FITS file and returns a 2D numpy array of the data. Use hdu to specify which HDU you want (default = primary = 0) def fromfits(infilename, hdu = 0, verbose = True): """ Reads a FITS file and returns a 2D numpy array of the data. Use hdu to specify which HDU you want (default = primary = 0) ...
Takes a 2D numpy array and write it into a FITS file. If you specify a header (pyfits format, as returned by fromfits()) it will be used for the image. You can give me boolean numpy arrays, I will convert them into 8 bit integers. def tofits(outfilename, pixelarray, hdr = None, verbose = True): """ Tak...
Returns a 2x2-subsampled version of array a (no interpolation, just cutting pixels in 4). The version below is directly from the scipy cookbook on rebinning : U{http://www.scipy.org/Cookbook/Rebinning} There is ndimage.zoom(cutout.array, 2, order=0, prefilter=False), but it makes funny borders. def subsamp...
Wrapper around rebin that actually rebins 2 by 2 def rebin2x2(a): """ Wrapper around rebin that actually rebins 2 by 2 """ inshape = np.array(a.shape) if not (inshape % 2 == np.zeros(2)).all(): # Modulo check to see if size is even raise RuntimeError, "I want even image shapes !" ...
Finds and labels the cosmic "islands" and returns a list of dicts containing their positions. This is made on purpose for visualizations a la f2n.drawstarslist, but could be useful anyway. def labelmask(self, verbose = None): """ Finds and labels the cosmic "islands" and returns a list of dicts...
Returns a morphologically dilated copy of the current mask. size = 3 or 5 decides how to dilate. def getdilatedmask(self, size=3): """ Returns a morphologically dilated copy of the current mask. size = 3 or 5 decides how to dilate. """ if size == 3: dilmask =...
Given the mask, we replace the actual problematic pixels with the masked 5x5 median value. This mimics what is done in L.A.Cosmic, but it's a bit harder to do in python, as there is no readymade masked median. So for now we do a loop... Saturated stars, if calculated, are also masked : they are ...
Uses the satlevel to find saturated stars (not cosmics !), and puts the result as a mask in self.satstars. This can then be used to avoid these regions in cosmic detection and cleaning procedures. Slow ... def findsatstars(self, verbose = None): """ Uses the satlevel to find saturated s...
Returns the mask of saturated stars after finding them if not yet done. Intended mainly for external use. def getsatstars(self, verbose = None): """ Returns the mask of saturated stars after finding them if not yet done. Intended mainly for external use. """ if verbose =...
Estimates the background level. This could be used to fill pixels in large cosmics. def guessbackgroundlevel(self): """ Estimates the background level. This could be used to fill pixels in large cosmics. """ if self.backgroundlevel == None: self.backgroundlevel = np.median(s...
Performs one iteration of the L.A.Cosmic algorithm. It operates on self.cleanarray, and afterwards updates self.mask by adding the newly detected cosmics to the existing self.mask. Cleaning is not made automatically ! You have to call clean() after each iteration. This way you can run it...
Full artillery :-) - Find saturated stars - Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found) Stops if no cosmics are found or if maxiter is reached. def run(self, maxiter = 4, verbose = False): """ Full artillery :-) - Find saturate...
Search your Django project root. returns: - path:string Django project root path def search_project_root(): """ Search your Django project root. returns: - path:string Django project root path """ while True: current = os.getcwd(...
Search your Django application root returns: - (String) Django application root path def search_app_root(): """ Search your Django application root returns: - (String) Django application root path """ while True: current = os.getcwd...
Judge where current working directory is in Django application or not. returns: - (Bool) cwd is in app dir returns True def in_app() -> bool: """ Judge where current working directory is in Django application or not. returns: - (Bool) cwd is in app dir returns ...
Calls update_cached_fields() for each object passed in as argument. Supports also iterable objects by checking __iter__ attribute. :param args: List of objects :return: None def update_cached_fields(*args): """ Calls update_cached_fields() for each object passed in as argument. Supports also it...
Call on pre_save signal for objects (to automatically refresh on save). :param update_fields: list of fields to update def update_cached_fields_pre_save(self, update_fields: list): """ Call on pre_save signal for objects (to automatically refresh on save). :param update_fields: list of ...
Start working on a new hotfix. This will create a new branch off master called hotfix/<name>. Args: name (str): The name of the new feature. def start(name): # type: (str) -> None """ Start working on a new hotfix. This will create a new branch off master called hotfix/<name>...
Merge current feature into develop. def finish(): # type: () -> None """ Merge current feature into develop. """ pretend = context.get('pretend', False) if not pretend and (git.staged() or git.unstaged()): log.err( "You have uncommitted changes in your repo!\n" "You nee...