text
stringlengths
81
112k
Combines the action preconditions into an applicability checking op. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A boolean tensor for checking if `action` is application in `state`. def co...
Compiles all actions bounds for the given `state`. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from action names to a pair of :obj:`rddl2tf.fluent.TensorFluent` representing its lower and upper bounds. def compile_ac...
Returns a partial scope with non-fluents. Returns: A mapping from non-fluent names to :obj:`rddl2tf.fluent.TensorFluent`. def non_fluents_scope(self) -> Dict[str, TensorFluent]: '''Returns a partial scope with non-fluents. Returns: A mapping from non-fluent names to :o...
Returns a partial scope with current state-fluents. Args: state_fluents (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from state fluent names to :obj:`rddl2tf.fluent.TensorFluent`. def state_scope(self, state_fluents: Sequence[tf.Tensor]) -> Dict[str, Te...
Returns a partial scope with current action-fluents. Args: action_fluents (Sequence[tf.Tensor]): The action fluents. Returns: A mapping from action fluent names to :obj:`rddl2tf.fluent.TensorFluent`. def action_scope(self, action_fluents: Sequence[tf.Tensor]) -> Dict[str, Tens...
Returns a partial scope with current next state-fluents. Args: next_state_fluents (Sequence[tf.Tensor]): The next state fluents. Returns: A mapping from next state fluent names to :obj:`rddl2tf.fluent.TensorFluent`. def next_state_scope(self, next_state_fluents: Sequence[tf.Te...
Returns the complete transition fluent scope for the current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A mapping from fluent names to :obj:`rddl2tf.f...
Returns the complete reward fluent scope for the current `state`, `action` fluents, and `next_state` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. next_state (Sequence[tf.Tensor]): The next st...
Returns the state invariant fluent scope for the current `state`. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from fluent names to :obj:`rddl2tf.fluent.TensorFluent`. def state_invariant_scope(self, state: Sequence[tf.Tensor]): '''R...
Instantiates `pvariables` given an initialization list and returns a list of TensorFluents in the given `ordering`. Returns: List[Tuple[str, TensorFluent]]: A list of pairs of fluent name and fluent tensor. def _initialize_pvariables(self, pvariables: Dict[str, PVariable], ...
Returns the non-fluents instantiated. def _initialize_non_fluents(self): '''Returns the non-fluents instantiated.''' non_fluents = self.rddl.domain.non_fluents initializer = self.rddl.non_fluents.init_non_fluent self.non_fluents = self._initialize_pvariables( non_fluents, ...
Returns the initial state-fluents instantiated. def _initialize_initial_state_fluents(self): '''Returns the initial state-fluents instantiated.''' state_fluents = self.rddl.domain.state_fluents initializer = self.rddl.instance.init_state self.initial_state_fluents = self._initialize_pva...
Returns the default action-fluents instantiated. def _initialize_default_action_fluents(self): '''Returns the default action-fluents instantiated.''' action_fluents = self.rddl.domain.action_fluents self.default_action_fluents = self._initialize_pvariables( action_fluents, ...
Compiles `fluents` into tensors with given `batch_size`. Returns: Sequence[tf.Tensor]: A tuple of tensors with first dimension corresponding to the batch size. def _compile_batch_fluents(self, fluents: List[Tuple[str, TensorFluent]], batch_size: int) -> Sequence...
Compile the expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optional[size]): The ba...
Compile a constant expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL constant expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optiona...
Compile a pvariable expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL pvariable expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optio...
Compile a random variable expression `expr` into a TensorFluent in the given `scope` with optional batch size. If `reparam` tensor is given, then it conditionally stops gradient backpropagation at the batch level where `reparam` is False. Args: expr (:obj:`rddl2tf.expr.Expr...
Compile an arithmetic expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL arithmetic expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Op...
Compile a function expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL function expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optiona...
Compile a control flow expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL control flow expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size ...
Compile an aggregation expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL aggregation expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (...
Use the current Query object to count the number of entries in `table` that satisfy `queries`. Parameters ---------- table : NumPy structured array, astropy Table, etc. Returns ------- mask : numpy bool array def mask(self, table): """ Use the c...
Use the current Query object to create a mask (a boolean array) for `table`. Parameters ---------- table : NumPy structured array, astropy Table, etc. column_slice : Column to return. Default is None (return all columns). Returns ------- table : filtered...
Use the current Query object to count the number of entries in `table` that satisfy `queries`. Parameters ---------- table : NumPy structured array, astropy Table, etc. Returns ------- count : int def count(self, table): """ Use the current Quer...
Get all variable names required for this query def variable_names(self): """ Get all variable names required for this query """ if self._variable_names is None: if self._operator is None: if self._operands is None: self._variable_names = ...
Creates a User object when requested. def user(self): """Creates a User object when requested.""" try: return self._user except AttributeError: self._user = MatrixUser(self.mxid, self.Api(identity=self.mxid)) return self._user
Creates a Room object when requested. def room(self): """Creates a Room object when requested.""" try: return self._room except AttributeError: room_id = self.json["room_id"] self._room = MatrixRoom(room_id, self.Api) return self._room
Joins room id or alias even if it must first be created. def join(self, room_str): """Joins room id or alias even if it must first be created.""" response = self.user_api.join_room(room_str) return self._mkroom(response["room_id"])
Calls GET /joined_rooms to refresh rooms list. def refresh_rooms(self): """Calls GET /joined_rooms to refresh rooms list.""" for room_id in self.user_api.get_joined_rooms()["joined_rooms"]: self._rooms[room_id] = MatrixRoom(room_id, self.user_api)
Validates the given input (has to be a valid data structure) is empty. Input *has* to be one of: `list`, `dict`, or `string`. It is specially useful when most of the validators being created are dealing with data structures that should not be empty. def not_empty(_object): """ Validates the given ...
This decorator has a double functionality, it can wrap validators and make them optional or it can wrap keys and make that entry optional. **Optional Validator:** Allows to have validators work only when there is a value that contains some data, otherwise it will just not pass the information to the ac...
Setting a walltime for the job >>> job.set_walltime(datetime.timedelta(hours=2, minutes=30)) :param walltime: Walltime of the job (an instance of timedelta) :returns: self :rtype: self def set_walltime(self, walltime): """ Setting a walltime for the job >>> jo...
Requests the specified url and returns a BeautifulSoup object with its contents. def get_url(url, parser='html'): """ Requests the specified url and returns a BeautifulSoup object with its contents. """ url = request.quote(url, safe=':/?=&') logger.debug('URL: %s', url) req = request.Re...
Request the specified method from the lastfm api. def get_lastfm(method, lastfm_key='', **kwargs): """ Request the specified method from the lastfm api. """ if not lastfm_key: if 'lastfm_key' not in CONFIG or not CONFIG['lastfm_key']: logger.warning('No lastfm key configured') ...
Remove accented characters and such. The argument chars_to_remove is a dictionary that maps a string of chars to a single character. Every occurrence of every character in the first string will be replaced by that second character passed as value. If only one mapping is desired, chars_to_remove may be ...
Returns the lyrics found in metrolyrics for the specified mp3 file or an empty string if not found. def metrolyrics(song): """ Returns the lyrics found in metrolyrics for the specified mp3 file or an empty string if not found. """ translate = {URLESCAPE: '', ' ': '-'} title = song.title.low...
Returns the lyrics found in darklyrics for the specified mp3 file or an empty string if not found. def darklyrics(song): """ Returns the lyrics found in darklyrics for the specified mp3 file or an empty string if not found. """ # Darklyrics relies on the album name if not hasattr(song, 'al...
Returns the lyrics found in azlyrics for the specified mp3 file or an empty string if not found. def azlyrics(song): """ Returns the lyrics found in azlyrics for the specified mp3 file or an empty string if not found. """ artist = song.artist.lower() if artist[0:2] == 'a ': artist =...
Returns the lyrics found in genius.com for the specified mp3 file or an empty string if not found. def genius(song): """ Returns the lyrics found in genius.com for the specified mp3 file or an empty string if not found. """ translate = { '@': 'at', '&': 'and', URLESCAPE:...
Returns the lyrics found in MetalArchives for the specified mp3 file or an empty string if not found. def metalarchives(song): """ Returns the lyrics found in MetalArchives for the specified mp3 file or an empty string if not found. """ artist = normalize(song.artist) title = normalize(song...
Returns the lyrics found in lyrics.wikia.com for the specified mp3 file or an empty string if not found. def lyricswikia(song): """ Returns the lyrics found in lyrics.wikia.com for the specified mp3 file or an empty string if not found. """ artist = song.artist.title() artist = normalize(ar...
Returns the lyrics found in musixmatch for the specified mp3 file or an empty string if not found. def musixmatch(song): """ Returns the lyrics found in musixmatch for the specified mp3 file or an empty string if not found. """ escape = re.sub("'-¡¿", '', URLESCAPE) translate = { es...
Returns the lyrics found in songlyrics.com for the specified mp3 file or an empty string if not found. def songlyrics(song): """ Returns the lyrics found in songlyrics.com for the specified mp3 file or an empty string if not found. """ translate = { URLESCAPE: '', ' ': '-' }...
Returns the lyrics found in lyrics.com for the specified mp3 file or an empty string if not found. def lyricscom(song): """ Returns the lyrics found in lyrics.com for the specified mp3 file or an empty string if not found. """ artist = song.artist.lower() artist = normalize(artist, ' ', '+'...
Returns the lyrics found in vagalume.com.br for the specified mp3 file or an empty string if not found. def vagalume(song): """ Returns the lyrics found in vagalume.com.br for the specified mp3 file or an empty string if not found. """ translate = { '@': 'a', URLESCAPE: '', ...
Returns the lyrics found in lyricsmode.com for the specified mp3 file or an empty string if not found. def lyricsmode(song): """ Returns the lyrics found in lyricsmode.com for the specified mp3 file or an empty string if not found. """ translate = { URLESCAPE: '', ' ': '_' }...
Returns the lyrics found in letras.com for the specified mp3 file or an empty string if not found. def letras(song): """ Returns the lyrics found in letras.com for the specified mp3 file or an empty string if not found. """ translate = { '&': 'a', URLESCAPE: '', ' ': '-'...
Returns the name of a website-scrapping function. def id_source(source, full=False): """ Returns the name of a website-scrapping function. """ if source not in source_ids: return '' if full: return source_ids[source][1] else: return source_ids[source][0]
app = Sanic() mserver = MetricsServer(app) mserver.add_task(update_gitlab_loop, params={'url': GITLAB_URL, 'token': token}) async def update_gitlab_loop(update_metrics, params): """ app = Sanic() mserver = MetricsServer(app) mserver.add_task(update_gitlab_loop, params={'url': GITLAB_URL, 'token...
Set the probe position, in normalized coordinates with origin at top left. def set_probe_position(self, new_probe_position): """ Set the probe position, in normalized coordinates with origin at top left. """ if new_probe_position is not None: # convert the probe position to a FloatPoint and...
Apply metadata groups to properties. Metadata groups is a tuple with two elements. The first is a list of strings representing a dict-path in which to add the controls. The second is a control group from which to read a list of controls to be added as name value pairs to the dict-path. def app...
Creates a new Analytics backend from the settings :param settings: Dictionary of settings for the analytics backend :returns: A backend object implementing the analytics api >>> >>> analytics = create_analytic({ >>> 'backend': 'analytics.backends.redis.Redis', >>> 'settings': { >>>...
Call this to initialize the state of the UI after everything has been connected. def initialize_state(self): """ Call this to initialize the state of the UI after everything has been connected. """ if self.__scan_hardware_source: self.__profile_changed_event_listener = self.__scan_hardware_...
Call this when the user clicks the play/pause button. def handle_play_pause_clicked(self): """ Call this when the user clicks the play/pause button. """ if self.__scan_hardware_source: if self.is_playing: self.__scan_hardware_source.stop_playing() else: ...
Call this when the user clicks the record button. def handle_record_clicked(self, callback_fn): """ Call this when the user clicks the record button. """ assert callable(callback_fn) if self.__scan_hardware_source: def finish_record(data_and_metadata_list): record_i...
Size the canvas item to the text content. def size_to_content(self, horizontal_padding=None, vertical_padding=None): """ Size the canvas item to the text content. """ if horizontal_padding is None: horizontal_padding = 0 if vertical_padding is None: vertical_padding = ...
Return after <rounds> passes through a cycled iterable. def round_controlled(cycled_iterable, rounds=1): """Return after <rounds> passes through a cycled iterable.""" round_start = None rounds_completed = 0 for item in cycled_iterable: if round_start is None: round_start = item ...
Returns a float with the rate of success from all the logged results. def success_rate(self): """ Returns a float with the rate of success from all the logged results. """ if self.successes + self.fails == 0: success_rate = 0 else: total_attempts = self.s...
Adds a new record to the statistics 'database'. This function is intended to be called after a website has been scraped. The arguments indicate the function that was called, the time taken to scrap the website and a boolean indicating if the lyrics were found or not. def add_result(self, source...
Returns the average time taken to scrape lyrics. If a string or a function is passed as source, return the average time taken to scrape lyrics from that source, otherwise return the total average. def avg_time(self, source=None): """ Returns the average time taken to scrape lyrics. If a...
Calculate the overall counts of best, worst, fastest, slowest, total found, total not found and total runtime Results are returned in a dictionary with the above parameters as keys. def calculate(self): """ Calculate the overall counts of best, worst, fastest, slowest, total fo...
Print a series of relevant stats about a full execution. This function is meant to be called at the end of the program. def print_stats(self): """ Print a series of relevant stats about a full execution. This function is meant to be called at the end of the program. """ ...
It broadcasts the smaller scope over the larger scope. It handles scope intersection as well as differences in scopes in order to output a resulting scope so that input scopes are contained within it (i.e., input scopes are subscopes of the output scope). Also, if necessary, it outputs ...
Turn baseParser results into a dataframe def get_baseparser_extended_df(sample, bp_lines, ref, alt): """Turn baseParser results into a dataframe""" columns = "chrom\tpos\tref\tcov\tA\tC\tG\tT\t*\t-\t+".split() if bp_lines is None: return None # change baseparser output to get most common maf p...
Remove mutations that are in normal def filter_out_mutations_in_normal(tumordf, normaldf, most_common_maf_min=0.2, most_common_count_maf_threshold=20, most_common_count_min=1): """Remove mutations that are in normal""" df = tumordf.merge(nor...
Selects only mutations that revert the given mutations in a single event. def select_only_revertant_mutations(bpdf, snv=None, ins=None, dlt=None): """ Selects only mutations that revert the given mutations in a single event. """ if sum([bool(snv), bool(ins), bool(dlt)]) != 1: raise(Exception("S...
Check if mutations in vcf are in bam def validate_mutations(vcffile, bams, reffa, chr_reffa, samples, output_format, outfile, mpileup_parameters=mpileup_parser.MPILEUP_DEFAULT_PARAMS): """Check if mutations in vcf are in bam""" output_header = "sample chrom pos ref cov A C G T * - + " \ ...
Prep a client by tagging it with and id and wrapping methods. Methods are wrapper to catch ConnectionError so that we can remove it from the pool until the instance comes back up. :returns: patched clients def _prep_clients(self, clients): """Prep a client by tagging it with and id an...
Wrap public functions to catch ConnectionError. When an error happens, it puts the client in the penalty box so that it won't be retried again for a little while. def _wrap_functions(self, client): """Wrap public functions to catch ConnectionError. When an error happens, it puts the c...
Restores clients that have reconnected. This function should be called first for every public method. def _prune_penalty_box(self): """Restores clients that have reconnected. This function should be called first for every public method. """ added = False for client in ...
Get the client for a given shard, based on what's available. If the proper client isn't available, the next available client is returned. If no clients are available, an exception is raised. def get_client(self, shard_key): """Get the client for a given shard, based on what's available. ...
Place client in the penalty box. :param client: Client object def _penalize_client(self, client): """Place client in the penalty box. :param client: Client object """ if client in self.active_clients: # hasn't been removed yet log.warning("%r marked down.", client...
Get the zrevrangebyscore across the cluster. Highest score for duplicate element is returned. A faster method should be written if scores are not needed. def zrevrange_with_int_score(self, key, max_score, min_score): """Get the zrevrangebyscore across the cluster. Highest score for dupl...
A helper function to interact with the regular expression engine that compiles and applies partial matches to a string. It expects key value tuples as arguments (any number of them) where the first pair is the regex to compile and the latter is the message to display when the regular expression does no...
Takes files from React side, creates SolveBio Object containing signed S3 URL. def generate_s3_url(files): """Takes files from React side, creates SolveBio Object containing signed S3 URL.""" if files: vault = g.client.Vault.get_personal_vault() files = json.loads(files) objects...
Handles downstream processes using metadata about the uploaded files from React side. def handle_uploaded_files(uploaded_files): """Handles downstream processes using metadata about the uploaded files from React side.""" if uploaded_files: uploaded_files = json.loads(uploaded_files)[0] ...
Create a custom camera panel. The camera panel type is specified in the 'camera_panel_type' key in the properties dict. The camera panel type must match a the 'camera_panel_type' of a camera panel factory in the Registry. The matching camera panel factory must return a ui_handler for the panel which is u...
Call this to initialize the state of the UI after everything has been connected. def initialize_state(self): """ Call this to initialize the state of the UI after everything has been connected. """ if self.__hardware_source: self.__profile_changed_event_listener = self.__hardware_source.pro...
Call this when the user clicks the play/pause button. def handle_play_pause_clicked(self): """ Call this when the user clicks the play/pause button. """ if self.__hardware_source: if self.is_playing: self.__hardware_source.stop_playing() else: sel...
Setup any data here, this method will be called before final SQL is generated def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): """Setup any data here, this method will be called before final SQL is generated""" c = self.copy() c.is_summary...
Prepare SQL from inner funcions (ll_to_earth or any other) def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): """Prepare SQL from inner funcions (ll_to_earth or any other)""" c = self.copy() c.is_summary = summarize c.for_save = for_...
Filter rows inside a circunference of radius distance `distance` :param distance: max distance to allow :param fields: `tuple` with the fields to filter (latitude, longitude) :param points: center of the circunference (latitude, longitude) :param annotate: name where the...
Gets a value for the specified path. :param path: the configuration key to fetch a value for, steps separated by the separator supplied to the constructor (default ``.``) :param default: a value to return if no value is found for the supplied path (``None`` is allowe...
Chisel action decorator def action(action_callback=None, **kwargs): """ Chisel action decorator """ if action_callback is None: return lambda fn: action(fn, **kwargs) else: return Action(action_callback, **kwargs).decorate_module(action_callback)
Call this when the user clicks the record button. def record_async(self, callback_fn): """ Call this when the user clicks the record button. """ assert callable(callback_fn) def record_thread(): current_frame_time = self.get_current_frame_time() def handle_finished(xda...
Get recently acquired (buffered) data. The start parameter can be negative to index backwards from the end. If start refers to a buffer item that doesn't exist or if count requests too many buffer items given the start value, the returned list may have fewer elements than count. Retur...
we nest all plain logs to prevent double log shipping def get_plain_logname(base_name, root_dir, enable_json): """ we nest all plain logs to prevent double log shipping """ if enable_json: nested_dir = os.path.join(root_dir, 'plain') if os.path.exists(root_dir) and not os.path.exists(ne...
json_formatter: 'fan.contrib.django.span_formatter.SpanFormatter' - add INSTALLATION_ID, SPAN and etc def setup_logger( base_name, root_dir=None, enable_json=True, json_formatter='tipsi_tools.tipsi_logging.JSFormatter', loggers={}, ): """ json_formatter: 'fan.contrib.django.span_for...
Run command in shell, accepts command construction from list Return (return_code, stdout, stderr) stdout and stderr - as list of strings def run(command): ''' Run command in shell, accepts command construction from list Return (return_code, stdout, stderr) stdout and stderr - as list of strings...
Alias to run with check return code and stderr def succ(cmd, check_stderr=True, stdout=None, stderr=None): ''' Alias to run with check return code and stderr ''' code, out, err = run(cmd) # Because we're raising error, sometimes we want to process stdout/stderr after catching error # so we're ...
Wait for socket opened on remote side. Return False after timeout def wait_socket(host, port, timeout=120): ''' Wait for socket opened on remote side. Return False after timeout ''' return wait_result(lambda: check_socket(host, port), True, timeout)
Format line system environment variables + defaults def interpolate_sysenv(line, defaults={}): ''' Format line system environment variables + defaults ''' map = ChainMap(os.environ, defaults) return line.format(**map)
Acts similar to bash 'source' or '.' commands. def source(fname): ''' Acts similar to bash 'source' or '.' commands. ''' rex = re.compile('(?:export |declare -x )?(.*?)="(.*?)"') out = call_out('source {} && export'.format(fname)) out = [x for x in out if 'export' in x or 'declare' in x] ou...
do something in other directory and return back after block ended def cd(dir_name): """ do something in other directory and return back after block ended """ old_path = os.path.abspath('.') os.chdir(dir_name) try: yield os.chdir(old_path) except Exception: os.chdir(o...
Returns True if identifier hasn't been seen before. def _is_new(self, identifier): """Returns True if identifier hasn't been seen before.""" if identifier in self.tracker: return False else: self.tracker.append(identifier) self.tracker.pop(0) retu...
Called when a GET request is sent to /rooms/{room_alias} def on_get(self, request, response, room_alias=None): """Called when a GET request is sent to /rooms/{room_alias}""" response.body = "{}" if self.handler(room_alias): response.status = falcon.HTTP_200 self.api.crea...
Responds to PUT request containing events. def on_put(self, request, response, txn_id=None): """Responds to PUT request containing events.""" response.body = "{}" # Check whether repeat txn_id if not self._is_new(txn_id): response.status = falcon.HTTP_200 return...
Responds to GET request for users. def on_get(self, request, response, user_id=None): """Responds to GET request for users.""" response.body = "{}" if self.handler(user_id): response.status = falcon.HTTP_200 self.api.register(utils.mxid2localpart(user_id)) else: ...
Set the frame parameters with the settings index and fire the frame parameters changed event. If the settings index matches the current settings index, call set current frame parameters. If the settings index matches the record settings index, call set record frame parameters. def set_frame_parameter...