code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def rbac_policy_update(request, policy_id, **kwargs): """Update a RBAC Policy. :param request: request context :param policy_id: target policy id :param target_tenant: target tenant of the policy :return: RBACPolicy object """ body = {'rbac_policy': kwargs} rbac_policy = neutronclient(r...
Update a RBAC Policy. :param request: request context :param policy_id: target policy id :param target_tenant: target tenant of the policy :return: RBACPolicy object
Below is the the instruction that describes the task: ### Input: Update a RBAC Policy. :param request: request context :param policy_id: target policy id :param target_tenant: target tenant of the policy :return: RBACPolicy object ### Response: def rbac_policy_update(request, policy_id, **kwargs):...
def query_hek(time, time_window=1): """ requests hek responses for a given time :param time: datetime object :param time_window: how far in hours on either side of the input time to look for results :return: hek response list """ hek_client = hek.HEKClient() start_time = time - timedelta...
requests hek responses for a given time :param time: datetime object :param time_window: how far in hours on either side of the input time to look for results :return: hek response list
Below is the the instruction that describes the task: ### Input: requests hek responses for a given time :param time: datetime object :param time_window: how far in hours on either side of the input time to look for results :return: hek response list ### Response: def query_hek(time, time_window=1): ...
def style_from_dict(style_dict, include_defaults=True): """ Create a ``Style`` instance from a dictionary or other mapping. The dictionary is equivalent to the ``Style.styles`` dictionary from pygments, with a few additions: it supports 'reverse' and 'blink'. Usage:: style_from_dict({ ...
Create a ``Style`` instance from a dictionary or other mapping. The dictionary is equivalent to the ``Style.styles`` dictionary from pygments, with a few additions: it supports 'reverse' and 'blink'. Usage:: style_from_dict({ Token: '#ff0000 bold underline', Token.Title: '...
Below is the the instruction that describes the task: ### Input: Create a ``Style`` instance from a dictionary or other mapping. The dictionary is equivalent to the ``Style.styles`` dictionary from pygments, with a few additions: it supports 'reverse' and 'blink'. Usage:: style_from_dict({ ...
def merge(self, target, source, target_comment=None, source_comment=None): """ Merge the ticket(s) or ticket ID(s) in source into the target ticket. :param target: ticket id or object to merge tickets into :param source: ticket id, object or list of tickets or ids to merge...
Merge the ticket(s) or ticket ID(s) in source into the target ticket. :param target: ticket id or object to merge tickets into :param source: ticket id, object or list of tickets or ids to merge into target :param source_comment: optional comment for the source ticket(s) :param target_c...
Below is the the instruction that describes the task: ### Input: Merge the ticket(s) or ticket ID(s) in source into the target ticket. :param target: ticket id or object to merge tickets into :param source: ticket id, object or list of tickets or ids to merge into target :param source_comme...
def _recursive_round(self, value, precision): """ Round all numbers within an array or nested arrays value: number or nested array of numbers precision: integer valueue of number of decimals to keep """ if hasattr(value, '__iter__'): return tuple(self....
Round all numbers within an array or nested arrays value: number or nested array of numbers precision: integer valueue of number of decimals to keep
Below is the the instruction that describes the task: ### Input: Round all numbers within an array or nested arrays value: number or nested array of numbers precision: integer valueue of number of decimals to keep ### Response: def _recursive_round(self, value, precision): """ ...
def Lomb_Scargle(data, precision, min_period, max_period, period_jobs=1): """ Returns the period of *data* according to the `Lomb-Scargle periodogram <https://en.wikipedia.org/wiki/Least-squares_spectral_analysis#The_Lomb.E2.80.93Scargle_periodogram>`_. **Parameters** data : array-like, shape = [n...
Returns the period of *data* according to the `Lomb-Scargle periodogram <https://en.wikipedia.org/wiki/Least-squares_spectral_analysis#The_Lomb.E2.80.93Scargle_periodogram>`_. **Parameters** data : array-like, shape = [n_samples, 2] or [n_samples, 3] Array containing columns *time*, *mag*, and (op...
Below is the the instruction that describes the task: ### Input: Returns the period of *data* according to the `Lomb-Scargle periodogram <https://en.wikipedia.org/wiki/Least-squares_spectral_analysis#The_Lomb.E2.80.93Scargle_periodogram>`_. **Parameters** data : array-like, shape = [n_samples, 2] or [...
def to_json(self): """ Returns the JSON Representation of the resource. """ result = super(FieldsResource, self).to_json() result['fields'] = self.fields_with_locales() return result
Returns the JSON Representation of the resource.
Below is the the instruction that describes the task: ### Input: Returns the JSON Representation of the resource. ### Response: def to_json(self): """ Returns the JSON Representation of the resource. """ result = super(FieldsResource, self).to_json() result['fields'] = self...
def _approxaA(self,R,vR,vT,z,vz,phi,interp=True,cindx=None): """ NAME: _approxaA PURPOSE: return action-angle coordinates for a point based on the linear approximation around the stream track INPUT: R,vR,vT,z,vz,phi - phase-space coordinates o...
NAME: _approxaA PURPOSE: return action-angle coordinates for a point based on the linear approximation around the stream track INPUT: R,vR,vT,z,vz,phi - phase-space coordinates of the given point interp= (True), if True, use the interpolated track ...
Below is the the instruction that describes the task: ### Input: NAME: _approxaA PURPOSE: return action-angle coordinates for a point based on the linear approximation around the stream track INPUT: R,vR,vT,z,vz,phi - phase-space coordinates of the given ...
def validate_regex(ctx, param, value): """ Validate that a provided regex compiles. """ if not value: return None try: re.compile(value) except re.error: raise click.BadParameter('Invalid regex "{0}" provided'.format(value)) return value
Validate that a provided regex compiles.
Below is the the instruction that describes the task: ### Input: Validate that a provided regex compiles. ### Response: def validate_regex(ctx, param, value): """ Validate that a provided regex compiles. """ if not value: return None try: re.compile(value) except re.error: ...
def runs(self, path="", filters={}, order="-created_at", per_page=None): """Return a set of runs from a project that match the filters provided. You can filter by config.*, summary.*, state, username, createdAt, etc. The filters use the same query language as MongoDB: https://docs.mong...
Return a set of runs from a project that match the filters provided. You can filter by config.*, summary.*, state, username, createdAt, etc. The filters use the same query language as MongoDB: https://docs.mongodb.com/manual/reference/operator/query Order can be created_at, heartbeat_...
Below is the the instruction that describes the task: ### Input: Return a set of runs from a project that match the filters provided. You can filter by config.*, summary.*, state, username, createdAt, etc. The filters use the same query language as MongoDB: https://docs.mongodb.com/manual/...
def mergebam(args): """ %prog mergebam dir1 homo_outdir or %prog mergebam dir1 dir2/20.bam het_outdir Merge sets of BAMs to make diploid. Two modes: - Homozygous mode: pair-up the bams in the two folders and merge - Heterozygous mode: pair the bams in first folder with a particular bam ...
%prog mergebam dir1 homo_outdir or %prog mergebam dir1 dir2/20.bam het_outdir Merge sets of BAMs to make diploid. Two modes: - Homozygous mode: pair-up the bams in the two folders and merge - Heterozygous mode: pair the bams in first folder with a particular bam
Below is the the instruction that describes the task: ### Input: %prog mergebam dir1 homo_outdir or %prog mergebam dir1 dir2/20.bam het_outdir Merge sets of BAMs to make diploid. Two modes: - Homozygous mode: pair-up the bams in the two folders and merge - Heterozygous mode: pair the bams in fi...
def detect(self, stream, threshold, threshold_type, trig_int, plotvar, daylong=False, parallel_process=True, xcorr_func=None, concurrency=None, cores=None, ignore_length=False, group_size=None, overlap="calculate", debug=0, full_peaks=False, save_progress=Fals...
Detect using a Tribe of templates within a continuous stream. :type stream: `obspy.core.stream.Stream` :param stream: Continuous data to detect within using the Template. :type threshold: float :param threshold: Threshold level, if using `threshold_type='MAD'` then this will...
Below is the the instruction that describes the task: ### Input: Detect using a Tribe of templates within a continuous stream. :type stream: `obspy.core.stream.Stream` :param stream: Continuous data to detect within using the Template. :type threshold: float :param threshold: ...
def find_executable(executable, path=None): """ As distutils.spawn.find_executable, but on Windows, look up every extension declared in PATHEXT instead of just `.exe` """ if sys.platform != 'win32': return distutils.spawn.find_executable(executable, path) if path is None: path =...
As distutils.spawn.find_executable, but on Windows, look up every extension declared in PATHEXT instead of just `.exe`
Below is the the instruction that describes the task: ### Input: As distutils.spawn.find_executable, but on Windows, look up every extension declared in PATHEXT instead of just `.exe` ### Response: def find_executable(executable, path=None): """ As distutils.spawn.find_executable, but on Windows, look ...
def print(root): # type: (Union[Nonterminal,Terminal,Rule])-> str """ Transform the parsed tree to the string. Expects tree like structure. You can see example output below. (R)SplitRules26 |--(N)Iterate | `--(R)SplitRules30 | `--(N)Symb | ...
Transform the parsed tree to the string. Expects tree like structure. You can see example output below. (R)SplitRules26 |--(N)Iterate | `--(R)SplitRules30 | `--(N)Symb | `--(R)SplitRules4 | `--(T)e `--(N)Concat `--(R)Split...
Below is the the instruction that describes the task: ### Input: Transform the parsed tree to the string. Expects tree like structure. You can see example output below. (R)SplitRules26 |--(N)Iterate | `--(R)SplitRules30 | `--(N)Symb | `--(R)SplitRules4 ...
def fullname(self): """ includes the full path with parent names """ prefix = "" if self.parent: if self.parent.fullname: prefix = self.parent.fullname + ":" else: # Only the root does not have a parent. In that case we also don't need a name. ...
includes the full path with parent names
Below is the the instruction that describes the task: ### Input: includes the full path with parent names ### Response: def fullname(self): """ includes the full path with parent names """ prefix = "" if self.parent: if self.parent.fullname: prefix = self.parent....
def to_bytes(s, encoding=None, errors=None): '''Convert *s* into bytes''' if not isinstance(s, bytes): return ('%s' % s).encode(encoding or 'utf-8', errors or 'strict') elif not encoding or encoding == 'utf-8': return s else: d = s.decode('utf-8') return d.encode(encoding...
Convert *s* into bytes
Below is the the instruction that describes the task: ### Input: Convert *s* into bytes ### Response: def to_bytes(s, encoding=None, errors=None): '''Convert *s* into bytes''' if not isinstance(s, bytes): return ('%s' % s).encode(encoding or 'utf-8', errors or 'strict') elif not encoding or enc...
def igrf12syn(isv, date, itype, alt, lat, elong): """ This is a synthesis routine for the 12th generation IGRF as agreed in December 2014 by IAGA Working Group V-MOD. It is valid 1900.0 to 2020.0 inclusive. Values for dates from 1945.0 to 2010.0 inclusive are definitive, otherwise they are non-d...
This is a synthesis routine for the 12th generation IGRF as agreed in December 2014 by IAGA Working Group V-MOD. It is valid 1900.0 to 2020.0 inclusive. Values for dates from 1945.0 to 2010.0 inclusive are definitive, otherwise they are non-definitive. INPUT isv = 0 if main-field values are req...
Below is the the instruction that describes the task: ### Input: This is a synthesis routine for the 12th generation IGRF as agreed in December 2014 by IAGA Working Group V-MOD. It is valid 1900.0 to 2020.0 inclusive. Values for dates from 1945.0 to 2010.0 inclusive are definitive, otherwise they are...
def format(self): """ Get the subtag code conventional format according to RFC 5646 section 2.1.1. :return: string -- subtag code conventional format. """ subtag = self.data['subtag'] if self.data['type'] == 'region': return subtag.upper() if self.dat...
Get the subtag code conventional format according to RFC 5646 section 2.1.1. :return: string -- subtag code conventional format.
Below is the the instruction that describes the task: ### Input: Get the subtag code conventional format according to RFC 5646 section 2.1.1. :return: string -- subtag code conventional format. ### Response: def format(self): """ Get the subtag code conventional format according to RFC 564...
def pull_byte(self, stack_pointer): """ pulled a byte from stack """ addr = stack_pointer.value byte = self.memory.read_byte(addr) # log.info( # log.error( # "%x|\tpull $%x from %s stack at $%x\t|%s", # self.last_op_address, byte, stack_pointer.name, addr, # ...
pulled a byte from stack
Below is the the instruction that describes the task: ### Input: pulled a byte from stack ### Response: def pull_byte(self, stack_pointer): """ pulled a byte from stack """ addr = stack_pointer.value byte = self.memory.read_byte(addr) # log.info( # log.error( # "%x...
def wallet_frontiers(self, wallet): """ Returns a list of pairs of account and block hash representing the head block starting for accounts from **wallet** :param wallet: Wallet to return frontiers for :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` ...
Returns a list of pairs of account and block hash representing the head block starting for accounts from **wallet** :param wallet: Wallet to return frontiers for :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_frontiers( ... wallet="000D1B...
Below is the the instruction that describes the task: ### Input: Returns a list of pairs of account and block hash representing the head block starting for accounts from **wallet** :param wallet: Wallet to return frontiers for :type wallet: str :raises: :py:exc:`nano.rpc.RPCExcepti...
def places_within_radius( self, place=None, latitude=None, longitude=None, radius=0, **kwargs ): """ Return descriptions of the places stored in the collection that are within the circle specified by the given location and radius. A list of dicts will be returned. Th...
Return descriptions of the places stored in the collection that are within the circle specified by the given location and radius. A list of dicts will be returned. The center of the circle can be specified by the identifier of another place in the collection with the *place* keyword arg...
Below is the the instruction that describes the task: ### Input: Return descriptions of the places stored in the collection that are within the circle specified by the given location and radius. A list of dicts will be returned. The center of the circle can be specified by the identifier of...
def make_content_range(self, length): """Creates a :class:`~werkzeug.datastructures.ContentRange` object from the current range and given content length. """ rng = self.range_for_length(length) if rng is not None: return ContentRange(self.units, rng[0], rng[1], length...
Creates a :class:`~werkzeug.datastructures.ContentRange` object from the current range and given content length.
Below is the the instruction that describes the task: ### Input: Creates a :class:`~werkzeug.datastructures.ContentRange` object from the current range and given content length. ### Response: def make_content_range(self, length): """Creates a :class:`~werkzeug.datastructures.ContentRange` object ...
def _increment_stage(self): """ Purpose: Increment stage pointer. Also check if Pipeline has completed. """ try: if self._cur_stage < self._stage_count: self._cur_stage += 1 else: self._completed_flag.set() except Excepti...
Purpose: Increment stage pointer. Also check if Pipeline has completed.
Below is the the instruction that describes the task: ### Input: Purpose: Increment stage pointer. Also check if Pipeline has completed. ### Response: def _increment_stage(self): """ Purpose: Increment stage pointer. Also check if Pipeline has completed. """ try: if se...
def lock_pidfile_or_die(pidfile): """ @pidfile: must be a writable path Exceptions are logged. Returns the PID. """ pid = os.getpid() try: remove_if_stale_pidfile(pidfile) pid_write_file = pidfile + '.' + str(pid) fpid = open(pid_write_file, 'w') try...
@pidfile: must be a writable path Exceptions are logged. Returns the PID.
Below is the the instruction that describes the task: ### Input: @pidfile: must be a writable path Exceptions are logged. Returns the PID. ### Response: def lock_pidfile_or_die(pidfile): """ @pidfile: must be a writable path Exceptions are logged. Returns the PID. ""...
def debug_print_strip_msg(self, i, line): """ Debug print indicating that an empty line is being skipped :param i: The line number of the line that is being currently parsed :param line: the parsed line :return: None """ if self.debug_level == 2: print...
Debug print indicating that an empty line is being skipped :param i: The line number of the line that is being currently parsed :param line: the parsed line :return: None
Below is the the instruction that describes the task: ### Input: Debug print indicating that an empty line is being skipped :param i: The line number of the line that is being currently parsed :param line: the parsed line :return: None ### Response: def debug_print_strip_msg(self, i, line):...
def get_previous_price_list(self, currency, start_date, end_date): """ Get List of prices between two dates """ start = start_date.strftime('%Y-%m-%d') end = end_date.strftime('%Y-%m-%d') url = ( 'https://api.coindesk.com/v1/bpi/historical/close.json' ...
Get List of prices between two dates
Below is the the instruction that describes the task: ### Input: Get List of prices between two dates ### Response: def get_previous_price_list(self, currency, start_date, end_date): """ Get List of prices between two dates """ start = start_date.strftime('%Y-%m-%d') end = e...
def get_devices(self, condition=None, page_size=1000): """Iterates over each :class:`Device` for this device cloud account Examples:: # get a list of all devices all_devices = list(dc.devicecore.get_devices()) # build a mapping of devices by their vendor id using a...
Iterates over each :class:`Device` for this device cloud account Examples:: # get a list of all devices all_devices = list(dc.devicecore.get_devices()) # build a mapping of devices by their vendor id using a # dict comprehension devices = dc.devicec...
Below is the the instruction that describes the task: ### Input: Iterates over each :class:`Device` for this device cloud account Examples:: # get a list of all devices all_devices = list(dc.devicecore.get_devices()) # build a mapping of devices by their vendor id usin...
def download_sample_and_align(job, sample, inputs, ids): """ Downloads the sample and runs BWA-kit :param JobFunctionWrappingJob job: Passed by Toil automatically :param tuple(str, list) sample: UUID and URLS for sample :param Namespace inputs: Contains input arguments :param dict ids: FileStor...
Downloads the sample and runs BWA-kit :param JobFunctionWrappingJob job: Passed by Toil automatically :param tuple(str, list) sample: UUID and URLS for sample :param Namespace inputs: Contains input arguments :param dict ids: FileStore IDs for shared inputs
Below is the the instruction that describes the task: ### Input: Downloads the sample and runs BWA-kit :param JobFunctionWrappingJob job: Passed by Toil automatically :param tuple(str, list) sample: UUID and URLS for sample :param Namespace inputs: Contains input arguments :param dict ids: FileStor...
def features_properties_null_remove(obj): """ Remove any properties of features in the collection that have entries mapping to a null (i.e., None) value """ features = obj['features'] for i in tqdm(range(len(features))): if 'properties' in features[i]: properties = features[...
Remove any properties of features in the collection that have entries mapping to a null (i.e., None) value
Below is the the instruction that describes the task: ### Input: Remove any properties of features in the collection that have entries mapping to a null (i.e., None) value ### Response: def features_properties_null_remove(obj): """ Remove any properties of features in the collection that have ent...
def merge(self, keypath, value, op='set'): """ First gets the cell at BeliefState's keypath, or creates a new cell from the first target that has that keypath (This could mess up if the member its copying from has a different Cell or domain for that keypath.) Second, this merges...
First gets the cell at BeliefState's keypath, or creates a new cell from the first target that has that keypath (This could mess up if the member its copying from has a different Cell or domain for that keypath.) Second, this merges that cell with the value
Below is the the instruction that describes the task: ### Input: First gets the cell at BeliefState's keypath, or creates a new cell from the first target that has that keypath (This could mess up if the member its copying from has a different Cell or domain for that keypath.) Second, this ...
def excel_to_sql(excel_file_path, engine, read_excel_kwargs=None, to_generic_type_kwargs=None, to_sql_kwargs=None): """Create a database from excel. :param read_excel_kwargs: dict, arguments for ``pandas.read_excel`` method. example: ``{"employee": {"ski...
Create a database from excel. :param read_excel_kwargs: dict, arguments for ``pandas.read_excel`` method. example: ``{"employee": {"skiprows": 10}, "department": {}}`` :param to_sql_kwargs: dict, arguments for ``pandas.DataFrame.to_sql`` method. limitation: 1. If a integer column has Non...
Below is the the instruction that describes the task: ### Input: Create a database from excel. :param read_excel_kwargs: dict, arguments for ``pandas.read_excel`` method. example: ``{"employee": {"skiprows": 10}, "department": {}}`` :param to_sql_kwargs: dict, arguments for ``pandas.DataFrame.to_sql`...
def compute_alignments(self, prev_state, precomputed_values, mask=None): """ Compute the alignment weights based on the previous state. """ WaSp = T.dot(prev_state, self.Wa) UaH = precomputed_values # For test time the UaH will be (time, output_dim) if UaH.ndim =...
Compute the alignment weights based on the previous state.
Below is the the instruction that describes the task: ### Input: Compute the alignment weights based on the previous state. ### Response: def compute_alignments(self, prev_state, precomputed_values, mask=None): """ Compute the alignment weights based on the previous state. """ WaSp...
def solve(self, lam): '''Solves the GFL for a fixed value of lambda.''' s = weighted_graphtf(self.nnodes, self.y, self.weights, lam, self.Dk.shape[0], self.Dk.shape[1], self.Dk.nnz, self.Dk.row.astype('int32'), self.Dk.col.astype('int32'), self.D...
Solves the GFL for a fixed value of lambda.
Below is the the instruction that describes the task: ### Input: Solves the GFL for a fixed value of lambda. ### Response: def solve(self, lam): '''Solves the GFL for a fixed value of lambda.''' s = weighted_graphtf(self.nnodes, self.y, self.weights, lam, self.Dk.shape[...
def period(self): """Period of the orbit as a timedelta """ return timedelta(seconds=2 * np.pi * np.sqrt(self.kep.a ** 3 / self.mu))
Period of the orbit as a timedelta
Below is the the instruction that describes the task: ### Input: Period of the orbit as a timedelta ### Response: def period(self): """Period of the orbit as a timedelta """ return timedelta(seconds=2 * np.pi * np.sqrt(self.kep.a ** 3 / self.mu))
def quandl_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, cache, show_progress...
quandl_bundle builds a daily dataset using Quandl's WIKI Prices dataset. For more information on Quandl's API and how to obtain an API key, please visit https://docs.quandl.com/docs#section-authentication
Below is the the instruction that describes the task: ### Input: quandl_bundle builds a daily dataset using Quandl's WIKI Prices dataset. For more information on Quandl's API and how to obtain an API key, please visit https://docs.quandl.com/docs#section-authentication ### Response: def quandl_bundle(envi...
def state(self): """Returns a new JIT state. You have to clean up by calling .destroy() afterwards. """ return Emitter(weakref.proxy(self.lib), self.lib.jit_new_state())
Returns a new JIT state. You have to clean up by calling .destroy() afterwards.
Below is the the instruction that describes the task: ### Input: Returns a new JIT state. You have to clean up by calling .destroy() afterwards. ### Response: def state(self): """Returns a new JIT state. You have to clean up by calling .destroy() afterwards. """ return Emitt...
def get_share_url_with_dirname(uk, shareid, dirname): '''得到共享目录的链接''' return ''.join([ const.PAN_URL, 'wap/link', '?shareid=', shareid, '&uk=', uk, '&dir=', encoder.encode_uri_component(dirname), '&third=0', ])
得到共享目录的链接
Below is the the instruction that describes the task: ### Input: 得到共享目录的链接 ### Response: def get_share_url_with_dirname(uk, shareid, dirname): '''得到共享目录的链接''' return ''.join([ const.PAN_URL, 'wap/link', '?shareid=', shareid, '&uk=', uk, '&dir=', encoder.encode_ur...
def getEAnnotation(self, source): """Return the annotation with a matching source attribute.""" for annotation in self.eAnnotations: if annotation.source == source: return annotation return None
Return the annotation with a matching source attribute.
Below is the the instruction that describes the task: ### Input: Return the annotation with a matching source attribute. ### Response: def getEAnnotation(self, source): """Return the annotation with a matching source attribute.""" for annotation in self.eAnnotations: if annotation.sourc...
def _read_response(self, response): """ JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON """ self.name = response['key'] self.description = response['description'] self.layoutName = response['repoLayoutRef'] self.archi...
JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON
Below is the the instruction that describes the task: ### Input: JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configuration+JSON ### Response: def _read_response(self, response): """ JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Repository+Configura...
def _analyze_file(self, f): """Analyze the file.""" f.seek(0) # Check for BOMs if self.CHECK_BOM: encoding = self.has_bom(f) f.seek(0) else: util.warn_deprecated( "'CHECK_BOM' attribute is deprecated. " "Please ...
Analyze the file.
Below is the the instruction that describes the task: ### Input: Analyze the file. ### Response: def _analyze_file(self, f): """Analyze the file.""" f.seek(0) # Check for BOMs if self.CHECK_BOM: encoding = self.has_bom(f) f.seek(0) else: ...
def origin_east_asia(origin): """\ Returns if the origin is located in East Asia Holds true for the following countries: * China * Japan * Mongolia * South Korea * Taiwan `origin` The origin to check. """ return origin_china(origin) or origin_jap...
\ Returns if the origin is located in East Asia Holds true for the following countries: * China * Japan * Mongolia * South Korea * Taiwan `origin` The origin to check.
Below is the the instruction that describes the task: ### Input: \ Returns if the origin is located in East Asia Holds true for the following countries: * China * Japan * Mongolia * South Korea * Taiwan `origin` The origin to check. ### Response: def or...
def normalize(self) -> 'State': """Normalize the state""" tensor = self.tensor / bk.ccast(bk.sqrt(self.norm())) return State(tensor, self.qubits, self._memory)
Normalize the state
Below is the the instruction that describes the task: ### Input: Normalize the state ### Response: def normalize(self) -> 'State': """Normalize the state""" tensor = self.tensor / bk.ccast(bk.sqrt(self.norm())) return State(tensor, self.qubits, self._memory)
def _load_poses(self): """Load ground truth poses (T_w_cam0) from file.""" pose_file = os.path.join(self.pose_path, self.sequence + '.txt') # Read and parse the poses poses = [] try: with open(pose_file, 'r') as f: lines = f.readlines() ...
Load ground truth poses (T_w_cam0) from file.
Below is the the instruction that describes the task: ### Input: Load ground truth poses (T_w_cam0) from file. ### Response: def _load_poses(self): """Load ground truth poses (T_w_cam0) from file.""" pose_file = os.path.join(self.pose_path, self.sequence + '.txt') # Read and parse the pose...
def get_creation_date( self, bucket: str, key: str, ) -> datetime: """ Retrieves the creation date for a given key in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which the creation date is ...
Retrieves the creation date for a given key in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which the creation date is being retrieved. :return: the creation date
Below is the the instruction that describes the task: ### Input: Retrieves the creation date for a given key in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which the creation date is being retrieved. :return: the creation date ### Re...
def _pop_comment_block(self, statements, header_re): """Look for a series of comments that start with one that matches the regex. If the first comment is found, all subsequent comments are popped from statements, concatenated and dedented and returned. """ res = [] commen...
Look for a series of comments that start with one that matches the regex. If the first comment is found, all subsequent comments are popped from statements, concatenated and dedented and returned.
Below is the the instruction that describes the task: ### Input: Look for a series of comments that start with one that matches the regex. If the first comment is found, all subsequent comments are popped from statements, concatenated and dedented and returned. ### Response: def _pop_comment_block(...
def covlen(args): """ %prog covlen covfile fastafile Plot coverage vs length. `covfile` is two-column listing contig id and depth of coverage. """ import numpy as np import pandas as pd import seaborn as sns from jcvi.formats.base import DictFile p = OptionParser(covlen.__doc__...
%prog covlen covfile fastafile Plot coverage vs length. `covfile` is two-column listing contig id and depth of coverage.
Below is the the instruction that describes the task: ### Input: %prog covlen covfile fastafile Plot coverage vs length. `covfile` is two-column listing contig id and depth of coverage. ### Response: def covlen(args): """ %prog covlen covfile fastafile Plot coverage vs length. `covfile` is tw...
def get_contacts(self): """ Fetches list of all contacts This will return chats with people from the address book only Use get_all_chats for all chats :return: List of contacts :rtype: list[Contact] """ all_contacts = self.wapi_functions.getAllContacts() ...
Fetches list of all contacts This will return chats with people from the address book only Use get_all_chats for all chats :return: List of contacts :rtype: list[Contact]
Below is the the instruction that describes the task: ### Input: Fetches list of all contacts This will return chats with people from the address book only Use get_all_chats for all chats :return: List of contacts :rtype: list[Contact] ### Response: def get_contacts(self): ...
def interp(self, new_timestamps, interpolation_mode=0): """ returns a new *Signal* interpolated using the *new_timestamps* Parameters ---------- new_timestamps : np.array timestamps used for interpolation interpolation_mode : int interpolation mode for in...
returns a new *Signal* interpolated using the *new_timestamps* Parameters ---------- new_timestamps : np.array timestamps used for interpolation interpolation_mode : int interpolation mode for integer signals; default 0 * 0 - repeat previous samp...
Below is the the instruction that describes the task: ### Input: returns a new *Signal* interpolated using the *new_timestamps* Parameters ---------- new_timestamps : np.array timestamps used for interpolation interpolation_mode : int interpolation mode for i...
def set_sequence_from_str(self, sequence): """ This is a convenience method to set the new QKeySequence of the shortcut editor from a string. """ self._qsequences = [QKeySequence(s) for s in sequence.split(', ')] self.update_warning()
This is a convenience method to set the new QKeySequence of the shortcut editor from a string.
Below is the the instruction that describes the task: ### Input: This is a convenience method to set the new QKeySequence of the shortcut editor from a string. ### Response: def set_sequence_from_str(self, sequence): """ This is a convenience method to set the new QKeySequence of the ...
def restore(self): """ Unloads all modules that weren't loaded when save_modules was called. """ sys = set(self._sys_modules.keys()) for mod_name in sys.difference(self._saved_modules): del self._sys_modules[mod_name]
Unloads all modules that weren't loaded when save_modules was called.
Below is the the instruction that describes the task: ### Input: Unloads all modules that weren't loaded when save_modules was called. ### Response: def restore(self): """ Unloads all modules that weren't loaded when save_modules was called. """ sys = set(self._sys_modules.keys()) ...
def unload_extension(self, module_str): """Unload an IPython extension by its module name. This function looks up the extension's name in ``sys.modules`` and simply calls ``mod.unload_ipython_extension(self)``. """ if module_str in sys.modules: mod = sys.modules[modu...
Unload an IPython extension by its module name. This function looks up the extension's name in ``sys.modules`` and simply calls ``mod.unload_ipython_extension(self)``.
Below is the the instruction that describes the task: ### Input: Unload an IPython extension by its module name. This function looks up the extension's name in ``sys.modules`` and simply calls ``mod.unload_ipython_extension(self)``. ### Response: def unload_extension(self, module_str): """...
def list_data_links(self, instance): """ Lists the data links visible to this client. Data links are returned in random order. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Link] """ # Server does not do pagination on listings of thi...
Lists the data links visible to this client. Data links are returned in random order. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Link]
Below is the the instruction that describes the task: ### Input: Lists the data links visible to this client. Data links are returned in random order. :param str instance: A Yamcs instance name. :rtype: ~collections.Iterable[.Link] ### Response: def list_data_links(self, instance): ...
def set_type_by_schema(self, schema_obj, schema_type): """ Set property type by schema object Schema will create, if it doesn't exists in collection :param dict schema_obj: raw schema object :param str schema_type: """ schema_id = self._get_object_schema_id(schem...
Set property type by schema object Schema will create, if it doesn't exists in collection :param dict schema_obj: raw schema object :param str schema_type:
Below is the the instruction that describes the task: ### Input: Set property type by schema object Schema will create, if it doesn't exists in collection :param dict schema_obj: raw schema object :param str schema_type: ### Response: def set_type_by_schema(self, schema_obj, schema_type): ...
def with_metaclass(meta, *bases): """ Create a base class with a metaclass. For example, if you have the metaclass >>> class Meta(type): ... pass Use this as the metaclass by doing >>> from symengine.compatibility import with_metaclass >>> class MyClass(with_metaclass(Meta, objec...
Create a base class with a metaclass. For example, if you have the metaclass >>> class Meta(type): ... pass Use this as the metaclass by doing >>> from symengine.compatibility import with_metaclass >>> class MyClass(with_metaclass(Meta, object)): ... pass This is equivalent ...
Below is the the instruction that describes the task: ### Input: Create a base class with a metaclass. For example, if you have the metaclass >>> class Meta(type): ... pass Use this as the metaclass by doing >>> from symengine.compatibility import with_metaclass >>> class MyClass(wit...
def _get_text(self): """ Get the text corresponding to this page """ boxes = self.boxes txt = [] for line in boxes: txt_line = u"" for box in line.word_boxes: txt_line += u" " + box.content txt.append(txt_line) r...
Get the text corresponding to this page
Below is the the instruction that describes the task: ### Input: Get the text corresponding to this page ### Response: def _get_text(self): """ Get the text corresponding to this page """ boxes = self.boxes txt = [] for line in boxes: txt_line = u"" ...
def sense_ttb(self, target): """Activate the RF field and probe for a Type B Target. The RC-S956 can discover Type B Targets (Type 4B Tag) at 106 kbps. For a Type 4B Tag the firmware automatically sends an ATTRIB command that configures the use of DID and 64 byte maximum frame s...
Activate the RF field and probe for a Type B Target. The RC-S956 can discover Type B Targets (Type 4B Tag) at 106 kbps. For a Type 4B Tag the firmware automatically sends an ATTRIB command that configures the use of DID and 64 byte maximum frame size. The driver reverts this configurati...
Below is the the instruction that describes the task: ### Input: Activate the RF field and probe for a Type B Target. The RC-S956 can discover Type B Targets (Type 4B Tag) at 106 kbps. For a Type 4B Tag the firmware automatically sends an ATTRIB command that configures the use of DID and 64...
def _process_messages(self, messages): """Send messages to the `processor` callback to be processed In the case we have a commit policy, we send messages to the processor in blocks no bigger than auto_commit_every_n (if set). Otherwise, we send the entire message block to be processed. ...
Send messages to the `processor` callback to be processed In the case we have a commit policy, we send messages to the processor in blocks no bigger than auto_commit_every_n (if set). Otherwise, we send the entire message block to be processed.
Below is the the instruction that describes the task: ### Input: Send messages to the `processor` callback to be processed In the case we have a commit policy, we send messages to the processor in blocks no bigger than auto_commit_every_n (if set). Otherwise, we send the entire message bloc...
def json(self, dict=False, **kwargs): """ Outputs NetJSON format """ try: graph = self.graph except AttributeError: raise NotImplementedError() return _netjson_networkgraph(self.protocol, self.version, ...
Outputs NetJSON format
Below is the the instruction that describes the task: ### Input: Outputs NetJSON format ### Response: def json(self, dict=False, **kwargs): """ Outputs NetJSON format """ try: graph = self.graph except AttributeError: raise NotImplementedError() ...
def derive(self, modifier): """ Returns a new :class:`Event` instance that will fire when this event fires. The value passed to the callbacks to the new event is the return value of the given `modifier` function which is passed the original value. """ def forward(...
Returns a new :class:`Event` instance that will fire when this event fires. The value passed to the callbacks to the new event is the return value of the given `modifier` function which is passed the original value.
Below is the the instruction that describes the task: ### Input: Returns a new :class:`Event` instance that will fire when this event fires. The value passed to the callbacks to the new event is the return value of the given `modifier` function which is passed the original value. ### Respons...
def verify_client_id(self): """ Verify a provided client id against the database and set the `Client` object that is associated with it to `self.client`. TODO: Document all of the thrown exceptions. """ from .models import Client from .exceptions.invalid_client ...
Verify a provided client id against the database and set the `Client` object that is associated with it to `self.client`. TODO: Document all of the thrown exceptions.
Below is the the instruction that describes the task: ### Input: Verify a provided client id against the database and set the `Client` object that is associated with it to `self.client`. TODO: Document all of the thrown exceptions. ### Response: def verify_client_id(self): """ Veri...
def contains(self, key, counter_id): """ Return whether a counter_id is present for a given instance key. If the key is not in the cache, raises a KeyError. """ with self._lock: return counter_id in self._metadata[key]
Return whether a counter_id is present for a given instance key. If the key is not in the cache, raises a KeyError.
Below is the the instruction that describes the task: ### Input: Return whether a counter_id is present for a given instance key. If the key is not in the cache, raises a KeyError. ### Response: def contains(self, key, counter_id): """ Return whether a counter_id is present for a given inst...
def get_label(self,callb=None): """Convenience method to request the label from the device This method will check whether the value has already been retrieved from the device, if so, it will simply return it. If no, it will request the information from the device and request that callb ...
Convenience method to request the label from the device This method will check whether the value has already been retrieved from the device, if so, it will simply return it. If no, it will request the information from the device and request that callb be executed when a response is received. Th...
Below is the the instruction that describes the task: ### Input: Convenience method to request the label from the device This method will check whether the value has already been retrieved from the device, if so, it will simply return it. If no, it will request the information from the device ...
def pkcs7_unpad(data): """ Remove the padding bytes that were added at point of encryption. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 """ if isinstance(data, str): return data[0:-ord(data[-1])] else: ...
Remove the padding bytes that were added at point of encryption. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209
Below is the the instruction that describes the task: ### Input: Remove the padding bytes that were added at point of encryption. Implementation copied from pyaspora: https://github.com/mjnovice/pyaspora/blob/master/pyaspora/diaspora/protocol.py#L209 ### Response: def pkcs7_unpad(data): """ Remove...
def export(name, target=None, rev=None, user=None, username=None, password=None, force=False, overwrite=False, externals=True, trust=False, trust_failures=None): ''' Export a file or directory from an S...
Export a file or directory from an SVN repository name Address and path to the file or directory to be exported. target Name of the target directory where the checkout will put the working directory rev : None The name revision number to checkout. Enable "force" if the dir...
Below is the the instruction that describes the task: ### Input: Export a file or directory from an SVN repository name Address and path to the file or directory to be exported. target Name of the target directory where the checkout will put the working directory rev : None ...
def escape(url): ''' add escape character `|` to `url` ''' if salt.utils.platform.is_windows(): return url scheme = urlparse(url).scheme if not scheme: if url.startswith('|'): return url else: return '|{0}'.format(url) elif scheme == 'salt': ...
add escape character `|` to `url`
Below is the the instruction that describes the task: ### Input: add escape character `|` to `url` ### Response: def escape(url): ''' add escape character `|` to `url` ''' if salt.utils.platform.is_windows(): return url scheme = urlparse(url).scheme if not scheme: if url.st...
def get_memory_map_xml(self): """! @brief Generate GDB memory map XML. """ root = ElementTree.Element('memory-map') for r in self._context.core.memory_map: # Look up the region type name. Regions default to ram if gdb doesn't # have a concept of the region type. ...
! @brief Generate GDB memory map XML.
Below is the the instruction that describes the task: ### Input: ! @brief Generate GDB memory map XML. ### Response: def get_memory_map_xml(self): """! @brief Generate GDB memory map XML. """ root = ElementTree.Element('memory-map') for r in self._context.core.memory_map: ...
def add_aggregated_lv_components(network, components): """ Aggregates LV load and generation at LV stations Use this function if you aim for MV calculation only. The according DataFrames of `components` are extended by load and generators representing these aggregated respecting the technology type...
Aggregates LV load and generation at LV stations Use this function if you aim for MV calculation only. The according DataFrames of `components` are extended by load and generators representing these aggregated respecting the technology type. Parameters ---------- network : Network The ...
Below is the the instruction that describes the task: ### Input: Aggregates LV load and generation at LV stations Use this function if you aim for MV calculation only. The according DataFrames of `components` are extended by load and generators representing these aggregated respecting the technology ty...
def assign_taxonomy( data, min_confidence=0.80, output_fp=None, training_data_fp=None, fixrank=True, max_memory=None, tmp_dir=tempfile.gettempdir()): """Assign taxonomy to each sequence in data with the RDP classifier data: open fasta file object or list of fasta lines confidence: m...
Assign taxonomy to each sequence in data with the RDP classifier data: open fasta file object or list of fasta lines confidence: minimum support threshold to assign taxonomy to a sequence output_fp: path to write output; if not provided, result will be returned in a dict of {seq_id:(ta...
Below is the the instruction that describes the task: ### Input: Assign taxonomy to each sequence in data with the RDP classifier data: open fasta file object or list of fasta lines confidence: minimum support threshold to assign taxonomy to a sequence output_fp: path to write output; if no...
def setup(self): """ *setup the workspace in the requested location* **Return:** - ``None`` """ self.log.info('starting the ``setup`` method') # RECURSIVELY CREATE MISSING DIRECTORIES if not os.path.exists(self.pathToWorkspace): os.makedi...
*setup the workspace in the requested location* **Return:** - ``None``
Below is the the instruction that describes the task: ### Input: *setup the workspace in the requested location* **Return:** - ``None`` ### Response: def setup(self): """ *setup the workspace in the requested location* **Return:** - ``None`` """ ...
def delete(self, id): """DELETE /layertemplates/id: Delete an existing item.""" # url('LayerTemplates', id=ID) lt = meta.Session.query(LayerTemplate).get(id) # use following query for getting a layertemplate owned by current user #lt = self._get_lt_from_user_by_id(c.user, id) ...
DELETE /layertemplates/id: Delete an existing item.
Below is the the instruction that describes the task: ### Input: DELETE /layertemplates/id: Delete an existing item. ### Response: def delete(self, id): """DELETE /layertemplates/id: Delete an existing item.""" # url('LayerTemplates', id=ID) lt = meta.Session.query(LayerTemplate).get(id) ...
def update(did): """Update DDO of an existing asset --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: DDO of the asset. schema: type: object required: - "@contex...
Update DDO of an existing asset --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: DDO of the asset. schema: type: object required: - "@context" - created...
Below is the the instruction that describes the task: ### Input: Update DDO of an existing asset --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: DDO of the asset. schema: type: obje...
def flatten_list(multiply_list): """ 碾平 list:: >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]] >>> flatten_list(a) [1, 2, 3, 4, 5, 6, 7, 8] :param multiply_list: 混淆的多层列表 :return: 单层的 list """ if isinstance(multiply_list, list): return [rv for l in multiply_list for rv ...
碾平 list:: >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]] >>> flatten_list(a) [1, 2, 3, 4, 5, 6, 7, 8] :param multiply_list: 混淆的多层列表 :return: 单层的 list
Below is the the instruction that describes the task: ### Input: 碾平 list:: >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]] >>> flatten_list(a) [1, 2, 3, 4, 5, 6, 7, 8] :param multiply_list: 混淆的多层列表 :return: 单层的 list ### Response: def flatten_list(multiply_list): """ 碾平 list:: ...
def get_go2sectiontxt(self): """Return a dict with actual header and user GO IDs as keys and their sections as values.""" go2txt = {} _get_secs = self.hdrobj.get_sections hdrgo2sectxt = {h:" ".join(_get_secs(h)) for h in self.get_hdrgos()} usrgo2hdrgo = self.get_usrgo2hdrgo() ...
Return a dict with actual header and user GO IDs as keys and their sections as values.
Below is the the instruction that describes the task: ### Input: Return a dict with actual header and user GO IDs as keys and their sections as values. ### Response: def get_go2sectiontxt(self): """Return a dict with actual header and user GO IDs as keys and their sections as values.""" go2txt = {}...
def get_fields(self, field_verbose=True, value_verbose=True, fields=[], extra_fields=[], remove_fields = []): ''' 返回字段名及其对应值的列表 field_verbose 为True,返回定义中的字段的verbose_name, False返回其name value_verbose 为True,返回数据的显示数据,会转换为choice的内容,为False, 返回数据的实际值 fields 指定了要显示的字段 extra_fiel...
返回字段名及其对应值的列表 field_verbose 为True,返回定义中的字段的verbose_name, False返回其name value_verbose 为True,返回数据的显示数据,会转换为choice的内容,为False, 返回数据的实际值 fields 指定了要显示的字段 extra_fields 指定了要特殊处理的非field,比如是函数 remove_fields 指定了不显示的字段
Below is the the instruction that describes the task: ### Input: 返回字段名及其对应值的列表 field_verbose 为True,返回定义中的字段的verbose_name, False返回其name value_verbose 为True,返回数据的显示数据,会转换为choice的内容,为False, 返回数据的实际值 fields 指定了要显示的字段 extra_fields 指定了要特殊处理的非field,比如是函数 remove_fields 指定了不显示的字段 ### ...
def rowCount(self, index=QModelIndex()): """Array row number""" if self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded
Array row number
Below is the the instruction that describes the task: ### Input: Array row number ### Response: def rowCount(self, index=QModelIndex()): """Array row number""" if self.total_rows <= self.rows_loaded: return self.total_rows else: return self.rows_loaded
def _archive_entry_year(self, category): " Return ARCHIVE_ENTRY_YEAR from settings (if exists) or year of the newest object in category " year = getattr(settings, 'ARCHIVE_ENTRY_YEAR', None) if not year: n = now() try: year = Listing.objects.filter( ...
Return ARCHIVE_ENTRY_YEAR from settings (if exists) or year of the newest object in category
Below is the the instruction that describes the task: ### Input: Return ARCHIVE_ENTRY_YEAR from settings (if exists) or year of the newest object in category ### Response: def _archive_entry_year(self, category): " Return ARCHIVE_ENTRY_YEAR from settings (if exists) or year of the newest object in category...
def list_bookmarks(self, start_date=None, end_date=None, limit=None): """List the aggregation's bookmarks.""" query = Search( using=self.client, index=self.aggregation_alias, doc_type=self.bookmark_doc_type ).sort({'date': {'order': 'desc'}}) range_ar...
List the aggregation's bookmarks.
Below is the the instruction that describes the task: ### Input: List the aggregation's bookmarks. ### Response: def list_bookmarks(self, start_date=None, end_date=None, limit=None): """List the aggregation's bookmarks.""" query = Search( using=self.client, index=self.aggreg...
def UpdateHuntObject(self, hunt_id, start_time=None, **kwargs): """Updates the hunt object by applying the update function.""" hunt_obj = self.ReadHuntObject(hunt_id) delta_suffix = "_delta" for k, v in kwargs.items(): if v is None: continue if k.endswith(delta_suffix): ke...
Updates the hunt object by applying the update function.
Below is the the instruction that describes the task: ### Input: Updates the hunt object by applying the update function. ### Response: def UpdateHuntObject(self, hunt_id, start_time=None, **kwargs): """Updates the hunt object by applying the update function.""" hunt_obj = self.ReadHuntObject(hunt_id) ...
def action_delete(self, courseid, taskid, path): """ Delete a file or a directory """ # normalize path = path.strip() if not path.startswith("/"): path = "/" + path wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: ret...
Delete a file or a directory
Below is the the instruction that describes the task: ### Input: Delete a file or a directory ### Response: def action_delete(self, courseid, taskid, path): """ Delete a file or a directory """ # normalize path = path.strip() if not path.startswith("/"): path = "/" + pat...
def _try_to_get_extension(obj): """ Try to get file extension from given path or file object. :param obj: a file, file-like object or something :return: File extension or None >>> _try_to_get_extension("a.py") 'py' """ if is_path(obj): path = obj elif is_path_obj(obj): ...
Try to get file extension from given path or file object. :param obj: a file, file-like object or something :return: File extension or None >>> _try_to_get_extension("a.py") 'py'
Below is the the instruction that describes the task: ### Input: Try to get file extension from given path or file object. :param obj: a file, file-like object or something :return: File extension or None >>> _try_to_get_extension("a.py") 'py' ### Response: def _try_to_get_extension(obj): """...
def vlm_add_input(self, psz_name, psz_input): '''Add a media's input MRL. This will add the specified one. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error. ''' return libvlc_vlm_add_input(self, str_to_bytes(psz_na...
Add a media's input MRL. This will add the specified one. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error.
Below is the the instruction that describes the task: ### Input: Add a media's input MRL. This will add the specified one. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error. ### Response: def vlm_add_input(self, psz_name, psz_input): ...
def IsPropertyInMetaIgnoreCase(classId, key): """ Methods returns the property meta of the provided key for the given classId. Given key is case insensitive. """ if classId in _ManagedObjectMeta: for prop in _ManagedObjectMeta[classId]: if (prop.lower() == key.lower()): return _ManagedObjectMeta[classId...
Methods returns the property meta of the provided key for the given classId. Given key is case insensitive.
Below is the the instruction that describes the task: ### Input: Methods returns the property meta of the provided key for the given classId. Given key is case insensitive. ### Response: def IsPropertyInMetaIgnoreCase(classId, key): """ Methods returns the property meta of the provided key for the given classId....
def get_hmac(self, key): """Returns the keyed HMAC for authentication of this state data. :param key: the key for the keyed hash function """ h = HMAC.new(key, None, SHA256) h.update(self.iv) h.update(str(self.chunks).encode()) h.update(self.f_key) h.upda...
Returns the keyed HMAC for authentication of this state data. :param key: the key for the keyed hash function
Below is the the instruction that describes the task: ### Input: Returns the keyed HMAC for authentication of this state data. :param key: the key for the keyed hash function ### Response: def get_hmac(self, key): """Returns the keyed HMAC for authentication of this state data. :param key...
def paragraph(node): """ Process a paragraph, which includes all content under it """ text = '' if node.string_content is not None: text = node.string_content o = nodes.paragraph('', ' '.join(text)) o.line = node.sourcepos[0][0] for n in MarkDown(node): o.append(n) r...
Process a paragraph, which includes all content under it
Below is the the instruction that describes the task: ### Input: Process a paragraph, which includes all content under it ### Response: def paragraph(node): """ Process a paragraph, which includes all content under it """ text = '' if node.string_content is not None: text = node.string_...
def AddMethod(obj, function, name=None): """ Adds either a bound method to an instance or the function itself (or an unbound method in Python 2) to a class. If name is ommited the name of the specified function is used by default. Example:: a = A() def f(self, x, y): self.z...
Adds either a bound method to an instance or the function itself (or an unbound method in Python 2) to a class. If name is ommited the name of the specified function is used by default. Example:: a = A() def f(self, x, y): self.z = x + y AddMethod(f, A, "add") a.add...
Below is the the instruction that describes the task: ### Input: Adds either a bound method to an instance or the function itself (or an unbound method in Python 2) to a class. If name is ommited the name of the specified function is used by default. Example:: a = A() def f(self, x, y)...
def NHot(n, *xs, simplify=True): """ Return an expression that means "exactly N input functions are true". If *simplify* is ``True``, return a simplified expression. """ if not isinstance(n, int): raise TypeError("expected n to be an int") if not 0 <= n <= len(xs): fstr = "e...
Return an expression that means "exactly N input functions are true". If *simplify* is ``True``, return a simplified expression.
Below is the the instruction that describes the task: ### Input: Return an expression that means "exactly N input functions are true". If *simplify* is ``True``, return a simplified expression. ### Response: def NHot(n, *xs, simplify=True): """ Return an expression that means "exactly N input ...
def run(self, key, value, num_alts): """Check value in INFO[key] of record Currently, only checks for consistent counts are implemented :param str key: key of INFO entry to check :param value: value to check :param int alts: list of alternative alleles, for length """ ...
Check value in INFO[key] of record Currently, only checks for consistent counts are implemented :param str key: key of INFO entry to check :param value: value to check :param int alts: list of alternative alleles, for length
Below is the the instruction that describes the task: ### Input: Check value in INFO[key] of record Currently, only checks for consistent counts are implemented :param str key: key of INFO entry to check :param value: value to check :param int alts: list of alternative alleles, for...
def resolve_upload_path(self, filename=None): """Resolve upload path for use with the executor. :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given uploaded file in programs executed using this executor """ ...
Resolve upload path for use with the executor. :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given uploaded file in programs executed using this executor
Below is the the instruction that describes the task: ### Input: Resolve upload path for use with the executor. :param filename: Filename to resolve :return: Resolved filename, which can be used to access the given uploaded file in programs executed using this executor ### R...
def _compute_e2_factor(self, imt, vs30): """ Compute and return e2 factor, equation 19, page 80. """ e2 = np.zeros_like(vs30) if imt.name == "PGV": period = 1 elif imt.name == "PGA": period = 0 else: period = imt.period ...
Compute and return e2 factor, equation 19, page 80.
Below is the the instruction that describes the task: ### Input: Compute and return e2 factor, equation 19, page 80. ### Response: def _compute_e2_factor(self, imt, vs30): """ Compute and return e2 factor, equation 19, page 80. """ e2 = np.zeros_like(vs30) if imt.name == "P...
def OnStartup(self): """A handler that is called on client startup.""" # We read the transaction log and fail any requests that are in it. If there # is anything in the transaction log we assume its there because we crashed # last time and let the server know. last_request = self.transaction_log.Ge...
A handler that is called on client startup.
Below is the the instruction that describes the task: ### Input: A handler that is called on client startup. ### Response: def OnStartup(self): """A handler that is called on client startup.""" # We read the transaction log and fail any requests that are in it. If there # is anything in the transaction...
def get_all_triggers(bump, file_triggers): """Aggregated set of significant figures to bump""" triggers = set() if file_triggers: triggers = triggers.union(detect_file_triggers(config.trigger_patterns)) if bump: _LOG.debug("trigger: %s bump requested", bump) triggers.add(bump) ...
Aggregated set of significant figures to bump
Below is the the instruction that describes the task: ### Input: Aggregated set of significant figures to bump ### Response: def get_all_triggers(bump, file_triggers): """Aggregated set of significant figures to bump""" triggers = set() if file_triggers: triggers = triggers.union(detect_file_tr...
def apply_correlation(self, sites, imt, residuals, stddev_intra=0): """ Apply correlation to randomly sampled residuals. :param sites: :class:`~openquake.hazardlib.site.SiteCollection` residuals were sampled for. :param imt: Intensity measure type obj...
Apply correlation to randomly sampled residuals. :param sites: :class:`~openquake.hazardlib.site.SiteCollection` residuals were sampled for. :param imt: Intensity measure type object, see :mod:`openquake.hazardlib.imt`. :param residuals: 2d numpy ...
Below is the the instruction that describes the task: ### Input: Apply correlation to randomly sampled residuals. :param sites: :class:`~openquake.hazardlib.site.SiteCollection` residuals were sampled for. :param imt: Intensity measure type object, see :mod:`open...
def formatTime(self, record, datefmt=None): # noqa """ Overrides formatTime method to use datetime module instead of time module to display time in microseconds. Time module by default does not resolve time to microseconds. """ if datefmt: s = datetime.dateti...
Overrides formatTime method to use datetime module instead of time module to display time in microseconds. Time module by default does not resolve time to microseconds.
Below is the the instruction that describes the task: ### Input: Overrides formatTime method to use datetime module instead of time module to display time in microseconds. Time module by default does not resolve time to microseconds. ### Response: def formatTime(self, record, datefmt=None): # noqa...
def _enrich_link(self, glossary): """ Enrich the dict glossary['link'] with an identifier onto the model """ try: Model = apps.get_model(*glossary['link']['model'].split('.')) obj = Model.objects.get(pk=glossary['link']['pk']) glossary['link'].update(i...
Enrich the dict glossary['link'] with an identifier onto the model
Below is the the instruction that describes the task: ### Input: Enrich the dict glossary['link'] with an identifier onto the model ### Response: def _enrich_link(self, glossary): """ Enrich the dict glossary['link'] with an identifier onto the model """ try: Model = app...
def datapoint_indices_for_tensor(self, tensor_index): """ Returns the indices for all datapoints in the given tensor. """ if tensor_index >= self._num_tensors: raise ValueError('Tensor index %d is greater than the number of tensors (%d)' %(tensor_index, self._num_tensors)) return sel...
Returns the indices for all datapoints in the given tensor.
Below is the the instruction that describes the task: ### Input: Returns the indices for all datapoints in the given tensor. ### Response: def datapoint_indices_for_tensor(self, tensor_index): """ Returns the indices for all datapoints in the given tensor. """ if tensor_index >= self._num_tensors: ...
def _python_type(self, key, value): """Returns proper type from the schema""" try: field_type = self._sp_cols[key]['type'] if field_type in ['Number', 'Currency']: return float(value) elif field_type == 'DateTime': # Need to remove th...
Returns proper type from the schema
Below is the the instruction that describes the task: ### Input: Returns proper type from the schema ### Response: def _python_type(self, key, value): """Returns proper type from the schema""" try: field_type = self._sp_cols[key]['type'] if field_type in ['Number', 'Currency...
def readGif(filename, asNumpy=True): """ readGif(filename, asNumpy=True) Read images from an animated GIF file. Returns a list of numpy arrays, or, if asNumpy is false, a list if PIL images. """ # Check PIL if PIL is None: raise RuntimeError("Need PIL to read animated gif files.") ...
readGif(filename, asNumpy=True) Read images from an animated GIF file. Returns a list of numpy arrays, or, if asNumpy is false, a list if PIL images.
Below is the the instruction that describes the task: ### Input: readGif(filename, asNumpy=True) Read images from an animated GIF file. Returns a list of numpy arrays, or, if asNumpy is false, a list if PIL images. ### Response: def readGif(filename, asNumpy=True): """ readGif(filename, asNumpy=True)...
def lookup_thread_id(self): """Lookup thread id as required by CommentThread.lookup_thread_id. This implementation will query GitHub with the required parameters to try and find the topic for the owner, realm, topic, etc., specified in init. """ query_string = 'in:title...
Lookup thread id as required by CommentThread.lookup_thread_id. This implementation will query GitHub with the required parameters to try and find the topic for the owner, realm, topic, etc., specified in init.
Below is the the instruction that describes the task: ### Input: Lookup thread id as required by CommentThread.lookup_thread_id. This implementation will query GitHub with the required parameters to try and find the topic for the owner, realm, topic, etc., specified in init. ### Response: ...
def _concrete_instance(self, instance_doc): """Concretize an instance document. :param dict instance_doc: A document describing an instance. Should come from the API. :returns: A subclass of :py:class:`bases.BaseInstance`, or None. :rtype: :py:class:`bases.BaseInstance` """ ...
Concretize an instance document. :param dict instance_doc: A document describing an instance. Should come from the API. :returns: A subclass of :py:class:`bases.BaseInstance`, or None. :rtype: :py:class:`bases.BaseInstance`
Below is the the instruction that describes the task: ### Input: Concretize an instance document. :param dict instance_doc: A document describing an instance. Should come from the API. :returns: A subclass of :py:class:`bases.BaseInstance`, or None. :rtype: :py:class:`bases.BaseInstance` ##...
def __write(self, s): """Write string s to the stream if a whole new block is ready to be written. """ self.buf += s while len(self.buf) > self.bufsize: self.fileobj.write(self.buf[:self.bufsize]) self.buf = self.buf[self.bufsize:]
Write string s to the stream if a whole new block is ready to be written.
Below is the the instruction that describes the task: ### Input: Write string s to the stream if a whole new block is ready to be written. ### Response: def __write(self, s): """Write string s to the stream if a whole new block is ready to be written. """ self.buf += s...