output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Return True if s is a LDAP DN.
Explain what the following Python 3 code does def is_dn(s): if s == '': return True rm = DN_REGEX.match(s) return rm is not None and rm.group(0) == s
You are a Python code analyst, evaluating scripts for potential improvements.
def _fold_line(self, line): """Write string line as one or more folded lines.""" if len(line) <= self._cols: self._output_file.write(line) self._output_file.write(self._line_sep) else: pos = self._cols self._output_file.write(line[0:self._cols]) ...
Implement a Python 3 function for writing string line as one or more folded lines.
You are a Python code architect, reviewing and designing scalable and efficient code
Return True if attr_value has to be base - 64 encoded.
Here you have a function in Python 3, explain what it does def _needs_base64_encoding(self, attr_type, attr_value): return attr_type.lower() in self._base64_attrs or \ isinstance(attr_value, bytes) or \ UNSAFE_STRING_RE.search(attr_value) is not None
As a Python code composer, you craft elegant and concise scripts.
def _unparse_attr(self, attr_type, attr_value): """Write a single attribute type/value pair.""" if self._needs_base64_encoding(attr_type, attr_value): if not isinstance(attr_value, bytes): attr_value = attr_value.encode(self._encoding) encoded = base64.encodestrin...
Can you write a function in Python 3 where it writes a single attribute type / value pair.
You are a Python code architect, reviewing and designing scalable and efficient code
Unparse a record from the database.
Given the following Python 3 function, write the documentation def _unparse_entry_record(self, entry): for attr_type in sorted(entry.keys()): for attr_value in entry[attr_type]: self._unparse_attr(attr_type, attr_value)
As a Python code analyst, you investigate and solve complex coding mysteries
Detect and write the changetype.
How would you explain what the following Python 3 function does def _unparse_changetype(self, mod_len): if mod_len == 2: changetype = 'add' elif mod_len == 3: changetype = 'modify' else: raise ValueError("modlist item of wrong length") self._unparse_a...
You are a Python code generator, capable of creating scripts from specifications.
def unparse(self, dn, record): """Write an entry or change record to the output file. :type dn: string :param dn: distinguished name :type record: Union[Dict[string, List[string]], List[Tuple]] :param record: Either a dictionary holding an entry or a list of additi...
Can you write a function in Python 3 where it writes an entry or change record to the output file.
You are a Python code generator, capable of creating scripts from specifications.
def _strip_line_sep(self, s): """Strip trailing line separators from s, but no other whitespaces.""" if s[-2:] == b'\r\n': return s[:-2] elif s[-1:] == b'\n': return s[:-1] else: return s
Implement a Python 3 function for stripping trailing line separators from s but no other whitespaces.
You are a Python code architect, reviewing and designing scalable and efficient code
def _iter_unfolded_lines(self): """Iter input unfoled lines. Skip comments.""" line = self._input_file.readline() while line: self.line_counter += 1 self.byte_counter += len(line) line = self._strip_line_sep(line) nextline = self._input_file.read...
Write a Python 3 function for iterating input unfoled lines. Skip comments.
As a Python code analyst, you investigate and solve complex coding mysteries
def _iter_blocks(self): """Iter input lines in blocks separated by blank lines.""" lines = [] for line in self._iter_unfolded_lines(): if line: lines.append(line) elif lines: self.records_read += 1 yield lines ...
Can you create a Python 3 function that iterates input lines in blocks separated by blank lines.
You are a Python code generator, capable of creating scripts from specifications.
Parse a single attribute type and value pair.
Can you generate the documentation for the following Python 3 function def _parse_attr(self, line): colon_pos = line.index(b':') attr_type = line[0:colon_pos].decode('ascii') if line[colon_pos:].startswith(b'::'): attr_value = base64.decodestring(line[colon_pos + 2:]) elif l...
As a python code expert, you are capable of creating scripts from specifications.
Check dn attribute for issues.
Can you tell what is the following Python 3 function doing def _check_dn(self, dn, attr_value): if dn is not None: self._error('Two lines starting with dn: in one record.') if not is_dn(attr_value): self._error('No valid string-representation of ' 'distinguished n...
You are a Python code architect, reviewing and designing scalable and efficient code
def _check_changetype(self, dn, changetype, attr_value): """Check changetype attribute for issues.""" if dn is None: self._error('Read changetype: before getting valid dn: line.') if changetype is not None: self._error('Two lines starting with changetype: in one record.')...
Create a Python 3 function for checking changetype attribute for issues.
You are a Python code architect, reviewing and designing scalable and efficient code
Parse a single entry record from a list of lines.
Can you generate the documentation for the following Python 3 function def _parse_entry_record(self, lines): dn = None entry = OrderedDict() for line in lines: attr_type, attr_value = self._parse_attr(line) if attr_type == 'dn': self._check_dn(dn, attr_v...
As a Python code analyst, you investigate and solve complex coding mysteries
Create an objective function and its derivative for W given M and X.
Here you have a function in Python 3, explain what it does def _create_w_objective(m, X, Z=None): genes, clusters = m.shape cells = X.shape[1] nonzeros = (X!=0) def objective(w): # convert w into a matrix first... because it's a vector for # optimization purposes w = w.reshape((m...
As a Python code composer, you craft elegant and concise scripts.
def zip_estimate_state(data, clusters, init_means=None, init_weights=None, max_iters=10, tol=1e-4, disp=True, inner_max_iters=400, normalize=True): """ Uses a Zero-inflated Poisson Mixture model to estimate cell states and cell state mixing weights. Args: data (array): genes x cells clu...
Write a Python 3 script to use a Zero - inflated Poisson Mixture model to estimate cell states and cell mixing weights.
As a python code expert, you are capable of creating scripts from specifications.
def kmeans_pp(data, k, centers=None): """ Generates kmeans++ initial centers. Args: data (array): A 2d array- genes x cells k (int): Number of clusters centers (array, optional): if provided, these are one or more known cluster centers. 2d array of genes x number of centers (<=k). ...
Write a Python 3 script to generate k - means ++ initial centers.
You are a Python code generator, capable of creating scripts from specifications.
Performs Poisson hard EM on the given data.
Can you generate a brief explanation for the following Python 3 code def poisson_cluster(data, k, init=None, max_iters=100): # TODO: be able to use a combination of fixed and unknown starting points # e.g., have init values only for certain genes, have a row of all # zeros indicating that kmeans++ should be...
As a Python code analyst, you investigate and solve complex coding mysteries
def cases(ctx, case_id, to_json): """Display cases in the database.""" adapter = ctx.obj['adapter'] cases = [] if case_id: case_obj = adapter.case({'case_id':case_id}) if not case_obj: LOG.info("Case {0} does not exist in database".format(case_id)) return ...
Can you create a Python 3 function that displays cases in the database.
As a python code expert, you are capable of creating scripts from specifications.
def variants(ctx, variant_id, chromosome, end_chromosome, start, end, variant_type, sv_type): """Display variants in the database.""" if sv_type: variant_type = 'sv' adapter = ctx.obj['adapter'] if (start or end): if not (chromosome and start and end): LOG.warn...
Write a Python 3 function for displaying variants in the database.
You are a Python code analyst, evaluating scripts for potential improvements.
r Diagonal of A \ mathrm A \ mathrm B \ intercal.
Can you generate a brief explanation for the following Python 3 code def dotd(A, B, out=None): A = asarray(A, float) B = asarray(B, float) if A.ndim == 1 and B.ndim == 1: if out is None: return dot(A, B) return dot(A, B, out) if out is None: out = empty((A.shape[0],),...
As a python code expert, you are capable of creating scripts from specifications.
r Dot product of a matrix and a diagonal one.
Can you generate the documentation for the following Python 3 function def ddot(L, R, left=None, out=None): L = asarray(L, float) R = asarray(R, float) if left is None: ok = min(L.ndim, R.ndim) == 1 and max(L.ndim, R.ndim) == 2 if not ok: msg = "Wrong array layout. One array shou...
As a Python code translator, you convert algorithms and pseudocode into Python.
Rank data for arrays contaning NaN values.
Explain what the following Python 3 code does def nanrankdata(a, axis=-1, inplace=False): from scipy.stats import rankdata if hasattr(a, "dtype") and issubdtype(a.dtype, integer): raise ValueError("Integer type is not supported.") if isinstance(a, (tuple, list)): if inplace: ra...
You are a Python code analyst, evaluating scripts for potential improvements.
r Economic eigen decomposition for symmetric matrices.
Can you generate a brief explanation for the following Python 3 code def economic_qs(K, epsilon=sqrt(finfo(float).eps)): (S, Q) = eigh(K) nok = abs(max(Q[0].min(), Q[0].max(), key=abs)) < epsilon nok = nok and abs(max(K.min(), K.max(), key=abs)) >= epsilon if nok: from scipy.linalg import eigh...
As a Python code translator, you convert algorithms and pseudocode into Python.
r Find the unique elements of an array.
Explain what the following Python 3 code does def unique(ar): import dask.array as da if isinstance(ar, da.core.Array): return da.unique(ar) return _unique(ar)
As a Python code composer, you craft elegant and concise scripts.
Natural logarithm of a LU decomposition.
Make a summary of the following Python 3 code def lu_slogdet(LU): LU = (asarray(LU[0], float), asarray(LU[1], float)) adet = _sum(log(_abs(LU[0].diagonal()))) s = prod(sign(LU[0].diagonal())) nrows_exchange = LU[1].size - _sum(LU[1] == arange(LU[1].size, dtype="int32")) odd = nrows_exchange % 2 =...
You are a Python code generator, capable of creating scripts from specifications.
r Solve for LU decomposition.
Explain what the following Python 3 code does def lu_solve(LU, b): from scipy.linalg import lu_solve as sp_lu_solve LU = (asarray(LU[0], float), asarray(LU[1], float)) b = asarray(b, float) return sp_lu_solve(LU, b, check_finite=False)
As a Python code composer, you craft elegant and concise scripts.
r Diagonal of A \ mathrm A \ mathrm B \ intercal.
Explain what the following Python 3 code does def dotd(A, B): A = asarray(A, float) B = asarray(B, float) if A.ndim == 1 and B.ndim == 1: return dot(A, B) out = empty((A.shape[0],), float) out[:] = sum(A * B.T, axis=1) return out
You are a Python code generator, capable of creating scripts from specifications.
r Economic Singular Value Decomposition.
Can you tell what is the following Python 3 function doing def economic_svd(G, epsilon=sqrt(finfo(float).eps)): from scipy.linalg import svd G = asarray(G, float) (U, S, V) = svd(G, full_matrices=False, check_finite=False) ok = S >= epsilon S = S[ok] U = U[:, ok] V = V[ok, :] return (U,...
You are a Python code architect, reviewing and designing scalable and efficient code
r Robust solve for the linear equations.
Given the following Python 3 function, write the documentation def rsolve(A, b, epsilon=_epsilon): A = asarray(A, float) b = asarray(b, float) if A.shape[0] == 0: return zeros((A.shape[1],)) if A.shape[1] == 0: return zeros((0,)) try: x = lstsq(A, b, rcond=epsilon) r ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def check_semidefinite_positiveness(A): """Check if ``A`` is a semi-definite positive matrix. Args: A (array_like): Matrix. Returns: bool: ``True`` if ``A`` is definite positive; ``False`` otherwise. """ B = empty_like(A) B[:] = A B[diag_indices_from(B)] += sqrt(finfo(float...
Create a Python 3 function to check if A is a semi - definite positive matrix.
You are a Python code analyst, evaluating scripts for potential improvements.
Checks if A is a symmetric matrix.
Explain what the following Python 3 code does def check_symmetry(A): A = asanyarray(A) if A.ndim != 2: raise ValueError("Checks symmetry only for bi-dimensional arrays.") if A.shape[0] != A.shape[1]: return False return abs(A - A.T).max() < sqrt(finfo(float).eps)
As a Python code composer, you craft elegant and concise scripts.
r Solve for Cholesky decomposition.
Make a summary of the following Python 3 code def cho_solve(L, b): from scipy.linalg import cho_solve as sp_cho_solve L = asarray(L, float) b = asarray(b, float) if L.size == 0: if b.size != 0: raise ValueError("Dimension mismatch between L and b.") return empty(b.shape) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def file_or_resource(fname=None): '''get filename and check if in getcwd then get from the package resources folder ''' if fname is not None: filename = os.path.expanduser(fname) resource_package = opentargets_validator.__name__ resource_path = os.path.sep.join(('resources',...
Write a Python 3 function that can get filename and check if in getcwd then get from the package resources folder
You are a Python code generator, capable of creating scripts from specifications.
r Solve a lower - triangular matrix A and b.
Make a summary of the following Python 3 code def stl(A, b): from scipy.linalg import solve_triangular A = asarray(A, float) b = asarray(b, float) return solve_triangular(A, b, lower=True, check_finite=False)
As a Python code analyst, you investigate and solve complex coding mysteries
Resolves the executable name and returns the command array with the resolved name.
Can you tell what is the following Python 3 function doing def _windows_resolve(command): try: import win32api except ImportError: if (2, 8) < sys.version_info < (3, 5): logger.info( "Resolving executable names only supported on Python 2.7 and 3.5+" ) ...
As a Python code composer, you craft elegant and concise scripts.
def run( command, timeout=None, debug=False, stdin=None, print_stdout=True, print_stderr=True, callback_stdout=None, callback_stderr=None, environment=None, environment_override=None, win32resolve=True, working_directory=None, ): """ Run an external process. ...
Can you implement a function in Python 3 that runs a command line and returns a dictionary containing the output of the command line and the exit code.
You are a Python code architect, reviewing and designing scalable and efficient code
A stand - in function that returns a valid result dictionary indicating a successful execution of a command.
Can you tell what is the following Python 3 function doing def run_process_dummy(command, **kwargs): warnings.warn( "procrunner.run_process_dummy() is deprecated", DeprecationWarning, stacklevel=2 ) time_start = time.strftime("%Y-%m-%d %H:%M:%S GMT", time.gmtime()) logger.info("run_process is d...
As a Python code translator, you convert algorithms and pseudocode into Python.
def add(self, data): """ Add a single character to buffer. If one or more full lines are found, print them (if desired) and pass to callback function. """ data = self._decoder.decode(data) if not data: return self._buffer += data if "\n" in dat...
Create a Python 3 function for adding a single character to the buffer.
As a Python code composer, you craft elegant and concise scripts.
def flush(self): """Print/send any remaining data to callback function.""" self._buffer += self._decoder.decode(b"", final=True) if self._buffer: if self._print: print(self._buffer) if self._callback: self._callback(self._buffer) se...
Implement a Python 3 function for printing and send any remaining data to callback function.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_output(self): """ Retrieve the stored data in full. This call may block if the reading thread has not yet terminated. """ self._closing = True if not self.has_finished(): if self._debug: # Main thread overtook stream reading thread. ...
Create a Python 3 function for retrieving the stored data in full.
As a Python code translator, you convert algorithms and pseudocode into Python.
def hira2kata(text, ignore=''): """Convert Hiragana to Full-width (Zenkaku) Katakana. Parameters ---------- text : str Hiragana string. ignore : str Characters to be ignored in converting. Return ------ str Katakana string. Examples -------- >>> pri...
Write a Python 3 function that can convert Hiragana to Full - width Katakana.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert Hiragana to Hankaku
Can you generate the documentation for the following Python 3 function def hira2hkata(text, ignore=''): if ignore: h2hk_map = _exclude_ignorechar(ignore, H2HK_TABLE.copy()) return _convert(text, h2hk_map) return _convert(text, H2HK_TABLE)
You are a Python code analyst, evaluating scripts for potential improvements.
def kata2hira(text, ignore=''): """Convert Full-width Katakana to Hiragana Parameters ---------- text : str Full-width Katakana string. ignore : str Characters to be ignored in converting. Return ------ str Hiragana string. Examples -------- >>> pri...
How would you implement a function in Python 3 that converts Full - width Katakana to Hiragana.
As a Python code translator, you convert algorithms and pseudocode into Python.
def h2z(text, ignore='', kana=True, ascii=False, digit=False): """Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana Parameters ---------- text : str Half-width Katakana string. ignore : str Characters to be ignored in converting. kana : bool Either c...
Can you implement a function in Python 3 that converts Hankaku to Zenkaku
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert a string from Zenkaku to Hankaku.
Can you generate the documentation for the following Python 3 function def z2h(text, ignore='', kana=True, ascii=False, digit=False): if ascii: if digit: if kana: z2h_map = Z2H_ALL else: z2h_map = Z2H_AD elif kana: z2h_map = Z2H_AK ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def normalize(text, mode='NFKC', ignore=''): """Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana, Full-width (Zenkaku) ASCII and DIGIT to Half-width (Hankaku) ASCII and DIGIT. Additionally, Full-width wave dash (〜) etc. are normalized Parameters ---------- text : str ...
Write a Python 3 script to convert Hankaku ASCII and DIGIT to Full - width ASCII and DIGIT and Hankaku.
As a Python code composer, you craft elegant and concise scripts.
def kana2alphabet(text): """Convert Hiragana to hepburn-style alphabets Parameters ---------- text : str Hiragana string. Return ------ str Hepburn-style alphabets string. Examples -------- >>> print(jaconv.kana2alphabet('まみさん')) mamisan """ text = ...
Can you implement a function in Python 3 that converts Hiragana to hepburn - style alphabets.
You are a Python code analyst, evaluating scripts for potential improvements.
def alphabet2kana(text): """Convert alphabets to Hiragana Parameters ---------- text : str Alphabets string. Return ------ str Hiragana string. Examples -------- >>> print(jaconv.alphabet2kana('mamisan')) まみさん """ text = text.replace('kya', 'きゃ').re...
Implement a function in Python 3 to convert alphabets to Kiragana.
You are a Python code generator, capable of creating scripts from specifications.
Plots a histogram of x using individual data points x and y.
Make a summary of the following Python 3 code def histpoints(x, bins=None, xerr=None, yerr='gamma', normed=False, **kwargs): import matplotlib.pyplot as plt if bins is None: bins = calc_nbins(x) h, bins = np.histogram(x, bins=bins) width = bins[1] - bins[0] center = (bins[:-1] + bins[1:]) ...
As a python code expert, you are capable of creating scripts from specifications.
Get an eventlet pool used to dispatch requests.
Given the following Python 3 function, write the documentation def pool(self): self._pool = self._pool or eventlet.GreenPool(size=self.pool_size) return self._pool
You are a Python code architect, reviewing and designing scalable and efficient code
Start the process with daemonization.
Explain what the following Python 3 code does def start(self): if self.pid is not None: LOG.error( "The process is already running with pid {0}.".format(self.pid) ) sys.exit(exit.ALREADY_RUNNING) self.daemonize() LOG.info("Beginning run loop...
As a python code expert, you are capable of creating scripts from specifications.
Stop the daemonized process.
Given the following Python 3 function, write the documentation def stop(self): if self.pid is None: return None try: while True: self.send(signal.SIGTERM) time.sleep(0.1) except RuntimeError as err: if "No such process" in...
As a Python code analyst, you investigate and solve complex coding mysteries
Set a function to run when the given signal is recieved.
Here you have a function in Python 3, explain what it does def handle(self, signum, handler): if not isinstance(signum, int): raise TypeError( "Signals must be given as integers. Got {0}.".format( type(signum), ), ) if not cal...
As a Python code translator, you convert algorithms and pseudocode into Python.
def send(self, signum): """Send the given signal to the running process. If the process is not running a RuntimeError with a message of "No such process" should be emitted. """ if not isinstance(signum, int): raise TypeError( "Signals must be given a...
How would you implement a function in Python 3 that sends the given signal to the running process.
As a Python code analyst, you investigate and solve complex coding mysteries
def shutdown(self, signum): """Handle all signals which trigger a process stop. This method should run all appropriate signal handlers registered through the 'handle' method. At the end it should cause the process to exit with a status code. If any of the handlers raise an exception ...
How would you implement a function in Python 3 that handles all signals which trigger a process stop.
As a Python code translator, you convert algorithms and pseudocode into Python.
This function takes a path and checks if the file is in the GMQL format.
Can you generate the documentation for the following Python 3 function def preprocess_path(path): if path.startswith("gs://"): fs = gcsfs.GCSFileSystem(token=get_gcloud_token()) for sub_f in fs.ls(path): if sub_f.endswith("/") and sub_f.split("/")[-2] == FILES_FOLDER: ret...
You are a Python code generator, capable of creating scripts from specifications.
Check if the path of the dataset contains a gdm dataset.
Here you have a function in Python 3, explain what it does def check_for_dataset(files): all_files = os.listdir(files) meta_files = set(map(lambda y: y[: -9], filter(lambda x: x.endswith(".gdm.meta"), all_files))) regs_files = set(map(lambda y: y[: -4], filter(lambda x: x.endswith(".gdm"), all_files))) ...
As a Python code composer, you craft elegant and concise scripts.
Loads the data from a local path into a GMQLDataset.
Given the following Python 3 function, write the documentation def load_from_path(local_path=None, parser=None, all_load=False): from .. import GDataframe from .. import GMQLDataset pmg = get_python_manager() local_path = preprocess_path(local_path) if all_load: # load directly the metad...
As a Python code translator, you convert algorithms and pseudocode into Python.
def load_from_remote(remote_name, owner=None): """ Loads the data from a remote repository. :param remote_name: The name of the dataset in the remote repository :param owner: (optional) The owner of the dataset. If nothing is provided, the current user is used. For public datasets use 'pu...
Implement a Python 3 function for loading the data from a remote repository.
You are a Python code architect, reviewing and designing scalable and efficient code
def scan(interface): """Perform a scan for access points in the area. Arguments: interface - device to use for scanning (e.g. eth1, wlan0). """ interface = _get_bytes(interface) head = ffi.new('wireless_scan_head *') with iwlib_socket() as sock: range = _get_range_info(interfa...
Create a Python 3 function to perform a scan for access points in the area.
You are a Python code generator, capable of creating scripts from specifications.
Login to the GMQL serivice.
Can you generate the documentation for the following Python 3 function def login(self, username=None, password=None): if (username is None) and (password is None): auth_token = self.__login_guest() elif (username is not None) and (password is not None): auth_token, fullName = sel...
You are a Python code architect, reviewing and designing scalable and efficient code
Logout from the remote account
Can you generate a brief explanation for the following Python 3 code def logout(self): url = self.address + "/logout" header = self.__check_authentication() response = requests.get(url, headers=header) if response.status_code != 200: raise ValueError("Code {}. {}".format(resp...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_dataset_list(self): """ Returns the list of available datasets for the current user. :return: a pandas Dataframe """ url = self.address + "/datasets" header = self.__check_authentication() response = requests.get(url, headers=header) response = response.j...
How would you code a function in Python 3 to return the list of available datasets for the current user.
You are a Python code generator, capable of creating scripts from specifications.
def get_dataset_samples(self, dataset_name, owner=None): """ Get the list of samples of a specific remote dataset. :param dataset_name: the dataset name :param owner: (optional) who owns the dataset. If it is not specified, the current user is used. For public dataset use 'public...
Write a Python 3 function for getting the list of samples of a specific remote dataset.
As a Python code composer, you craft elegant and concise scripts.
def get_dataset_schema(self, dataset_name, owner=None): """ Given a dataset name, it returns a BedParser coherent with the schema of it :param dataset_name: a dataset name on the repository :param owner: (optional) who owns the dataset. If it is not specified, the current user is...
Implement a Python 3 function for giving a dataset name, it returns a BedParser coherent with the schema of it :param dataset_name: a dataset name on the repository :param owner: (optional) who owns the dataset. If it is not specified, the current user is used. For public dataset use 'public'. :return: a BedParser
You are a Python code analyst, evaluating scripts for potential improvements.
Upload a dataset to the repository
Make a summary of the following Python 3 code def upload_dataset(self, dataset, dataset_name, schema_path=None): url = self.address + "/datasets/" + dataset_name + "/uploadSample" header = self.__check_authentication() fields = dict() remove = False if isinstance(dataset, GData...
You are a Python code architect, reviewing and designing scalable and efficient code
Deletes the dataset with the specified name from the repository.
Can you tell what is the following Python 3 function doing def delete_dataset(self, dataset_name): url = self.address + "/datasets/" + dataset_name header = self.__check_authentication() response = requests.delete(url, headers=header) if response.status_code != 200: raise Val...
As a Python code analyst, you investigate and solve complex coding mysteries
This function downloads the dataset from the repository and puts it in the specified local folder.
Given the following Python 3 function, write the documentation def download_dataset(self, dataset_name, local_path, how="stream"): if not os.path.isdir(local_path): os.makedirs(local_path) else: raise ValueError("Path {} already exists!".format(local_path)) local_path = ...
You are a Python code generator, capable of creating scripts from specifications.
def query(self, query, output_path=None, file_name="query", output="tab"): """ Execute a GMQL textual query on the remote server. :param query: the string containing the query :param output_path (optional): where to store the results locally. If specified the results are download...
Implement a function in Python 3 to execute a GMQL textual query on the remote server and return a pandas dataframe with the result data.
You are a Python code analyst, evaluating scripts for potential improvements.
def trace_job(self, jobId): """ Get information about the specified remote job :param jobId: the job identifier :return: a dictionary with the information """ header = self.__check_authentication() status_url = self.address + "/jobs/" + jobId + "/trace" status_re...
Write a Python 3 function that can get information about the specified remote job.
You are a Python code analyst, evaluating scripts for potential improvements.
Sets the behavior of the API .
Can you generate a brief explanation for the following Python 3 code def set_mode(how): global __mode if how == "local": __mode = how elif how == "remote": __mode = how else: raise ValueError("how must be 'local' or 'remote'")
You are a Python code generator, capable of creating scripts from specifications.
def set_progress(how): """ Enables or disables the progress bars for the loading, writing and downloading of datasets :param how: True if you want the progress bar, False otherwise :return: None Example:: import gmql as gl gl.set_progress(True) # abilitates progress bars ...
Create a Python 3 function to enable or disables the progress bars for the loading writing and downloading of datasets .
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_meta_profiling(how): """ Enables or disables the profiling of metadata at the loading of a GMQLDataset :param how: True if you want to analyze the metadata when a GMQLDataset is created by a load_from_*. False otherwise. (Default=True) :return: None """ global __metadata_pro...
How would you implement a function in Python 3 that enables or disables the profiling of metadata at the loading of a GMQLDataset .
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_regions(self, path): """ Given a file path, it loads it into memory as a Pandas dataframe :param path: file path :return: a Pandas Dataframe """ if self.schema_format.lower() == GTF.lower(): res = self._parse_gtf_regions(path) else: res ...
Write a Python 3 script to give a file path it loads it into memory as a Pandas dataframe
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the unordered list of attributes
Can you tell what is the following Python 3 function doing def get_attributes(self): attr = ['chr', 'start', 'stop'] if self.strandPos is not None: attr.append('strand') if self.otherPos: for i, o in enumerate(self.otherPos): attr.append(o[1]) ret...
You are a Python code generator, capable of creating scripts from specifications.
def get_ordered_attributes(self): """ Returns the ordered list of attributes :return: list of strings """ attrs = self.get_attributes() attr_arr = np.array(attrs) poss = [self.chrPos, self.startPos, self.stopPos] if self.strandPos is not None: poss.ap...
How would you implement a function in Python 3 that returns the ordered list of attributes
As a Python code analyst, you investigate and solve complex coding mysteries
def get_types(self): """ Returns the unordered list of data types :return: list of data types """ types = [str, int, int] if self.strandPos is not None: types.append(str) if self.otherPos: for o in self.otherPos: types.append(o[2])...
How would you code a function in Python 3 to return the unordered list of data types that are used in the log file.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_name_type_dict(self): """ Returns a dictionary of the type {'column_name': data_type, ...} :return: dict """ attrs = self.get_attributes() types = self.get_types() d = dict() for i,a in enumerate(attrs): d[a] = types[i] return...
Write a Python 3 function that can return a dictionary of the typenames and data types.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_ordered_types(self): """ Returns the ordered list of data types :return: list of data types """ types = self.get_types() types_arr = np.array(types) poss = [self.chrPos, self.startPos, self.stopPos] if self.strandPos is not None: poss.append(s...
Can you create a Python 3 function that returns the ordered list of data types in the order of the positiy.
As a python code expert, you are capable of creating scripts from specifications.
def xmeans(cls, initial_centers=None, kmax=20, tolerance=0.025, criterion=splitting_type.BAYESIAN_INFORMATION_CRITERION, ccore=False): """ Constructor of the x-means clustering.rst algorithm :param initial_centers: Initial coordinates of centers of clusters that are represented by list: [center...
Create a Python 3 function for returning a new object containing the x - means clustering. rst algorithm.
You are a Python code analyst, evaluating scripts for potential improvements.
Return a new CLARANS object.
Given the following Python 3 function, write the documentation def clarans(cls, number_clusters, num_local, max_neighbour): model = clarans(None, number_clusters, num_local, max_neighbour) return cls(model)
As a Python code composer, you craft elegant and concise scripts.
This method is used to create OPTICS clustering. rst objects for the given data.
Can you generate a brief explanation for the following Python 3 code def optics(cls, data, eps, minpts, ccore=False): data = cls.input_preprocess(data) model = optics(data, eps, minpts) return cls(model)
You are a Python code architect, reviewing and designing scalable and efficient code
def is_pyclustering_instance(model): """ Checks if the clustering.rst algorithm belongs to pyclustering :param model: the clustering.rst algorithm model :return: the truth value (Boolean) """ return any(isinstance(model, i) for i in [xmeans, clarans, rock, optics])
Write a Python 3 script for checking if the clustering. rst algorithm belongs to pyclustering
As a Python code translator, you convert algorithms and pseudocode into Python.
Performs clustering.rst :param data: Data to be fit :return: the clustering.rst object
Can you generate a brief explanation for the following Python 3 code def fit(self, data=None): if self.is_pyclustering_instance(self.model): if isinstance(self.model, xmeans): data = self.input_preprocess(data) self.model._xmeans__pointer_data = data elif ...
You are a Python code generator, capable of creating scripts from specifications.
Computes and returns the list of labels indicating the data points and the corresponding cluster ids.
How would you explain what the following Python 3 function does def _labels_from_pyclusters(self): clusters = self.model.get_clusters() labels = [] for i in range(0, len(clusters)): for j in clusters[i]: labels.insert(int(j), i) return labels
As a Python code analyst, you investigate and solve complex coding mysteries
def retrieve_cluster(self, df, cluster_no): """ Extracts the cluster at the given index from the input dataframe :param df: the dataframe that contains the clusters :param cluster_no: the cluster number :return: returns the extracted cluster """ if self.is_pyclus...
Can you implement a function in Python 3 that extracts the cluster at the given index from the input dataframe that contains the clusters .
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_labels(obj): """ Retrieve the labels of a clustering.rst object :param obj: the clustering.rst object :return: the resulting labels """ if Clustering.is_pyclustering_instance(obj.model): return obj._labels_from_pyclusters else: ret...
Can you create a Python 3 function that retrieves the labels of a clustering. rst object.
As a Python code analyst, you investigate and solve complex coding mysteries
def silhouette_n_clusters(data, k_min, k_max, distance='euclidean'): """ Computes and plot the silhouette score vs number of clusters graph to help selecting the number of clusters visually :param data: The data object :param k_min: lowerbound of the cluster range :param k_max: ...
Create a Python 3 function for computing and plots the silhouette score vs number of clusters graph to help selecting the number of clusters visually
As a Python code translator, you convert algorithms and pseudocode into Python.
def elbow_method(data, k_min, k_max, distance='euclidean'): """ Calculates and plots the plot of variance explained - number of clusters Implementation reference: https://github.com/sarguido/k-means-clustering.rst :param data: The dataset :param k_min: lowerbound of the cluster ...
Write a Python 3 function that can calculate and plots the variance explained vs. k
As a python code expert, you are capable of creating scripts from specifications.
Calculates the adjusted mutual information score w. r. t. the reference clusters
Explain what the following Python 3 code does def adjusted_mutual_info(self, reference_clusters): return adjusted_mutual_info_score(self.get_labels(self), self.get_labels(reference_clusters))
As a Python code analyst, you investigate and solve complex coding mysteries
Calculates the adjusted rand score w. r. t. the reference clusters
Can you generate the documentation for the following Python 3 function def adjusted_rand_score(self, reference_clusters): return adjusted_rand_score(self.get_labels(self), self.get_labels(reference_clusters))
You are a Python code architect, reviewing and designing scalable and efficient code
def completeness_score(self, reference_clusters): """ Calculates the completeness score w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: the resulting completeness score """ return completen...
How would you code a function in Python 3 to calculate the completeness score w. r. t. the reference clusters
You are a Python code analyst, evaluating scripts for potential improvements.
def fowlkes_mallows(self, reference_clusters): """ Calculates the Fowlkes-Mallows index (FMI) w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: The resulting Fowlkes-Mallows score. """ return...
Can you write a function in Python 3 where it calculates the Fowlkes - Mallows index w. r. t. the reference clusters.
You are a Python code architect, reviewing and designing scalable and efficient code
def homogeneity_score(self, reference_clusters): """ Calculates the homogeneity score w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: The resulting homogeneity score. """ return homogeneity...
Create a Python 3 function for calculating the homogeneity score w. r. t. the reference clusters
You are a Python code generator, capable of creating scripts from specifications.
def mutual_info_score(self, reference_clusters): """ Calculates the MI (mutual information) w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: The resulting MI score. """ return mutual_info_sc...
How would you code a function in Python 3 to calculate the MI score w. r. t. the reference clusters
You are a Python code generator, capable of creating scripts from specifications.
Calculates the normalized mutual information score w. r. t. the reference clusters
Given the following Python 3 function, write the documentation def normalized_mutual_info_score(self, reference_clusters): return normalized_mutual_info_score(self.get_labels(self), self.get_labels(reference_clusters))
You are a Python code generator, capable of creating scripts from specifications.
def silhouette_score(self, data, metric='euclidean', sample_size=None, random_state=None, **kwds): """ Computes the mean Silhouette Coefficient of all samples (implicit evaluation) :param data: The data that the clusters are generated from :param metric: the pairwise distance metric ...
Write a Python 3 function that can compute the mean Silhouette Coefficient of all samples in the cluster
As a Python code composer, you craft elegant and concise scripts.
Multiple materializations. Enables the user to specify a set of GMQLDataset to be materialized.
Explain what the following Python 3 code does def materialize(datasets): from .. import GMQLDataset if isinstance(datasets, dict): result = dict() for output_path in datasets.keys(): dataset = datasets[output_path] if not isinstance(dataset, GMQLDataset.GMQLDataset): ...
As a Python code composer, you craft elegant and concise scripts.
def retrieve_bicluster(self, df, row_no, column_no): """ Extracts the bicluster at the given row bicluster number and the column bicluster number from the input dataframe. :param df: the input dataframe whose values were biclustered :param row_no: the number of the row bicluster ...
How would you code a function in Python 3 to retrieve the bicluster at the given row and column number from the input dataframe.
As a python code expert, you are capable of creating scripts from specifications.