code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def relpath(self, start='.'): """ Return this path as a relative path, based from `start`, which defaults to the current working directory. """ cwd = self._next_class(start) return cwd.relpathto(self)
Return this path as a relative path, based from `start`, which defaults to the current working directory.
Below is the the instruction that describes the task: ### Input: Return this path as a relative path, based from `start`, which defaults to the current working directory. ### Response: def relpath(self, start='.'): """ Return this path as a relative path, based from `start`, which defaults ...
def genNewID(self): """ Generates a new ID. If ``reuse_ids`` was false, the new ID will be read from an internal counter which is also automatically increased. This means that the newly generated ID is already reserved. If ``reuse_ids`` was true, this method sta...
Generates a new ID. If ``reuse_ids`` was false, the new ID will be read from an internal counter which is also automatically increased. This means that the newly generated ID is already reserved. If ``reuse_ids`` was true, this method starts counting up from ``start_id`` until ...
Below is the the instruction that describes the task: ### Input: Generates a new ID. If ``reuse_ids`` was false, the new ID will be read from an internal counter which is also automatically increased. This means that the newly generated ID is already reserved. If ``reuse_id...
def _connect(self, database=None): """ Connect to given database """ conn_args = { 'host': self.config['host'], 'user': self.config['user'], 'password': self.config['password'], 'port': self.config['port'], 'sslmode': self.confi...
Connect to given database
Below is the the instruction that describes the task: ### Input: Connect to given database ### Response: def _connect(self, database=None): """ Connect to given database """ conn_args = { 'host': self.config['host'], 'user': self.config['user'], '...
def run_simulations(self, parameter_list, data_folder): """ This function runs multiple simulations in parallel. """ # Open up a session s = drmaa.Session() s.initialize() # Create a job template for each parameter combination jobs = {} for param...
This function runs multiple simulations in parallel.
Below is the the instruction that describes the task: ### Input: This function runs multiple simulations in parallel. ### Response: def run_simulations(self, parameter_list, data_folder): """ This function runs multiple simulations in parallel. """ # Open up a session s = d...
def dqdv(voltage, capacity, voltage_resolution=None, capacity_resolution=None, voltage_fwhm=0.01, pre_smoothing=True, diff_smoothing=False, post_smoothing=True, post_normalization=True, interpolation_method=None, gaussian_order=None, gaussian_mode=None, gaussian_cval=None, gaussian_t...
Convenience functions for creating dq-dv data from given capacity and voltage data. Args: voltage: nd.array or pd.Series capacity: nd.array or pd.Series voltage_resolution: used for interpolating voltage data (e.g. 0.005) capacity_resolution: used for interpolating capacity data...
Below is the the instruction that describes the task: ### Input: Convenience functions for creating dq-dv data from given capacity and voltage data. Args: voltage: nd.array or pd.Series capacity: nd.array or pd.Series voltage_resolution: used for interpolating voltage data (e.g. 0.0...
def read(self, context, cmd_args): """ Execute Vagrant read command on instance placed into configuration directory. :param resort.engine.execution.Context context: Current execution context. :param list cmd_args: Command argument list. """ try: current_dir = os.getcwd() os.chdir(c...
Execute Vagrant read command on instance placed into configuration directory. :param resort.engine.execution.Context context: Current execution context. :param list cmd_args: Command argument list.
Below is the the instruction that describes the task: ### Input: Execute Vagrant read command on instance placed into configuration directory. :param resort.engine.execution.Context context: Current execution context. :param list cmd_args: Command argument list. ### Response: def read(self, cont...
def get_line_numbers(self, buffer): """ Return a (start_line, end_line) pair. """ # Get absolute cursor positions from the text object. from_, to = self.operator_range(buffer.document) from_ += buffer.cursor_position to += buffer.cursor_position # Take th...
Return a (start_line, end_line) pair.
Below is the the instruction that describes the task: ### Input: Return a (start_line, end_line) pair. ### Response: def get_line_numbers(self, buffer): """ Return a (start_line, end_line) pair. """ # Get absolute cursor positions from the text object. from_, to = self.opera...
def plot_series_residuals_internal(self, varied_data, varied_idx, **kwargs): """ Analogous to :meth:`plot_series` but for internal residuals from last run. """ nf = len(self.f_cb(*self.pre_process( self.internal_xout[0], self.internal_params_out[0]))) xerr = np.empty((self.internal_x...
Analogous to :meth:`plot_series` but for internal residuals from last run.
Below is the the instruction that describes the task: ### Input: Analogous to :meth:`plot_series` but for internal residuals from last run. ### Response: def plot_series_residuals_internal(self, varied_data, varied_idx, **kwargs): """ Analogous to :meth:`plot_series` but for internal residuals from last ru...
def multiple_devices_data_message(self, registration_ids=None, condition=None, collapse_key=None, delay_while_idle=False, time_to_...
Sends push message to multiple devices, can send to over 1000 devices Args: registration_ids (list, optional): FCM device registration IDs condition (str, optiona): Topic condition to deliver messages to collapse_key (str, optional): Identifier for a group of messages ...
Below is the the instruction that describes the task: ### Input: Sends push message to multiple devices, can send to over 1000 devices Args: registration_ids (list, optional): FCM device registration IDs condition (str, optiona): Topic condition to deliver messages to co...
def get_families(self): """Gets the family list resulting from a search. return: (osid.relationship.FamilyList) - the family list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: ...
Gets the family list resulting from a search. return: (osid.relationship.FamilyList) - the family list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the family list resulting from a search. return: (osid.relationship.FamilyList) - the family list raise: IllegalState - list already retrieved *compliance: mandatory -- This method must be implemented.* ### Response: de...
def _deprecated_kwargs(kwargs, arg_newarg): """ arg_newarg is a list of tuples, where each tuple has a pair of strings. ('old_arg', 'new_arg') A DeprecationWarning is raised for the arguments that need to be replaced. """ warn_for = [] for (arg, new_kw) in arg_newarg: if ...
arg_newarg is a list of tuples, where each tuple has a pair of strings. ('old_arg', 'new_arg') A DeprecationWarning is raised for the arguments that need to be replaced.
Below is the the instruction that describes the task: ### Input: arg_newarg is a list of tuples, where each tuple has a pair of strings. ('old_arg', 'new_arg') A DeprecationWarning is raised for the arguments that need to be replaced. ### Response: def _deprecated_kwargs(kwargs, arg_newarg)...
def iterate(matrix, expansion, inflation): """ Run a single iteration (expansion + inflation) of the mcl algorithm :param matrix: The matrix to perform the iteration on :param expansion: Cluster expansion factor :param inflation: Cluster inflation factor """ # Expansion matrix = exp...
Run a single iteration (expansion + inflation) of the mcl algorithm :param matrix: The matrix to perform the iteration on :param expansion: Cluster expansion factor :param inflation: Cluster inflation factor
Below is the the instruction that describes the task: ### Input: Run a single iteration (expansion + inflation) of the mcl algorithm :param matrix: The matrix to perform the iteration on :param expansion: Cluster expansion factor :param inflation: Cluster inflation factor ### Response: def iterate...
def get(self, ring, angle): """Get RGB color tuple of color at index pixel""" pixel = self.angleToPixel(angle, ring) return self._get_base(pixel)
Get RGB color tuple of color at index pixel
Below is the the instruction that describes the task: ### Input: Get RGB color tuple of color at index pixel ### Response: def get(self, ring, angle): """Get RGB color tuple of color at index pixel""" pixel = self.angleToPixel(angle, ring) return self._get_base(pixel)
def example(host, user, password, token): """run the example.""" client = None try: if token: print('token login') client = MatrixClient(host, token=token, user_id=user) else: print('password login') client = MatrixClient(host) toke...
run the example.
Below is the the instruction that describes the task: ### Input: run the example. ### Response: def example(host, user, password, token): """run the example.""" client = None try: if token: print('token login') client = MatrixClient(host, token=token, user_id=user) ...
def compile(pattern, namespaces=None, flags=0, **kwargs): # noqa: A001 """Compile CSS pattern.""" if namespaces is not None: namespaces = ct.Namespaces(**namespaces) custom = kwargs.get('custom') if custom is not None: custom = ct.CustomSelectors(**custom) if isinstance(pattern, ...
Compile CSS pattern.
Below is the the instruction that describes the task: ### Input: Compile CSS pattern. ### Response: def compile(pattern, namespaces=None, flags=0, **kwargs): # noqa: A001 """Compile CSS pattern.""" if namespaces is not None: namespaces = ct.Namespaces(**namespaces) custom = kwargs.get('custo...
def set(ctx, key, value): """ Set configuration parameters """ if key == "default_account" and value[0] == "@": value = value[1:] ctx.blockchain.config[key] = value
Set configuration parameters
Below is the the instruction that describes the task: ### Input: Set configuration parameters ### Response: def set(ctx, key, value): """ Set configuration parameters """ if key == "default_account" and value[0] == "@": value = value[1:] ctx.blockchain.config[key] = value
def run_via_api(self, container_params=None): """ create a container using this image and run it in background via Docker-py API. https://docker-py.readthedocs.io/en/stable/api.html Note: If you are using Healthchecks, be aware that support of some options were introduced just wi...
create a container using this image and run it in background via Docker-py API. https://docker-py.readthedocs.io/en/stable/api.html Note: If you are using Healthchecks, be aware that support of some options were introduced just with version of Docker-py API 1.29 :param container_params: ...
Below is the the instruction that describes the task: ### Input: create a container using this image and run it in background via Docker-py API. https://docker-py.readthedocs.io/en/stable/api.html Note: If you are using Healthchecks, be aware that support of some options were introduced just...
def get_assessment_offered_lookup_session(self): """Gets the ``OsidSession`` associated with the assessment offered lookup service. return: (osid.assessment.AssessmentOfferedLookupSession) - an ``AssessmentOfferedLookupSession`` raise: OperationFailed - unable to complete reque...
Gets the ``OsidSession`` associated with the assessment offered lookup service. return: (osid.assessment.AssessmentOfferedLookupSession) - an ``AssessmentOfferedLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_assessment_off...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the assessment offered lookup service. return: (osid.assessment.AssessmentOfferedLookupSession) - an ``AssessmentOfferedLookupSession`` raise: OperationFailed - unable to compl...
def _split_sympy_quantum_factor(expr): """Split a product into sympy and qnet factors This is a helper routine for applying some sympy transformation on an arbitrary product-like expression in QNET. The idea is this:: expr -> sympy_factor, quantum_factor sympy_factor -> sympy_function(symp...
Split a product into sympy and qnet factors This is a helper routine for applying some sympy transformation on an arbitrary product-like expression in QNET. The idea is this:: expr -> sympy_factor, quantum_factor sympy_factor -> sympy_function(sympy_factor) expr -> sympy_factor * quant...
Below is the the instruction that describes the task: ### Input: Split a product into sympy and qnet factors This is a helper routine for applying some sympy transformation on an arbitrary product-like expression in QNET. The idea is this:: expr -> sympy_factor, quantum_factor sympy_factor...
def list(self, page=1, per_page=10, omit=None): """List groups by page. The API allows certain fields to be excluded from the results so that very large groups can be fetched without exceeding the maximum response size. At the time of this writing, only 'memberships' is supporte...
List groups by page. The API allows certain fields to be excluded from the results so that very large groups can be fetched without exceeding the maximum response size. At the time of this writing, only 'memberships' is supported. :param int page: page number :param int...
Below is the the instruction that describes the task: ### Input: List groups by page. The API allows certain fields to be excluded from the results so that very large groups can be fetched without exceeding the maximum response size. At the time of this writing, only 'memberships' is ...
def classify_format(f): """ Determine the format of word embedding file by their content. This operation only looks at the first two lines and does not check the sanity of input file. Args: f (Filelike): Returns: class """ l0, l1 = _get_two_lines(f) if loader.glove...
Determine the format of word embedding file by their content. This operation only looks at the first two lines and does not check the sanity of input file. Args: f (Filelike): Returns: class
Below is the the instruction that describes the task: ### Input: Determine the format of word embedding file by their content. This operation only looks at the first two lines and does not check the sanity of input file. Args: f (Filelike): Returns: class ### Response: def classif...
def dict_to_object(self, obj): # pylint: disable=no-self-use """Return object from dict.""" if not isinstance(obj, dict): return obj if 'sensor_id' in obj: sensor = Sensor(obj['sensor_id']) for key, val in obj.items(): setattr(sensor, key, val...
Return object from dict.
Below is the the instruction that describes the task: ### Input: Return object from dict. ### Response: def dict_to_object(self, obj): # pylint: disable=no-self-use """Return object from dict.""" if not isinstance(obj, dict): return obj if 'sensor_id' in obj: sensor...
def get_last_traded_dt(self, asset, dt): """ Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the la...
Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the last traded day. dt : pd.Timestamp The dt a...
Below is the the instruction that describes the task: ### Input: Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to ge...
def npv(self): r"""Return negative predictive value (NPV). NPV is defined as :math:`\frac{tn}{tn + fn}` Cf. https://en.wikipedia.org/wiki/Negative_predictive_value Returns ------- float The negative predictive value of the confusion table Example ...
r"""Return negative predictive value (NPV). NPV is defined as :math:`\frac{tn}{tn + fn}` Cf. https://en.wikipedia.org/wiki/Negative_predictive_value Returns ------- float The negative predictive value of the confusion table Example ------- ...
Below is the the instruction that describes the task: ### Input: r"""Return negative predictive value (NPV). NPV is defined as :math:`\frac{tn}{tn + fn}` Cf. https://en.wikipedia.org/wiki/Negative_predictive_value Returns ------- float The negative predictive v...
def get(self, request, bot_id, id, format=None): """ Get list of source state of a handler --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated """ return super(SourceStateList, self).get(request, bot_i...
Get list of source state of a handler --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated
Below is the the instruction that describes the task: ### Input: Get list of source state of a handler --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated ### Response: def get(self, request, bot_id, id, format=None): ""...
def calc_all_ar_coefs(self, ar_order, ma_model): """Determine the AR coeffcients based on a least squares approach. The argument `ar_order` defines the number of AR coefficients to be determined. The argument `ma_order` defines a pure |MA| model. The least squares approach is applied o...
Determine the AR coeffcients based on a least squares approach. The argument `ar_order` defines the number of AR coefficients to be determined. The argument `ma_order` defines a pure |MA| model. The least squares approach is applied on all those coefficents of the pure MA model, which ...
Below is the the instruction that describes the task: ### Input: Determine the AR coeffcients based on a least squares approach. The argument `ar_order` defines the number of AR coefficients to be determined. The argument `ma_order` defines a pure |MA| model. The least squares approach is ...
def getLogger(name=None): ''' return a logger instrumented with additional 1-letter logging methods; ''' logger = logging.getLogger(name=name) if not hasattr(logger, 'd'): def d(self, msg, *args, **kwargs): return self.log(DEBUG, msg, *args, **kwargs) logger.d = types....
return a logger instrumented with additional 1-letter logging methods;
Below is the the instruction that describes the task: ### Input: return a logger instrumented with additional 1-letter logging methods; ### Response: def getLogger(name=None): ''' return a logger instrumented with additional 1-letter logging methods; ''' logger = logging.getLogger(name=name) ...
def PathIsDir(self, key, val, env): """Validator to check if Path is a directory.""" if not os.path.isdir(val): if os.path.isfile(val): m = 'Directory path for option %s is a file: %s' else: m = 'Directory path for option %s does not exist: %s' ...
Validator to check if Path is a directory.
Below is the the instruction that describes the task: ### Input: Validator to check if Path is a directory. ### Response: def PathIsDir(self, key, val, env): """Validator to check if Path is a directory.""" if not os.path.isdir(val): if os.path.isfile(val): m = 'Director...
def get_element_attribute(elem_to_parse, attrib_name, default_value=u''): """ :return: an attribute from the parsed element if it has the attribute, otherwise the default value """ element = get_element(elem_to_parse) if element is None: return default_value return element.attrib....
:return: an attribute from the parsed element if it has the attribute, otherwise the default value
Below is the the instruction that describes the task: ### Input: :return: an attribute from the parsed element if it has the attribute, otherwise the default value ### Response: def get_element_attribute(elem_to_parse, attrib_name, default_value=u''): """ :return: an attribute from the parsed element i...
def encrypt_and_hmac(self, packet): """ Encrypts and signs a Packet() using self.SK_ei and self.SK_ai :param packet: Unecrypted Packet() with one or more payloads. :return: Encrypted and signed Packet() with a single payloads.SK """ final = Packet(exchange_type=packet.ex...
Encrypts and signs a Packet() using self.SK_ei and self.SK_ai :param packet: Unecrypted Packet() with one or more payloads. :return: Encrypted and signed Packet() with a single payloads.SK
Below is the the instruction that describes the task: ### Input: Encrypts and signs a Packet() using self.SK_ei and self.SK_ai :param packet: Unecrypted Packet() with one or more payloads. :return: Encrypted and signed Packet() with a single payloads.SK ### Response: def encrypt_and_hmac(self, pac...
def siblingExtensionSearch(self, *exts): """Attempt to return a path with my name, given multiple possible extensions. Each extension in exts will be tested and the first path which exists will be returned. If no path exists, None will be returned. If '' is in exts, then if th...
Attempt to return a path with my name, given multiple possible extensions. Each extension in exts will be tested and the first path which exists will be returned. If no path exists, None will be returned. If '' is in exts, then if the file referred to by this path exists, 'self' will ...
Below is the the instruction that describes the task: ### Input: Attempt to return a path with my name, given multiple possible extensions. Each extension in exts will be tested and the first path which exists will be returned. If no path exists, None will be returned. If '' is in...
def _take_bits(buf, count): """Return the booleans that were packed into bytes.""" # TODO: Verify output bytes_count = (count + 7) // 8 bytes_mod = count % 8 data = _unpack_from(buf, 'B', bytes_count) values = [] for i, byte in enumerate(data): for _ in range(8 if i != bytes_count -...
Return the booleans that were packed into bytes.
Below is the the instruction that describes the task: ### Input: Return the booleans that were packed into bytes. ### Response: def _take_bits(buf, count): """Return the booleans that were packed into bytes.""" # TODO: Verify output bytes_count = (count + 7) // 8 bytes_mod = count % 8 data = _...
def _ref_covered_by_at_least_one_full_length_contig(nucmer_hits, percent_threshold, max_nt_extend): '''Returns true iff there exists a contig that completely covers the reference sequence nucmer_hits = hits made by self._parse_nucmer_coords_file.''' for l in nucmer_hits.values(): ...
Returns true iff there exists a contig that completely covers the reference sequence nucmer_hits = hits made by self._parse_nucmer_coords_file.
Below is the the instruction that describes the task: ### Input: Returns true iff there exists a contig that completely covers the reference sequence nucmer_hits = hits made by self._parse_nucmer_coords_file. ### Response: def _ref_covered_by_at_least_one_full_length_contig(nucmer_hits, perce...
def extractRuntime(runtime_dirs): """ Used to find the correct static lib name to pass to gcc """ names = [str(item) for name in runtime_dirs for item in os.listdir(name)] string = '\n'.join(names) result = extract(RUNTIME_PATTERN, string, condense=True) return result
Used to find the correct static lib name to pass to gcc
Below is the the instruction that describes the task: ### Input: Used to find the correct static lib name to pass to gcc ### Response: def extractRuntime(runtime_dirs): """ Used to find the correct static lib name to pass to gcc """ names = [str(item) for name in runtime_dirs for item in os.listdir...
def create_inquirer_layout( ic: InquirerControl, get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]], **kwargs) -> Layout: """Create a layout combining question and inquirer selection.""" ps = PromptSession(get_prompt_tokens, reserve_space_for_menu=0, **kwargs) _fix_unecessary...
Create a layout combining question and inquirer selection.
Below is the the instruction that describes the task: ### Input: Create a layout combining question and inquirer selection. ### Response: def create_inquirer_layout( ic: InquirerControl, get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]], **kwargs) -> Layout: """Create a layout co...
def add(self, widget, *args, **kwargs): """Insert new element. Usage: window.add(widget, **{ 'prop1': val, 'prop2': val2 }) """ ins_widget = widget(*args, **kwargs) self.__iadd__(ins_widget) return ins_widget
Insert new element. Usage: window.add(widget, **{ 'prop1': val, 'prop2': val2 })
Below is the the instruction that describes the task: ### Input: Insert new element. Usage: window.add(widget, **{ 'prop1': val, 'prop2': val2 }) ### Response: def add(self, widget, *args, **kwargs): """Insert new element. Usage: ...
def list_objects(self, prefix=None, delimiter=None): """ List the objects for this bucket. :param str prefix: If specified, only objects that start with this prefix are listed. :param str delimiter: If specified, return only objects whose name ...
List the objects for this bucket. :param str prefix: If specified, only objects that start with this prefix are listed. :param str delimiter: If specified, return only objects whose name do not contain the delimiter after the prefix. ...
Below is the the instruction that describes the task: ### Input: List the objects for this bucket. :param str prefix: If specified, only objects that start with this prefix are listed. :param str delimiter: If specified, return only objects whose name ...
def _compute_prediction(self,X): """ compute predictions given a new X """ A_pred = np.dot(X,self._Bhat) Y_pred = self._basis_object.inverse_transform(A_pred) return Y_pred
compute predictions given a new X
Below is the the instruction that describes the task: ### Input: compute predictions given a new X ### Response: def _compute_prediction(self,X): """ compute predictions given a new X """ A_pred = np.dot(X,self._Bhat) Y_pred = self._basis_object.inverse_transform(A_pred) return Y_pr...
def query_db_reference(): """ Returns list of cross references by query parameters --- tags: - Query functions parameters: - name: type_ in: query type: string required: false description: Reference type default: EMBL - name: identifier ...
Returns list of cross references by query parameters --- tags: - Query functions parameters: - name: type_ in: query type: string required: false description: Reference type default: EMBL - name: identifier in: query type: string...
Below is the the instruction that describes the task: ### Input: Returns list of cross references by query parameters --- tags: - Query functions parameters: - name: type_ in: query type: string required: false description: Reference type default: ...
def container_stop(name, timeout=30, force=True, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Stop a container name : Name of the container to stop remote_addr : An URL to a remote Server, you also have to give cert and key if you provide rem...
Stop a container name : Name of the container to stop remote_addr : An URL to a remote Server, you also have to give cert and key if you provide remote_addr and its a TCP Address! Examples: https://myserver.lan:8443 /var/lib/mysocket.sock cert : ...
Below is the the instruction that describes the task: ### Input: Stop a container name : Name of the container to stop remote_addr : An URL to a remote Server, you also have to give cert and key if you provide remote_addr and its a TCP Address! Examples: https:...
def lower(string): """Lower.""" new_string = [] for c in string: o = ord(c) new_string.append(chr(o + 32) if UC_A <= o <= UC_Z else c) return ''.join(new_string)
Lower.
Below is the the instruction that describes the task: ### Input: Lower. ### Response: def lower(string): """Lower.""" new_string = [] for c in string: o = ord(c) new_string.append(chr(o + 32) if UC_A <= o <= UC_Z else c) return ''.join(new_string)
def since_last_check(self): """Time since the last checking. Either :func:`since_start` or :func:`since_last_check` is a checking operation. Returns (float): Time in seconds. """ if not self._is_running: raise TimerError('timer is not running') dur =...
Time since the last checking. Either :func:`since_start` or :func:`since_last_check` is a checking operation. Returns (float): Time in seconds.
Below is the the instruction that describes the task: ### Input: Time since the last checking. Either :func:`since_start` or :func:`since_last_check` is a checking operation. Returns (float): Time in seconds. ### Response: def since_last_check(self): """Time since the last checkin...
def start(name): # type: (str) -> None """ Start working on a new feature by branching off develop. This will create a new branch off develop called feature/<name>. Args: name (str): The name of the new feature. """ feature_name = 'feature/' + common.to_branch_name(name) ...
Start working on a new feature by branching off develop. This will create a new branch off develop called feature/<name>. Args: name (str): The name of the new feature.
Below is the the instruction that describes the task: ### Input: Start working on a new feature by branching off develop. This will create a new branch off develop called feature/<name>. Args: name (str): The name of the new feature. ### Response: def start(name): # type: (str) ->...
def p_definitions(self, p): 'definitions : definitions definition' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
definitions : definitions definition
Below is the the instruction that describes the task: ### Input: definitions : definitions definition ### Response: def p_definitions(self, p): 'definitions : definitions definition' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
def create_binary(self, key, value): """Create method of CRUD operation for binary data. Args: key (string): The variable to write to the DB. value (any): The data to write to the DB. Returns: (string): Result of DB write. """ data = None ...
Create method of CRUD operation for binary data. Args: key (string): The variable to write to the DB. value (any): The data to write to the DB. Returns: (string): Result of DB write.
Below is the the instruction that describes the task: ### Input: Create method of CRUD operation for binary data. Args: key (string): The variable to write to the DB. value (any): The data to write to the DB. Returns: (string): Result of DB write. ### Response: ...
def load(fp, encode_nominal=False, return_type=DENSE): '''Load a file-like object containing the ARFF document and convert it into a Python object. :param fp: a file-like object. :param encode_nominal: boolean, if True perform a label encoding while reading the .arff file. :param return_typ...
Load a file-like object containing the ARFF document and convert it into a Python object. :param fp: a file-like object. :param encode_nominal: boolean, if True perform a label encoding while reading the .arff file. :param return_type: determines the data structure used to store the dat...
Below is the the instruction that describes the task: ### Input: Load a file-like object containing the ARFF document and convert it into a Python object. :param fp: a file-like object. :param encode_nominal: boolean, if True perform a label encoding while reading the .arff file. :param ret...
def change_mime(self, bucket, key, mime): """修改文件mimeType: 主动修改指定资源的文件类型,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html Args: bucket: 待操作资源所在空间 key: 待操作资源文件名 mime: 待操作文件目标mimeType """ resource = entry(bucke...
修改文件mimeType: 主动修改指定资源的文件类型,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html Args: bucket: 待操作资源所在空间 key: 待操作资源文件名 mime: 待操作文件目标mimeType
Below is the the instruction that describes the task: ### Input: 修改文件mimeType: 主动修改指定资源的文件类型,具体规格参考: http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html Args: bucket: 待操作资源所在空间 key: 待操作资源文件名 mime: 待操作文件目标mimeType ### Response: def change_...
def meta(name, value, scheme=None): """ Adds meta information to a class definition. @param name: name of the meta data class @type name: str or unicode @param value: metadata value @type value: str or unicode @param scheme: format information about the value @type scheme: str or unicode...
Adds meta information to a class definition. @param name: name of the meta data class @type name: str or unicode @param value: metadata value @type value: str or unicode @param scheme: format information about the value @type scheme: str or unicode or None
Below is the the instruction that describes the task: ### Input: Adds meta information to a class definition. @param name: name of the meta data class @type name: str or unicode @param value: metadata value @type value: str or unicode @param scheme: format information about the value @type s...
def _get_cells_headers_ids(self, hed, index): """ Returns a list with ids of rows of same column. :param hed: The list that represents the table header. :type hed: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement)) :param index: The index of columns. :type inde...
Returns a list with ids of rows of same column. :param hed: The list that represents the table header. :type hed: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement)) :param index: The index of columns. :type index: int :return: The list with ids of rows of same column. ...
Below is the the instruction that describes the task: ### Input: Returns a list with ids of rows of same column. :param hed: The list that represents the table header. :type hed: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement)) :param index: The index of columns. :type i...
def get(key, service=None, profile=None): ''' Get a value from a keyring service ''' service = _get_service(service, profile) return keyring.get_password(service, key)
Get a value from a keyring service
Below is the the instruction that describes the task: ### Input: Get a value from a keyring service ### Response: def get(key, service=None, profile=None): ''' Get a value from a keyring service ''' service = _get_service(service, profile) return keyring.get_password(service, key)
def write(self, pkt): """accepts a either a single packet or a list of packets to be written to the dumpfile """ if not self.header_present: self._write_header(pkt) if type(pkt) is bytes: self._write_packet(pkt) else: for p in pkt: ...
accepts a either a single packet or a list of packets to be written to the dumpfile
Below is the the instruction that describes the task: ### Input: accepts a either a single packet or a list of packets to be written to the dumpfile ### Response: def write(self, pkt): """accepts a either a single packet or a list of packets to be written to the dumpfile """ ...
def check_periodic_bulk_vm_notif_rcvd(self): """Bulk VM check handler called from periodic uplink detection. This gets called by the 'normal' stage of uplink detection. The bulk VM event sends all the VM's running in this agent. Sometimes during upgrades, it was found that due to some r...
Bulk VM check handler called from periodic uplink detection. This gets called by the 'normal' stage of uplink detection. The bulk VM event sends all the VM's running in this agent. Sometimes during upgrades, it was found that due to some race condition, the server does not send the Bulk...
Below is the the instruction that describes the task: ### Input: Bulk VM check handler called from periodic uplink detection. This gets called by the 'normal' stage of uplink detection. The bulk VM event sends all the VM's running in this agent. Sometimes during upgrades, it was found that ...
def _get_version_output(self): """ Ignoring errors, call `ceph --version` and return only the version portion of the output. For example, output like:: ceph version 9.0.1-1234kjd (asdflkj2k3jh234jhg) Would return:: 9.0.1-1234kjd """ if not self....
Ignoring errors, call `ceph --version` and return only the version portion of the output. For example, output like:: ceph version 9.0.1-1234kjd (asdflkj2k3jh234jhg) Would return:: 9.0.1-1234kjd
Below is the the instruction that describes the task: ### Input: Ignoring errors, call `ceph --version` and return only the version portion of the output. For example, output like:: ceph version 9.0.1-1234kjd (asdflkj2k3jh234jhg) Would return:: 9.0.1-1234kjd ### Response: ...
def get_plugin(self, method): """ Return plugin object if CLI option is activated and method exists @param method: name of plugin's method we're calling @type method: string @returns: list of plugins with `method` """ all_plugins = [] for entry_point in...
Return plugin object if CLI option is activated and method exists @param method: name of plugin's method we're calling @type method: string @returns: list of plugins with `method`
Below is the the instruction that describes the task: ### Input: Return plugin object if CLI option is activated and method exists @param method: name of plugin's method we're calling @type method: string @returns: list of plugins with `method` ### Response: def get_plugin(self, method): ...
def load_source(source): """ Common entry point for loading some form of raw swagger schema. Supports: - python object (dictionary-like) - path to yaml file - path to json file - file object (json or yaml). - json string. - yaml string. """ if isinsta...
Common entry point for loading some form of raw swagger schema. Supports: - python object (dictionary-like) - path to yaml file - path to json file - file object (json or yaml). - json string. - yaml string.
Below is the the instruction that describes the task: ### Input: Common entry point for loading some form of raw swagger schema. Supports: - python object (dictionary-like) - path to yaml file - path to json file - file object (json or yaml). - json string. - yam...
def get_service_location_info(self, service_location_id): """ Request service location info Parameters ---------- service_location_id : int Returns ------- dict """ url = urljoin(URLS['servicelocation'], service_location_id, "info") ...
Request service location info Parameters ---------- service_location_id : int Returns ------- dict
Below is the the instruction that describes the task: ### Input: Request service location info Parameters ---------- service_location_id : int Returns ------- dict ### Response: def get_service_location_info(self, service_location_id): """ Request s...
def exception(self, event=None, *args, **kw): """ Process event and call :meth:`logging.Logger.error` with the result, after setting ``exc_info`` to `True`. """ if not self._logger.isEnabledFor(logging.ERROR): return kw = self._add_base_info(kw) kw['l...
Process event and call :meth:`logging.Logger.error` with the result, after setting ``exc_info`` to `True`.
Below is the the instruction that describes the task: ### Input: Process event and call :meth:`logging.Logger.error` with the result, after setting ``exc_info`` to `True`. ### Response: def exception(self, event=None, *args, **kw): """ Process event and call :meth:`logging.Logger.error` wit...
def get_base_config(self): """Responsible for getting core configuration from config files. """ shutit_global.shutit_global_object.yield_to_draw() cp = self.config_parser # TODO: what happens if a command-line arg was already set? # BEGIN Read from config files # build - details relating to the build se...
Responsible for getting core configuration from config files.
Below is the the instruction that describes the task: ### Input: Responsible for getting core configuration from config files. ### Response: def get_base_config(self): """Responsible for getting core configuration from config files. """ shutit_global.shutit_global_object.yield_to_draw() cp = self.config_pa...
def predecessors(self, node, exclude_compressed=True): """ Returns the list of predecessors of a given node Parameters ---------- node : str The target node exclude_compressed : boolean If true, compressed nodes are excluded from the predecessors...
Returns the list of predecessors of a given node Parameters ---------- node : str The target node exclude_compressed : boolean If true, compressed nodes are excluded from the predecessors list Returns ------- list List of pre...
Below is the the instruction that describes the task: ### Input: Returns the list of predecessors of a given node Parameters ---------- node : str The target node exclude_compressed : boolean If true, compressed nodes are excluded from the predecessors list ...
def metricCompute(self, sensorToBody, bodyToSpecificObject): """ Compute the "sensor's location relative to a specific object" from the "body's location relative to a specific object" and the "sensor's location relative to body" @param sensorToBody (numpy array) Active cells o...
Compute the "sensor's location relative to a specific object" from the "body's location relative to a specific object" and the "sensor's location relative to body" @param sensorToBody (numpy array) Active cells of a single module that represents the sensor's location relative to t...
Below is the the instruction that describes the task: ### Input: Compute the "sensor's location relative to a specific object" from the "body's location relative to a specific object" and the "sensor's location relative to body" @param sensorToBody (numpy array) Active cells of a ...
def _remove_files(self, directory, pattern): ''' Removes all files matching the search path Arguments: search_path -- The path you would like to remove, can contain wildcards Example: self._remove_files("output/*.html") ''' for root, dirnames, file_names...
Removes all files matching the search path Arguments: search_path -- The path you would like to remove, can contain wildcards Example: self._remove_files("output/*.html")
Below is the the instruction that describes the task: ### Input: Removes all files matching the search path Arguments: search_path -- The path you would like to remove, can contain wildcards Example: self._remove_files("output/*.html") ### Response: def _remove_files(self, directo...
def DeleteConflict(self, conflict_link, options=None): """Deletes a conflict. :param str conflict_link: The link to the conflict. :param dict options: The request options for the request. :return: The deleted Conflict. :rtype: dic...
Deletes a conflict. :param str conflict_link: The link to the conflict. :param dict options: The request options for the request. :return: The deleted Conflict. :rtype: dict
Below is the the instruction that describes the task: ### Input: Deletes a conflict. :param str conflict_link: The link to the conflict. :param dict options: The request options for the request. :return: The deleted Conflict. :rtype: ...
def filepath(self, filename): """The full path to a file""" return os.path.join(self.node.full_path, filename)
The full path to a file
Below is the the instruction that describes the task: ### Input: The full path to a file ### Response: def filepath(self, filename): """The full path to a file""" return os.path.join(self.node.full_path, filename)
def generate(extra_mods='', overwrite=False, so_mods='', python2_bin='python2', python3_bin='python3', absonly=True, compress='gzip'): ''' Generate the salt-thin tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma...
Generate the salt-thin tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma delimited string. Permits forcing an overwrite of the output file as well. CLI Example: .. code-block:: bash salt-run thin.generate salt-run...
Below is the the instruction that describes the task: ### Input: Generate the salt-thin tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma delimited string. Permits forcing an overwrite of the output file as well. CLI Example: ...
def to_deeper_model(self, target_id, new_layer): """Insert a relu-conv-bn block after the target block. Args: target_id: A convolutional layer ID. The new block should be inserted after the block. new_layer: An instance of StubLayer subclasses. """ self.operation_...
Insert a relu-conv-bn block after the target block. Args: target_id: A convolutional layer ID. The new block should be inserted after the block. new_layer: An instance of StubLayer subclasses.
Below is the the instruction that describes the task: ### Input: Insert a relu-conv-bn block after the target block. Args: target_id: A convolutional layer ID. The new block should be inserted after the block. new_layer: An instance of StubLayer subclasses. ### Response: def to_deep...
def reconnect(connection): """Open a new datafind connection based on an existing connection This is required because of https://git.ligo.org/lscsoft/glue/issues/1 Parameters ---------- connection : :class:`~gwdatafind.http.HTTPConnection` or `FflConnection` a connection object (doesn't ne...
Open a new datafind connection based on an existing connection This is required because of https://git.ligo.org/lscsoft/glue/issues/1 Parameters ---------- connection : :class:`~gwdatafind.http.HTTPConnection` or `FflConnection` a connection object (doesn't need to be open) Returns --...
Below is the the instruction that describes the task: ### Input: Open a new datafind connection based on an existing connection This is required because of https://git.ligo.org/lscsoft/glue/issues/1 Parameters ---------- connection : :class:`~gwdatafind.http.HTTPConnection` or `FflConnection` ...
def delete(gandi, resource, force): """ Delete a hosted certificate. Resource can be a FQDN or an ID """ infos = gandi.hostedcert.infos(resource) if not infos: return if not force: proceed = click.confirm('Are you sure to delete the following hosted ' ...
Delete a hosted certificate. Resource can be a FQDN or an ID
Below is the the instruction that describes the task: ### Input: Delete a hosted certificate. Resource can be a FQDN or an ID ### Response: def delete(gandi, resource, force): """ Delete a hosted certificate. Resource can be a FQDN or an ID """ infos = gandi.hostedcert.infos(resource) if ...
def expectation_step(t_table, stanzas, schemes, rprobs): """ Compute posterior probability of schemes for each stanza """ probs = numpy.zeros((len(stanzas), schemes.num_schemes)) for i, stanza in enumerate(stanzas): scheme_indices = schemes.get_schemes_for_len(len(stanza)) for schem...
Compute posterior probability of schemes for each stanza
Below is the the instruction that describes the task: ### Input: Compute posterior probability of schemes for each stanza ### Response: def expectation_step(t_table, stanzas, schemes, rprobs): """ Compute posterior probability of schemes for each stanza """ probs = numpy.zeros((len(stanzas), schem...
def get_initial_data(self): """ Return a dictionary specifying the defaults for this form. This dictionary can be used to inject the initial values for an Angular controller using the directive: ``ng-init={{ thisform.get_initial_data|js|safe }}``. """ data = {} ng...
Return a dictionary specifying the defaults for this form. This dictionary can be used to inject the initial values for an Angular controller using the directive: ``ng-init={{ thisform.get_initial_data|js|safe }}``.
Below is the the instruction that describes the task: ### Input: Return a dictionary specifying the defaults for this form. This dictionary can be used to inject the initial values for an Angular controller using the directive: ``ng-init={{ thisform.get_initial_data|js|safe }}``. ### Response: def ...
def send_message(self, recipient_list, subject, body): """发送站内消息 :param recipient_list: 收件人列表 :param subject: 标题 :param body: 内容(不能超过 1024 个字符) """ url = 'http://www.shanbay.com/api/v1/message/' recipient = ','.join(recipient_list) data = { 'r...
发送站内消息 :param recipient_list: 收件人列表 :param subject: 标题 :param body: 内容(不能超过 1024 个字符)
Below is the the instruction that describes the task: ### Input: 发送站内消息 :param recipient_list: 收件人列表 :param subject: 标题 :param body: 内容(不能超过 1024 个字符) ### Response: def send_message(self, recipient_list, subject, body): """发送站内消息 :param recipient_list: 收件人列表 :param...
def asm_module(exprs, dst_reg, sym_to_reg, triple_or_target=None): ''' Generate an LLVM module for a list of expressions Arguments: * See :meth:`arybo.lib.exprs_asm.asm_binary` for a description of the list of arguments Output: * An LLVM module with one function named "__arybo", containing...
Generate an LLVM module for a list of expressions Arguments: * See :meth:`arybo.lib.exprs_asm.asm_binary` for a description of the list of arguments Output: * An LLVM module with one function named "__arybo", containing the translated expression. See :meth:`arybo.lib.exprs_asm.asm_bin...
Below is the the instruction that describes the task: ### Input: Generate an LLVM module for a list of expressions Arguments: * See :meth:`arybo.lib.exprs_asm.asm_binary` for a description of the list of arguments Output: * An LLVM module with one function named "__arybo", containing the ...
def make_subset(self, samples=None, name=None): """ Creates a subset of samples, which can be treated independently. Parameters ---------- samples : str or array - like Name of sample, or list of sample names. name : (optional) str or number The n...
Creates a subset of samples, which can be treated independently. Parameters ---------- samples : str or array - like Name of sample, or list of sample names. name : (optional) str or number The name of the sample group. Defaults to n + 1, where n is t...
Below is the the instruction that describes the task: ### Input: Creates a subset of samples, which can be treated independently. Parameters ---------- samples : str or array - like Name of sample, or list of sample names. name : (optional) str or number The ...
def generateSingleNodeRST(self, node): ''' Creates the reStructuredText document for the leaf like node object. It is **assumed** that the specified ``node.kind`` is in :data:`~exhale.utils.LEAF_LIKE_KINDS`. File, directory, and namespace nodes are treated separately. ...
Creates the reStructuredText document for the leaf like node object. It is **assumed** that the specified ``node.kind`` is in :data:`~exhale.utils.LEAF_LIKE_KINDS`. File, directory, and namespace nodes are treated separately. :Parameters: ``node`` (ExhaleNode) ...
Below is the the instruction that describes the task: ### Input: Creates the reStructuredText document for the leaf like node object. It is **assumed** that the specified ``node.kind`` is in :data:`~exhale.utils.LEAF_LIKE_KINDS`. File, directory, and namespace nodes are treated separately....
def image(self): """An Image like array of ``self.data`` convenient for image processing tasks * 2D array for single band, grayscale image data * 3D array for three band, RGB image data Enables working with ``self.data`` as if it were a PIL image. See https://planetaryimage.re...
An Image like array of ``self.data`` convenient for image processing tasks * 2D array for single band, grayscale image data * 3D array for three band, RGB image data Enables working with ``self.data`` as if it were a PIL image. See https://planetaryimage.readthedocs.io/en/latest/usage...
Below is the the instruction that describes the task: ### Input: An Image like array of ``self.data`` convenient for image processing tasks * 2D array for single band, grayscale image data * 3D array for three band, RGB image data Enables working with ``self.data`` as if it were a PIL imag...
def expectRegion(self, filename, x, y, maxrms=0): """ Wait until a portion of the screen matches the target image The region compared is defined by the box (x, y), (x + image.width, y + image.height) """ log.debug('expectRegion %s (%s, %s)', filename, x, y) retur...
Wait until a portion of the screen matches the target image The region compared is defined by the box (x, y), (x + image.width, y + image.height)
Below is the the instruction that describes the task: ### Input: Wait until a portion of the screen matches the target image The region compared is defined by the box (x, y), (x + image.width, y + image.height) ### Response: def expectRegion(self, filename, x, y, maxrms=0): """ Wai...
def empty(self): """remove all children from the widget""" for k in list(self.children.keys()): self.remove_child(self.children[k])
remove all children from the widget
Below is the the instruction that describes the task: ### Input: remove all children from the widget ### Response: def empty(self): """remove all children from the widget""" for k in list(self.children.keys()): self.remove_child(self.children[k])
def adjacent(self,rng2): """ Test for adjacency. :param rng2: :param use_direction: false by default :param type: GenomicRange :param type: use_direction """ if self.chr != rng2.chr: return False if self.direction != rng2.direction and use_direction: return False if self.end == rn...
Test for adjacency. :param rng2: :param use_direction: false by default :param type: GenomicRange :param type: use_direction
Below is the the instruction that describes the task: ### Input: Test for adjacency. :param rng2: :param use_direction: false by default :param type: GenomicRange :param type: use_direction ### Response: def adjacent(self,rng2): """ Test for adjacency. :param rng2: :param use_dire...
def update(self, data): """Updates the object information based on live data, if there were any changes made. Any changes will be automatically applied to the object, but will not be automatically persisted. You must manually call `db.session.add(instance)` on the object. Args: ...
Updates the object information based on live data, if there were any changes made. Any changes will be automatically applied to the object, but will not be automatically persisted. You must manually call `db.session.add(instance)` on the object. Args: data (:obj:): AWS API Resource ...
Below is the the instruction that describes the task: ### Input: Updates the object information based on live data, if there were any changes made. Any changes will be automatically applied to the object, but will not be automatically persisted. You must manually call `db.session.add(instance)` on t...
def add_jobflow_steps(self, jobflow_id, steps): """ Adds steps to a jobflow :type jobflow_id: str :param jobflow_id: The job flow id :type steps: list(boto.emr.Step) :param steps: A list of steps to add to the job """ if type(steps) != types.ListType: ...
Adds steps to a jobflow :type jobflow_id: str :param jobflow_id: The job flow id :type steps: list(boto.emr.Step) :param steps: A list of steps to add to the job
Below is the the instruction that describes the task: ### Input: Adds steps to a jobflow :type jobflow_id: str :param jobflow_id: The job flow id :type steps: list(boto.emr.Step) :param steps: A list of steps to add to the job ### Response: def add_jobflow_steps(self, jobflow_id, s...
def parse_unit(prop, dictionary, dt=None): '''Do a fuzzy match for `prop` in the dictionary, taking into account unit suffix.''' # add the observation's time try: dt = timezone.parse_datetime(dictionary.get('date_time')) except TypeError: dt = None # 'prop' is a stub of the property...
Do a fuzzy match for `prop` in the dictionary, taking into account unit suffix.
Below is the the instruction that describes the task: ### Input: Do a fuzzy match for `prop` in the dictionary, taking into account unit suffix. ### Response: def parse_unit(prop, dictionary, dt=None): '''Do a fuzzy match for `prop` in the dictionary, taking into account unit suffix.''' # add the observati...
def _memory_usage(func, gallery_conf): """Get memory usage of a function call.""" if gallery_conf['show_memory']: from memory_profiler import memory_usage assert callable(func) mem, out = memory_usage(func, max_usage=True, retval=True, multiprocess=True) ...
Get memory usage of a function call.
Below is the the instruction that describes the task: ### Input: Get memory usage of a function call. ### Response: def _memory_usage(func, gallery_conf): """Get memory usage of a function call.""" if gallery_conf['show_memory']: from memory_profiler import memory_usage assert callable(func...
def genXML(self): """ Return XML root """ # Check conditions if self.filename is None or \ self.foldername is None or \ self.imgSize is None: return None top = Element('annotation') if self.verified: top...
Return XML root
Below is the the instruction that describes the task: ### Input: Return XML root ### Response: def genXML(self): """ Return XML root """ # Check conditions if self.filename is None or \ self.foldername is None or \ self.imgSize is None: ...
def setData(self, index, value, role=QtCore.Qt.UserRole): """Sets data at *index* to *value* in underlying data structure See :qtdoc:`QAbstractItemModel<QAbstractItemModel.setData>`, and :qtdoc:`subclassing<qabstractitemmodel.subclassing>` """ if role == QtCore.Qt.EditRole: ...
Sets data at *index* to *value* in underlying data structure See :qtdoc:`QAbstractItemModel<QAbstractItemModel.setData>`, and :qtdoc:`subclassing<qabstractitemmodel.subclassing>`
Below is the the instruction that describes the task: ### Input: Sets data at *index* to *value* in underlying data structure See :qtdoc:`QAbstractItemModel<QAbstractItemModel.setData>`, and :qtdoc:`subclassing<qabstractitemmodel.subclassing>` ### Response: def setData(self, index, value, role=Qt...
def get_paths(self, id_or_uri, path_id_or_uri=''): """ Gets all paths or a specific attachment path for the specified volume attachment. Args: id_or_uri: Can be either the volume attachment id or the volume attachment uri. path_id_or_uri: Can be either the path id or the...
Gets all paths or a specific attachment path for the specified volume attachment. Args: id_or_uri: Can be either the volume attachment id or the volume attachment uri. path_id_or_uri: Can be either the path id or the path uri. Returns: dict: Paths.
Below is the the instruction that describes the task: ### Input: Gets all paths or a specific attachment path for the specified volume attachment. Args: id_or_uri: Can be either the volume attachment id or the volume attachment uri. path_id_or_uri: Can be either the path id or the p...
def _open_text(fname, **kwargs): """On Python 3 opens a file in text mode by using fs encoding and a proper en/decoding errors handler. On Python 2 this is just an alias for open(name, 'rt'). """ if PY3: kwargs.setdefault('encoding', ENCODING) kwargs.setdefault('errors', ENCODING_ERR...
On Python 3 opens a file in text mode by using fs encoding and a proper en/decoding errors handler. On Python 2 this is just an alias for open(name, 'rt').
Below is the the instruction that describes the task: ### Input: On Python 3 opens a file in text mode by using fs encoding and a proper en/decoding errors handler. On Python 2 this is just an alias for open(name, 'rt'). ### Response: def _open_text(fname, **kwargs): """On Python 3 opens a file in text...
def stop(self): """Called to stop the reveiver thread.""" self._stop_thread.set() # f you want to close the connection in a timely fashion, # call shutdown() before close(). with self._lock: # Receive thread might use the socket self.receive_socket.shutdown(socket.SH...
Called to stop the reveiver thread.
Below is the the instruction that describes the task: ### Input: Called to stop the reveiver thread. ### Response: def stop(self): """Called to stop the reveiver thread.""" self._stop_thread.set() # f you want to close the connection in a timely fashion, # call shutdown() before clo...
def load(items, default_section=_DEFAULT_SECTION): """ 从混合类型组中读取配置 :param default_section: :param items: :return: """ settings = [] assert isinstance(items, list), 'items必须为list' logger.debug(items) for item in items: if _is_conf(item): settings.append(load_...
从混合类型组中读取配置 :param default_section: :param items: :return:
Below is the the instruction that describes the task: ### Input: 从混合类型组中读取配置 :param default_section: :param items: :return: ### Response: def load(items, default_section=_DEFAULT_SECTION): """ 从混合类型组中读取配置 :param default_section: :param items: :return: """ settings = [] ...
def import_class(import_path): """ Imports a class dynamically from a full import path. """ if not '.' in import_path: raise IncorrectImportPath( "Invalid Python-style import path provided: {0}.".format( import_path ) ) path_bits = import_path...
Imports a class dynamically from a full import path.
Below is the the instruction that describes the task: ### Input: Imports a class dynamically from a full import path. ### Response: def import_class(import_path): """ Imports a class dynamically from a full import path. """ if not '.' in import_path: raise IncorrectImportPath( "...
def leave_classdef(self, node): """check number of public methods""" my_methods = sum( 1 for method in node.mymethods() if not method.name.startswith("_") ) # Does the class contain less than n public methods ? # This checks only the methods defined in the current cl...
check number of public methods
Below is the the instruction that describes the task: ### Input: check number of public methods ### Response: def leave_classdef(self, node): """check number of public methods""" my_methods = sum( 1 for method in node.mymethods() if not method.name.startswith("_") ) # D...
def read_file(filename): """ return the contents of the file named filename or None if file not found """ if os.path.isfile(filename): with open(filename, 'r') as f: return f.read()
return the contents of the file named filename or None if file not found
Below is the the instruction that describes the task: ### Input: return the contents of the file named filename or None if file not found ### Response: def read_file(filename): """ return the contents of the file named filename or None if file not found """ if os.path.isfile(filename): with open(fi...
def exists(*nictag, **kwargs): ''' Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ''' ret = {} if not nictag: return {'...
Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin
Below is the the instruction that describes the task: ### Input: Check if nictags exists nictag : string one or more nictags to check verbose : boolean return list of nictags CLI Example: .. code-block:: bash salt '*' nictagadm.exists admin ### Response: def exists(*nict...
def fillna(self, value): """Returns Series with missing values replaced with value. Parameters ---------- value : {int, float, bytes, bool} Scalar value to replace missing values with. Returns ------- Series With missing values replaced. ...
Returns Series with missing values replaced with value. Parameters ---------- value : {int, float, bytes, bool} Scalar value to replace missing values with. Returns ------- Series With missing values replaced.
Below is the the instruction that describes the task: ### Input: Returns Series with missing values replaced with value. Parameters ---------- value : {int, float, bytes, bool} Scalar value to replace missing values with. Returns ------- Series ...
def filter_butter_coeffs(filtertype, freq, samplerate, order=5): # type: (str, Union[float, Tuple[float, float]], int, int) -> Tuple[np.ndarray, np.ndarray] """ calculates the coefficients for a digital butterworth filter filtertype: 'low', 'high', 'band' freq : cutoff freq. in...
calculates the coefficients for a digital butterworth filter filtertype: 'low', 'high', 'band' freq : cutoff freq. in the case of 'band': (low, high) Returns --> (b, a)
Below is the the instruction that describes the task: ### Input: calculates the coefficients for a digital butterworth filter filtertype: 'low', 'high', 'band' freq : cutoff freq. in the case of 'band': (low, high) Returns --> (b, a) ### Response: def filter_butter_coeffs(filtert...
def _process_mgi_note_vocevidence_view(self, limit): """ Here we fetch the free text descriptions of the phenotype associations. Triples: <annot_id> dc:description "description text" :param limit: :return: """ line_counter = 0 if self.test_mode: ...
Here we fetch the free text descriptions of the phenotype associations. Triples: <annot_id> dc:description "description text" :param limit: :return:
Below is the the instruction that describes the task: ### Input: Here we fetch the free text descriptions of the phenotype associations. Triples: <annot_id> dc:description "description text" :param limit: :return: ### Response: def _process_mgi_note_vocevidence_view(self, limit): ...
def pack(self): ''' Make ApptRec json/msgpack-friendly ''' reqdictf = {k.name.lower(): v for (k, v) in self.reqdict.items()} incunitf = None if self.incunit is None else self.incunit.name.lower() return (reqdictf, incunitf, self.incval)
Make ApptRec json/msgpack-friendly
Below is the the instruction that describes the task: ### Input: Make ApptRec json/msgpack-friendly ### Response: def pack(self): ''' Make ApptRec json/msgpack-friendly ''' reqdictf = {k.name.lower(): v for (k, v) in self.reqdict.items()} incunitf = None if self.incunit is N...
def trunc_neg_eigs(self, particle): """ Given a state represented as a model parameter vector, returns a model parameter vector representing the same state with any negative eigenvalues set to zero. :param np.ndarray particle: Vector of length ``(dim ** 2, )`` repres...
Given a state represented as a model parameter vector, returns a model parameter vector representing the same state with any negative eigenvalues set to zero. :param np.ndarray particle: Vector of length ``(dim ** 2, )`` representing a state. :return: The same state with any...
Below is the the instruction that describes the task: ### Input: Given a state represented as a model parameter vector, returns a model parameter vector representing the same state with any negative eigenvalues set to zero. :param np.ndarray particle: Vector of length ``(dim ** 2, )`` ...
def brightness_temp(self, band, temp_scale='K'): """Calculate brightness temperature of Landsat 8 as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php T = K2 / log((K1 / L) + 1) and L = ML * Q + AL where: T = At-satellite brightness temperature (degrees kelvin) ...
Calculate brightness temperature of Landsat 8 as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php T = K2 / log((K1 / L) + 1) and L = ML * Q + AL where: T = At-satellite brightness temperature (degrees kelvin) L = TOA spectral radiance (Watts / (m2 * srad * mm)...
Below is the the instruction that describes the task: ### Input: Calculate brightness temperature of Landsat 8 as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php T = K2 / log((K1 / L) + 1) and L = ML * Q + AL where: T = At-satellite brightness temperature (degrees...
def get_first(): """ return first droplet """ client = po.connect() # this depends on the DIGITALOCEAN_API_KEY envvar all_droplets = client.droplets.list() id = all_droplets[0]['id'] # I'm cheating because I only have one droplet return client.droplets.get(id)
return first droplet
Below is the the instruction that describes the task: ### Input: return first droplet ### Response: def get_first(): """ return first droplet """ client = po.connect() # this depends on the DIGITALOCEAN_API_KEY envvar all_droplets = client.droplets.list() id = all_droplets[0]['id'] # I'm ch...
def framework_find(fn, executable_path=None, env=None): """ Find a framework using dyld semantics in a very loose manner. Will take input such as: Python Python.framework Python.framework/Versions/Current """ try: return dyld_find(fn, executable_path=executable_path,...
Find a framework using dyld semantics in a very loose manner. Will take input such as: Python Python.framework Python.framework/Versions/Current
Below is the the instruction that describes the task: ### Input: Find a framework using dyld semantics in a very loose manner. Will take input such as: Python Python.framework Python.framework/Versions/Current ### Response: def framework_find(fn, executable_path=None, env=None): ""...
def compute_distortion(x_orig, y_orig, x_rect, y_rect, order, debugplot): """Compute image distortion transformation. This function computes the following 2D transformation: x_orig = sum[i=0:order]( sum[j=0:j]( a_ij * x_rect**(i - j) * y_rect**j )) y_orig = sum[i=0:order]( sum[j=0:j]( b_ij * x_rect**(i...
Compute image distortion transformation. This function computes the following 2D transformation: x_orig = sum[i=0:order]( sum[j=0:j]( a_ij * x_rect**(i - j) * y_rect**j )) y_orig = sum[i=0:order]( sum[j=0:j]( b_ij * x_rect**(i - j) * y_rect**j )) Parameters ---------- x_orig : numpy array ...
Below is the the instruction that describes the task: ### Input: Compute image distortion transformation. This function computes the following 2D transformation: x_orig = sum[i=0:order]( sum[j=0:j]( a_ij * x_rect**(i - j) * y_rect**j )) y_orig = sum[i=0:order]( sum[j=0:j]( b_ij * x_rect**(i - j) * y_re...