output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def state_invariant_scope(self, state: Sequence[tf.Tensor]): '''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`. ...
Implement a Python 3 function for returning the state invariant fluent scope for the current state.
As a Python code composer, you craft elegant and concise scripts.
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, self.rddl.domain.non_fluent_o...
How would you code a function in Python 3 to return the non - fluents instantiated.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the initial state - fluents instantiated.
Given the following Python 3 function, write the documentation 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._...
You are a Python code generator, capable of creating scripts from specifications.
Returns the default action - fluents instantiated.
Make a summary of the following Python 3 code 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, s...
As a Python code composer, you craft elegant and concise scripts.
def _compile_batch_fluents(self, fluents: List[Tuple[str, TensorFluent]], batch_size: int) -> Sequence[tf.Tensor]: '''Compiles `fluents` into tensors with given `batch_size`. Returns: Sequence[tf.Tensor]: A tuple of tensors with first dimension correspond...
Write a Python 3 script for compiling fluents into tensors with given batch_size.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _compile_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> TensorFluent: '''Compile the expression `e...
How would you implement a function in Python 3 that compiles the expression expr into a TensorFluent in the given scope with optional batch size.
As a Python code analyst, you investigate and solve complex coding mysteries
def _compile_constant_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> Tenso...
Implement a Python 3 function for compiling a constant expression expr into a TensorFluent in the given scope with optional batch size.
You are a Python code generator, capable of creating scripts from specifications.
def _compile_pvariable_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> ...
Can you implement a function in Python 3 that compiles a pvariable expression expr into a TensorFluent in the given scope with optional batch size.
You are a Python code generator, capable of creating scripts from specifications.
def _compile_random_variable_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optiona...
Create a Python 3 function to compile a random variable expression expr into a TensorFluent in the given scope with optional batch size and optional noise.
You are a Python code architect, reviewing and designing scalable and efficient code
def _compile_arithmetic_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None...
Implement a function in Python 3 to compile an arithmetic expression expr into a TensorFluent in the given scope with optional batch size.
You are a Python code generator, capable of creating scripts from specifications.
def _compile_function_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> Tenso...
How would you implement a function in Python 3 that compiles a RDDL unary function expression expr into a TensorFluent in the given scope with optional batch size.
You are a Python code analyst, evaluating scripts for potential improvements.
Compile a control flow expression expr into a TensorFluent in the given scope with optional batch size.
How would you explain what the following Python 3 function does def _compile_control_flow_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, ...
As a python code expert, you are capable of creating scripts from specifications.
def _compile_aggregation_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] =...
How would you code a function in Python 3 to compile an aggregation expression expr into a TensorFluent in the given scope with optional batch size.
As a python code expert, you are capable of creating scripts from specifications.
def mask(self, table): """ 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 ""...
Can you write a function in Python 3 where it returns a numpy array that contains the number of entries in table that satisfy the queries.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a filtered version of the table.
Can you tell what is the following Python 3 function doing def filter(self, table, column_slice=None): if self._operator is None and self._operands is None: return table if column_slice is None else self._get_table_column(table, column_slice) if self._operator == 'AND' and column_slice is N...
You are a Python code architect, reviewing and designing scalable and efficient code
def count(self, table): """ 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 """ i...
Create a Python 3 function to return the number of entries in table that satisfy the queries.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get all variable names required for this query.
How would you explain what the following Python 3 function does def variable_names(self): if self._variable_names is None: if self._operator is None: if self._operands is None: self._variable_names = tuple() else: self._variabl...
You are a Python code generator, capable of creating scripts from specifications.
Creates a User object when requested.
Explain what the following Python 3 code does def user(self): try: return self._user except AttributeError: self._user = MatrixUser(self.mxid, self.Api(identity=self.mxid)) return self._user
As a Python code analyst, you investigate and solve complex coding mysteries
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
Can you implement a function in Python 3 that creates a Room object when requested.
As a Python code translator, you convert algorithms and pseudocode into Python.
Joins a room id or alias even if it must first be created.
Explain what the following Python 3 code does def join(self, room_str): response = self.user_api.join_room(room_str) return self._mkroom(response["room_id"])
As a Python code composer, you craft elegant and concise scripts.
Calls GET / joined_rooms to refresh rooms list.
Can you generate a brief explanation for the following Python 3 code def refresh_rooms(self): for room_id in self.user_api.get_joined_rooms()["joined_rooms"]: self._rooms[room_id] = MatrixRoom(room_id, self.user_api)
As a Python code composer, you craft elegant and concise scripts.
Validates the given input is not empty.
Can you generate a brief explanation for the following Python 3 code def not_empty(_object): if is_callable(_object): _validator = _object @wraps(_validator) @instance_of() def decorated(value): ensure(value, "%s is empty" % safe_repr(value)) return _validato...
You are a Python code generator, capable of creating scripts from specifications.
Set a walltime for the job
How would you explain what the following Python 3 function does def set_walltime(self, walltime): if not isinstance(walltime, timedelta): raise TypeError( 'walltime must be an instance of datetime.timedelta. %s given' % type(walltime) ) self._opti...
You are a Python code architect, reviewing and designing scalable and efficient code
Requests the specified url and returns a BeautifulSoup object with its contents.
Can you generate the documentation for the following Python 3 function def get_url(url, parser='html'): url = request.quote(url, safe=':/?=&') logger.debug('URL: %s', url) req = request.Request(url, headers={'User-Agent': 'foobar'}) try: response = request.urlopen(req) except HTTPError: ...
As a Python code composer, you craft elegant and concise scripts.
Request the specified method from the lastfm api.
Can you tell what is the following Python 3 function doing def get_lastfm(method, lastfm_key='', **kwargs): if not lastfm_key: if 'lastfm_key' not in CONFIG or not CONFIG['lastfm_key']: logger.warning('No lastfm key configured') return '' else: lastfm_key = CONFIG...
You are a Python code analyst, evaluating scripts for potential improvements.
Normalizes a string according to the given characters.
Here you have a function in Python 3, explain what it does def normalize(string, chars_to_remove=None, replacement=''): ret = string.translate(str.maketrans({ 'á': 'a', 'ä': 'a', 'æ': 'ae', 'é': 'e', 'í': 'i', 'ó': 'o', 'ö': 'o', 'ú': 'u', 'ü':...
As a Python code translator, you convert algorithms and pseudocode into Python.
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.lower() title = normalize(title, translate) title = re.sub(r'\-{2,}', '-', title) artist = song....
Create a Python 3 function for returning the lyrics found in metrolyrics for the specified mp3 file or an empty string if not found.
As a python code expert, you are capable of creating scripts from specifications.
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, 'album') or not song.album: song.fetch_album_name() if not hasattr(song, 'album') or not so...
How would you code a function in Python 3 to return the lyrics found in darklyrics for the specified mp3 file.
As a Python code composer, you craft elegant and concise scripts.
Returns the lyrics found in azlyrics for the specified mp3 file.
Can you generate a brief explanation for the following Python 3 code def azlyrics(song): artist = song.artist.lower() if artist[0:2] == 'a ': artist = artist[2:] artist = normalize(artist, URLESCAPES, '') title = song.title.lower() title = normalize(title, URLESCAPES, '') url = 'https:/...
As a Python code translator, you convert algorithms and pseudocode into Python.
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: '', ' ': '-' } artist = song.artist.capitalize() artist = normalize(artist, transla...
How would you implement a function in Python 3 that returns the lyrics found in genius. com for the specified mp3 file or an empty string if not found.
As a Python code composer, you craft elegant and concise scripts.
Returns the lyrics found in MetalArchives for the specified mp3 file or an empty string if not found.
How would you explain what the following Python 3 function does def metalarchives(song): artist = normalize(song.artist) title = normalize(song.title) url = 'https://www.metal-archives.com/search/ajax-advanced/searching/songs' url += f'/?songTitle={title}&bandName={artist}&ExactBandMatch=1' soup = ...
You are a Python code generator, capable of creating scripts from specifications.
Returns the lyrics found in lyrics. wikia. com for the specified mp3 file or an empty string if not found.
Can you tell what is the following Python 3 function doing def lyricswikia(song): artist = song.artist.title() artist = normalize(artist, ' ', '_') title = song.title title = normalize(title, ' ', '_') url = 'https://lyrics.wikia.com/wiki/{}:{}'.format(artist, title) soup = get_url(url) tex...
You are a Python code generator, capable of creating scripts from specifications.
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 = { escape: '', ' ': '-' } artist = song.artist.title() artist = re.sub(r"( '|' )", '', ar...
How would you implement a function in Python 3 that returns the lyrics found in musixmatch for the specified mp3 file or an empty string if not found.
You are a Python code generator, capable of creating scripts from specifications.
Returns the lyrics found in songlyrics. com for the specified mp3 file or an empty string if not found.
Explain what the following Python 3 code does def songlyrics(song): translate = { URLESCAPE: '', ' ': '-' } artist = song.artist.lower() artist = normalize(artist, translate) title = song.title.lower() title = normalize(title, translate) artist = re.sub(r'\-{2,}', '-', artis...
You are a Python code analyst, evaluating scripts for potential improvements.
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, ' ', '+') title = song.title url = 'https://www.lyrics.com/artist/{}'.format(artist) soup = get_url...
Create a Python 3 function for returning the lyrics found in lyrics. com for the specified mp3 file or an empty string if not found.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the lyrics found in vagalume. com. br for the specified mp3 file or an empty string if not found.
How would you explain what the following Python 3 function does def vagalume(song): translate = { '@': 'a', URLESCAPE: '', ' ': '-' } artist = song.artist.lower() artist = normalize(artist, translate) artist = re.sub(r'\-{2,}', '-', artist) title = song.title.lower() ...
As a Python code composer, you craft elegant and concise scripts.
Returns the lyrics found in lyricsmode. com for the specified mp3 file.
Make a summary of the following Python 3 code def lyricsmode(song): translate = { URLESCAPE: '', ' ': '_' } artist = song.artist.lower() artist = normalize(artist, translate) title = song.title.lower() title = normalize(title, translate) artist = re.sub(r'\_{2,}', '_', artis...
You are a Python code analyst, evaluating scripts for potential improvements.
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: '', ' ': '-' } artist = song.artist.lower() artist = normalize(artist, translate) title = song.title...
Implement a Python 3 function for returning the lyrics found in letras. com for the specified mp3 file or an empty string if not found.
You are a Python code analyst, evaluating scripts for potential improvements.
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]
Create a Python 3 function for returning the name of a website - scrapping function.
You are a Python code analyst, evaluating scripts for potential improvements.
async def update_gitlab_loop(update_metrics, params): """ app = Sanic() mserver = MetricsServer(app) mserver.add_task(update_gitlab_loop, params={'url': GITLAB_URL, 'token': token}) """ gitlab_api = gitlab.Gitlab(url=params['url'], private_token=params['token'], api_version=4) while True: ...
Implement a Python 3 function for updating metrics for a single gitlab instance.
As a Python code analyst, you investigate and solve complex coding mysteries
Sets the probe position in normalized coordinates with origin at top left.
Can you generate the documentation for the following Python 3 function def set_probe_position(self, new_probe_position): if new_probe_position is not None: # convert the probe position to a FloatPoint and limit it to the 0.0 to 1.0 range in both axes. new_probe_position = Geometry.FloatP...
As a Python code composer, you craft elegant and concise scripts.
Applies metadata groups to properties.
Can you generate a brief explanation for the following Python 3 code def apply_metadata_groups(self, properties: typing.Dict, metatdata_groups: typing.Tuple[typing.List[str], str]) -> None: pass
As a python code expert, you are capable of creating scripts from specifications.
Creates a new Analytics backend from the settings
Can you tell what is the following Python 3 function doing def create_analytic_backend(settings): backend = settings.get('backend') if isinstance(backend, basestring): backend = import_string(backend) elif backend: backend = backend else: raise KeyError('backend') return bac...
As a Python code translator, you convert algorithms and pseudocode into Python.
Initialize the state of the UI.
Here you have a function in Python 3, explain what it does def initialize_state(self): if self.__scan_hardware_source: self.__profile_changed_event_listener = self.__scan_hardware_source.profile_changed_event.listen(self.__update_profile_index) self.__frame_parameters_changed_event_liste...
As a Python code analyst, you investigate and solve complex coding mysteries
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: self.__scan_hardware_source.start_playing()
Write a Python 3 script for calling this when the user clicks the play or pause button.
As a Python code composer, you craft elegant and concise scripts.
Handle the record button clicked.
Can you generate the documentation for the following Python 3 function def handle_record_clicked(self, callback_fn): assert callable(callback_fn) if self.__scan_hardware_source: def finish_record(data_and_metadata_list): record_index = self.__scan_hardware_source.record_inde...
You are a Python code architect, reviewing and designing scalable and efficient code
Size the canvas item to the text content.
Can you generate the documentation for the following Python 3 function def size_to_content(self, horizontal_padding=None, vertical_padding=None): if horizontal_padding is None: horizontal_padding = 0 if vertical_padding is None: vertical_padding = 0 self.sizing.set_fix...
As a python code expert, you are capable of creating scripts from specifications.
Return after <rounds > passes through a cycled iterable.
How would you explain what the following Python 3 function does def round_controlled(cycled_iterable, rounds=1): round_start = None rounds_completed = 0 for item in cycled_iterable: if round_start is None: round_start = item elif item == round_start: rounds_completed...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a float with the rate of success from all the logged results.
Here you have a function in Python 3, explain what it does def success_rate(self): if self.successes + self.fails == 0: success_rate = 0 else: total_attempts = self.successes + self.fails success_rate = (self.successes * 100 / total_attempts) return success_r...
You are a Python code analyst, evaluating scripts for potential improvements.
Adds a new record to the statistics database.
Here you have a function in Python 3, explain what it does def add_result(self, source, found, runtime): self.source_stats[source.__name__].add_runtime(runtime) if found: self.source_stats[source.__name__].successes += 1 else: self.source_stats[source.__name__].fails += 1
As a python code expert, you are capable of creating scripts from specifications.
def avg_time(self, source=None): """ 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. """ if source is None: run...
Write a Python 3 script to return the average time taken to scrape the lyrics from a source or the total average time taken to scrape the lyrics from that source.
As a Python code composer, you craft elegant and concise scripts.
def calculate(self): """ 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. """ best, worst, fastest, slowest = (), (), (), () found...
How would you implement a function in Python 3 that calculates the overall counts of best worst fastest slowest total not found and total runtime.
As a Python code translator, you convert algorithms and pseudocode into Python.
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. """ stats = self.calculate() total_time = '%d:%02d:%02d' % (stats['total_time'] / 3600, ...
Write a Python 3 script to print a series of relevant stats about a full execution. This function is meant to be called at the end of the program.
You are a Python code analyst, evaluating scripts for potential improvements.
This function broadcasts the smaller scope over the larger scope. It broadcasts the smaller scope over the larger scope. It handles scope intersection as well as differences in scopes and outputs a resulting scope so that input scopes are subscopes of the resulting scope.
How would you explain what the following Python 3 function does def broadcast(cls, s1: ParamsList, s2: ParamsList) -> BroadcastTuple: '''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 ...
You are a Python code analyst, evaluating scripts for potential improvements.
Turn baseParser results into a dataframe
Here you have a function in Python 3, explain what it does def get_baseparser_extended_df(sample, bp_lines, ref, alt): 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 per indel bpdf = pd.DataFrame([...
As a Python code translator, you convert algorithms and pseudocode into Python.
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(normaldf, on=["chrom", "pos"], suffixes=...
Create a Python 3 function to filter out mutations that are in normal.
As a Python code composer, you craft elegant and concise scripts.
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("Should be either snv, ins or del".format(snv))) if snv: if snv ...
Can you create a Python 3 function that selects only mutations that revert the given mutations in a single event.
You are a Python code analyst, evaluating scripts for potential improvements.
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 * - + " \ "val_ref val_alt val_al_type v...
Implement a function in Python 3 to validate mutations in vcf file.
You are a Python code architect, reviewing and designing scalable and efficient code
Prepare a list of clients by tagging it with and id and wrapping methods.
Can you generate the documentation for the following Python 3 function def _prep_clients(self, clients): for pool_id, client in enumerate(clients): # Tag it with an id we'll use to identify it in the pool if hasattr(client, "pool_id"): raise ValueError("%r is already part...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _wrap_functions(self, client): """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(fn): def wrapper(*args, **kwargs): "...
Write a Python 3 function that can wrap public functions to catch ConnectionError and TimeoutError.
You are a Python code architect, reviewing and designing scalable and efficient code
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 self.penalty_box.get(): log.info("Client %r is back up.", client) self.active_clients.ap...
Can you write a function in Python 3 where it restores clients that have reconnected.
You are a Python code architect, reviewing and designing scalable and efficient code
Get the client for a given shard.
Make a summary of the following Python 3 code def get_client(self, shard_key): self._prune_penalty_box() if len(self.active_clients) == 0: raise ClusterEmptyError("All clients are down.") # So that hashing is consistent when a node is down, check against # the initial clien...
As a Python code translator, you convert algorithms and pseudocode into Python.
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) self.active_clients.remove(client) self.penalt...
Write a Python 3 function that can place client in the penalty box.
You are a Python code analyst, evaluating scripts for potential improvements.
def zrevrange_with_int_score(self, key, max_score, min_score): """Get the zrevrangebyscore across the cluster. Highest score for duplicate element is returned. A faster method should be written if scores are not needed. """ self._prune_penalty_box() if len(self.active_cl...
Write a Python 3 script for getting the zrevrangebyscore across the cluster.
You are a Python code generator, capable of creating scripts from specifications.
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 = [] for i in xrange(len(files)): obj = g.client.Object.create(...
Implement a Python 3 function for taking files from React side creates SolveBio Object containing signed S3 URL.
You are a Python code generator, capable of creating scripts from specifications.
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] _id = uploaded_files.get('id') # Strip extension from filename _filename = ...
Write a Python 3 script to handle downstream processes using metadata about the uploaded files from React side.
You are a Python code generator, capable of creating scripts from specifications.
def create_camera_panel(document_controller, panel_id, properties): """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 matc...
Create a Python 3 function to create a custom camera panel.
As a Python code analyst, you investigate and solve complex coding mysteries
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.profile_changed_event.listen(self.__update_profile_index) self.__frame_pa...
Create a Python 3 function for initializing the state of the class.
You are a Python code analyst, evaluating scripts for potential improvements.
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: self.__hardware_source.start_playing()
How would you code a function in Python 3 to call this when the user clicks the play or pause button.
You are a Python code architect, reviewing and designing scalable and efficient code
Setup any data here this method will be called before final SQL is generated
Can you generate a brief explanation for the following Python 3 code def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): c = self.copy() c.is_summary = summarize c.for_save = for_save final_points = [] for i, p in enumerate(sel...
As a python code expert, you are capable of creating scripts from specifications.
Prepare SQL from inner funcions.
Can you tell what is the following Python 3 function doing def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False): c = self.copy() c.is_summary = summarize c.for_save = for_save for pos, expression in enumerate(self.expressions): ...
You are a Python code analyst, evaluating scripts for potential improvements.
def in_distance(self, distance, fields, points, annotate='_ed_distance'): """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 o...
Write a Python 3 script for filtering rows inside a circunference of radius distance distance
You are a Python code analyst, evaluating scripts for potential improvements.
def get(self, path, default=_NoDefault, as_type=None, resolve_references=True): """ 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 d...
How would you implement a function in Python 3 that gets a value for the specified configuration key.
As a Python code composer, you craft elegant and concise scripts.
Call this when the user clicks the record button.
Explain what the following Python 3 code does def record_async(self, callback_fn): assert callable(callback_fn) def record_thread(): current_frame_time = self.get_current_frame_time() def handle_finished(xdatas): callback_fn(xdatas) self.start_recor...
You are a Python code architect, reviewing and designing scalable and efficient code
Get the recently acquired buffer data.
How would you explain what the following Python 3 function does def get_buffer_data(self, start: int, count: int) -> typing.Optional[typing.List[typing.List[typing.Dict]]]: if hasattr(self.__device, "get_buffer_data"): buffer_data = self.__device.get_buffer_data(start, count) enabled_ch...
You are a Python code architect, reviewing and designing scalable and efficient code
Get the log name for a plain log file.
Explain what the following Python 3 code does def get_plain_logname(base_name, root_dir, enable_json): if enable_json: nested_dir = os.path.join(root_dir, 'plain') if os.path.exists(root_dir) and not os.path.exists(nested_dir): os.mkdir(nested_dir) root_dir = nested_dir retur...
As a Python code analyst, you investigate and solve complex coding mysteries
Setup the logger for the given base_name root_dir and loggers.
Given the following Python 3 function, write the documentation 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_formatter.SpanFormatter' - add INSTALLATION_ID,...
As a Python code analyst, you investigate and solve complex coding mysteries
Run command in shell accepts command construction from list Return return code stdout and stderr - as list of strings
Can you generate a brief explanation for the following Python 3 code def run(command): ''' Run command in shell, accepts command construction from list Return (return_code, stdout, stderr) stdout and stderr - as list of strings ''' if isinstance(command, list): command = ' '.join(command...
You are a Python code generator, capable of creating scripts from specifications.
Run a command and return the output and error.
Can you generate a brief explanation for the following Python 3 code 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 ...
You are a Python code analyst, evaluating scripts for potential improvements.
Wait for socket opened on remote side. Return False after timeout.
Given the following Python 3 function, write the documentation 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)
You are a Python code architect, reviewing and designing scalable and efficient code
Interpolate line system environment variables + defaults
Can you generate the documentation for the following Python 3 function def interpolate_sysenv(line, defaults={}): ''' Format line system environment variables + defaults ''' map = ChainMap(os.environ, defaults) return line.format(**map)
You are a Python code analyst, evaluating scripts for potential improvements.
Acts similar to bash source or. commands. Acts similar to bash source or. commands. Acts similar to bash source or. commands.
Can you generate a brief explanation for the following Python 3 code 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 '...
As a Python code composer, you craft elegant and concise scripts.
cd - yield the current directory and return back after block ended
Can you generate the documentation for the following Python 3 function def cd(dir_name): old_path = os.path.abspath('.') os.chdir(dir_name) try: yield os.chdir(old_path) except Exception: os.chdir(old_path) raise
As a Python code analyst, you investigate and solve complex coding mysteries
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) return True
Can you create a Python 3 function that returns True if identifier has not been seen before.
You are a Python code architect, reviewing and designing scalable and efficient code
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.create_room(alias=room_alias) else: respon...
Can you create a Python 3 function that calls when a GET request is sent to the room
As a python code expert, you are capable of creating scripts from specifications.
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 request.context["body"] = request....
Write a Python 3 script to respond to PUT request containing events.
As a Python code translator, you convert algorithms and pseudocode into Python.
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: response.status = falcon...
Can you implement a function in Python 3 that responds to GET request for users.
As a python code expert, you are capable of creating scripts from specifications.
def set_frame_parameters(self, profile_index: int, frame_parameters) -> None: """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 matc...
Create a Python 3 function for setting the frame parameters with the settings index and fire the frame parameters changed event.
As a Python code translator, you convert algorithms and pseudocode into Python.
This function is used to wrap the Verlet class in order to generate a list of verlets for a given differential system.
How would you explain what the following Python 3 function does def verlet(dfun, xzero, vzero, timerange, timestep): '''Verlet method integration. This function wraps the Verlet class. :param dfun: second derivative function of the system. The differential system arranged as a serie...
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a request object to the internal list of requests and URLs.
How would you explain what the following Python 3 function does def add_request(self, request): # Duplicate request name? if request.name in self.requests: raise ValueError('redefinition of request "{0}"'.format(request.name)) self.requests[request.name] = request # Add the...
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a response header to the internal dictionary.
How would you explain what the following Python 3 function does def add_header(self, key, value): assert isinstance(key, str), 'header key must be of type str' assert isinstance(value, str), 'header value must be of type str' self.headers[key] = value
As a Python code analyst, you investigate and solve complex coding mysteries
Send an HTTP response to the application.
Here you have a function in Python 3, explain what it does def response(self, status, content_type, content, headers=None): assert not isinstance(content, (str, bytes)), 'response content cannot be of type str or bytes' response_headers = [('Content-Type', content_type)] if headers: ...
As a python code expert, you are capable of creating scripts from specifications.
def response_text(self, status, text=None, content_type='text/plain', encoding='utf-8', headers=None): """ Send a plain-text response """ if text is None: if isinstance(status, str): text = status else: text = status.phrase ...
How would you code a function in Python 3 to send a plain - text response.
You are a Python code generator, capable of creating scripts from specifications.
def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None): """ Send a JSON response """ encoder = JSONEncoder( check_circular=self.app.validate_output, allow_nan=False, sort_keys=True, ...
Create a Python 3 function for sending a JSON response
As a Python code composer, you craft elegant and concise scripts.
def reconstruct_url(self, path_info=None, query_string=None, relative=False): """ Reconstructs the request URL using the algorithm provided by PEP3333 """ environ = self.environ if relative: url = '' else: url = environ['wsgi.url_scheme'] + '://' ...
Implement a function in Python 3 to reconstruct the URL using the algorithm provided by PEP3333_get_url_from_environ.
As a Python code composer, you craft elegant and concise scripts.
def read_xdg_config_dirs(name, extension): """ Read from files found in XDG-specified system-wide configuration paths, defaulting to ``/etc/xdg``. Depends on ``XDG_CONFIG_DIRS`` environment variable. :param name: application or configuration set name :param extension: file extension to look for...
Implement a function in Python 3 to read from files found in XDG - specified system - wide configuration directories.
You are a Python code architect, reviewing and designing scalable and efficient code
def read_xdg_config_home(name, extension): """ Read from file found in XDG-specified configuration home directory, expanding to ``${HOME}/.config/name.extension`` by default. Depends on ``XDG_CONFIG_HOME`` or ``HOME`` environment variables. :param name: application or configuration set name :pa...
Write a Python 3 script to read from file found in XDG - specified configuration home directory.
As a Python code translator, you convert algorithms and pseudocode into Python.
def read_envvars(name, extension): """ Read environment variables starting with ``NAME_``, where subsequent underscores are interpreted as namespaces. Underscores can be retained as namespaces by doubling them up, e.g. ``NAME_SPA__CE_KEY`` would be accessible in the resulting `.Configuration` as ...
Implement a function in Python 3 to read environment variables starting with NAME_ and returns a Configuration instance.
You are a Python code architect, reviewing and designing scalable and efficient code
Read values from a file provided as a environment variable .
How would you explain what the following Python 3 function does def read_envvar_file(name, extension): envvar_file = environ.get('{}_config_file'.format(name).upper()) if envvar_file: # envvar set, load value as file return loadf(envvar_file) else: # envvar not set, return an empty s...
As a python code expert, you are capable of creating scripts from specifications.
Read values from a file located in a directory specified by an environment variable.
How would you explain what the following Python 3 function does def read_envvar_dir(envvar, name, extension): config_dir = environ.get(envvar) if not config_dir: return NotConfigured # envvar is set, construct full file path, expanding user to allow the envvar containing a value like ~/config c...
You are a Python code architect, reviewing and designing scalable and efficient code