code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def plot(self): """Export a given dataset to a `CSV` file. This method is a slot connected to the `export` QAction. See the :meth:`addEntry` method for details. """ # The PyTables node tied to the current leaf of the databases tree current = self.vtgui.dbs_tree_view.curr...
Export a given dataset to a `CSV` file. This method is a slot connected to the `export` QAction. See the :meth:`addEntry` method for details.
Below is the the instruction that describes the task: ### Input: Export a given dataset to a `CSV` file. This method is a slot connected to the `export` QAction. See the :meth:`addEntry` method for details. ### Response: def plot(self): """Export a given dataset to a `CSV` file. T...
def add_listener(self, event, callback, once=False): """ Register a *callback* for the specified *event*. The function will be called with the #Job as its first argument. If *once* is #True, the listener will be removed after it has been invoked once or when the job is re-started. Note that if ...
Register a *callback* for the specified *event*. The function will be called with the #Job as its first argument. If *once* is #True, the listener will be removed after it has been invoked once or when the job is re-started. Note that if the event already ocurred, *callback* will be called immediat...
Below is the the instruction that describes the task: ### Input: Register a *callback* for the specified *event*. The function will be called with the #Job as its first argument. If *once* is #True, the listener will be removed after it has been invoked once or when the job is re-started. Note that...
def disassemble(bytecode, pc=0, fork=DEFAULT_FORK): """ Disassemble an EVM bytecode :param bytecode: binary representation of an evm bytecode :type bytecode: str | bytes | bytearray :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork...
Disassemble an EVM bytecode :param bytecode: binary representation of an evm bytecode :type bytecode: str | bytes | bytearray :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) :type fork: str :return: th...
Below is the the instruction that describes the task: ### Input: Disassemble an EVM bytecode :param bytecode: binary representation of an evm bytecode :type bytecode: str | bytes | bytearray :param pc: program counter of the first instruction(optional) :type pc: int :param f...
def cluster_sample1(): "Start with wrong number of clusters." start_centers = [[3.7, 5.5]] template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE1, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION) template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE1, criterion = splitt...
Start with wrong number of clusters.
Below is the the instruction that describes the task: ### Input: Start with wrong number of clusters. ### Response: def cluster_sample1(): "Start with wrong number of clusters." start_centers = [[3.7, 5.5]] template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE1, criterion = splitting_type....
def do_hotswap(self, msg): """ Attempt to hotswap the code """ #: Show hotswap tooltip try: self.app.widget.showTooltip("Hot swapping...", now=True) except: pass self.save_changed_files(msg) hotswap = self.hotswap app = self.app tr...
Attempt to hotswap the code
Below is the the instruction that describes the task: ### Input: Attempt to hotswap the code ### Response: def do_hotswap(self, msg): """ Attempt to hotswap the code """ #: Show hotswap tooltip try: self.app.widget.showTooltip("Hot swapping...", now=True) except: ...
def description(self) -> str: '''Test name in nose output (intended to be overridden).''' return '{0.uuid.hex}—{1}'.format(self, self.context.module)
Test name in nose output (intended to be overridden).
Below is the the instruction that describes the task: ### Input: Test name in nose output (intended to be overridden). ### Response: def description(self) -> str: '''Test name in nose output (intended to be overridden).''' return '{0.uuid.hex}—{1}'.format(self, self.context.module)
def _constructTypeQualifiedName(self, type, full=False): """ For given type construct its full qualified name. AnonymousField = [ "*" ] TypeName . TypeName = identifier | QualifiedIdent . QualifiedIdent = PackageName "." identifier . """ t = type["type"] if t == TYPE_IDENT: return type["def"] eli...
For given type construct its full qualified name. AnonymousField = [ "*" ] TypeName . TypeName = identifier | QualifiedIdent . QualifiedIdent = PackageName "." identifier .
Below is the the instruction that describes the task: ### Input: For given type construct its full qualified name. AnonymousField = [ "*" ] TypeName . TypeName = identifier | QualifiedIdent . QualifiedIdent = PackageName "." identifier . ### Response: def _constructTypeQualifiedName(self, type, full=False)...
def add_data_point(self, value, number_format=None): """ Return a CategoryDataPoint object newly created with value *value*, an optional *number_format*, and appended to this sequence. """ data_point = CategoryDataPoint(self, value, number_format) self.append(data_point) ...
Return a CategoryDataPoint object newly created with value *value*, an optional *number_format*, and appended to this sequence.
Below is the the instruction that describes the task: ### Input: Return a CategoryDataPoint object newly created with value *value*, an optional *number_format*, and appended to this sequence. ### Response: def add_data_point(self, value, number_format=None): """ Return a CategoryDataPoint ...
def h_from_V(self, V, method='spline'): r'''Method to calculate the height of liquid in a fully defined tank given a specified volume of liquid in it `V`. `V` must be under the maximum volume. If the method is 'spline', and the interpolation table is not yet defined, creates it by callin...
r'''Method to calculate the height of liquid in a fully defined tank given a specified volume of liquid in it `V`. `V` must be under the maximum volume. If the method is 'spline', and the interpolation table is not yet defined, creates it by calling the method set_table. If the method is...
Below is the the instruction that describes the task: ### Input: r'''Method to calculate the height of liquid in a fully defined tank given a specified volume of liquid in it `V`. `V` must be under the maximum volume. If the method is 'spline', and the interpolation table is not yet defined,...
def namespaces(self, psuedo=True): """ Fetches a list of namespaces for this wiki and returns them as a dictionary of namespace IDs corresponding to namespace names. If *psuedo* is ``True``, the dictionary will also list psuedo-namespaces, which are the "Special:" and "Media:" na...
Fetches a list of namespaces for this wiki and returns them as a dictionary of namespace IDs corresponding to namespace names. If *psuedo* is ``True``, the dictionary will also list psuedo-namespaces, which are the "Special:" and "Media:" namespaces (special because they have no content ...
Below is the the instruction that describes the task: ### Input: Fetches a list of namespaces for this wiki and returns them as a dictionary of namespace IDs corresponding to namespace names. If *psuedo* is ``True``, the dictionary will also list psuedo-namespaces, which are the "Special:" a...
def _getLayer(self, name, **kwargs): """ name will be a string, but there may not be a layer with a name matching the string. If not, a ``ValueError`` must be raised. Subclasses may override this method. """ for glyph in self.layers: if glyph.layer.na...
name will be a string, but there may not be a layer with a name matching the string. If not, a ``ValueError`` must be raised. Subclasses may override this method.
Below is the the instruction that describes the task: ### Input: name will be a string, but there may not be a layer with a name matching the string. If not, a ``ValueError`` must be raised. Subclasses may override this method. ### Response: def _getLayer(self, name, **kwargs): """...
def model_loss(y, model, mean=True): """ Define loss of TF graph :param y: correct labels :param model: output of the model :param mean: boolean indicating whether should return mean of loss or vector of losses for each input of the batch :return: return mean of loss if True, otherwise return...
Define loss of TF graph :param y: correct labels :param model: output of the model :param mean: boolean indicating whether should return mean of loss or vector of losses for each input of the batch :return: return mean of loss if True, otherwise return vector with per sample loss
Below is the the instruction that describes the task: ### Input: Define loss of TF graph :param y: correct labels :param model: output of the model :param mean: boolean indicating whether should return mean of loss or vector of losses for each input of the batch :return: return mean of loss i...
def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: ...
Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. code-block:: bash salt '*' heat.delete_stack name=mystack po...
Below is the the instruction that describes the task: ### Input: Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: .. ...
def is_match(self, command): """Returns `True` if rule matches the command. :type command: Command :rtype: bool """ if command.output is None and self.requires_output: return False try: with logs.debug_time(u'Trying rule: {};'.format(self.name))...
Returns `True` if rule matches the command. :type command: Command :rtype: bool
Below is the the instruction that describes the task: ### Input: Returns `True` if rule matches the command. :type command: Command :rtype: bool ### Response: def is_match(self, command): """Returns `True` if rule matches the command. :type command: Command :rtype: bool ...
def check_other(self): """ If the requirement is frozen somewhere other than pypi or github, skip. If you have a private pypi or use --extra-index-url, consider contributing support here. """ if self.reqs: self.stdout.write(self.style.ERROR("\nOnly pypi and g...
If the requirement is frozen somewhere other than pypi or github, skip. If you have a private pypi or use --extra-index-url, consider contributing support here.
Below is the the instruction that describes the task: ### Input: If the requirement is frozen somewhere other than pypi or github, skip. If you have a private pypi or use --extra-index-url, consider contributing support here. ### Response: def check_other(self): """ If the requirem...
def size(self, table=None): """ Return the size, in bytes, of the profile or *table*. If *table* is `None`, this function returns the size of the whole profile (i.e. the sum of the table sizes). Otherwise, it returns the size of *table*. Note: if the file is gzipped, it...
Return the size, in bytes, of the profile or *table*. If *table* is `None`, this function returns the size of the whole profile (i.e. the sum of the table sizes). Otherwise, it returns the size of *table*. Note: if the file is gzipped, it returns the compressed size.
Below is the the instruction that describes the task: ### Input: Return the size, in bytes, of the profile or *table*. If *table* is `None`, this function returns the size of the whole profile (i.e. the sum of the table sizes). Otherwise, it returns the size of *table*. Note: if th...
def install(): """ Installs ScoutApm SQL Instrumentation by monkeypatching the `cursor` method of BaseDatabaseWrapper, to return a wrapper that instruments any calls going through it. """ @monkeypatch_method(BaseDatabaseWrapper) def cursor(original, self, *args, ...
Installs ScoutApm SQL Instrumentation by monkeypatching the `cursor` method of BaseDatabaseWrapper, to return a wrapper that instruments any calls going through it.
Below is the the instruction that describes the task: ### Input: Installs ScoutApm SQL Instrumentation by monkeypatching the `cursor` method of BaseDatabaseWrapper, to return a wrapper that instruments any calls going through it. ### Response: def install(): """ Installs ScoutApm SQ...
def get_nodes_with(self, obj): """Return nodes with `obj`.""" result = set() if nx.__version__[0] == "1": nodes = self.nodes_iter() else: nodes = self.nodes for node in nodes: if node[OBJ] == obj: result.add(node) retu...
Return nodes with `obj`.
Below is the the instruction that describes the task: ### Input: Return nodes with `obj`. ### Response: def get_nodes_with(self, obj): """Return nodes with `obj`.""" result = set() if nx.__version__[0] == "1": nodes = self.nodes_iter() else: nodes = self.nod...
def set_(schema=None, key=None, user=None, value=None, **kwargs): ''' Set key in a particular GNOME schema CLI Example: .. code-block:: bash salt '*' gnome.set user=<username> schema=org.gnome.desktop.screensaver key=idle-activation-enabled value=False ''' _gsession = _GSettings(user...
Set key in a particular GNOME schema CLI Example: .. code-block:: bash salt '*' gnome.set user=<username> schema=org.gnome.desktop.screensaver key=idle-activation-enabled value=False
Below is the the instruction that describes the task: ### Input: Set key in a particular GNOME schema CLI Example: .. code-block:: bash salt '*' gnome.set user=<username> schema=org.gnome.desktop.screensaver key=idle-activation-enabled value=False ### Response: def set_(schema=None, key=None, us...
def _m_degree(self, term): """Return Porter helper function _m_degree value. m-degree is equal to the number of V to C transitions Parameters ---------- term : str The word for which to calculate the m-degree Returns ------- int ...
Return Porter helper function _m_degree value. m-degree is equal to the number of V to C transitions Parameters ---------- term : str The word for which to calculate the m-degree Returns ------- int The m-degree as defined in the Porter ...
Below is the the instruction that describes the task: ### Input: Return Porter helper function _m_degree value. m-degree is equal to the number of V to C transitions Parameters ---------- term : str The word for which to calculate the m-degree Returns -...
def detect_gpt(self, filename, offset, fs_guid): """Used by rawdisk.session.Session to match gpt partitions agains filesystem plugins. Args: filename: device or file that it will read in order to detect the filesystem fs_id: filesystem guid to match ...
Used by rawdisk.session.Session to match gpt partitions agains filesystem plugins. Args: filename: device or file that it will read in order to detect the filesystem fs_id: filesystem guid to match (ex. {EBD0A0A2-B9E5-4433-87C0-68B6B72699C7}) ...
Below is the the instruction that describes the task: ### Input: Used by rawdisk.session.Session to match gpt partitions agains filesystem plugins. Args: filename: device or file that it will read in order to detect the filesystem fs_id: filesystem guid to match ...
def attach(self, filename=None, content_type=None, data=None, disposition=None, headers=None): """Adds an attachment to the message. :param filename: filename of attachment :param content_type: file mimetype :par...
Adds an attachment to the message. :param filename: filename of attachment :param content_type: file mimetype :param data: the raw file data :param disposition: content-disposition (if any)
Below is the the instruction that describes the task: ### Input: Adds an attachment to the message. :param filename: filename of attachment :param content_type: file mimetype :param data: the raw file data :param disposition: content-disposition (if any) ### Response: def attach(se...
def Triangular(low, peak, high, tag=None): """ A triangular random variate Parameters ---------- low : scalar Lower bound of the distribution support peak : scalar The location of the triangle's peak (low <= peak <= high) high : scalar Upper bound of the distribu...
A triangular random variate Parameters ---------- low : scalar Lower bound of the distribution support peak : scalar The location of the triangle's peak (low <= peak <= high) high : scalar Upper bound of the distribution support
Below is the the instruction that describes the task: ### Input: A triangular random variate Parameters ---------- low : scalar Lower bound of the distribution support peak : scalar The location of the triangle's peak (low <= peak <= high) high : scalar Upper bound o...
def draw_if_interactive(): """ This should be overriden in a windowing environment if drawing should be done in interactive python mode """ DEBUG_MSG("draw_if_interactive()", 1, None) if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: ...
This should be overriden in a windowing environment if drawing should be done in interactive python mode
Below is the the instruction that describes the task: ### Input: This should be overriden in a windowing environment if drawing should be done in interactive python mode ### Response: def draw_if_interactive(): """ This should be overriden in a windowing environment if drawing should be done in int...
def date(ctx, year, month, day): """ Defines a date value """ return _date(conversions.to_integer(year, ctx), conversions.to_integer(month, ctx), conversions.to_integer(day, ctx))
Defines a date value
Below is the the instruction that describes the task: ### Input: Defines a date value ### Response: def date(ctx, year, month, day): """ Defines a date value """ return _date(conversions.to_integer(year, ctx), conversions.to_integer(month, ctx), conversions.to_integer(day, ctx))
def write(variable, value): """ write an element to LiFePO4wered. :param variable: the element. :type variable: Lifepo4weredEnum :param int value: the value to write. :return: the written value :rtype: int :raises ValueError: if variable parameter is not a member of Lifepo4weredEnum ...
write an element to LiFePO4wered. :param variable: the element. :type variable: Lifepo4weredEnum :param int value: the value to write. :return: the written value :rtype: int :raises ValueError: if variable parameter is not a member of Lifepo4weredEnum :raises ValueError: if value is not an ...
Below is the the instruction that describes the task: ### Input: write an element to LiFePO4wered. :param variable: the element. :type variable: Lifepo4weredEnum :param int value: the value to write. :return: the written value :rtype: int :raises ValueError: if variable parameter is not a m...
def legendre_fit_magseries(times, mags, errs, period, legendredeg=10, sigclip=30.0, plotfit=False, magsarefluxes=False, verbose=True): '''Fit an arbitrary-order Legendre series, vi...
Fit an arbitrary-order Legendre series, via least squares, to the magnitude/flux time series. This is a series of the form:: p(x) = c_0*L_0(x) + c_1*L_1(x) + c_2*L_2(x) + ... + c_n*L_n(x) where L_i's are Legendre polynomials (also called "Legendre functions of the first kind") and c_i's are t...
Below is the the instruction that describes the task: ### Input: Fit an arbitrary-order Legendre series, via least squares, to the magnitude/flux time series. This is a series of the form:: p(x) = c_0*L_0(x) + c_1*L_1(x) + c_2*L_2(x) + ... + c_n*L_n(x) where L_i's are Legendre polynomials (al...
def get_known_subqueues(self): """ Returns all known subqueues """ if not self.has_subqueues: return set() return set(context.connections.redis.smembers(self.redis_key_known_subqueues))
Returns all known subqueues
Below is the the instruction that describes the task: ### Input: Returns all known subqueues ### Response: def get_known_subqueues(self): """ Returns all known subqueues """ if not self.has_subqueues: return set() return set(context.connections.redis.smembers(self.redis_key_know...
def request(self, path, data=None, headers=None, method=None): """Performs a HTTP request to the Go server Args: path (str): The full path on the Go server to request. This includes any query string attributes. data (str, dict, bool, optional): If any data is present thi...
Performs a HTTP request to the Go server Args: path (str): The full path on the Go server to request. This includes any query string attributes. data (str, dict, bool, optional): If any data is present this request will become a POST request. headers (dict,...
Below is the the instruction that describes the task: ### Input: Performs a HTTP request to the Go server Args: path (str): The full path on the Go server to request. This includes any query string attributes. data (str, dict, bool, optional): If any data is present this ...
def show_cationpi(self): """Visualizes cation-pi interactions""" grp = self.getPseudoBondGroup("Cation-Pi-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 grp.lineType = self.chimera.Dash for i, cat in enumerate(self.plcomplex.pication): m = self.model ...
Visualizes cation-pi interactions
Below is the the instruction that describes the task: ### Input: Visualizes cation-pi interactions ### Response: def show_cationpi(self): """Visualizes cation-pi interactions""" grp = self.getPseudoBondGroup("Cation-Pi-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 gr...
def _get_action_endpoint(action): """ Return the endpoint base on the view's action :param action: :return: """ _endpoint = None if is_method(action): if hasattr(action, "_rule_cache"): rc = action._rule_cache if rc: k = list(rc.keys())[0] ...
Return the endpoint base on the view's action :param action: :return:
Below is the the instruction that describes the task: ### Input: Return the endpoint base on the view's action :param action: :return: ### Response: def _get_action_endpoint(action): """ Return the endpoint base on the view's action :param action: :return: """ _endpoint = None i...
def cli(env, title, subject_id, body, hardware_identifier, virtual_identifier, priority): """Create a support ticket.""" ticket_mgr = SoftLayer.TicketManager(env.client) if body is None: body = click.edit('\n\n' + ticket.TEMPLATE_MSG) created_ticket = ticket_mgr.create_ticket( title=tit...
Create a support ticket.
Below is the the instruction that describes the task: ### Input: Create a support ticket. ### Response: def cli(env, title, subject_id, body, hardware_identifier, virtual_identifier, priority): """Create a support ticket.""" ticket_mgr = SoftLayer.TicketManager(env.client) if body is None: bod...
def adapt(self, other: 'BinningBase'): """Adapt this binning so that it contains all bins of another binning. Parameters ---------- other: BinningBase """ # TODO: in-place arg if np.array_equal(self.bins, other.bins): return None, None elif no...
Adapt this binning so that it contains all bins of another binning. Parameters ---------- other: BinningBase
Below is the the instruction that describes the task: ### Input: Adapt this binning so that it contains all bins of another binning. Parameters ---------- other: BinningBase ### Response: def adapt(self, other: 'BinningBase'): """Adapt this binning so that it contains all bins of a...
def to_fp(self, file_pointer, comments=None): """ The method can be used to save a CNF+ formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. ...
The method can be used to save a CNF+ formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. :param fname: a file name where to store the formula. :pa...
Below is the the instruction that describes the task: ### Input: The method can be used to save a CNF+ formula into a file pointer. The file pointer is expected as an argument. Additionally, supplementary comment lines can be specified in the ``comments`` parameter. ...
def no_inner_space(self, *, outer=True): """Default spacing for all things written is ignored in this context. :outer: boolean, if True the typical padding and newline are added before the first and after the last things written """ if outer: self._pad() indent_was = self._indent...
Default spacing for all things written is ignored in this context. :outer: boolean, if True the typical padding and newline are added before the first and after the last things written
Below is the the instruction that describes the task: ### Input: Default spacing for all things written is ignored in this context. :outer: boolean, if True the typical padding and newline are added before the first and after the last things written ### Response: def no_inner_space(self, *, outer=...
def _submarine_2d_smooth(space, taper): """Return a 2d smooth 'submarine' phantom.""" def logistic(x, c): """Smoothed step function from 0 to 1, centered at 0.""" return 1. / (1 + np.exp(-c * x)) def blurred_ellipse(x): """Blurred characteristic function of an ellipse. If ...
Return a 2d smooth 'submarine' phantom.
Below is the the instruction that describes the task: ### Input: Return a 2d smooth 'submarine' phantom. ### Response: def _submarine_2d_smooth(space, taper): """Return a 2d smooth 'submarine' phantom.""" def logistic(x, c): """Smoothed step function from 0 to 1, centered at 0.""" return 1...
def _decoder(self, obj): """ Decode a toc element leaf-node """ if '__class__' in obj: elem = eval(obj['__class__'])() elem.ident = obj['ident'] elem.group = str(obj['group']) elem.name = str(obj['name']) elem.ctype = str(obj['ctype']) ...
Decode a toc element leaf-node
Below is the the instruction that describes the task: ### Input: Decode a toc element leaf-node ### Response: def _decoder(self, obj): """ Decode a toc element leaf-node """ if '__class__' in obj: elem = eval(obj['__class__'])() elem.ident = obj['ident'] elem.gro...
def document(request, abbr, session, bill_id, doc_id): ''' Context: - abbr - session - bill - version - metadata - nav_active Templates: - billy/web/public/document.html ''' # get fixed version fixed_bill_id = fix_bill_id(bill_id) # re...
Context: - abbr - session - bill - version - metadata - nav_active Templates: - billy/web/public/document.html
Below is the the instruction that describes the task: ### Input: Context: - abbr - session - bill - version - metadata - nav_active Templates: - billy/web/public/document.html ### Response: def document(request, abbr, session, bill_id, doc_id): ''' ...
def main(): """Parse the command line and run :func:`migrate`.""" parser = get_args_parser() args = parser.parse_args() config = Config.from_parse_args(args) migrate(config)
Parse the command line and run :func:`migrate`.
Below is the the instruction that describes the task: ### Input: Parse the command line and run :func:`migrate`. ### Response: def main(): """Parse the command line and run :func:`migrate`.""" parser = get_args_parser() args = parser.parse_args() config = Config.from_parse_args(args) migrate(co...
def worker_loop_v1(dataset, key_queue, data_queue, batchify_fn): """Worker loop for multiprocessing DataLoader.""" while True: idx, samples = key_queue.get() if idx is None: break batch = batchify_fn([dataset[i] for i in samples]) data_queue.put((idx, batch))
Worker loop for multiprocessing DataLoader.
Below is the the instruction that describes the task: ### Input: Worker loop for multiprocessing DataLoader. ### Response: def worker_loop_v1(dataset, key_queue, data_queue, batchify_fn): """Worker loop for multiprocessing DataLoader.""" while True: idx, samples = key_queue.get() if idx is ...
def colorize(message, color=None): """Returns a message in a specified color.""" if not color: return message colors = { "green": colorama.Fore.GREEN, "yellow": colorama.Fore.YELLOW, "blue": colorama.Fore.BLUE, "red": colorama.Fore.RED, } return "{color}{mes...
Returns a message in a specified color.
Below is the the instruction that describes the task: ### Input: Returns a message in a specified color. ### Response: def colorize(message, color=None): """Returns a message in a specified color.""" if not color: return message colors = { "green": colorama.Fore.GREEN, "yellow"...
def inverse_transform(self, y, lengths=None): """Return label strings. Args: y: label id matrix. lengths: sentences length. Returns: list: list of list of strings. """ y = np.argmax(y, -1) inverse_y = [self._label_vocab.id2doc(ids) fo...
Return label strings. Args: y: label id matrix. lengths: sentences length. Returns: list: list of list of strings.
Below is the the instruction that describes the task: ### Input: Return label strings. Args: y: label id matrix. lengths: sentences length. Returns: list: list of list of strings. ### Response: def inverse_transform(self, y, lengths=None): """Return lab...
def get_bin(self, arch='x86'): """ Get binaries of Visual C++. """ bin_dir = os.path.join(self.vc_dir, 'bin') if arch == 'x86': arch = '' cl_path = os.path.join(bin_dir, arch, 'cl.exe') link_path = os.path.join(bin_dir, arch, 'link.exe') ml_nam...
Get binaries of Visual C++.
Below is the the instruction that describes the task: ### Input: Get binaries of Visual C++. ### Response: def get_bin(self, arch='x86'): """ Get binaries of Visual C++. """ bin_dir = os.path.join(self.vc_dir, 'bin') if arch == 'x86': arch = '' cl_path = ...
def refine_rotation(self): """ Helper method for refining rotation matrix by ensuring that second and third rows are perpindicular to the first. Gets new y vector from an orthogonal projection of x onto y and the new z vector from a cross product of the new x and y Args:...
Helper method for refining rotation matrix by ensuring that second and third rows are perpindicular to the first. Gets new y vector from an orthogonal projection of x onto y and the new z vector from a cross product of the new x and y Args: tol to test for rotation ...
Below is the the instruction that describes the task: ### Input: Helper method for refining rotation matrix by ensuring that second and third rows are perpindicular to the first. Gets new y vector from an orthogonal projection of x onto y and the new z vector from a cross product of the new ...
def update(self, account_sid=values.unset, api_version=values.unset, friendly_name=values.unset, sms_application_sid=values.unset, sms_fallback_method=values.unset, sms_fallback_url=values.unset, sms_method=values.unset, sms_url=values.unset, status_callback=v...
Update the IncomingPhoneNumberInstance :param unicode account_sid: The SID of the Account that created the resource to update :param unicode api_version: The API version to use for incoming calls made to the phone number :param unicode friendly_name: A string to describe the resource :p...
Below is the the instruction that describes the task: ### Input: Update the IncomingPhoneNumberInstance :param unicode account_sid: The SID of the Account that created the resource to update :param unicode api_version: The API version to use for incoming calls made to the phone number :para...
def lock(backend=None, remote=None): ''' .. versionadded:: 2015.5.0 Set a fileserver update lock for VCS fileserver backends (:mod:`git <salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn <salt.fileserver.svnfs>`). .. note:: This will only operate on enabled backends...
.. versionadded:: 2015.5.0 Set a fileserver update lock for VCS fileserver backends (:mod:`git <salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn <salt.fileserver.svnfs>`). .. note:: This will only operate on enabled backends (those configured in :conf_master:`files...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2015.5.0 Set a fileserver update lock for VCS fileserver backends (:mod:`git <salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn <salt.fileserver.svnfs>`). .. note:: This will only operate...
def get_all_permissions(self): """Returns a set of tuples with the perm name and view menu name""" perms = set() for role in self.get_user_roles(): for perm_view in role.permissions: t = (perm_view.permission.name, perm_view.view_menu.name) perms.add(t...
Returns a set of tuples with the perm name and view menu name
Below is the the instruction that describes the task: ### Input: Returns a set of tuples with the perm name and view menu name ### Response: def get_all_permissions(self): """Returns a set of tuples with the perm name and view menu name""" perms = set() for role in self.get_user_roles(): ...
def get_datapoints(root): """Parse datapoints with ignition delay from file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with ignition delay data """ # Shock tube experiment will have one data group, while RCM ma...
Parse datapoints with ignition delay from file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with ignition delay data
Below is the the instruction that describes the task: ### Input: Parse datapoints with ignition delay from file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with ignition delay data ### Response: def get_datapoints(root...
def add_functions(spec_dict: Mapping[str, Any]) -> Mapping[str, Any]: """Add function keys to spec_dict Args: spec_dict (Mapping[str, Any]): bel specification dictionary Returns: Mapping[str, Any]: bel specification dictionary with added function keys """ # Class 'Mapping' does no...
Add function keys to spec_dict Args: spec_dict (Mapping[str, Any]): bel specification dictionary Returns: Mapping[str, Any]: bel specification dictionary with added function keys
Below is the the instruction that describes the task: ### Input: Add function keys to spec_dict Args: spec_dict (Mapping[str, Any]): bel specification dictionary Returns: Mapping[str, Any]: bel specification dictionary with added function keys ### Response: def add_functions(spec_dict: Ma...
def addImg(self, img, maxShear=0.015, maxRot=100, minMatches=12, borderWidth=3): # borderWidth=100 """ Args: img (path or array): image containing the same object as in the reference image Kwargs: maxShear (float): In order to define a good fit, refe...
Args: img (path or array): image containing the same object as in the reference image Kwargs: maxShear (float): In order to define a good fit, refect higher shear values between this and the reference image maxRot (float): Same for rotation ...
Below is the the instruction that describes the task: ### Input: Args: img (path or array): image containing the same object as in the reference image Kwargs: maxShear (float): In order to define a good fit, refect higher shear values between this an...
def insert_or_merge_entity(self, entity): ''' Adds an insert or merge entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.insert_or_merge_entity` for more information on insert or merge operations. The operation will not be executed until t...
Adds an insert or merge entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.insert_or_merge_entity` for more information on insert or merge operations. The operation will not be executed until the batch is committed. :param entity: The...
Below is the the instruction that describes the task: ### Input: Adds an insert or merge entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.insert_or_merge_entity` for more information on insert or merge operations. The operation will not be executed ...
def start_master_nodes(masters, cl_args): ''' Start master nodes ''' pids = [] for master in masters: Log.info("Starting master on %s" % master) cmd = "%s agent -config %s >> /tmp/nomad_server_log 2>&1 &" \ % (get_nomad_path(cl_args), get_nomad_master_config_file(cl_args)) if not is_self...
Start master nodes
Below is the the instruction that describes the task: ### Input: Start master nodes ### Response: def start_master_nodes(masters, cl_args): ''' Start master nodes ''' pids = [] for master in masters: Log.info("Starting master on %s" % master) cmd = "%s agent -config %s >> /tmp/nomad_server_log 2>...
def until(self, regex): """Wait until the regex encountered """ logger.debug('waiting for %s', regex) r = re.compile(regex, re.M) self.tn.expect([r])
Wait until the regex encountered
Below is the the instruction that describes the task: ### Input: Wait until the regex encountered ### Response: def until(self, regex): """Wait until the regex encountered """ logger.debug('waiting for %s', regex) r = re.compile(regex, re.M) self.tn.expect([r])
def betting_market_rules_update( self, rules_id, names, descriptions, account=None, **kwargs ): """ Update betting market rules :param str rules_id: Id of the betting market rules to update :param list names: Internationalized names, e.g. ``[['de', 'Foo'], ['...
Update betting market rules :param str rules_id: Id of the betting market rules to update :param list names: Internationalized names, e.g. ``[['de', 'Foo'], ['en', 'bar']]`` :param list descriptions: Internationalized descriptions, e.g. ``[['de', 'Foo...
Below is the the instruction that describes the task: ### Input: Update betting market rules :param str rules_id: Id of the betting market rules to update :param list names: Internationalized names, e.g. ``[['de', 'Foo'], ['en', 'bar']]`` :param list descriptions...
def _set_event_entry(self, v, load=False): """ Setter method for event_entry, mapped from YANG variable /rmon/event_entry (list) If this variable is read-only (config: false) in the source YANG file, then _set_event_entry is considered as a private method. Backends looking to populate this variable ...
Setter method for event_entry, mapped from YANG variable /rmon/event_entry (list) If this variable is read-only (config: false) in the source YANG file, then _set_event_entry is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_event_entry()...
Below is the the instruction that describes the task: ### Input: Setter method for event_entry, mapped from YANG variable /rmon/event_entry (list) If this variable is read-only (config: false) in the source YANG file, then _set_event_entry is considered as a private method. Backends looking to populate ...
def deleteinputfile(project, filename, credentials=None): """Delete an input file""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable filename = filename.replace("..","") #Simple security if len(filename) == 0: #Deleting all input fi...
Delete an input file
Below is the the instruction that describes the task: ### Input: Delete an input file ### Response: def deleteinputfile(project, filename, credentials=None): """Delete an input file""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable filename = file...
def dropout(a, p=0.5, inplace=False): """Randomly set elements from `a` equal to zero, with proportion `p`. Similar in concept to the dropout technique employed within neural networks. Parameters ---------- a: numpy.ndarray Array to be modified. p: float in [0, 1] ...
Randomly set elements from `a` equal to zero, with proportion `p`. Similar in concept to the dropout technique employed within neural networks. Parameters ---------- a: numpy.ndarray Array to be modified. p: float in [0, 1] Expected proportion of elements in the resul...
Below is the the instruction that describes the task: ### Input: Randomly set elements from `a` equal to zero, with proportion `p`. Similar in concept to the dropout technique employed within neural networks. Parameters ---------- a: numpy.ndarray Array to be modified. p: ...
def _update_cardinality(self, column): """ QUERY ES TO FIND CARDINALITY AND PARTITIONS FOR A SIMPLE COLUMN """ now = Date.now() if column.es_index in self.index_does_not_exist: return if column.jx_type in STRUCT: Log.error("not supported") ...
QUERY ES TO FIND CARDINALITY AND PARTITIONS FOR A SIMPLE COLUMN
Below is the the instruction that describes the task: ### Input: QUERY ES TO FIND CARDINALITY AND PARTITIONS FOR A SIMPLE COLUMN ### Response: def _update_cardinality(self, column): """ QUERY ES TO FIND CARDINALITY AND PARTITIONS FOR A SIMPLE COLUMN """ now = Date.now() if c...
def print_no_files_found(opts): """ Prints message that no files were found in the input directory with the given list of extensions. :param opts: Namespace object created from command-line arguments. Must have the attributes 'extensions' and 'input' """ msg = "No files found with [" +', '...
Prints message that no files were found in the input directory with the given list of extensions. :param opts: Namespace object created from command-line arguments. Must have the attributes 'extensions' and 'input'
Below is the the instruction that describes the task: ### Input: Prints message that no files were found in the input directory with the given list of extensions. :param opts: Namespace object created from command-line arguments. Must have the attributes 'extensions' and 'input' ### Response: def prin...
def bonds(self): """List of :class:`Bonds <pubchempy.Bond>` between :class:`Atoms <pubchempy.Atom>` in this Compound.""" return sorted(self._bonds.values(), key=lambda x: (x.aid1, x.aid2))
List of :class:`Bonds <pubchempy.Bond>` between :class:`Atoms <pubchempy.Atom>` in this Compound.
Below is the the instruction that describes the task: ### Input: List of :class:`Bonds <pubchempy.Bond>` between :class:`Atoms <pubchempy.Atom>` in this Compound. ### Response: def bonds(self): """List of :class:`Bonds <pubchempy.Bond>` between :class:`Atoms <pubchempy.Atom>` in this Compound.""" r...
def make_request(endpoint, **kwargs): """Send a request to server.""" data = kwargs.get('json', []) package = kwargs.get('package', None) method = kwargs.get('method', 'GET') function = getattr(requests, method.lower()) try: if package: respo...
Send a request to server.
Below is the the instruction that describes the task: ### Input: Send a request to server. ### Response: def make_request(endpoint, **kwargs): """Send a request to server.""" data = kwargs.get('json', []) package = kwargs.get('package', None) method = kwargs.get('method', 'GET') ...
def str_to_credentials(s): ''' str_to_credentials(s) yields (key, secret) if the given string is a valid representation of a set of credentials. Valid representations include '<key>:<secret>' and '<key>\n<secret>'. All initial and trailing whitespace is always stripped from both key and scret. If a ...
str_to_credentials(s) yields (key, secret) if the given string is a valid representation of a set of credentials. Valid representations include '<key>:<secret>' and '<key>\n<secret>'. All initial and trailing whitespace is always stripped from both key and scret. If a newline appears in the string, th...
Below is the the instruction that describes the task: ### Input: str_to_credentials(s) yields (key, secret) if the given string is a valid representation of a set of credentials. Valid representations include '<key>:<secret>' and '<key>\n<secret>'. All initial and trailing whitespace is always stripped ...
def __resource_descriptor(self, resource_path, methods): """Describes a resource. Args: resource_path: string, the path of the resource (e.g., 'entries.items') methods: list of tuples of type (endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods that serve this resourc...
Describes a resource. Args: resource_path: string, the path of the resource (e.g., 'entries.items') methods: list of tuples of type (endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods that serve this resource. Returns: Dictionary describing the resource.
Below is the the instruction that describes the task: ### Input: Describes a resource. Args: resource_path: string, the path of the resource (e.g., 'entries.items') methods: list of tuples of type (endpoints.Service, protorpc.remote._RemoteMethodInfo), the methods that serve this re...
def _getMethodsVoc(self): """Return the registered methods as DisplayList """ methods = api.search({ "portal_type": "Method", "is_active": True }, "bika_setup_catalog") items = map(lambda m: (api.get_uid(m), api.get_title(m)), methods) items.sort(...
Return the registered methods as DisplayList
Below is the the instruction that describes the task: ### Input: Return the registered methods as DisplayList ### Response: def _getMethodsVoc(self): """Return the registered methods as DisplayList """ methods = api.search({ "portal_type": "Method", "is_active": True...
def get_name_DID_record(self, did): """ Given a DID for a name, return the name record. Return {'record': ...} on success Return {'error': ...} on error """ try: did_info = parse_DID(did) assert did_info['name_type'] == 'name' except Except...
Given a DID for a name, return the name record. Return {'record': ...} on success Return {'error': ...} on error
Below is the the instruction that describes the task: ### Input: Given a DID for a name, return the name record. Return {'record': ...} on success Return {'error': ...} on error ### Response: def get_name_DID_record(self, did): """ Given a DID for a name, return the name record. ...
def write_to_file(self, destination_path): """ Writes the metadata json or xml to a file. :param destination_path: the file path the file format is inferred from the destination_path extension. :type destination_path: str :return: the written metadata :rtype: str...
Writes the metadata json or xml to a file. :param destination_path: the file path the file format is inferred from the destination_path extension. :type destination_path: str :return: the written metadata :rtype: str
Below is the the instruction that describes the task: ### Input: Writes the metadata json or xml to a file. :param destination_path: the file path the file format is inferred from the destination_path extension. :type destination_path: str :return: the written metadata :rtyp...
def _convert_point(self, metric, ts, point, sd_point): """Convert an OC metric point to a SD point.""" if (metric.descriptor.type == metric_descriptor.MetricDescriptorType .CUMULATIVE_DISTRIBUTION): sd_dist_val = sd_point.value.distribution_value sd_dist_val.coun...
Convert an OC metric point to a SD point.
Below is the the instruction that describes the task: ### Input: Convert an OC metric point to a SD point. ### Response: def _convert_point(self, metric, ts, point, sd_point): """Convert an OC metric point to a SD point.""" if (metric.descriptor.type == metric_descriptor.MetricDescriptorType ...
def set_forbidden_types(self, types): """Set all forbidden type values :param typees: a list with forbidden type values :type typees: list :returns: None :rtype: None :raises: None """ if self._forbidden_types == types: return self._fo...
Set all forbidden type values :param typees: a list with forbidden type values :type typees: list :returns: None :rtype: None :raises: None
Below is the the instruction that describes the task: ### Input: Set all forbidden type values :param typees: a list with forbidden type values :type typees: list :returns: None :rtype: None :raises: None ### Response: def set_forbidden_types(self, types): """Set al...
def tmp_file(suffix=u"", root=None): """ Return a (handler, path) tuple for a temporary file with given suffix created by ``tempfile``. :param string suffix: the suffix (e.g., the extension) of the file :param string root: path to the root temporary directory; if ``None``, t...
Return a (handler, path) tuple for a temporary file with given suffix created by ``tempfile``. :param string suffix: the suffix (e.g., the extension) of the file :param string root: path to the root temporary directory; if ``None``, the default temporary directory ...
Below is the the instruction that describes the task: ### Input: Return a (handler, path) tuple for a temporary file with given suffix created by ``tempfile``. :param string suffix: the suffix (e.g., the extension) of the file :param string root: path to the root temporary directory; ...
def constraints(self): """ Unique list of constraints among all populations in set. """ cs = [] for pop in self.poplist: cs += [c for c in pop.constraints] return list(set(cs))
Unique list of constraints among all populations in set.
Below is the the instruction that describes the task: ### Input: Unique list of constraints among all populations in set. ### Response: def constraints(self): """ Unique list of constraints among all populations in set. """ cs = [] for pop in self.poplist: cs += ...
def warp_pointer(self, x, y, src_window = X.NONE, src_x = 0, src_y = 0, src_width = 0, src_height = 0, onerror = None): """Move the pointer relative its current position by the offsets (x, y). However, if src_window is a window the pointer is only moved if the specified rect...
Move the pointer relative its current position by the offsets (x, y). However, if src_window is a window the pointer is only moved if the specified rectangle in src_window contains it. If src_width is 0 it will be replaced with the width of src_window - src_x. src_height is treated in a ...
Below is the the instruction that describes the task: ### Input: Move the pointer relative its current position by the offsets (x, y). However, if src_window is a window the pointer is only moved if the specified rectangle in src_window contains it. If src_width is 0 it will be replaced with...
def add(self, pattern, function, method=None, type_cast=None): """Function for registering a path pattern. Args: pattern (str): Regex pattern to match a certain path. function (function): Function to associate with this path. method (str, optional): Usually used to d...
Function for registering a path pattern. Args: pattern (str): Regex pattern to match a certain path. function (function): Function to associate with this path. method (str, optional): Usually used to define one of GET, POST, PUT, DELETE. You may use whatever ...
Below is the the instruction that describes the task: ### Input: Function for registering a path pattern. Args: pattern (str): Regex pattern to match a certain path. function (function): Function to associate with this path. method (str, optional): Usually used to define...
def change_id(self, new_id): """Change the id of this content.""" self._load_raw_content() self._id = new_id self.get_filename(renew=True) self.get_filepath(renew=True) return
Change the id of this content.
Below is the the instruction that describes the task: ### Input: Change the id of this content. ### Response: def change_id(self, new_id): """Change the id of this content.""" self._load_raw_content() self._id = new_id self.get_filename(renew=True) self.get_filepath(renew=Tr...
def main(): """Main function for the deprecated 'sl' command.""" print("ERROR: Use the 'slcli' command instead.", file=sys.stderr) print("> slcli %s" % ' '.join(sys.argv[1:]), file=sys.stderr) exit(-1)
Main function for the deprecated 'sl' command.
Below is the the instruction that describes the task: ### Input: Main function for the deprecated 'sl' command. ### Response: def main(): """Main function for the deprecated 'sl' command.""" print("ERROR: Use the 'slcli' command instead.", file=sys.stderr) print("> slcli %s" % ' '.join(sys.argv[1:]), f...
def build_parser(): """ _build_parser_ Set up CLI parser options, parse the CLI options an return the parsed results """ parser = argparse.ArgumentParser( description='dockerstache templating util' ) parser.add_argument( '--output', '-o', help='Working directory...
_build_parser_ Set up CLI parser options, parse the CLI options an return the parsed results
Below is the the instruction that describes the task: ### Input: _build_parser_ Set up CLI parser options, parse the CLI options an return the parsed results ### Response: def build_parser(): """ _build_parser_ Set up CLI parser options, parse the CLI options an return the parsed results ...
def render(self, name, value, attrs=None, renderer=None): """ Render the placeholder field. """ other_instance_languages = None if value and value != "-DUMMY-": if get_parent_language_code(self.parent_object): # Parent is a multilingual object, provide...
Render the placeholder field.
Below is the the instruction that describes the task: ### Input: Render the placeholder field. ### Response: def render(self, name, value, attrs=None, renderer=None): """ Render the placeholder field. """ other_instance_languages = None if value and value != "-DUMMY-": ...
def qsnorm(p): """ rational approximation for x where q(x)=d, q being the cumulative normal distribution function. taken from Abramowitz & Stegun p. 933 |error(x)| < 4.5*10**-4 """ d = p if d < 0. or d > 1.: print('d not in (1,1) ') sys.exit() x = 0. if (d - 0.5) > 0:...
rational approximation for x where q(x)=d, q being the cumulative normal distribution function. taken from Abramowitz & Stegun p. 933 |error(x)| < 4.5*10**-4
Below is the the instruction that describes the task: ### Input: rational approximation for x where q(x)=d, q being the cumulative normal distribution function. taken from Abramowitz & Stegun p. 933 |error(x)| < 4.5*10**-4 ### Response: def qsnorm(p): """ rational approximation for x where q(x)=d, ...
def get_datastore_files(service_instance, directory, datastores, container_object, browser_spec): ''' Get the files with a given browser specification from the datastore. service_instance The Service Instance Object from which to obtain datastores. directory The name of the directory w...
Get the files with a given browser specification from the datastore. service_instance The Service Instance Object from which to obtain datastores. directory The name of the directory where we would like to search datastores Name of the datastores container_object The ...
Below is the the instruction that describes the task: ### Input: Get the files with a given browser specification from the datastore. service_instance The Service Instance Object from which to obtain datastores. directory The name of the directory where we would like to search datasto...
def _stringifyResultRecords(self, struct): ''' The Partner WSDL defines result element not defined in the "SObject" section of the Partner WSDL as <any/> elements, which get unmarshalled by suds into single-element lists. We prefer that they are strings, so we'll convert structures like [(records...
The Partner WSDL defines result element not defined in the "SObject" section of the Partner WSDL as <any/> elements, which get unmarshalled by suds into single-element lists. We prefer that they are strings, so we'll convert structures like [(records){ type = "Contact" Id = "003000000000000000" ...
Below is the the instruction that describes the task: ### Input: The Partner WSDL defines result element not defined in the "SObject" section of the Partner WSDL as <any/> elements, which get unmarshalled by suds into single-element lists. We prefer that they are strings, so we'll convert structures l...
def dict_snake_to_camel_case(snake_dict, convert_keys=True, convert_subkeys=False): """ Recursively convert a snake_cased dict into a camelCased dict :param snake_dict: Dictionary to convert :param convert_keys: Whether the key should be converted :param convert_subkeys: Whether to also convert the...
Recursively convert a snake_cased dict into a camelCased dict :param snake_dict: Dictionary to convert :param convert_keys: Whether the key should be converted :param convert_subkeys: Whether to also convert the subkeys, in case they are named properties of the dict :return:
Below is the the instruction that describes the task: ### Input: Recursively convert a snake_cased dict into a camelCased dict :param snake_dict: Dictionary to convert :param convert_keys: Whether the key should be converted :param convert_subkeys: Whether to also convert the subkeys, in case they are ...
def _indent(string, count): '''indent `string` by `count` * INDENT''' indent = _INDENT * count ret = indent + string.replace('\n', '\n' + indent) return ret.rstrip()
indent `string` by `count` * INDENT
Below is the the instruction that describes the task: ### Input: indent `string` by `count` * INDENT ### Response: def _indent(string, count): '''indent `string` by `count` * INDENT''' indent = _INDENT * count ret = indent + string.replace('\n', '\n' + indent) return ret.rstrip()
def should_run(keywords, post_processor): """ Check if the postprocessor should run for the current hazard and exposure :param keywords: impact layer keywords :type keywords: dict :param post_processor: the post processor instance to check :type post_processor: dict :returns: Tuple with True...
Check if the postprocessor should run for the current hazard and exposure :param keywords: impact layer keywords :type keywords: dict :param post_processor: the post processor instance to check :type post_processor: dict :returns: Tuple with True if success, else False with an error message. :rt...
Below is the the instruction that describes the task: ### Input: Check if the postprocessor should run for the current hazard and exposure :param keywords: impact layer keywords :type keywords: dict :param post_processor: the post processor instance to check :type post_processor: dict :returns: ...
def compute_cusum_ts(self, ts): """ Compute the Cumulative Sum at each point 't' of the time series. """ mean = np.mean(ts) cusums = np.zeros(len(ts)) cusum[0] = (ts[0] - mean) for i in np.arange(1, len(ts)): cusums[i] = cusums[i - 1] + (ts[i] - mean) assert(...
Compute the Cumulative Sum at each point 't' of the time series.
Below is the the instruction that describes the task: ### Input: Compute the Cumulative Sum at each point 't' of the time series. ### Response: def compute_cusum_ts(self, ts): """ Compute the Cumulative Sum at each point 't' of the time series. """ mean = np.mean(ts) cusums = np.zeros(len(t...
def set_auth_request(self, interface_id, address=None): """ Set the authentication request field for the specified engine. """ self.interface.set_auth_request(interface_id, address) self._engine.update()
Set the authentication request field for the specified engine.
Below is the the instruction that describes the task: ### Input: Set the authentication request field for the specified engine. ### Response: def set_auth_request(self, interface_id, address=None): """ Set the authentication request field for the specified engine. "...
def setReferenceVoltage(self, caldb, calv): """See :meth:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel.setReferenceVoltage>`""" self.caldb = caldb self.calv = calv for test in self._tests: test.setReferenceVoltage(caldb, calv)
See :meth:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel.setReferenceVoltage>`
Below is the the instruction that describes the task: ### Input: See :meth:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel.setReferenceVoltage>` ### Response: def setReferenceVoltage(self, caldb, calv): """See :meth:`StimulusModel<sparkle.stim.stimulus_model.StimulusModel.setReferenceVoltage>`""" ...
def decode_tag(stream): """Decode a tag value from a serialized stream. :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded tag :rtype: bytes """ (reserved, tag) = unpack_value(">cc", stream) if reserved != b"\x00": raise DeserializationError("Invalid t...
Decode a tag value from a serialized stream. :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded tag :rtype: bytes
Below is the the instruction that describes the task: ### Input: Decode a tag value from a serialized stream. :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded tag :rtype: bytes ### Response: def decode_tag(stream): """Decode a tag value from a serialized stream. ...
def gauss_fit(X, Y): """ Fit the function to a gaussian. Parameters ---------- X: 1d array X values Y: 1d array Y values Returns ------- (The return from scipy.optimize.curve_fit) popt : array Optimal values for the parameters pcov : 2d array ...
Fit the function to a gaussian. Parameters ---------- X: 1d array X values Y: 1d array Y values Returns ------- (The return from scipy.optimize.curve_fit) popt : array Optimal values for the parameters pcov : 2d array The estimated covariance of popt...
Below is the the instruction that describes the task: ### Input: Fit the function to a gaussian. Parameters ---------- X: 1d array X values Y: 1d array Y values Returns ------- (The return from scipy.optimize.curve_fit) popt : array Optimal values for the pa...
def setOffset(self, value): """ Sets the offset of the L{WriteData} stream object in wich the data is written. @type value: int @param value: Integer value that represent the offset we want to start writing in the L{WriteData} stream. @raise WrongOffsetValue...
Sets the offset of the L{WriteData} stream object in wich the data is written. @type value: int @param value: Integer value that represent the offset we want to start writing in the L{WriteData} stream. @raise WrongOffsetValueException: The value is beyond the total length ...
Below is the the instruction that describes the task: ### Input: Sets the offset of the L{WriteData} stream object in wich the data is written. @type value: int @param value: Integer value that represent the offset we want to start writing in the L{WriteData} stream. @r...
def to_datetime(self, column): ''' This function converts epoch timestamps to datetimes. :param column: column to convert from current state -> datetime ''' if column in self: if self[column].dtype in NUMPY_NUMERICAL: self[column] = pd.to_datetime(sel...
This function converts epoch timestamps to datetimes. :param column: column to convert from current state -> datetime
Below is the the instruction that describes the task: ### Input: This function converts epoch timestamps to datetimes. :param column: column to convert from current state -> datetime ### Response: def to_datetime(self, column): ''' This function converts epoch timestamps to datetimes. ...
def insert(self, name, entry_type, filename): '''Insert an entry into the Zeal database. Args: name: A string representing the name of the entry. entry_type: A string representing the entry type. filename: A string representing the filename of the documentation ...
Insert an entry into the Zeal database. Args: name: A string representing the name of the entry. entry_type: A string representing the entry type. filename: A string representing the filename of the documentation for the entry. Raises: Ru...
Below is the the instruction that describes the task: ### Input: Insert an entry into the Zeal database. Args: name: A string representing the name of the entry. entry_type: A string representing the entry type. filename: A string representing the filename of the documen...
def check_cmms_gender(self, ind_object): """ Check if the phenotype is correct. Args: ind_object : An Individuals object Yields: bool : True if phenotype status is correct False otherwise """ ind_id = ind_obje...
Check if the phenotype is correct. Args: ind_object : An Individuals object Yields: bool : True if phenotype status is correct False otherwise
Below is the the instruction that describes the task: ### Input: Check if the phenotype is correct. Args: ind_object : An Individuals object Yields: bool : True if phenotype status is correct False otherwise ### Response: def check_cmms...
def uclust_cluster_from_sorted_fasta_filepath( fasta_filepath, uc_save_filepath=None, percent_ID=0.97, max_accepts=1, max_rejects=8, stepwords=8, word_length=8, optimal=False, exact=False, suppress_sort=False, enable_rev_strand_matc...
Returns clustered uclust file from sorted fasta
Below is the the instruction that describes the task: ### Input: Returns clustered uclust file from sorted fasta ### Response: def uclust_cluster_from_sorted_fasta_filepath( fasta_filepath, uc_save_filepath=None, percent_ID=0.97, max_accepts=1, max_rejects=8, stepwor...
def _consume_blanklines(self): """ Consume blank lines that are between records - For warcs, there are usually 2 - For arcs, may be 1 or 0 - For block gzipped files, these are at end of each gzip envelope and are included in record length which is the full gzip envelope ...
Consume blank lines that are between records - For warcs, there are usually 2 - For arcs, may be 1 or 0 - For block gzipped files, these are at end of each gzip envelope and are included in record length which is the full gzip envelope - For uncompressed, they are between recor...
Below is the the instruction that describes the task: ### Input: Consume blank lines that are between records - For warcs, there are usually 2 - For arcs, may be 1 or 0 - For block gzipped files, these are at end of each gzip envelope and are included in record length which is the ...
def values(self): """ On Python 2.7+: D.values() -> a set-like object providing a view on D's values On Python 2.6: D.values() -> an iterator over D's values """ if ver == (2, 7): return self.viewvalues() elif ver == (2, 6): ...
On Python 2.7+: D.values() -> a set-like object providing a view on D's values On Python 2.6: D.values() -> an iterator over D's values
Below is the the instruction that describes the task: ### Input: On Python 2.7+: D.values() -> a set-like object providing a view on D's values On Python 2.6: D.values() -> an iterator over D's values ### Response: def values(self): """ On Python 2.7+: D....
def read_plain_int64(file_obj, count): """Read `count` 64-bit ints using the plain encoding.""" return struct.unpack("<{}q".format(count).encode("utf-8"), file_obj.read(8 * count))
Read `count` 64-bit ints using the plain encoding.
Below is the the instruction that describes the task: ### Input: Read `count` 64-bit ints using the plain encoding. ### Response: def read_plain_int64(file_obj, count): """Read `count` 64-bit ints using the plain encoding.""" return struct.unpack("<{}q".format(count).encode("utf-8"), file_obj.read(8 * coun...
def choose_tag(self: object, tokens: List[str], index: int, history: List[str]): """ Looks up token in ``lemmas`` dict and returns the corresponding value as lemma. :rtype: str :type tokens: list :param tokens: List of tokens to be lemmatized :type index: int ...
Looks up token in ``lemmas`` dict and returns the corresponding value as lemma. :rtype: str :type tokens: list :param tokens: List of tokens to be lemmatized :type index: int :param index: Int with current token :type history: list :param history: List wit...
Below is the the instruction that describes the task: ### Input: Looks up token in ``lemmas`` dict and returns the corresponding value as lemma. :rtype: str :type tokens: list :param tokens: List of tokens to be lemmatized :type index: int :param index: Int with curre...
def ucas_download_single(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''video page''' html = get_content(url) # resourceID is UUID resourceID = re.findall( r'resourceID":"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})', html)[0] assert resourceID != '', 'Canno...
video page
Below is the the instruction that describes the task: ### Input: video page ### Response: def ucas_download_single(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''video page''' html = get_content(url) # resourceID is UUID resourceID = re.findall( r'resourceID":"([0-9a-f]{8}-[...
def dissimilarity_metric(self, a, b): """Return non-zero if references to this module are strange, and should be drawn extra-long. The value defines the length, in rank. This is also good for putting some vertical space between seperate subsystems. Returns an int bet...
Return non-zero if references to this module are strange, and should be drawn extra-long. The value defines the length, in rank. This is also good for putting some vertical space between seperate subsystems. Returns an int between 1 (default) and 4 (highly unrelated).
Below is the the instruction that describes the task: ### Input: Return non-zero if references to this module are strange, and should be drawn extra-long. The value defines the length, in rank. This is also good for putting some vertical space between seperate subsystems. ...
def add_output(self, address, value, unit='satoshi'): """ Add an output (a person who will receive funds via this tx). If no unit is specified, satoshi is implied. """ value_satoshi = self.from_unit_to_satoshi(value, unit) if self.verbose: print("Adding outpu...
Add an output (a person who will receive funds via this tx). If no unit is specified, satoshi is implied.
Below is the the instruction that describes the task: ### Input: Add an output (a person who will receive funds via this tx). If no unit is specified, satoshi is implied. ### Response: def add_output(self, address, value, unit='satoshi'): """ Add an output (a person who will receive funds v...
def push_focus(self, cli, buffer_name): """ Push buffer on the focus stack. """ assert isinstance(buffer_name, six.text_type) self.focus_stack.append(buffer_name)
Push buffer on the focus stack.
Below is the the instruction that describes the task: ### Input: Push buffer on the focus stack. ### Response: def push_focus(self, cli, buffer_name): """ Push buffer on the focus stack. """ assert isinstance(buffer_name, six.text_type) self.focus_stack.append(buffer_name)