output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Opens a new connection.
Given the following Python 3 function, write the documentation def open_connection(self, connection_id, info=None): request = requests_pb2.OpenConnectionRequest() request.connection_id = connection_id if info is not None: # Info is a list of repeated pairs, setting a dict directly fa...
As a Python code analyst, you investigate and solve complex coding mysteries
Closes a connection. :param connection_id: ID of the connection to close.
How would you explain what the following Python 3 function does def close_connection(self, connection_id): request = requests_pb2.CloseConnectionRequest() request.connection_id = connection_id self._apply(request)
As a python code expert, you are capable of creating scripts from specifications.
Creates a new statement.
Can you tell what is the following Python 3 function doing def create_statement(self, connection_id): request = requests_pb2.CreateStatementRequest() request.connection_id = connection_id response_data = self._apply(request) response = responses_pb2.CreateStatementResponse() res...
As a Python code composer, you craft elegant and concise scripts.
def close_statement(self, connection_id, statement_id): """Closes a statement. :param connection_id: ID of the current connection. :param statement_id: ID of the statement to close. """ request = requests_pb2.CloseStatementRequest() request.conne...
Can you write a function in Python 3 where it closes a statement. :param connection_id: ID of the current connection. :param statement_id: ID of the statement to close.
You are a Python code generator, capable of creating scripts from specifications.
Prepares and immediately executes a statement.
Explain what the following Python 3 code does def prepare_and_execute(self, connection_id, statement_id, sql, max_rows_total=None, first_frame_max_size=None): request = requests_pb2.PrepareAndExecuteRequest() request.connection_id = connection_id request.statement_id = statement_id reque...
As a Python code translator, you convert algorithms and pseudocode into Python.
def prepare(self, connection_id, sql, max_rows_total=None): """Prepares a statement. :param connection_id: ID of the current connection. :param sql: SQL query. :param max_rows_total: The maximum number of rows that will be allowed for this query. ...
Can you implement a function in Python 3 that prepares a statement. :param connection_id: ID of the current connection. :param sql: SQL query. :param max_rows_total: The maximum number of rows that will be allowed for this query. :returns: Signature of the prepared statement.
You are a Python code architect, reviewing and designing scalable and efficient code
def execute(self, connection_id, statement_id, signature, parameter_values=None, first_frame_max_size=None): """Returns a frame of rows. The frame describes whether there may be another frame. If there is not another frame, the current iteration is done when we have finished the rows in...
Implement a function in Python 3 to execute a statement and returns a Frame of rows.
As a Python code composer, you craft elegant and concise scripts.
def fetch(self, connection_id, statement_id, offset=0, frame_max_size=None): """Returns a frame of rows. The frame describes whether there may be another frame. If there is not another frame, the current iteration is done when we have finished the rows in the this frame. :param...
How would you code a function in Python 3 to return a frame of rows.
As a Python code analyst, you investigate and solve complex coding mysteries
Closes the cursor. No further operations are allowed once the cursor is closed. If the cursor is used in a ``with`` statement, this method will be automatically called at the end of the ``with`` block.
Explain what the following Python 3 code does def close(self): if self._closed: raise ProgrammingError('the cursor is already closed') if self._id is not None: self._connection._client.close_statement(self._connection._id, self._id) self._id = None self._signa...
As a Python code translator, you convert algorithms and pseudocode into Python.
Transforms a common_pb2. Row object into a list of Python values.
Can you generate the documentation for the following Python 3 function def _transform_row(self, row): tmp_row = [] for i, column in enumerate(row.value): if column.has_array_value: raise NotImplementedError('array types are not supported') elif column.scalar_valu...
As a Python code analyst, you investigate and solve complex coding mysteries
Read - only attribute providing the current 0 - based index of the the cursor in the result set or None if the index cannot be determined.
Can you generate the documentation for the following Python 3 function def rownumber(self): if self._frame is not None and self._pos is not None: return self._frame.offset + self._pos return self._pos
You are a Python code analyst, evaluating scripts for potential improvements.
def Timestamp(year, month, day, hour, minute, second): """Constructs an object holding a datetime/timestamp value.""" return datetime.datetime(year, month, day, hour, minute, second)
Implement a function in Python 3 to construct a datetime. datetime object holding a datetime value.
As a python code expert, you are capable of creating scripts from specifications.
def close(self): """Closes the connection. No further operations are allowed, either on the connection or any of its cursors, once the connection is closed. If the connection is used in a ``with`` statement, this method will be automatically called at the end of the ``with`` blo...
How would you code a function in Python 3 to close the connection. No further operations are allowed, either on the connection or any of its cursors, once the connection is closed. If the connection is used in a ``with`` statement, this method will be automatically called at the end of the ``with`` block.
As a python code expert, you are capable of creating scripts from specifications.
def cursor(self, cursor_factory=None): """Creates a new cursor. :param cursor_factory: This argument can be used to create non-standard cursors. The class returned must be a subclass of :class:`~phoenixdb.cursor.Cursor` (for example :class:`~phoenixdb.cursor.DictCurs...
Write a Python 3 function for creating a new cursor.
You are a Python code analyst, evaluating scripts for potential improvements.
Sets one or more parameters in the current connection.
Can you generate the documentation for the following Python 3 function def set_session(self, autocommit=None, readonly=None): props = {} if autocommit is not None: props['autoCommit'] = bool(autocommit) if readonly is not None: props['readOnly'] = bool(readonly) p...
As a python code expert, you are capable of creating scripts from specifications.
def fit(self, X, y): """Fit the model Parameters ---------- X : array-like of shape = [n_samples, n_features] The training input samples. y : array-like, shape = [n_samples] The target values Returns ------- self : object ...
Implement a Python 3 function for fitting the model to the set of training data and target values.
As a Python code translator, you convert algorithms and pseudocode into Python.
def predict(self, X): """Predict target values for X. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. Returns ------- y : array of shape = [n_samples] The predicted target value. """ ...
Write a Python 3 function for predicting target values for X.
You are a Python code analyst, evaluating scripts for potential improvements.
Compute hidden activations given X
Can you generate a brief explanation for the following Python 3 code def _compute_hidden_activations(self, X): self._compute_input_activations(X) acts = self.input_activations_ if (callable(self.activation_func)): args_dict = self.activation_args if (self.activation_args) else {} ...
As a Python code analyst, you investigate and solve complex coding mysteries
Generate the random hidden layer s activations given X as input.
Make a summary of the following Python 3 code def transform(self, X, y=None): if (self.components_ is None): raise ValueError('No components initialized') return self._compute_hidden_activations(X)
You are a Python code generator, capable of creating scripts from specifications.
def _compute_radii(self): """Generate RBF radii""" # use supplied radii if present radii = self._get_user_components('radii') # compute radii if (radii is None): centers = self.components_['centers'] n_centers = centers.shape[0] max_dist = n...
Can you write a function in Python 3 where it generates RBF radii for the user.
As a Python code analyst, you investigate and solve complex coding mysteries
Generate centers for the user defined centers.
How would you explain what the following Python 3 function does def _compute_centers(self, X, sparse, rs): # use supplied centers if present centers = self._get_user_components('centers') # use points taken uniformly from the bounding # hyperrectangle if (centers is None): ...
As a Python code composer, you craft elegant and concise scripts.
Generate MLP biases for the current user.
Make a summary of the following Python 3 code def _compute_biases(self, rs): # use supplied biases if present biases = self._get_user_components('biases') if (biases is None): b_size = self.n_hidden biases = rs.normal(size=b_size) self.components_['biases'] = bi...
As a python code expert, you are capable of creating scripts from specifications.
def _generate_components(self, X): """Generate components of hidden layer given X""" rs = check_random_state(self.random_state) if (self._use_mlp_input): self._compute_biases(rs) self._compute_weights(X, rs) if (self._use_rbf_input): self._compute_ce...
Write a Python 3 script to generate components of hidden layer given X
As a Python code translator, you convert algorithms and pseudocode into Python.
Compute input activations given X
Can you generate the documentation for the following Python 3 function def _compute_input_activations(self, X): n_samples = X.shape[0] mlp_acts = np.zeros((n_samples, self.n_hidden)) if (self._use_mlp_input): b = self.components_['biases'] w = self.components_['weights'...
As a python code expert, you are capable of creating scripts from specifications.
Generate centers then compute tau dF and dN vals
Given the following Python 3 function, write the documentation def _compute_centers(self, X, sparse, rs): super(GRBFRandomLayer, self)._compute_centers(X, sparse, rs) centers = self.components_['centers'] sorted_distances = np.sort(squareform(pdist(centers))) self.dF_vals = sorted_dist...
As a Python code translator, you convert algorithms and pseudocode into Python.
fit regression using pseudo - inverse
Given the following Python 3 function, write the documentation def _fit_regression(self, y): if self.regressor is None: self.coefs_ = safe_sparse_dot(pinv2(self.hidden_activations_), y) else: self.regressor.fit(self.hidden_activations_, y) self.fitted_ = True
As a python code expert, you are capable of creating scripts from specifications.
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
Can you write a function in Python 3 where it fits the model using X y as training data.
You are a Python code generator, capable of creating scripts from specifications.
get predictions using internal least squares
Can you generate the documentation for the following Python 3 function def _get_predictions(self): if self.regressor is None: preds = safe_sparse_dot(self.hidden_activations_, self.coefs_) else: preds = self.regressor.predict(self.hidden_activations_) return preds
You are a Python code architect, reviewing and designing scalable and efficient code
Predict values using the model.
How would you explain what the following Python 3 function does def predict(self, X): if not self.fitted_: raise ValueError("ELMRegressor not fitted") # compute hidden layer activations self.hidden_activations_ = self.hidden_layer.transform(X) # compute output predictions f...
You are a Python code analyst, evaluating scripts for potential improvements.
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
Write a Python 3 script to fit the model using X y as training data.
As a Python code composer, you craft elegant and concise scripts.
Predict values using the model Taxonomy
Can you generate a brief explanation for the following Python 3 code def predict(self, X): raw_predictions = self.decision_function(X) class_predictions = self.binarizer.inverse_transform(raw_predictions) return class_predictions
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a RandomLayer object from the current parameters.
Can you tell what is the following Python 3 function doing def _create_random_layer(self): return RandomLayer(n_hidden=self.n_hidden, alpha=self.alpha, random_state=self.random_state, activation_func=self.activation_func, ...
You are a Python code analyst, evaluating scripts for potential improvements.
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
Create a Python 3 function to fit the model using X y as training data.
As a Python code composer, you craft elegant and concise scripts.
def predict(self, X): """ Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values. """ ...
Implement a function in Python 3 to predict values using the model
You are a Python code generator, capable of creating scripts from specifications.
Fit the model using X y as training data.
How would you explain what the following Python 3 function does def fit(self, X, y): self.classes_ = np.unique(y) y_bin = self.binarizer.fit_transform(y) super(ELMClassifier, self).fit(X, y_bin) return self
As a python code expert, you are capable of creating scripts from specifications.
Compute the accuracy score of the classifier with the given data.
Can you tell what is the following Python 3 function doing def score(self, X, y): from sklearn.metrics import accuracy_score return accuracy_score(y, self.predict(X))
As a Python code composer, you craft elegant and concise scripts.
def compat_serializer_check_is_valid(serializer): """ http://www.django-rest-framework.org/topics/3.0-announcement/#using-is_validraise_exceptiontrue """ if DRFVLIST[0] >= 3: serializer.is_valid(raise_exception=True) else: if not serializer.is_valid(): serializers.ValidationError...
Write a Python 3 function that can check if the serializer is valid.
You are a Python code analyst, evaluating scripts for potential improvements.
def compat_serializer_attr(serializer, obj): """ Required only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer. This is a quick solution but works without breajing anything. """ if DRFVLIST[0] == 3 and DRFVLIST[1] == 1: for i in serializer.instance...
How would you code a function in Python 3 to require only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer. This is a quick solution but works without breajing anything.
You are a Python code analyst, evaluating scripts for potential improvements.
A class decorator that can be used to implement pagination for messages.
Can you tell what is the following Python 3 function doing def compat_pagination_messages(cls): if DRFVLIST[0] == 3 and DRFVLIST[1] >= 1: setattr(cls, "pagination_class", MessagePagination) return cls else: # DRF 2 pagination setattr(cls, "paginate_by", getattr(settings, "DJANGO_...
As a python code expert, you are capable of creating scripts from specifications.
def get_participants(self, obj): """ Allows to define a callback for serializing information about the user. """ # we set the many to many serialization to False, because we only want it with retrieve requests if self.callback is None: return [participant.id for participant in obj.pa...
Write a Python 3 function for returning a list of the user s participants.
As a Python code translator, you convert algorithms and pseudocode into Python.
We say if the message should trigger a notification
Make a summary of the following Python 3 code def get_is_notification(self, obj): try: o = compat_serializer_attr(self, obj) return o.is_notification except Exception: return False
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_readers(self, obj): """ Return the ids of the people who read the message instance. """ try: o = compat_serializer_attr(self, obj) return o.readers except Exception: return []
Write a Python 3 function that can return the ids of the people who read the message instance.
As a python code expert, you are capable of creating scripts from specifications.
Gets all the threads in which the current participant is involved. The method excludes threads where the participant is left.
Make a summary of the following Python 3 code def get_threads_where_participant_is_active(self, participant_id): participations = Participation.objects.\ filter(participant__id=participant_id).\ exclude(date_left__lte=now()).\ distinct().\ select_related('thread')...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_active_threads_involving_all_participants(self, *participant_ids): """ Gets the threads where the specified participants are active and no one has left. """ query = Thread.objects.\ exclude(participation__date_left__lte=now()).\ annotate(count_participants=Count('partici...
How would you implement a function in Python 3 that gets the threads where the specified participants are active and no one has left.
You are a Python code analyst, evaluating scripts for potential improvements.
Get or create a Thread instance for the current participant.
Explain what the following Python 3 code does def get_or_create_thread(self, request, name=None, *participant_ids): # we get the current participant # or create him if he does not exit participant_ids = list(participant_ids) if request.rest_messaging_participant.id not in participant_i...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the number of messages sent in the last 24 hours so we can ensure that the user does not exceed his messaging limits
Here you have a function in Python 3, explain what it does def return_daily_messages_count(self, sender): h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, sent_at__gte=h24).count()
You are a Python code architect, reviewing and designing scalable and efficient code
Check who read each message.
Here you have a function in Python 3, explain what it does def check_who_read(self, messages): # we get the corresponding Participation objects for m in messages: readers = [] for p in m.thread.participation_set.all(): if p.date_last_check is None: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Check if each message requires a notification for the specified participant.
Explain what the following Python 3 code does def check_is_notification(self, participant_id, messages): try: # we get the last check last_check = NotificationCheck.objects.filter(participant__id=participant_id).latest('id').date_check except Exception: # we have no n...
As a python code expert, you are capable of creating scripts from specifications.
def get_lasts_messages_of_threads(self, participant_id, check_who_read=True, check_is_notification=True): """ Returns the last message in each thread """ # we get the last message for each thread # we must query the messages using two queries because only Postgres supports .order_by('thread', '-...
Write a Python 3 script to return the last message in each thread in the given participant.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_all_messages_in_thread(self, participant_id, thread_id, check_who_read=True): """ Returns all the messages in a thread. """ try: messages = Message.objects.filter(thread__id=thread_id).\ order_by('-id').\ select_related('thread').\ pref...
Write a Python 3 function that can return all the messages in a thread.
You are a Python code architect, reviewing and designing scalable and efficient code
Create a new Thread.
How would you explain what the following Python 3 function does def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=compat_get_request_data(request)) compat_serializer_check_is_valid(serializer) self.perform_create(request, serializer) headers = self.get_suc...
As a python code expert, you are capable of creating scripts from specifications.
def mark_thread_as_read(self, request, pk=None): """ Pk is the pk of the Thread to which the messages belong. """ # we get the thread and check for permission thread = Thread.objects.get(id=pk) self.check_object_permissions(request, thread) # we save the date try: ...
Implement a Python 3 function for marking the Thread as read.
As a python code expert, you are capable of creating scripts from specifications.
def process(self, quoted=False): ''' Parse an URL ''' self.p = urlparse(self.raw) self.scheme = self.p.scheme self.netloc = self.p.netloc self.opath = self.p.path if not quoted else quote(self.p.path) self.path = [x for x in self.opath.split('/') if x] self.params...
Write a Python 3 function for parsing a URL and parse its components.
As a Python code translator, you convert algorithms and pseudocode into Python.
def fetch(self, url, encoding=None, force_refetch=False, nocache=False, quiet=True): ''' Fetch a HTML file as binary''' try: if not force_refetch and self.cache is not None and url in self.cache: # try to look for content in cache logging.debug('Retrieving con...
Write a Python 3 function that can fetch a HTML file as binary
You are a Python code analyst, evaluating scripts for potential improvements.
Download a file at url and save it to path.
Can you generate the documentation for the following Python 3 function def download(self, url, path, force_refetch=False, nocache=False): ''' Download a file at $url and save it to $path ''' # Enable cache if os.path.isfile(path): getLogger().info("File exists, download task ...
As a python code expert, you are capable of creating scripts from specifications.
def _pass_list(self) -> List[Dict[str, Any]]: """Extract next stops along the journey.""" stops: List[Dict[str, Any]] = [] for stop in self.journey.PassList.BasicStop: index = stop.get("index") station = stop.Location.Station.HafasName.Text.text station_id = s...
Write a Python 3 function for extracting next stops along the journey.
You are a Python code analyst, evaluating scripts for potential improvements.
def validate(style): """Check `style` against pyout.styling.schema. Parameters ---------- style : dict Style object to validate. Raises ------ StyleValidationError if `style` is not valid. """ try: import jsonschema except ImportError: return try: ...
How would you code a function in Python 3 to validate a dict containing a single item in the sequence.
You are a Python code architect, reviewing and designing scalable and efficient code
def value_type(value): """Classify `value` of bold, color, and underline keys. Parameters ---------- value : style value Returns ------- str, {"simple", "lookup", "re_lookup", "interval"} """ try: keys = list(value.keys()) except AttributeError: return "simple" ...
How would you implement a function in Python 3 that classifies value into a sequence of keys.
As a python code expert, you are capable of creating scripts from specifications.
def _register_mecab_loc(location): ''' Set MeCab binary location ''' global MECAB_LOC if not os.path.isfile(location): logging.getLogger(__name__).warning("Provided mecab binary location does not exist {}".format(location)) logging.getLogger(__name__).info("Mecab binary is switched to: {}"....
Implement a Python 3 function for registering the location of the mecab binary.
As a python code expert, you are capable of creating scripts from specifications.
def run_mecab_process(content, *args, **kwargs): ''' Use subprocess to run mecab ''' encoding = 'utf-8' if 'encoding' not in kwargs else kwargs['encoding'] mecab_loc = kwargs['mecab_loc'] if 'mecab_loc' in kwargs else None if mecab_loc is None: mecab_loc = MECAB_LOC proc_args = [mecab_...
Create a Python 3 function to use subprocess to run mecab
As a python code expert, you are capable of creating scripts from specifications.
def parse(content, *args, **kwargs): ''' Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed ''' global MECAB_PYTHON3 if 'mecab_loc' not in kwargs and MECAB_PYTHON3 and 'MeCab' in globals(): return MeCab.Tagger(*args).parse(content) else: return r...
Write a Python 3 script to use mecab - python3 by default to parse JP text. Fall back to mecab binary app.
You are a Python code analyst, evaluating scripts for potential improvements.
def create_track(self, path_in_ipod=None, checksum=None): """ :param path_in_ipod: the path of audio file in the iPod base :param checksum: CHECKSUM of the audio file in member audiodb :return: a new Track, you may want append it to the playlist.tracks """ if bool(path_in...
Implement a Python 3 function for creating a new track
As a Python code composer, you craft elegant and concise scripts.
return tuple containing text and lang code
Here you have a function in Python 3, explain what it does def voice(self): dbid = self.lldb.dbid text, lang = self._voiceoverdb.get_text_lang(dbid) return text, lang
You are a Python code analyst, evaluating scripts for potential improvements.
def add(self, src): """ store an audio file to storage dir :param src: audio file path :return: checksum value """ if not audio.get_type(src): raise TypeError('The type of this file is not supported.') return super().add(src)
How would you code a function in Python 3 to store an audio file to storage dir
As a Python code analyst, you investigate and solve complex coding mysteries
def _get_cmd(command, arguments): """Merge command with arguments.""" if arguments is None: arguments = [] if command.endswith(".py") or command.endswith(".pyw"): return [sys.executable, command] + list(arguments) else: return [command] + list(arguments)
Create a Python 3 function for merging command with arguments.
As a python code expert, you are capable of creating scripts from specifications.
A command line argument parser.
Can you tell what is the following Python 3 function doing def argparse(argv, parser, arguments): def add_arg(parser, arg_spec): parser.add_argument(arg_spec.name, help=arg_spec.help) return parser parse_request = parser \ .map(lambda i: ArgumentParser(description=i.description)) \ ...
You are a Python code architect, reviewing and designing scalable and efficient code
def gassists_pv(self,dg,dt,dt2,na=None,memlimit=-1): """Calculates p-values of gene i regulating gene j with genotype data assisted method with multiple tests. dg: numpy.ndarray(nt,ns,dtype=gtype(='u1' by default)) Genotype data. Entry dg[i,j] is genotype i's value for sample j. Each value must be among 0,1,...,n...
Write a Python 3 function for calculating P - values of gene i regulating gene j with multiple tests.
You are a Python code generator, capable of creating scripts from specifications.
Calculates the probability of regulating gene i with genotype data assisted method.
Here you have a function in Python 3, explain what it does def _gassist_any(self,dg,dt,dt2,name,na=None,nodiag=False,memlimit=-1): if self.lib is None: raise ValueError("Not initialized.") import numpy as np from .auto import ftype_np,gtype_np from .types import isint if dg.dtype.char!=gtype_np: raise ValueErr...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculates the probability of regulating gene i with genotype data assisted method.
How would you explain what the following Python 3 function does def gassist(self,dg,dt,dt2,na=None,nodiag=False,memlimit=-1): return _gassist_any(self,dg,dt,dt2,"pij_gassist",na=na,nodiag=nodiag,memlimit=memlimit)
As a Python code analyst, you investigate and solve complex coding mysteries
def _cassists_any(self,dc,dt,dt2,name,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous anchor data assisted method, with multiple tests, by converting log likelihoods into probabilities per A for all B. dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous ...
Create a Python 3 function for calculating probability of gene i regulating gene j with continuous anchor data assisted method, with multiple tests, by converting log likelihoods into probabilities per A for all B. dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous anchor data. Entry dc[i,j] is anchor i'...
As a python code expert, you are capable of creating scripts from specifications.
This method calculates the probability of regulating gene i with continuous data assisted method.
Explain what the following Python 3 code does def cassists(self,dc,dt,dt2,nodiag=False,memlimit=-1): return _cassists_any(self,dc,dt,dt2,"pijs_cassist",nodiag=nodiag,memlimit=memlimit)
You are a Python code architect, reviewing and designing scalable and efficient code
Calculates probability of any gene i regulating gene j with continuous data assisted method.
Given the following Python 3 function, write the documentation def _cassist_any(self,dc,dt,dt2,name,nodiag=False,memlimit=-1): if self.lib is None: raise ValueError("Not initialized.") import numpy as np from .auto import ftype_np from .types import isint if dc.dtype.char!=ftype_np or dt.dtype.char!=ftype_np or ...
As a python code expert, you are capable of creating scripts from specifications.
This method calculates the probability of regulating gene i with continuous data assisted method.
Can you generate the documentation for the following Python 3 function def cassist(self,dc,dt,dt2,nodiag=False,memlimit=-1): return _cassist_any(self,dc,dt,dt2,"pij_cassist",nodiag=nodiag,memlimit=memlimit)
As a Python code composer, you craft elegant and concise scripts.
def rank_pv(self,dt,dt2,memlimit=-1): """Calculates p-values of gene i correlating with gene j by converting log likelihoods into probabilities per A for all B. dt: numpy.ndarray(nt,ns,dtype=ftype(='=f4' by default)) Gene expression data for A Entry dt[i,j] is gene i's expression level for sample j. dt2:numpy.ndar...
Write a Python 3 script to calculate the p - values of each gene i correlating with gene j by converting log likelihoods into probabilities per A for all samples for each sample j.
You are a Python code analyst, evaluating scripts for potential improvements.
Calculates the complex flow vector Q_n.
Make a summary of the following Python 3 code def qn(phi, *n): phi = np.ravel(phi) n = np.asarray(n) i_n_phi = np.zeros((n.size, phi.size), dtype=complex) np.outer(n, phi, out=i_n_phi.imag) qn = np.exp(i_n_phi, out=i_n_phi).sum(axis=1) if qn.size == 1: qn = qn[0] return qn
As a Python code composer, you craft elegant and concise scripts.
r Returns the correlation function and the statistical error of the anisotropy.
How would you explain what the following Python 3 function does def correlation(self, n, k, error=False): self._calculate_corr(n, k) corr_nk = self._corr[n][k] if error: self._calculate_corr_err(n, k) return corr_nk, self._corr_err[n][k] else: return ...
You are a Python code generator, capable of creating scripts from specifications.
r Returns the cumulant of an anisotropy n and k - particle cumulant for n.
Can you generate the documentation for the following Python 3 function def cumulant(self, n, k, error=False): corr_nk = self.correlation(n, k, error=error) if k == 2: return corr_nk elif k == 4: corr_n2 = self.correlation(n, 2) return corr_nk - 2*corr_n2*corr...
You are a Python code analyst, evaluating scripts for potential improvements.
r Returns the flow coefficient v_n and v_n_error of the k - particle cumulant.
Can you generate the documentation for the following Python 3 function def flow(self, n, k, error=False, imaginary='nan'): cnk = self.cumulant(n, k, error=error) if error: cnk, cnk_err = cnk vnk_to_k = self._cnk_prefactor[k] * cnk kinv = 1/k if vnk_to_k >= 0: ...
As a Python code composer, you craft elegant and concise scripts.
Evaluate the _unnormalized_ flow PDF.
Here you have a function in Python 3, explain what it does def _pdf(self, phi): pdf = np.inner(self._vn, np.cos(np.outer(phi, self._n))) pdf *= 2. pdf += 1. return pdf
As a Python code analyst, you investigate and solve complex coding mysteries
Generate random numbers in [- pi ).
Here you have a function in Python 3, explain what it does def _uniform_phi(M): return np.random.uniform(-np.pi, np.pi, M)
As a Python code composer, you craft elegant and concise scripts.
r Evaluate the flow PDF at a given angle.
Given the following Python 3 function, write the documentation def pdf(self, phi): if self._n is None: pdf = np.empty_like(phi) pdf.fill(.5/np.pi) return pdf phi = np.asarray(phi) pdf = self._pdf(phi) pdf /= 2.*np.pi return pdf
As a Python code analyst, you investigate and solve complex coding mysteries
Update object with data from source to target.
Given the following Python 3 function, write the documentation def flex_update_obj(source, target, __silent, *fields, **field_map): ''' Pull data from source to target. Target's __dict__ (object data) will be used by default. Otherwise, it'll be treated as a dictionary ''' source_dict = source.__dict__ if h...
You are a Python code analyst, evaluating scripts for potential improvements.
Create an object of type cls using obj_data.
Here you have a function in Python 3, explain what it does def to_obj(cls, obj_data=None, *fields, **field_map): ''' Use obj_data (dict-like) to construct an object of type cls prioritize obj_dict when there are conficts ''' if not fields: fields = obj_data.keys() try: kwargs = {field(f,...
As a Python code composer, you craft elegant and concise scripts.
def is_kana(text): ''' Check if a text if written in kana only (hiragana & katakana) if text is empty then return True ''' if text is None: raise ValueError("text cannot be None") for c in text: if c not in HIRAGANA and c not in KATAKANA: return False return True
Can you implement a function in Python 3 that checks if a text is written in kana only
You are a Python code analyst, evaluating scripts for potential improvements.
def txt2mecab(text, **kwargs): ''' Use mecab to parse one sentence ''' mecab_out = _internal_mecab_parse(text, **kwargs).splitlines() tokens = [MeCabToken.parse(x) for x in mecab_out] return MeCabSent(text, tokens)
How would you code a function in Python 3 to use mecab to parse one sentence
You are a Python code analyst, evaluating scripts for potential improvements.
Use mecab to parse many lines
Can you generate the documentation for the following Python 3 function def lines2mecab(lines, **kwargs): ''' Use mecab to parse many lines ''' sents = [] for line in lines: sent = txt2mecab(line, **kwargs) sents.append(sent) return sents
You are a Python code architect, reviewing and designing scalable and efficient code
Parse the content and return the list of words in the format specified.
Here you have a function in Python 3, explain what it does def analyse(content, splitlines=True, format=None, **kwargs): ''' Japanese text > tokenize/txt/html ''' sents = DekoText.parse(content, splitlines=splitlines, **kwargs) doc = [] final = sents # Generate output if format == 'html': ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Use pos - sc1 - sc2 as POS
Can you tell what is the following Python 3 function doing def pos3(self): ''' Use pos-sc1-sc2 as POS ''' parts = [self.pos] if self.sc1 and self.sc1 != '*': parts.append(self.sc1) if self.sc2 and self.sc2 != '*': parts.append(self.sc2) return '-'....
As a Python code composer, you craft elegant and concise scripts.
def to_ruby(self): ''' Convert one MeCabToken into HTML ''' if self.need_ruby(): surface = self.surface reading = self.reading_hira() return '<ruby><rb>{sur}</rb><rt>{read}</rt></ruby>'.format(sur=surface, read=reading) elif self.is_eos: return '' ...
Implement a function in Python 3 to convert one MeCabToken into HTML
As a python code expert, you are capable of creating scripts from specifications.
Parse a text string and add it to this doc
Here you have a function in Python 3, explain what it does def add(self, sentence_text, **kwargs): ''' Parse a text string and add it to this doc ''' sent = MeCabSent.parse(sentence_text, **kwargs) self.sents.append(sent) return sent
You are a Python code analyst, evaluating scripts for potential improvements.
def smart_text(s, encoding="utf-8", strings_only=False, errors="strict"): """Return a unicode object representing 's'. Treats bytes using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, six.text_type): return s ...
Write a Python 3 function for returning a unicode object representing s.
You are a Python code analyst, evaluating scripts for potential improvements.
def smart_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """Return a bytes version of 's' encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, six.binary_type): if encoding == "utf-8": ...
Write a Python 3 function for returning a bytes version of s encoded as specified in encoding.
You are a Python code analyst, evaluating scripts for potential improvements.
def output(self, response, accepts): """ Formats a response from a view to handle any RDF graphs If a view function returns an RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling """ graph = self.get_graph(response) if graph is not None: ...
How would you code a function in Python 3 to format a response based on any RDF graphs that are accepted by the view function.
You are a Python code architect, reviewing and designing scalable and efficient code
Decorates a view function to return formatted RDF graphs
Make a summary of the following Python 3 code def decorate(self, view): from functools import wraps @wraps(view) def decorated(*args, **kwargs): response = view(*args, **kwargs) accept = self.get_accept() return self.output(response, accept) return decorated
As a python code expert, you are capable of creating scripts from specifications.
def get(self, var, default=None): """Return a value from configuration. Safe version which always returns a default value if the value is not found. """ try: return self.__get(var) except (KeyError, IndexError): return default
Write a Python 3 function for returning a value from configuration. Safe version which always returns a default value.
You are a Python code architect, reviewing and designing scalable and efficient code
def insert(self, var, value, index=None): """Insert at the index. If the index is not provided appends to the end of the list. """ current = self.__get(var) if not isinstance(current, list): raise KeyError("%s: is not a list" % var) if index is None: ...
Create a Python 3 function for inserting a value into the internal list.
As a Python code translator, you convert algorithms and pseudocode into Python.
def keys(self): """Return a merged set of top level keys from all configurations.""" s = set() for config in self.__configs: s |= config.keys() return s
Create a Python 3 function to return a merged set of top level keys from all configurations.
You are a Python code generator, capable of creating scripts from specifications.
Emit a record. Output the record to the file.
Make a summary of the following Python 3 code def emit(self, record): try: if self.shouldRollover(record): self.doRollover() FileHandler.emit(self, record) except (KeyboardInterrupt, SystemExit): raise except Exception: self.handleE...
You are a Python code analyst, evaluating scripts for potential improvements.
def doRollover(self): """Do a rollover, as described in __init__().""" self.stream.close() try: if self.backupCount > 0: tmp_location = "%s.0" % self.baseFilename os.rename(self.baseFilename, tmp_location) for i in range(self.backupCoun...
Can you implement a function in Python 3 that does a rollover of the backup file.
You are a Python code architect, reviewing and designing scalable and efficient code
Determine if rollover should occur.
Make a summary of the following Python 3 code def shouldRollover(self, record): if self.maxBytes > 0: # are we rolling over? msg = "%s\n" % self.format(record) self.stream.seek(0, 2) # due to non-posix-compliant win feature if self.stream.tell() + len(msg) >= self.maxBytes:...
As a Python code analyst, you investigate and solve complex coding mysteries