output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Initializes the global parser and the global arguments for the a logger.
Here you have a function in Python 3, explain what it does def initialize(glob, sudo=False, multi_level_debug=False, add_config=False, add_demo=False, add_interact=False, add_step=False, add_time=False, ...
As a Python code analyst, you investigate and solve complex coding mysteries
Function for validating group of arguments
Can you tell what is the following Python 3 function doing def validate(glob, *arg_checks): locals().update(glob) # allows to import user-defined objects from glob # into the local scope if glob['args'] is None or glob['logger'] is None: return exit_app = False for c...
You are a Python code analyst, evaluating scripts for potential improvements.
Calcualte mse between vector or matrix x and xhat
Here you have a function in Python 3, explain what it does def mse(x, xhat): buf_ = x - xhat np.square(buf_, out=buf_) # square in-place sum_ = np.sum(buf_) sum_ /= x.size # divide in-place return sum_
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns an approximation of A of rank r in least - squares sense.
Explain what the following Python 3 code does def low_rank_approximation(A, r): try: u, s, v = np.linalg.svd(A, full_matrices=False) except np.linalg.LinAlgError as e: print('Matrix:', A) print('Matrix rank:', np.linalg.matrix_rank(A)) raise Ar = np.zeros((len(u), len(v)), d...
You are a Python code generator, capable of creating scripts from specifications.
Computes the sorted eigendecomposition of G.
Given the following Python 3 function, write the documentation def eigendecomp(G, d): N = G.shape[0] lamda, u = np.linalg.eig(G) # test decomposition of G. #G_hat = np.dot(np.dot(u, np.diag(lamda)), u.T) #assert np.linalg.norm(G_hat - G) < 1e-10, 'decomposition not exact: err {}'.format(np.linalg.no...
You are a Python code generator, capable of creating scripts from specifications.
def projection(x, A, b): """ Returns the vector xhat closest to x in 2-norm, satisfying A.xhat =b. :param x: vector :param A, b: matrix and array characterizing the constraints on x (A.x = b) :return x_hat: optimum angle vector, minimizing cost. :return cost: least square error of xhat, x :re...
Can you write a function in Python 3 where it returns the vector xhat closest to x in 2 - norm satisfying A. xhat = b.
You are a Python code analyst, evaluating scripts for potential improvements.
def build_comparators(*values_or_types): ''' All of the comparators that can be used for arguments. ''' comparators = [] for item in values_or_types: if isinstance(item, Comparator): comparators.append(item) elif isinstance(item, type): # If you are passing ar...
Can you implement a function in Python 3 that builds a list of all of the comparators that can be used for arguments.
As a Python code composer, you craft elegant and concise scripts.
Adds a new ArgumentsExpectationRule to the expectation
Here you have a function in Python 3, explain what it does def args(self, *args, **kwargs): self._any_args = False self._arguments_rule.set_args(*args, **kwargs) return self
You are a Python code analyst, evaluating scripts for potential improvements.
def return_value(self): """ Returns the value for this expectation or raises the proper exception. """ if self._raises: # Handle exceptions if inspect.isclass(self._raises): raise self._raises() else: raise self._raises ...
How would you code a function in Python 3 to return the value for this expectation or raises the proper exception.
As a Python code translator, you convert algorithms and pseudocode into Python.
def match(self, *args, **kwargs): """ Check the if these args match this expectation. """ return self._any_args or \ self._arguments_rule.validate(*args, **kwargs)
Can you implement a function in Python 3 that checks if these args match this expectation.
As a python code expert, you are capable of creating scripts from specifications.
Load default record file factory.
Can you generate the documentation for the following Python 3 function def record_file_factory(self): try: get_distribution('invenio-records-files') from invenio_records_files.utils import record_file_factory default = record_file_factory except DistributionNotFound: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def register_previewer(self, name, previewer): """Register a previewer in the system.""" if name in self.previewers: assert name not in self.previewers, \ "Previewer with same name already registered" self.previewers[name] = previewer if hasattr(previewer, 'pr...
Implement a Python 3 function for registering a previewer in the system.
As a Python code composer, you craft elegant and concise scripts.
def iter_previewers(self, previewers=None): """Get previewers ordered by PREVIEWER_PREVIEWERS_ORDER.""" if self.entry_point_group is not None: self.load_entry_point_group(self.entry_point_group) self.entry_point_group = None previewers = previewers or \ self....
Can you implement a function in Python 3 that iterates over the previewers.
As a Python code analyst, you investigate and solve complex coding mysteries
def init_app(self, app, entry_point_group='invenio_previewer.previewers'): """Flask application initialization.""" self.init_config(app) app.register_blueprint(blueprint) state = _InvenioPreviewerState( app, entry_point_group=entry_point_group) app.extensi...
Can you write a function in Python 3 where it initializes the Flask application.
As a Python code translator, you convert algorithms and pseudocode into Python.
def parse(self, data): """Parse a 9 bytes packet in the Humidity format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x2EB2", 'packet_length': 8, ...
Can you create a Python 3 function that parses a 9 bytes packet in the Humidity format and return a dictionary containing the data extracted.
As a Python code analyst, you investigate and solve complex coding mysteries
def create_tokenizer(self, name, config=dict()): """Create a pipeline component from a factory. name (unicode): Factory name to look up in `Language.factories`. config (dict): Configuration parameters to initialise component. RETURNS (callable): Pipeline component. """ i...
Can you create a Python 3 function that creates a pipeline component from a factory.
As a Python code analyst, you investigate and solve complex coding mysteries
def add_codes(err_cls): """Add error codes to string messages via class attribute names.""" class ErrorsWithCodes(object): def __getattribute__(self, code): msg = getattr(err_cls, code) return '[{code}] {msg}'.format(code=code, msg=msg) return ErrorsWithCodes()
Write a Python 3 script for adding error codes to string messages via class attribute names.
As a python code expert, you are capable of creating scripts from specifications.
def _warn(message, warn_type='user'): """ message (unicode): The message to display. category (Warning): The Warning to show. """ w_id = message.split('[', 1)[1].split(']', 1)[0] # get ID from string if warn_type in SPACY_WARNING_TYPES and w_id not in SPACY_WARNING_IGNORE: category = WA...
Can you write a function in Python 3 where it displays a warning message.
As a Python code composer, you craft elegant and concise scripts.
Download compatible model from default download path using pip.
Make a summary of the following Python 3 code def download(model=None, direct=False, *pip_args): if model is None: model = about.__default_corpus__ if direct: dl = download_model('{m}/{m}.tar.gz#egg={m}'.format(m=model), pip_args) else: shortcuts = get_json(about.__shortcuts__, "ava...
You are a Python code architect, reviewing and designing scalable and efficient code
def link(origin, link_name, force=False, model_path=None): """ Create a symlink for models within the spacy/data directory. Accepts either the name of a pip package, or the local path to the model data directory. Linking models allows loading them via spacy.load(link_name). """ if util.is_packag...
How would you code a function in Python 3 to create a symlink for models within the spacy data directory.
You are a Python code analyst, evaluating scripts for potential improvements.
Loads a language model from a data directory path. Creates a pipeline from meta. json and then calls from_disk() with path.
Can you generate a brief explanation for the following Python 3 code def load_model_from_path(model_path, meta=False, **overrides): from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers ...
You are a Python code architect, reviewing and designing scalable and efficient code
Check if string maps to a package installed via pip.
Given the following Python 3 function, write the documentation def is_package(name): name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True ...
You are a Python code analyst, evaluating scripts for potential improvements.
Yields an infinite series of linearly decaying values.
Make a summary of the following Python 3 code def decaying(start, stop, decay): def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1
As a python code expert, you are capable of creating scripts from specifications.
def read_json(location): """Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content. """ location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f)
Implement a function in Python 3 to open and load JSON from file.
As a Python code composer, you craft elegant and concise scripts.
def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: ...
Write a Python 3 script for getting user input from command line via raw_input.
As a Python code analyst, you investigate and solve complex coding mysteries
def print_table(data, title=None): """Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above. """ if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join...
How would you implement a function in Python 3 that prints data in table format.
As a Python code analyst, you investigate and solve complex coding mysteries
def print_markdown(data, title=None): """Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2. """ def excl_value(value): # contains path, i.e. personal info re...
Create a Python 3 function for printing data in GitHub - flavoured Markdown format for issues etc.
You are a Python code architect, reviewing and designing scalable and efficient code
def prints(*texts, **kwargs): """Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit. """ exits = kwargs.get('exits', None) ...
Write a Python 3 script for printing formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit.
As a Python code composer, you craft elegant and concise scripts.
def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped tex...
How would you implement a function in Python 3 that wraps text at given width using textwrap module.
As a Python code composer, you craft elegant and concise scripts.
Escapes HTML in a displaCy text.
Can you generate the documentation for the following Python 3 function def escape_html(text): text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text
As a Python code translator, you convert algorithms and pseudocode into Python.
def normalize_string_keys(old): """Given a dictionary, make sure keys are unicode strings, not bytes.""" new = {} for key, value in old.items(): if isinstance(key, bytes_): new[key.decode('utf8')] = value else: new[key] = value return new
Write a Python 3 script to give a dictionary make sure keys are unicode strings not bytes.
As a python code expert, you are capable of creating scripts from specifications.
Escape a string using the locale.
Here you have a function in Python 3, explain what it does def locale_escape(string, errors='replace'): ''' Mangle non-supported characters, for savages with ascii terminals. ''' encoding = locale.getpreferredencoding() string = string.encode(encoding, errors).decode('utf8') return string
You are a Python code generator, capable of creating scripts from specifications.
Parses an incoming CMU pronouncing dictionary file.
Can you generate the documentation for the following Python 3 function def parse_cmu(cmufh): pronunciations = list() for line in cmufh: line = line.strip().decode('utf-8') if line.startswith(';'): continue word, phones = line.split(" ", 1) pronunciations.append((word....
You are a Python code analyst, evaluating scripts for potential improvements.
def init_cmu(filehandle=None): """Initialize the module's pronunciation data. This function is called automatically the first time you attempt to use another function in the library that requires loading the pronunciation data from disk. You can call this function manually to control when and how t...
Can you implement a function in Python 3 that initializes the module s pronunciation data.
You are a Python code generator, capable of creating scripts from specifications.
Get the rhyming part of a string with CMUdict phones.
How would you explain what the following Python 3 function does def rhyming_part(phones): phones_list = phones.split() for i in range(len(phones_list) - 1, 0, -1): if phones_list[i][-1] in '12': return ' '.join(phones_list[i:]) return phones
As a Python code translator, you convert algorithms and pseudocode into Python.
Search the CMU dictionary for pronunciations matching a regular expression.
Can you tell what is the following Python 3 function doing def search(pattern): init_cmu() regexp = re.compile(r"\b" + pattern + r"\b") return [word for word, phones in pronunciations if regexp.search(phones)]
As a Python code composer, you craft elegant and concise scripts.
def search_stresses(pattern): """Get words whose stress pattern matches a regular expression. This function is a special case of :func:`search` that searches only the stress patterns of each pronunciation in the dictionary. You can get stress patterns for a word using the :func:`stresses_for_word` func...
Create a Python 3 function for searching the words whose stress pattern matches a regular expression.
You are a Python code analyst, evaluating scripts for potential improvements.
def rhymes(word): """Get words rhyming with a given word. This function may return an empty list if no rhyming words are found in the dictionary, or if the word you pass to the function is itself not found in the dictionary. .. doctest:: >>> import pronouncing >>> pronouncing.rhym...
Create a Python 3 function to return a list of words rhyming with a given word.
You are a Python code architect, reviewing and designing scalable and efficient code
Set the default values on the ds9 display.
How would you explain what the following Python 3 function does def set_ds9(self, level="PREF"): self.set_zoom() ds9_settings = config.read("DS9."+level) for key in ds9_settings.keys(): value = ds9_settings[key] cmd = key.replace("_", " ") self.ds9.set("{} {}"...
You are a Python code generator, capable of creating scripts from specifications.
def cfht_megacam_tap_query(ra_deg=180.0, dec_deg=0.0, width=1, height=1, date=None): """Do a query of the CADC Megacam table. Get all observations inside the box (right now it turns width/height into a radius, should not do this). @rtype : Table @param ra_deg: center of search region, in degrees @...
Can you write a function in Python 3 where it does a query of the CADC Megacam table.
You are a Python code analyst, evaluating scripts for potential improvements.
Raises a ValueError if the size of the dimension doesn t match the number of bands in the array
Can you tell what is the following Python 3 function doing def validate(self, size): msg = 'scale and array size must match, ' \ 'but were scale: {self.scale.n_bands}, array size: {size}' if size != len(self.scale): raise ValueError(msg.format(**locals()))
As a Python code composer, you craft elegant and concise scripts.
def resampled( chunksize_bytes=DEFAULT_CHUNK_SIZE, resample_to=SR44100(), store_resampled=False): """ Create a basic processing pipeline that can resample all incoming audio to a normalized sampling rate for downstream processing, and store a convenient, compressed version for pl...
Create a Python 3 function for creating a basic processing pipeline that can resample all incoming audio to a normalized sampling rate for downstream processing.
As a python code expert, you are capable of creating scripts from specifications.
Generates a base class suitable as a starting point for many audio processing of a single object.
How would you explain what the following Python 3 function does def audio_graph( chunksize_bytes=DEFAULT_CHUNK_SIZE, resample_to=SR44100(), store_fft=False): """ Produce a base class suitable as a starting point for many audio processing pipelines. This class resamples all audio to ...
You are a Python code architect, reviewing and designing scalable and efficient code
def with_onsets(fft_feature): """ Produce a mixin class that extracts onsets :param fft_feature: The short-time fourier transform feature :return: A mixin class that extracts onsets """ class Onsets(BaseModel): onset_prep = ArrayWithUnitsFeature( SlidingWindow, n...
How would you implement a function in Python 3 that produces a mixin class that extracts onsets from a short - time fourier transform feature
As a python code expert, you are capable of creating scripts from specifications.
Plot the Keplerian sheared field locations.
Can you tell what is the following Python 3 function doing def keplerian_sheared_field_locations(ax, kbos, date, ras, decs, names, elongation=False, plot=False): seps = {'dra': 0., 'ddec': 0.} for kbo in kbos: ra = kbo.ra dec = kbo.dec kbo.compute(date) seps['dra'] += kbo.ra - ra...
You are a Python code architect, reviewing and designing scalable and efficient code
Calculates the solar elongation at the given date.
Can you generate a brief explanation for the following Python 3 code def field_elongation(ra, dec, date): sun = ephem.Sun() sun.compute(date) sep = ephem.separation((ra, dec), sun) retval = 180. - math.degrees(sep) return retval
As a Python code translator, you convert algorithms and pseudocode into Python.
def str_to_timedelta(value: str, fmt: str = None) -> Optional[datetime.timedelta]: """ Convert string value to timedelta instance according to the given format. If format not set function tries to load timedelta using default ``TIMEDELTA_FORMAT`` and then both of magic "full" forma...
Implement a Python 3 function for converting string value to timedelta instance according to given format.
You are a Python code generator, capable of creating scripts from specifications.
Implement divison for timedelta instances.
Explain what the following Python 3 code does def timedelta_div(first: datetime.timedelta, second: datetime.timedelta) -> Optional[float]: """Implement divison for timedelta instances. :param first: First timedelta instance. :param second: Second timedelta instance. """ first_seco...
As a Python code analyst, you investigate and solve complex coding mysteries
def timedelta_seconds(value: datetime.timedelta) -> int: """Return full number of seconds from timedelta. By default, Python returns only one day seconds, not all timedelta seconds. :param value: Timedelta instance. """ return SECONDS_PER_DAY * value.days + value.seconds
Implement a function in Python 3 to return the number of seconds from a timedelta instance.
You are a Python code analyst, evaluating scripts for potential improvements.
Display the timedelta formatted according to the given string.
Given the following Python 3 function, write the documentation def timedelta_to_str(value: datetime.timedelta, fmt: str = None) -> str: # Only ``datetime.timedelta`` instances allowed for this function if not isinstance(value, datetime.timedelta): raise ValueError( 'Value should be a "dateti...
You are a Python code architect, reviewing and designing scalable and efficient code
def align(expnums, ccd, version='s', dry_run=False): """Create a 'shifts' file that transforms the space/flux/time scale of all images to the first image. This function relies on the .fwhm, .trans.jmp, .phot and .zeropoint.used files for inputs. The scaling we are computing here is for use in planting sour...
Can you create a Python 3 function that creates a shifts file that transforms the space and flux time scale of all images to the first image.
You are a Python code generator, capable of creating scripts from specifications.
def dist(self): """ How should the values in range be sampled, uniformly or via some function. :return: """ if self.func is None: return random.uniform(self.min, self.max) if self._dist is None: x = numpy.arange(self.min, self.max, (self.max-self.m...
Create a Python 3 function to return the distance between the values in range uniformly or via some function.
You are a Python code analyst, evaluating scripts for potential improvements.
def next(self): """ :return: a set of values that can be used for an planted object builder. """ # x y mag pix rate angle ''/h rate id # 912.48 991.06 22.01 57.32 -45.23 10.60 0 self._n -= 1 if self._n...
Can you implement a function in Python 3 that returns the next set of values that can be used for an planted object builder.
You are a Python code generator, capable of creating scripts from specifications.
Send a command to foscam.
How would you explain what the following Python 3 function does def send_command(self, cmd, params=None, raw=False): ''' Send command to foscam. ''' paramstr = '' if params: paramstr = urlencode(params) paramstr = '&' + paramstr if paramstr else '' ...
You are a Python code generator, capable of creating scripts from specifications.
def execute_command(self, cmd, params=None, callback=None, raw=False): ''' Execute a command and return a parsed response. ''' def execute_with_callbacks(cmd, params=None, callback=None, raw=False): code, params = self.send_command(cmd, params, raw) if callback: ...
Can you implement a function in Python 3 that executes a command and return a parsed response.
As a Python code composer, you craft elegant and concise scripts.
Set the IP information of the current system.
Can you generate a brief explanation for the following Python 3 code def set_ip_info(self, is_dhcp, ip='', gate='', mask='', dns1='', dns2='', callback=None): ''' isDHCP: 0(False), 1(True) System will reboot automatically to take effect after call this CGI command...
You are a Python code analyst, evaluating scripts for potential improvements.
Set http port and media port of camera.
Can you generate the documentation for the following Python 3 function def set_port_info(self, webport, mediaport, httpsport, onvifport, callback=None): ''' Set http port and media port of camera. ''' params = {'webPort' : webport, ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_wifi_list(self, startno, callback=None): ''' Get the aps around after refreshWifiList. Note: Only 10 aps will be returned one time. ''' params = {'startNo': startno} return self.execute_command('getWifiList', params, callback=callback)
How would you code a function in Python 3 to get the wifi list around after refreshWifiList.
You are a Python code analyst, evaluating scripts for potential improvements.
def set_wifi_setting(self, ssid, psk, isenable, isusewifi, nettype, encryptype, authmode, keyformat, defaultkey, key1='', key2='', key3='', key4='', key1len=64, key2len=64, key3len=64, key4len=64, callback=No...
Can you create a Python 3 function that sets wifi config. Camera will not connect to AP unless you enject your cable.
As a Python code composer, you craft elegant and concise scripts.
Set UPnP config for the current set of UPnP entries.
Explain what the following Python 3 code does def set_upnp_config(self, isenable, callback=None): ''' Set UPnP config ''' params = {'isEnable': isenable} return self.execute_command('setUPnPConfig', params, callback=callback)
As a python code expert, you are capable of creating scripts from specifications.
Set the stream fromat of sub stream.
How would you explain what the following Python 3 function does def set_sub_video_stream_type(self, format, callback=None): ''' Set the stream fromat of sub stream. Supported format: (1) H264 : 0 (2) MotionJpeg 1 ''' params = {'format': format} r...
As a Python code composer, you craft elegant and concise scripts.
def set_sub_stream_format(self, format, callback=None): ''' Set the stream fromat of sub stream???? ''' params = {'format': format} return self.execute_command('setSubStreamFormat', params, callback=callback)
How would you implement a function in Python 3 that sets the format of the sub stream
You are a Python code architect, reviewing and designing scalable and efficient code
def set_main_video_stream_type(self, streamtype, callback=None): ''' Set the stream type of main stream ''' params = {'streamType': streamtype} return self.execute_command('setMainVideoStreamType', params, callback=callback)
Can you write a function in Python 3 where it sets the stream type of main stream
You are a Python code analyst, evaluating scripts for potential improvements.
Set the video stream param of the current session.
Make a summary of the following Python 3 code def set_video_stream_param(self, streamtype, resolution, bitrate, framerate, gop, isvbr, callback=None): ''' Set the video stream param of stream N streamtype(0~3): Stream N. resolution(0~4): 0 720P, 1 VGA...
As a Python code composer, you craft elegant and concise scripts.
Mirror the video in the current node.
Make a summary of the following Python 3 code def mirror_video(self, is_mirror, callback=None): ''' Mirror video ``is_mirror``: 0 not mirror, 1 mirror ''' params = {'isMirror': is_mirror} return self.execute_command('mirrorVideo', params, callback=callback)
You are a Python code analyst, evaluating scripts for potential improvements.
def flip_video(self, is_flip, callback=None): ''' Flip video ``is_flip``: 0 Not flip, 1 Flip ''' params = {'isFlip': is_flip } return self.execute_command('flipVideo', params, callback=callback)
Create a Python 3 function to flip video ``is_flip``: 0 Not flip, 1 Flip
You are a Python code architect, reviewing and designing scalable and efficient code
Change password of a resource.
How would you explain what the following Python 3 function does def change_password(self, usrname, oldpwd, newpwd, callback=None): ''' Change password. ''' params = {'usrName': usrname, 'oldPwd' : oldpwd, 'newPwd' : newpwd, } r...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_infra_led_config(self, mode, callback=None): ''' Set Infrared LED configuration cmd: setInfraLedConfig mode(0,1): 0=Auto mode, 1=Manual mode ''' params = {'mode': mode} return self.execute_command('setInfraLedConfig', params, callback=callback)
Write a Python 3 script to set the state of the Infrared LED to the specified mode.
As a Python code composer, you craft elegant and concise scripts.
def set_motion_detection(self, enabled=1): ''' Get the current config and set the motion detection on or off ''' result, current_config = self.get_motion_detect_config() if result != FOSCAM_SUCCESS: return result current_config['isEnable'] = enabled se...
Implement a function in Python 3 to set the motion detection on or off of the current config.
As a Python code composer, you craft elegant and concise scripts.
def set_motion_detection1(self, enabled=1): ''' Get the current config and set the motion detection on or off ''' result, current_config = self.get_motion_detect_config1() if result != FOSCAM_SUCCESS: return result current_config['isEnable'] = enabled ...
How would you code a function in Python 3 to set the motion detection on or off for one of the available resources.
You are a Python code analyst, evaluating scripts for potential improvements.
def set_alarm_record_config(self, is_enable_prerecord=1, prerecord_secs=5, alarm_record_secs=300, callback=None): ''' Set alarm record config Return: set result(0-success, -1-error) ''' params = {'isEnablePreRecord': is_enable_prerecord, ...
How would you code a function in Python 3 to set alarm record config
You are a Python code analyst, evaluating scripts for potential improvements.
Set local alarm - record configuration
Can you tell what is the following Python 3 function doing def set_local_alarm_record_config(self, is_enable_local_alarm_record = 1, local_alarm_record_secs = 30, callback=None): ''' Set local alarm-record config `is_enable_local_alarm_record`: 0 disable, 1 ...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_h264_frm_ref_mode(self, mode=1, callback=None): ''' Set frame shipping reference mode of H264 encode stream. params: `mode`: see docstr of meth::get_h264_frm_ref_mode ''' params = {'mode': mode} return self.execute_command('setH264FrmRefMode', params, ...
Can you write a function in Python 3 where it sets the frame shipping reference mode of H264 encode stream.
As a python code expert, you are capable of creating scripts from specifications.
def set_schedule_record_config(self, is_enable, record_level, space_full_mode, is_enable_audio, schedule0 = 0, schedule1 = 0, schedule2 = 0, schedule3 = 0, schedule4 = 0, schedule5 = 0, ...
Implement a Python 3 function for setting schedule record config. cmd: setScheduleRecordConfig args: See docstring of meth::get_schedule_record_config
As a Python code analyst, you investigate and solve complex coding mysteries
Set the path of the record
Can you generate a brief explanation for the following Python 3 code def set_record_path(self, path, callback=None): ''' Set Record path: sd/ftp cmd: setRecordPath param: path: (0,SD), (2, FTP) ''' params = {'Path': path} return self.execute_command('...
As a python code expert, you are capable of creating scripts from specifications.
def get_log(self, offset, count=10, callback=None): ''' Retrieve log records from camera. cmd: getLog param: offset: log offset for first record count: number of records to return ''' params = {'offset': offset, 'count': count} return self.ex...
Write a Python 3 script to retrieve log records from camera.
As a python code expert, you are capable of creating scripts from specifications.
retrieve the aperture correction for this exposure
Can you tell what is the following Python 3 function doing def get_apcor(expnum, ccd, version='p', prefix=None): uri = get_uri(expnum, ccd, ext=APCOR_EXT, version=version, prefix=prefix) apcor_file_name = tempfile.NamedTemporaryFile() client.copy(uri, apcor_file_name.name) apcor_file_name.seek(0) re...
You are a Python code generator, capable of creating scripts from specifications.
def cone_search(ra, dec, dra=0.01, ddec=0.01, mjdate=None, calibration_level=2, use_ssos=True, collection='CFHTMEGAPIPE'): """Do a QUERY on the TAP service for all observations that are part of OSSOS (*P05/*P016) where taken after mjd and have calibration 'observable'. @param ra: RA center ...
Write a Python 3 script to do a QUERY on the TAP service for all observations that are part of OSSOS (*P05/*P016) where taken after mjd and have calibration 'observable'. @param ra: RA center of search cont @type ra: Quantity @param dec: float degrees @type dec: Quantity @param dra: float degrees @type dra: Quantity @p...
You are a Python code architect, reviewing and designing scalable and efficient code
Populate the DBIMAGES and HEADERS of a CFHT dataset.
Given the following Python 3 function, write the documentation def populate(dataset_name, data_web_service_url=DATA_WEB_SERVICE + "CFHT"): data_dest = get_uri(dataset_name, version='o', ext=FITS_EXT) data_source = "%s/%so.{}" % (data_web_service_url, dataset_name, FITS_EXT) mkdir(os.path.dirname(data_dest...
As a Python code composer, you craft elegant and concise scripts.
Returns the nominal URI for a candidate file.
Given the following Python 3 function, write the documentation def get_cands_uri(field, ccd, version='p', ext='measure3.cands.astrom', prefix=None, block=None): """ return the nominal URI for a candidate file. @param field: the OSSOS field name @param ccd: which CCD are the candid...
You are a Python code generator, capable of creating scripts from specifications.
Build the URI for an OSSOS image stored in the dbimages file.
Can you generate a brief explanation for the following Python 3 code def get_uri(expnum, ccd=None, version='p', ext=FITS_EXT, subdir=None, prefix=None): """ Build the uri for an OSSOS image stored in the dbimages containerNode. :rtype : basestring expnum: CFHT exposure numbe...
As a python code expert, you are capable of creating scripts from specifications.
given a key return the vospace tag value.
How would you explain what the following Python 3 function does def get_tag(expnum, key): uri = tag_uri(key) force = uri not in get_tags(expnum) value = get_tags(expnum, force=force).get(uri, None) return value
You are a Python code architect, reviewing and designing scalable and efficient code
def get_process_tag(program, ccd, version='p'): """ make a process tag have a suffix indicating which ccd its for. @param program: Name of the process that a tag is built for. @param ccd: the CCD number that this process ran on. @param version: The version of the exposure (s, p, o) that the process ...
How would you code a function in Python 3 to return a string that represents the process tag for a given CCD number and version.
As a python code expert, you are capable of creating scripts from specifications.
Report back status of a given program.
Can you generate a brief explanation for the following Python 3 code def get_status(task, prefix, expnum, version, ccd, return_message=False): key = get_process_tag(prefix+task, ccd, version) status = get_tag(expnum, key) logger.debug('%s: %s' % (key, status)) if return_message: return status ...
As a python code expert, you are capable of creating scripts from specifications.
def set_status(task, prefix, expnum, version, ccd, status): """ set the processing status of the given program. @param task: name of the processing task @param prefix: was there a prefix on the exposure number processed? @param expnum: exposure number processed. @param version: which version of ...
Implement a Python 3 function for setting the processing status of the given program.
You are a Python code generator, capable of creating scripts from specifications.
Get a cutout from an exposure based on the RA and DEC location.
Can you generate a brief explanation for the following Python 3 code def _cutout_expnum(observation, sky_coord, radius): uri = observation.get_image_uri() cutout_filehandle = tempfile.NamedTemporaryFile() disposition_filename = client.copy(uri + "({},{},{})".format(sky_coord.ra.to('degree').value, ...
As a python code expert, you are capable of creating scripts from specifications.
Given an OSSOS frameid return the expnum version and ccdnum as a dictionary.
Can you generate a brief explanation for the following Python 3 code def frame2expnum(frameid): result = {} parts = re.search('(?P<expnum>\d{7})(?P<type>\S)(?P<ccd>\d\d)', frameid) assert parts is not None result['expnum'] = parts.group('expnum') result['ccd'] = parts.group('ccd') result['versio...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_image(expnum, ccd=None, version='p', ext=FITS_EXT, subdir=None, prefix=None, cutout=None, return_file=True, flip_image=True): """Get a FITS file for this expnum/ccd from VOSpace. @param cutout: (str) @param return_file: return an filename (True) or HDUList (False) @param expnum:...
Implement a Python 3 function for getting a FITS file for this exposure number and CCD.
You are a Python code generator, capable of creating scripts from specifications.
reset the datasec to account for a possible cutout
Given the following Python 3 function, write the documentation def reset_datasec(cutout, datasec, naxis1, naxis2): if cutout is None or cutout == "[*,*]": return datasec try: datasec = datasec_to_list(datasec) except: return datasec # check for '-*' in the cutout string and rep...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a HDU from the given URI from the VOSpace.
Can you generate the documentation for the following Python 3 function def get_hdu(uri, cutout=None): try: # the filename is based on the Simple FITS images file. filename = os.path.basename(uri) if os.access(filename, os.F_OK) and cutout is None: logger.debug("File already on di...
As a Python code analyst, you investigate and solve complex coding mysteries
Get the FWHM from the VOSpace annotation.
Can you generate the documentation for the following Python 3 function def get_fwhm_tag(expnum, ccd, prefix=None, version='p'): uri = get_uri(expnum, ccd, version, ext='fwhm', prefix=prefix) if uri not in fwhm: key = "fwhm_{:1s}{:02d}".format(version, int(ccd)) fwhm[uri] = get_tag(expnum, key) ...
As a python code expert, you are capable of creating scripts from specifications.
Get the FWHM computed for the given expnum and ccd.
Can you generate the documentation for the following Python 3 function def get_fwhm(expnum, ccd, prefix=None, version='p'): uri = get_uri(expnum, ccd, version, ext='fwhm', prefix=prefix) filename = os.path.basename(uri) try: return fwhm[uri] except: pass try: fwhm[uri] = f...
As a python code expert, you are capable of creating scripts from specifications.
def _get_zeropoint(expnum, ccd, prefix=None, version='p'): """ Retrieve the zeropoint stored in the tags associated with this image. @param expnum: Exposure number @param ccd: ccd of the exposure @param prefix: possible prefix (such as 'fk') @param version: which version: p, s, or o ? @retur...
How would you code a function in Python 3 to retrieve the zeropoint stored in the tags associated with this image.
As a Python code composer, you craft elegant and concise scripts.
Get the zeropoint for this exposure using the zeropoint. used file created during source planting..
How would you explain what the following Python 3 function does def get_zeropoint(expnum, ccd, prefix=None, version='p'): uri = get_uri(expnum, ccd, version, ext='zeropoint.used', prefix=prefix) try: return zmag[uri] except: pass try: zmag[uri] = float(open_vos_or_local(uri).rea...
You are a Python code architect, reviewing and designing scalable and efficient code
make directory tree in vospace.
How would you explain what the following Python 3 function does def mkdir(dirname): dir_list = [] while not client.isdir(dirname): dir_list.append(dirname) dirname = os.path.dirname(dirname) while len(dir_list) > 0: logging.info("Creating directory: %s" % (dir_list[-1])) try...
As a Python code translator, you convert algorithms and pseudocode into Python.
Open and return a handle on a VOSpace data connection
Here you have a function in Python 3, explain what it does def vofile(filename, **kwargs): basename = os.path.basename(filename) if os.access(basename, os.R_OK): return open(basename, 'r') kwargs['view'] = kwargs.get('view', 'data') return client.open(filename, **kwargs)
As a Python code analyst, you investigate and solve complex coding mysteries
def open_vos_or_local(path, mode="rb"): """ Opens a file which can either be in VOSpace or the local filesystem. @param path: @param mode: @return: """ filename = os.path.basename(path) if os.access(filename, os.F_OK): return open(filename, mode) if path.startswith("vos:"): ...
Write a Python 3 function that can open a file which can either be in VOSpace or the local filesystem.
You are a Python code generator, capable of creating scripts from specifications.
def copy(source, dest): """ use the vospace service to get a file. @param source: @param dest: @return: """ logger.info("copying {} -> {}".format(source, dest)) return client.copy(source, dest)
How would you code a function in Python 3 to copy a file from source to dest
You are a Python code generator, capable of creating scripts from specifications.
def vlink(s_expnum, s_ccd, s_version, s_ext, l_expnum, l_ccd, l_version, l_ext, s_prefix=None, l_prefix=None): """make a link between two version of a file. @param s_expnum: @param s_ccd: @param s_version: @param s_ext: @param l_expnum: @param l_ccd: @param l_version: @par...
Implement a function in Python 3 to make a link between two versions of a file
You are a Python code generator, capable of creating scripts from specifications.
def delete(expnum, ccd, version, ext, prefix=None): """ delete a file, no error on does not exist @param expnum: @param ccd: @param version: @param ext: @param prefix: @return: """ uri = get_uri(expnum, ccd=ccd, version=version, ext=ext, prefix=prefix) remove(uri)
Create a Python 3 function to delete a file, no error on does not exist @param expnum: @param ccd: @param version: @param ext: @param prefix: @return:
As a Python code composer, you craft elegant and concise scripts.