output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
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 :r...
Implement a function in Python 3 to identify a merge compatible method available in self.
You are a Python code analyst, evaluating scripts for potential improvements.
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
Implement a Python 3 function for converting a TweetStatus object to a Tweet object.
As a python code expert, you are capable of creating scripts from specifications.
Wrap the cell in a tree of objects.
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...
As a Python code analyst, you investigate and solve complex coding mysteries
Get the amount of memory and swap Mebibytes
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:"): ...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the cpu info from the node
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")...
As a Python code analyst, you investigate and solve complex coding mysteries
Get data about the graphics card.
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].st...
As a python code expert, you are capable of creating scripts from specifications.
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-...
How would you implement a function in Python 3 that gets the serial number. Requires root access
As a Python code composer, you craft elegant and concise scripts.
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 =...
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.
As a Python code composer, you craft elegant and concise scripts.
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...
Can you create a Python 3 function that gets total disk size in GB.
You are a Python code generator, capable of creating scripts from specifications.
Get the IP address used for public connections.
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
You are a Python code architect, reviewing and designing scalable and efficient code
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}
Create a Python 3 function to get the MAC address of a specific IP
You are a Python code analyst, evaluating scripts for potential improvements.
Get all the hw info.
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()) i...
As a Python code translator, you convert algorithms and pseudocode into Python.
Print the header for the CSV table.
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))
You are a Python code analyst, evaluating scripts for potential improvements.
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)
Can you create a Python 3 function that prints as a table.
As a python code expert, you are capable of creating scripts from specifications.
Run in agent mode.
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.clien...
You are a Python code architect, reviewing and designing scalable and efficient code
Calculate the matrix of transition frequencies.
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
You are a Python code analyst, evaluating scripts for potential improvements.
r This function calculates the boundary indices within a list of magnetic states.
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. ...
You are a Python code architect, reviewing and designing scalable and efficient code
Exclude states from matrices.
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_o...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function calculates the reduced matrix elements <N L J > given a list of fine states.
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 ...
As a Python code composer, you craft elegant and concise scripts.
r This function calculates the average speed of an atom in a vapour assuming a Maxwell - Boltzmann velocity distribution.
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)
You are a Python code analyst, evaluating scripts for potential improvements.
r Find all possible decays from a given fine state.
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_belo...
You are a Python code analyst, evaluating scripts for potential improvements.
The LaTeX routine for states.
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)+'...
You are a Python code architect, reviewing and designing scalable and efficient code
The LaTeX representation routine for transitions.
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: ...
As a Python code analyst, you investigate and solve complex coding mysteries
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 iLef...
Write a Python 3 script for finding the lower index of the segment that contains the value x
As a Python code translator, you convert algorithms and pseudocode into Python.
ur This function calculates the matrix elements of the electric dipole in the helicity tree.
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...
As a Python code composer, you craft elegant and concise scripts.
r Return the Doppler width of a transition at a given temperature.
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)
As a Python code composer, you craft elegant and concise scripts.
r Find all allowed transitions in the atom.
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 = state...
You are a Python code architect, reviewing and designing scalable and efficient code
Read ImageJ s ROI format.
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/develope...
You are a Python code analyst, evaluating scripts for potential improvements.
r Calculate the allowed total angular momenta.
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)]
As a python code expert, you are capable of creating scripts from specifications.
ur Returns the angular momentum matrix for a \ given a J angular momentum.
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*Kroneck...
You are a Python code architect, reviewing and designing scalable and efficient code
Return a matrix representation of the spherical tensor with quantum numbers J_i J_j K Q.
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)])....
You are a Python code analyst, evaluating scripts for potential improvements.
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) ...
Create a Python 3 function for returning the small Wigner d matrix for angular momentum J.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the Wigner D matrix for angular momentum J.
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)
You are a Python code generator, capable of creating scripts from specifications.
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) # | ...
Can you write a function in Python 3 where it generates coordinates for a tiling of unit squares.
As a Python code composer, you craft elegant and concise scripts.
Generate coordinates for a tiling of unit triangles.
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...
You are a Python code analyst, evaluating scripts for potential improvements.
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.')
Can you write a function in Python 3 where it restores settings to default values.
As a Python code analyst, you investigate and solve complex coding mysteries
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 = ...
Write a Python 3 script to load config file into default settings
You are a Python code architect, reviewing and designing scalable and efficient code
Shortcut function for EmailFromTemplate class.
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)
As a python code expert, you are capable of creating scripts from specifications.
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(l...
Can you implement a function in Python 3 that sets the logging level of the current log entry.
As a Python code composer, you craft elegant and concise scripts.
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: ...
Write a Python 3 function for loading the configfile and return a dict of the class
As a Python code translator, you convert algorithms and pseudocode into Python.
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: ...
Implement a Python 3 function for parsing a string to remove and replace all wiki markup tags
You are a Python code analyst, evaluating scripts for potential improvements.
Parse a string object to de - wikified text
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...
You are a Python code analyst, evaluating scripts for potential improvements.
This function runs the Runge - Kutta method compiled in path + name...
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,...
You are a Python code analyst, evaluating scripts for potential improvements.
This function returns the oscillation periods and shortest and half lives of a characteristic.
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 l...
You are a Python code generator, capable of creating scripts from specifications.
Retrieve unique hash in a cross - platform manner
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: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
This method is used to refine the cell of the structure.
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) ...
As a python code expert, you are capable of creating scripts from specifications.
Reads all lines from the current data source and yields each FileResult objects that are available in the file.
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] ...
You are a Python code analyst, evaluating scripts for potential improvements.
Get and return data from the API.
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()
You are a Python code generator, capable of creating scripts from specifications.
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 10...
Can you create a Python 3 function that returns possible backscatter data.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a summary of the information our database holds for the given IP address.
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 ...
You are a Python code generator, capable of creating scripts from specifications.
Summary information about a particular port.
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...
As a python code expert, you are capable of creating scripts from specifications.
Return a list of top ports for a particular date with return limit.
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...
As a python code expert, you are capable of creating scripts from specifications.
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. ...
Create a Python 3 function to return the port data for a given date range.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a summary of the information our database holds for the given ASNUM number.
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)
You are a Python code architect, reviewing and designing scalable and efficient code
Returns daily summary of the specified datetimes.
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")]) ...
You are a Python code architect, reviewing and designing scalable and efficient code
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")]) e...
Can you create a Python 3 function that returns daily summary information of submitted 404 Error Page.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns detail information of submitted 404 Error Page Information.
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: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Get a list of glossary terms and definitions.
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)
You are a Python code analyst, evaluating scripts for potential improvements.
Append a path to sys. path.
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)
As a python code expert, you are capable of creating scripts from specifications.
Get the caller s file path by the index of the stack
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 = inspec...
As a python code expert, you are capable of creating scripts from specifications.
Get the caller s path to sys. path
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
As a python code expert, you are capable of creating scripts from specifications.
Returns the path of the git root directory of the caller s file Raises a RuntimeError if a git repository cannot be found
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: ...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Implement a Python 3 function for getting the caller s parent path to sys. path
As a Python code translator, you convert algorithms and pseudocode into Python.
This function writes the Fortran code needed to calculate the time evolution of the density matrix elements.
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(omeg...
You are a Python code generator, capable of creating scripts from specifications.
This function runs the Runge - Kutta method compiled in path + name...
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...
As a Python code translator, you convert algorithms and pseudocode into Python.
Sends an email to the recipient based on the parameters passed to the constructor.
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: s...
As a Python code composer, you craft elegant and concise scripts.
def _tag(element): """Return element.tag with xmlns stripped away.""" tag = element.tag if tag[0] == "{": uri, tag = tag[1:].split("}") return tag
Write a Python 3 script for returning element. tag with xmlns stripped away.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _uriPrefix(element): """Return xmlns prefix of the given element.""" i = element.tag.find('}') if i < 0: return "" return element.tag[:i+1]
Can you create a Python 3 function that returns xmlns prefix of the given element.
You are a Python code generator, capable of creating scripts from specifications.
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 as...
How would you code a function in Python 3 to read the required and optional elements and returns the remaining elements.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the arguments options and outputs tuples.
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(param...
You are a Python code architect, reviewing and designing scalable and efficient code
Parse the given value and return result.
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)
As a python code expert, you are capable of creating scripts from specifications.
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.
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]
You are a Python code architect, reviewing and designing scalable and efficient code
Given a string X returns a string of unranked version of X.
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 In...
As a Python code analyst, you investigate and solve complex coding mysteries
Given an input string X returns an unranked version of X.
Here you have a function in Python 3, explain what it does def decode(self, covertext): if not isinstance(covertext, str): raise InvalidInputException('Input must be of type string.') insufficient = (len(covertext) < self._fixed_slice) if insufficient: raise DecodeFailu...
As a Python code composer, you craft elegant and concise scripts.
r Define a nice symbol with matrix indices.
How would you explain what the following Python 3 function does def define_symbol(name, open_brace, comma, i, j, close_brace, variables, **kwds): r"""Define a nice symbol with matrix indices. >>> name = "rho" >>> from sympy import symbols >>> t, x, y, z = symbols("t, x, y, z", positiv...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function returns a unitary vector describing the polarization of a single - plane wave.
Make a summary of the following Python 3 code def polarization_vector(phi, theta, alpha, beta, p, numeric=False, abstract=False): """This function returns a unitary vector describing the polarization of plane waves.: INPUT: - ``phi`` - The spherical coordinates azimuthal angle...
As a Python code translator, you convert algorithms and pseudocode into Python.
r This function takes a cartesian basis and converts it to the helicity basis.
Here you have a function in Python 3, explain what it does def cartesian_to_helicity(vector, numeric=False): if numeric: vector = list(vector) vector[0] = nparray(vector[0]) vector[1] = nparray(vector[1]) vector[2] = nparray(vector[2]) v = [(vector[0]-1j*vector[1])/npsqrt(2)...
As a Python code composer, you craft elegant and concise scripts.
r Extract an matrix element of a vector operator.
Given the following Python 3 function, write the documentation def vector_element(r, i, j): return Matrix([r[p][i, j] for p in range(3)])
You are a Python code generator, capable of creating scripts from specifications.
This function returns the outer product of a canonical basis of an \ Ne - dimensional Hilbert space.
Can you generate a brief explanation for the following Python 3 code def ketbra(i, j, Ne): return ket(i, Ne)*bra(j, Ne)
You are a Python code analyst, evaluating scripts for potential improvements.
r This function returns the action of a Lindblad operator A on a density matrix rho.
Can you generate a brief explanation for the following Python 3 code def lindblad_operator(A, rho): a, b = sigma_operator_indices(A) # print(111, a, b) if a is not None and b is not None: Ne = A.shape[0] L = zeros(Ne, Ne) L[a, a] += rho[b, b] for j in range(Ne): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def lindblad_terms(gamma, rho, Ne, verbose=1): u"""Return the Lindblad terms for decays gamma in matrix form. >>> from sympy import pprint >>> aux = define_frequencies(4, explicitly_antisymmetric=True) >>> omega_level, omega, gamma = aux >>> gamma = gamma.subs({gamma[2, 0]:0, gamma[3, 0]:0, gamma[3...
Write a Python 3 script for returning the Lindblad terms for decays gamma in matrix form.
You are a Python code analyst, evaluating scripts for potential improvements.
r Return a phase transformation to eliminate explicit time dependence.
Can you tell what is the following Python 3 function doing def phase_transformation(Ne, Nl, r, Lij, omega_laser, phase): ph = find_phase_transformation(Ne, Nl, r, Lij) return {phase[i]: sum([ph[i][j]*omega_laser[j] for j in range(Nl)]) for i in range(Ne)}
You are a Python code architect, reviewing and designing scalable and efficient code
r Return symbolic Hamiltonian.
Explain what the following Python 3 code does def hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level, omega_laser, xi, RWA=True, RF=True): r"""Return symbolic Hamiltonian. >>> from sympy import zeros, pi, pprint, symbols >>> Ne = 3 >>> Nl = 2 >>> Ep, omega_laser = define_laser...
As a Python code translator, you convert algorithms and pseudocode into Python.
r Cross product of two 3d vectors.
How would you explain what the following Python 3 function does def cross(a, b): if isinstance(a, Mul): a = a.expand() avect = 1 aivect = -1 for ai, fact in enumerate(a.args): if isinstance(fact, Vector3D): avect = fact aivect = ai ...
As a Python code analyst, you investigate and solve complex coding mysteries
Saves user s settings to a file in the user s data directory.
Can you generate a brief explanation for the following Python 3 code def write_settings(settings): ''' Saves user's settings @returns True on success @returns False on failure ''' if not os.access(DATA_DIR, os.W_OK): return False try: f = open(DATA_DIR + os.sep + SETTINGS_FILE, 'w') ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Determine if a field is constant by group in df
Can you generate the documentation for the following Python 3 function def is_field_unique_by_group(df, field_col, group_col): ''' Determine if field is constant by group in df ''' def num_unique(x): return len(pd.unique(x)) num_distinct = df.groupby(group_col)[field_col].agg(num_unique) ret...
As a Python code composer, you craft elegant and concise scripts.
List files in a directory of stan
How would you explain what the following Python 3 function does def _list_files_in_path(path, pattern="*.stan"): results = [] for dirname, subdirs, files in os.walk(path): for name in files: if fnmatch(name, pattern): results.append(os.path.join(dirname, name)) return(re...
As a Python code analyst, you investigate and solve complex coding mysteries
Generates a random valid perovskite structure in ASE format.
Can you tell what is the following Python 3 function doing def generate_random_perovskite(lat=None): ''' This generates a random valid perovskite structure in ASE format. Useful for testing. Binary and organic perovskites are not considered. ''' if not lat: lat = round(random.uniform(3.5...
As a python code expert, you are capable of creating scripts from specifications.
def check_positive_integer(name, value): """Check a value is a positive integer. Returns the value if so, raises ValueError otherwise. """ try: value = int(value) is_positive = (value > 0) except ValueError: raise ValueError('%s should be an integer; got %r' % (name, value)...
Can you write a function in Python 3 where it checks a value is a positive integer. Returns the value if so raises ValueError otherwise.
As a Python code composer, you craft elegant and concise scripts.
def check_color_input(value): """Check a value is a valid colour input. Returns a parsed `RGBColor` instance if so, raises ValueError otherwise. """ value = value.lower() # Trim a leading hash if value.startswith('#'): value = value[1:] if len(value) != 6: raise ValueE...
Can you write a function in Python 3 where it checks a value is a valid colour input.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_octahedra(self, atoms, periodicity=3): ''' Extract octahedra as lists of sequence numbers of corner atoms ''' octahedra = [] for n, i in enumerate(atoms): found = [] if i.symbol in Perovskite_Structure.B: for m, j in enumerate(self....
Can you create a Python 3 function that extracts octahedra as lists of sequence numbers of corner atoms.
You are a Python code analyst, evaluating scripts for potential improvements.
Extract the main tilting plane based on Z coordinate
Here you have a function in Python 3, explain what it does def get_tiltplane(self, sequence): ''' Extract the main tilting plane basing on Z coordinate ''' sequence = sorted(sequence, key=lambda x: self.virtual_atoms[ x ].z) in_plane = [] for i in range(0, len(sequence)-4...
You are a Python code architect, reviewing and designing scalable and efficient code
Extract tilting planes based on distance map
Given the following Python 3 function, write the documentation def get_tiltplanes(self, sequence): ''' Extract tilting planes basing on distance map ''' tilting_planes = [] distance_map = [] for i in range(1, len(sequence)): distance_map.append([ sequence[i],...
You are a Python code generator, capable of creating scripts from specifications.
def get_help_keys(self): """ Returns dict of help_context keys (description texts used in `EmailRegistry.register()` method). """ help_keys = {} for k, v in self.help_context.items(): if isinstance(v, tuple): help_keys[k] = v[0] else: ...
Write a Python 3 script for returning dict of help_context keys.
As a Python code composer, you craft elegant and concise scripts.
Returns dict of help_context values.
Can you generate a brief explanation for the following Python 3 code def get_help_values(self): help_values = {} for k, v in self.help_context.items(): if isinstance(v, tuple) and len(v) == 2: help_values[k] = v[1] else: help_values[k] = u"<%s>" % ...
As a python code expert, you are capable of creating scripts from specifications.
def register(self, path, help_text=None, help_context=None): """ Registers email template. Example usage: email_templates.register('hello_template.html', help_text=u'Hello template', help_context={'username': u'Name of user in hello expression'}) :param path...
Write a Python 3 script to register an email template file path.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_registration(self, path): """ Returns registration item for specified path. If an email template is not registered, this will raise NotRegistered. """ if not self.is_registered(path): raise NotRegistered("Email template not registered") return self._r...
How would you code a function in Python 3 to return the registration item for the specified path.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the form help text for creating email templates.
Can you generate the documentation for the following Python 3 function def get_form_help_text(self, path): try: form_help_text = self.get_registration(path).as_form_help_text() except NotRegistered: form_help_text = u"" return form_help_text
You are a Python code architect, reviewing and designing scalable and efficient code
def analyze(self, output_file=None): """ Analyzes the parsed results from Flake8 or PEP 8 output and creates FileResult instances :param output_file: If specified, output will be written to this file instead of stdout. """ fr = None for path, code, line, char, desc in se...
How would you code a function in Python 3 to analyze the parsed results from Flake8 or PEP 8 output and creates HTML file result instances.
You are a Python code generator, capable of creating scripts from specifications.
Generates an HTML file based on the data from the Parser object and Jinja2 templates.
Can you tell what is the following Python 3 function doing def generate(self, output_file=None): fd = output_file # Write to stdout if we do not have a file to write to if not fd: fd = stdout else: try: fd = open(output_file, 'w') exc...
You are a Python code generator, capable of creating scripts from specifications.