code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def download_fastqs(self,dest_dir,barcode,overwrite=False): """ Downloads all FASTQ files in the project that match the specified barcode, or if a barcode isn't given, all FASTQ files as in this case it is assumed that this is not a multiplexed experiment. Files are downloaded to the d...
Downloads all FASTQ files in the project that match the specified barcode, or if a barcode isn't given, all FASTQ files as in this case it is assumed that this is not a multiplexed experiment. Files are downloaded to the directory specified by dest_dir. Args: barcode: `str`. ...
Below is the the instruction that describes the task: ### Input: Downloads all FASTQ files in the project that match the specified barcode, or if a barcode isn't given, all FASTQ files as in this case it is assumed that this is not a multiplexed experiment. Files are downloaded to the directory sp...
def wait(sec): ''' Prints a timer with the format 0:00 to the console, and then clears the line when the timer is done ''' while sec > 0: sys.stdout.write('\r' + str(sec//60).zfill(1) + ":" + str(sec % 60).zfill(2) + ' ') sec -= 1 time.sleep(1) ...
Prints a timer with the format 0:00 to the console, and then clears the line when the timer is done
Below is the the instruction that describes the task: ### Input: Prints a timer with the format 0:00 to the console, and then clears the line when the timer is done ### Response: def wait(sec): ''' Prints a timer with the format 0:00 to the console, and then clears the line when the timer is done ...
def abu_profiles(p,ifig=1,xlm=xlm,ylm=(-8,0),show=False,abunds='All',xaxis=xaxis_type, figsize1=(8,8)): '''Four panels of abundance plots Parameters ---------- p : instance mesa_profile instance xlm : tuple xlimits: mass_min, mass_max abus : 'All' plots many 'commonly used'...
Four panels of abundance plots Parameters ---------- p : instance mesa_profile instance xlm : tuple xlimits: mass_min, mass_max abus : 'All' plots many 'commonly used' isotopes up to Fe if they are in your mesa output. otherwise provide a list of lists of desired abus ...
Below is the the instruction that describes the task: ### Input: Four panels of abundance plots Parameters ---------- p : instance mesa_profile instance xlm : tuple xlimits: mass_min, mass_max abus : 'All' plots many 'commonly used' isotopes up to Fe if they are in your mes...
def prepare_venn_axes(ax, centers, radii): ''' Sets properties of the axis object to suit venn plotting. I.e. hides ticks, makes proper xlim/ylim. ''' ax.set_aspect('equal') ax.set_xticks([]) ax.set_yticks([]) min_x = min([centers[i][0] - radii[i] for i in range(len(radii))]) max_x = max...
Sets properties of the axis object to suit venn plotting. I.e. hides ticks, makes proper xlim/ylim.
Below is the the instruction that describes the task: ### Input: Sets properties of the axis object to suit venn plotting. I.e. hides ticks, makes proper xlim/ylim. ### Response: def prepare_venn_axes(ax, centers, radii): ''' Sets properties of the axis object to suit venn plotting. I.e. hides ticks, makes...
def authenticate(self, provider, creds=None, cookies=None): """Authenticate against the specified provider. :param str provider: Authorize against this provider. :param pants.auth.basic_auth.BasicAuthCreds creds: The creds to use. If unspecified, assumes that creds are set in the netrc file. :par...
Authenticate against the specified provider. :param str provider: Authorize against this provider. :param pants.auth.basic_auth.BasicAuthCreds creds: The creds to use. If unspecified, assumes that creds are set in the netrc file. :param pants.auth.cookies.Cookies cookies: Store the auth cookies in th...
Below is the the instruction that describes the task: ### Input: Authenticate against the specified provider. :param str provider: Authorize against this provider. :param pants.auth.basic_auth.BasicAuthCreds creds: The creds to use. If unspecified, assumes that creds are set in the netrc file. :p...
def p_type_list(self, p): '''type_list : type_list type_def | empty''' if p[1] is None: p[0] = [] else: p[1].append(p[2]) p[0] = p[1]
type_list : type_list type_def | empty
Below is the the instruction that describes the task: ### Input: type_list : type_list type_def | empty ### Response: def p_type_list(self, p): '''type_list : type_list type_def | empty''' if p[1] is None: p[0] = [] else: p[1...
def strip_ansi_escape_codes(self, string_buffer): """ Remove any ANSI (VT100) ESC codes from the output http://en.wikipedia.org/wiki/ANSI_escape_code Note: this does not capture ALL possible ANSI Escape Codes only the ones I have encountered Current codes that are filt...
Remove any ANSI (VT100) ESC codes from the output http://en.wikipedia.org/wiki/ANSI_escape_code Note: this does not capture ALL possible ANSI Escape Codes only the ones I have encountered Current codes that are filtered: ESC = '\x1b' or chr(27) ESC = is the escape char...
Below is the the instruction that describes the task: ### Input: Remove any ANSI (VT100) ESC codes from the output http://en.wikipedia.org/wiki/ANSI_escape_code Note: this does not capture ALL possible ANSI Escape Codes only the ones I have encountered Current codes that are filte...
def getImportFromObjects(node): '''Returns a list of objects referenced by import from node''' somenames = [x.asname for x in node.names if x.asname] othernames = [x.name for x in node.names if not x.asname] return somenames+othernames
Returns a list of objects referenced by import from node
Below is the the instruction that describes the task: ### Input: Returns a list of objects referenced by import from node ### Response: def getImportFromObjects(node): '''Returns a list of objects referenced by import from node''' somenames = [x.asname for x in node.names if x.asname] othernames = [x.n...
def bind_key_name(self, function, object_name): """Bind a key to an object name""" for funcname, name in self.name_map.items(): if funcname == function: self.name_map[ funcname] = object_name
Bind a key to an object name
Below is the the instruction that describes the task: ### Input: Bind a key to an object name ### Response: def bind_key_name(self, function, object_name): """Bind a key to an object name""" for funcname, name in self.name_map.items(): if funcname == function: self.n...
def consume(callback, bindings=None, queues=None): """ Start a message consumer that executes the provided callback when messages are received. This API is blocking and will not return until the process receives a signal from the operating system. .. warning:: This API is runs the callback in ...
Start a message consumer that executes the provided callback when messages are received. This API is blocking and will not return until the process receives a signal from the operating system. .. warning:: This API is runs the callback in the IO loop thread. This means if your callback could r...
Below is the the instruction that describes the task: ### Input: Start a message consumer that executes the provided callback when messages are received. This API is blocking and will not return until the process receives a signal from the operating system. .. warning:: This API is runs the callba...
def __on_publish(self, client, userdata, mid): # pylint: disable=W0613 """ A message has been published by a server :param client: Client that received the message :param userdata: User data (unused) :param mid: Message ID """ try: self.__in_f...
A message has been published by a server :param client: Client that received the message :param userdata: User data (unused) :param mid: Message ID
Below is the the instruction that describes the task: ### Input: A message has been published by a server :param client: Client that received the message :param userdata: User data (unused) :param mid: Message ID ### Response: def __on_publish(self, client, userdata, mid): # pylint...
def _connect(self): """ Connects the bot to the server and identifies itself. """ self.conn = self._create_connection() spawn(self.conn.connect) self.set_nick(self.nick) self.cmd(u'USER', u'{0} 3 * {1}'.format(self.nick, self.realname))
Connects the bot to the server and identifies itself.
Below is the the instruction that describes the task: ### Input: Connects the bot to the server and identifies itself. ### Response: def _connect(self): """ Connects the bot to the server and identifies itself. """ self.conn = self._create_connection() spawn(self.conn.connec...
def fmtVersion(*vsnparts): ''' Join a string of parts together with a . separator. Args: *vsnparts: Returns: ''' if len(vsnparts) < 1: raise s_exc.BadTypeValu(valu=repr(vsnparts), name='fmtVersion', mesg='Not enough version parts to form a versi...
Join a string of parts together with a . separator. Args: *vsnparts: Returns:
Below is the the instruction that describes the task: ### Input: Join a string of parts together with a . separator. Args: *vsnparts: Returns: ### Response: def fmtVersion(*vsnparts): ''' Join a string of parts together with a . separator. Args: *vsnparts: Returns: ...
def ranker(self, X, meta): """ Sort the place features list by the score of its relevance. """ # total score is just a sum of each row total_score = X.sum(axis=1).transpose() total_score = np.squeeze(np.asarray(total_score)) # matrix to array ranks = total_score....
Sort the place features list by the score of its relevance.
Below is the the instruction that describes the task: ### Input: Sort the place features list by the score of its relevance. ### Response: def ranker(self, X, meta): """ Sort the place features list by the score of its relevance. """ # total score is just a sum of each row t...
def MRCA(list_of_taxids): """ This gets the most recent common ancester (MRCA) for a list of taxids >>> mylist = [3702, 3649, 3694, 3880] >>> MRCA(mylist) 'rosids' """ from ete2 import Tree t = TaxIDTree(list_of_taxids) t = Tree(str(t), format=8) ancestor = t.get_common_ances...
This gets the most recent common ancester (MRCA) for a list of taxids >>> mylist = [3702, 3649, 3694, 3880] >>> MRCA(mylist) 'rosids'
Below is the the instruction that describes the task: ### Input: This gets the most recent common ancester (MRCA) for a list of taxids >>> mylist = [3702, 3649, 3694, 3880] >>> MRCA(mylist) 'rosids' ### Response: def MRCA(list_of_taxids): """ This gets the most recent common ancester (MRCA) fo...
def blacklistClient(self, clientName: str, reason: str = None, code: int = None): """ Add the client specified by `clientName` to this node's blacklist """ msg = "{} blacklisting client {}".format(self, clientName) if reason: msg += " for reaso...
Add the client specified by `clientName` to this node's blacklist
Below is the the instruction that describes the task: ### Input: Add the client specified by `clientName` to this node's blacklist ### Response: def blacklistClient(self, clientName: str, reason: str = None, code: int = None): """ Add the client specified by `clientName` to ...
def reporter(self): """ Creates a report of the results """ # Create the path in which the reports are stored make_path(self.reportpath) header = 'Strain,Gene,PercentIdentity,Genus,FoldCoverage\n' data = '' with open(os.path.join(self.reportpath, self.anal...
Creates a report of the results
Below is the the instruction that describes the task: ### Input: Creates a report of the results ### Response: def reporter(self): """ Creates a report of the results """ # Create the path in which the reports are stored make_path(self.reportpath) header = 'Strain,Ge...
def get_label_scale(self, min_val, max_val, size): """Dynamically change the scale of the graph (y lable)""" if size < self.SCALE_DENSITY: label_cnt = 1 else: label_cnt = int(size / self.SCALE_DENSITY) try: if max_val >= 100: label = [i...
Dynamically change the scale of the graph (y lable)
Below is the the instruction that describes the task: ### Input: Dynamically change the scale of the graph (y lable) ### Response: def get_label_scale(self, min_val, max_val, size): """Dynamically change the scale of the graph (y lable)""" if size < self.SCALE_DENSITY: label_cnt = 1 ...
def get_kwargs(self, **kwargs): """ Creates a full URL to request based on arguments. :Parametes: - `kwargs`: All keyword arguments to build a kubernetes API endpoint """ version = kwargs.pop("version", "v1") if version == "v1": base = kwargs.pop("...
Creates a full URL to request based on arguments. :Parametes: - `kwargs`: All keyword arguments to build a kubernetes API endpoint
Below is the the instruction that describes the task: ### Input: Creates a full URL to request based on arguments. :Parametes: - `kwargs`: All keyword arguments to build a kubernetes API endpoint ### Response: def get_kwargs(self, **kwargs): """ Creates a full URL to request bas...
def get_from_string(cls, string_phase): """ Convert string value obtained from k8s API to PodPhase enum value :param string_phase: str, phase value from Kubernetes API :return: PodPhase """ if string_phase == 'Pending': return cls.PENDING elif string_...
Convert string value obtained from k8s API to PodPhase enum value :param string_phase: str, phase value from Kubernetes API :return: PodPhase
Below is the the instruction that describes the task: ### Input: Convert string value obtained from k8s API to PodPhase enum value :param string_phase: str, phase value from Kubernetes API :return: PodPhase ### Response: def get_from_string(cls, string_phase): """ Convert string val...
def period(A,M1,M2): """ calculate binary period from separation. Parameters ---------- A : float separation A Rsun. M1, M2 : float M in Msun. Returns ------- p period in days. """ A *= rsun_cm print(A) velocity = np.sqrt(grav_const*msun_...
calculate binary period from separation. Parameters ---------- A : float separation A Rsun. M1, M2 : float M in Msun. Returns ------- p period in days.
Below is the the instruction that describes the task: ### Input: calculate binary period from separation. Parameters ---------- A : float separation A Rsun. M1, M2 : float M in Msun. Returns ------- p period in days. ### Response: def period(A,M1,M2): """ ...
def proximal_translation(prox_factory, y): r"""Calculate the proximal of the translated function F(x - y). Parameters ---------- prox_factory : callable A factory function that, when called with a step size, returns the proximal operator of ``F``. y : Element in domain of ``F``. ...
r"""Calculate the proximal of the translated function F(x - y). Parameters ---------- prox_factory : callable A factory function that, when called with a step size, returns the proximal operator of ``F``. y : Element in domain of ``F``. Returns ------- prox_factory : functi...
Below is the the instruction that describes the task: ### Input: r"""Calculate the proximal of the translated function F(x - y). Parameters ---------- prox_factory : callable A factory function that, when called with a step size, returns the proximal operator of ``F``. y : Element i...
def merge(cls, *args, **kwargs): """Create a new Ent from one or more existing Ents. Keys in the later Ent objects will overwrite the keys of the previous Ents. Later keys of different type than in earlier Ents will be bravely ignored. The following keyword arguments are recogn...
Create a new Ent from one or more existing Ents. Keys in the later Ent objects will overwrite the keys of the previous Ents. Later keys of different type than in earlier Ents will be bravely ignored. The following keyword arguments are recognized: newkeys: boolean value to det...
Below is the the instruction that describes the task: ### Input: Create a new Ent from one or more existing Ents. Keys in the later Ent objects will overwrite the keys of the previous Ents. Later keys of different type than in earlier Ents will be bravely ignored. The following key...
def _deserialize( self, data, fields_dict, error_store, many=False, partial=False, unknown=RAISE, dict_class=dict, index_errors=True, index=None, ): """Deserialize ``data`` based on the schema defined by ``fields_dict``. :param dict data: The data to deserialize. :param dict...
Deserialize ``data`` based on the schema defined by ``fields_dict``. :param dict data: The data to deserialize. :param dict fields_dict: Mapping of field names to :class:`Field` objects. :param ErrorStore error_store: Structure to store errors. :param bool many: Set to `True` if ``data`...
Below is the the instruction that describes the task: ### Input: Deserialize ``data`` based on the schema defined by ``fields_dict``. :param dict data: The data to deserialize. :param dict fields_dict: Mapping of field names to :class:`Field` objects. :param ErrorStore error_store: Structur...
def validate_attr(resource_attr_id, scenario_id, template_id=None): """ Check that a resource attribute satisfies the requirements of all the types of the resource. """ rs = db.DBSession.query(ResourceScenario).\ filter(ResourceScenario.resource_attr_id==resource_attr...
Check that a resource attribute satisfies the requirements of all the types of the resource.
Below is the the instruction that describes the task: ### Input: Check that a resource attribute satisfies the requirements of all the types of the resource. ### Response: def validate_attr(resource_attr_id, scenario_id, template_id=None): """ Check that a resource attribute satisfies the requi...
def python_2_format_compatible(method): """ Handles bytestring and unicode inputs for the `__format__()` method in Python 2. This function has no effect in Python 3. :param method: The `__format__()` method to wrap. :return: The wrapped method. """ if six.PY3: return method def...
Handles bytestring and unicode inputs for the `__format__()` method in Python 2. This function has no effect in Python 3. :param method: The `__format__()` method to wrap. :return: The wrapped method.
Below is the the instruction that describes the task: ### Input: Handles bytestring and unicode inputs for the `__format__()` method in Python 2. This function has no effect in Python 3. :param method: The `__format__()` method to wrap. :return: The wrapped method. ### Response: def python_2_format_co...
def add_self_loops(matrix, loop_value): """ Add self-loops to the matrix by setting the diagonal to loop_value :param matrix: The matrix to add loops to :param loop_value: Value to use for self-loops :returns: The matrix with self-loops """ shape = matrix.shape assert shape[0] =...
Add self-loops to the matrix by setting the diagonal to loop_value :param matrix: The matrix to add loops to :param loop_value: Value to use for self-loops :returns: The matrix with self-loops
Below is the the instruction that describes the task: ### Input: Add self-loops to the matrix by setting the diagonal to loop_value :param matrix: The matrix to add loops to :param loop_value: Value to use for self-loops :returns: The matrix with self-loops ### Response: def add_self_loops(mat...
async def popen_uci(command: Union[str, List[str]], *, setpgrp: bool = False, loop=None, **popen_args: Any) -> Tuple[asyncio.SubprocessTransport, UciProtocol]: """ Spawns and initializes an UCI engine. :param command: Path of the engine executable, or a list including the path and arguments. :p...
Spawns and initializes an UCI engine. :param command: Path of the engine executable, or a list including the path and arguments. :param setpgrp: Open the engine process in a new process group. This will stop signals (such as keyboard interrupts) from propagating from the parent process....
Below is the the instruction that describes the task: ### Input: Spawns and initializes an UCI engine. :param command: Path of the engine executable, or a list including the path and arguments. :param setpgrp: Open the engine process in a new process group. This will stop signals (such as k...
def get_default_field_names(self, declared_fields, model_info): """ Return the default list of field names that will be used if the `Meta.fields` option is not specified. """ return ( [self.url_field_name] + list(declared_fields.keys()) + list(...
Return the default list of field names that will be used if the `Meta.fields` option is not specified.
Below is the the instruction that describes the task: ### Input: Return the default list of field names that will be used if the `Meta.fields` option is not specified. ### Response: def get_default_field_names(self, declared_fields, model_info): """ Return the default list of field names th...
def _reformat_policy(policy): """ Policies returned from boto3 are massive, ugly, and difficult to read. This method flattens and reformats the policy. :param policy: Result from invoking describe_load_balancer_policies(...) :return: Returns a tuple containing policy_name and the reformatted policy...
Policies returned from boto3 are massive, ugly, and difficult to read. This method flattens and reformats the policy. :param policy: Result from invoking describe_load_balancer_policies(...) :return: Returns a tuple containing policy_name and the reformatted policy dict.
Below is the the instruction that describes the task: ### Input: Policies returned from boto3 are massive, ugly, and difficult to read. This method flattens and reformats the policy. :param policy: Result from invoking describe_load_balancer_policies(...) :return: Returns a tuple containing policy_name...
def get_rich_events(self, item): """ In the events there are some common fields with the crate. The name of the field must be the same in the create and in the downloads event so we can filer using it in crate and event at the same time. * Fields that don't change: the field doe...
In the events there are some common fields with the crate. The name of the field must be the same in the create and in the downloads event so we can filer using it in crate and event at the same time. * Fields that don't change: the field does not change with the events in a create so t...
Below is the the instruction that describes the task: ### Input: In the events there are some common fields with the crate. The name of the field must be the same in the create and in the downloads event so we can filer using it in crate and event at the same time. * Fields that don't chang...
def is_user_valid(self, userID): """ Check if this User ID is valid. """ cur = self.conn.cursor() cur.execute('SELECT * FROM users WHERE id=? LIMIT 1', [userID]) results = cur.fetchall() cur.close() return len(results) > 0
Check if this User ID is valid.
Below is the the instruction that describes the task: ### Input: Check if this User ID is valid. ### Response: def is_user_valid(self, userID): """ Check if this User ID is valid. """ cur = self.conn.cursor() cur.execute('SELECT * FROM users WHERE id=? LIMIT 1', [userID]) ...
def splitByConnectivity(actor, maxdepth=100): """ Split a mesh by connectivity and order the pieces by increasing area. :param int maxdepth: only consider this number of mesh parts. .. hint:: |splitmesh| |splitmesh.py|_ """ actor.addIDs() pd = actor.polydata() cf = vtk.vtkConnectivityF...
Split a mesh by connectivity and order the pieces by increasing area. :param int maxdepth: only consider this number of mesh parts. .. hint:: |splitmesh| |splitmesh.py|_
Below is the the instruction that describes the task: ### Input: Split a mesh by connectivity and order the pieces by increasing area. :param int maxdepth: only consider this number of mesh parts. .. hint:: |splitmesh| |splitmesh.py|_ ### Response: def splitByConnectivity(actor, maxdepth=100): """ ...
def filter(pred: Callable, xs: Iterable): """ Applied a predicate to a list returning a :py:class:`PromisedObject` containing the values satisfying the predicate. :param pred: predicate function. :param xs: iterable object. :returns: :py:class:`PromisedObject` """ generator = (x for x i...
Applied a predicate to a list returning a :py:class:`PromisedObject` containing the values satisfying the predicate. :param pred: predicate function. :param xs: iterable object. :returns: :py:class:`PromisedObject`
Below is the the instruction that describes the task: ### Input: Applied a predicate to a list returning a :py:class:`PromisedObject` containing the values satisfying the predicate. :param pred: predicate function. :param xs: iterable object. :returns: :py:class:`PromisedObject` ### Response: def ...
def initialize(self, client, initial_response, deserialization_callback): """Set the initial status of this LRO. :param initial_response: The initial response of the poller :raises: CloudError if initial status is incorrect LRO state """ self._client = client self._respo...
Set the initial status of this LRO. :param initial_response: The initial response of the poller :raises: CloudError if initial status is incorrect LRO state
Below is the the instruction that describes the task: ### Input: Set the initial status of this LRO. :param initial_response: The initial response of the poller :raises: CloudError if initial status is incorrect LRO state ### Response: def initialize(self, client, initial_response, deserialization...
def _map_condition(self, wire_map, condition): """Use the wire_map dict to change the condition tuple's creg name. Args: wire_map (dict): a map from wires to wires condition (tuple): (ClassicalRegister,int) Returns: tuple(ClassicalRegister,int): new condition...
Use the wire_map dict to change the condition tuple's creg name. Args: wire_map (dict): a map from wires to wires condition (tuple): (ClassicalRegister,int) Returns: tuple(ClassicalRegister,int): new condition
Below is the the instruction that describes the task: ### Input: Use the wire_map dict to change the condition tuple's creg name. Args: wire_map (dict): a map from wires to wires condition (tuple): (ClassicalRegister,int) Returns: tuple(ClassicalRegister,int): ne...
def _strand_flag(data): """ 0: unstranded 1: stranded 2: reverse stranded """ strand_flag = {"unstranded": "0", "firststrand": "2", "secondstrand": "1"} stranded = dd.get_strandedness(data) assert stranded in strand_flag, ("%s is not a valid strandedness va...
0: unstranded 1: stranded 2: reverse stranded
Below is the the instruction that describes the task: ### Input: 0: unstranded 1: stranded 2: reverse stranded ### Response: def _strand_flag(data): """ 0: unstranded 1: stranded 2: reverse stranded """ strand_flag = {"unstranded": "0", "firststrand": "2", "sec...
def cublasZherk(handle, uplo, trans, n, k, alpha, A, lda, beta, C, ldc): """ Rank-k operation on Hermitian matrix. """ status = _libcublas.cublasZherk_v2(handle, _CUBLAS_FILL_MODE[uplo], _CUBLAS_OP[trans], ...
Rank-k operation on Hermitian matrix.
Below is the the instruction that describes the task: ### Input: Rank-k operation on Hermitian matrix. ### Response: def cublasZherk(handle, uplo, trans, n, k, alpha, A, lda, beta, C, ldc): """ Rank-k operation on Hermitian matrix. """ status = _libcublas.cublasZherk_v2(handle, ...
def add_progress(self, count, symbol='#', color=None, on_color=None, attrs=None): """Add a section of progress to the progressbar. The progress is captured by "count" and displayed as a fraction of the statusbar width proportional to this count over the total progre...
Add a section of progress to the progressbar. The progress is captured by "count" and displayed as a fraction of the statusbar width proportional to this count over the total progress displayed. The progress will be displayed using the "symbol" character and the foreground and backgroun...
Below is the the instruction that describes the task: ### Input: Add a section of progress to the progressbar. The progress is captured by "count" and displayed as a fraction of the statusbar width proportional to this count over the total progress displayed. The progress will be displayed ...
def simxPackInts(intList): ''' Please have a look at the function description/documentation in the V-REP user manual ''' if sys.version_info[0] == 3: s=bytes() for i in range(len(intList)): s=s+struct.pack('<i',intList[i]) s=bytearray(s) else: s='' ...
Please have a look at the function description/documentation in the V-REP user manual
Below is the the instruction that describes the task: ### Input: Please have a look at the function description/documentation in the V-REP user manual ### Response: def simxPackInts(intList): ''' Please have a look at the function description/documentation in the V-REP user manual ''' if sys.v...
def get_cutoff_indices(flow, fhigh, df, N): """ Gets the indices of a frequency series at which to stop an overlap calculation. Parameters ---------- flow: float The frequency (in Hz) of the lower index. fhigh: float The frequency (in Hz) of the upper index. df: float ...
Gets the indices of a frequency series at which to stop an overlap calculation. Parameters ---------- flow: float The frequency (in Hz) of the lower index. fhigh: float The frequency (in Hz) of the upper index. df: float The frequency step (in Hz) of the frequency series...
Below is the the instruction that describes the task: ### Input: Gets the indices of a frequency series at which to stop an overlap calculation. Parameters ---------- flow: float The frequency (in Hz) of the lower index. fhigh: float The frequency (in Hz) of the upper index. ...
def rename_directory(db, user_id, old_api_path, new_api_path): """ Rename a directory. """ old_db_path = from_api_dirname(old_api_path) new_db_path = from_api_dirname(new_api_path) if old_db_path == '/': raise RenameRoot('Renaming the root directory is not permitted.') # Overwritin...
Rename a directory.
Below is the the instruction that describes the task: ### Input: Rename a directory. ### Response: def rename_directory(db, user_id, old_api_path, new_api_path): """ Rename a directory. """ old_db_path = from_api_dirname(old_api_path) new_db_path = from_api_dirname(new_api_path) if old_db_...
def decoder(self, response: bytes): """编码请求为bytes. 检查是否使用debug模式和是否对数据进行压缩.之后根据状态将python字典形式的请求编码为字节串. Parameters: response (bytes): - 响应的字节串编码 Return: (Dict[str, Any]): - python字典形式的响应 """ response = response[:-(len(self.SEPARATOR))] ...
编码请求为bytes. 检查是否使用debug模式和是否对数据进行压缩.之后根据状态将python字典形式的请求编码为字节串. Parameters: response (bytes): - 响应的字节串编码 Return: (Dict[str, Any]): - python字典形式的响应
Below is the the instruction that describes the task: ### Input: 编码请求为bytes. 检查是否使用debug模式和是否对数据进行压缩.之后根据状态将python字典形式的请求编码为字节串. Parameters: response (bytes): - 响应的字节串编码 Return: (Dict[str, Any]): - python字典形式的响应 ### Response: def decoder(self, response: bytes): ...
def distutils_old_autosemver_case(metadata, attr, value): """DEPRECATED""" metadata = distutils_default_case(metadata, attr, value) create_changelog(bugtracker_url=getattr(metadata, 'bugtracker_url', '')) return metadata
DEPRECATED
Below is the the instruction that describes the task: ### Input: DEPRECATED ### Response: def distutils_old_autosemver_case(metadata, attr, value): """DEPRECATED""" metadata = distutils_default_case(metadata, attr, value) create_changelog(bugtracker_url=getattr(metadata, 'bugtracker_url', '')) retu...
def convert_flux(wavelengths, fluxes, out_flux_unit, **kwargs): """Perform conversion for :ref:`supported flux units <synphot-flux-units>`. Parameters ---------- wavelengths : array-like or `~astropy.units.quantity.Quantity` Wavelength values. If not a Quantity, assumed to be in Angstro...
Perform conversion for :ref:`supported flux units <synphot-flux-units>`. Parameters ---------- wavelengths : array-like or `~astropy.units.quantity.Quantity` Wavelength values. If not a Quantity, assumed to be in Angstrom. fluxes : array-like or `~astropy.units.quantity.Quantity` ...
Below is the the instruction that describes the task: ### Input: Perform conversion for :ref:`supported flux units <synphot-flux-units>`. Parameters ---------- wavelengths : array-like or `~astropy.units.quantity.Quantity` Wavelength values. If not a Quantity, assumed to be in Angstrom....
def init_logging(debug=False, logfile=None): """Initialize logging.""" loglevel = logging.DEBUG if debug else logging.INFO logformat = '%(asctime)s %(name)s: %(levelname)s: %(message)s' formatter = logging.Formatter(logformat) stderr = logging.StreamHandler() stderr.setFormatter(formatter) ...
Initialize logging.
Below is the the instruction that describes the task: ### Input: Initialize logging. ### Response: def init_logging(debug=False, logfile=None): """Initialize logging.""" loglevel = logging.DEBUG if debug else logging.INFO logformat = '%(asctime)s %(name)s: %(levelname)s: %(message)s' formatter = lo...
def is_ipynb(): """Return True if the module is running in IPython kernel, False if in IPython shell or other Python shell. Copied from: http://stackoverflow.com/a/37661854/1592810 There are other methods there too >>> is_ipynb() False """ try: shell = get_ipython().__class__....
Return True if the module is running in IPython kernel, False if in IPython shell or other Python shell. Copied from: http://stackoverflow.com/a/37661854/1592810 There are other methods there too >>> is_ipynb() False
Below is the the instruction that describes the task: ### Input: Return True if the module is running in IPython kernel, False if in IPython shell or other Python shell. Copied from: http://stackoverflow.com/a/37661854/1592810 There are other methods there too >>> is_ipynb() False ### Response...
def createExpenseItemsForEvents(request=None, datetimeTuple=None, rule=None, event=None): ''' For each StaffMember-related Repeated Expense Rule, look for EventStaffMember instances in the designated time window that do not already have expenses associated with them. For hourly rental expenses, the...
For each StaffMember-related Repeated Expense Rule, look for EventStaffMember instances in the designated time window that do not already have expenses associated with them. For hourly rental expenses, then generate new expenses that are associated with this rule. For non-hourly expenses, generate new ...
Below is the the instruction that describes the task: ### Input: For each StaffMember-related Repeated Expense Rule, look for EventStaffMember instances in the designated time window that do not already have expenses associated with them. For hourly rental expenses, then generate new expenses that are ...
def add_highlights_docs(docs): """ "highlight": { "knowledge_graph.title.value": [ "Before 1 January 2018, will <em>South</em> <em>Korea</em> file a World Trade Organization dispute against the United States related to solar panels?" ] } """ if not...
"highlight": { "knowledge_graph.title.value": [ "Before 1 January 2018, will <em>South</em> <em>Korea</em> file a World Trade Organization dispute against the United States related to solar panels?" ] }
Below is the the instruction that describes the task: ### Input: "highlight": { "knowledge_graph.title.value": [ "Before 1 January 2018, will <em>South</em> <em>Korea</em> file a World Trade Organization dispute against the United States related to solar panels?" ] } ### Resp...
def resolve_self_references(self, rules): """Resolves `$self` references to actual application name in security group rules.""" with suppress(KeyError): rule = rules.pop('$self') rules[self.app_name] = rule return rules
Resolves `$self` references to actual application name in security group rules.
Below is the the instruction that describes the task: ### Input: Resolves `$self` references to actual application name in security group rules. ### Response: def resolve_self_references(self, rules): """Resolves `$self` references to actual application name in security group rules.""" with suppres...
def fold(self, predicate): """Takes a predicate and applies it to each node starting from the leaves and making the return value propagate.""" childs = {x:y.fold(predicate) for (x,y) in self._attributes.items() if isinstance(y, SerializableTypedAttributesHolder)} return...
Takes a predicate and applies it to each node starting from the leaves and making the return value propagate.
Below is the the instruction that describes the task: ### Input: Takes a predicate and applies it to each node starting from the leaves and making the return value propagate. ### Response: def fold(self, predicate): """Takes a predicate and applies it to each node starting from the leaves a...
def dbg_repr(self, max_display=10): """ Debugging output of this slice. :param max_display: The maximum number of SimRun slices to show. :return: A string representation. """ s = repr(self) + "\n" if len(self.chosen_statements) > max_display: ...
Debugging output of this slice. :param max_display: The maximum number of SimRun slices to show. :return: A string representation.
Below is the the instruction that describes the task: ### Input: Debugging output of this slice. :param max_display: The maximum number of SimRun slices to show. :return: A string representation. ### Response: def dbg_repr(self, max_display=10): """ Debugging output of t...
def exists(self, doc_id, rev_id=''): ''' a method to determine if document exists :param doc_id: string with id of document in bucket :param rev_id: [optional] string with revision id of document in bucket :return: boolean indicating existence of docume...
a method to determine if document exists :param doc_id: string with id of document in bucket :param rev_id: [optional] string with revision id of document in bucket :return: boolean indicating existence of document
Below is the the instruction that describes the task: ### Input: a method to determine if document exists :param doc_id: string with id of document in bucket :param rev_id: [optional] string with revision id of document in bucket :return: boolean indicating existence of documen...
def inner(self, x1, x2): """Return the weighted inner product of ``x1`` and ``x2``. Parameters ---------- x1, x2 : `NumpyTensor` Tensors whose inner product is calculated. Returns ------- inner : float or complex The inner product of the ...
Return the weighted inner product of ``x1`` and ``x2``. Parameters ---------- x1, x2 : `NumpyTensor` Tensors whose inner product is calculated. Returns ------- inner : float or complex The inner product of the two provided tensors.
Below is the the instruction that describes the task: ### Input: Return the weighted inner product of ``x1`` and ``x2``. Parameters ---------- x1, x2 : `NumpyTensor` Tensors whose inner product is calculated. Returns ------- inner : float or complex ...
def _is_target_a_directory(link, rel_target): """ If creating a symlink from link to a target, determine if target is a directory (relative to dirname(link)). """ target = os.path.join(os.path.dirname(link), rel_target) return os.path.isdir(target)
If creating a symlink from link to a target, determine if target is a directory (relative to dirname(link)).
Below is the the instruction that describes the task: ### Input: If creating a symlink from link to a target, determine if target is a directory (relative to dirname(link)). ### Response: def _is_target_a_directory(link, rel_target): """ If creating a symlink from link to a target, determine if target is a dir...
def _process_response(self, response): """ Update the internal state with the data from the response """ assert self._state == self._STATE_RUNNING, "Should be running if processing response" cols = None data = [] for r in response: if not cols: cols = ...
Update the internal state with the data from the response
Below is the the instruction that describes the task: ### Input: Update the internal state with the data from the response ### Response: def _process_response(self, response): """ Update the internal state with the data from the response """ assert self._state == self._STATE_RUNNING, "Should be run...
def if_stmt(self, if_loc, test, if_colon_loc, body, elifs, else_opt): """if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]""" stmt = ast.If(orelse=[], else_loc=None, else_colon_loc=None) if else_opt: stmt.else_loc, stmt.else_colon_loc, st...
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
Below is the the instruction that describes the task: ### Input: if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] ### Response: def if_stmt(self, if_loc, test, if_colon_loc, body, elifs, else_opt): """if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]""" ...
def maybe_start_recording(tokens, index): """Return a new _RSTCommentBlockRecorder when its time to record.""" if tokens[index].type == TokenType.BeginRSTComment: return _RSTCommentBlockRecorder(index, tokens[index].line) return None
Return a new _RSTCommentBlockRecorder when its time to record.
Below is the the instruction that describes the task: ### Input: Return a new _RSTCommentBlockRecorder when its time to record. ### Response: def maybe_start_recording(tokens, index): """Return a new _RSTCommentBlockRecorder when its time to record.""" if tokens[index].type == TokenType.BeginRSTCom...
def find_one_raw(self, resource, _id): """Find document by id.""" return self._find_by_id(resource=resource, _id=_id)
Find document by id.
Below is the the instruction that describes the task: ### Input: Find document by id. ### Response: def find_one_raw(self, resource, _id): """Find document by id.""" return self._find_by_id(resource=resource, _id=_id)
def fetch_model(self, source: str, file: Union[str, BinaryIO], chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None: """Download the model from GCS.""" download_http(source, file, self._log, chunk_size)
Download the model from GCS.
Below is the the instruction that describes the task: ### Input: Download the model from GCS. ### Response: def fetch_model(self, source: str, file: Union[str, BinaryIO], chunk_size: int=DEFAULT_DOWNLOAD_CHUNK_SIZE) -> None: """Download the model from GCS.""" download_http(sourc...
def _norm_perm_list_from_perm_dict(self, perm_dict): """Return a minimal, ordered, hashable list of subjects and permissions.""" high_perm_dict = self._highest_perm_dict_from_perm_dict(perm_dict) return [ [k, list(sorted(high_perm_dict[k]))] for k in ORDERED_PERM_LIST ...
Return a minimal, ordered, hashable list of subjects and permissions.
Below is the the instruction that describes the task: ### Input: Return a minimal, ordered, hashable list of subjects and permissions. ### Response: def _norm_perm_list_from_perm_dict(self, perm_dict): """Return a minimal, ordered, hashable list of subjects and permissions.""" high_perm_dict = self...
def _calculate_sun_vector(self): """Calculate sun vector for this sun.""" z_axis = Vector3(0., 0., -1.) x_axis = Vector3(1., 0., 0.) north_vector = Vector3(0., 1., 0.) # rotate north vector based on azimuth, altitude, and north _sun_vector = north_vector \ .r...
Calculate sun vector for this sun.
Below is the the instruction that describes the task: ### Input: Calculate sun vector for this sun. ### Response: def _calculate_sun_vector(self): """Calculate sun vector for this sun.""" z_axis = Vector3(0., 0., -1.) x_axis = Vector3(1., 0., 0.) north_vector = Vector3(0., 1., 0.) ...
def open(cls, filename, crs=None): """Creates a FileCollection from a file in disk. Parameters ---------- filename : str Path of the file to read. crs : CRS overrides the crs of the collection, this funtion will not reprojects """ with fi...
Creates a FileCollection from a file in disk. Parameters ---------- filename : str Path of the file to read. crs : CRS overrides the crs of the collection, this funtion will not reprojects
Below is the the instruction that describes the task: ### Input: Creates a FileCollection from a file in disk. Parameters ---------- filename : str Path of the file to read. crs : CRS overrides the crs of the collection, this funtion will not reprojects ### R...
def payout(address): """returns all received transactions between the address and registered delegate accounts ORDER by timestamp ASC.""" qry = DbCursor().execute_and_fetchall(""" SELECT DISTINCT transactions."id", transactions."amount", transactions."times...
returns all received transactions between the address and registered delegate accounts ORDER by timestamp ASC.
Below is the the instruction that describes the task: ### Input: returns all received transactions between the address and registered delegate accounts ORDER by timestamp ASC. ### Response: def payout(address): """returns all received transactions between the address and registered delegate account...
def unpack_2to8(data): """ Promote 2-bit unisgned data into 8-bit unsigned data. Args: data: Numpy array with dtype == uint8 Notes: DATA MUST BE LOADED as np.array() with dtype='uint8'. This works with some clever shifting and AND / OR operations. Data is LOADED as 8-bit, ...
Promote 2-bit unisgned data into 8-bit unsigned data. Args: data: Numpy array with dtype == uint8 Notes: DATA MUST BE LOADED as np.array() with dtype='uint8'. This works with some clever shifting and AND / OR operations. Data is LOADED as 8-bit, then promoted to 32-bits: ...
Below is the the instruction that describes the task: ### Input: Promote 2-bit unisgned data into 8-bit unsigned data. Args: data: Numpy array with dtype == uint8 Notes: DATA MUST BE LOADED as np.array() with dtype='uint8'. This works with some clever shifting and AND / OR operati...
def transform(self, m): """Replace point by its transformation with matrix-like m.""" if len(m) != 6: raise ValueError("bad sequ. length") self.x, self.y = TOOLS._transform_point(self, m) return self
Replace point by its transformation with matrix-like m.
Below is the the instruction that describes the task: ### Input: Replace point by its transformation with matrix-like m. ### Response: def transform(self, m): """Replace point by its transformation with matrix-like m.""" if len(m) != 6: raise ValueError("bad sequ. length") self....
def generate_rpn_proposals(boxes, scores, img_shape, pre_nms_topk, post_nms_topk=None): """ Sample RPN proposals by the following steps: 1. Pick top k1 by scores 2. NMS them 3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output. Args: ...
Sample RPN proposals by the following steps: 1. Pick top k1 by scores 2. NMS them 3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output. Args: boxes: nx4 float dtype, the proposal boxes. Decoded to floatbox already scores: n float, the logits img_shape:...
Below is the the instruction that describes the task: ### Input: Sample RPN proposals by the following steps: 1. Pick top k1 by scores 2. NMS them 3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output. Args: boxes: nx4 float dtype, the proposal boxes. Decoded to fl...
def run_program(program, *args): """Wrap subprocess.check_output to make life easier.""" real_args = [program] real_args.extend(args) logging.debug(_('check_output arguments: %s'), real_args) check_output(real_args, universal_newlines=True)
Wrap subprocess.check_output to make life easier.
Below is the the instruction that describes the task: ### Input: Wrap subprocess.check_output to make life easier. ### Response: def run_program(program, *args): """Wrap subprocess.check_output to make life easier.""" real_args = [program] real_args.extend(args) logging.debug(_('check_output argume...
def prepend(self, frame_p): """ Push frame to the front of the message, i.e. before all other frames. Message takes ownership of frame, will destroy it when message is sent. Returns 0 on success, -1 on error. Deprecates zmsg_push, which did not nullify the caller's frame reference. """ r...
Push frame to the front of the message, i.e. before all other frames. Message takes ownership of frame, will destroy it when message is sent. Returns 0 on success, -1 on error. Deprecates zmsg_push, which did not nullify the caller's frame reference.
Below is the the instruction that describes the task: ### Input: Push frame to the front of the message, i.e. before all other frames. Message takes ownership of frame, will destroy it when message is sent. Returns 0 on success, -1 on error. Deprecates zmsg_push, which did not nullify the caller's frame reference. ...
def uninstall_task(self, name): """Removes the named task from this goal. Allows external plugins to modify the execution plan. Use with caution. Note: Does not relax a serialization requirement that originated from the uninstalled task's install() call. :API: public """ if name in self._...
Removes the named task from this goal. Allows external plugins to modify the execution plan. Use with caution. Note: Does not relax a serialization requirement that originated from the uninstalled task's install() call. :API: public
Below is the the instruction that describes the task: ### Input: Removes the named task from this goal. Allows external plugins to modify the execution plan. Use with caution. Note: Does not relax a serialization requirement that originated from the uninstalled task's install() call. :API: public...
def set_model_domain(model, domain): """ Sets the domain on the ONNX model. :param model: instance of an ONNX model :param domain: string containing the domain name of the model Example: :: from onnxmltools.utils import set_model_domain onnx_model = load_model("SqueezeNet.onnx...
Sets the domain on the ONNX model. :param model: instance of an ONNX model :param domain: string containing the domain name of the model Example: :: from onnxmltools.utils import set_model_domain onnx_model = load_model("SqueezeNet.onnx") set_model_domain(onnx_model, "com.acme...
Below is the the instruction that describes the task: ### Input: Sets the domain on the ONNX model. :param model: instance of an ONNX model :param domain: string containing the domain name of the model Example: :: from onnxmltools.utils import set_model_domain onnx_model = load_mo...
def set_nbytes(self, key, nbytes=None): """ Set the `nbytes` attribute on the HDF5 object identified by `key`. """ obj = super().__getitem__(key) if nbytes is not None: # size set from outside obj.attrs['nbytes'] = nbytes else: # recursively determine the si...
Set the `nbytes` attribute on the HDF5 object identified by `key`.
Below is the the instruction that describes the task: ### Input: Set the `nbytes` attribute on the HDF5 object identified by `key`. ### Response: def set_nbytes(self, key, nbytes=None): """ Set the `nbytes` attribute on the HDF5 object identified by `key`. """ obj = super().__getite...
def run_ec2_import(self, config_file_location, description, region='us-east-1'): """ Runs the command to import an uploaded vmdk to aws ec2 :param config_file_location: config file of import param location :param description: description to attach to the import task :return: the ...
Runs the command to import an uploaded vmdk to aws ec2 :param config_file_location: config file of import param location :param description: description to attach to the import task :return: the import task id for the given ami
Below is the the instruction that describes the task: ### Input: Runs the command to import an uploaded vmdk to aws ec2 :param config_file_location: config file of import param location :param description: description to attach to the import task :return: the import task id for the given ami...
def append(self, val): """Connect any new results to the resultset. This is where all the heavy lifting is done for creating results: - We add a datatype here, so that each result can handle validation etc independently. This is so that scraper authors don't need to worry about...
Connect any new results to the resultset. This is where all the heavy lifting is done for creating results: - We add a datatype here, so that each result can handle validation etc independently. This is so that scraper authors don't need to worry about creating and passing around datat...
Below is the the instruction that describes the task: ### Input: Connect any new results to the resultset. This is where all the heavy lifting is done for creating results: - We add a datatype here, so that each result can handle validation etc independently. This is so that scraper author...
def report_comment_abuse(context, obj): """ Checks whether a user can report abuse (has not liked comment previously) or has reported abuse previously and renders appropriate response. If requesting user is part of the 'Moderators' group a vote equal to ABUSE_CUTOFF setting will be made, thereby im...
Checks whether a user can report abuse (has not liked comment previously) or has reported abuse previously and renders appropriate response. If requesting user is part of the 'Moderators' group a vote equal to ABUSE_CUTOFF setting will be made, thereby immediately marking the comment as abusive.
Below is the the instruction that describes the task: ### Input: Checks whether a user can report abuse (has not liked comment previously) or has reported abuse previously and renders appropriate response. If requesting user is part of the 'Moderators' group a vote equal to ABUSE_CUTOFF setting will be...
def sync_repo_hook(self, repo_id): """Sync a GitHub repo's hook with the locally stored repo.""" # Get the hook that we may have set in the past gh_repo = self.api.repository_with_id(repo_id) hooks = (hook.id for hook in gh_repo.hooks() if hook.config.get('url', '') == s...
Sync a GitHub repo's hook with the locally stored repo.
Below is the the instruction that describes the task: ### Input: Sync a GitHub repo's hook with the locally stored repo. ### Response: def sync_repo_hook(self, repo_id): """Sync a GitHub repo's hook with the locally stored repo.""" # Get the hook that we may have set in the past gh_repo = s...
def alphabeta(game, alpha_beta=(-float('inf'), float('inf')), player=dominoes.players.identity): ''' Runs minimax search with alpha-beta pruning on the provided game. :param Game game: game to search :param tuple alpha_beta: a tuple of two floats that indicate ...
Runs minimax search with alpha-beta pruning on the provided game. :param Game game: game to search :param tuple alpha_beta: a tuple of two floats that indicate the initial values of alpha and beta, respectively. The default is (-inf, inf). :param ca...
Below is the the instruction that describes the task: ### Input: Runs minimax search with alpha-beta pruning on the provided game. :param Game game: game to search :param tuple alpha_beta: a tuple of two floats that indicate the initial values of alpha and beta, ...
def _parse_docline(self, line, container): """Parses a single line of code following a docblock to see if it as a valid code element that can be decorated. If so, return the name of the code element.""" match = self.RE_DECOR.match(line) if match is not None: return "{...
Parses a single line of code following a docblock to see if it as a valid code element that can be decorated. If so, return the name of the code element.
Below is the the instruction that describes the task: ### Input: Parses a single line of code following a docblock to see if it as a valid code element that can be decorated. If so, return the name of the code element. ### Response: def _parse_docline(self, line, container): """Parses a sin...
def team_events(self, team, year=None, simple=False, keys=False): """ Get team events a team has participated in. :param team: Team to get events for. :param year: Year to get events from. :param simple: Get only vital data. :param keys: Get just the keys of the events. ...
Get team events a team has participated in. :param team: Team to get events for. :param year: Year to get events from. :param simple: Get only vital data. :param keys: Get just the keys of the events. Set to True if you only need the keys of each event and not their full data. :...
Below is the the instruction that describes the task: ### Input: Get team events a team has participated in. :param team: Team to get events for. :param year: Year to get events from. :param simple: Get only vital data. :param keys: Get just the keys of the events. Set to True if yo...
def lookup(self): """ Prints name, author, size and age """ print "%s by %s, size: %s, uploaded %s ago" % (self.name, self.author, self.size, self.age)
Prints name, author, size and age
Below is the the instruction that describes the task: ### Input: Prints name, author, size and age ### Response: def lookup(self): """ Prints name, author, size and age """ print "%s by %s, size: %s, uploaded %s ago" % (self.name, self.author, ...
def pdf_Gates_Gaudin_Schuhman_basis_integral(d, d_characteristic, m, n): r'''Calculates the integral of the multiplication of d^n by the Gates, Gaudin and Schuhman (GGS) model given a particle diameter `d`, characteristic (maximum) particle diameter `d_characteristic`, and exponent `m`. .. mat...
r'''Calculates the integral of the multiplication of d^n by the Gates, Gaudin and Schuhman (GGS) model given a particle diameter `d`, characteristic (maximum) particle diameter `d_characteristic`, and exponent `m`. .. math:: \int d^n\cdot q(d)\; dd =\frac{m}{m+n} d^n \left(\frac{d} ...
Below is the the instruction that describes the task: ### Input: r'''Calculates the integral of the multiplication of d^n by the Gates, Gaudin and Schuhman (GGS) model given a particle diameter `d`, characteristic (maximum) particle diameter `d_characteristic`, and exponent `m`. .. math:: ...
def delete_submission(self, submission_id): """Deletes a Clinvar submission object, along with all associated clinvar objects (variants and casedata) Args: submission_id(str): the ID of the submission to be deleted Returns: deleted_objects(int): the numb...
Deletes a Clinvar submission object, along with all associated clinvar objects (variants and casedata) Args: submission_id(str): the ID of the submission to be deleted Returns: deleted_objects(int): the number of associated objects removed (variants and/or cased...
Below is the the instruction that describes the task: ### Input: Deletes a Clinvar submission object, along with all associated clinvar objects (variants and casedata) Args: submission_id(str): the ID of the submission to be deleted Returns: deleted_objects(...
def percent_bandwidth(data, period, std=2.0): """ Percent Bandwidth. Formula: %_bw = data() - l_bb() / bb_range() """ catch_errors.check_for_period_error(data, period) period = int(period) percent_bandwidth = ((np.array(data) - lower_bollinger_band(data, period...
Percent Bandwidth. Formula: %_bw = data() - l_bb() / bb_range()
Below is the the instruction that describes the task: ### Input: Percent Bandwidth. Formula: %_bw = data() - l_bb() / bb_range() ### Response: def percent_bandwidth(data, period, std=2.0): """ Percent Bandwidth. Formula: %_bw = data() - l_bb() / bb_range() """ catch_errors.check_f...
def next(self): """Next point in iteration """ if self.count < len(self.reservoir): self.count += 1 return self.reservoir[self.count-1] raise StopIteration("Reservoir exhausted")
Next point in iteration
Below is the the instruction that describes the task: ### Input: Next point in iteration ### Response: def next(self): """Next point in iteration """ if self.count < len(self.reservoir): self.count += 1 return self.reservoir[self.count-1] raise StopIteration...
def init(cls, repo_dir=None, temp=False, initial_commit=False): """Run `git init` in the repo_dir. Defaults to current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for you and the repository will be initialized. The tempdir is ...
Run `git init` in the repo_dir. Defaults to current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for you and the repository will be initialized. The tempdir is scheduled for deletion (when the process exits) through an exit fun...
Below is the the instruction that describes the task: ### Input: Run `git init` in the repo_dir. Defaults to current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for you and the repository will be initialized. The tempdir is schedu...
def get_asset_composition_design_session(self): """Gets the session for creating asset compositions. return: (osid.repository.AssetCompositionDesignSession) - an AssetCompositionDesignSession raise: OperationFailed - unable to complete request raise: Unimplemented - su...
Gets the session for creating asset compositions. return: (osid.repository.AssetCompositionDesignSession) - an AssetCompositionDesignSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_asset_composition_design() is false ...
Below is the the instruction that describes the task: ### Input: Gets the session for creating asset compositions. return: (osid.repository.AssetCompositionDesignSession) - an AssetCompositionDesignSession raise: OperationFailed - unable to complete request raise: Unimplem...
def variables(self): """Returns the list of all tf.Variables created by module instantiation.""" result = [] for _, value in sorted(self.variable_map.items()): if isinstance(value, list): result.extend(value) else: result.append(value) return result
Returns the list of all tf.Variables created by module instantiation.
Below is the the instruction that describes the task: ### Input: Returns the list of all tf.Variables created by module instantiation. ### Response: def variables(self): """Returns the list of all tf.Variables created by module instantiation.""" result = [] for _, value in sorted(self.variable_map.item...
def genExamplePlanet(binaryLetter=''): """ Creates a fake planet with some defaults :param `binaryLetter`: host star is part of a binary with letter binaryletter :return: """ planetPar = PlanetParameters() planetPar.addParam('discoverymethod', 'transit') planetPar.addParam('discoveryyear', ...
Creates a fake planet with some defaults :param `binaryLetter`: host star is part of a binary with letter binaryletter :return:
Below is the the instruction that describes the task: ### Input: Creates a fake planet with some defaults :param `binaryLetter`: host star is part of a binary with letter binaryletter :return: ### Response: def genExamplePlanet(binaryLetter=''): """ Creates a fake planet with some defaults :param `...
def deserialize(self, apic_frame): """Convert APIC frame into Image.""" return Image(data=apic_frame.data, desc=apic_frame.desc, type=apic_frame.type)
Convert APIC frame into Image.
Below is the the instruction that describes the task: ### Input: Convert APIC frame into Image. ### Response: def deserialize(self, apic_frame): """Convert APIC frame into Image.""" return Image(data=apic_frame.data, desc=apic_frame.desc, type=apic_frame.type)
def domain_of_validity(self): """ Return the domain of validity for this CRS as: (west, east, south, north). For example:: >>> print(get(21781).domain_of_validity()) [5.96, 10.49, 45.82, 47.81] """ # TODO: Generalise interface to return a polyg...
Return the domain of validity for this CRS as: (west, east, south, north). For example:: >>> print(get(21781).domain_of_validity()) [5.96, 10.49, 45.82, 47.81]
Below is the the instruction that describes the task: ### Input: Return the domain of validity for this CRS as: (west, east, south, north). For example:: >>> print(get(21781).domain_of_validity()) [5.96, 10.49, 45.82, 47.81] ### Response: def domain_of_validity(self): ...
def documents(cls, filter=None, **kwargs): """ Returns a list of Documents if any document is filtered """ documents = [cls(document) for document in cls.find(filter, **kwargs)] return [document for document in documents if document.document]
Returns a list of Documents if any document is filtered
Below is the the instruction that describes the task: ### Input: Returns a list of Documents if any document is filtered ### Response: def documents(cls, filter=None, **kwargs): """ Returns a list of Documents if any document is filtered """ documents = [cls(document) for document i...
def romanize(number): """Convert `number` to a Roman numeral.""" roman = [] for numeral, value in NUMERALS: times, number = divmod(number, value) roman.append(times * numeral) return ''.join(roman)
Convert `number` to a Roman numeral.
Below is the the instruction that describes the task: ### Input: Convert `number` to a Roman numeral. ### Response: def romanize(number): """Convert `number` to a Roman numeral.""" roman = [] for numeral, value in NUMERALS: times, number = divmod(number, value) roman.append(times * nume...
def add_coverage(self, qname, sname, qcover, scover=None): """Add percentage coverage values to self.alignment_coverage.""" self.alignment_coverage.loc[qname, sname] = qcover if scover: self.alignment_coverage.loc[sname, qname] = scover
Add percentage coverage values to self.alignment_coverage.
Below is the the instruction that describes the task: ### Input: Add percentage coverage values to self.alignment_coverage. ### Response: def add_coverage(self, qname, sname, qcover, scover=None): """Add percentage coverage values to self.alignment_coverage.""" self.alignment_coverage.loc[qname, sn...
def get_facet_objects_serializer(self, *args, **kwargs): """ Return the serializer instance which should be used for serializing faceted objects. """ facet_objects_serializer_class = self.get_facet_objects_serializer_class() kwargs["context"] = self.get_serializer_context...
Return the serializer instance which should be used for serializing faceted objects.
Below is the the instruction that describes the task: ### Input: Return the serializer instance which should be used for serializing faceted objects. ### Response: def get_facet_objects_serializer(self, *args, **kwargs): """ Return the serializer instance which should be used for se...
def determine_band_channel(kal_out): """Return band, channel, target frequency from kal output.""" band = "" channel = "" tgt_freq = "" while band == "": for line in kal_out.splitlines(): if "Using " in line and " channel " in line: band = str(line.split()[1]) ...
Return band, channel, target frequency from kal output.
Below is the the instruction that describes the task: ### Input: Return band, channel, target frequency from kal output. ### Response: def determine_band_channel(kal_out): """Return band, channel, target frequency from kal output.""" band = "" channel = "" tgt_freq = "" while band == "": ...
def try_storage(self, identifier, req, resp, resource, uri_kwargs): """Try to find user in configured user storage object. Args: identifier: User identifier. Returns: user object. """ if identifier is None: user = None # note: if use...
Try to find user in configured user storage object. Args: identifier: User identifier. Returns: user object.
Below is the the instruction that describes the task: ### Input: Try to find user in configured user storage object. Args: identifier: User identifier. Returns: user object. ### Response: def try_storage(self, identifier, req, resp, resource, uri_kwargs): """Try to...
def add_acquisition_source( self, method, submission_number=None, internal_uid=None, email=None, orcid=None, source=None, datetime=None, ): """Add acquisition source. :type submission_number: integer :type email: integer ...
Add acquisition source. :type submission_number: integer :type email: integer :type source: string :param method: method of acquisition for the suggested document :type method: string :param orcid: orcid of the user that is creating the record :type orcid: st...
Below is the the instruction that describes the task: ### Input: Add acquisition source. :type submission_number: integer :type email: integer :type source: string :param method: method of acquisition for the suggested document :type method: string :param orcid: ...
def last_year(today: datetime=None, tz=None): """ Returns last year begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: today = datetime.ut...
Returns last year begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
Below is the the instruction that describes the task: ### Input: Returns last year begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) ### Response: def last_year(today: datetime=N...
def to_file_mode(self): """ Write all the messages to files """ for message_no in range(len(self.messages)): self.__to_file(message_no)
Write all the messages to files
Below is the the instruction that describes the task: ### Input: Write all the messages to files ### Response: def to_file_mode(self): """ Write all the messages to files """ for message_no in range(len(self.messages)): self.__to_file(message_no)
def p_example_multiline(self, p): """example_field : ID EQ NL INDENT ex_map NL DEDENT""" p[0] = AstExampleField( self.path, p.lineno(1), p.lexpos(1), p[1], p[5])
example_field : ID EQ NL INDENT ex_map NL DEDENT
Below is the the instruction that describes the task: ### Input: example_field : ID EQ NL INDENT ex_map NL DEDENT ### Response: def p_example_multiline(self, p): """example_field : ID EQ NL INDENT ex_map NL DEDENT""" p[0] = AstExampleField( self.path, p.lineno(1), p.lexpos(1), p[1], p[5...