Instruction:
Implement a Python 3 function for
giving a ciphertext returns a plaintext using the keys specified in self. _ecb_enc_K1 and self. _ecb_enc_K2.

Response:
def decrypt(self, ciphertext):
        """Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``.

        Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string.
        Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative message length greater than the ciphertext length.
        Raises ``UnrecoverableDecryptionError`` if invalid padding is detected, or the the MAC is invalid.
        """

        if not isinstance(ciphertext, str):
            raise CiphertextTypeError("Input ciphertext is not of type string")

        plaintext_length = self.getPlaintextLen(ciphertext)
        ciphertext_length = self.getCiphertextLen(ciphertext)
        ciphertext_complete = (len(ciphertext) >= ciphertext_length)
        if ciphertext_complete is False:
            raise RecoverableDecryptionError('Incomplete ciphertext: ('+str(len(ciphertext))+' of '+str(ciphertext_length)+').')

        ciphertext = ciphertext[:ciphertext_length]

        W1_start = 0
        W1_end = AES.block_size
        W1 = ciphertext[W1_start:W1_end]

        W2_start = AES.block_size
        W2_end = AES.block_size + plaintext_length
        W2 = ciphertext[W2_start:W2_end]

        T_start = AES.block_size + plaintext_length
        T_end = AES.block_size + plaintext_length + Encrypter._MAC_LENGTH
        T_expected = ciphertext[T_start:T_end]

        mac = HMAC.new(self.K2, W1 + W2, SHA512)
        T_actual = mac.digest()[:Encrypter._MAC_LENGTH]
        if T_expected != T_actual:
            raise UnrecoverableDecryptionError('Failed to verify MAC.')

        iv2_bytes = '\x02' + self._ecb_enc_K1.decrypt(W1)[1:8]
        counter_val = fte.bit_ops.bytes_to_long(iv2_bytes)
        counter_length_in_bits = AES.block_size * 8
        counter = Counter.new(
            counter_length_in_bits, initial_value=counter_val)
        ctr_enc = AES.new(key=self.K1,
                          mode=AES.MODE_CTR,
                          IV='\x00' * 8 + iv2_bytes,
                          counter=counter)
        plaintext = ctr_enc.decrypt(W2)

        return plaintext


Instruction:
Can you tell what is the following Python 3 function doing
def getCiphertextLen(self, ciphertext):

        plaintext_length = self.getPlaintextLen(ciphertext)
        ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION
        return ciphertext_length

Response: Given a ciphertext with a valid header returns the length of the ciphertext inclusive of ciphertext expansion.


Instruction:
Implement a function in Python 3 to
give a ciphertext with a valid header returns the length of the plaintext payload.

Response:
def getPlaintextLen(self, ciphertext):
        """Given a ``ciphertext`` with a valid header, returns the length of the plaintext payload.
        """

        completeCiphertextHeader = (len(ciphertext) >= 16)
        if completeCiphertextHeader is False:
            raise RecoverableDecryptionError('Incomplete ciphertext header.')

        ciphertext_header = ciphertext[:16]
        L = self._ecb_enc_K1.decrypt(ciphertext_header)

        padding_expected = '\x00\x00\x00\x00'
        padding_actual = L[-8:-4]
        validPadding = (padding_actual == padding_expected)
        if validPadding is False:
            raise UnrecoverableDecryptionError(
                'Invalid padding: ' + padding_actual)

        message_length = fte.bit_ops.bytes_to_long(L[-8:])

        msgLenNonNegative = (message_length >= 0)
        if msgLenNonNegative is False:
            raise UnrecoverableDecryptionError('Negative message length.')

        return message_length


Instruction:
Implement a function in Python 3 to
create a digest suitable for use within an object.

Response:
def _make_digest(k, **kwargs):
    """
    Creates a digest suitable for use within an :class:`phyles.FSCache`
    object from the key object `k`.

    >>> adict = {'a' : {'b':1}, 'f': []}
    >>> make_digest(adict)
    'a2VKynHgDrUIm17r6BQ5QcA5XVmqpNBmiKbZ9kTu0A'
    """
    result = list()
    result_dict = _make_digest_dict(k, **kwargs)
    if result_dict is None:
        return 'default'
    else:
        for (key, h) in sorted(result_dict.items()):
            result.append('{}_{}'.format(key, h))
        return '.'.join(result)


Instruction:
Can you implement a function in Python 3 that
gives model name and stan model code file compute path to cached stan fit if include_prefix returns ( model_prefix model_cachefile

Response:
def cached_model_file(model_name='anon_model', file=None, model_code=None, cache_dir=None,
                      fit_cachefile=None, include_prefix=False):
    ''' Given model name & stan model code/file, compute path to cached stan fit

        if include_prefix, returns (model_prefix, model_cachefile)
    '''
    cache_dir = _get_cache_dir(cache_dir)
    model_name = _sanitize_model_name(model_name)
    ## compute model prefix
    if file:
        model_code = _read_file(file)
    if model_code:
        model_prefix = '.'.join([model_name, _make_digest(dict(model_code=model_code,
                                                               pystan=pystan.__version__,
                                                               cython=Cython.__version__))])
    else: ## handle case where no model code given
        if file is not None:
            logger.info('Note - no model code detected from given file: {}'.format(file))
        else:
            logger.info('Note - no model code detected (neither file nor model_code given)')
    ## parse model_prefix from fit_cachefile if given
    if fit_cachefile:
        # if necessary, impute cache_dir from filepath
        if fit_cachefile != os.path.basename(fit_cachefile):
            cache_dir, fit_cachefile = os.path.split(os.path.abspath(fit_cachefile))
        # if fit_cachefile given, parse to get fit_model_prefix
        fit_model_prefix = re.sub(string=os.path.basename(fit_cachefile), pattern='(.*).stanfit.*', repl='\\1')
        if model_code:
            if fit_model_prefix != model_prefix:
                logger.warning('Computed model prefix does not match that used to estimate model. Using prefix matching fit_cachefile')
        model_prefix = fit_model_prefix
    # compute path to model cachefile
    model_cachefile = '.'.join([model_prefix, 'stanmodel', 'pkl'])
    if include_prefix:
        return model_prefix, model_cachefile
    return model_cachefile


Instruction:
Write a Python 3 script for
giving inputs to cached_stan_fit compute pickle file containing cached fit

Response:
def cached_stan_file(model_name='anon_model', file=None, model_code=None,
                  cache_dir=None, fit_cachefile=None, cache_only=None, force=False,
                  include_modelfile=False, prefix_only=False,
                  **kwargs
                  ):
    ''' Given inputs to cached_stan_fit, compute pickle file containing cached fit
    '''
    model_prefix, model_cachefile = cached_model_file(model_name=model_name, file=file, model_code=model_code,
                                                      cache_dir=cache_dir, fit_cachefile=fit_cachefile, include_prefix=True)
    if not fit_cachefile:
        fit_cachefile = '.'.join([model_prefix, 'stanfit', _make_digest(dict(**kwargs)), 'pkl'])
    if include_modelfile:
        return model_cachefile, fit_cachefile
    if prefix_only:
        fit_cachefile = re.sub(string=fit_cachefile, pattern='.pkl$', repl='')
    return fit_cachefile


Instruction:
Can you tell what is the following Python 3 function doing
def _cached_stan_fit(model_name='anon_model', file=None, model_code=None,
                    force=False, cache_dir=None, cache_only=None,
                     fit_cachefile=None, **kwargs):
    ''' Cache fit stan model, by storing pickled objects in filesystem

    per following warning:
      07: UserWarning: Pickling fit objects is an experimental feature!
        The relevant StanModel instance must be pickled along with this fit object.
        When unpickling the StanModel must be unpickled first.
        pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
    '''
    if fit_cachefile and cache_only is None:
        cache_only = True
    model_cachefile, fit_cachefile = cached_stan_file(model_name=model_name, file=file, model_code=model_code,
                                                      cache_dir=cache_dir, fit_cachefile=fit_cachefile,
                                                      include_modelfile=True, **kwargs)
    cache_dir = _get_cache_dir(cache_dir)
    model_name = _sanitize_model_name(model_name)
    model_code = _get_model_code(model_code=model_code, file=file)
    logger.info('Step 1: Get compiled model code, possibly from cache')
    stan_model = cached(func=pystan.StanModel,
                         cache_filename=model_cachefile,
                         model_code=model_code,
                         cache_dir=cache_dir,
                         model_name=model_name,
                         cache_only=cache_only,
                         force=force)

    ## either pull fitted model from cache, or fit model
    logger.info('Step 2: Get posterior draws from model, possibly from cache')
    fit = cached(func=stan_model.sampling,
                  cache_filename=fit_cachefile,
                  cache_dir=cache_dir,
                  force=force,
                  cache_only=cache_only,
                  **kwargs)
    return fit

Response: Cache fit stan model with the given model code and parameters.


Instruction:
Write a Python 3 function for
fitting a lorentzian curve using p0 as an initial guess. Returns a list of N_points.

Response:
def fit_lorentizan(curve,p0=None,N_points=1000):
	'''Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess.
	It returns a curve with N_points.'''
	def lorentzian(x,x0,A,gamma): return A*gamma**2/((x-x0)**2+gamma**2)
	N=len(curve)
	x=[curve[i][0] for i in range(N)]
	y=[curve[i][1] for i in range(N)]

	from scipy.optimize import curve_fit
	popt,pcov = curve_fit(lorentzian,x,y,p0=p0)
	x0=popt[0]; A=popt[1]; gamma=popt[2]

	a=x[0]; b=x[-1]
	x_step=(b-a)/(N_points-1)
	x_fit=[a+i*x_step for i in range(N_points)]
	fited_curve=[(xi,lorentzian(xi,x0,A,gamma)) for xi in x_fit]
	return fited_curve,A,x0,gamma


Instruction:
How would you implement a function in Python 3 that
returns the amplitude of the electric field for a Gaussian beam.

Response:
def electric_field_amplitude_gaussian(P, sigmax, sigmay=None, Omega=1.0e6,
                                      units="ad-hoc"):
    """Return the amplitude of the electric field for a Gaussian beam.

    This the amplitude at the center of a laser beam of power P (in Watts) and\
 a Gaussian intensity distribution of standard deviations sigmax, sigmay\
 (in meters). The value of E0 is given in rescaled units according to the\
 frequency scale  Omega (in Hertz) understood as absolute frequency\
 (as opposed to angular frequency).

    >>> print(electric_field_amplitude_gaussian(0.001, 0.001))
    19.6861467587

    """
    e0 = hbar*Omega/(e*a0)  # This is the electric field scale.

    if sigmay is None: sigmay = sigmax
    E0 = sqrt((c*mu0*P)/(2*Pi))/sqrt(sigmax*sigmay)
    if units == "ad-hoc":
        E0 = E0/e0
    return E0


Instruction:
Can you tell what is the following Python 3 function doing
def electric_field_amplitude_top(P, a, Omega=1e6, units="ad-hoc"):
    e0 = hbar*Omega/(e*a0)  # This is the electric field scale.
    E0 = sqrt((c*mu0*P)/(Pi*a**2))
    if units == "ad-hoc":
        E0 = E0/e0
    return E0

Response: Return the amplitude of the electric field for a top hat beam of power P and a top - hat intensity distribution of radius a.


Instruction:
Write a Python 3 function that can
return the amplitude of the electric field for saturation parameter.

Response:
def electric_field_amplitude_intensity(s0, Isat=16.6889462814,
                                       Omega=1e6, units="ad-hoc"):
    """Return the amplitude of the electric field for saturation parameter.

    This is at a given saturation parameter s0=I/Isat, where I0 is by default \
Isat=16.6889462814 m/m^2 is the saturation intensity of the D2 line of \
rubidium for circularly polarized light. Optionally, a frequency scale \
`Omega` can be provided.

    >>> print(electric_field_amplitude_intensity(1.0, units="ad-hoc"))
    9.0152984553
    >>> print(electric_field_amplitude_intensity(1.0, Omega=1.0, units="SI"))
    112.135917207
    >>> print(electric_field_amplitude_intensity(1.0, units="SI"))
    0.000112135917207

    """
    E0_sat = sqrt(2*mu0*c*Isat)/Omega

    if units == "ad-hoc":
        e0 = hbar/(e*a0)  # This is the electric field scale.
        E0_sat = E0_sat/e0

    return E0_sat*sqrt(s0)


Instruction:
How would you explain what the following Python 3 function does
def fprint(expr, print_ascii=False):
    if print_ascii:
        pprint(expr, use_unicode=False, num_columns=120)
    else:
        return expr

Response: r Prints the expression in the notebook.


Instruction:
Given the following Python 3 function, write the documentation
def Mu(i, j, s, N, excluded_mu=[]):
    if i == j:
        if s == -1:
            if i == 1:
                return 0
            else:
                mes = 'There is no population rhoii with i='+str(i)+'.'
                raise ValueError(mes)
        mu = i-1
    elif i > j and s == 1:
        mu = i - j + sum([N-k for k in range(1, j)])+N-1
    elif i > j and s == -1:
        mu = i - j + sum([N-k for k in range(1, j)])+N-1 + N*(N-1)/2
    else:
        mes = 'i='+str(i)+', j='+str(j)
        mes += ' Equations for i<j are not calculated.'+str(s)
        raise ValueError(mes)

    if excluded_mu != []:
        mu = mu-len([ii for ii in excluded_mu if ii < mu])
    return mu

Response: This function calculates the global index mu for the element i j.


Instruction:
Can you implement a function in Python 3 that
returns i j s for any given mu.

Response:
def IJ(mu, N):
    """Return i, j, s for any given mu."""
    if mu == 0: return 1, 1, 1

    if mu not in range(0, N**2):
        raise ValueError('mu has an invalid value mu='+str(mu)+'.')

    if 1 <= mu <= N-1:
        return mu+1, mu+1, 1
    else:
        m = N-1
        M = N*(N-1)/2
        for jj in range(1, N):
            for ii in range(jj+1, N+1):
                m += 1
                if m == mu or m+M == mu:
                    if mu > N*(N+1)/2 - 1:
                        return ii, jj, -1
                    else:
                        return ii, jj, 1


Instruction:
Explain what the following Python 3 code does
def read_result(path, name, i=None, j=None, s=0, N=None,
                excluded_mu=[], use_netcdf=True, clone=None):
    r"""This function reads the results stored in path under file name.dat
    returning them as a list of N^2 lists of the form
    [frequency, rho22, rho33, ... rho_N,N-1]. Alternatively it can return only
    two lists [frequency, rho_i,j,s] where s must be 1 for the real part and
    -1 for the imaginary part.
    """
    if clone is not None:
        clone = '_'+str(clone)
    else:
        clone = ''

    if use_netcdf:
        ncfile = Dataset(path+name+clone+'.nc', 'r')
        matrix = ncfile.variables['matrix'][:]
        vector = ncfile.variables['vector'][:]
        Nrho, n_points = len(matrix), len(matrix[0])
        ncfile.close()

        if i is not None:
            mu = Mu(i, j, s, N, excluded_mu)
            if sage_included:
                return [(vector[k], matrix[mu-1][k]) for k in range(n_points)]
            else:
                return vector, matrix[mu-1]
        else:
            return [vector] + [matrix[k] for k in range(Nrho)]
        # ln=[for i in range(m)]
    else:
        r = file(path+name+clone+'.dat', 'r')
        l = r.readlines()
        r.close()

        try:
            ln = [[float(num) for num in li.split()] for li in l]
        except:
            print(num)
            print([l[0]])
            print([l[-2]])
            print([l[-1]])
            raise ValueError

        if i is not None:
            mu = Mu(i, j, s, N, excluded_mu)
            if sage_included:
                return [(li[0], li[mu]) for li in ln]
            else:
                x = [li[0] for li in ln]
                y = [li[mu] for li in ln]
                return x, y
        else:
            dat = [[ln[ii][0] for ii in range(len(ln))]]
            dat += [[ln[ii][mu+1] for ii in range(len(ln))]
                    for mu in range(N**2-1)]
            return dat

Response:
r This function reads the results stored in path under file name. dat
    returns them as a list of N^2 lists where N is the number of times the real part and rho_i j s is the imaginary part and s is the number of times the imaginary part.


Instruction:
Here you have a function in Python 3, explain what it does
def calculate_iI_correspondence(omega):
    Ne = len(omega[0])
    om = omega[0][0]
    correspondence = []
    I = 0
    for i in range(Ne):
        if omega[i][0] != om:
            om = omega[i][0]
            I += 1
        correspondence += [(i+1, I+1)]
    Nnd = I+1

    def I_nd(i):
        return correspondence[i-1][1]

    def i_d(I):
        for i in range(Ne):
            if correspondence[i][1] == I:
                return correspondence[i][0]

    return i_d, I_nd, Nnd

Response: r Return the correspondance between degenerate and nondegenerate schemes.


Instruction:
Explain what the following Python 3 code does
def find_omega_min(omega, Nl, detuningsij, i_d, I_nd):
    omega_min = []
    omega_min_indices = []
    for l in range(Nl):
        omegas = sorted([(omega[i_d(p[0]+1)-1][i_d(p[1]+1)-1], p)
                         for p in detuningsij[l]])
        omega_min += [omegas[0][0]]
        omega_min_indices += [omegas[0][1]]
    return omega_min, omega_min_indices

Response:
r This function returns a list of length Nl containing the mininmal frequency
    that each laser excites.


Instruction:
Implement a function in Python 3 to
identify a merge compatible method available in self.

Response:
def _merge_method(self, key):
        """
        Identify a merge compatible method available in self[key]. Currently we
        support 'update' and 'append'.

        :param key: Attribute name or item key
        :return: Method name usable to merge a value into the instance mapped
                by key
        :rtype: str
        """
        if key in self:
            for method in ["update", "append"]:
                if hasattr(self[key], method):
                    return method
        return None


Instruction:
Implement a Python 3 function for
converting a TweetStatus object to a Tweet object.

Response:
def _tweepy_status_to_tweet(self, status):
        """
        Fields documentation: https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
        """
        tweet = Tweet()
        tweet.published_at = status.created_at
        tweet.content = status.text

        return tweet


Instruction:
Can you generate the documentation for the following Python 3 function
def wrap_cell(entity, json_obj, mapping, table_view=False):
    '''
    Cell wrappers
    for customizing the GUI data table

    TODO : must coincide with hierarchy!
    TODO : simplify this!
    '''
    html_class = '' # for GUI javascript
    out = ''

    #if 'cell_wrapper' in entity: # TODO : this bound type was defined by apps only
    #    out = entity['cell_wrapper'](json_obj)
    #else:

    if entity['multiple']:
        out = ", ".join(  map(lambda x: num2name(x, entity, mapping), json_obj.get(entity['source'], []))  )

    elif entity['is_chem_formula']:
        out = html_formula(json_obj[ entity['source'] ]) if entity['source'] in json_obj else '—'

    elif entity['source'] == 'bandgap':
        html_class = ' class=_g'
        out = json_obj.get('bandgap')
        if out is None: out = '—'

    # dynamic determination below:
    elif entity['source'] == 'energy':
        html_class = ' class=_e'
        out = "%6.5f" % json_obj['energy'] if json_obj['energy'] else '—'

    elif entity['source'] == 'dims':
        out = "%4.2f" % json_obj['dims'] if json_obj['periodicity'] in [2, 3] else '—'

    else:
        out = num2name(json_obj.get(entity['source']), entity, mapping) or '—'

    if table_view:
        return '' + str(out) + '	'
    elif html_class:
        return '' + str(out) + ''

    return str(out)

Response: Wrap the cell in a tree of objects.


Instruction:
Make a summary of the following Python 3 code
def meminfo():
    f = open("/proc/meminfo")
    hwinfo = {}
    for line in f.readlines():
        meml = line.split()
        if (meml[0] == "MemTotal:"):
            mem = int(meml[1])
            hwinfo["Mem_MiB"] = mem/1024
        elif (meml[0] == "SwapTotal:"):
            swap = int(meml[1])
            hwinfo["Swap_MiB"] = swap/1024
    f.close()
    return hwinfo

Response: Get the amount of memory and swap Mebibytes


Instruction:
Can you generate the documentation for the following Python 3 function
def cpuinfo():
    f = open("/proc/cpuinfo")
    hwinfo = {}
    for line in f.readlines():
        cpul = line.split(":")
        name = cpul[0].strip()
        if (len(cpul) > 1):
            val = cpul[1].strip()
        if (name == "model name"):
            hwinfo["CPU"] = val
        elif (name == "cpu MHz"):
            hwinfo["MHz"] = int(round(float(val)))
    f.close()
    return hwinfo

Response: Get the cpu info from the node


Instruction:
How would you explain what the following Python 3 function does
def vgadata():
    if os.path.isfile('/sbin/lspci'):
        lspci = '/sbin/lspci'
    else:
        lspci = '/usr/bin/lspci'
    f = os.popen (lspci + ' -m')
    pdata = {}
    for line in f.readlines():
        p = line.split("\"")
        name = p[1].strip()
        if (name == "VGA compatible controller"):
            pdata["Graphics"] = p[3] + " " + p[5]
    f.close()
    return pdata

Response: Get data about the graphics card.


Instruction:
How would you implement a function in Python 3 that
gets the serial number. Requires root access

Response:
def serial_number():
    """Get the serial number. Requires root access"""
    sdata = {}
    if os.getuid() == 0:
        try:
            sdata['Serial'] = open('/sys/class/dmi/id/product_serial') \
                .read().strip()
        except:
            for line in os.popen('/usr/sbin/dmidecode -s system-serial-number'):
                sdata['Serial'] = line.strip()
    return sdata


Instruction:
How would you code a function in Python 3 to
get manufacturer and model number. On older Linux kernel versions without / sys / class / dmi / id this requires root access.

Response:
def system_model():
    """Get manufacturer and model number.

    On older Linux kernel versions without /sys/class/dmi/id this
    requires root access.
    """
    mdata = {}
    man = None
    pn = None
    try:
        # This might be
        # sys_vendor, bios_vendor, board_vendor, or chassis_vendor
        man = open('/sys/class/dmi/id/sys_vendor').read().strip()
    except:
        if os.getuid() == 0:
            for line in os.popen('/usr/sbin/dmidecode -s system-manufacturer'):
                man = line.strip()
    try:
        pn = open('/sys/class/dmi/id/product_name').read().strip()
    except:
        if os.getuid() == 0:
            for line in os.popen('/usr/sbin/dmidecode -s system-product-name'):
                pn = line.strip()
    if man is not None:
        mdata['System_manufacturer'] = man
    if pn is not None:
        mdata['System_product_name'] = pn
    return mdata


Instruction:
Can you create a Python 3 function that
gets total disk size in GB.

Response:
def diskdata():
    """Get total disk size in GB."""
    p = os.popen("/bin/df -l -P")
    ddata = {}
    tsize = 0
    for line in p.readlines():
        d = line.split()
        if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]):
            tsize = tsize + int(d[1])
    ddata["Disk_GB"] = int(tsize)/1000000
    p.close()
    return ddata


Instruction:
Here you have a function in Python 3, explain what it does
def ip_address():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 8.8.8.8 is the google public DNS
    s.connect(("8.8.8.8", 53))
    ip = s.getsockname()[0]
    s.close()
    return ip

Response: Get the IP address used for public connections.


Instruction:
Create a Python 3 function to
get the MAC address of a specific IP

Response:
def mac_address(ip):
    """Get the MAC address"""
    mac = ''
    for line in os.popen('/sbin/ifconfig'):
        s = line.split()
        if len(s) > 3:
            if s[3] == 'HWaddr':
                mac = s[4]
            elif s[2] == ip:
                break
    return {'MAC': mac}


Instruction:
How would you explain what the following Python 3 function does
def getallhwinfo():
    hwinfo = meminfo()
    hwinfo.update(cpuinfo())
    hwinfo.update(uname())
    hwinfo.update(vgadata())
    hwinfo.update(distro())
    hwinfo.update(diskdata())
    hwinfo.update(hostname())
    hwinfo.update(serial_number())
    ip = ip_address()
    hwinfo.update(mac_address(ip))
    hwinfo.update({'IP': ip})
    hwinfo.update(system_model())
    return hwinfo

Response: Get all the hw info.


Instruction:
How would you explain what the following Python 3 function does
def printheader(h=None):
    writer = csv.writer(sys.stdout)
    writer.writerow(header_fields(h))

Response: Print the header for the CSV table.


Instruction:
Can you create a Python 3 function that
prints as a table.

Response:
def printtable(h, header):
    """Print as a table."""
    hk = header_fields(h)
    if (header):
        printheader()
    writer = csv.DictWriter(sys.stdout, hk, extrasaction='ignore')
    writer.writerow(h)


Instruction:
Make a summary of the following Python 3 code
def agent(server="http://localhost:8000"):
    import xmlrpc.client
    sp = xmlrpc.client.ServerProxy(server)
    hw = getallhwinfo()
    fields = header_fields()
    for f in fields:
        if not f in hw:
            hw[f] = ''
    try:
        sp.puthwinfo(xmlrpc.client.dumps((hw,)))
    except xmlrpc.client.Error as v:
        print("ERROR occured: ", v)

Response: Run in agent mode.


Instruction:
Here you have a function in Python 3, explain what it does
def calculate_omega_matrix(states, Omega=1):
    N = len(states)
    omega = [[2*Pi*(states[i].nu-states[j].nu)/Omega
              for j in range(N)] for i in range(N)]

    return omega

Response: Calculate the matrix of transition frequencies.


Instruction:
Make a summary of the following Python 3 code
def calculate_boundaries(fine_states, full_magnetic_states):
    N_magnetic = len(full_magnetic_states)

    # We calculate the boundaries of the various detail levels
    # First we will make a list of indices of that will tell where each fine
    # level begins and ends.
    fq = full_magnetic_states[0].quantum_numbers[:4]
    index_list_fine = []; start_fine = 0
    # And another list of indices that will tell where each hyperfine level
    # begins and ends.
    hq = full_magnetic_states[0].quantum_numbers[:5]
    index_list_hyperfine = []; start_hyperfine = 0

    for i in range(N_magnetic):
        magnetic = full_magnetic_states[i]
        if magnetic.quantum_numbers[:4] != fq:
            index_list_fine += [(start_fine, i)]
            start_fine = i
            fq = magnetic.quantum_numbers[:4]

        if magnetic.quantum_numbers[:5] != hq:
            index_list_hyperfine += [(start_hyperfine, i)]
            start_hyperfine = i
            hq = magnetic.quantum_numbers[:5]

        if i == N_magnetic-1:
            index_list_fine += [(start_fine, i+1)]
            index_list_hyperfine += [(start_hyperfine, i+1)]
    return index_list_fine, index_list_hyperfine

Response: r This function calculates the boundary indices within a list of magnetic states.


Instruction:
Explain what the following Python 3 code does
def exclude_states(omega, gamma, r, Lij, states, excluded_states):
    Ne = len(omega)
    excluded_indices = [i for i in range(Ne) if states[i] in excluded_states]

    omega_new = []; gamma_new = []; r_new = [[], [], []]; Lij_new = []
    for i in range(Ne):
        row_om = []; row_ga = []; row_L = []
        for j in range(Ne):
            if j not in excluded_indices:
                row_om += [omega[i][j]]
                row_ga += [gamma[i][j]]
                row_L += [Lij[i][j]]
        if i not in excluded_indices:
            omega_new += [row_om]
            gamma_new += [row_ga]
            Lij_new += [row_L]

    for p in range(3):
        for i in range(Ne):
            row_r = []
            for j in range(Ne):
                if j not in excluded_indices:
                    row_r += [r[p][i][j]]
            if i not in excluded_indices:
                r_new[p] += [row_r]

    states_new = [states[i] for i in range(Ne) if i not in excluded_indices]

    return omega_new, gamma_new, r_new, Lij_new, states_new

Response: Exclude states from matrices.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def calculate_reduced_matrix_elements_0(fine_states):
	'''This function calculates the reduced matrix elments <N,L,J||T^1(r)||N',L',J'> given a list of fine states.'''
	#We calculate the reduced matrix elements starting from the list of fine_states

	#The factor composed of physical quantities.
	factor=sqrt(3*c**3*me**2*e**2/(16*Pi*epsilon0*hbar**3))
	#We read the database to obtain the Einstein A coefficients in Hz.
	einsteinA=get_einstein_A_matrix(fine_states)
	#We read the database to obtain the transition frequencies in Hz.
	omega_fine=calculate_omega_matrix(fine_states)

	reduced_matrix_elements=[[0.0 for jj in range(len(fine_states))] for ii in range(len(fine_states))]

	for ii in range(len(fine_states)):
		i=fine_states[ii]
		for jj in range(ii):
			j=fine_states[jj]
			t=Transition(i,j)
			einsteinAij=einsteinA[ii][jj]
			omega0=omega_fine[ii][jj]

			#The formula is valid only for i =/= j so that omega0 =/= 0.
			#Because fine states are asumed to be ordered by their energies we can asume that
			# i decays in j.
			Ji=i.j; Jj=j.j

			rij=sqrt((2.0*Ji+1)/(2*Jj+1))*sqrt(einsteinAij/omega0**3)
			rij=factor*rij

			reduced_matrix_elements[ii][jj]=rij
			#We add the matrix elements on the other side of the diagonal.
			reduced_matrix_elements[jj][ii]=rij*(-1)**(Jj-Ji)

	return reduced_matrix_elements

Response: This function calculates the reduced matrix elements <N L J > given a list of fine states.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def speed_rms(Temperature,element,isotope):
    atom = Atom(element, isotope)
    return sqrt(3*Temperature*k_B/atom.mass)

Response: r This function calculates the average speed of an atom in a vapour assuming a Maxwell - Boltzmann velocity distribution.


Instruction:
Here you have a function in Python 3, explain what it does
def find_decays(self, fine_state):
        def decays_from(fine_state, transitions):
            states_below = []
            for t in transitions:
                if t.e2 == fine_state:
                    states_below += [t.e1]
            return states_below

        def iterate(states, transitions):
            new_and_old_states = states[:]
            for state in states:
                new_states = decays_from(state, transitions)
                for new_state in new_states:
                    if new_state not in new_and_old_states:
                        new_and_old_states += [new_state]

            if states == new_and_old_states:
                return states
            else:
                return iterate(new_and_old_states, transitions)

        transitions = self.transitions()
        states = iterate([fine_state], transitions)

        return states

Response: r Find all possible decays from a given fine state.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _latex_(self):
        if self.l == 0: l = 'S'
        elif self.l == 1: l = 'P'
        elif self.l == 2: l = 'D'
        elif self.l == 3: l = 'F'
        else: l = str(self.l)

        if self.f is None:
            s = '^{'+str(self.isotope)+'}\\mathrm{'+self.element+'}\\ '
            s += str(self.n)+l+'_{'+str(self.j)+'}'
        else:
            s = '^{'+str(self.isotope)+'}\\mathrm{'+self.element+'}\\ '
            s += str(self.n)+l+'_{'+str(self.j)+'}^{'+str(self.f)+'}'

        if self.m is not None:
            s = s[:-1] + ','+str(self.m)+'}'

        return s

Response: The LaTeX routine for states.


Instruction:
Can you generate the documentation for the following Python 3 function
def _latex_(self):
        if self.allowed:
            return self.e1._latex_()+'\\ \\rightarrow \\ '+self.e2._latex_()
        elif not self.allowed:
            return self.e1._latex_()+'\\ \\nrightarrow \\ '+self.e2._latex_()
        else:
            return self.e1._latex_()+'\\ \\rightarrow^? \\ '+self.e2._latex_()

        return self.e1._latex_()+'\\ \\nleftrightarrow \\ '+self.e2._latex_()

Response: The LaTeX representation routine for transitions.


Instruction:
Write a Python 3 script for
finding the lower index of the segment that contains the value x

Response:
def _findSegment(self, x):
        '''
        :param x: x value to place in segment defined by the xData (instantiation)
        :return: The lower index in the segment
        '''
        iLeft = 0
        iRight = len(self.xData) - 1
        while True:
            if iRight - iLeft <= 1:
                return iLeft
            i = (iRight + iLeft) / 2
            if x < self.xData[i]:
                iRight = i
            else:
                iLeft = i


Instruction:
Can you tell what is the following Python 3 function doing
def calculate_r_matrices(fine_states, reduced_matrix_elements, q=None,
                         numeric=True, convention=1):
    ur"""Calculate the matrix elements of the electric dipole (in the helicity
    basis).

    We calculate all matrix elements for the D2 line in Rb 87.

    >>> from sympy import symbols, pprint
    >>> red = symbols("r", positive=True)
    >>> reduced_matrix_elements = [[0, -red], [red, 0]]
    >>> g = State("Rb", 87, 5, 0, 1/Integer(2))
    >>> e = State("Rb", 87, 5, 1, 3/Integer(2))
    >>> fine_levels = [g, e]
    >>> r = calculate_r_matrices(fine_levels, reduced_matrix_elements,
    ...     numeric=False)
    >>> pprint(r[0][8:,:8])
    ⎡                √3⋅r                                  ⎤
    ⎢ 0       0      ────    0    0       0     0      0   ⎥
    ⎢                 6                                    ⎥
    ⎢                                                      ⎥
    ⎢      -√15⋅r                       √15⋅r              ⎥
    ⎢ 0    ───────     0     0    0     ─────   0      0   ⎥
    ⎢         12                          60               ⎥
    ⎢                                                      ⎥
    ⎢               -√15⋅r                     √5⋅r        ⎥
    ⎢ 0       0     ───────  0    0       0    ────    0   ⎥
    ⎢                  12                       20         ⎥
    ⎢                                                      ⎥
    ⎢                                                √10⋅r ⎥
    ⎢ 0       0        0     0    0       0     0    ───── ⎥
    ⎢                                                  20  ⎥
    ⎢                                                      ⎥
    ⎢√2⋅r                       -√6⋅r                      ⎥
    ⎢────     0        0     0  ──────    0     0      0   ⎥
    ⎢ 4                           12                       ⎥
    ⎢                                                      ⎥
    ⎢         r                          -r                ⎥
    ⎢ 0       ─        0     0    0      ───    0      0   ⎥
    ⎢         4                           4                ⎥
    ⎢                                                      ⎥
    ⎢                √3⋅r                      -r          ⎥
    ⎢ 0       0      ────    0    0       0    ───     0   ⎥
    ⎢                 12                        4          ⎥
    ⎢                                                      ⎥
    ⎢                                                -√6⋅r ⎥
    ⎢ 0       0        0     0    0       0     0    ──────⎥
    ⎢                                                  12  ⎥
    ⎢                                                      ⎥
    ⎢ 0       0        0     0    0       0     0      0   ⎥
    ⎢                                                      ⎥
    ⎢                        r                             ⎥
    ⎢ 0       0        0     ─    0       0     0      0   ⎥
    ⎢                        2                             ⎥
    ⎢                                                      ⎥
    ⎢                            √6⋅r                      ⎥
    ⎢ 0       0        0     0   ────     0     0      0   ⎥
    ⎢                             6                        ⎥
    ⎢                                                      ⎥
    ⎢                                   √10⋅r              ⎥
    ⎢ 0       0        0     0    0     ─────   0      0   ⎥
    ⎢                                     10               ⎥
    ⎢                                                      ⎥
    ⎢                                          √5⋅r        ⎥
    ⎢ 0       0        0     0    0       0    ────    0   ⎥
    ⎢                                           10         ⎥
    ⎢                                                      ⎥
    ⎢                                                √15⋅r ⎥
    ⎢ 0       0        0     0    0       0     0    ───── ⎥
    ⎢                                                  30  ⎥
    ⎢                                                      ⎥
    ⎢ 0       0        0     0    0       0     0      0   ⎥
    ⎢                                                      ⎥
    ⎣ 0       0        0     0    0       0     0      0   ⎦
    >>> pprint(r[1][8:,:8])
    ⎡       -√3⋅r                                                 ⎤
    ⎢  0    ──────     0      0      0        0       0       0   ⎥
    ⎢         6                                                   ⎥
    ⎢                                                             ⎥
    ⎢√15⋅r                         -√5⋅r                          ⎥
    ⎢─────    0        0      0    ──────     0       0       0   ⎥
    ⎢  12                            20                           ⎥
    ⎢                                                             ⎥
    ⎢                                      -√15⋅r                 ⎥
    ⎢  0      0        0      0      0     ───────    0       0   ⎥
    ⎢                                         30                  ⎥
    ⎢                                                             ⎥
    ⎢               -√15⋅r                          -√5⋅r         ⎥
    ⎢  0      0     ───────   0      0        0     ──────    0   ⎥
    ⎢                  12                             20          ⎥
    ⎢                                                             ⎥
    ⎢                        √3⋅r                                 ⎥
    ⎢  0      0        0     ────    0        0       0       0   ⎥
    ⎢                         6                                   ⎥
    ⎢                                                             ⎥
    ⎢  r                            √3⋅r                          ⎥
    ⎢  ─      0        0      0     ────      0       0       0   ⎥
    ⎢  4                             12                           ⎥
    ⎢                                                             ⎥
    ⎢        √3⋅r                                                 ⎥
    ⎢  0     ────      0      0      0        0       0       0   ⎥
    ⎢         6                                                   ⎥
    ⎢                                                             ⎥
    ⎢                  r                            -√3⋅r         ⎥
    ⎢  0      0        ─      0      0        0     ──────    0   ⎥
    ⎢                  4                              12          ⎥
    ⎢                                                             ⎥
    ⎢                                                       -√3⋅r ⎥
    ⎢  0      0        0      0      0        0       0     ──────⎥
    ⎢                                                         6   ⎥
    ⎢                                                             ⎥
    ⎢  0      0        0      0      0        0       0       0   ⎥
    ⎢                                                             ⎥
    ⎢                        √3⋅r                                 ⎥
    ⎢  0      0        0     ────    0        0       0       0   ⎥
    ⎢                         6                                   ⎥
    ⎢                                                             ⎥
    ⎢                              √30⋅r                          ⎥
    ⎢  0      0        0      0    ─────      0       0       0   ⎥
    ⎢                                15                           ⎥
    ⎢                                                             ⎥
    ⎢                                       √15⋅r                 ⎥
    ⎢  0      0        0      0      0      ─────     0       0   ⎥
    ⎢                                         10                  ⎥
    ⎢                                                             ⎥
    ⎢                                               √30⋅r         ⎥
    ⎢  0      0        0      0      0        0     ─────     0   ⎥
    ⎢                                                 15          ⎥
    ⎢                                                             ⎥
    ⎢                                                        √3⋅r ⎥
    ⎢  0      0        0      0      0        0       0      ──── ⎥
    ⎢                                                         6   ⎥
    ⎢                                                             ⎥
    ⎣  0      0        0      0      0        0       0       0   ⎦
    >>> pprint(r[2][8:,:8])
    ⎡√3⋅r                                           ⎤
    ⎢────     0     0      0     0      0     0    0⎥
    ⎢ 6                                             ⎥
    ⎢                                               ⎥
    ⎢                    √10⋅r                      ⎥
    ⎢  0      0     0    ─────   0      0     0    0⎥
    ⎢                      20                       ⎥
    ⎢                                               ⎥
    ⎢√15⋅r                      √5⋅r                ⎥
    ⎢─────    0     0      0    ────    0     0    0⎥
    ⎢  12                        20                 ⎥
    ⎢                                               ⎥
    ⎢       √15⋅r                     √15⋅r         ⎥
    ⎢  0    ─────   0      0     0    ─────   0    0⎥
    ⎢         12                        60          ⎥
    ⎢                                               ⎥
    ⎢  0      0     0      0     0      0     0    0⎥
    ⎢                                               ⎥
    ⎢                    √6⋅r                       ⎥
    ⎢  0      0     0    ────    0      0     0    0⎥
    ⎢                     12                        ⎥
    ⎢                                               ⎥
    ⎢√3⋅r                        r                  ⎥
    ⎢────     0     0      0     ─      0     0    0⎥
    ⎢ 12                         4                  ⎥
    ⎢                                               ⎥
    ⎢         r                         r           ⎥
    ⎢  0      ─     0      0     0      ─     0    0⎥
    ⎢         4                         4           ⎥
    ⎢                                               ⎥
    ⎢              √2⋅r                      √6⋅r   ⎥
    ⎢  0      0    ────    0     0      0    ────  0⎥
    ⎢               4                         12    ⎥
    ⎢                                               ⎥
    ⎢  0      0     0      0     0      0     0    0⎥
    ⎢                                               ⎥
    ⎢  0      0     0      0     0      0     0    0⎥
    ⎢                                               ⎥
    ⎢                    √15⋅r                      ⎥
    ⎢  0      0     0    ─────   0      0     0    0⎥
    ⎢                      30                       ⎥
    ⎢                                               ⎥
    ⎢                           √5⋅r                ⎥
    ⎢  0      0     0      0    ────    0     0    0⎥
    ⎢                            10                 ⎥
    ⎢                                               ⎥
    ⎢                                 √10⋅r         ⎥
    ⎢  0      0     0      0     0    ─────   0    0⎥
    ⎢                                   10          ⎥
    ⎢                                               ⎥
    ⎢                                        √6⋅r   ⎥
    ⎢  0      0     0      0     0      0    ────  0⎥
    ⎢                                         6     ⎥
    ⎢                                               ⎥
    ⎢                                              r⎥
    ⎢  0      0     0      0     0      0     0    ─⎥
    ⎣                                              2⎦

    """
    magnetic_states = make_list_of_states(fine_states, 'magnetic', verbose=0)
    aux = calculate_boundaries(fine_states, magnetic_states)
    index_list_fine, index_list_hyperfine = aux

    Ne = len(magnetic_states)

    r = [[[0 for j in range(Ne)] for i in range(Ne)] for p in range(3)]

    II = fine_states[0].i

    for p in [-1, 0, 1]:
        for i in range(Ne):
            ei = magnetic_states[i]
            ii = fine_index(i, index_list_fine)

            for j in range(Ne):
                ej = magnetic_states[j]
                jj = fine_index(j, index_list_fine)

                reduced_matrix_elementij = reduced_matrix_elements[ii][jj]
                if reduced_matrix_elementij != 0:

                    ji = ei.j; jj = ej.j
                    fi = ei.f; fj = ej.f
                    mi = ei.m; mj = ej.m

                    rpij = matrix_element(ji, fi, mi, jj, fj, mj,
                                          II, reduced_matrix_elementij, p,
                                          numeric=numeric,
                                          convention=convention)

                    if q == 1:
                        r[p+1][i][j] = rpij*delta_lesser(i, j)
                    elif q == -1:
                        r[p+1][i][j] = rpij*delta_greater(i, j)
                    else:
                        r[p+1][i][j] = rpij

    if not numeric:
        r = [Matrix(ri) for ri in r]
    return r

Response: ur This function calculates the matrix elements of the electric dipole in the helicity tree.


Instruction:
Here you have a function in Python 3, explain what it does
def doppler_width(transition, Temperature):
    atom = Atom(transition.e1.element, transition.e1.isotope)
    m = atom.mass
    omega = transition.omega
    return omega*np.log(8*np.sqrt(2))*np.sqrt(k_B*Temperature/m/c**2)

Response: r Return the Doppler width of a transition at a given temperature.


Instruction:
Here you have a function in Python 3, explain what it does
def transitions(self, omega_min=None, omega_max=None):
        states = self.states()
        transitions = states
        transitions = []
        for i in range(len(states)):
            si = states[i]
            for j in range(i):
                sj = states[j]
                t = Transition(sj, si)
                if t.allowed:
                    transitions += [t]

        if omega_min is not None:
            transitions = [ti for ti in transitions
                           if abs(ti.omega) >= omega_min]
        if omega_max is not None:
            transitions = [ti for ti in transitions
                           if abs(ti.omega) <= omega_max]

        return transitions

Response: r Find all allowed transitions in the atom.


Instruction:
Here you have a function in Python 3, explain what it does
def read_roi(fileobj):
    '''
    points = read_roi(fileobj)

    Read ImageJ's ROI format. Points are returned in a nx2 array. Each row
    is in [row, column] -- that is, (y,x) -- order.
    '''
    # This is based on:
    # http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiDecoder.java.html
    # http://rsbweb.nih.gov/ij/developer/source/ij/io/RoiEncoder.java.html

    SPLINE_FIT = 1
    DOUBLE_HEADED = 2
    OUTLINE = 4
    OVERLAY_LABELS = 8
    OVERLAY_NAMES = 16
    OVERLAY_BACKGROUNDS = 32
    OVERLAY_BOLD = 64
    SUB_PIXEL_RESOLUTION = 128
    DRAW_OFFSET = 256

    class RoiType:
        POLYGON = 0
        RECT = 1
        OVAL = 2
        LINE = 3
        FREELINE = 4
        POLYLINE = 5
        NOROI = 6
        FREEHAND = 7
        TRACED = 8
        ANGLE = 9
        POINT = 10

    def get8():
        s = fileobj.read(1)
        if not s:
            raise IOError('readroi: Unexpected EOF')
        return ord(s)

    def get16():
        b0 = get8()
        b1 = get8()
        return (b0 << 8) | b1

    def get32():
        s0 = get16()
        s1 = get16()
        return (s0 << 16) | s1

    def getfloat():
        v = np.int32(get32())
        return v.view(np.float32)

    #===========================================================================
    #Read Header data

    magic = fileobj.read(4)
    if magic != b'Iout':
        raise ValueError('Magic number not found')

    version = get16()

    # It seems that the roi type field occupies 2 Bytes, but only one is used
    roi_type = get8()
    # Discard second Byte:
    get8()

    top = get16()
    left = get16()
    bottom = get16()
    right = get16()
    n_coordinates = get16()
    x1 = getfloat()
    y1 = getfloat()
    x2 = getfloat()
    y2 = getfloat()
    stroke_width = get16()
    shape_roi_size = get32()
    stroke_color = get32()
    fill_color = get32()
    subtype = get16()

    options = get16()
    arrow_style = get8()
    arrow_head_size = get8()
    rect_arc_size = get16()
    position = get32()
    header2offset = get32()

    # End Header data
    #===========================================================================

    #RoiDecoder.java checks the version when setting sub-pixel resolution, therefore so do we
    subPixelResolution = ((options&SUB_PIXEL_RESOLUTION)!=0) and (version>=222)

    # Check exceptions
    if roi_type not in [RoiType.FREEHAND, RoiType.TRACED, RoiType.POLYGON, RoiType.RECT, RoiType.POINT]:
        raise NotImplementedError('roireader: ROI type %s not supported' % roi_type)

    if subtype != 0:
        raise NotImplementedError('roireader: ROI subtype %s not supported (!= 0)' % subtype)

    if roi_type == RoiType.RECT:
        if subPixelResolution:
            return np.array(
                [[y1, x1], [y1, x1+x2], [y1+y2, x1+x2], [y1+y2, x1]],
                dtype=np.float32)
        else:
            return np.array(
                [[top, left], [top, right], [bottom, right], [bottom, left]],
                dtype=np.int16)

    if subPixelResolution:
        getc = getfloat
        points = np.empty((n_coordinates, 2), dtype=np.float32)
        fileobj.seek(4*n_coordinates, 1)
    else:
        getc = get16
        points = np.empty((n_coordinates, 2), dtype=np.int16)

    points[:, 1] = [getc() for i in range(n_coordinates)]
    points[:, 0] = [getc() for i in range(n_coordinates)]

    if not subPixelResolution:
        points[:, 1] += left
        points[:, 0] += top

    return points

Response: Read ImageJ s ROI format.


Instruction:
Here you have a function in Python 3, explain what it does
def perm_j(j1, j2):
    jmin = abs(j1-j2)
    jmax = j1+j2
    return [jmin + i for i in range(jmax-jmin+1)]

Response: r Calculate the allowed total angular momenta.


Instruction:
Make a summary of the following Python 3 code
def angular_momentum_matrix(J, ind="z"):
    MJ = [-J+i for i in range(2*J+1)]

    if ind == "x":
        JX = Matrix([[sqrt((J-mj)*(J+mj+1))/2*KroneckerDelta(mi-1, mj)
                     for mj in MJ] for mi in MJ])
        JX += Matrix([[sqrt((J+mj)*(J-mj+1))/2*KroneckerDelta(mi+1, mj)
                      for mj in MJ] for mi in MJ])
        return JX
    elif ind == "y":
        JY = Matrix([[-I*sqrt((J-mj)*(J+mj+1))/2*KroneckerDelta(mi-1, mj)
                     for mj in MJ] for mi in MJ])
        JY += Matrix([[+I*sqrt((J+mj)*(J-mj+1))/2*KroneckerDelta(mi+1, mj)
                      for mj in MJ] for mi in MJ])
        return JY
    elif ind == "z":
        JZ = Matrix([[mi*KroneckerDelta(mi, mj) for mj in MJ] for mi in MJ])
        return JZ
    elif ind == "all":
        JX = angular_momentum_matrix(J, "x")
        JY = angular_momentum_matrix(J, "y")
        JZ = angular_momentum_matrix(J, "z")
        return JX, JY, JZ

Response:
ur Returns the angular momentum matrix for a \
    given a J angular momentum.


Instruction:
Can you tell what is the following Python 3 function doing
def spherical_tensor(Ji, Jj, K, Q):
    keti = {(Ji, Mi): Matrix([KroneckerDelta(i, j)
            for j in range(2*Ji+1)])
            for i, Mi in enumerate(perm_m(Ji))}

    braj = {(Jj, Mj): Matrix([KroneckerDelta(i, j)
            for j in range(2*Jj+1)]).adjoint()
            for i, Mj in enumerate(perm_m(Jj))}

    if K not in perm_j(Ji, Jj):
        raise ValueError("K value is not allowed.")
    if Q not in perm_m(K):
        raise ValueError("Q value is not allowed.")

    Ni = 2*Ji+1
    Nj = 2*Jj+1
    T = zeros(Ni, Nj)
    for i, Mi in enumerate(perm_m(Ji)):
        for j, Mj in enumerate(perm_m(Jj)):
            T += (-1)**(Jj-Mj)*clebsch_gordan(Ji, Jj, K, Mi, -Mj, Q) * \
                keti[(Ji, Mi)]*braj[(Jj, Mj)]

    return T

Response:
Return a matrix representation of the spherical tensor with quantum
    numbers J_i J_j K Q.


Instruction:
Create a Python 3 function for
returning the small Wigner d matrix for angular momentum J.

Response:
def wigner_d_small(J, beta):
    u"""Return the small Wigner d matrix for angular momentum J.

    We use the general formula from [Edmonds74]_, equation 4.1.15.

    Some examples form [Edmonds74]_:

    >>> from sympy import Integer, symbols, pi
    >>> half = 1/Integer(2)
    >>> beta = symbols("beta", real=True)
    >>> wigner_d_small(half, beta)
    Matrix([
    [ cos(beta/2), sin(beta/2)],
    [-sin(beta/2), cos(beta/2)]])

    >>> from sympy import pprint
    >>> pprint(wigner_d_small(2*half, beta), use_unicode=True)
    ⎡        2⎛β⎞              ⎛β⎞    ⎛β⎞           2⎛β⎞     ⎤
    ⎢     cos ⎜─⎟        √2⋅sin⎜─⎟⋅cos⎜─⎟        sin ⎜─⎟     ⎥
    ⎢         ⎝2⎠              ⎝2⎠    ⎝2⎠            ⎝2⎠     ⎥
    ⎢                                                        ⎥
    ⎢       ⎛β⎞    ⎛β⎞       2⎛β⎞      2⎛β⎞        ⎛β⎞    ⎛β⎞⎥
    ⎢-√2⋅sin⎜─⎟⋅cos⎜─⎟  - sin ⎜─⎟ + cos ⎜─⎟  √2⋅sin⎜─⎟⋅cos⎜─⎟⎥
    ⎢       ⎝2⎠    ⎝2⎠        ⎝2⎠       ⎝2⎠        ⎝2⎠    ⎝2⎠⎥
    ⎢                                                        ⎥
    ⎢        2⎛β⎞               ⎛β⎞    ⎛β⎞          2⎛β⎞     ⎥
    ⎢     sin ⎜─⎟        -√2⋅sin⎜─⎟⋅cos⎜─⎟       cos ⎜─⎟     ⎥
    ⎣         ⎝2⎠               ⎝2⎠    ⎝2⎠           ⎝2⎠     ⎦

    From table 4 in [Edmonds74]_

    >>> wigner_d_small(half, beta).subs({beta:pi/2})
    Matrix([
    [ sqrt(2)/2, sqrt(2)/2],
    [-sqrt(2)/2, sqrt(2)/2]])

    >>> wigner_d_small(2*half, beta).subs({beta:pi/2})
    Matrix([
    [       1/2,  sqrt(2)/2,       1/2],
    [-sqrt(2)/2,          0, sqrt(2)/2],
    [       1/2, -sqrt(2)/2,       1/2]])

    >>> wigner_d_small(3*half, beta).subs({beta:pi/2})
    Matrix([
    [ sqrt(2)/4,  sqrt(6)/4,  sqrt(6)/4, sqrt(2)/4],
    [-sqrt(6)/4, -sqrt(2)/4,  sqrt(2)/4, sqrt(6)/4],
    [ sqrt(6)/4, -sqrt(2)/4, -sqrt(2)/4, sqrt(6)/4],
    [-sqrt(2)/4,  sqrt(6)/4, -sqrt(6)/4, sqrt(2)/4]])

    >>> wigner_d_small(4*half, beta).subs({beta:pi/2})
    Matrix([
    [      1/4,  1/2, sqrt(6)/4,  1/2,       1/4],
    [     -1/2, -1/2,         0,  1/2,       1/2],
    [sqrt(6)/4,    0,      -1/2,    0, sqrt(6)/4],
    [     -1/2,  1/2,         0, -1/2,       1/2],
    [      1/4, -1/2, sqrt(6)/4, -1/2,       1/4]])

    """
    def prod(x):
        p = 1
        for i, xi in enumerate(x): p = p*xi
        return p

    M = [J-i for i in range(2*J+1)]
    d = []
    for Mi in M:
        row = []
        for Mj in M:

            # We get the maximum and minimum value of sigma.
            sigmamax = max([-Mi-Mj, J-Mj])
            sigmamin = min([0, J-Mi])

            dij = sqrt(factorial(J+Mi)*factorial(J-Mi) /
                       factorial(J+Mj)/factorial(J-Mj))
            terms = [[(-1)**(J-Mi-s),
                      binomial(J+Mj, J-Mi-s),
                      binomial(J-Mj, s),
                      cos(beta/2)**(2*s+Mi+Mj),
                      sin(beta/2)**(2*J-2*s-Mj-Mi)]
                     for s in range(sigmamin, sigmamax+1)]

            terms = [prod(term) if 0 not in term else 0 for term in terms]

            dij = dij*sum(terms)
            row += [dij]
        d += [row]

    return Matrix(d)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def wigner_d(J, alpha, beta, gamma):
    d = wigner_d_small(J, beta)
    M = [J-i for i in range(2*J+1)]
    D = [[exp(I*Mi*alpha)*d[i, j]*exp(I*Mj*gamma)
          for j, Mj in enumerate(M)] for i, Mi in enumerate(M)]
    return Matrix(D)

Response: Return the Wigner D matrix for angular momentum J.


Instruction:
Can you write a function in Python 3 where it
generates coordinates for a tiling of unit squares.

Response:
def generate_unit_squares(image_width, image_height):
    """Generate coordinates for a tiling of unit squares."""
    # Iterate over the required rows and cells.  The for loops (x, y)
    # give the coordinates of the top left-hand corner of each square:
    #
    #      (x, y) +-----+ (x + 1, y)
    #             |     |
    #             |     |
    #             |     |
    #  (x, y + 1) +-----+ (x + 1, y + 1)
    #
    for x in range(image_width):
        for y in range(image_height):
            yield [(x, y), (x + 1, y), (x + 1, y + 1), (x, y + 1)]


Instruction:
Make a summary of the following Python 3 code
def generate_unit_triangles(image_width, image_height):
    # Our triangles lie with one side parallel to the x-axis.  Let s be
    # the length of one side, and h the height of the triangle.
    #
    # The for loops (x, y) gives the coordinates of the top left-hand corner
    # of a pair of triangles:
    #
    #           (x, y) +-----+ (x + 1, y)
    #                   \   / \
    #                    \ /   \
    #    (x + 1/2, y + h) +-----+ (x + 3/2, y + h)
    #
    # where h = sin(60°) is the height of an equilateral triangle with
    # side length 1.
    #
    # On odd-numbered rows, we translate by (s/2, 0) to make the triangles
    # line up with the even-numbered rows.
    #
    # To avoid blank spaces on the edge of the canvas, the first pair of
    # triangles on each row starts at (-1, 0) -- one width before the edge
    # of the canvas.
    h = math.sin(math.pi / 3)

    for x in range(-1, image_width):
        for y in range(int(image_height / h)):

            # Add a horizontal offset on odd numbered rows
            x_ = x if (y % 2 == 0) else x + 0.5

            yield [(x_, y * h), (x_ + 1, y * h), (x_ + 0.5, (y + 1) * h)]
            yield [(x_ + 1, y * h), (x_ + 1.5, (y + 1) * h),
                   (x_ + 0.5, (y + 1) * h)]

Response: Generate coordinates for a tiling of unit triangles.


Instruction:
Can you write a function in Python 3 where it
restores settings to default values.

Response:
def restore_default_settings():
    """ Restore settings to default values.
    """
    global __DEFAULTS
    __DEFAULTS.CACHE_DIR = defaults.CACHE_DIR
    __DEFAULTS.SET_SEED = defaults.SET_SEED
    __DEFAULTS.SEED = defaults.SEED
    logging.info('Settings reverted to their default values.')


Instruction:
Write a Python 3 script to
load config file into default settings

Response:
def load_config(config_file='~/.stancache.ini'):
    """ Load config file into default settings
    """
    if not os.path.exists(config_file):
        logging.warning('Config file does not exist: {}. Using default settings.'.format(config_file))
        return
    ## get user-level config in *.ini format
    config = configparser.ConfigParser()
    config.read(config_file)
    if not config.has_section('main'):
        raise ValueError('Config file {} has no section "main"'.format(config_file))
    for (key, val) in config.items('main'):
        _set_value(key.upper(), val)
    return


Instruction:
Here you have a function in Python 3, explain what it does
def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs):

    eft = EmailFromTemplate(name=name)
    eft.subject = subject
    eft.context = ctx_dict
    eft.get_object()
    eft.render_message()
    eft.send_email(send_to=send_to, **kwargs)

Response: Shortcut function for EmailFromTemplate class.


Instruction:
Can you implement a function in Python 3 that
sets the logging level of the current log entry.

Response:
def set_level(cls, level):
        """
        :raises: ValueError
        """
        level = (
            level
            if not is_str(level)
            else int(LOGGING_LEVELS.get(level.upper(), level))
        )

        for handler in root.handlers:
            handler.setLevel(level)

        root.setLevel(level)


Instruction:
Write a Python 3 function for
loading the configfile and return a dict of the class

Response:
def load_config(cls, configfile="logging.yaml"):
        """
        :raises: ValueError
        """
        configfile = getenv(cls.CONFIGFILE_ENV_KEY, configfile)
        if isfile(configfile):
            with open(configfile, "r") as cf:
                # noinspection PyBroadException
                try:
                    dictConfig(load(cf))
                except ValueError:
                    debug("Learn to config foooo! Improper config at %s", configfile)
                except Exception:
                    exception("Something went wrong while reading %s.", configfile)
        else:
            raise ValueError("Invalid configfile specified: {}".format(configfile))


Instruction:
Implement a Python 3 function for
parsing a string to remove and replace all wiki markup tags

Response:
def __parse(self, string=''):
        '''
        Parse a string to remove and replace all wiki markup tags
        '''
        self.string = string
        self.string = self.wiki_re.sub('', self.string)
        # search for lists
        self.listmatch = re.search('^(\*+)', self.string)
        if self.listmatch:
            self.string = self.__list(self.listmatch) + re.sub('^(\*+)', \
                          '', self.string)
        return self.string


Instruction:
Given the following Python 3 function, write the documentation
def parse_string(self, string=''):
        '''
        Parse a string object to de-wikified text
        '''
        self.strings = string.splitlines(1)
        self.strings = [self.__parse(line) for line in self.strings]
        return ''.join(self.strings)

Response: Parse a string object to de - wikified text


Instruction:
Can you tell what is the following Python 3 function doing
def run_evolution(path,name,E0,laser_frequencies,  N_iter,dt,N_states,
				spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None,
				rho0=None,print_steps=False,
				integrate=False,
				save_systems=False,save_eigenvalues=False,rk4=False,use_netcdf=True):
	"""This function runs the Runge-Kutta method compiled in path+name..."""
	def py2f_bool(bool_var):
		if bool_var:
			return ".true.\n"
		else:
			return ".false.\n"

	if rk4:
		return run_rk4(path,name,E0,laser_frequencies,  N_iter,dt,N_states,
				spectrum_of_laser=spectrum_of_laser,N_delta=N_delta,
				frequency_step=frequency_step, frequency_end=frequency_end,
				rho0=rho0,print_steps=print_steps,
				integrate=integrate,save_systems=save_systems)

	t0=time()
	params =str(N_iter)+'\n'
	params+=str(dt)+'\n'
	#We give the flag on wether to print each time step.
	params+=py2f_bool(print_steps)

	#We give the initial value of rho
	N_vars=N_states*(N_states+1)/2-1
	if rho0==None:
		params+=''.join(['(0.0,0.0) ' for i in range(N_states**2-1)])
	elif len(rho0)==N_states-1:
		if sage_included:
			params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
		else:
			params+=''.join(['('+str(i.real)+','+str(i.imag)+') ' for i in rho0])
		params+=''.join(['(0.0,0.0) ' for i in range( N_states**2 -N_states)])
	elif len(rho0)==N_vars:
		params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
	else:
		raise ValueError,'rho0 had an invalid number of elements.'

	params+='\n'
	#We give the amplitude of the electrical fields.
	params+=''.join([str(i)+' ' for i in E0])+'\n'

	#We give the detuning of each laser (taken from the lowest frequency transition).
	params+=''.join([str(i)+' ' for i in laser_frequencies])+'\n'

	#We give the flag on wether to calculate spectrums or time evolution.
	if spectrum_of_laser==None:
		params+='.false.\n'
		params+=py2f_bool(save_systems)
		params+=py2f_bool(save_eigenvalues)
		params+=py2f_bool(use_netcdf)
		params+=py2f_bool(integrate)

	else:
		if frequency_end !=None:
			if frequency_step !=None:
				raise ValueError,'both frequency_end and frequency_step were specified.'
			if N_delta==1:
				frequency_step=0.0
			else:
				frequency_step=(frequency_end-laser_frequencies[spectrum_of_laser-1])/(N_delta-1)

		#frequency_step=frequency_end
		params+='.true.\n'
		params+=py2f_bool(save_systems)
		params+=py2f_bool(save_eigenvalues)
		params+=py2f_bool(use_netcdf)
		params+=py2f_bool(integrate)

		params+=str(spectrum_of_laser)+'\n'
		params+=str(N_delta)+'\n'
		params+=str(frequency_step)
	#print params

	f=file(path+name+'_params.dat','w')
	f.write(params)
	f.close()

	os.system(path+name)
	return time()-t0

Response: This function runs the Runge - Kutta method compiled in path + name...


Instruction:
Can you tell what is the following Python 3 function doing
def characteristic_times(path,name,Omega=1):
	r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the oscillation periods, and the shortest and half lives.
The results are lists ordered as:
	``[detunings, oscillation_periods_1, oscillation_periods_N**2-1, half_lives_1, half_lives_N**2-1]``.
'''
	re,im=get_eigenvalues(path,name)

	log12=log(0.5)
	Nr=len(re[0]); Nd=len(re)
	half_lives=[]; oscillation_periods=[]
	for i in range(Nr):
		col_half=[]
		col_osci=[]
		for j in range(Nd):
			if re[j][i]>=0.0 and i!=0:
				raise ValueError,'an eigenvalue was greater or equall to zero:'+str(re[j][i])+'.'
			else:
				col_half+=[log12/re[j][i]/Omega]

			if im[j][i]==0.0 and i!=0:
				col_osci+=[float('inf')]
			else:
				col_osci+=[abs(2*pi/im[j][i])/Omega]
		half_lives+=[col_half]
		oscillation_periods+=[col_osci]
	return oscillation_periods+half_lives[1:]

Response: This function returns the oscillation periods and shortest and half lives of a characteristic.


Instruction:
Given the following Python 3 function, write the documentation
def get_checksum(self):
        '''
        Retrieve unique hash in a cross-platform manner:
        this is how calculation identity is determined
        '''
        if self._checksum:
            return self._checksum

        if not self._filename:
            raise RuntimeError('Source calc file is required in order to properly save the data!')

        calc_checksum = hashlib.sha224()
        struc_repr = ""
        for ase_obj in self.structures:
            struc_repr += "%3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f %3.6f " % tuple(map(abs, [ase_obj.cell[0][0], ase_obj.cell[0][1], ase_obj.cell[0][2], ase_obj.cell[1][0], ase_obj.cell[1][1], ase_obj.cell[1][2], ase_obj.cell[2][0], ase_obj.cell[2][1], ase_obj.cell[2][2]])) # NB beware of length & minus zeros

            for atom in ase_obj:
                struc_repr += "%s %3.6f %3.6f %3.6f " % tuple(map(abs, [chemical_symbols.index(atom.symbol), atom.x, atom.y, atom.z])) # NB beware of length & minus zeros

        if self.info["energy"] is None:
            energy = str(None)
        else:
            energy = str(round(self.info['energy'], 11 - int(math.log10(math.fabs(self.info['energy'])))))

        calc_checksum.update((
            struc_repr + "\n" +
            energy + "\n" +
            self.info['prog'] + "\n" +
            str(self.info['input']) + "\n" +
            str(sum([2**x for x in self.info['calctypes']]))
        ).encode('ascii')) # NB this is fixed and should not be changed

        result = base64.b32encode(calc_checksum.digest()).decode('ascii')
        result = result[:result.index('=')] + 'CI'
        return result

Response: Retrieve unique hash in a cross - platform manner


Instruction:
Here you have a function in Python 3, explain what it does
def refine_cell(self, tilde_obj):
        '''
        NB only used for perovskite_tilting app
        '''
        try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
        except Exception as ex:
            self.error = 'Symmetry finder error: %s' % ex
        else:
            self.refinedcell = Atoms(numbers=numbers, cell=lattice, scaled_positions=positions, pbc=tilde_obj['structures'][-1].get_pbc())
            self.refinedcell.periodicity = sum(self.refinedcell.get_pbc())
            self.refinedcell.dims = abs(det(tilde_obj['structures'][-1].cell))

Response: This method is used to refine the cell of the structure.


Instruction:
How would you explain what the following Python 3 function does
def parse(self):

        if self.data is None:
            raise ValueError('No input data provided, unable to parse')

        for line in self.data:
            parts = line.strip().split()
            try:
                path = parts[0]
                code = parts[1]
                path, line, char = path.split(':')[:3]

                if not re.match(POSITION, line):
                    continue
                if not re.match(POSITION, char):
                    continue
                if not re.match(ERROR_CODE, code):
                    continue
                if not re.match(FILEPATH, path):
                    continue

            # For parts mismatch
            except IndexError:
                continue
            # For unpack mismatch
            except ValueError:
                continue

            yield path, code, line, char, ' '.join(parts[2:])

Response: Reads all lines from the current data source and yields each FileResult objects that are available in the file.


Instruction:
Can you tell what is the following Python 3 function doing
def _get(function, return_format=None):
    if return_format:
        return requests.get(''.join([__BASE_URL, function, return_format])).text
    return requests.get(''.join([__BASE_URL, function, JSON])).json()

Response: Get and return data from the API.


Instruction:
Can you create a Python 3 function that
returns possible backscatter data.

Response:
def backscatter(date=None, rows=None, return_format=None):
    """Returns possible backscatter data.

    This report only includes "syn ack" data and is summarized by source port.

    :param date: optional string (in Y-M-D format) or datetime.date() object
    :param rows: optional number of rows returned (default 1000)
    :returns: list -- backscatter data.
    """
    uri = 'backscatter'
    if date:
        try:
            uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
        except AttributeError:
            uri = '/'.join([uri, date])
        if rows:
            uri = '/'.join([uri, str(rows)])
    return _get(uri, return_format)


Instruction:
Can you tell what is the following Python 3 function doing
def ip(ip_address, return_format=None):
    response = _get('ip/{address}'.format(address=ip_address), return_format)
    if 'bad IP address' in str(response):
        raise Error('Bad IP address, {address}'.format(address=ip_address))
    else:
        return response

Response: Returns a summary of the information our database holds for the given IP address.


Instruction:
Can you generate the documentation for the following Python 3 function
def port(port_number, return_format=None):
    response = _get('port/{number}'.format(number=port_number), return_format)
    if 'bad port number' in str(response):
        raise Error('Bad port number, {number}'.format(number=port_number))
    else:
        return response

Response: Summary information about a particular port.


Instruction:
Can you tell what is the following Python 3 function doing
def topports(sort_by='records', limit=10, date=None, return_format=None):
    uri = '/'.join(['topports', sort_by, str(limit)])
    if date:
        try:
            uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
        except AttributeError:
            uri = '/'.join([uri, date])
    return _get(uri, return_format)

Response: Return a list of top ports for a particular date with return limit.


Instruction:
Create a Python 3 function to
return the port data for a given date range.

Response:
def porthistory(port_number, start_date=None, end_date=None, return_format=None):
    """Returns port data for a range of dates.

    In the return data:

    Records: Total number of records for a given date range.
    Targets: Number of unique destination IP addresses.
    Sources: Number of unique originating IPs.

    :param port_number: a valid port number (required)
    :param start_date: string or datetime.date(), default is 30 days ago
    :param end_date: string or datetime.date(), default is today
    """
    uri = 'porthistory/{port}'.format(port=port_number)

    if not start_date:
        # default 30 days ago
        start_date = datetime.datetime.now() - datetime.timedelta(days=30)

    try:
        uri = '/'.join([uri, start_date.strftime("%Y-%m-%d")])
    except AttributeError:
        uri = '/'.join([uri, start_date])
    if end_date:
        try:
            uri = '/'.join([uri, end_date.strftime("%Y-%m-%d")])
        except AttributeError:
            uri = '/'.join([uri, end_date])
    response = _get(uri, return_format)
    if 'bad port number' in str(response):
        raise Error('Bad port, {port}'.format(port=port_number))
    else:
        return response


Instruction:
Can you tell what is the following Python 3 function doing
def asnum(number, limit=None, return_format=None):
    uri = 'asnum/{number}'.format(number=number)
    if limit:
        uri = '/'.join([uri, str(limit)])
    return _get(uri, return_format)

Response: Returns a summary of the information our database holds for the given ASNUM number.


Instruction:
Can you tell what is the following Python 3 function doing
def dailysummary(start_date=None, end_date=None, return_format=None):
    uri = 'dailysummary'

    if not start_date:
        # default today
        start_date = datetime.datetime.now()

    try:
        uri = '/'.join([uri, start_date.strftime("%Y-%m-%d")])
    except AttributeError:
        uri = '/'.join([uri, start_date])
    if end_date:
        try:
            uri = '/'.join([uri, end_date.strftime("%Y-%m-%d")])
        except AttributeError:
            uri = '/'.join([uri, end_date])
    return _get(uri, return_format)

Response: Returns daily summary of the specified datetimes.


Instruction:
Can you create a Python 3 function that
returns daily summary information of submitted 404 Error Page.

Response:
def daily404summary(date, return_format=None):
    """Returns daily summary information of submitted 404 Error Page
    Information.

    :param date: string or datetime.date() (required)
    """
    uri = 'daily404summary'
    if date:
        try:
            uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
        except AttributeError:
            uri = '/'.join([uri, date])
    return _get(uri, return_format)


Instruction:
Here you have a function in Python 3, explain what it does
def daily404detail(date, limit=None, return_format=None):
    uri = 'daily404detail'
    if date:
        try:
            uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
        except AttributeError:
            uri = '/'.join([uri, date])
        if limit:
            uri = '/'.join([uri, str(limit)])
    return _get(uri, return_format)

Response: Returns detail information of submitted 404 Error Page Information.


Instruction:
Can you generate the documentation for the following Python 3 function
def glossary(term=None, return_format=None):
    uri = 'glossary'
    if term:
        uri = '/'.join([uri, term])
    return _get(uri, return_format)

Response: Get a list of glossary terms and definitions.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _append_path(new_path):  # type: (str) -> None
    for path in sys.path:
        path = os.path.abspath(path)
        if new_path == path:
            return
    sys.path.append(new_path)

Response: Append a path to sys. path.


Instruction:
Given the following Python 3 function, write the documentation
def _caller_path(index):  # type: (int) -> str
    module = None
    stack = inspect.stack()
    while not module:
        if index >= len(stack):
            raise RuntimeError("Cannot find import path")
        frame = stack[index]
        module = inspect.getmodule(frame[0])
        index += 1
    filename = module.__file__
    path = os.path.dirname(os.path.realpath(filename))
    return path

Response: Get the caller s file path by the index of the stack


Instruction:
How would you explain what the following Python 3 function does
def get_current_path(index=2):  # type: (int) -> str
    try:
        path = _caller_path(index)
    except RuntimeError:
        path = os.getcwd()
    return path

Response: Get the caller s path to sys. path


Instruction:
How would you explain what the following Python 3 function does
def get_git_root(index=3):  # type: (int) -> str
    path = get_current_path(index=index)
    while True:
        git_path = os.path.join(path, '.git')
        if os.path.isdir(git_path):
            return path
        if os.path.dirname(path) == path:
            raise RuntimeError("Cannot find git root")
        path = os.path.split(path)[0]

Response:
Returns the path of the git root directory of the caller s file
    Raises a RuntimeError if a git repository cannot be found


Instruction:
Implement a Python 3 function for
getting the caller s parent path to sys. path

Response:
def get_parent_path(index=2):  # type: (int) -> str
    """
    Get the caller's parent path to sys.path
    If the caller is a CLI through stdin, the parent of the current working
    directory is used
    """
    try:
        path = _caller_path(index)
    except RuntimeError:
        path = os.getcwd()
    path = os.path.abspath(os.path.join(path, os.pardir))
    return path


Instruction:
Explain what the following Python 3 code does
def write_rk4(path,name,laser,omega,gamma,r,Lij,states=None,verbose=1):

	global omega_rescaled

	t0=time()
	Ne=len(omega[0])
	Nl=len(laser)

	if states==None: states=range(1,Ne+1)

	#We make some checks
	for i in range(Ne):
		for j in range(Ne):
			b1=not ('.' in str(omega[i][j]) or 'e' in str(omega[i][j]))
			if b1: raise ValueError,'omega must be composed of floating point numbers.'
			b2=not ('.' in str(gamma[i][j]) or 'e' in str(gamma[i][j]))
			if b2: raise ValueError,'gamma must be composed of floating point numbers.'

	#We rescale the frequencies as requested.
	#~ if Omega != None:
		#~ omega_rescaled=[[omega[i][j]/Omega for j in range(Ne)] for i in range(Ne)]
		#~ #gamma=[[gamma[i][j]/Omega for j in range(Ne)] for i in range(Ne)]
	#~ else:
		#~ omega_rescaled=omega[:]
	omega_rescaled=omega[:]

	#We determine wether it is possible to eliminate explicit time-dependance
	theta=find_phase_transformation(Ne,Nl,r,Lij)
	#We find the detunings if required

	#We construct the correspondence i <-> I between degenerate and non-degenerate indices.
	i_d,I_nd,Nnd=calculate_iI_correspondence(omega)
	#We get wich transitions each laser induces
	detunings,detuningsij=laser_detunings(Lij,Nl,i_d,I_nd,Nnd)

	#We get how many transitions each  laser induces
	detuning_indices=[len(detunings[i]) for i in range(Nl)]

	#The number of detunings
	Nd=sum([len(detunings[l]) for l in range(Nl)])
	combinations=detuning_combinations(detuning_indices)

	code0='''program evolution_rk4
	implicit none
	complex*16, dimension('''+str(Ne*(Ne+1)/2-1)+') :: x,k1,k2,k3,k4\n'
	code0+='''    real*8 :: dt,t,ddelta,delta,delta0
	integer :: i,j,n,ldelta,ndelta,detuning_index,n_aprox,n_mod

	logical :: print_steps,run_spectrum\n'''
	code0+='    real*8, dimension('+str(Nl)+') :: E0,detuning_knob\n'
	code0+='    real*8, dimension('+str(Nd)+') :: detuning\n\n'

	code0+="    open(unit=1,file='"+path+name+".dat',status='unknown')\n\n"
	code0+='    n_aprox=1500\n'
	code0+='    !We load the parameters\n'
	code0+="    open(unit=2,file='"+path+name+"_params.dat',status='unknown')\n"
	code0+='''    read(2,*) n
    read(2,*) dt
    read(2,*) print_steps
    read(2,*) x
    read(2,*) E0\n'''

	code0+='    read(2,*) detuning_knob\n'
	code0+='    read(2,*) run_spectrum\n\n'
	code0+='''    if (run_spectrum) then
		read(2,*) ldelta
		read(2,*) ndelta
		read(2,*) ddelta
		close(2)
		delta0=detuning_knob(ldelta)
		n_mod=ndelta/n_aprox
    else
		ldelta=1; ndelta=1; ddelta=0; delta=0
		close(2)
		n_mod=n/n_aprox
    end if
    if (n_mod==0) n_mod=1\n\n\n'''

	#We add the code to caculate all the initial detunings for each laser.
	code0+='	!We calculate the initial detunings.\n'
	#We find the minimal frequency corresponding to each laser.
	omega_min,omega_min_indices=find_omega_min(omega_rescaled,Nl,detuningsij,i_d,I_nd)

	det_index=1
	for l in range(Nl):
		omega0=omega_min[l]
		for p in detuningsij[l]:
			code0+='	detuning('+str(det_index)+')='
			code0+=format_double(omega0-omega_rescaled[p[0]][p[1]])+'+detuning_knob('+str(l+1)+')\n'
			det_index+=1
	code0+='\n'

	code0+='''	t=0
	if (.not. run_spectrum) WRITE(1,*) t,real(x),imag(x('''+str(Ne)+''':))\n'''
	code0+='''	!We start the detuning variation\n'''
	code0+='	delta=detuning_knob(ldelta)\n'
	code0+='''    do j=1,ndelta
		!We run the Runge Kutta method
		t=0.0
		do i=1,n-1\n'''

	code0+='            call f(x          , t       , k1,   E0, detuning, detuning_knob)\n'
	code0+='            call f(x+0.5*k1*dt, t+dt*0.5, k2,   E0, detuning, detuning_knob)\n'
	code0+='            call f(x+0.5*k2*dt, t+dt*0.5, k3,   E0, detuning, detuning_knob)\n'
	code0+='            call f(x    +k3*dt, t+dt    , k4,   E0, detuning, detuning_knob)\n'

	code0+='''			x= x+(k1+2*k2+2*k3+k4)*dt/6
			if (print_steps.and. .not. run_spectrum) print*,'t=',t,'delta=',delta
			t= t+ dt

			if (isnan(real(x(1)))) stop 1
			if (.not. run_spectrum .and. mod(i,n_mod)==0) WRITE(1,*) t,real(x),imag(x('''+str(Ne)+''':))
		end do
		if (print_steps) print*, 'delta=',delta,'percentage=',100*(delta-delta0)/(ddelta*ndelta)

		!We recalculate the detunings
		if (run_spectrum) then
			if (mod(j,n_mod)==0) WRITE(1,*) delta,real(x),imag(x('''+str(Ne)+''':))
			delta=delta+ddelta
			detuning_knob(ldelta)=detuning_knob(ldelta)+ddelta\n'''

	#We add the code to caculate all detunings for each laser
	#This way of assigining a global index ll to the detunings ammounts to
	#   ll=   number_of_previous_detunings
	#       + number_of_detuning_ordered_by_row_and_from_left_to_right_column
	#like this
	#->
	#-> ->
	#-> -> ->
	#for each l

	#We find the minimal frequency corresponding to each laser
	omega_min,omega_min_indices=find_omega_min(omega_rescaled,Nl,detuningsij,i_d,I_nd)

	det_index=1
	for l in range(Nl):
		omega0=omega_min[l]
		code0+='			if (ldelta=='+str(l+1)+') then\n'
		for p in detuningsij[l]:
			code0+='				detuning('+str(det_index)+')=detuning('+str(det_index)+')'
			#code0+='+('+str(omega0-omega_rescaled[p[0]][p[1]])+'+ddelta\n'
			code0+='+ddelta\n'
			det_index+=1
		code0+='			end if\n'

	code0+='''		end if

	end do

    close(1)

end program\n\n'''

	code0+='subroutine f(x,t,y,    E0, detuning,detuning_knob)\n'

	code0+='''    implicit none
    real*8, intent(in) :: t\n'''
	code0+='    complex*16, dimension('+str(Ne*(Ne+1)/2-1)+'), intent(in)  :: x\n'
	code0+='    complex*16, dimension('+str(Ne*(Ne+1)/2-1)+'), intent(out) :: y\n'
	code0+='    real*8, dimension('+str(Nl)+'), intent(in) :: E0,detuning_knob\n'
	code0+='    real*8, dimension('+str(Nd)+'), intent(in) :: detuning\n\n'

	code0+='    complex*16 :: I,fact,aux\n'
	code0+='    real*8 :: rho11\n\n'
	code0+='    I=(0,1D0)\n'

	#We establish the scaling of the equations
	#~ if Omega==None:
		#~ h  =1.054571726e-34; e=1.602176565e-19
		#~ code0+='    fact=I*'+str(e/h)+'\n'
	#~ else:
		#~ #code0+='    fact=I*'+str(float(Omega/sqrt(2)))+'\n'
		#~ code0+='    fact=I*'+str(float(1/sqrt(2)))+'\n'
		#~ #code0+='    fact=I*'+str(float(1/(sqrt(2)*Omega)))+'\n'
	code0+='    fact=I*'+format_double(float(1/sqrt(2)))+'\n'

	#We give the code to calculate rho11
	code0+='    rho11=1\n'
	for i in range(1,Ne):
		code0+='    rho11=rho11 -x('+str(i)+')\n'
	code0+='\n\n'

	####################################################################
	#We produce the code for the first order equations.
	####################################################################
	if len(theta)>0:
		code=''
		for mu in range(1,Ne*(Ne+1)/2):
			i,j,s=IJ(mu,Ne)
			#print 'ecuacion mu=',mu,',i,j=',i,j
			eqmu='    y('+str(mu)+')= 0\n'

			####################################################################
			#We add the terms associated with the effective hamiltonian
			#other than those associated with the phase transformation.

			for k in range(1,Ne+1):
				#Case 1
				if k>=j:
					for l in Lij[i-1][k-1]:
						if k>i:
							#print 'E0^',l,-1,'r',i,k,'rho',k,j,'case 1.1'
							eqmu+=add_line(Ne,mu,'+',laser,l,-1,  r,i,k,  k,j)
						elif k<i:
							#print 'E0^',l, 1,'r',i,k,'rho',k,j,'case 1.2'
							eqmu+=add_line(Ne,mu,'+',laser,l, 1,  r,i,k,  k,j)

				#Case 2
				elif k<j:
					for l in Lij[i-1][k-1]:
						if k>i:
							#print 'E0^',l,-1,'r',i,k,'rhoa',j,k,'case 2.1'
							eqmu+=add_line(Ne,mu,'+',laser,l,-1,  r,i,k,  j,k,True)
						elif k<i:
							#print 'E0^',l, 1,'r',i,k,'rhoa',j,k,'case 2.2'
							eqmu+=add_line(Ne,mu,'+',laser,l, 1,  r,i,k,  j,k,True)
				#Case 3
				if k<=i:
					for l in Lij[k-1][j-1]:
						if k<j:
							#print 'E0^',l,-1,'r',k,j,'rho',i,k,'case 3.1'
							eqmu+=add_line(Ne,mu,'-',laser,l,-1,  r,k,j,  i,k)
						elif k>j:
							#print 'E0^',l, 1,'r',k,j,'rho',i,k,'case 3.2'
							eqmu+=add_line(Ne,mu,'-',laser,l, 1,  r,k,j,  i,k)
				#Case 4
				elif k>i:
					for l in Lij[k-1][j-1]:
						if k<j:
							#print 'E0^',l,-1,'r',k,j,'rhoa',k,i,'case 4.1'
							eqmu+=add_line(Ne,mu,'-',laser,l,-1,  r,k,j,  k,i,True)
						elif k>j:
							#print 'E0^',l, 1,'r',k,j,'rhoa',k,i,'case 4.2'
							eqmu+=add_line(Ne,mu,'-',laser,l, 1,  r,k,j,  k,i,True)

			eqmu+='    y('+str(mu)+')=y('+str(mu)+')*fact\n'

			####################################################################
			#We add the terms associated with the phase transformation.

			extra=Theta(i,j,theta,omega_rescaled,omega_min,detunings,detuningsij,
						combinations,detuning_indices,Lij,i_d,I_nd,Nnd,
						verbose=verbose,states=states)

			if extra!='':
				eqmu+='    y('+str(mu)+')=y('+str(mu)+') + I*('+extra+')*x('+str(mu)+')\n'

			####################################################################

			#~ if i==j:
				#~ for k in range(1,Ne+1):
					#~ if k < i:
						#~ muii=Mu(i,i,s=1,N=Ne)
						#~ eqmu+='    y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][k-1])+')*x('+str(muii)+')\n'
					#~ elif k > i:
						#~ mukk=Mu(k,k,s=1,N=Ne)
						#~ eqmu+='    y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][k-1])+')*x('+str(mukk)+')\n'
				#~ eqmu+='\n'
			#~ else:
				#~ eqmu+='    y('+str(mu)+')= y('+str(mu)+') - ('+format_double(gamma[i-1][j-1]/2)+')*x('+str(mu)+')\n'
#~

			####################################################################
			code+=eqmu+'\n'

		#We add the terms associated with spontaneous decay.
		#First for populations.
		for i in range(2,Ne+1):
			mu=Mu(i,i,1,Ne)
			for k in range(1,Ne+1):
				gams=0
				if k<i:
					gams+=gamma[i-1][k-1]
				elif k>i:
					nu=Mu(k,k,1,Ne)
					ga=gamma[i-1][k-1]
					if ga != 0:
						code+='    y('+str(mu)+')=y('+str(mu)+')'
						code+='-('+format_double(ga)+')*x('+str(nu)+')\n'
				if gams!=0:
					code+='    y('+str(mu)+')=y('+str(mu)+')'
					code+='-('+format_double(gams)+')*x('+str(mu)+')\n'

		#And now for coherences
		for i in range(1,Ne+1):
			for j in range(1,i):
				gams=gamma[i-1][j-1]/2
				if gams!=0:
					for a in range(i+1,Ne+1):
						mu=Mu(a,i,+1,Ne)
						code+='    y('+str(mu)+')=y('+str(mu)+')'
						code+='-('+format_double(gams)+')*x('+str(mu)+')\n'

						#~ mu=Mu(a,i,-1,Ne)
						#~ code+='    y('+str(mu)+')=y('+str(mu)+')'
						#~ code+='-('+format_double(gams)+')*x('+str(mu)+')\n'

					for b in range(1,i):
						mu=Mu(i,b,+1,Ne)
						code+='    y('+str(mu)+')=y('+str(mu)+')'
						code+='-('+format_double(gams)+')*x('+str(mu)+')\n'

						#~ mu=Mu(i,b,-1,Ne)
						#~ code+='    y('+str(mu)+')=y('+str(mu)+')'
						#~ code+='-('+format_double(gams)+')*x('+str(mu)+')\n'

		####################################################################
		####################################################################
		####################################################################
		#code+='    y=y/'+str(Omega)+'\n'

		f=file(path+name+'.f90','w')
		code=code0+code+'end subroutine\n'
		f.write(code)
		f.close()

		return time()-t0
	else:
		print 'There was no phase transformation capable of eliminating explicit time dependance.'

Response: This function writes the Fortran code needed to calculate the time evolution of the density matrix elements.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def run_rk4(path,name,E0,laser_frequencies,  N_iter,dt,N_states,
				spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None,
				rho0=None,print_steps=False,integrate=False,
				save_systems=False):
	"""This function runs the Runge-Kutta method compiled in path+name..."""

	t0=time()
	params =str(N_iter)+'\n'
	params+=str(dt)+'\n'
	#We give the flag on wether to print each time step.
	if print_steps:
		params+='.true.\n'
	else:
		params+='.false.\n'

	#We give the initial value of rho
	N_vars=N_states*(N_states+1)/2-1
	if rho0==None:
		params+=''.join(['(0.0,0.0) ' for i in range(N_vars)])
	elif len(rho0)==N_states-1:
		if sage_included:
			params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])
		else:
			params+=''.join(['('+str(i.real)+','+str(i.imag)+') ' for i in rho0])
		params+=''.join(['(0.0,0.0) ' for i in range(N_vars-N_states+1)])
	elif len(rho0)==N_vars:
		params+=''.join(['('+str(real(i))+','+str(imag(i))+') ' for i in rho0])

	params+='\n'
	#We give the amplitude of the electrical fields.
	params+=''.join([str(i)+' ' for i in E0])+'\n'

	#We give the detuning of each laser (taken from the lowest frequency transition).
	params+=''.join([str(i)+' ' for i in laser_frequencies])+'\n'

	#We give the flag on wether to calculate spectrums or time evolution.
	if spectrum_of_laser==None:
		params+='.false.'
	else:
		if frequency_end !=None:
			if frequency_step !=None:
				raise ValueError,'both frequency_end and frequency_step were specified.'
			if N_delta==1:
				frequency_step=0.0
			else:
				frequency_step=(frequency_end-laser_frequencies[spectrum_of_laser-1])/(N_delta-1)

		#frequency_step=frequency_end
		params+='.true.\n'
		params+=str(spectrum_of_laser)+'\n'
		params+=str(N_delta)+'\n'
		params+=str(frequency_step)
	#print params

	f=file(path+name+'_params.dat','w')
	f.write(params)
	f.close()

	os.system(path+name)

	return time()-t0

Response: This function runs the Runge - Kutta method compiled in path + name...


Instruction:
Can you generate a brief explanation for the following Python 3 code
def send_email(self, send_to, attachment_paths=None, fail_silently=True, *args, **kwargs):
        msg = self.get_message_object(send_to, attachment_paths, *args, **kwargs)
        msg.content_subtype = self.content_subtype

        try:
            self.sent = msg.send()
        except SMTPException, e:
            if not fail_silently:
                raise
            logger.error(u'Problem sending email to %s: %s', send_to, e)

        return self.sent

Response: Sends an email to the recipient based on the parameters passed to the constructor.


Instruction:
Write a Python 3 script for
returning element. tag with xmlns stripped away.

Response:
def _tag(element):
    """Return element.tag with xmlns stripped away."""
    tag = element.tag
    if tag[0] == "{":
        uri, tag = tag[1:].split("}")
    return tag


Instruction:
Can you create a Python 3 function that
returns xmlns prefix of the given element.

Response:
def _uriPrefix(element):
    """Return xmlns prefix of the given element."""
    i = element.tag.find('}')
    if i < 0:
        return ""
    return element.tag[:i+1]


Instruction:
How would you code a function in Python 3 to
read the required and optional elements and returns the remaining elements.

Response:
def _parseElements(self, elementTree, expectedTag = None):
    """Read REQUIRED_ELEMENTS and OPTIONAL_ELEMENTS and returns
    the rest of the children.  Every read child element's text
    value will be filled into an attribute of the same name,
    i.e. <description>Test</description> will lead to 'Test' being
    assigned to self.description.  Missing REQUIRED_ELEMENTS
    result in warnings."""

    xmlns = _uriPrefix(elementTree)

    if expectedTag is not None:
        assert _tag(elementTree) == expectedTag, 'expected <%s>, got <%s>' % (expectedTag, _tag(elementTree))

    parsed = []

    for tagName in self.REQUIRED_ELEMENTS + self.OPTIONAL_ELEMENTS:
        tags = elementTree.findall(xmlns + tagName)
        if tags:
            parsed.extend(tags)
            tagValue = tags[0].text
            tagValue = tagValue.strip() if tagValue else ""
            if len(tags) > 1:
                logger.warning("More than one <%s> found within %r (using only first)" % (tagName, _tag(elementTree)))
        else:
            tagValue = None
            if tagName in self.REQUIRED_ELEMENTS:
                logger.warning("Required element %r not found within %r" % (tagName, _tag(elementTree)))
        setattr(self, _tagToIdentifier(tagName), tagValue)

    return [tag for tag in elementTree if tag not in parsed]


Instruction:
Given the following Python 3 function, write the documentation
def classifyParameters(self):

        arguments = []
        options = []
        outputs = []
        for parameter in self.parameters():
            if parameter.channel == 'output' and not parameter.isExternalType():
                outputs.append(parameter)
            elif parameter.index is not None:
                arguments.append(parameter)
                if parameter.flag is not None or parameter.longflag is not None:
                    logger.warning("Parameter '%s' has both index=%d and flag set." % (
                        parameter.identifier(), parameter.index))
            elif parameter.flag or parameter.longflag:
                options.append(parameter)
            else:
                logger.warning("Parameter '%s' cannot be passed (missing flag, longflag, or index)!" % parameter.name)
        arguments.sort(key = lambda parameter: parameter.index)
        return (arguments, options, outputs)

Response: Return the arguments options and outputs tuples.


Instruction:
Explain what the following Python 3 code does
def parseValue(self, value):
        if self.isVector():
            return list(map(self._pythonType, value.split(',')))
        if self.typ == 'boolean':
            return _parseBool(value)
        return self._pythonType(value)

Response: Parse the given value and return result.


Instruction:
Here you have a function in Python 3, explain what it does
def defaultExtension(self):
        result = self.EXTERNAL_TYPES[self.typ]
        if not self.fileExtensions:
            return result
        if result in self.fileExtensions:
            return result
        return self.fileExtensions[0]

Response:
Return the default extension for this parameter type checked
        against supported fileExtensions. If the default extension is not within supported fileExtensions return the first supported
        extension.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def encode(self, X, seed=None):

        if not X:
            return ''

        if not isinstance(X, str):
            raise InvalidInputException('Input must be of type string.')

        if seed is not None and len(seed) != 8:
            raise InvalidSeedLength('The seed is not 8 bytes long, seed length: '+str(len(seed)))

        ciphertext = self._encrypter.encrypt(X)

        maximumBytesToRank = int(math.floor(self.getCapacity() / 8.0))
        unrank_payload_len = (
            maximumBytesToRank - DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT)
        unrank_payload_len = min(len(ciphertext), unrank_payload_len)

        if unrank_payload_len <= 0:
            raise InsufficientCapacityException('Language doesn\'t have enough capacity')

        msg_len_header = fte.bit_ops.long_to_bytes(unrank_payload_len)
        msg_len_header = string.rjust(
            msg_len_header, DfaEncoderObject._COVERTEXT_HEADER_LEN_PLAINTEXT, '\x00')
        random_bytes = seed if seed is not None else fte.bit_ops.random_bytes(8)
        msg_len_header = random_bytes + msg_len_header
        msg_len_header = self._encrypter.encryptOneBlock(msg_len_header)

        unrank_payload = msg_len_header + \
            ciphertext[:maximumBytesToRank -
                DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT]

        random_padding_bytes = maximumBytesToRank - len(unrank_payload)
        if random_padding_bytes > 0:
            unrank_payload += fte.bit_ops.random_bytes(random_padding_bytes)

        unrank_payload = fte.bit_ops.bytes_to_long(unrank_payload)

        formatted_covertext_header = self._dfa.unrank(unrank_payload)
        unformatted_covertext_body = ciphertext[
            maximumBytesToRank - DfaEncoderObject._COVERTEXT_HEADER_LEN_CIPHERTTEXT:]

        covertext = formatted_covertext_header + unformatted_covertext_body

        return covertext

Response: Given a string X returns a string of unranked version of X.