INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Provide a transactional scope around a series of operations.
def session_scope(session_cls=None): """Provide a transactional scope around a series of operations.""" session = session_cls() if session_cls else Session() try: yield session session.commit() except Exception: session.rollback() raise finally: session.close(...
Opens a file dialog to get the path to a file and put tha tpath in the correct textbox
def open_file_dialog(self): """ Opens a file dialog to get the path to a file and put tha tpath in the correct textbox """ dialog = QtWidgets.QFileDialog sender = self.sender() if sender == self.btn_open_source: textbox = self.source_path elif sender =...
Resets the dialog box by finding all avaliable scripts that can be imported in the input folder :param folder: folder in which to find scripts
def reset_avaliable(self, folder): """ Resets the dialog box by finding all avaliable scripts that can be imported in the input folder :param folder: folder in which to find scripts """ try: self.list_script_model.removeRows(0, self.list_script_model.rowCount()) ...
Forces a reset if the class type is changed from instruments to scripts or vice versa
def class_type_changed(self): """ Forces a reset if the class type is changed from instruments to scripts or vice versa """ if self.source_path.text(): self.reset_avaliable(self.source_path.text())
fills a tree with nested parameters Args: tree: QtGui.QTreeView to fill parameters: dictionary or Parameter object which contains the information to use to fill
def fill_list(self, list, input_list): """ fills a tree with nested parameters Args: tree: QtGui.QTreeView to fill parameters: dictionary or Parameter object which contains the information to use to fill """ for name in input_list: # print(inde...
finds apropriate utxo's to include in rawtx, while being careful to never spend old transactions with a lot of coin age. Argument is intiger, returns list of apropriate UTXO's
def select_inputs(self, address: str, amount: int) -> dict: '''finds apropriate utxo's to include in rawtx, while being careful to never spend old transactions with a lot of coin age. Argument is intiger, returns list of apropriate UTXO's''' utxos = [] utxo_sum = Decimal(0) ...
list UTXOs modified version to allow filtering by address.
def listunspent( self, address: str="", minconf: int=1, maxconf: int=999999, ) -> list: '''list UTXOs modified version to allow filtering by address. ''' if address: return self.req("listunspent", [minconf, maxconf, [address]]) ret...
Compute pairwise distances between two sequences (raw strings).
def score_pairwise(aseq, bseq): """Compute pairwise distances between two sequences (raw strings).""" assert len(aseq) == len(bseq) # Affine gap penalties -- default values from EMBOSS needle/water GAP_OPEN = -10.0 GAP_EXTEND = -0.5 GAP_CHARS = frozenset('-.') score = 0.0 in_gap = True...
Compute absolute identity (# matching sites) between sequence strings.
def identity_abs(aseq, bseq): """Compute absolute identity (# matching sites) between sequence strings.""" assert len(aseq) == len(bseq) return sum(a == b for a, b in zip(aseq, bseq) if not (a in '-.' and b in '-.'))
Compute absolute identity (# matching sites) between sequence strings.
def identity_avg(aseq, bseq): """Compute absolute identity (# matching sites) between sequence strings.""" match = identity_abs(aseq, bseq) alen = len(aseq.replace('-', '').replace('.', '')) blen = len(bseq.replace('-', '').replace('.', '')) avg_len = 0.5 * (alen + blen) return match / avg_len
Command line tool to convert from Remind to iCalendar
def rem2ics(): """Command line tool to convert from Remind to iCalendar""" # pylint: disable=maybe-no-member from argparse import ArgumentParser, FileType from dateutil.parser import parse from sys import stdin, stdout parser = ArgumentParser(description='Converter from Remind to iCalendar synt...
Command line tool to convert from iCalendar to Remind
def ics2rem(): """Command line tool to convert from iCalendar to Remind""" from argparse import ArgumentParser, FileType from sys import stdin, stdout parser = ArgumentParser(description='Converter from iCalendar to Remind syntax.') parser.add_argument('-l', '--label', help='Label for every Remind ...
Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -)
def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: ...
Parse a line of remind output into a dict line -- the remind output text -- the original remind input
def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': ...
Return the distance between all dates and 0 if they are different
def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval
Generate an rdate or rrule from a list of dates and add it to the vevent
def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=i...
Generate vevent from given event
def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] ...
Reload Remind files if the mtime is newer
def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: ...
UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file
def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._remind...
Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None)
def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] ...
Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filena...
def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of al...
Return iCal object of the Remind commands in lines
def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal
Convert from iCal rrule to Remind recurrence syntax
def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: ...
unify dtend and duration to the duration of the given vevent
def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value r...
Generate a Remind MSG from the given vevent. Opposite of _gen_description()
def _gen_msg(vevent, label, tail, sep): """Generate a Remind MSG from the given vevent. Opposite of _gen_description() """ rem = ['MSG'] msg = [] if label: msg.append(label) if hasattr(vevent, 'summary') and vevent.summary.value: msg.appen...
Generate a Remind command from the given vevent
def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._par...
Return Remind commands for all events of a iCalendar
def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, la...
Append a Remind command generated from the iCalendar to the file
def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(i...
Remove the Remind command with the uid from the file
def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filen...
Update the Remind command with the uid in the file with the new iCalendar
def replace(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" return self.replace_vobject(uid, readOne(ical), filename)
Update the Remind command with the uid in the file with the new iCalendar
def replace_vobject(self, uid, ical, filename=None): """Update the Remind command with the uid in the file with the new iCalendar""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self...
Move the Remind command with the uid from from_file to to_file
def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).rea...
Expand the content of a file into a string. If @include directives are found in the config, they are expanded by this function. In case recursion is detected or a RunTimeError is thrown, ``None`` is returned.
def expand_include(filename): """ Expand the content of a file into a string. If @include directives are found in the config, they are expanded by this function. In case recursion is detected or a RunTimeError is thrown, ``None`` is returned. """ open_files = set...
displays the doc string of the selected element
def show_info(self): """ displays the doc string of the selected element """ sender = self.sender() tree = sender.parent() index = tree.selectedIndexes() info = '' if index != []: index = index[0] name = str(index.model().itemFromI...
fills a tree with nested parameters Args: tree: QtGui.QTreeView parameters: dictionary or Parameter object Returns:
def fill_tree(self, tree, input_dict): """ fills a tree with nested parameters Args: tree: QtGui.QTreeView parameters: dictionary or Parameter object Returns: """ def removeAll(tree): if tree.model().rowCount() > 0: ...
Check if there are any grand parents. Set the grandparents id:s Arguments: mother (Individual): An Individual object that represents the mother father (Individual): An Individual object that represents the father
def check_grandparents(self, mother = None, father = None): """ Check if there are any grand parents. Set the grandparents id:s Arguments: mother (Individual): An Individual object that represents the mother father (Individual): An Individual obj...
Return the individual info in a dictionary for json.
def to_json(self): """ Return the individual info in a dictionary for json. """ self.logger.debug("Returning json info") individual_info = { 'family_id': self.family, 'id':self.individual_id, 'sex':str(self.sex), 'phenotype': str(...
Return the individual info in a madeline formated string
def to_madeline(self): """ Return the individual info in a madeline formated string """ #Convert sex to madeleine type self.logger.debug("Returning madeline info") if self.sex == 1: madeline_gender = 'M' elif self.sex == 2: madeline_gender ...
generate rfc3339 time format input : d = date type local_tz = use local time zone if true, otherwise mark as utc output : rfc3339 string date format. ex : `2008-04-02T20:00:00+07:00`
def generate_rfc3339(d, local_tz=True): """ generate rfc3339 time format input : d = date type local_tz = use local time zone if true, otherwise mark as utc output : rfc3339 string date format. ex : `2008-04-02T20:00:00+07:00` """ try: if local_tz: d = dateti...
input : date : date type local_tz : if true, use system timezone, otherwise return 0 return the date of UTC offset. If date does not have any timezone info, we use local timezone, otherwise return 0
def _calculate_offset(date, local_tz): """ input : date : date type local_tz : if true, use system timezone, otherwise return 0 return the date of UTC offset. If date does not have any timezone info, we use local timezone, otherwise return 0 """ if local_tz: #handle year bef...
input : date : date type local_tz : bool offset generated from _calculate_offset offset in seconds offset = 0 -> +00:00 offset = 1800 -> +00:30 offset = -3600 -> -01:00
def _generate_timezone(date, local_tz): """ input : date : date type local_tz : bool offset generated from _calculate_offset offset in seconds offset = 0 -> +00:00 offset = 1800 -> +00:30 offset = -3600 -> -01:00 """ offset = _calculate_offset(date, local_tz) hour = abs...
takes in a path to a folder or file and return the module path and the path to the module the module is idenitified by the path being in os.path, e.g. if /Users/Projects/Python/ is in os.path, then folder_name = '/Users/PycharmProjects/pylabcontrol/pylabcontrol/scripts/script_dummy.pyc' ret...
def module_name_from_path(folder_name, verbose=False): """ takes in a path to a folder or file and return the module path and the path to the module the module is idenitified by the path being in os.path, e.g. if /Users/Projects/Python/ is in os.path, then folder_name = '/Users/PycharmProje...
returns all the packages in the module Args: module_name: name of module Returns:
def explore_package(module_name): """ returns all the packages in the module Args: module_name: name of module Returns: """ packages = [] loader = pkgutil.get_loader(module_name) for sub_module in pkgutil.walk_packages([os.path.dirname(loader.get_filename())], ...
Create a parser by defining which input files it will read from. Input: directory - str, directory to read from files - str, list of files from which to search.
def generate_from_directory(cls, directory): """Create a parser by defining which input files it will read from. Input: directory - str, directory to read from files - str, list of files from which to search. """ files = [os.path.join(directory, f) for f in o...
Get composition of output structure Returns: String - Composition based on output structure
def get_composition(self): '''Get composition of output structure Returns: String - Composition based on output structure ''' strc = self.get_output_structure() counts = Counter(strc.get_chemical_symbols()) return ''.join(k if counts[k]==1 else '%s%d'...
Compute the density from the output structure
def get_density(self): """Compute the density from the output structure""" strc = self.get_output_structure() density = sum(strc.get_masses()) / strc.get_volume() * 1.660539040 return Property(scalars=[Scalar(value=density)], units="g/(cm^3)")
Whether the calculation has converged Returns: Property where "scalar" is a boolean indicating
def is_converged(self): '''Whether the calculation has converged Returns: Property where "scalar" is a boolean indicating ''' # Check for cached result if self._converged is None: self._converged = self._is_converged() return Property(scalars=[Scalar...
Get the number of atoms in the calculated structure. Returns: Property, where number of atoms is a scalar.
def get_number_of_atoms(self): """Get the number of atoms in the calculated structure. Returns: Property, where number of atoms is a scalar. """ strc = self.get_output_structure() if not strc: return None return Property(scalars=[Scalar(value=len(strc))], uni...
imports all the module_type from additional modules that contain module_type This name of those modules is in the config file that is located in the main directory module_type: str that specifies the type of module to be loaded (scripts / instruments) :return: module_list: a list with modules that contain ...
def import_sub_modules(module_type): """ imports all the module_type from additional modules that contain module_type This name of those modules is in the config file that is located in the main directory module_type: str that specifies the type of module to be loaded (scripts / instruments) :retur...
gets the value for "name" from "path_to_file" config file Args: name: name of varibale in config file path_to_file: path to config file Returns: path to dll if name exists in the file; otherwise, returns None
def get_config_value(name, path_to_file='config.txt'): """ gets the value for "name" from "path_to_file" config file Args: name: name of varibale in config file path_to_file: path to config file Returns: path to dll if name exists in the file; otherwise, returns None """ # if ...
loads a .b26 file into a dictionary Args: file_name: Returns: dictionary with keys instrument, scripts, probes
def load_b26_file(file_name): """ loads a .b26 file into a dictionary Args: file_name: Returns: dictionary with keys instrument, scripts, probes """ # file_name = "Z:\Lab\Cantilever\Measurements\\tmp_\\a" assert os.path.exists(file_name) with open(file_name, 'r') as infile: ...
save instruments, scripts and probes as a json file Args: filename: instruments: scripts: probes: dictionary of the form {instrument_name : probe_1_of_intrument, probe_2_of_intrument, ...} Returns:
def save_b26_file(filename, instruments=None, scripts=None, probes=None, overwrite=False, verbose=False): """ save instruments, scripts and probes as a json file Args: filename: instruments: scripts: probes: dictionary of the form {instrument_name : probe_1_of_intrument, prob...
load all the instruments or script objects that are located in folder_name and return a dictionary with the script class name and path_to_python_file Args: folder_name (string): folder in which to search for class objects / or name of module class_type (string or class): class type for which to ...
def get_classes_in_folder(folder_name, class_type, verbose=False): """ load all the instruments or script objects that are located in folder_name and return a dictionary with the script class name and path_to_python_file Args: folder_name (string): folder in which to search for class objects / o...
NOT IMPLEMENTED YET tries to instantiate all the instruments that are imported in /instruments/__init__.py and the probes of each instrument that could be instantiated into a .b26 file in the folder path Args: path: target path for .b26 files
def export_default_probes(path, module_name = '', raise_errors = False): """ NOT IMPLEMENTED YET tries to instantiate all the instruments that are imported in /instruments/__init__.py and the probes of each instrument that could be instantiated into a .b26 file in the folder path Args: path:...
tries to instantiate all the scripts that are imported in /scripts/__init__.py saves each script that could be instantiated into a .b26 file in the folder path Args: target_folder: target path for .b26 files source_folder: location of python script files
def export_default_scripts(target_folder, source_folder = None, raise_errors = False, verbose=False): """ tries to instantiate all the scripts that are imported in /scripts/__init__.py saves each script that could be instantiated into a .b26 file in the folder path Args: target_folder: target pa...
exports the existing scripts/instruments (future: probes) into folder as .b26 files Args: target_folder: target location of created .b26 script files source_folder: singel path or list of paths that contains the location of python script files can also be just the name of a module class_type...
def export(target_folder, source_folders = None, class_type ='all', raise_errors = False): """ exports the existing scripts/instruments (future: probes) into folder as .b26 files Args: target_folder: target location of created .b26 script files source_folder: singel path or list of paths tha...
Reading socket and receiving message from server. Check the CRC32.
def recv_message(self, debug=False): """ Reading socket and receiving message from server. Check the CRC32. """ if debug: packet = self.sock.recv(1024) # reads how many bytes to read hexdump(packet) packet_length_data = self.sock.recv(4) # reads how man...
Returns a list of CategoryList objects, associated with this model instance. :param dict|None init_kwargs: :param list|None additional_parents_aliases: :rtype: list|CategoryRequestHandler :return:
def get_category_lists(self, init_kwargs=None, additional_parents_aliases=None): """Returns a list of CategoryList objects, associated with this model instance. :param dict|None init_kwargs: :param list|None additional_parents_aliases: :rtype: list|CategoryRequestHandler ...
Enables editor functionality for categories of this object. :param Request request: Django request object :param dict editor_init_kwargs: Keyword args to initialize category lists editor with. See CategoryList.enable_editor() :param list additional_parents_aliases: Aliases of catego...
def enable_category_lists_editor(self, request, editor_init_kwargs=None, additional_parents_aliases=None, lists_init_kwargs=None, handler_init_kwargs=None): """Enables editor functionality for categories of this object. :param Request request: Django request object ...
Add this model instance to a category. :param Category category: Category to add this object to :param User user: User heir who adds :return:
def add_to_category(self, category, user): """Add this model instance to a category. :param Category category: Category to add this object to :param User user: User heir who adds :return: """ init_kwargs = { 'category': category, 'creator': user, ...
Removes this object from a given category. :param Category category: :return:
def remove_from_category(self, category): """Removes this object from a given category. :param Category category: :return: """ ctype = ContentType.objects.get_for_model(self) self.categories.model.objects.filter(category=category, content_type=ctype, object_id=self.id).d...
Returns a QuerySet of Ties for the given categories. :param list|Category categories: :param User|None user: :param int|None status: :return:
def get_ties_for_categories_qs(cls, categories, user=None, status=None): """Returns a QuerySet of Ties for the given categories. :param list|Category categories: :param User|None user: :param int|None status: :return: """ if not isinstance(categories, list): ...
Returns a QuerySet of objects of this type associated with the given category. :param Category category: :rtype: list :return:
def get_from_category_qs(cls, category): """Returns a QuerySet of objects of this type associated with the given category. :param Category category: :rtype: list :return: """ ids = cls.get_ties_for_categories_qs(category).values_list('object_id').distinct() filte...
This is run if file is directly executed, but not if imported as module. Having this in a separate function allows importing the file into interactive python, and still able to execute the function for testing
def main(): """This is run if file is directly executed, but not if imported as module. Having this in a separate function allows importing the file into interactive python, and still able to execute the function for testing""" parser = argparse.ArgumentParser() parser.add_argument("-f", "--fil...
Extend with a full subtree <= the current minimum subtree. The leaves must form a full subtree, i.e. of size 2^k for some k. If there is a minimum subtree (i.e. __mintree_height > 0), then the input subtree must be smaller or of equal size to the minimum subtree. If the subtree is smal...
def _push_subtree(self, leaves: List[bytes]): """Extend with a full subtree <= the current minimum subtree. The leaves must form a full subtree, i.e. of size 2^k for some k. If there is a minimum subtree (i.e. __mintree_height > 0), then the input subtree must be smaller or of equal siz...
Create a new instance of this class derived from the current instance such that: (new.trace_id == current.trace_id and new.parent_span_id == current.span_id) The new L{Trace} instance will have a new unique span_id and if set the endpoint of the current L{Trace} object...
def child(self, name): """ Create a new instance of this class derived from the current instance such that: (new.trace_id == current.trace_id and new.parent_span_id == current.span_id) The new L{Trace} instance will have a new unique span_id and if set the ...
resolve a local object :param obj: the local object. :param pointer: the pointer :type pointer: DocumentPointer, str :param registry: the registry. It mays be omited if inner json references document don't refer to other documents. :type registry: Provider, d...
def resolve(obj, pointer, registry=None): """resolve a local object :param obj: the local object. :param pointer: the pointer :type pointer: DocumentPointer, str :param registry: the registry. It mays be omited if inner json references document don't refer to...
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
def run_migrations(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ with engine.connect() as connection: context.configure( connection=connection, target_metadata=Model.metadata) ...
Add a url scheme to this endpoint. It takes a url string and create the OEmbedUrlScheme object internally. Args: url: The url string that represents a url scheme to add.
def addUrlScheme(self, url): ''' Add a url scheme to this endpoint. It takes a url string and create the OEmbedUrlScheme object internally. Args: url: The url string that represents a url scheme to add. ''' #@TODO: validate invalid url format according to ht...
Try to find if url matches against any of the schemes within this endpoint. Args: url: The url to match against each scheme Returns: True if a matching scheme was found for the url, False otherwise
def match(self, url): ''' Try to find if url matches against any of the schemes within this endpoint. Args: url: The url to match against each scheme Returns: True if a matching scheme was found for the url, False otherwise ''' try: ...
Format the input url and optional parameters, and provides the final url where to get the given resource. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: The complete url of the endpoint and resource.
def request(self, url, **opt): ''' Format the input url and optional parameters, and provides the final url where to get the given resource. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: The complete ...
Convert the resource url to a complete url and then fetch the data from it. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: OEmbedResponse object according to data fetched
def get(self, url, **opt): ''' Convert the resource url to a complete url and then fetch the data from it. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: OEmbedResponse object according to data fetched...
Fetch url and create a response object according to the mime-type. Args: url: The url to fetch data from Returns: OEmbedResponse object according to data fetched
def fetch(self, url): ''' Fetch url and create a response object according to the mime-type. Args: url: The url to fetch data from Returns: OEmbedResponse object according to data fetched ''' opener = self._urllib.build_opener() opener.ad...
Get an OEmbedResponse from one of the providers configured in this consumer according to the resource url. Args: url: The url of the resource to get. format: Desired response format. **opt: Optional parameters to pass in the url to the provider. Returns: ...
def embed(self, url, format='json', **opt): ''' Get an OEmbedResponse from one of the providers configured in this consumer according to the resource url. Args: url: The url of the resource to get. format: Desired response format. **opt: Optional para...
run function of TauDEM, take pitremove as an example. Compare the max, min, and average of rawdem and filled DEM. The result will be:: RawDEM: Max: 284.07, Min: 139.11, Mean: 203.92 FilledDEM: Max: 284.07, Min: 139.11, Mean: 203.93
def pitremove_example(): """run function of TauDEM, take pitremove as an example. Compare the max, min, and average of rawdem and filled DEM. The result will be:: RawDEM: Max: 284.07, Min: 139.11, Mean: 203.92 FilledDEM: Max: 284.07, Min: 139.11, Mean: 203.93 """ dem = '../tests/da...
figures out the iterator type based on the script settings and (optionally) subscripts Args: script_settings: iterator_type subscripts: subscripts Returns:
def get_iterator_type(script_settings, subscripts={}): """ figures out the iterator type based on the script settings and (optionally) subscripts Args: script_settings: iterator_type subscripts: subscripts Returns: """ if 'iterator_type' in scrip...
Runs either a loop or a parameter sweep over the subscripts in the order defined by the parameter_list 'script_order'
def _function(self): ''' Runs either a loop or a parameter sweep over the subscripts in the order defined by the parameter_list 'script_order' ''' def get_sweep_parameters(): """ Returns: the paramter values over which to sweep """ #in both...
this function takes care of signals emitted by the subscripts Args: progress_subscript: progress of subscript
def _receive_signal(self, progress_subscript): """ this function takes care of signals emitted by the subscripts Args: progress_subscript: progress of subscript """ self.progress = self._estimate_progress() self.updateProgress.emit(int(self.progress))
Returns: itself as a dictionary
def to_dict(self): """ Returns: itself as a dictionary """ dictator = Script.to_dict(self) # the dynamically created ScriptIterator classes have a generic name # replace this with ScriptIterator to indicate that this class is of type ScriptIterator dictator[self.n...
creates all the dynamic classes in the script and the class of the script itself and updates the script info with these new classes Args: script_information: A dictionary describing the ScriptIterator, or an existing object script_iterators: dictionary with the scriptiterators (...
def create_dynamic_script_class(script_information, script_iterators={},verbose=False): ''' creates all the dynamic classes in the script and the class of the script itself and updates the script info with these new classes Args: script_information: A dictionary describing t...
Args: package_name: name of package Returns: the script_iterators of the package as a dictionary
def get_script_iterator(package_name, verbose = False): """ Args: package_name: name of package Returns: the script_iterators of the package as a dictionary """ packs = hf.explore_package(package_name + '.core') print(packs) script_iterator = {} ...
Connect to the Herkulex bus Connect to serial port to which Herkulex Servos are attatched Args: portname (str): The serial port name baudrate (int): The serial port baudrate Raises: SerialException: Error occured while opening serial port
def connect(portname, baudrate): """ Connect to the Herkulex bus Connect to serial port to which Herkulex Servos are attatched Args: portname (str): The serial port name baudrate (int): The serial port baudrate Raises: SerialException: Error occured while opening serial port ...
Calculate Checksum 1 Calculate the ckecksum 1 required for the herkulex data packet Args: data (list): the data of which checksum is to be calculated stringlength (int): the length of the data Returns: int: The calculated checksum 1
def checksum1(data, stringlength): """ Calculate Checksum 1 Calculate the ckecksum 1 required for the herkulex data packet Args: data (list): the data of which checksum is to be calculated stringlength (int): the length of the data Returns: int: The calculated checksum 1 ...
Send data to herkulex Paketize & write the packet to serial port Args: data (list): the data to be sent Raises: SerialException: Error occured while opening serial port
def send_data(data): """ Send data to herkulex Paketize & write the packet to serial port Args: data (list): the data to be sent Raises: SerialException: Error occured while opening serial port """ datalength = len(data) csm1 = checksum1(data, datalength) csm2 = checks...
Clears the errors register of all Herkulex servos Args: none
def clear_errors(): """ Clears the errors register of all Herkulex servos Args: none """ data = [] data.append(0x0B) data.append(BROADCAST_ID) data.append(RAM_WRITE_REQ) data.append(STATUS_ERROR_RAM) data.append(BYTE2) data.append(0x00) data.append(0x00) send_da...
scale a value from one range to another
def scale(input_value, input_min, input_max, out_min, out_max): """ scale a value from one range to another """ # Figure out how 'wide' each range is input_span = input_max - input_min output_span = out_max - out_min # Convert the left range into a 0-1 range (float) valuescaled = float(input...
Scan for the herkulex servos connected This function will scan for all the herkulex servos connected to the bus. Args: none Returns: list: a list of tuples of the form [(id, model)]
def scan_servos(): """Scan for the herkulex servos connected This function will scan for all the herkulex servos connected to the bus. Args: none Returns: list: a list of tuples of the form [(id, model)] """ servos = [] for servo_id in range(0x00, 0xFE): model = get_model(servo_id)...
Get the servo model This function gets the model of the herkules servo, provided its id Args: servoid(int): the id of the servo Returns: int: an integer corresponding to the model number 0x06 for DRS-602 0x04 for DRS-402 0x02 for DRS-202
def get_model(servoid): """ Get the servo model This function gets the model of the herkules servo, provided its id Args: servoid(int): the id of the servo Returns: int: an integer corresponding to the model number 0x06 for DRS-602 0x04 for DRS-402 ...
Get the error status of servo This function gets the error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet
def get_servo_status(self): """ Get the error status of servo This function gets the error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet """ data = [] ...
Get the detailed error status of servo This function gets the detailed error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet
def get_servo_status_detail(self): """ Get the detailed error status of servo This function gets the detailed error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet ...
Set the LED Color of Herkulex Args: colorcode (int): The code for colors (0x00-OFF 0x02-BLUE 0x03-CYAN 0x04-RED 0x05-ORANGE 0x...
def set_led(self, colorcode): """ Set the LED Color of Herkulex Args: colorcode (int): The code for colors (0x00-OFF 0x02-BLUE 0x03-CYAN 0x04-RED ...
Set the Brakes of Herkulex In braked mode, position control and velocity control will not work, enable torque before that Args: none
def brake_on(self): """ Set the Brakes of Herkulex In braked mode, position control and velocity control will not work, enable torque before that Args: none """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRI...
Set the torques of Herkulex to zero In this mode, position control and velocity control will not work, enable torque before that. Also the servo shaft is freely movable Args: none
def torque_off(self): """ Set the torques of Herkulex to zero In this mode, position control and velocity control will not work, enable torque before that. Also the servo shaft is freely movable Args: none """ data = [] data.append(0x0A) ...
Enable the torques of Herkulex In this mode, position control and velocity control will work. Args: none
def torque_on(self): """ Enable the torques of Herkulex In this mode, position control and velocity control will work. Args: none """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append...
get the torque state of motor Returns: bool: True if torque is enabled, else False
def get_torque_state(self): """ get the torque state of motor Returns: bool: True if torque is enabled, else False """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(TORQUE_CONTROL_RAM) data...
Set the position of Herkulex Enable torque using torque_on function before calling this Args: goalposition (int): The desired position, min-0 & max-1023 goaltime (int): the time taken to move from present position to goalposition led (int): the LED col...
def set_servo_position(self, goalposition, goaltime, led): """ Set the position of Herkulex Enable torque using torque_on function before calling this Args: goalposition (int): The desired position, min-0 & max-1023 goaltime (int): the time taken to move from present ...
Gets the current position of Herkulex Args: none Returns: int: position of the servo- 0 to 1023 Raises: SerialException: Error occured while opening serial port
def get_servo_position(self): """ Gets the current position of Herkulex Args: none Returns: int: position of the servo- 0 to 1023 Raises: SerialException: Error occured while opening serial port """ #global SERPORT data = [...
Gets the current temperature of Herkulex Args: none Returns: int: the current temperature register of Herkulex Raises: SerialException: Error occured while opening serial port
def get_servo_temperature(self): """ Gets the current temperature of Herkulex Args: none Returns: int: the current temperature register of Herkulex Raises: SerialException: Error occured while opening serial port """ data = [] ...
Gets the current torque of Herkulex Gives the current load on the servo shaft. It is actually the PWM value to the motors Args: none Returns: int: the torque on servo shaft. range from -1023 to 1023 Raises: SerialException: Error occured wh...
def get_servo_torque(self): """ Gets the current torque of Herkulex Gives the current load on the servo shaft. It is actually the PWM value to the motors Args: none Returns: int: the torque on servo shaft. range from -1023 to 1023 Raises: ...
Set the Herkulex in continuous rotation mode Args: goalspeed (int): the speed , range -1023 to 1023 led (int): the LED color 0x00 LED off 0x04 GREEN 0x08 BLUE 0x10 RED
def set_servo_speed(self, goalspeed, led): """ Set the Herkulex in continuous rotation mode Args: goalspeed (int): the speed , range -1023 to 1023 led (int): the LED color 0x00 LED off 0x04 GREEN 0x08 BLUE ...