output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def get_raid_fgi_status(report): """Gather fgi(foreground initialization) information of raid configuration This function returns a fgi status which contains activity status and its values from the report. :param report: SCCI report information :returns: dict of fgi status of logical_drives, such ...
Create a Python 3 function for gathering fgi status of the RAID configuration and return a dict of activity status and log drive number.
As a python code expert, you are capable of creating scripts from specifications.
get firmware upgrade status of bios or irmc
Here you have a function in Python 3, explain what it does def get_firmware_upgrade_status(irmc_info, upgrade_type): host = irmc_info.get('irmc_address') userid = irmc_info.get('irmc_username') password = irmc_info.get('irmc_password') port = irmc_info.get('irmc_port', 443) auth_method = irmc_info....
As a Python code translator, you convert algorithms and pseudocode into Python.
def median(ma): """ do it row by row, to save memory....""" _median = 0*ma[0].filled(fill_value=0) for i in range(ma.shape[-1]): t=xmedian(ma[:,:,i]) _median[:,i]=t t=None return _median
Write a Python 3 function that can do it row by row to save memory...
You are a Python code architect, reviewing and designing scalable and efficient code
def xmedian(ma): """ Given a masked numpy array (build using numpy.ma class) return the median value of the array.""" import numpy _medianIndex = numpy.floor(ma.count(axis=0)/2.0) _sortIndex = ma.argsort(kind='heapsort',axis=0) _median = ma[0].filled(fill_value=0)*0 for idx in range(len(_sor...
Create a Python 3 function to give a masked numpy array return the median value of the array.
You are a Python code architect, reviewing and designing scalable and efficient code
Generates a provisional name for an object given the information in the astromaton header and FITS header.
Can you generate the documentation for the following Python 3 function def _generate_provisional_name(q, astrom_header, fits_header): while True: ef = get_epoch_field(astrom_header, fits_header) epoch_field = ef[0] + ef[1] count = storage.increment_object_counter(storage.MEASURE3, epoch_fiel...
As a Python code composer, you craft elegant and concise scripts.
def on_toggle_autoplay_key(self): """ The user has pressed the keybind for toggling autoplay. """ if self.autoplay_manager.is_running(): self.autoplay_manager.stop_autoplay() self.view.set_autoplay(False) else: self.autoplay_manager.start_autop...
Can you implement a function in Python 3 that toggles autoplay mode when the user presses the keybind for toggling autoplay.
As a Python code composer, you craft elegant and concise scripts.
def on_accept(self, auto=False): """ Initiates acceptance procedure, gathering required data. @param auto: Set on_accept to automatic measure of source? """ if self.model.is_current_source_named(): provisional_name = self.model.get_current_source_name() else:...
Write a Python 3 script to initiate acceptance procedure, gathering required data. @param auto: Set on_accept to automatic measure of source?
You are a Python code architect, reviewing and designing scalable and efficient code
This method is called when the user is about to accept an object.
Make a summary of the following Python 3 code def on_do_accept(self, minor_planet_number, provisional_name, note1, note2, date_of_obs, ra, dec, obs_mag,...
As a python code expert, you are capable of creating scripts from specifications.
Called when a vetting candidate is accepted.
How would you explain what the following Python 3 function does def on_do_accept(self, comment): self.view.close_vetting_accept_source_dialog() # Set to None if blank if len(comment.strip()) == 0: comment = None writer = self.model.get_writer() writer.write_source(s...
As a Python code translator, you convert algorithms and pseudocode into Python.
def on_load_comparison(self, research=False): """ Display the comparison image @param research: find a new comparison image even if one already known? """ cutout = self.model.get_current_cutout() if research: cutout.comparison_image_index = None compa...
How would you implement a function in Python 3 that displays the comparison image
You are a Python code architect, reviewing and designing scalable and efficient code
def compute_trans(expnums, ccd, version, prefix=None, default="WCS"): """ Pull the astrometric header for each image, compute an x/y transform and compare to trans.jmp this one overides trans.jmp if they are very different. @param expnums: @param ccd: @param version: @param prefix: @ret...
Create a Python 3 function to compute the x y transform of each image and compare to trans. jmp
As a Python code composer, you craft elegant and concise scripts.
def step2(expnums, ccd, version, prefix=None, dry_run=False, default="WCS"): """run the actual step2 on the given exp/ccd combo""" jmp_trans = ['step2ajmp'] jmp_args = ['step2bjmp'] matt_args = ['step2matt_jmp'] idx = 0 for expnum in expnums: jmp_args.append( storage.get_f...
Can you write a function in Python 3 where it runs the actual step2 on the given expnum and ccd combo
As a Python code composer, you craft elegant and concise scripts.
Parse the nate simulation file.
Here you have a function in Python 3, explain what it does def parse_nate_sims(path): ''' parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly for every particle in the simulation at t=0. The second (parts3999.dat) contains the same info at t...
You are a Python code generator, capable of creating scripts from specifications.
Convert netmask from CIDR format to doted decimal string.
Can you generate a brief explanation for the following Python 3 code def _convert_netmask(mask): if mask not in range(0, 33): raise scci.SCCIInvalidInputError( 'Netmask value is invalid.') return socket.inet_ntoa(struct.pack( '!L', int('1' * mask + '0' * (32 - mask), 2)))
You are a Python code generator, capable of creating scripts from specifications.
def apply(self, reboot=False): """Apply the configuration to iRMC.""" self.root.use_virtual_addresses = True self.root.manage.manage = True self.root.mode = 'new' self.root.init_boot = reboot self.client.set_profile(self.root.get_json())
Write a Python 3 script to apply the configuration to iRMC.
You are a Python code architect, reviewing and designing scalable and efficient code
Terminate VIOM configuration from iRMC.
Can you tell what is the following Python 3 function doing def terminate(self, reboot=False): self.root.manage.manage = False self.root.mode = 'delete' self.root.init_boot = reboot self.client.set_profile(self.root.get_json())
You are a Python code architect, reviewing and designing scalable and efficient code
def set_lan_port(self, port_id, mac=None): """Set LAN port information to configuration. :param port_id: Physical port ID. :param mac: virtual MAC address if virtualization is necessary. """ port_handler = _parse_physical_port_id(port_id) port = self._find_port(port_hand...
Write a Python 3 script to set the LAN port information to the configuration.
You are a Python code architect, reviewing and designing scalable and efficient code
def set_iscsi_volume(self, port_id, initiator_iqn, initiator_dhcp=False, initiator_ip=None, initiator_netmask=None, target_dhcp=False, target_iqn=None, target_ip=None, target_port=3260, target_lun=0, boot_prio=1, ...
Write a Python 3 script to set iSCSI volume information to configuration.
You are a Python code generator, capable of creating scripts from specifications.
Set FibreChannel volume information to configuration.
How would you explain what the following Python 3 function does def set_fc_volume(self, port_id, target_wwn, target_lun=0, boot_prio=1, initiator_wwnn=None, initiator_wwpn=None): """Set FibreChannel volume information to configuration. :param port_id: Physica...
You are a Python code generator, capable of creating scripts from specifications.
Create ports with former port index.
Here you have a function in Python 3, explain what it does def _pad_former_ports(self, port_handler): if not port_handler.need_padding(): return for port_idx in range(1, port_handler.port_idx): pad_handler = port_handler.__class__( port_handler.slot_type, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def chunk_size_samples(sf, buf): """ Black magic to account for the fact that libsndfile's behavior varies depending on file format when using the virtual io api. If you ask for more samples from an ogg or flac file than are available at that moment, libsndfile will give you no more samples ever, e...
How would you implement a function in Python 3 that returns the number of samples in a chunk of a file.
As a Python code analyst, you investigate and solve complex coding mysteries
def encode(number, alphabet): """ Converts an integer to a base n string where n is the length of the provided alphabet. Modified from http://en.wikipedia.org/wiki/Base_36 """ if not isinstance(number, (int, long)): raise TypeError("Number must be an integer.") base_n = "" sign...
Can you implement a function in Python 3 that converts an integer to a base n string where n is the length of the alphabet.
As a Python code translator, you convert algorithms and pseudocode into Python.
Categorical compression of a block of audio samples and convert them into a categorical distribution of the specified mu - law.
Given the following Python 3 function, write the documentation def categorical(x, mu=255, normalize=True): if normalize: # normalize the signal mx = x.max() x = np.divide(x, mx, where=mx != 0) # mu law compression x = mu_law(x) # translate and scale to [0, 1] x = (x - x.mi...
You are a Python code generator, capable of creating scripts from specifications.
def inverse_categorical(x, mu=255): """ Invert categorical samples """ flat = x.reshape((-1, x.shape[-1])) indices = np.argmax(flat, axis=1).astype(np.float32) indices = (indices / mu) - 0.5 inverted = inverse_mu_law(indices, mu=mu).reshape(x.shape[:-1]) return ArrayWithUnits(inverted, x...
Can you implement a function in Python 3 that inverses of categorical samples.
You are a Python code generator, capable of creating scripts from specifications.
def synthesize(self, duration, freqs_in_hz=[440.]): """ Synthesize one or more sine waves Args: duration (numpy.timdelta64): The duration of the sound to be synthesized freqs_in_hz (list of float): Numbers representing the frequencies in h...
Can you implement a function in Python 3 that synthesizes one or more sine waves
You are a Python code analyst, evaluating scripts for potential improvements.
Synthesize periodic ticks generated from white noise and an envelope sound to be synthesized
Given the following Python 3 function, write the documentation def synthesize(self, duration, tick_frequency): sr = self.samplerate.samples_per_second # create a short, tick sound tick = np.random.uniform(low=-1., high=1., size=int(sr * .1)) tick *= np.linspace(1, 0, len(tick)) #...
You are a Python code analyst, evaluating scripts for potential improvements.
def synthesize(self, duration): """ Synthesize white noise Args: duration (numpy.timedelta64): The duration of the synthesized sound """ sr = self.samplerate.samples_per_second seconds = duration / Seconds(1) samples = np.random.uniform(low=-1., high=...
Can you implement a function in Python 3 that synthesizes white noise with a given duration.
You are a Python code generator, capable of creating scripts from specifications.
Query the SSOS file for this workunit.
Can you generate the documentation for the following Python 3 function def query_ssos(self): self._ssos_queried = True mpc_filename = self.save() return self.builder.build_workunit(mpc_filename)
You are a Python code analyst, evaluating scripts for potential improvements.
def save(self): """ Update the SouceReading information for the currently recorded observations and then flush those to a file. @return: mpc_filename of the resulting save. """ self.get_writer().flush() mpc_filename = self.get_writer().get_filename() self.get_writ...
Create a Python 3 function to save the current state of the SouceReading information for the currently recorded observations.
You are a Python code generator, capable of creating scripts from specifications.
def get_writer(self): """ Get a writer. This method also makes the output filename be the same as the .track file but with .mpc. (Currently only works on local filesystem) :rtype MPCWriter """ if self._writer is None: suffix = tasks.get_suffix(tasks.T...
Write a Python 3 function that can get a MPCWriter object for the current entry.
As a Python code analyst, you investigate and solve complex coding mysteries
def _filter(self, filename): """ return 'true' if filename doesn't match name_filter regex and should be filtered out of the list. @param filename: @return: """ return self.name_filter is not None and re.search(self.name_filter, filename) is None
Implement a function in Python 3 to return true if filename matches the name_filter regex and should be filtered out of the list.
As a Python code analyst, you investigate and solve complex coding mysteries
Gets a new workunit from the directory.
Here you have a function in Python 3, explain what it does def get_workunit(self, ignore_list=None): if ignore_list is None: ignore_list = [] potential_files = self.get_potential_files(ignore_list) while len(potential_files) > 0: potential_file = self.select_potential_f...
As a python code expert, you are capable of creating scripts from specifications.
Get a listing of files for the appropriate task which may or may not be locked and not done.
Can you generate a brief explanation for the following Python 3 code def get_potential_files(self, ignore_list): exclude_prefix = self.taskid == tasks.suffixes.get(tasks.REALS_TASK, '') and 'fk' or None filenames = [filename for filename in self.directory_context.get_listing(self.ta...
You are a Python code generator, capable of creating scripts from specifications.
def move_discovery_to_front(self, data): """ Moves the discovery triplet to the front of the reading list. Leaves everything else in the same order. """ readings = self.get_readings(data) discovery_index = self.get_discovery_index(data) reordered_readings = (read...
Write a Python 3 function for moving the discovery triplet to the front of the reading list.
As a Python code analyst, you investigate and solve complex coding mysteries
def TAPQuery(RAdeg=180.0, DECdeg=0.0, width=1, height=1): """Do a query of the CADC Megacam table. Get all observations insize the box. Returns a file-like object""" QUERY =( """ SELECT """ """ COORD1(CENTROID(Plane.position_bounds)) AS "RAJ2000", COORD2(CENTROID(Plane.position_bounds)) AS "DEJ...
Implement a function in Python 3 to do a query of the CADC Megacam table. Returns a file - like object.
You are a Python code analyst, evaluating scripts for potential improvements.
check the tags for the given expnum and ccd set
Can you tell what is the following Python 3 function doing def check_tags(my_expnum, ops_set, my_ccds, dry_run=True): tags = storage.get_tags(my_expnum) count = 0 outcount = 0 fails = [] for ccd in my_ccds: success = True count += 1 for ops in ops_set: for fake in ops[0]: ...
As a Python code composer, you craft elegant and concise scripts.
def get_flipped_ext(file_id,ccd): """Given a list of exposure numbers and CCD, get them from the DB""" import MOPfits import os, shutil filename=MOPfits.adGet(file_id,extno=int(ccd)) if int(ccd)<18: tfname=filename+"F" shutil.move(filename, tfname) os.system("imcopy %s[-*,...
Write a Python 3 function for giving a list of exposure numbers and CCD return the filename of the file that is flipped.
As a Python code composer, you craft elegant and concise scripts.
def get_file_ids(object): """Get the exposure for a particular line in the meausre table""" import MOPdbaccess mysql = MOPdbaccess.connect('cfeps','cfhls',dbSystem='MYSQL') cfeps=mysql.cursor() sql="SELECT file_id FROM measure WHERE provisional LIKE %s" cfeps.execute(sql,(object, )) file_ids...
Can you write a function in Python 3 where it gets the exposure for a particular line in the meausre table
As a Python code translator, you convert algorithms and pseudocode into Python.
Main entry point for the main script.
Explain what the following Python 3 code does def main(): parser = argparse.ArgumentParser( description='replace image header') parser.add_argument('--extname', help='name of extension to in header') parser.add_argument('expnum', type=str, help='exposu...
As a Python code translator, you convert algorithms and pseudocode into Python.
def convert(lat, lon): """convert lat/lon from the ecliptic to the invariable plane.""" x = numpy.cos(lon) * numpy.cos(lat) y = numpy.sin(lon) * numpy.cos(lat) z = numpy.sin(lat) # Invariable plane: values in arcseconds. epsilon = 5713.86 omega = 387390.8 coseps = numpy.cos(epsilon * ...
Can you create a Python 3 function that converts lat / lon from the ecliptic to the invariable plane
You are a Python code architect, reviewing and designing scalable and efficient code
def searchTriples(expnums,ccd): """Given a list of exposure numbers, find all the KBOs in that set of exposures""" import MOPfits,os import MOPdbaccess if len(expnums)!=3: return(-1) mysql=MOPdbaccess.connect('bucket','cfhls','MYSQL') bucket=mysql.cursor() ### Some pro...
Write a Python 3 function for giving a list of exposure numbers, find all the KBOs in that set of exposures
You are a Python code analyst, evaluating scripts for potential improvements.
def handle_error(self, error, download_request): """ Checks what error occured and looks for an appropriate solution. Args: error: Exception The error that has occured. download_request: The request which resulted in the error. """ if ...
Implement a function in Python 3 to handle an error that occurred while downloading the object.
You are a Python code generator, capable of creating scripts from specifications.
def get_current_observation_date(self): """ Get the date of the current observation by looking in the header of the observation for the DATE and EXPTIME keywords. The 'DATE AT MIDDLE OF OBSERVATION' of the observation is returned @return: Time """ # All HDU eleme...
Can you implement a function in Python 3 that gets the date of the current observation by looking in the header of the last HDU element and the EXPTIME keywords.
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the square of the drop - off in the peak
Given the following Python 3 function, write the documentation def square(m, eff_max,c,m0,sigma,m1=21): return (eff_max-c*(m-21)**2)/(1+numpy.exp((m-m0)/sigma))
As a Python code translator, you convert algorithms and pseudocode into Python.
def parse_square_param(line): """ Parse the line from the .eff file that contains the efficiency function parameters for a 'square' function line : the line containt the parameters, must start with 'square_param' """ if not line.startswith("square_param="): raise ValueError("Not a valid ...
Create a Python 3 function for parsing the line from the. eff file that contains the efficiency function parameters for a square
As a Python code analyst, you investigate and solve complex coding mysteries
Parse the Jean - Marcs. eff files.
How would you explain what the following Python 3 function does def parse_eff(filename): blocks = [] block = {} with open(filename) as efile: for line in efile.readlines(): if line.lstrip().startswith("#"): continue keyword = line.lstrip().split("=")[0] ...
You are a Python code analyst, evaluating scripts for potential improvements.
Reads a value from the configuration file.
Can you generate a brief explanation for the following Python 3 code def read(keypath, configfile=None): if configfile in _configs: appconfig = _configs[configfile] else: appconfig = AppConfig(configfile=configfile) _configs[configfile] = appconfig return appconfig.read(keypath)
As a python code expert, you are capable of creating scripts from specifications.
def _cdata_header(self, colsep="|"): """ Create a header for the CDATA section, as a visual guide. """ fields = self.fields header_lines = [] line = "" for fieldName in self.field_names: width = int(fields[fieldName]['attr']['width']) line ...
Write a Python 3 script to create a CDATA section for the current locale.
You are a Python code analyst, evaluating scripts for potential improvements.
Append a data column to the ephemeris listing.
How would you explain what the following Python 3 function does def _append_cdata(self, coordinate): fields = self.fields sra = coordinate.ra.to_string(units.hour, sep=':', precision=2, pad=True) sdec = coordinate.dec.to_string(units.degree, sep=':', precision=1, alwayssign=True) coord =...
You are a Python code analyst, evaluating scripts for potential improvements.
def gemini_writer(self, f_handle): """ Write out a GEMINI formated OT ephemeris. This is just a hack of SSD Horizons output. """ f_handle.write(GEMINI_HEADER) # Date__(UT)__HR:MN Date_________JDUT R.A.___(ICRF/J2000.0)___DEC dRA*cosD d(DEC)/dt # 1 2 ...
Can you create a Python 3 function that writes out a GEMINI formated OT ephemeris.
As a Python code composer, you craft elegant and concise scripts.
A simple script to loop over the standard tags for the mkpsf and and check if the process failed.
Explain what the following Python 3 code does def mkpsf_failures(): for expnum in storage.list_dbimages(): for ccd in range(36): if not storage.get_status(MKPSF, "", expnum, "p", ccd): # get_status returns FALSE if process didn't succeed, # with return_message=Tr...
As a python code expert, you are capable of creating scripts from specifications.
def searchTriples(expnums,ccd,plant=False): """Given a list of exposure numbers, find all the KBOs in that set of exposures""" import MOPfits,os import MOPdbaccess if len(expnums)!=3: raise TaskError, "got %d exposures"%(len(expnums)) ### Some program Constants proc_these_files=[...
How would you code a function in Python 3 to give a list of exposures find all the KBOs in that set of exposures and return a list of the KBOs that are found in the same order as the original ones.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the nailing images associated with expnum.
Make a summary of the following Python 3 code def get_nailing(expnum,ccd): sql=""" SELECT e.expnum, (e.mjdate - f.mjdate) dt FROM bucket.exposure e JOIN bucket.exposure f JOIN bucket.association b ON b.expnum=f.expnum JOIN bucket.association a ON a.pointing=b.pointing AND a.expnum=e.expnum W...
As a Python code translator, you convert algorithms and pseudocode into Python.
def intersect(self, other): """ Return the intersection between this frequency band and another. Args: other (FrequencyBand): the instance to intersect with Examples:: >>> import zounds >>> b1 = zounds.FrequencyBand(500, 1000) >>> b2 = zo...
Implement a Python 3 function for returning the intersection between this frequency band and another.
As a Python code translator, you convert algorithms and pseudocode into Python.
def bands(self): """ An iterable of all bands in this scale """ if self._bands is None: self._bands = self._compute_bands() return self._bands
Create a Python 3 function for returning an iterable of all bands in this scale.
As a Python code composer, you craft elegant and concise scripts.
Ensures that every adjacent frequency band pair in the set of frequency bands meets the required overlap ratio.
Here you have a function in Python 3, explain what it does def ensure_overlap_ratio(self, required_ratio=0.5): msg = \ 'band {i}: ratio must be at least {required_ratio} but was {ratio}' for i in range(0, len(self) - 1): b1 = self[i] b2 = self[i + 1] tr...
As a Python code analyst, you investigate and solve complex coding mysteries
def Q(self): """ The quality factor of the scale, or, the ratio of center frequencies to bandwidths """ return np.array(list(self.center_frequencies)) \ / np.array(list(self.bandwidths))
Can you create a Python 3 function that returns the quality factor of the center frequencies and bandwidths of the logarithmic center frequencies.
You are a Python code generator, capable of creating scripts from specifications.
Given a frequency band and a frequency dimension comprised of n_samples return a slice that may be used to extract only the frequency samples that intersect with the frequency band.
Make a summary of the following Python 3 code def get_slice(self, frequency_band): index = frequency_band if isinstance(index, slice): types = { index.start.__class__, index.stop.__class__, index.step.__class__ } if He...
You are a Python code generator, capable of creating scripts from specifications.
Returns a LinearScale instance from a sampling rate.
Can you generate the documentation for the following Python 3 function def from_sample_rate(sample_rate, n_bands, always_even=False): fb = FrequencyBand(0, sample_rate.nyquist) return LinearScale(fb, n_bands, always_even=always_even)
As a Python code composer, you craft elegant and concise scripts.
def _hz_to_semitones(self, hz): """ Convert hertz into a number of semitones above or below some reference value, in this case, A440 """ return np.log(hz / self._a440) / np.log(self._a)
How would you implement a function in Python 3 that converts an hertz into a number of semitones above or below some reference value.
As a Python code analyst, you investigate and solve complex coding mysteries
def resolve(object): """Look up the name of a source using a resolver""" import re sesame_cmd = 'curl -s http://cdsweb.u-strasbg.fr/viz-bin/nph-sesame/-oI?'+string.replace(object,' ','') f = os.popen(sesame_cmd) lines = f.readlines() f.close() for line in lines: if re.searc...
Write a Python 3 script for looking up the name of a source using a resolver
You are a Python code architect, reviewing and designing scalable and efficient code
def remove_border(axes=None, keep=('left', 'bottom'), remove=('right', 'top'), labelcol=ALMOST_BLACK): """ Minimize chart junk by stripping out unnecessary plot borders and axis ticks. The top/right/left/bottom keywords toggle whether the corresponding plot border is drawn """ ax = axes or plt.gca()...
Write a Python 3 script for removing unnecessary plot borders and axis ticks.
As a Python code translator, you convert algorithms and pseudocode into Python.
def handle_exit_code(d, code): """Sample function showing how to interpret the dialog exit codes. This function is not used after every call to dialog in this demo for two reasons: 1. For some boxes, unfortunately, dialog returns the code for ERROR when the user presses ESC (instead of th...
Create a Python 3 function to sample function showing how to interpret the dialog exit codes. This function is not used after every call to dialog in this demo for two reasons: 1. For some boxes, unfortunately, dialog returns the code for ERROR when the user presses ESC (instead of the one chosen for ESC). As these box...
As a Python code analyst, you investigate and solve complex coding mysteries
def searchTriples(expnums,ccd): """Given a list of exposure numbers, find all the KBOs in that set of exposures""" import MOPfits,os import MOPdbaccess if len(expnums)!=3: return(-1) ### Some program Constants proc_file = open("proc-these-files","w") proc_file.write("# Files...
Can you write a function in Python 3 where it gives a list of exposure numbers, find all the KBOs in that set of exposures
As a Python code composer, you craft elegant and concise scripts.
def discands(record): """Display the candidates contained in a candidate record list""" import pyfits pyraf.iraf.images() pyraf.iraf.images.tv() display = pyraf.iraf.images.tv.display width=128 cands = record['cands'] exps= record['fileId'] comments= record['comments'] ...
Can you create a Python 3 function that displays the candidates contained in a candidate record list
As a Python code analyst, you investigate and solve complex coding mysteries
Given the position and time determin if the given target is up.
Here you have a function in Python 3, explain what it does def is_up(coordinate, current_time): cfht.date = current_time.iso.replace('-', '/') cfht.horizon = math.radians(-7) sun.compute(cfht) sun_rise = Time(str(sun.rise_time).replace('/', '-')) sun_set = Time(str(sun.set_time).replace('/', '-')) ...
You are a Python code architect, reviewing and designing scalable and efficient code
The main function of the TAP query.
Explain what the following Python 3 code does def TAPQuery(query): tapURL = "http://cadc-ccda.hia-iha.nrc-cnrc.gc.ca/tap/sync" ## Some default parameters for that TAP service queries. tapParams={'REQUEST': 'doQuery', 'LANG': 'ADQL', 'FORMAT': 'votable', 'Q...
As a python code expert, you are capable of creating scripts from specifications.
def step1(expnum, ccd, prefix='', version='p', sex_thresh=_SEX_THRESHOLD, wave_thresh=_WAVE_THRESHOLD, maxcount=_MAX_COUNT, dry_run=False): """run the actual step1jmp/matt codes. expnum: the CFHT expousre to process ccd: which ccd in the...
Can you implement a function in Python 3 that runs the actual step1jmp and matt codes.
As a Python code analyst, you investigate and solve complex coding mysteries
Create JSON data for AdapterConfig.
Explain what the following Python 3 code does def get_json(self): viom_table = self.get_basic_json() if self.slots: viom_table['Slots'] = { 'Slot': [s.get_json() for s in self.slots.values()] } if self.manage: viom_table['VIOMManage'] = self.ma...
You are a Python code architect, reviewing and designing scalable and efficient code
Create JSON data for the current object.
How would you explain what the following Python 3 function does def get_json(self): json = self.get_basic_json() if self.onboard_cards: json['OnboardControllers'] = { 'OnboardController': [c.get_json() for c in self.onboard_cards.values()] } ...
As a Python code composer, you craft elegant and concise scripts.
def get_json(self): """Create JSON data for LANPort. :returns: JSON data as follows: { "@PortIdx":1, "PortEnable":{ }, "UseVirtualAddresses":{ }, "BootProtocol":{ }, "VirtualAddr...
How would you code a function in Python 3 to create JSON data for LANPort.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_json(self): """Create FC port. :returns: JSON for FC port as follows: { "@PortIdx":1, "PortEnable":{ }, "UseVirtualAddresses":{ }, "VirtualAddress":{ "WWNN":{ ...
Implement a function in Python 3 to create FC port. :returns: JSON for FC port as follows: { "@PortIdx":1, "PortEnable":{ }, "UseVirtualAddresses":{ }, "VirtualAddress":{ "WWNN":{ }, "WWPN":{ }, "MAC":{ } }, "BootProtocol":{ }, "BootPriority":{ }, "FCBootEnvironment":{ } }
You are a Python code architect, reviewing and designing scalable and efficient code
Create JSON for CNA port.
How would you explain what the following Python 3 function does def get_json(self): port = self.get_basic_json() port['Functions'] = { 'Function': [f.get_json() for f in self.functions.values()] } return port
You are a Python code generator, capable of creating scripts from specifications.
def get_json(self): """Create JSON for FCBootEnvironment. :returns: JSON for FCBootEnvironment as follows: { "FCBootEnvironment":{ "FCTargets":{ "FCTarget":[ ] }, "FC...
Implement a Python 3 function for creating JSON for FCBootEnvironment.
You are a Python code analyst, evaluating scripts for potential improvements.
Create JSON data for iSCSI initiator.
Explain what the following Python 3 code does def get_json(self): if self.dhcp_usage: return {'DHCPUsage': self.dhcp_usage, 'Name': self.iqn} else: return self.get_basic_json()
You are a Python code generator, capable of creating scripts from specifications.
def get_json(self): """Create JSON data for iSCSI target. :returns: JSON data for iSCSI target as follows: { "DHCPUsage":{ }, "Name":{ }, "IPv4Address":{ }, "PortNumber":{ ...
Write a Python 3 function for creating JSON data for iSCSI target.
You are a Python code analyst, evaluating scripts for potential improvements.
def zscale(data,contrast,min=100,max=60000): """Scale the data cube into the range 0-255""" ## pic 100 random elements along each dimension ## use zscale (see the IRAF display man page or ## http://iraf.net/article.php/20051205162333315 import random x=[] for i in random.sample(xrange(data.shape[0]),50): ...
Write a Python 3 function that can scale the data cube into the range 0 - 255
As a python code expert, you are capable of creating scripts from specifications.
def update_values(ims, image_id, iq_zeropt=True, comment=False, snr=False, commdict=None): """ Update a row in ossuary with :param ims: an ImageQuery, contains image table and a connector :param image_id: the primary key of the row to be updated :param iq_zeropt: Keyword set if iq and zeropoint are ...
Write a Python 3 script for updating a row in ossuary with
As a python code expert, you are capable of creating scripts from specifications.
def main(): """ Update the ossuary Postgres db with images observed for OSSOS. iq: Go through and check all ossuary's images for new existence of IQs/zeropoints. comment: Go through all ossuary and Then updates ossuary with new images that are at any stage of processing. Constructs full image en...
Can you create a Python 3 function that updates the ossuary Postgres db with images observed for OSSOS. iq: Go through and check all ossuary's images for new existence of IQs/zeropoints. comment: Go through all ossuary and Then updates ossuary with new images that are at any stage of processing. Constructs full image e...
You are a Python code architect, reviewing and designing scalable and efficient code
Compute a square view of the frequency adaptive transform by resampling each frequency band and performing an overlap - add procedure in the frequency adaptive transform by the number of samples.
Given the following Python 3 function, write the documentation def square(self, n_coeffs, do_overlap_add=False): resampled_bands = [ self._resample(band, n_coeffs) for band in self.iter_bands()] stacked = np.vstack(resampled_bands).T fdim = FrequencyDimension(self.scale...
You are a Python code analyst, evaluating scripts for potential improvements.
Convert a point from one coordinate system to another.
Given the following Python 3 function, write the documentation def convert(self, point): x, y = point (x1, y1) = x - self.x_offset, y - self.y_offset logger.debug("converted {} {} ==> {} {}".format(x, y, x1, y1)) return x1, y1
As a Python code analyst, you investigate and solve complex coding mysteries
Create sane default persistence settings for learning pipelines
Explain what the following Python 3 code does def simple_settings(cls): class Settings(ff.PersistenceSettings): _id = cls.__name__ id_provider = ff.StaticIdProvider(_id) key_builder = ff.StringDelimitedKeyBuilder() database = ff.FileSystemDatabase( path=_id, key_builder=...
You are a Python code architect, reviewing and designing scalable and efficient code
def apply_network(network, x, chunksize=None): """ Apply a pytorch network, potentially in chunks """ network_is_cuda = next(network.parameters()).is_cuda x = torch.from_numpy(x) with torch.no_grad(): if network_is_cuda: x = x.cuda() if chunksize is None: ...
Write a Python 3 script to apply a pytorch network potentially in chunks
You are a Python code architect, reviewing and designing scalable and efficient code
Sample the norm of a pixel.
Can you generate a brief explanation for the following Python 3 code def sample_norm(x): original = x # square x = x ** 2 # feature-map-wise sum x = torch.sum(x, dim=1) # scale by number of feature maps x *= 1.0 / original.shape[1] x += 10e-8 x = torch.sqrt(x) return original / x...
You are a Python code analyst, evaluating scripts for potential improvements.
def reset_coord(self): """ Reset the source location based on the init_skycoord values @return: """ (x, y, idx) = self.world2pix(self.init_skycoord.ra, self.init_skycoord.dec, usepv=True) self.updat...
Implement a Python 3 function for resetting the source location based on the init_skycoord values
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the coordinates of the source in the cutout reference frame.
Make a summary of the following Python 3 code def pixel_coord(self): return self.get_pixel_coordinates(self.reading.pix_coord, self.reading.get_ccd_num())
You are a Python code architect, reviewing and designing scalable and efficient code
Flips the X and Y coordinates of the image.
Can you tell what is the following Python 3 function doing def flip_flip(self, point): x, y = point if self.reading.compute_inverted(): naxis1 = self.reading.obs.header.get(self.reading.obs.HEADER_IMG_SIZE_X, self.reading.obs.header.get('NAXIS...
You are a Python code generator, capable of creating scripts from specifications.
def update_pixel_location(self, new_pixel_location, hdu_index): """ Update the x/y location of the associated reading by using new_pixel_location and transforming from cutout reference frame to observation refrence frame. @param new_pixel_location: (x, y) location of the source in cutout...
How would you code a function in Python 3 to update the x y location of the associated reading by using new_pixel_location and transforming from cutoutPixelReferenceFrame to observation refrence frame.
You are a Python code generator, capable of creating scripts from specifications.
def get_pixel_coordinates(self, point, ccdnum): """ Retrieves the pixel location of a point within the current HDUList given the location in the original FITS image. This takes into account that the image may be a cutout of a larger original. Args: point: tuple(float,...
Create a Python 3 function for retrieving the pixel location of a point within the current HDUList given the location in the original FITS image. This takes into account that the image may be a cutout of a larger original. Args: point: tuple(float, float) (x, y) in original. Returns: (x, y) pixel in this image. @param ...
As a python code expert, you are capable of creating scripts from specifications.
def get_observation_coordinates(self, x, y, hdulist_index): """ Retrieves the location of a point using the coordinate system of the original observation, i.e. the original image before any cutouts were done. Returns: (x, y) in the original image coordinate system. ...
Can you create a Python 3 function that returns the location of a point using the coordinate system of the original image before any cutouts were done.
You are a Python code architect, reviewing and designing scalable and efficient code
Convert a given RA and DEC position to the X Y coordinates of the extension in the cutout reference frame.
Here you have a function in Python 3, explain what it does def world2pix(self, ra, dec, usepv=True): x, y, idx = (0, 0, 0) for idx in range(1, len(self.hdulist)): hdu = self.hdulist[idx] x, y = hdu.wcs.sky2xy(ra, dec, usepv=usepv) if 0 < x < hdu.header['NAXIS1'] and 0...
As a Python code analyst, you investigate and solve complex coding mysteries
Return the photometric zeropoint of the CCD associated with the reading.
Given the following Python 3 function, write the documentation def zmag(self,): if self._zmag is None: hdulist_index = self.get_hdulist_idx(self.reading.get_ccd_num()) self._zmag = self.hdulist[hdulist_index].header.get('PHOTZP', 0.0) return self._zmag
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the aperture correction of for the CCD associated with the reading.
Make a summary of the following Python 3 code def apcor(self): if self._apcor is None: try: self._apcor = Downloader().download_apcor(self.reading.get_apcor_uri()) except: self._apcor = ApcorData.from_string("5 15 99.99 99.99") return self._apcor
You are a Python code generator, capable of creating scripts from specifications.
Get the observed magnitude at the current pixel x y location.
Make a summary of the following Python 3 code def get_observed_magnitude(self, centroid=True): # NOTE: this import is only here so that we don't load up IRAF # unnecessarily (ex: for candidates processing). """ Get the magnitude at the current pixel x/y location. :return: Table ...
As a Python code composer, you craft elegant and concise scripts.
Returns a list of possible comparison images for the current cutout.
Can you generate the documentation for the following Python 3 function def comparison_image_list(self): if self._comparison_image_list is not None: return self._comparison_image_list ref_ra = self.reading.ra * units.degree ref_dec = self.reading.dec * units.degree radius = ...
You are a Python code generator, capable of creating scripts from specifications.
Retrieves the comparison image for this cutout.
How would you explain what the following Python 3 function does def retrieve_comparison_image(self): # selecting comparator when on a comparator should load a new one. collectionID = self.comparison_image_list[self.comparison_image_index]['EXPNUM'] ref_ra = self.reading.ra * units.degree ...
As a python code expert, you are capable of creating scripts from specifications.
check that the passwd provided matches the required password
Explain what the following Python 3 code does def check_password(self, passwd, group): # This provides authentication via CADC. """check that the passwd provided matches the required password.""" return gms.isMember(self.login, passwd, group)
You are a Python code generator, capable of creating scripts from specifications.
def integer_based_slice(self, ts): """ Transform a :class:`TimeSlice` into integer indices that numpy can work with Args: ts (slice, TimeSlice): the time slice to translate into integer indices """ if isinstance(ts, slice): try: ...
How would you code a function in Python 3 to transform a TimeSlice into an integer slice that numpy can work with.
You are a Python code generator, capable of creating scripts from specifications.
Loads the observations of the object.
Make a summary of the following Python 3 code def load_observations((observations, regex, rename), path, filenames): for filename in filenames: if re.search(regex, filename) is None: logging.error("Skipping {}".format(filename)) continue obs = mpc.MPCReader().read(os.path.jo...
You are a Python code architect, reviewing and designing scalable and efficient code
Add KBOs to an image.
Make a summary of the following Python 3 code def plant_kbos(filename, psf, kbos, shifts, prefix): iraf.set(uparm="./") iraf.digiphot() iraf.apphot() iraf.daophot(_doprint=0) iraf.images() if shifts['nmag'] < 4: logging.warning("Mag shift based on fewer than 4 common stars.") f...
You are a Python code architect, reviewing and designing scalable and efficient code