output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Load pdfs from local filepath if not already b64 encoded Load pdfs from local filepath if not already b64 encoded
Here you have a function in Python 3, explain what it does def pdf_preprocess(pdf, batch=False): if batch: return [pdf_preprocess(doc, batch=False) for doc in pdf] if os.path.isfile(pdf): # a filepath is provided, read and encode return b64encode(open(pdf, 'rb').read()) else: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a list of persons that are linked to the given text.
Make a summary of the following Python 3 code def people(text, cloud=None, batch=None, api_key=None, version=2, **kwargs): url_params = {"batch": batch, "api_key": api_key, "version": version} return api_handler(text, cloud=cloud, api="people", url_params=url_params, **kwargs)
As a Python code translator, you convert algorithms and pseudocode into Python.
Updates the statistics with the given list of numbers .
How would you explain what the following Python 3 function does def update(self, x # type: Sequence[Union[int, float]] ): # type: (...) -> None """ updates the statistics with the given list of numbers It uses an online algorithm which uses compensated sum...
You are a Python code analyst, evaluating scripts for potential improvements.
def hash_and_serialize_chunk(chunk_pii_data, # type: Sequence[Sequence[str]] keys, # type: Sequence[Sequence[bytes]] schema # type: Schema ): # type: (...) -> Tuple[List[str], Sequence[int]] """ Generate Bloom filters ...
Implement a Python 3 function for generating Bloom filters (ie hash) from chunks of PII then serialize the generated Bloom filters. It also computes and outputs the Hamming weight (or popcount) -- the number of bits set to one -- of the generated Bloom filters. :param chunk_pii_data: An iterable of indexable records. :...
You are a Python code generator, capable of creating scripts from specifications.
Generates a list of secret keys from a CSV file.
How would you explain what the following Python 3 function does def generate_clk_from_csv(input_f, # type: TextIO keys, # type: Tuple[AnyStr, AnyStr] schema, # type: Schema validate=True, # type: bool header=True...
You are a Python code analyst, evaluating scripts for potential improvements.
Splits a sequence into chunks of size chunk_size.
Can you generate a brief explanation for the following Python 3 code def chunks(seq, chunk_size): # type: (Sequence[T], int) -> Iterable[Sequence[T]] """ Split seq into chunk_size-sized chunks. :param seq: A sequence to chunk. :param chunk_size: The size of chunk. """ return (seq[i:i + ...
As a python code expert, you are capable of creating scripts from specifications.
Loads first column of specified CSV file from package data.
Can you generate the documentation for the following Python 3 function def load_csv_data(resource_name): # type: (str) -> List[str] """ Loads first column of specified CSV file from package data. """ data_bytes = pkgutil.get_data('clkhash', 'data/{}'.format(resource_name)) if data_bytes is None: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def save_csv(data, # type: Iterable[Tuple[Union[str, int], ...]] headers, # type: Iterable[str] file # type: TextIO ): # type: (...) -> None """ Output generated data to file as CSV with header. :param data: An iterable of tuples containing raw data. :param...
Write a Python 3 script for saving data to file as CSV with header.
As a Python code translator, you convert algorithms and pseudocode into Python.
def random_date(start, end): # type: (datetime, datetime) -> datetime """ Generate a random datetime between two datetime objects. :param start: datetime of start :param end: datetime of end :return: random datetime between start and end """ delta = end - start int_delta = (delta.days *...
Write a Python 3 function for generating a random datetime between two datetime objects.
You are a Python code generator, capable of creating scripts from specifications.
def generate_random_person(self, n): # type: (int) -> Iterable[Tuple[str, str, str, str]] """ Generator that yields details on a person with plausible name, sex and age. :yields: Generated data for one person tuple - (id: int, name: str('First Last'), birthdate: str('DD/MM/Y...
Implement a Python 3 function for generating n random person names and birthdates.
You are a Python code analyst, evaluating scripts for potential improvements.
Loads a name database from CSV files sourced from http://www. quietaffiliate. com / free - first - name - and - last - name - databases - csv - and - sql.
Can you tell what is the following Python 3 function doing def load_names(self): # type: () -> None """ Loads a name database from package data Uses data files sourced from http://www.quietaffiliate.com/free-first-name-and-last-name-databases-csv-and-sql/ """ self.all_m...
As a Python code analyst, you investigate and solve complex coding mysteries
def generate_subsets(self, sz, overlap=0.8, subsets=2): # type: (int, float, int) -> Tuple[List, ...] """ Return random subsets with nonempty intersection. The random subsets are of specified size. If an element is common to two subsets, then it is common to all subsets. ...
Write a Python 3 function that can generate random subsets with nonempty intersection.
As a Python code analyst, you investigate and solve complex coding mysteries
Unpacks the data from the list of data and target pairs into two lists.
How would you explain what the following Python 3 function does def _unpack_list(example): try: x = example[0] y = example[1] meta = None return x, y, meta except IndexError: raise IndicoError( "Invalid input data. Please ensure input data is " "f...
You are a Python code generator, capable of creating scripts from specifications.
def _unpack_dict(example): """ Input data format standardization """ try: x = example['data'] y = example['target'] meta = example.get('metadata', {}) return x, y, meta except KeyError: raise IndicoError( "Invalid input data. Please ensure input d...
Write a Python 3 script for unpacking the data and target keys from the given example dictionary into two lists.
As a python code expert, you are capable of creating scripts from specifications.
Break Xs Ys and metadata out into separate lists for basic data preprocessing.
Given the following Python 3 function, write the documentation def _unpack_data(data): xs = [None] * len(data) ys = [None] * len(data) metadata = [None] * len(data) for idx, example in enumerate(data): if isinstance(example, (list, tuple)): xs[idx], ys[idx], metadata[idx] = _unpack_l...
As a Python code composer, you craft elegant and concise scripts.
Packs data into a list of dicts.
Make a summary of the following Python 3 code def _pack_data(X, Y, metadata): if not any(metadata): # legacy list of list format is acceptable return list(zip(X, Y)) else: # newer dictionary-based format is required in order to save metadata return [ { ...
You are a Python code analyst, evaluating scripts for potential improvements.
Plots the output of the explain endpoint over a sequence of C objects that can be visualized over a terminal visual.
How would you explain what the following Python 3 function does def visualize_explanation(explanation, label=None): if not sys.version_info[:2] >= (3, 5): raise IndicoError("Python >= 3.5+ is required for explanation visualization") try: from colr import Colr as C except ImportError: rais...
As a Python code analyst, you investigate and solve complex coding mysteries
Vectorize a single sequence of data.
Given the following Python 3 function, write the documentation def vectorize(data, cloud=None, api_key=None, version=None, **kwargs): batch = detect_batch(data) data = data_preprocess(data, batch=batch) url_params = {"batch": batch, "api_key": api_key, "version": version, "method": "vectorize"} return a...
You are a Python code architect, reviewing and designing scalable and efficient code
Wrapper around api_handler from indicoio. utils. api to add in stored keyword argument to the JSON body
Given the following Python 3 function, write the documentation def _api_handler(self, *args, **kwargs): keyword_arguments = {} keyword_arguments.update(self.keywords) keyword_arguments.update(kwargs) return api_handler(*args, **keyword_arguments)
You are a Python code architect, reviewing and designing scalable and efficient code
This method is used to add data to the training model.
Make a summary of the following Python 3 code def add_data(self, data, cloud=None, batch=False, api_key=None, version=None, **kwargs): if not len(data): raise IndicoError("No input data provided.") batch = isinstance(data[0], (list, tuple, dict)) # standarize format for preprocessing ...
You are a Python code analyst, evaluating scripts for potential improvements.
def info(self, cloud=None, api_key=None, version=None, **kwargs): """ Return the current state of the model associated with a given collection """ url_params = {"batch": False, "api_key": api_key, "version": version, "method": "info"} return self._api_handler(None, cloud=cloud, a...
Can you write a function in Python 3 where it gets the current state of the model associated with a given collection.
You are a Python code analyst, evaluating scripts for potential improvements.
def wait(self, interval=1, **kwargs): """ Block until the collection's model is completed training """ while True: status = self.info(**kwargs).get('status') if status == "ready": break if status != "training": raise Ind...
Implement a function in Python 3 to block until the collection s model is completed training
As a Python code translator, you convert algorithms and pseudocode into Python.
This method registers a new resource in the collection.
Given the following Python 3 function, write the documentation def register(self, make_public=False, cloud=None, api_key=None, version=None, **kwargs): kwargs['make_public'] = make_public url_params = {"batch": False, "api_key": api_key, "version": version, "method": "register"} return self._api...
As a Python code analyst, you investigate and solve complex coding mysteries
This method allows you to authorize another user to access your model in a read or write capacity.
Can you tell what is the following Python 3 function doing def authorize(self, email, permission_type='read', cloud=None, api_key=None, version=None, **kwargs): kwargs['permission_type'] = permission_type kwargs['email'] = email url_params = {"batch": False, "api_key": api_key, "version": versio...
You are a Python code generator, capable of creating scripts from specifications.
This method allows you to remove another user s access to your collection.
Given the following Python 3 function, write the documentation def deauthorize(self, email, cloud=None, api_key=None, version=None, **kwargs): kwargs['email'] = email url_params = {"batch": False, "api_key": api_key, "version": version, "method": "deauthorize"} return self._api_handler(None, clo...
As a Python code translator, you convert algorithms and pseudocode into Python.
def convert_to_py_error(error_message): """ Raise specific exceptions for ease of error handling """ message = error_message.lower() for err_msg, err_type in ERR_MSGS: if err_msg in message: return err_type(error_message) else: return IndicoError(error_message)
Write a Python 3 script to convert an error message to a Python error.
As a Python code translator, you convert algorithms and pseudocode into Python.
def facial_localization(image, cloud=None, batch=False, api_key=None, version=None, **kwargs): """ Given an image, returns a list of faces found within the image. For each face, we return a dictionary containing the upper left corner and lower right corner. If crop is True, the cropped face is included ...
Implement a function in Python 3 to give an image returns a list of faces found within the image.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a summary of the top N words of a given text.
Explain what the following Python 3 code does def summarization(text, cloud=None, batch=False, api_key=None, version=1, **kwargs): url_params = {"batch": batch, "api_key": api_key, "version": version} return api_handler(text, cloud=cloud, api="summarization", url_params=url_params, **kwargs)
As a Python code analyst, you investigate and solve complex coding mysteries
def hkdf(master_secret, # type: bytes num_keys, # type: int hash_algo='SHA256', # type: str salt=None, # type: Optional[bytes] info=None, # type: Optional[bytes] key_size=DEFAULT_KEY_SIZE # type: int ): # type: (...) -> Tuple[bytes, ...] """ Execut...
Create a Python 3 function for generating a key derivation function from the master_secret and returns the key derivation function and the key material.
As a Python code composer, you craft elegant and concise scripts.
def generate_key_lists(master_secrets, # type: Sequence[Union[bytes, str]] num_identifier, # type: int key_size=DEFAULT_KEY_SIZE, # type: int salt=None, # type: Optional[bytes] info=None, # type: Optional[bytes] ...
Can you implement a function in Python 3 that generates a list of derived key lists for each master secret.
You are a Python code analyst, evaluating scripts for potential improvements.
def validate_row_lengths(fields, # type: Sequence[FieldSpec] data # type: Sequence[Sequence[str]] ): # type: (...) -> None """ Validate the `data` row lengths according to the specification in `fields`. :param fields: The `FieldSpec` objects f...
Create a Python 3 function to validate the data row lengths according to the specification in fields.
As a Python code composer, you craft elegant and concise scripts.
def validate_entries(fields, # type: Sequence[FieldSpec] data # type: Sequence[Sequence[str]] ): # type: (...) -> None """ Validate the `data` entries according to the specification in `fields`. :param fields: The `FieldSpec` objects forming the ...
Can you implement a function in Python 3 that validates the data entries according to the specification in .
You are a Python code analyst, evaluating scripts for potential improvements.
def validate_header(fields, # type: Sequence[FieldSpec] column_names # type: Sequence[str] ): # type: (...) -> None """ Validate the `column_names` according to the specification in `fields`. :param fields: The `FieldSpec` objects forming the ...
Implement a function in Python 3 to validate the header of the given fields according to the specification in .
As a Python code composer, you craft elegant and concise scripts.
def config(env=DEFAULT_ENV, default=None): """Returns a dictionary with EMAIL_* settings from EMAIL_URL.""" conf = {} s = os.environ.get(env, default) if s: conf = parse(s) return conf
Write a Python 3 script to return a dictionary with EMAIL_* settings from EMAIL_URL.
As a Python code composer, you craft elegant and concise scripts.
def parse(url): """Parses an email URL.""" conf = {} url = urlparse.urlparse(url) qs = urlparse.parse_qs(url.query) # Remove query strings path = url.path[1:] path = path.split('?', 2)[0] # Update with environment configuration conf.update({ 'EMAIL_FILE_PATH': path, ...
Can you implement a function in Python 3 that parses an email URL and returns a dictionary of configuration variables.
You are a Python code generator, capable of creating scripts from specifications.
def to_tf_matrix(expression_matrix, gene_names, tf_names): """ :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf...
Can you implement a function in Python 3 that converts an expression matrix to a numpy matrix representing the predictor matrix for the regressions.
You are a Python code analyst, evaluating scripts for potential improvements.
Fits a single model to the given target gene expression.
How would you explain what the following Python 3 function does def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): """ :param regressor_type:...
As a python code expert, you are capable of creating scripts from specifications.
This function takes the feature importances inferred from the trained model and returns the feature importances inferred from the trained model.
Here you have a function in Python 3, explain what it does def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): """ Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a Pandas DataFrame containing the meta information about the regression.
Can you generate the documentation for the following Python 3 function def to_meta_df(trained_regressor, target_gene_name): """ :param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas D...
As a Python code translator, you convert algorithms and pseudocode into Python.
def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): """ :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. ...
Can you create a Python 3 function that returns a Pandas DataFrame representing inferred regulatory links and their respective cluster names.
As a Python code composer, you craft elegant and concise scripts.
Retry a function on a node in a node s tree.
How would you explain what the following Python 3 function does def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries...
As a Python code composer, you craft elegant and concise scripts.
Infer partial network for a set of transcription factors.
Here you have a function in Python 3, explain what it does def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expressi...
You are a Python code generator, capable of creating scripts from specifications.
def target_gene_indices(gene_names, target_genes): """ :param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix. """ if is...
Can you create a Python 3 function that returns the column indices of the target genes in the expression_matrix.
As a python code expert, you are capable of creating scripts from specifications.
This function creates a Dask computation graph for a set of regulatory links.
Can you generate a brief explanation for the following Python 3 code def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, ...
You are a Python code generator, capable of creating scripts from specifications.
def window_boundaries(self, current_round): """ :param current_round: :return: the low and high boundaries of the estimators window to consider. """ lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi
Create a Python 3 function to return the low and high boundaries of the estimators window to consider.
You are a Python code analyst, evaluating scripts for potential improvements.
Generates an encrypted URL with the specified options
Explain what the following Python 3 code does def generate(self, **options): '''Generates an encrypted URL with the specified options''' if options.get('unsafe', False): return unsafe_url(**options) else: return self.generate_new(options)
You are a Python code architect, reviewing and designing scalable and efficient code
CheckOnline - Check online User
How would you explain what the following Python 3 function does def checkOnline(self, userId): desc = { "name": "CheckOnlineReslut", "desc": "checkOnlineUser返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,20...
As a python code expert, you are capable of creating scripts from specifications.
Add a blacklist to a user.
Given the following Python 3 function, write the documentation def addBlacklist(self, userId, blackUserId): desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "...
You are a Python code architect, reviewing and designing scalable and efficient code
发送单聊模板消息方法(一个用户向多个用户发送不同消息内容,单条消息最大 128k。每分钟最多发送 6000 条信息,每次发送用户上限为 1000 人。) 方法 @param templateMessage:单聊模版消息。 @return code:返回码,200 为正常。 @return errorMessage:错误信息。
Can you generate the documentation for the following Python 3 function def publishTemplate(self, templateMessage): desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "d...
You are a Python code architect, reviewing and designing scalable and efficient code
publishGroup - Publishes a group
Given the following Python 3 function, write the documentation def publishGroup(self, fromUserId, toGroupId, objectName, content, pushContent=None, pushData=None, isPersiste...
As a Python code composer, you craft elegant and concise scripts.
发送聊天室消息方法(一个用户向聊天室发送消息,单条消息最大 128k。每秒钟限 100 次。) 方法 @param fromUserId:发送人用户 Id。(必传) @param toChatroomId:接收聊天室Id,提供多个本参数可以实现向多个聊天室发送消息。(必传) @param txtMessage:发送消息内容(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。
Can you generate a brief explanation for the following Python 3 code def publishChatroom(self, fromUserId, toChatroomId, objectName, content): desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "...
As a Python code composer, you craft elegant and concise scripts.
broadcasts a message to the push server
Given the following Python 3 function, write the documentation def broadcast(self, fromUserId, objectName, content, pushContent=None, pushData=None, os=None): """ 发送广播消息方法(发送消息给一个应用下的所有注册用户,如用户未在线...
As a python code expert, you are capable of creating scripts from specifications.
Delete a message from the database.
Explain what the following Python 3 code does def deleteMessage(self, date): desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" }, { ...
You are a Python code generator, capable of creating scripts from specifications.
Tries to utf - 8 encode x when possible returns a list of strings.
Can you tell what is the following Python 3 function doing def to_utf8(x): if isinstance(x, basestring): return x.encode('utf-8') if isinstance(x, unicode) else x try: l = iter(x) except TypeError: return x return [to_utf8(i) for i in l]
As a Python code translator, you convert algorithms and pseudocode into Python.
def _split_url_string(query_string): """ Turns a `query_string` into a Python dictionary with unquoted values """ parameters = parse_qs(to_utf8(query_string), keep_blank_values=True) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) retu...
Can you implement a function in Python 3 that turns a query_string into a Python dictionary with unquoted values
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_normalized_parameters(request): """ Returns a string that contains the parameters that must be signed. This function is called by SignatureMethod subclass CustomSignatureMethod_HMAC_SHA1 """ # See issues #10 and #12 if ('Content-Type' not in request.headers or \ ...
How would you code a function in Python 3 to return a string that contains the parameters that must be signed.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a normalized url without params
Can you generate a brief explanation for the following Python 3 code def get_normalized_url(url): scheme, netloc, path, params, query, fragment = urlparse(url) # Exclude default port numbers. if scheme == 'http' and netloc[-3:] == ':80': netloc = netloc[:-3] elif scheme == '...
As a Python code translator, you convert algorithms and pseudocode into Python.
Serialize as a URL for a GET request.
Here you have a function in Python 3, explain what it does def to_url(request): scheme, netloc, path, query, fragment = urlsplit(to_utf8(request.url)) query = parse_qs(query) for key, value in request.data_and_params.iteritems(): query.setdefault(key, []).append(value) quer...
As a python code expert, you are capable of creating scripts from specifications.
def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): """ Launch arboreto with [GRNBoos...
Can you implement a function in Python 3 that launches arboreto with GRNBoost2.
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate a Gene - E3 regressor for a set of genes.
Can you generate a brief explanation for the following Python 3 code def genie3(expression_data, gene_names=None, tf_names='all', client_or_address='local', limit=None, seed=None, verbose=False): """ Launch arboreto with [GENIE3] profile. :p...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function computes the regulatory links for a set of regulatory links in a single cluster.
Explain what the following Python 3 code does def diy(expression_data, regressor_type, regressor_kwargs, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=F...
As a python code expert, you are capable of creating scripts from specifications.
def _prepare_client(client_or_address): """ :param client_or_address: one of: * None * verbatim: 'local' * string address * a Client instance :return: a tuple: (Client instance, shutdown callback function). :raises: ValueError if no valid client input was prov...
Write a Python 3 script to prepare a client instance.
You are a Python code analyst, evaluating scripts for potential improvements.
def _prepare_input(expression_data, gene_names, tf_names): """ Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D nump...
How would you implement a function in Python 3 that prepares the input for the next iteration of the sequence.
You are a Python code generator, capable of creating scripts from specifications.
def _make_common_signature(self): """生成通用签名, 一般情况下,您不需要调用该方法 文档详见 http://docs.rongcloud.cn/server.html#_API_调用签名规则 :return: {'app-key':'xxx','nonce':'xxx','timestamp':'xxx','signature':'xxx'} """ nonce = str(random.random()) timestamp = str(int(time.time()) * 1000) signat...
Implement a Python 3 function for making common signature for the current application key.
As a Python code translator, you convert algorithms and pseudocode into Python.
Makes a http call. Logs response information.
Can you tell what is the following Python 3 function doing def _http_call(self, url, method, **kwargs): logging.debug("Request[{0}]: {1}".format(method, url)) start_time = datetime.datetime.now() logging.debug("Header: {0}".format(kwargs['headers'])) logging.debug("Params: {0}".format(k...
As a Python code analyst, you investigate and solve complex coding mysteries
:param method: methodName :param action: MethodUrl, :param params: Dictionary,form params for api. :param timeout: (optional) Float describing the timeout of the request. :return:
Here you have a function in Python 3, explain what it does def call_api(self, action, params=None, method=('API', 'POST', 'application/x-www-form-urlencoded'), **kwargs): """ :param method: methodName :param action: MethodUrl, ...
As a Python code composer, you craft elegant and concise scripts.
def calculate_width_and_height(url_parts, options): '''Appends width and height information to url''' width = options.get('width', 0) has_width = width height = options.get('height', 0) has_height = height flip = options.get('flip', False) flop = options.get('flop', False) if flip: ...
How would you implement a function in Python 3 that calculates the width and height of a node in url_parts.
As a Python code composer, you craft elegant and concise scripts.
Returns the url for the specified options
Can you tell what is the following Python 3 function doing def url_for(**options): '''Returns the url for the specified options''' url_parts = get_url_parts(**options) image_hash = hashlib.md5(b(options['image_url'])).hexdigest() url_parts.append(image_hash) return "/".join(url_parts)
As a Python code translator, you convert algorithms and pseudocode into Python.
def mini(description, **kwargs): """Single notification function Simple notification function in one line. Has only one required parameter and attempts to use reasonable defaults for everything else :param string description: Notification message """ kwargs['notifierFactory'] = GrowlNotifier gntp.notifier.mini(...
Create a Python 3 function for singling notification function in one line. Has only one required parameter kwargs will be passed to GrowlNotifier. notifier. mini
You are a Python code generator, capable of creating scripts from specifications.
Query the chatroom for a user.
Can you tell what is the following Python 3 function doing def queryUser(self, chatroomId, count, order): desc = { "name": "ChatroomUserQueryReslut", "desc": " chatroomUserQuery 返回结果", "fields": [{ "name": "code", "type": "Integer", ...
As a Python code composer, you craft elegant and concise scripts.
def addGagUser(self, userId, chatroomId, minute): """ 添加禁言聊天室成员方法(在 App 中如果不想让某一用户在聊天室中发言时,可将此用户在聊天室中禁言,被禁言用户可以接收查看聊天室中用户聊天信息,但不能发送消息.) 方法 @param userId:用户 Id。(必传) @param chatroomId:聊天室 Id。(必传) @param minute:禁言时长,以分钟为单位,最大值为43200分钟。(必传) @return code:返回码,200 为正常。 ...
Write a Python 3 script for adding a new gag user to the chatroom.
You are a Python code generator, capable of creating scripts from specifications.
This method rollbacks a user from a chatroom to a specific user.
Can you generate the documentation for the following Python 3 function def rollbackBlockUser(self, userId, chatroomId): desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", ...
As a Python code analyst, you investigate and solve complex coding mysteries
add priority to a message
Can you generate the documentation for the following Python 3 function def addPriority(self, objectName): desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回...
You are a Python code analyst, evaluating scripts for potential improvements.
Set a push tag.
How would you explain what the following Python 3 function does def setUserPushTag(self, userTag): desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为...
You are a Python code generator, capable of creating scripts from specifications.
def broadcastPush(self, pushMessage): """ 广播消息方法(fromuserid 和 message为null即为不落地的push) 方法 @param pushMessage:json数据 @return code:返回码,200 为正常。 @return errorMessage:错误信息。 """ desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", ...
Implement a function in Python 3 to broadcast a push message to the user.
As a python code expert, you are capable of creating scripts from specifications.
def load_tf_names(path): """ :param path: the path of the transcription factor list file. :return: a list of transcription factor names read from the file. """ with open(path) as file: tfs_in_file = [line.strip() for line in file.readlines()] return tfs_in_file
Create a Python 3 function for loading the transcription factor names from a file.
As a python code expert, you are capable of creating scripts from specifications.
Refreshes the cache for a group.
Explain what the following Python 3 code does def refresh(self, groupId, groupName): desc = { "name": "CodeSuccessReslut", "desc": " http 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" ...
You are a Python code analyst, evaluating scripts for potential improvements.
def join(self, userId, groupId, groupName): """ 将用户加入指定群组,用户将可以收到该群的消息,同一用户最多可加入 500 个群,每个群最大至 3000 人。 方法 @param userId:要加入群的用户 Id,可提交多个,最多不超过 1000 个。(必传) @param groupId:要加入的群 Id。(必传) @param groupName:要加入的群 Id 对应的名称。(必传) @return code:返回码,200 为正常。 @return err...
Can you create a Python 3 function that joins a user with another user.
You are a Python code analyst, evaluating scripts for potential improvements.
def queryUser(self, groupId): """ 查询群成员方法 方法 @param groupId:群组Id。(必传) @return code:返回码,200 为正常。 @return id:群成员用户Id。 @return users:群成员列表。 """ desc = { "name": "GroupUserQueryReslut", "desc": "groupUserQuery返回结果", "field...
Create a Python 3 function for querying the group user.
You are a Python code generator, capable of creating scripts from specifications.
def dismiss(self, userId, groupId): """ 解散群组方法。(将该群解散,所有用户都无法再接收该群的消息。) 方法 @param userId:操作解散群的用户 Id。(必传) @param groupId:要解散的群 Id。(必传) @return code:返回码,200 为正常。 @return errorMessage:错误信息。 """ desc = { "name": "CodeSuccessReslut", ...
Create a Python 3 function for dismissing a user from a group.
You are a Python code analyst, evaluating scripts for potential improvements.
def parse_gntp(data, password=None): """Attempt to parse a message as a GNTP message :param string data: Message to be parsed :param string password: Optional password to be used to verify the message """ data = gntp.shim.u(data) match = GNTP_INFO_LINE_SHORT.match(data) if not match: raise errors.ParseError('...
Can you write a function in Python 3 where it attempts to parse a message as a GNTP message
As a Python code analyst, you investigate and solve complex coding mysteries
def _parse_info(self, data): """Parse the first line of a GNTP message to get security and other info values :param string data: GNTP Message :return dict: Parsed GNTP Info line """ match = GNTP_INFO_LINE.match(data) if not match: raise errors.ParseError('ERROR_PARSING_INFO_LINE') info = match.grou...
Implement a function in Python 3 to parse the first line of a GNTP message to get security and other info values
You are a Python code analyst, evaluating scripts for potential improvements.
Set a password for a GNTP Message
How would you explain what the following Python 3 function does def set_password(self, password, encryptAlgo='MD5'): if not password: self.info['encryptionAlgorithmID'] = None self.info['keyHashAlgorithm'] = None return self.password = gntp.shim.b(password) self.encryptAlgo = encryptAlgo.upper() if n...
You are a Python code architect, reviewing and designing scalable and efficient code
Helper function to decode hex string to proper hex string
Here you have a function in Python 3, explain what it does def _decode_hex(self, value): result = '' for i in range(0, len(value), 2): tmp = int(value[i:i + 2], 16) result += chr(tmp) return result
As a Python code composer, you craft elegant and concise scripts.
def _validate_password(self, password): """Validate GNTP Message against stored password""" self.password = password if password is None: raise errors.AuthError('Missing password') keyHash = self.info.get('keyHash', None) if keyHash is None and self.password is None: return True if keyHash is None: ...
Can you create a Python 3 function that validates GNTP Message against stored password
As a Python code composer, you craft elegant and concise scripts.
Generate info line for GNTP Message
How would you explain what the following Python 3 function does def _format_info(self): info = 'GNTP/%s %s' % ( self.info.get('version'), self.info.get('messagetype'), ) if self.info.get('encryptionAlgorithmID', None): info += ' %s:%s' % ( self.info.get('encryptionAlgorithmID'), self.info.get('iv...
You are a Python code analyst, evaluating scripts for potential improvements.
Helper function to parse GNTP headers into a dictionary
Can you generate the documentation for the following Python 3 function def _parse_dict(self, data): d = {} for line in data.split('\r\n'): match = GNTP_HEADER.match(line) if not match: continue key = match.group(1).strip() val = match.group(2).strip() d[key] = val return d
You are a Python code analyst, evaluating scripts for potential improvements.
Add binary resource to the list of resources
Can you tell what is the following Python 3 function doing def add_resource(self, data): data = gntp.shim.b(data) identifier = hashlib.md5(data).hexdigest() self.resources[identifier] = data return 'x-growl-resource://%s' % identifier
You are a Python code architect, reviewing and designing scalable and efficient code
Decode GNTP Message :param string data:
Can you generate a brief explanation for the following Python 3 code def decode(self, data, password=None): self.password = password self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self.headers = self._parse_dict(parts[0])
As a Python code translator, you convert algorithms and pseudocode into Python.
Validate required headers and validate notification headers
Explain what the following Python 3 code does def validate(self): '''Validate required headers and validate notification headers''' for header in self._requiredHeaders: if not self.headers.get(header, False): raise errors.ParseError('Missing Registration Header: ' + header) for notice in self.notifications...
As a Python code composer, you craft elegant and concise scripts.
def decode(self, data, password): """Decode existing GNTP Registration message :param string data: Message to decode """ self.raw = gntp.shim.u(data) parts = self.raw.split('\r\n\r\n') self.info = self._parse_info(self.raw) self._validate_password(password) self.headers = self._parse_dict(parts[0]) ...
Implement a function in Python 3 to decode existing GNTP Registration message
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_notification(self, name, enabled=True): """Add new Notification to Registration message :param string name: Notification Name :param boolean enabled: Enable this notification by default """ notice = {} notice['Notification-Name'] = name notice['Notification-Enabled'] = enabled self.notificatio...
Write a Python 3 function for adding new Notification to Registration message self
You are a Python code architect, reviewing and designing scalable and efficient code
Encode a GNTP Registration Message. Returned as a byte string
Here you have a function in Python 3, explain what it does def encode(self): buff = _GNTPBuffer() buff.writeln(self._format_info()) #Headers for k, v in self.headers.items(): buff.writeheader(k, v) buff.writeln() #Notifications if len(self.notifications) > 0: for notice in self.notifications: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
This method returns the SMS Image Code for a given appKey.
Make a summary of the following Python 3 code def getImageCode(self, appKey): desc = { "name": "SMSImageCodeReslut", "desc": " getImageCode 成功返回结果", "fields": [{ "name": "code", "type": "Integer", "desc": "返回码,200 为正常。" ...
As a Python code analyst, you investigate and solve complex coding mysteries
sendCode - Sends code to a mobile user.
Explain what the following Python 3 code does def sendCode(self, mobile, templateId, region, verifyId=None, verifyCode=None): """ 发送短信验证码方法。 方法 @param mobile:接收短信验证码的目标手机号,每分钟同一手机号只能发送一次短信验证码,同一手机号 1 小时内最多发送 3 ...
You are a Python code architect, reviewing and designing scalable and efficient code
This method verify the code of a given session.
Can you generate the documentation for the following Python 3 function def verifyCode(self, sessionId, code): desc = { "name": "SMSVerifyCodeResult", "desc": " VerifyCode 返回结果", "fields": [{ "name": "code", "type": "Integer", "...
As a Python code analyst, you investigate and solve complex coding mysteries
def mini(description, applicationName='PythonMini', noteType="Message", title="Mini Message", applicationIcon=None, hostname='localhost', password=None, port=23053, sticky=False, priority=None, callback=None, notificationIcon=None, identifier=None, notifierFactory=GrowlNotifier): """Single notification fun...
Create a Python 3 function to single notification function Simple notification function in one line. Has only one required parameter and attempts to use reasonable defaults for everything else :param string description: Notification message .. warning:: For now, only URL callbacks are supported. In the future, the call...
As a python code expert, you are capable of creating scripts from specifications.
Send GNTP Registration to Growl
Here you have a function in Python 3, explain what it does def register(self): logger.info('Sending registration to %s:%s', self.hostname, self.port) register = gntp.core.GNTPRegister() register.add_header('Application-Name', self.applicationName) for notification in self.notifications: enabled = notificatio...
You are a Python code generator, capable of creating scripts from specifications.
Send a GNTP notification to the GNTP server.
Can you tell what is the following Python 3 function doing def notify(self, noteType, title, description, icon=None, sticky=False, priority=None, callback=None, identifier=None, custom={}): """Send a GNTP notifications .. warning:: Must have registered with growl beforehand or messages will be ignored :pa...
As a Python code translator, you convert algorithms and pseudocode into Python.
def subscribe(self, id, name, port): """Send a Subscribe request to a remote machine""" sub = gntp.core.GNTPSubscribe() sub.add_header('Subscriber-ID', id) sub.add_header('Subscriber-Name', name) sub.add_header('Subscriber-Port', port) if self.password: sub.set_password(self.password, self.passwordHash) ...
Write a Python 3 script to send a Subscribe request to a remote machine
You are a Python code analyst, evaluating scripts for potential improvements.