code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _get_persistent_boot_devices(self): """Get details of persistent boot devices, its order :returns: List of dictionary of boot sources and list of boot device order :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not ...
Get details of persistent boot devices, its order :returns: List of dictionary of boot sources and list of boot device order :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the command is not supported on the server.
Below is the the instruction that describes the task: ### Input: Get details of persistent boot devices, its order :returns: List of dictionary of boot sources and list of boot device order :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if t...
def download(which, destination=None): """ I realize that the download for the dumps is going to take awhile. Given that, I've decided to approach this using threads. When you call this method, it will launch a thread to download the data. By default, the dump is dropped into the...
I realize that the download for the dumps is going to take awhile. Given that, I've decided to approach this using threads. When you call this method, it will launch a thread to download the data. By default, the dump is dropped into the current working directory. If the directory given ...
Below is the the instruction that describes the task: ### Input: I realize that the download for the dumps is going to take awhile. Given that, I've decided to approach this using threads. When you call this method, it will launch a thread to download the data. By default, the dump is droppe...
def set_compiler_channels(self, channel_list, operator="mix"): """General method for setting the input channels for the status process Given a list of status channels that are gathered during the pipeline construction, this method will automatically set the input channel for the status ...
General method for setting the input channels for the status process Given a list of status channels that are gathered during the pipeline construction, this method will automatically set the input channel for the status process. This makes use of the ``mix`` channel operator of nextflo...
Below is the the instruction that describes the task: ### Input: General method for setting the input channels for the status process Given a list of status channels that are gathered during the pipeline construction, this method will automatically set the input channel for the status proce...
def asDictionary(self): """ returns the object as a dictionary """ template = { "type" : "esriPMS", "url" : self._url, "imageData" : self._imageDate, "contentType" : self._contentType, "width" : self._width, "height" : self._height,...
returns the object as a dictionary
Below is the the instruction that describes the task: ### Input: returns the object as a dictionary ### Response: def asDictionary(self): """ returns the object as a dictionary """ template = { "type" : "esriPMS", "url" : self._url, "imageData" : self._imageDate,...
def get_escape(self, c, i): """Get an escape.""" try: escaped = next(i) except StopIteration: escaped = '' return c + escaped if self.keep_escapes else escaped
Get an escape.
Below is the the instruction that describes the task: ### Input: Get an escape. ### Response: def get_escape(self, c, i): """Get an escape.""" try: escaped = next(i) except StopIteration: escaped = '' return c + escaped if self.keep_escapes else escaped
def run_checks(self, service): """ Runs each check for the service and reports to the service's discovery method based on the results. If all checks pass and the service's present node was previously reported as down, the present node is reported as up. Conversely, if a...
Runs each check for the service and reports to the service's discovery method based on the results. If all checks pass and the service's present node was previously reported as down, the present node is reported as up. Conversely, if any of the checks fail and the service's present nod...
Below is the the instruction that describes the task: ### Input: Runs each check for the service and reports to the service's discovery method based on the results. If all checks pass and the service's present node was previously reported as down, the present node is reported as up. Conver...
def top(self) -> "InstanceNode": """Return an instance node corresponding to the root of the data tree.""" inst = self while inst.parinst: inst = inst.up() return inst
Return an instance node corresponding to the root of the data tree.
Below is the the instruction that describes the task: ### Input: Return an instance node corresponding to the root of the data tree. ### Response: def top(self) -> "InstanceNode": """Return an instance node corresponding to the root of the data tree.""" inst = self while inst.parinst: ...
def _get_arg_info(self): ''' get all the info of a method call this will find what arg names you passed into the method and tie them to their passed in values, it will also find file and line number return -- dict -- a bunch of info on the call ''' ret_dict = { ...
get all the info of a method call this will find what arg names you passed into the method and tie them to their passed in values, it will also find file and line number return -- dict -- a bunch of info on the call
Below is the the instruction that describes the task: ### Input: get all the info of a method call this will find what arg names you passed into the method and tie them to their passed in values, it will also find file and line number return -- dict -- a bunch of info on the call ### Respo...
def save_plain_image_as_file(self, filepath, format='png', quality=90): """Used for generating thumbnails. Does not include overlaid graphics. """ pixbuf = self.get_plain_image_as_pixbuf() options, values = [], [] if format == 'jpeg': options.append('quality'...
Used for generating thumbnails. Does not include overlaid graphics.
Below is the the instruction that describes the task: ### Input: Used for generating thumbnails. Does not include overlaid graphics. ### Response: def save_plain_image_as_file(self, filepath, format='png', quality=90): """Used for generating thumbnails. Does not include overlaid graphics....
def runPlink(options): """Runs Plink with the geno option. :param options: the options. :type options: argparse.Namespace """ # The plink command plinkCommand = ["plink", "--noweb", "--bfile", options.bfile, "--geno", str(options.geno), "--make-bed", "--out", options.out] ...
Runs Plink with the geno option. :param options: the options. :type options: argparse.Namespace
Below is the the instruction that describes the task: ### Input: Runs Plink with the geno option. :param options: the options. :type options: argparse.Namespace ### Response: def runPlink(options): """Runs Plink with the geno option. :param options: the options. :type options: argparse.Name...
def undoable(method): """ Decorator undoable allows an instance method to be undone. It does this by wrapping the method call as a Command, then calling self.do() on the command. Classes which use this decorator should implement a do() method like such: def do(self, command): retu...
Decorator undoable allows an instance method to be undone. It does this by wrapping the method call as a Command, then calling self.do() on the command. Classes which use this decorator should implement a do() method like such: def do(self, command): return self.undo_manager.do(command)
Below is the the instruction that describes the task: ### Input: Decorator undoable allows an instance method to be undone. It does this by wrapping the method call as a Command, then calling self.do() on the command. Classes which use this decorator should implement a do() method like such: def ...
def _example_stock_basic(quote_ctx): """ 获取股票信息,输出 股票代码,股票名,每手数量,股票类型,子类型所属正股 """ ret_status, ret_data = quote_ctx.get_stock_basicinfo(ft.Market.HK, ft.SecurityType.STOCK) if ret_status != ft.RET_OK: print(ret_data) exit() print("stock_basic") print(ret_data)
获取股票信息,输出 股票代码,股票名,每手数量,股票类型,子类型所属正股
Below is the the instruction that describes the task: ### Input: 获取股票信息,输出 股票代码,股票名,每手数量,股票类型,子类型所属正股 ### Response: def _example_stock_basic(quote_ctx): """ 获取股票信息,输出 股票代码,股票名,每手数量,股票类型,子类型所属正股 """ ret_status, ret_data = quote_ctx.get_stock_basicinfo(ft.Market.HK, ft.SecurityType.STOCK) if ret_...
def _set_snps(self, snps, build=37): """ Set `_snps` and `_build` properties of this ``Individual``. Notes ----- Intended to be used internally to `lineage`. Parameters ---------- snps : pandas.DataFrame individual's genetic data normalized for use w...
Set `_snps` and `_build` properties of this ``Individual``. Notes ----- Intended to be used internally to `lineage`. Parameters ---------- snps : pandas.DataFrame individual's genetic data normalized for use with `lineage` build : int bui...
Below is the the instruction that describes the task: ### Input: Set `_snps` and `_build` properties of this ``Individual``. Notes ----- Intended to be used internally to `lineage`. Parameters ---------- snps : pandas.DataFrame individual's genetic data ...
def _get_input_target_path(self, local_file_path): """Returns a directory or file path to be the target for "gsutil cp". If the filename contains a wildcard, then the target path must be a directory in order to ensure consistency whether the source pattern contains one or multiple files. Args: ...
Returns a directory or file path to be the target for "gsutil cp". If the filename contains a wildcard, then the target path must be a directory in order to ensure consistency whether the source pattern contains one or multiple files. Args: local_file_path: A full path terminating in a file or ...
Below is the the instruction that describes the task: ### Input: Returns a directory or file path to be the target for "gsutil cp". If the filename contains a wildcard, then the target path must be a directory in order to ensure consistency whether the source pattern contains one or multiple files. ...
def get(self): """ :param payload: a key/value object containing the scimeta you want to store e.g. {"weather": "sunny", "temperature": "80C" } :return: empty (200 status code) """ url = "{url_base}/resource/{pid}/scimeta/custom/".for...
:param payload: a key/value object containing the scimeta you want to store e.g. {"weather": "sunny", "temperature": "80C" } :return: empty (200 status code)
Below is the the instruction that describes the task: ### Input: :param payload: a key/value object containing the scimeta you want to store e.g. {"weather": "sunny", "temperature": "80C" } :return: empty (200 status code) ### Response: def get(self): """ ...
def SendSerializedMessage(self, message): """ Send the `message` to the remote client. Args: message (neo.Network.Message): """ try: ba = Helper.ToArray(message) ba2 = binascii.unhexlify(ba) self.bytes_out += len(ba2) s...
Send the `message` to the remote client. Args: message (neo.Network.Message):
Below is the the instruction that describes the task: ### Input: Send the `message` to the remote client. Args: message (neo.Network.Message): ### Response: def SendSerializedMessage(self, message): """ Send the `message` to the remote client. Args: message...
def calc_atlas_projections(subject_cortices, atlas_cortices, atlas_map, worklog, atlases=Ellipsis): ''' calc_atlas_projections calculates the lazy map of atlas projections. Afferent parameters: @ atlases The atlases that should be applied to the subject. This can be specified as a list/tuple...
calc_atlas_projections calculates the lazy map of atlas projections. Afferent parameters: @ atlases The atlases that should be applied to the subject. This can be specified as a list/tuple of atlas names or as a string where the atlas names are separated by whitespace, commas, or sem...
Below is the the instruction that describes the task: ### Input: calc_atlas_projections calculates the lazy map of atlas projections. Afferent parameters: @ atlases The atlases that should be applied to the subject. This can be specified as a list/tuple of atlas names or as a string wher...
def _copy_stream_position(position): """Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]): StreamPostion (or dictionary in StreamPosition format) to copy. Returns: ~google.clo...
Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]): StreamPostion (or dictionary in StreamPosition format) to copy. Returns: ~google.cloud.bigquery_storage_v1beta1.types.StreamPosi...
Below is the the instruction that describes the task: ### Input: Copy a StreamPosition. Args: position (Union[ \ dict, \ ~google.cloud.bigquery_storage_v1beta1.types.StreamPosition \ ]): StreamPostion (or dictionary in StreamPosition format) to copy. Ret...
def fileModifiedTimestamp(fname): """return "YYYY-MM-DD" when the file was modified.""" modifiedTime=os.path.getmtime(fname) stamp=time.strftime('%Y-%m-%d', time.localtime(modifiedTime)) return stamp
return "YYYY-MM-DD" when the file was modified.
Below is the the instruction that describes the task: ### Input: return "YYYY-MM-DD" when the file was modified. ### Response: def fileModifiedTimestamp(fname): """return "YYYY-MM-DD" when the file was modified.""" modifiedTime=os.path.getmtime(fname) stamp=time.strftime('%Y-%m-%d', time.localtime(m...
def _init_impl(self, data, ctx_list): """Sets data and grad.""" self._ctx_list = list(ctx_list) self._ctx_map = [[], []] for i, ctx in enumerate(self._ctx_list): dev_list = self._ctx_map[ctx.device_typeid&1] while len(dev_list) <= ctx.device_id: de...
Sets data and grad.
Below is the the instruction that describes the task: ### Input: Sets data and grad. ### Response: def _init_impl(self, data, ctx_list): """Sets data and grad.""" self._ctx_list = list(ctx_list) self._ctx_map = [[], []] for i, ctx in enumerate(self._ctx_list): dev_list =...
def get_right_geo_fhs(self, dsid, fhs): """Find the right geographical file handlers for given dataset ID *dsid*.""" ds_info = self.ids[dsid] req_geo, rem_geo = self._get_req_rem_geo(ds_info) desired, other = split_desired_other(fhs, req_geo, rem_geo) if desired: try:...
Find the right geographical file handlers for given dataset ID *dsid*.
Below is the the instruction that describes the task: ### Input: Find the right geographical file handlers for given dataset ID *dsid*. ### Response: def get_right_geo_fhs(self, dsid, fhs): """Find the right geographical file handlers for given dataset ID *dsid*.""" ds_info = self.ids[dsid] ...
def get_id(self, name, recurse=True): """Get the first id matching ``name``. Will either be a local or a var. :name: TODO :returns: TODO """ self._dlog("getting id '{}'".format(name)) var = self._search("vars", name, recurse) return var
Get the first id matching ``name``. Will either be a local or a var. :name: TODO :returns: TODO
Below is the the instruction that describes the task: ### Input: Get the first id matching ``name``. Will either be a local or a var. :name: TODO :returns: TODO ### Response: def get_id(self, name, recurse=True): """Get the first id matching ``name``. Will either be a local ...
def init_from_datastore(self): """Initializes batches by reading from the datastore.""" self._data = {} for entity in self._datastore_client.query_fetch( kind=self._entity_kind_batches): batch_id = entity.key.flat_path[-1] self._data[batch_id] = dict(entity) self._data[batch_id]['i...
Initializes batches by reading from the datastore.
Below is the the instruction that describes the task: ### Input: Initializes batches by reading from the datastore. ### Response: def init_from_datastore(self): """Initializes batches by reading from the datastore.""" self._data = {} for entity in self._datastore_client.query_fetch( kind=self._...
def sparse_allclose(a, b, rtol=1e-5, atol=1e-8): """ Version of np.allclose for use with sparse matrices """ c = np.abs(a - b) - rtol * np.abs(b) # noinspection PyUnresolvedReferences return c.max() <= atol
Version of np.allclose for use with sparse matrices
Below is the the instruction that describes the task: ### Input: Version of np.allclose for use with sparse matrices ### Response: def sparse_allclose(a, b, rtol=1e-5, atol=1e-8): """ Version of np.allclose for use with sparse matrices """ c = np.abs(a - b) - rtol * np.abs(b) # noinspection PyU...
def get_wordset(poems): """get all words""" words = sorted(list(set(reduce(lambda x, y: x + y, poems)))) return words
get all words
Below is the the instruction that describes the task: ### Input: get all words ### Response: def get_wordset(poems): """get all words""" words = sorted(list(set(reduce(lambda x, y: x + y, poems)))) return words
def p_enum(self, p): # noqa '''enum : ENUM IDENTIFIER '{' enum_seq '}' annotations''' p[0] = ast.Enum( name=p[2], items=p[4], annotations=p[6], lineno=p.lineno(2) )
enum : ENUM IDENTIFIER '{' enum_seq '}' annotations
Below is the the instruction that describes the task: ### Input: enum : ENUM IDENTIFIER '{' enum_seq '}' annotations ### Response: def p_enum(self, p): # noqa '''enum : ENUM IDENTIFIER '{' enum_seq '}' annotations''' p[0] = ast.Enum( name=p[2], items=p[4], annotations=p[6], lineno=p.li...
def decrease_priority(self, infohash_list): """ Decrease priority of torrents. :param infohash_list: Single or list() of infohashes. """ data = self._process_infohash_list(infohash_list) return self._post('command/decreasePrio', data=data)
Decrease priority of torrents. :param infohash_list: Single or list() of infohashes.
Below is the the instruction that describes the task: ### Input: Decrease priority of torrents. :param infohash_list: Single or list() of infohashes. ### Response: def decrease_priority(self, infohash_list): """ Decrease priority of torrents. :param infohash_list: Single or list()...
def __build_problem(self): """Build the matrix representation of the sampling problem.""" # Set up the mathematical problem prob = constraint_matrices(self.model, zero_tol=self.feasibility_tol) # check if there any non-zero equality constraints equalities = prob.equalities ...
Build the matrix representation of the sampling problem.
Below is the the instruction that describes the task: ### Input: Build the matrix representation of the sampling problem. ### Response: def __build_problem(self): """Build the matrix representation of the sampling problem.""" # Set up the mathematical problem prob = constraint_matrices(sel...
def calc_erc_weights(returns, initial_weights=None, risk_weights=None, covar_method='ledoit-wolf', risk_parity_method='ccd', maximum_iterations=100, tolerance=1E-8): """ Calculates the e...
Calculates the equal risk contribution / risk parity weights given a DataFrame of returns. Args: * returns (DataFrame): Returns for multiple securities. * initial_weights (list): Starting asset weights [default inverse vol]. * risk_weights (list): Risk target weights [default equal weig...
Below is the the instruction that describes the task: ### Input: Calculates the equal risk contribution / risk parity weights given a DataFrame of returns. Args: * returns (DataFrame): Returns for multiple securities. * initial_weights (list): Starting asset weights [default inverse vol]. ...
def get_registered_credits (self): """ 登録単位数合計の取得 """ self.req("RSW0001000-flow") r = self.get({ "_eventId": "search", "moduleCode": 1, "gakkiKbnCode": "A" }) html = r.text # XXX ...
登録単位数合計の取得
Below is the the instruction that describes the task: ### Input: 登録単位数合計の取得 ### Response: def get_registered_credits (self): """ 登録単位数合計の取得 """ self.req("RSW0001000-flow") r = self.get({ "_eventId": "search", "moduleCode": 1, ...
def devnull(): """Temporarily redirect stdout and stderr to /dev/null.""" try: original_stderr = os.dup(sys.stderr.fileno()) original_stdout = os.dup(sys.stdout.fileno()) null = open(os.devnull, 'w') os.dup2(null.fileno(), sys.stderr.fileno()) os.dup2(null.fileno(), sys....
Temporarily redirect stdout and stderr to /dev/null.
Below is the the instruction that describes the task: ### Input: Temporarily redirect stdout and stderr to /dev/null. ### Response: def devnull(): """Temporarily redirect stdout and stderr to /dev/null.""" try: original_stderr = os.dup(sys.stderr.fileno()) original_stdout = os.dup(sys.stdo...
def removeBreakpoint( self, lineno = -1 ): """ Removes the breakpoint at the inputed line number. If the lineno is -1, then the current line number will be used :note The lineno is 0-based, while the editor displays lines as a 1-based system. So...
Removes the breakpoint at the inputed line number. If the lineno is -1, then the current line number will be used :note The lineno is 0-based, while the editor displays lines as a 1-based system. So, if you remove a breakpoint at visual line ...
Below is the the instruction that describes the task: ### Input: Removes the breakpoint at the inputed line number. If the lineno is -1, then the current line number will be used :note The lineno is 0-based, while the editor displays lines as a 1-based system....
def parse_multipart_formdata(reader, boundary, cb): """Read data from ``reader`` and parse multipart/form-data fields. ``boundary`` is the multipart/form-data boundary. ``cb`` is a callable that will be called as ``cb(headers, reader)`` to handle the parsed field. """ breader = BoundaryReader(...
Read data from ``reader`` and parse multipart/form-data fields. ``boundary`` is the multipart/form-data boundary. ``cb`` is a callable that will be called as ``cb(headers, reader)`` to handle the parsed field.
Below is the the instruction that describes the task: ### Input: Read data from ``reader`` and parse multipart/form-data fields. ``boundary`` is the multipart/form-data boundary. ``cb`` is a callable that will be called as ``cb(headers, reader)`` to handle the parsed field. ### Response: def parse_mul...
def _fix_gatk_header(exist_files, out_file, config): """Ensure consistent headers for VCF concatenation. Fixes problems for genomes that start with chrM by reheadering the first file. These files do haploid variant calling which lack the PID phasing key/value pair in FORMAT, so initial chrM samples cau...
Ensure consistent headers for VCF concatenation. Fixes problems for genomes that start with chrM by reheadering the first file. These files do haploid variant calling which lack the PID phasing key/value pair in FORMAT, so initial chrM samples cause errors during concatenation due to the lack of header...
Below is the the instruction that describes the task: ### Input: Ensure consistent headers for VCF concatenation. Fixes problems for genomes that start with chrM by reheadering the first file. These files do haploid variant calling which lack the PID phasing key/value pair in FORMAT, so initial chrM sa...
def stats_per36(self, kind='R', summary=False): """Returns a DataFrame of per-36-minutes stats.""" return self._get_stats_table('per_minute', kind=kind, summary=summary)
Returns a DataFrame of per-36-minutes stats.
Below is the the instruction that describes the task: ### Input: Returns a DataFrame of per-36-minutes stats. ### Response: def stats_per36(self, kind='R', summary=False): """Returns a DataFrame of per-36-minutes stats.""" return self._get_stats_table('per_minute', kind=kind, summary=summary)
def check_s3(self, bucket, element): # pragma: no cover """This method is a helper con `cache_s3`. Read method `cache_s3` for more information. :param bucket: :param element: :return: """ session = boto3.Session(profile_name=self.profile_name) s3 = sessi...
This method is a helper con `cache_s3`. Read method `cache_s3` for more information. :param bucket: :param element: :return:
Below is the the instruction that describes the task: ### Input: This method is a helper con `cache_s3`. Read method `cache_s3` for more information. :param bucket: :param element: :return: ### Response: def check_s3(self, bucket, element): # pragma: no cover """This metho...
def convert_the_args(raw_args): """ Function used to convert the arguments of methods """ if not raw_args: return "" if isinstance(raw_args,dict): out_args = ", ".join([ "{}={}".format(k,v) for k,v in raw_args.iteritems() ]) elif isinstance(raw_args,(list,tuple)): ...
Function used to convert the arguments of methods
Below is the the instruction that describes the task: ### Input: Function used to convert the arguments of methods ### Response: def convert_the_args(raw_args): """ Function used to convert the arguments of methods """ if not raw_args: return "" if isinstance(raw_args,dict): out...
def SolveServiceArea(self, facilities=None, barriers=None, polylineBarriers=None, polygonBarriers=None, attributeParameterValues=None, defaultBreaks=None, excludeSourcesF...
The solve operation is performed on a network layer resource of type service area (layerType is esriNAServerServiceArea).
Below is the the instruction that describes the task: ### Input: The solve operation is performed on a network layer resource of type service area (layerType is esriNAServerServiceArea). ### Response: def SolveServiceArea(self, facilities=None, barriers=None, ...
def write_outro (self): """Write outro comments.""" self.stoptime = time.time() duration = self.stoptime - self.starttime self.comment(_("Stopped checking at %(time)s (%(duration)s)") % {"time": strformat.strtime(self.stoptime), "duration": strformat.strduratio...
Write outro comments.
Below is the the instruction that describes the task: ### Input: Write outro comments. ### Response: def write_outro (self): """Write outro comments.""" self.stoptime = time.time() duration = self.stoptime - self.starttime self.comment(_("Stopped checking at %(time)s (%(duration)s)"...
def publocus(args): """ %prog publocus idsfile > idsfiles.publocus Given a list of model identifiers, convert each into a GenBank approved pub_locus. Example output: Medtr1g007020.1 MTR_1g007020 Medtr1g007030.1 MTR_1g007030 Medtr1g007060.1 MTR_1g007060A Medtr1g007060.2 MTR_1g00...
%prog publocus idsfile > idsfiles.publocus Given a list of model identifiers, convert each into a GenBank approved pub_locus. Example output: Medtr1g007020.1 MTR_1g007020 Medtr1g007030.1 MTR_1g007030 Medtr1g007060.1 MTR_1g007060A Medtr1g007060.2 MTR_1g007060B
Below is the the instruction that describes the task: ### Input: %prog publocus idsfile > idsfiles.publocus Given a list of model identifiers, convert each into a GenBank approved pub_locus. Example output: Medtr1g007020.1 MTR_1g007020 Medtr1g007030.1 MTR_1g007030 Medtr1g007060.1 MTR_1g...
def cone_search_lonlat(self, lon, lat, radius): """ Find all the HEALPix pixels within a given radius of a longitude/latitude. Note that this returns all pixels that overlap, including partially, with the search cone. This function can only be used for a single lon/lat pair at a...
Find all the HEALPix pixels within a given radius of a longitude/latitude. Note that this returns all pixels that overlap, including partially, with the search cone. This function can only be used for a single lon/lat pair at a time, since different calls to the function may result in a differe...
Below is the the instruction that describes the task: ### Input: Find all the HEALPix pixels within a given radius of a longitude/latitude. Note that this returns all pixels that overlap, including partially, with the search cone. This function can only be used for a single lon/lat pair at ...
def draw(self, points, target=None, **kwargs): """ Called from the fit method, this method creates the canvas and draws the plot on it. Parameters ---------- kwargs: generic keyword arguments. """ # Resolve the labels with the classes labels = sel...
Called from the fit method, this method creates the canvas and draws the plot on it. Parameters ---------- kwargs: generic keyword arguments.
Below is the the instruction that describes the task: ### Input: Called from the fit method, this method creates the canvas and draws the plot on it. Parameters ---------- kwargs: generic keyword arguments. ### Response: def draw(self, points, target=None, **kwargs): """ ...
def create_from_pointer(cls, pointer): """ :type pointer: Pointer """ instance = cls.__new__(cls) instance.pointer = pointer instance.label_monetary_account = LabelMonetaryAccount() instance.label_monetary_account._iban = pointer.value instance.label_mone...
:type pointer: Pointer
Below is the the instruction that describes the task: ### Input: :type pointer: Pointer ### Response: def create_from_pointer(cls, pointer): """ :type pointer: Pointer """ instance = cls.__new__(cls) instance.pointer = pointer instance.label_monetary_account = Label...
def get_unique_key_from_get(get_dict): """ Build a unique key from get data """ site = Site.objects.get_current() key = get_dict_to_encoded_url(get_dict) cache_key = '{}_{}'.format(site.domain, key) return hashlib.md5(cache_key).hexdigest()
Build a unique key from get data
Below is the the instruction that describes the task: ### Input: Build a unique key from get data ### Response: def get_unique_key_from_get(get_dict): """ Build a unique key from get data """ site = Site.objects.get_current() key = get_dict_to_encoded_url(get_dict) cache_key = '{}_{}'.forma...
def create_tomography_circuits(circuit, qreg, creg, tomoset): """ Add tomography measurement circuits to a QuantumProgram. The quantum program must contain a circuit 'name', which is treated as a state preparation circuit for state tomography, or as teh circuit being measured for process tomography...
Add tomography measurement circuits to a QuantumProgram. The quantum program must contain a circuit 'name', which is treated as a state preparation circuit for state tomography, or as teh circuit being measured for process tomography. This function then appends the circuit with a set of measurements sp...
Below is the the instruction that describes the task: ### Input: Add tomography measurement circuits to a QuantumProgram. The quantum program must contain a circuit 'name', which is treated as a state preparation circuit for state tomography, or as teh circuit being measured for process tomography. Thi...
def fit(self, X, y, exposure=None, weights=None): """Fit the generalized additive model. Parameters ---------- X : array-like, shape (n_samples, m_features) Training vectors, where n_samples is the number of samples and m_features is the number of features. ...
Fit the generalized additive model. Parameters ---------- X : array-like, shape (n_samples, m_features) Training vectors, where n_samples is the number of samples and m_features is the number of features. y : array-like, shape (n_samples,) Target val...
Below is the the instruction that describes the task: ### Input: Fit the generalized additive model. Parameters ---------- X : array-like, shape (n_samples, m_features) Training vectors, where n_samples is the number of samples and m_features is the number of feature...
def fillup_layer(layer, first_clbit): """ Given a layer, replace the Nones in it with EmptyWire elements. Args: layer (list): The layer that contains Nones. first_clbit (int): The first wire that is classic. Returns: list: The new layer, with no Nones...
Given a layer, replace the Nones in it with EmptyWire elements. Args: layer (list): The layer that contains Nones. first_clbit (int): The first wire that is classic. Returns: list: The new layer, with no Nones.
Below is the the instruction that describes the task: ### Input: Given a layer, replace the Nones in it with EmptyWire elements. Args: layer (list): The layer that contains Nones. first_clbit (int): The first wire that is classic. Returns: list: The new layer, wi...
def s3_delete_file(bucket, filename, client=None, raiseonfail=False): """This deletes a file from S3. Parameters ---------- bucket : str The AWS S3 bucket to delete the file from. filename : str The full file name of the file to delete, including any prefixes. client : boto3....
This deletes a file from S3. Parameters ---------- bucket : str The AWS S3 bucket to delete the file from. filename : str The full file name of the file to delete, including any prefixes. client : boto3.Client or None If None, this function will instantiate a new `boto3.C...
Below is the the instruction that describes the task: ### Input: This deletes a file from S3. Parameters ---------- bucket : str The AWS S3 bucket to delete the file from. filename : str The full file name of the file to delete, including any prefixes. client : boto3.Client o...
def brightness_multi(x, gamma=1, gain=1, is_random=False): """Change the brightness of multiply images, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpyarray List of images with dimension of ...
Change the brightness of multiply images, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpyarray List of images with dimension of [n_images, row, col, channel] (default). others : args ...
Below is the the instruction that describes the task: ### Input: Change the brightness of multiply images, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpyarray List of images with dimension ...
def violinplot(self, n=1000, **kwargs): """Plot violins of each distribution in the model family Parameters ---------- n : int Number of random variables to generate kwargs : dict or keywords Any keyword arguments to seaborn.violinplot Returns ...
Plot violins of each distribution in the model family Parameters ---------- n : int Number of random variables to generate kwargs : dict or keywords Any keyword arguments to seaborn.violinplot Returns ------- ax : matplotlib.Axes object ...
Below is the the instruction that describes the task: ### Input: Plot violins of each distribution in the model family Parameters ---------- n : int Number of random variables to generate kwargs : dict or keywords Any keyword arguments to seaborn.violinplot ...
def app_name_from_ini_parser(ini_parser): """ Returns the name of the main application from the given ini file parser. The name is found as follows: * If the ini file contains only one app:<app name> section, return this app name; * Else, if the ini file contains a pipeline:main section, us...
Returns the name of the main application from the given ini file parser. The name is found as follows: * If the ini file contains only one app:<app name> section, return this app name; * Else, if the ini file contains a pipeline:main section, use the name of the innermost app; * Else ra...
Below is the the instruction that describes the task: ### Input: Returns the name of the main application from the given ini file parser. The name is found as follows: * If the ini file contains only one app:<app name> section, return this app name; * Else, if the ini file contains a pipeline:m...
def getDownloader(self, url): """Get an image downloader.""" filename = self.namer(url, self.stripUrl) if filename is None: filename = url.rsplit('/', 1)[1] dirname = getDirname(self.name) return ComicImage(self.name, url, self.stripUrl, dirname, filename, self.sessio...
Get an image downloader.
Below is the the instruction that describes the task: ### Input: Get an image downloader. ### Response: def getDownloader(self, url): """Get an image downloader.""" filename = self.namer(url, self.stripUrl) if filename is None: filename = url.rsplit('/', 1)[1] dirname = ...
def key_file(self, value): """gets/sets the certificate file""" import os if os.path.isfile(value): self._keyfile = value
gets/sets the certificate file
Below is the the instruction that describes the task: ### Input: gets/sets the certificate file ### Response: def key_file(self, value): """gets/sets the certificate file""" import os if os.path.isfile(value): self._keyfile = value
def _select_channels(data, channels): """Select channels. Parameters ---------- data : instance of ChanTime data with all the channels channels : list channels of interest Returns ------- instance of ChanTime data with only channels of interest Notes --...
Select channels. Parameters ---------- data : instance of ChanTime data with all the channels channels : list channels of interest Returns ------- instance of ChanTime data with only channels of interest Notes ----- This function does the same as wonamb...
Below is the the instruction that describes the task: ### Input: Select channels. Parameters ---------- data : instance of ChanTime data with all the channels channels : list channels of interest Returns ------- instance of ChanTime data with only channels of in...
def observe_reward_value(self, state_key, action_key): ''' Compute the reward value. Args: state_key: The key of state. action_key: The key of action. Returns: Reward value. ''' x, y = state_k...
Compute the reward value. Args: state_key: The key of state. action_key: The key of action. Returns: Reward value.
Below is the the instruction that describes the task: ### Input: Compute the reward value. Args: state_key: The key of state. action_key: The key of action. Returns: Reward value. ### Response: def observe_reward_value(s...
async def send_async(self, message, callback, timeout=0): """Add a single message to the internal pending queue to be processed by the Connection without waiting for it to be sent. :param message: The message to send. :type message: ~uamqp.message.Message :param callback: The ca...
Add a single message to the internal pending queue to be processed by the Connection without waiting for it to be sent. :param message: The message to send. :type message: ~uamqp.message.Message :param callback: The callback to be run once a disposition is received in receipt o...
Below is the the instruction that describes the task: ### Input: Add a single message to the internal pending queue to be processed by the Connection without waiting for it to be sent. :param message: The message to send. :type message: ~uamqp.message.Message :param callback: The ca...
def from_bed(fileobj, field_sep=b'\t', interval_maker=None): ''' Initialize a ``GenomeIntervalTree`` from a BED file. Each line of the file must consist of several fields, separated using ``field_sep``. The first three fields are ``chrom``, ``start`` and ``end`` (where ``start`` is 0-bas...
Initialize a ``GenomeIntervalTree`` from a BED file. Each line of the file must consist of several fields, separated using ``field_sep``. The first three fields are ``chrom``, ``start`` and ``end`` (where ``start`` is 0-based and the corresponding interval is ``[start, end)``). The remaining fie...
Below is the the instruction that describes the task: ### Input: Initialize a ``GenomeIntervalTree`` from a BED file. Each line of the file must consist of several fields, separated using ``field_sep``. The first three fields are ``chrom``, ``start`` and ``end`` (where ``start`` is 0-based and ...
def allstack(vals, depth=0): """ If an ndarray has been split into multiple chunks by splitting it along each axis at a number of locations, this function rebuilds the original array from chunks. Parameters ---------- vals : nested lists of ndarrays each level of nesting of the list...
If an ndarray has been split into multiple chunks by splitting it along each axis at a number of locations, this function rebuilds the original array from chunks. Parameters ---------- vals : nested lists of ndarrays each level of nesting of the lists representing a dimension of the...
Below is the the instruction that describes the task: ### Input: If an ndarray has been split into multiple chunks by splitting it along each axis at a number of locations, this function rebuilds the original array from chunks. Parameters ---------- vals : nested lists of ndarrays each ...
def make_stmt_from_sort_key(key, verb): """Make a Statement from the sort key. Specifically, the sort key used by `group_and_sort_statements`. """ def make_agent(name): if name == 'None' or name is None: return None return Agent(name) StmtClass = get_statement_by_name(v...
Make a Statement from the sort key. Specifically, the sort key used by `group_and_sort_statements`.
Below is the the instruction that describes the task: ### Input: Make a Statement from the sort key. Specifically, the sort key used by `group_and_sort_statements`. ### Response: def make_stmt_from_sort_key(key, verb): """Make a Statement from the sort key. Specifically, the sort key used by `group_a...
def queue(self, queue, message, params={}, uids=[]): """ Queue a job in Rhumba """ d = { 'id': uuid.uuid1().get_hex(), 'version': 1, 'message': message, 'params': params } if uids: for uid in uids: ...
Queue a job in Rhumba
Below is the the instruction that describes the task: ### Input: Queue a job in Rhumba ### Response: def queue(self, queue, message, params={}, uids=[]): """ Queue a job in Rhumba """ d = { 'id': uuid.uuid1().get_hex(), 'version': 1, 'message': me...
def fill_dups_arr(data): """ fills the duplicates array from the multi_muscle_align tmp files """ ## build the duplicates array duplefiles = glob.glob(os.path.join(data.tmpdir, "duples_*.tmp.npy")) duplefiles.sort(key=lambda x: int(x.rsplit("_", 1)[-1][:-8])) ## enter the duplicates filter ...
fills the duplicates array from the multi_muscle_align tmp files
Below is the the instruction that describes the task: ### Input: fills the duplicates array from the multi_muscle_align tmp files ### Response: def fill_dups_arr(data): """ fills the duplicates array from the multi_muscle_align tmp files """ ## build the duplicates array duplefiles = glob.glob(...
def crop(self, minimum_address, maximum_address): """Keep given range and discard the rest. `minimum_address` is the first word address to keep (including). `maximum_address` is the last word address to keep (excluding). """ minimum_address *= self.word_size_b...
Keep given range and discard the rest. `minimum_address` is the first word address to keep (including). `maximum_address` is the last word address to keep (excluding).
Below is the the instruction that describes the task: ### Input: Keep given range and discard the rest. `minimum_address` is the first word address to keep (including). `maximum_address` is the last word address to keep (excluding). ### Response: def crop(self, minimum_address, ma...
def create_node_creation_factor(self, tool, source, output_plate, plate_manager): """ Creates a factor that itself creates an output node, and ensures that the plate for the output node exists along with all relevant meta-data :param tool: The tool :param source: The source node...
Creates a factor that itself creates an output node, and ensures that the plate for the output node exists along with all relevant meta-data :param tool: The tool :param source: The source node :param output_plate: The details of the plate that will be created (dict) :param plat...
Below is the the instruction that describes the task: ### Input: Creates a factor that itself creates an output node, and ensures that the plate for the output node exists along with all relevant meta-data :param tool: The tool :param source: The source node :param output_plate: The...
def can_handle(self, input_dict): """ Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise """ ...
Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise
Below is the the instruction that describes the task: ### Input: Validates that the input dictionary contains only one key and is of the given intrinsic_name :param input_dict: Input dictionary representing the intrinsic function :return: True if it matches expected structure, False otherwise ### R...
def extract_model_meta(base_meta: dict, extra_meta: dict, model_url: str) -> dict: """ Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ `index.json`. :param base_meta: tree["meta"] :class:`dict` containing data from the backend. :param extra_meta: dict ...
Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ `index.json`. :param base_meta: tree["meta"] :class:`dict` containing data from the backend. :param extra_meta: dict containing data from the user, similar to `template_meta.json`. :param model_url: public UR...
Below is the the instruction that describes the task: ### Input: Merge the metadata from the backend and the extra metadata into a dict which is suitable for \ `index.json`. :param base_meta: tree["meta"] :class:`dict` containing data from the backend. :param extra_meta: dict containing data from the u...
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 '' ...
Convert one MeCabToken into HTML
Below is the the instruction that describes the task: ### Input: Convert one MeCabToken into HTML ### Response: def to_ruby(self): ''' Convert one MeCabToken into HTML ''' if self.need_ruby(): surface = self.surface reading = self.reading_hira() return '<ruby><rb...
def factorization_machine_model(factor_size, num_features, lr_mult_config, wd_mult_config, init_config): """ builds factorization machine network with proper formulation: y = w_0 \sum(x_i w_i) + 0.5(\sum\sum<v_i,v_j>x_ix_j - \sum<v_iv_i>x_i^2) """ x = mx.symbol.Variable("...
builds factorization machine network with proper formulation: y = w_0 \sum(x_i w_i) + 0.5(\sum\sum<v_i,v_j>x_ix_j - \sum<v_iv_i>x_i^2)
Below is the the instruction that describes the task: ### Input: builds factorization machine network with proper formulation: y = w_0 \sum(x_i w_i) + 0.5(\sum\sum<v_i,v_j>x_ix_j - \sum<v_iv_i>x_i^2) ### Response: def factorization_machine_model(factor_size, num_features, lr_mul...
def start_event(self): """Called by the event loop when it is started. Creates the output frame pools (if used) then calls :py:meth:`on_start`. Creating the output frame pools now allows their size to be configured before starting the component. """ # create object pool...
Called by the event loop when it is started. Creates the output frame pools (if used) then calls :py:meth:`on_start`. Creating the output frame pools now allows their size to be configured before starting the component.
Below is the the instruction that describes the task: ### Input: Called by the event loop when it is started. Creates the output frame pools (if used) then calls :py:meth:`on_start`. Creating the output frame pools now allows their size to be configured before starting the component. ### Re...
def groups_open(self, room_id, **kwargs): """Adds the private group back to the user’s list of private groups.""" return self.__call_api_post('groups.open', roomId=room_id, kwargs=kwargs)
Adds the private group back to the user’s list of private groups.
Below is the the instruction that describes the task: ### Input: Adds the private group back to the user’s list of private groups. ### Response: def groups_open(self, room_id, **kwargs): """Adds the private group back to the user’s list of private groups.""" return self.__call_api_post('groups.open...
def open(self, mode='r', **kwargs): """Open file ``uri`` under the pointer.""" _fs, filename = opener.parse(self.uri) return _fs.open(filename, mode=mode, **kwargs)
Open file ``uri`` under the pointer.
Below is the the instruction that describes the task: ### Input: Open file ``uri`` under the pointer. ### Response: def open(self, mode='r', **kwargs): """Open file ``uri`` under the pointer.""" _fs, filename = opener.parse(self.uri) return _fs.open(filename, mode=mode, **kwargs)
def remove_dataset(self, dataset=None, **kwargs): """ Remove a dataset from the Bundle. This removes all matching Parameters from the dataset, model, and constraint contexts (by default if the context tag is not provided). You must provide some sort of filter or this will raise an Erro...
Remove a dataset from the Bundle. This removes all matching Parameters from the dataset, model, and constraint contexts (by default if the context tag is not provided). You must provide some sort of filter or this will raise an Error (so that all Parameters are not accidentally removed...
Below is the the instruction that describes the task: ### Input: Remove a dataset from the Bundle. This removes all matching Parameters from the dataset, model, and constraint contexts (by default if the context tag is not provided). You must provide some sort of filter or this will raise ...
def bulk_create_awards(objects, batch_size=500, post_save_signal=True): """ Saves award objects. """ count = len(objects) if not count: return badge = objects[0].badge try: Award.objects.bulk_create(objects, batch_size=batch_size) if post_save_signal: for ...
Saves award objects.
Below is the the instruction that describes the task: ### Input: Saves award objects. ### Response: def bulk_create_awards(objects, batch_size=500, post_save_signal=True): """ Saves award objects. """ count = len(objects) if not count: return badge = objects[0].badge try: ...
def dict_is_subset(subset: Any, full_set: Any) -> bool: """ Checks that all keys present in `subset` are present and have the same value in `full_set`. If a key is in `full_set` but not in `subset` then True will be returned anyways. """ if not isinstance(subset, full_set.__class__): re...
Checks that all keys present in `subset` are present and have the same value in `full_set`. If a key is in `full_set` but not in `subset` then True will be returned anyways.
Below is the the instruction that describes the task: ### Input: Checks that all keys present in `subset` are present and have the same value in `full_set`. If a key is in `full_set` but not in `subset` then True will be returned anyways. ### Response: def dict_is_subset(subset: Any, full_set: Any) -> bool...
def fetch_tuples(self, max_tuples=20, timeout=None): """ Fetch a number of tuples from this view. Fetching of data must have been started with :py:meth:`start_data_fetch` before calling this method. If ``timeout`` is ``None`` then the returned list will contain ``max_tu...
Fetch a number of tuples from this view. Fetching of data must have been started with :py:meth:`start_data_fetch` before calling this method. If ``timeout`` is ``None`` then the returned list will contain ``max_tuples`` tuples. Otherwise if the timeout is reached the list may c...
Below is the the instruction that describes the task: ### Input: Fetch a number of tuples from this view. Fetching of data must have been started with :py:meth:`start_data_fetch` before calling this method. If ``timeout`` is ``None`` then the returned list will contain ``max_tuples...
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[str]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_strlist(value) return retval
Convert things on the way from the database to Python.
Below is the the instruction that describes the task: ### Input: Convert things on the way from the database to Python. ### Response: def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[str]: """Convert things on the way from the database to Python.""...
def step(self, batch_size, max_norm=None): """Makes one step of parameter update. Should be called after `fp16_optimizer.backward()`, and outside of `record()` scope. Parameters ---------- batch_size : int Batch size of data processed. Gradient will be normalized by ...
Makes one step of parameter update. Should be called after `fp16_optimizer.backward()`, and outside of `record()` scope. Parameters ---------- batch_size : int Batch size of data processed. Gradient will be normalized by `1/batch_size`. Set this to 1 if you norma...
Below is the the instruction that describes the task: ### Input: Makes one step of parameter update. Should be called after `fp16_optimizer.backward()`, and outside of `record()` scope. Parameters ---------- batch_size : int Batch size of data processed. Gradient will be...
def _uninstall(cls): """ uninstall the hook if installed """ if cls._hook: sys.meta_path.remove(cls._hook) cls._hook = None
uninstall the hook if installed
Below is the the instruction that describes the task: ### Input: uninstall the hook if installed ### Response: def _uninstall(cls): """ uninstall the hook if installed """ if cls._hook: sys.meta_path.remove(cls._hook) cls._hook = None
def clouds(self, id=None, name=None, provider=None, search=None): """ Property-like function to call the _list_clouds function in order to populate self._clouds dict :returns: A list of Cloud instances. """ if self._clouds is None: self._clouds = {} ...
Property-like function to call the _list_clouds function in order to populate self._clouds dict :returns: A list of Cloud instances.
Below is the the instruction that describes the task: ### Input: Property-like function to call the _list_clouds function in order to populate self._clouds dict :returns: A list of Cloud instances. ### Response: def clouds(self, id=None, name=None, provider=None, search=None): """ ...
def account(self, id): """ Fetch account information by user `id`. Does not require authentication. Returns a `user dict`_. """ id = self.__unpack_id(id) url = '/api/v1/accounts/{0}'.format(str(id)) return self.__api_request('GET', url)
Fetch account information by user `id`. Does not require authentication. Returns a `user dict`_.
Below is the the instruction that describes the task: ### Input: Fetch account information by user `id`. Does not require authentication. Returns a `user dict`_. ### Response: def account(self, id): """ Fetch account information by user `id`. Does ...
def get_DID_name(self, did): """ Given a DID, get the name Return None if not found, or if the name was revoked Raise if the DID is invalid """ did = str(did) did_info = None try: did_info = parse_DID(did) assert did_info['name_type...
Given a DID, get the name Return None if not found, or if the name was revoked Raise if the DID is invalid
Below is the the instruction that describes the task: ### Input: Given a DID, get the name Return None if not found, or if the name was revoked Raise if the DID is invalid ### Response: def get_DID_name(self, did): """ Given a DID, get the name Return None if not found, or i...
def get_link_page_text(link_page): """ Construct the dialog box to display a list of links to the user. """ text = '' for i, link in enumerate(link_page): capped_link_text = (link['text'] if len(link['text']) <= 20 else link['text'][:19...
Construct the dialog box to display a list of links to the user.
Below is the the instruction that describes the task: ### Input: Construct the dialog box to display a list of links to the user. ### Response: def get_link_page_text(link_page): """ Construct the dialog box to display a list of links to the user. """ text = '' for i, link i...
def pca(adata, **kwargs) -> Union[Axes, List[Axes], None]: """\ Scatter plot in PCA coordinates. Parameters ---------- {adata_color_etc} {scatter_bulk} {show_save_ax} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it. """ return plot_scat...
\ Scatter plot in PCA coordinates. Parameters ---------- {adata_color_etc} {scatter_bulk} {show_save_ax} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
Below is the the instruction that describes the task: ### Input: \ Scatter plot in PCA coordinates. Parameters ---------- {adata_color_etc} {scatter_bulk} {show_save_ax} Returns ------- If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it. ### Response: def pca(ad...
def send_photo(self, chat_id, photo, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send photos. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendphoto Parameters: ...
Use this method to send photos. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendphoto Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: ...
Below is the the instruction that describes the task: ### Input: Use this method to send photos. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendphoto Parameters: :param chat_id: Unique identifier for the target chat or username of the tar...
def remove_trailing_spaces(self, index=None): """Remove trailing spaces""" if index is None: index = self.get_stack_index() finfo = self.data[index] finfo.editor.remove_trailing_spaces()
Remove trailing spaces
Below is the the instruction that describes the task: ### Input: Remove trailing spaces ### Response: def remove_trailing_spaces(self, index=None): """Remove trailing spaces""" if index is None: index = self.get_stack_index() finfo = self.data[index] finfo.editor.re...
def update(self, measurement, measurement_matrix): """ After each :py:meth:`predict`, this method may be called repeatedly to provide additional measurements for each time step. Args: measurement (MultivariateNormal): Measurement for this time step with speci...
After each :py:meth:`predict`, this method may be called repeatedly to provide additional measurements for each time step. Args: measurement (MultivariateNormal): Measurement for this time step with specified mean and covariance. measurement_matrix (array): Measu...
Below is the the instruction that describes the task: ### Input: After each :py:meth:`predict`, this method may be called repeatedly to provide additional measurements for each time step. Args: measurement (MultivariateNormal): Measurement for this time step with specifi...
def magic(self, arg_s): """DEPRECATED. Use run_line_magic() instead. Call a magic function by name. Input: a string containing the name of the magic function to call and any additional arguments to be passed to the magic. magic('name -opt foo bar') is equivalent to typing at t...
DEPRECATED. Use run_line_magic() instead. Call a magic function by name. Input: a string containing the name of the magic function to call and any additional arguments to be passed to the magic. magic('name -opt foo bar') is equivalent to typing at the ipython prompt: ...
Below is the the instruction that describes the task: ### Input: DEPRECATED. Use run_line_magic() instead. Call a magic function by name. Input: a string containing the name of the magic function to call and any additional arguments to be passed to the magic. magic('name -opt foo ...
def rename(self): """ Renames the selected item in the tree view """ src = self.get_current_path() pardir, name = os.path.split(src) new_name, status = QtWidgets.QInputDialog.getText( self.tree_view, _('Rename '), _('New name:'), QtWidgets.QLineEdi...
Renames the selected item in the tree view
Below is the the instruction that describes the task: ### Input: Renames the selected item in the tree view ### Response: def rename(self): """ Renames the selected item in the tree view """ src = self.get_current_path() pardir, name = os.path.split(src) new_name, st...
def depth(n, tree): """get depth of an element in the tree""" d = 0 parent = tree[n] while parent is not None: d += 1 parent = tree[parent] return d
get depth of an element in the tree
Below is the the instruction that describes the task: ### Input: get depth of an element in the tree ### Response: def depth(n, tree): """get depth of an element in the tree""" d = 0 parent = tree[n] while parent is not None: d += 1 parent = tree[parent] return d
def walk(self, topdown=True, followlinks=True): """ walk: walk the filesystem (just like os.walk). Use like: path = URI('/some/dir') for root, dirs, files in path.walk(): do_something() root will be an URI object. """ return self.connection.w...
walk: walk the filesystem (just like os.walk). Use like: path = URI('/some/dir') for root, dirs, files in path.walk(): do_something() root will be an URI object.
Below is the the instruction that describes the task: ### Input: walk: walk the filesystem (just like os.walk). Use like: path = URI('/some/dir') for root, dirs, files in path.walk(): do_something() root will be an URI object. ### Response: def walk(self, topdown=True,...
def field_definition_post_save(sender, instance, created, raw, **kwargs): """ This signal is connected by all FieldDefinition subclasses see comment in FieldDefinitionBase for more details """ model_class = instance.model_def.model_class().render_state() field = instance.construct_for_migrate() ...
This signal is connected by all FieldDefinition subclasses see comment in FieldDefinitionBase for more details
Below is the the instruction that describes the task: ### Input: This signal is connected by all FieldDefinition subclasses see comment in FieldDefinitionBase for more details ### Response: def field_definition_post_save(sender, instance, created, raw, **kwargs): """ This signal is connected by all Fie...
def token_view(token): """Show token details.""" if request.method == "POST" and 'delete' in request.form: db.session.delete(token) db.session.commit() return redirect(url_for('.index')) show_token = session.pop('show_personal_access_token', False) form = TokenForm(request.form...
Show token details.
Below is the the instruction that describes the task: ### Input: Show token details. ### Response: def token_view(token): """Show token details.""" if request.method == "POST" and 'delete' in request.form: db.session.delete(token) db.session.commit() return redirect(url_for('.index'...
def get_asset_id(self): """Gets the ``Asset Id`` corresponding to this content. return: (osid.id.Id) - the asset ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id if not bool(se...
Gets the ``Asset Id`` corresponding to this content. return: (osid.id.Id) - the asset ``Id`` *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the ``Asset Id`` corresponding to this content. return: (osid.id.Id) - the asset ``Id`` *compliance: mandatory -- This method must be implemented.* ### Response: def get_asset_id(self): """Gets the ``Asset Id`` correspon...
def strip_accents(s): """ Strip accents to prepare for slugification. """ nfkd = unicodedata.normalize('NFKD', unicode(s)) return u''.join(ch for ch in nfkd if not unicodedata.combining(ch))
Strip accents to prepare for slugification.
Below is the the instruction that describes the task: ### Input: Strip accents to prepare for slugification. ### Response: def strip_accents(s): """ Strip accents to prepare for slugification. """ nfkd = unicodedata.normalize('NFKD', unicode(s)) return u''.join(ch for ch in nfkd if not unicoded...
def invertible_flatten2(unflat_list): """ An alternative to invertible_flatten1 which uses cumsum Flattens ``list`` but remember how to reconstruct the unflat ``list`` Returns flat ``list`` and the unflat ``list`` with indexes into the flat ``list`` Args: unflat_list (list): Retur...
An alternative to invertible_flatten1 which uses cumsum Flattens ``list`` but remember how to reconstruct the unflat ``list`` Returns flat ``list`` and the unflat ``list`` with indexes into the flat ``list`` Args: unflat_list (list): Returns: tuple: flat_list, cumlen_list See...
Below is the the instruction that describes the task: ### Input: An alternative to invertible_flatten1 which uses cumsum Flattens ``list`` but remember how to reconstruct the unflat ``list`` Returns flat ``list`` and the unflat ``list`` with indexes into the flat ``list`` Args: unflat_list...
def iddofobject(data, commdct, key): """from commdct, return the idd of the object key""" dtls = data.dtls i = dtls.index(key) return commdct[i]
from commdct, return the idd of the object key
Below is the the instruction that describes the task: ### Input: from commdct, return the idd of the object key ### Response: def iddofobject(data, commdct, key): """from commdct, return the idd of the object key""" dtls = data.dtls i = dtls.index(key) return commdct[i]
def extra(self): """ Return the extra parameters that this instance. Extra meaning those that are not listed in the c_params specification. :return: The key,value pairs for keys that are not in the c_params specification, """ return dict([(key, val) f...
Return the extra parameters that this instance. Extra meaning those that are not listed in the c_params specification. :return: The key,value pairs for keys that are not in the c_params specification,
Below is the the instruction that describes the task: ### Input: Return the extra parameters that this instance. Extra meaning those that are not listed in the c_params specification. :return: The key,value pairs for keys that are not in the c_params specification, ### Response:...
def loadavg(): ''' Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python ''' if __gr...
Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report loadaverages to Python
Below is the the instruction that describes the task: ### Input: Return the load averages for this minion .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' status.loadavg :raises CommandExecutionError: If the system cannot report ...
def _emitHMM(self, token_type, past_states, past_emissions): """ emits a word based on previous tokens """ assert token_type in self.emissions return utils.weighted_choice(self.emissions[token_type].items())
emits a word based on previous tokens
Below is the the instruction that describes the task: ### Input: emits a word based on previous tokens ### Response: def _emitHMM(self, token_type, past_states, past_emissions): """ emits a word based on previous tokens """ assert token_type in self.emissions return utils.weighted_choice(se...
async def getWorker(self, *args, **kwargs): """ Get a worker-type Get a worker from a worker-type. This method gives output: ``v1/worker-response.json#`` This method is ``experimental`` """ return await self._makeApiCall(self.funcinfo["getWorker"], *args, **kw...
Get a worker-type Get a worker from a worker-type. This method gives output: ``v1/worker-response.json#`` This method is ``experimental``
Below is the the instruction that describes the task: ### Input: Get a worker-type Get a worker from a worker-type. This method gives output: ``v1/worker-response.json#`` This method is ``experimental`` ### Response: async def getWorker(self, *args, **kwargs): """ Get a w...
def _update_report_item(self, **update_props): """ Update the text for each element at the configured path if attribute matches """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = wrap_value(update_props['values']) xroot = self._get_xroot_for...
Update the text for each element at the configured path if attribute matches
Below is the the instruction that describes the task: ### Input: Update the text for each element at the configured path if attribute matches ### Response: def _update_report_item(self, **update_props): """ Update the text for each element at the configured path if attribute matches """ tree_to_up...