code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def fetch_all(self, credentials, regions = [], partition_name = 'aws', targets = None): """ Fetch all the configuration supported by Scout2 for a given service :param credentials: F :param service: Name of the service :param regions: N...
Fetch all the configuration supported by Scout2 for a given service :param credentials: F :param service: Name of the service :param regions: Name of regions to fetch data from :param partition_name: AWS partition to connect to ...
Below is the the instruction that describes the task: ### Input: Fetch all the configuration supported by Scout2 for a given service :param credentials: F :param service: Name of the service :param regions: Name of regions to fetch data from ...
def multiply(self, other): """Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Chi: the scalar multiplication other * self as a Chi object. Raises: QiskitError: if other is not a valid scalar. """ ...
Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Chi: the scalar multiplication other * self as a Chi object. Raises: QiskitError: if other is not a valid scalar.
Below is the the instruction that describes the task: ### Input: Return the QuantumChannel self + other. Args: other (complex): a complex number. Returns: Chi: the scalar multiplication other * self as a Chi object. Raises: QiskitError: if other is not ...
def run(self, repo: str, branch: str, task: Task, git_repo: Repo, repo_path: Path): """ Starts up a VM, builds an docker image and gets it to the VM, runs the script over SSH, returns result. Stops the VM if ``keep_vm_running`` is not set. """ from fabric import api from fabr...
Starts up a VM, builds an docker image and gets it to the VM, runs the script over SSH, returns result. Stops the VM if ``keep_vm_running`` is not set.
Below is the the instruction that describes the task: ### Input: Starts up a VM, builds an docker image and gets it to the VM, runs the script over SSH, returns result. Stops the VM if ``keep_vm_running`` is not set. ### Response: def run(self, repo: str, branch: str, task: Task, git_repo: Repo, repo_p...
def find_python_files(dirname): """Yield all of the importable Python files in `dirname`, recursively. To be importable, the files have to be in a directory with a __init__.py, except for `dirname` itself, which isn't required to have one. The assumption is that `dirname` was specified directly, so th...
Yield all of the importable Python files in `dirname`, recursively. To be importable, the files have to be in a directory with a __init__.py, except for `dirname` itself, which isn't required to have one. The assumption is that `dirname` was specified directly, so the user knows best, but subdirectori...
Below is the the instruction that describes the task: ### Input: Yield all of the importable Python files in `dirname`, recursively. To be importable, the files have to be in a directory with a __init__.py, except for `dirname` itself, which isn't required to have one. The assumption is that `dirname`...
def bind(self): """Activate this Shader, making it the currently-bound program. Any Mesh.draw() calls after bind() will have their data processed by this Shader. To unbind, call Shader.unbind(). Example:: shader.bind() mesh.draw() shader.unbind() .. ...
Activate this Shader, making it the currently-bound program. Any Mesh.draw() calls after bind() will have their data processed by this Shader. To unbind, call Shader.unbind(). Example:: shader.bind() mesh.draw() shader.unbind() .. note:: Shader.bind() and Sh...
Below is the the instruction that describes the task: ### Input: Activate this Shader, making it the currently-bound program. Any Mesh.draw() calls after bind() will have their data processed by this Shader. To unbind, call Shader.unbind(). Example:: shader.bind() mesh.draw...
def collections(self): """List top-level collections of the client's database. Returns: Sequence[~.firestore_v1beta1.collection.CollectionReference]: iterator of subcollections of the current document. """ iterator = self._firestore_api.list_collection_ids( ...
List top-level collections of the client's database. Returns: Sequence[~.firestore_v1beta1.collection.CollectionReference]: iterator of subcollections of the current document.
Below is the the instruction that describes the task: ### Input: List top-level collections of the client's database. Returns: Sequence[~.firestore_v1beta1.collection.CollectionReference]: iterator of subcollections of the current document. ### Response: def collections(self): ...
def get_bounding_box(self): """ Returns the bounding box for this cell. Returns ------- out : Numpy array[2,2] or ``None`` Bounding box of this cell [[x_min, y_min], [x_max, y_max]], or ``None`` if the cell is empty. """ if len(self.elemen...
Returns the bounding box for this cell. Returns ------- out : Numpy array[2,2] or ``None`` Bounding box of this cell [[x_min, y_min], [x_max, y_max]], or ``None`` if the cell is empty.
Below is the the instruction that describes the task: ### Input: Returns the bounding box for this cell. Returns ------- out : Numpy array[2,2] or ``None`` Bounding box of this cell [[x_min, y_min], [x_max, y_max]], or ``None`` if the cell is empty. ### Response: de...
def y_axis_rotation(theta): """Generates a 3x3 rotation matrix for a rotation of angle theta about the y axis. Parameters ---------- theta : float amount to rotate, in radians Returns ------- :obj:`numpy.ndarray` of float A random...
Generates a 3x3 rotation matrix for a rotation of angle theta about the y axis. Parameters ---------- theta : float amount to rotate, in radians Returns ------- :obj:`numpy.ndarray` of float A random 3x3 rotation matrix.
Below is the the instruction that describes the task: ### Input: Generates a 3x3 rotation matrix for a rotation of angle theta about the y axis. Parameters ---------- theta : float amount to rotate, in radians Returns ------- :obj:`numpy.ndarray`...
def get(self, instance, acl): """Get an ACL by ID belonging to the instance specified by name. :param str instance: The name of the instance from which to fetch the ACL. :param str acl: The ID of the ACL to fetch. :returns: An :py:class:`Acl` object, or None if ACL does not exist. ...
Get an ACL by ID belonging to the instance specified by name. :param str instance: The name of the instance from which to fetch the ACL. :param str acl: The ID of the ACL to fetch. :returns: An :py:class:`Acl` object, or None if ACL does not exist. :rtype: :py:class:`Acl`
Below is the the instruction that describes the task: ### Input: Get an ACL by ID belonging to the instance specified by name. :param str instance: The name of the instance from which to fetch the ACL. :param str acl: The ID of the ACL to fetch. :returns: An :py:class:`Acl` object, or None ...
def encode_eternal_jwt_token(self, user, **custom_claims): """ This utility function encodes a jwt token that never expires .. note:: This should be used sparingly since the token could become a security concern if it is ever lost. If you use this method, you...
This utility function encodes a jwt token that never expires .. note:: This should be used sparingly since the token could become a security concern if it is ever lost. If you use this method, you should be sure that your application also implements a black...
Below is the the instruction that describes the task: ### Input: This utility function encodes a jwt token that never expires .. note:: This should be used sparingly since the token could become a security concern if it is ever lost. If you use this method, you should be...
def GetFeedItemIdsForCampaign(campaign_feed): """Gets the Feed Item Ids used by a campaign through a given Campaign Feed. Args: campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. Returns: A list of Feed Item IDs. """ feed_item_ids = set() try: lhs_operand = campaign_feed['...
Gets the Feed Item Ids used by a campaign through a given Campaign Feed. Args: campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. Returns: A list of Feed Item IDs.
Below is the the instruction that describes the task: ### Input: Gets the Feed Item Ids used by a campaign through a given Campaign Feed. Args: campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from. Returns: A list of Feed Item IDs. ### Response: def GetFeedItemIdsForCampaign(campaign...
def galactic2fk5(l, b): """ Convert galactic l/b to fk5 ra/dec Parameters ---------- l, b : float Galactic coordinates in radians. Returns ------- ra, dec : float FK5 ecliptic coordinates in radians. """ a = SkyCoord(l, b, unit=(u.radian, u.radian), frame='galac...
Convert galactic l/b to fk5 ra/dec Parameters ---------- l, b : float Galactic coordinates in radians. Returns ------- ra, dec : float FK5 ecliptic coordinates in radians.
Below is the the instruction that describes the task: ### Input: Convert galactic l/b to fk5 ra/dec Parameters ---------- l, b : float Galactic coordinates in radians. Returns ------- ra, dec : float FK5 ecliptic coordinates in radians. ### Response: def galactic2fk5(l, b)...
def create(cls, community, record, user=None, expires_at=None, notify=True): """Create a record inclusion request to a community. :param community: Community object. :param record: Record API object. :param expires_at: Time after which the request expires and shouldn't ...
Create a record inclusion request to a community. :param community: Community object. :param record: Record API object. :param expires_at: Time after which the request expires and shouldn't be resolved anymore.
Below is the the instruction that describes the task: ### Input: Create a record inclusion request to a community. :param community: Community object. :param record: Record API object. :param expires_at: Time after which the request expires and shouldn't be resolved anymore. ###...
def plot_file(self, name: str=None, time: int=None) -> None: """ Plot specific time for provided datafile. If no time provided, will plot middle. :param: savefile name :param: time/data column """ if not time: time = int(len(self.times) / 2) i...
Plot specific time for provided datafile. If no time provided, will plot middle. :param: savefile name :param: time/data column
Below is the the instruction that describes the task: ### Input: Plot specific time for provided datafile. If no time provided, will plot middle. :param: savefile name :param: time/data column ### Response: def plot_file(self, name: str=None, time: int=None) -> None: """ Pl...
def merge_dicts(*args): r""" add / concatenate / union / join / merge / combine dictionaries Copies the first dictionary given and then repeatedly calls update using the rest of the dicts given in args. Duplicate keys will receive the last value specified the list of dictionaries. Returns: ...
r""" add / concatenate / union / join / merge / combine dictionaries Copies the first dictionary given and then repeatedly calls update using the rest of the dicts given in args. Duplicate keys will receive the last value specified the list of dictionaries. Returns: dict: mergedict_ C...
Below is the the instruction that describes the task: ### Input: r""" add / concatenate / union / join / merge / combine dictionaries Copies the first dictionary given and then repeatedly calls update using the rest of the dicts given in args. Duplicate keys will receive the last value specified th...
def set_color_hsv(self, hue, saturation, value): """Turn the bulb on with the given values as HSV.""" try: data = "action=on&color={};{};{}".format(hue, saturation, value) request = requests.post( '{}/{}/{}'.format(self.resource, URI, self._mac), d...
Turn the bulb on with the given values as HSV.
Below is the the instruction that describes the task: ### Input: Turn the bulb on with the given values as HSV. ### Response: def set_color_hsv(self, hue, saturation, value): """Turn the bulb on with the given values as HSV.""" try: data = "action=on&color={};{};{}".format(hue, saturati...
def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height): """Check if constrains are satisfied""" if (xmax - xmin) * (ymax - ymin) < 2: return False # only 1 pixel x1 = float(xmin) / width y1 = float(ymin) / height x2 = float(xmax) / width ...
Check if constrains are satisfied
Below is the the instruction that describes the task: ### Input: Check if constrains are satisfied ### Response: def _check_satisfy_constraints(self, label, xmin, ymin, xmax, ymax, width, height): """Check if constrains are satisfied""" if (xmax - xmin) * (ymax - ymin) < 2: return False...
def rectwv_coeff_add_longslit_model(rectwv_coeff, geometry, debugplot=0): """Compute longslit_model coefficients for RectWaveCoeff object. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for a particular CSU configuration...
Compute longslit_model coefficients for RectWaveCoeff object. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for a particular CSU configuration corresponding to a longslit observation. geometry : TBD debugplo...
Below is the the instruction that describes the task: ### Input: Compute longslit_model coefficients for RectWaveCoeff object. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for a particular CSU configuration correspondi...
def _make_safe_id(self, id): """Returns a modified id that has been made safe for SBML. Replaces or deletes the ones that aren't allowed. """ substitutions = { '-': '_DASH_', '/': '_FSLASH_', '\\': '_BSLASH_', '(': '_LPAREN_', ...
Returns a modified id that has been made safe for SBML. Replaces or deletes the ones that aren't allowed.
Below is the the instruction that describes the task: ### Input: Returns a modified id that has been made safe for SBML. Replaces or deletes the ones that aren't allowed. ### Response: def _make_safe_id(self, id): """Returns a modified id that has been made safe for SBML. Replaces or dele...
def clock(self, interval, basis): """Return a NodeInput tuple for triggering an event every interval. We request each distinct type of clock at most once and combine it with our latch stream each time it is requested. Args: interval (int): The interval (in seconds) at which...
Return a NodeInput tuple for triggering an event every interval. We request each distinct type of clock at most once and combine it with our latch stream each time it is requested. Args: interval (int): The interval (in seconds) at which this input should trigger.
Below is the the instruction that describes the task: ### Input: Return a NodeInput tuple for triggering an event every interval. We request each distinct type of clock at most once and combine it with our latch stream each time it is requested. Args: interval (int): The interv...
async def execute(self, keys=[], args=[], client=None): "Execute the script, passing any required ``args``" if client is None: client = self.registered_client args = tuple(keys) + tuple(args) # make sure the Redis server knows about the script if isinstance(client, Ba...
Execute the script, passing any required ``args``
Below is the the instruction that describes the task: ### Input: Execute the script, passing any required ``args`` ### Response: async def execute(self, keys=[], args=[], client=None): "Execute the script, passing any required ``args``" if client is None: client = self.registered_client...
def dK_dr_via_X(self, X, X2): """ compute the derivative of K wrt X going through X """ #a convenience function, so we can cache dK_dr return self.dK_dr(self._scaled_dist(X, X2))
compute the derivative of K wrt X going through X
Below is the the instruction that describes the task: ### Input: compute the derivative of K wrt X going through X ### Response: def dK_dr_via_X(self, X, X2): """ compute the derivative of K wrt X going through X """ #a convenience function, so we can cache dK_dr return self...
def rep(obj, *attrs, **kwargs): """Create a repr of a property based class quickly Args: obj -- instance of class *attrs -- list of attrs to add to the representation **kwargs -- Extra arguments to add that are not captured as attributes Returns: A string representing the cla...
Create a repr of a property based class quickly Args: obj -- instance of class *attrs -- list of attrs to add to the representation **kwargs -- Extra arguments to add that are not captured as attributes Returns: A string representing the class
Below is the the instruction that describes the task: ### Input: Create a repr of a property based class quickly Args: obj -- instance of class *attrs -- list of attrs to add to the representation **kwargs -- Extra arguments to add that are not captured as attributes Returns:...
def plot_normal(x=None, mean_x=None,std_x=None,color='red',linewidth=2,alpha=1,bins=20,xlim=False,plot_mean=True,plot_std=False,plot_2std=True,figure=None,annotate=True,histogram=True): """ plot a fit of a normal distribution to the data in x. """ import pylab if figure is None: figure=pylab...
plot a fit of a normal distribution to the data in x.
Below is the the instruction that describes the task: ### Input: plot a fit of a normal distribution to the data in x. ### Response: def plot_normal(x=None, mean_x=None,std_x=None,color='red',linewidth=2,alpha=1,bins=20,xlim=False,plot_mean=True,plot_std=False,plot_2std=True,figure=None,annotate=True,histogram=Tru...
def p_restore(p): """ statement : RESTORE | RESTORE ID | RESTORE NUMBER """ if len(p) == 2: id_ = '__DATA__{0}'.format(len(gl.DATAS)) else: id_ = p[2] lbl = check_and_make_label(id_, p.lineno(1)) p[0] = make_sentence('RESTORE', lbl)
statement : RESTORE | RESTORE ID | RESTORE NUMBER
Below is the the instruction that describes the task: ### Input: statement : RESTORE | RESTORE ID | RESTORE NUMBER ### Response: def p_restore(p): """ statement : RESTORE | RESTORE ID | RESTORE NUMBER """ if len(p) == 2: id...
def _q_to_dcm(self, q): """ Create DCM from q :param q: array q which represents a quaternion [w, x, y, z] :returns: 3x3 dcm array """ assert(len(q) == 4) assert(np.allclose(QuaternionBase.norm_array(q), 1)) dcm = np.zeros([3, 3]) a = q[0] ...
Create DCM from q :param q: array q which represents a quaternion [w, x, y, z] :returns: 3x3 dcm array
Below is the the instruction that describes the task: ### Input: Create DCM from q :param q: array q which represents a quaternion [w, x, y, z] :returns: 3x3 dcm array ### Response: def _q_to_dcm(self, q): """ Create DCM from q :param q: array q which represents a quaternion...
def create_main_target (self, name): """ Returns a 'MainTarget' class instance corresponding to the 'name'. """ assert isinstance(name, basestring) if not self.built_main_targets_: self.build_main_targets () return self.main_targets_.get (name, None)
Returns a 'MainTarget' class instance corresponding to the 'name'.
Below is the the instruction that describes the task: ### Input: Returns a 'MainTarget' class instance corresponding to the 'name'. ### Response: def create_main_target (self, name): """ Returns a 'MainTarget' class instance corresponding to the 'name'. """ assert isinstance(name, basestrin...
def _search_for_files(parts): """ Given a list of parts, return all of the nested file parts. """ file_parts = [] for part in parts: if isinstance(part, list): file_parts.extend(_search_for_files(part)) elif isinstance(part, FileToken): file_parts.append(part) ret...
Given a list of parts, return all of the nested file parts.
Below is the the instruction that describes the task: ### Input: Given a list of parts, return all of the nested file parts. ### Response: def _search_for_files(parts): """ Given a list of parts, return all of the nested file parts. """ file_parts = [] for part in parts: if isinstance(part, lis...
def loadImageData(filename, spacing=()): """Read and return a ``vtkImageData`` object from file.""" if not os.path.isfile(filename): colors.printc("~noentry File not found:", filename, c=1) return None if ".tif" in filename.lower(): reader = vtk.vtkTIFFReader() elif ".slc" in fi...
Read and return a ``vtkImageData`` object from file.
Below is the the instruction that describes the task: ### Input: Read and return a ``vtkImageData`` object from file. ### Response: def loadImageData(filename, spacing=()): """Read and return a ``vtkImageData`` object from file.""" if not os.path.isfile(filename): colors.printc("~noentry File not f...
def process_block(self, block): """ process block from the block_parser and return a list of processed lines """ ret = [] output = None input_lines = None lineno = self.IP.execution_count input_prompt = self.promptin % lineno output_prompt = self....
process block from the block_parser and return a list of processed lines
Below is the the instruction that describes the task: ### Input: process block from the block_parser and return a list of processed lines ### Response: def process_block(self, block): """ process block from the block_parser and return a list of processed lines """ ret = [] o...
def walk_preorder(self): """Depth-first preorder walk over the cursor and its descendants. Yields cursors. """ yield self for child in self.get_children(): for descendant in child.walk_preorder(): yield descendant
Depth-first preorder walk over the cursor and its descendants. Yields cursors.
Below is the the instruction that describes the task: ### Input: Depth-first preorder walk over the cursor and its descendants. Yields cursors. ### Response: def walk_preorder(self): """Depth-first preorder walk over the cursor and its descendants. Yields cursors. """ yiel...
def get_output(self, transaction_hash, output_index): """ Gets an output and information about its asset ID and asset quantity. :param bytes transaction_hash: The hash of the transaction containing the output. :param int output_index: The index of the output. :return: An object ...
Gets an output and information about its asset ID and asset quantity. :param bytes transaction_hash: The hash of the transaction containing the output. :param int output_index: The index of the output. :return: An object containing the output as well as its asset ID and asset quantity. ...
Below is the the instruction that describes the task: ### Input: Gets an output and information about its asset ID and asset quantity. :param bytes transaction_hash: The hash of the transaction containing the output. :param int output_index: The index of the output. :return: An object conta...
def __print_command_help(self, session, namespace, cmd_name): """ Prints the documentation of the given command :param session: Session handler :param namespace: Name space of the command :param cmd_name: Name of the command """ # Extract documentation ar...
Prints the documentation of the given command :param session: Session handler :param namespace: Name space of the command :param cmd_name: Name of the command
Below is the the instruction that describes the task: ### Input: Prints the documentation of the given command :param session: Session handler :param namespace: Name space of the command :param cmd_name: Name of the command ### Response: def __print_command_help(self, session, namespace, c...
def add(self, *args, **kwargs): """See ReplayBuffer.store_effect""" idx = self._next_idx super().add(*args, **kwargs) self._it_sum[idx] = self._max_priority ** self._alpha self._it_min[idx] = self._max_priority ** self._alpha
See ReplayBuffer.store_effect
Below is the the instruction that describes the task: ### Input: See ReplayBuffer.store_effect ### Response: def add(self, *args, **kwargs): """See ReplayBuffer.store_effect""" idx = self._next_idx super().add(*args, **kwargs) self._it_sum[idx] = self._max_priority ** self._alpha ...
def _get_choices(self, gandi): """ Internal method to get choices list """ packages = super(CertificatePackageType, self)._get_choices(gandi) return list(set([pack.split('_')[1] for pack in packages]))
Internal method to get choices list
Below is the the instruction that describes the task: ### Input: Internal method to get choices list ### Response: def _get_choices(self, gandi): """ Internal method to get choices list """ packages = super(CertificatePackageType, self)._get_choices(gandi) return list(set([pack.split('_')[1...
def is_username_valid(username): """ Check if a valid username. valid: oracle bill-gates steve.jobs micro_soft not valid Bill Gates - no space allowed me@yo.com - @ is not a valid character :param username: string :return: """ pattern = re....
Check if a valid username. valid: oracle bill-gates steve.jobs micro_soft not valid Bill Gates - no space allowed me@yo.com - @ is not a valid character :param username: string :return:
Below is the the instruction that describes the task: ### Input: Check if a valid username. valid: oracle bill-gates steve.jobs micro_soft not valid Bill Gates - no space allowed me@yo.com - @ is not a valid character :param username: string :return: #...
def get(self): """ Get a JSON-ready representation of this HtmlContent. :returns: This HtmlContent, ready for use in a request body. :rtype: dict """ content = {} if self.mime_type is not None: content["type"] = self.mime_type if self.content...
Get a JSON-ready representation of this HtmlContent. :returns: This HtmlContent, ready for use in a request body. :rtype: dict
Below is the the instruction that describes the task: ### Input: Get a JSON-ready representation of this HtmlContent. :returns: This HtmlContent, ready for use in a request body. :rtype: dict ### Response: def get(self): """ Get a JSON-ready representation of this HtmlContent. ...
def stack_get(self, key): """Set a value in a task context stack """ task = Task.current_task() try: context = task._context_stack except AttributeError: return if key in context: return context[key][-1]
Set a value in a task context stack
Below is the the instruction that describes the task: ### Input: Set a value in a task context stack ### Response: def stack_get(self, key): """Set a value in a task context stack """ task = Task.current_task() try: context = task._context_stack except AttributeE...
def direct_to_template( request, template, extra_context=None, mimetype=None, **kwargs): """ Render a given template with any extra URL parameters in the context as ``{{ params }}``. """ if extra_context is None: extra_context = {} dictionary = {'params': kwargs} for key, val...
Render a given template with any extra URL parameters in the context as ``{{ params }}``.
Below is the the instruction that describes the task: ### Input: Render a given template with any extra URL parameters in the context as ``{{ params }}``. ### Response: def direct_to_template( request, template, extra_context=None, mimetype=None, **kwargs): """ Render a given template with any ...
async def query_handler(service, action_type, payload, props, **kwds): """ This action handler interprets the payload as a query to be executed by the api gateway service. """ # check that the action type indicates a query if action_type == query_action_type(): print('encountered...
This action handler interprets the payload as a query to be executed by the api gateway service.
Below is the the instruction that describes the task: ### Input: This action handler interprets the payload as a query to be executed by the api gateway service. ### Response: async def query_handler(service, action_type, payload, props, **kwds): """ This action handler interprets the payload a...
def inside(self, x, y): """ check, if field position is inside map :param x: x pos :param y: y pos :return: """ return 0 <= x < self.width and 0 <= y < self.height
check, if field position is inside map :param x: x pos :param y: y pos :return:
Below is the the instruction that describes the task: ### Input: check, if field position is inside map :param x: x pos :param y: y pos :return: ### Response: def inside(self, x, y): """ check, if field position is inside map :param x: x pos :param y: y pos ...
def get_additional_occurrences(self, start, end): """ Return persisted occurrences which are now in the period """ return [occ for _, occ in list(self.lookup.items()) if (occ.start < end and occ.end >= start and not occ.cancelled)]
Return persisted occurrences which are now in the period
Below is the the instruction that describes the task: ### Input: Return persisted occurrences which are now in the period ### Response: def get_additional_occurrences(self, start, end): """ Return persisted occurrences which are now in the period """ return [occ for _, occ in list(s...
def convert_l2normalization(node, **kwargs): """Map MXNet's L2Normalization operator attributes to onnx's LpNormalization operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) mode = attrs.get("mode", "instance") if mode != "channel": raise Attri...
Map MXNet's L2Normalization operator attributes to onnx's LpNormalization operator and return the created node.
Below is the the instruction that describes the task: ### Input: Map MXNet's L2Normalization operator attributes to onnx's LpNormalization operator and return the created node. ### Response: def convert_l2normalization(node, **kwargs): """Map MXNet's L2Normalization operator attributes to onnx's LpNormaliz...
def load(self, prof_name): """ Load the profile with the given name. :param str prof_name: Profile name. :rtype: ProfileStub :return: An stub to loaded profile. """ prof_dir = self.__profile_dir(prof_name) prof_ini_path = self.__profile_ini_path(prof_dir) if not os.path.exists(p...
Load the profile with the given name. :param str prof_name: Profile name. :rtype: ProfileStub :return: An stub to loaded profile.
Below is the the instruction that describes the task: ### Input: Load the profile with the given name. :param str prof_name: Profile name. :rtype: ProfileStub :return: An stub to loaded profile. ### Response: def load(self, prof_name): """ Load the profile with the given name. :p...
def get(self, request, pk=None): """ Handles GET requests. """ self.top_level_forum = get_object_or_404(Forum, pk=pk) if pk else None return super().get(request, pk)
Handles GET requests.
Below is the the instruction that describes the task: ### Input: Handles GET requests. ### Response: def get(self, request, pk=None): """ Handles GET requests. """ self.top_level_forum = get_object_or_404(Forum, pk=pk) if pk else None return super().get(request, pk)
def run_command(cmd, sudo=False): '''run_command uses subprocess to send a command to the terminal. :param cmd: the command to send, should be a list for subprocess :param error_message: the error message to give to user if fails, if none specified, will alert that command failed. :param sudopw: if ...
run_command uses subprocess to send a command to the terminal. :param cmd: the command to send, should be a list for subprocess :param error_message: the error message to give to user if fails, if none specified, will alert that command failed. :param sudopw: if specified (not None) command will be run ...
Below is the the instruction that describes the task: ### Input: run_command uses subprocess to send a command to the terminal. :param cmd: the command to send, should be a list for subprocess :param error_message: the error message to give to user if fails, if none specified, will alert that command fa...
def set_class_value(self, selector, classname): """Set the class of element matched by the given selector.""" return self.evaluate(""" (function () {{ var element = document.querySelector({0}); element.className = {1}; }})();""".format(repr(selector), repr...
Set the class of element matched by the given selector.
Below is the the instruction that describes the task: ### Input: Set the class of element matched by the given selector. ### Response: def set_class_value(self, selector, classname): """Set the class of element matched by the given selector.""" return self.evaluate(""" (function () {{ ...
def deleted(self, src, path): """Update the reference tree when a handled file is deleted.""" if self.parents[path] is not None: for parent in self.parents[path]: self.children[parent].remove(path) if not self.children[parent]: del self.chi...
Update the reference tree when a handled file is deleted.
Below is the the instruction that describes the task: ### Input: Update the reference tree when a handled file is deleted. ### Response: def deleted(self, src, path): """Update the reference tree when a handled file is deleted.""" if self.parents[path] is not None: for parent in self.pa...
def main(): """ main """ # BZ 1581651 - Override the ArgumentParser to disable argument abbreviations. parser = OverrideArgumentParser( description=u'APB tooling for ' u'assisting in building and packaging APBs.' ) parser.add_argument( '--debug', action='store_true',...
main
Below is the the instruction that describes the task: ### Input: main ### Response: def main(): """ main """ # BZ 1581651 - Override the ArgumentParser to disable argument abbreviations. parser = OverrideArgumentParser( description=u'APB tooling for ' u'assisting in building and packagi...
def engage(self, height): """ Move the magnet to a specific height, in mm from home position """ if height > MAX_ENGAGE_HEIGHT or height < 0: raise ValueError('Invalid engage height. Should be 0 to {}'.format( MAX_ENGAGE_HEIGHT)) self._driver.move(heig...
Move the magnet to a specific height, in mm from home position
Below is the the instruction that describes the task: ### Input: Move the magnet to a specific height, in mm from home position ### Response: def engage(self, height): """ Move the magnet to a specific height, in mm from home position """ if height > MAX_ENGAGE_HEIGHT or height < 0:...
def do_parse(self, arg, fullparse=False): """Parse the test results from the specified directory and load them under the name of 'module.executable ' that they were created with. E.g. parse classes.polya/ """ from os import path fullpath = path.abspath(path.expanduser(arg)) ...
Parse the test results from the specified directory and load them under the name of 'module.executable ' that they were created with. E.g. parse classes.polya/
Below is the the instruction that describes the task: ### Input: Parse the test results from the specified directory and load them under the name of 'module.executable ' that they were created with. E.g. parse classes.polya/ ### Response: def do_parse(self, arg, fullparse=False): """Parse the test ...
def dumps(self): """ Returns contents of config file as string OUT: out (type: str, hint: config content) """ out = "" for option in self.options: value = make_value(option.default_value) out += "%s = %s%s\n" % (option.name, value, (" # %s" % option.comment) if option.comment else "") return ou...
Returns contents of config file as string OUT: out (type: str, hint: config content)
Below is the the instruction that describes the task: ### Input: Returns contents of config file as string OUT: out (type: str, hint: config content) ### Response: def dumps(self): """ Returns contents of config file as string OUT: out (type: str, hint: config content) """ out = "" for option in self...
def decode(self, covertext): """Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``. """ if not isinstance(covertext, str): raise InvalidInputException('Input must be of type string.') insufficient = (len(covertext) < self._fixed_slice) if insufficient: ...
Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``.
Below is the the instruction that describes the task: ### Input: Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``. ### Response: def decode(self, covertext): """Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``. """ if not isinstance(covertext, str): ...
def byte_href_anchors_state_machine(self): ''' byte-based state machine extractor of anchor tags, so we can compute byte offsets for anchor texts and associate them with their href. Generates tuple(href_string, first_byte, byte_length, anchor_text) ''' ta...
byte-based state machine extractor of anchor tags, so we can compute byte offsets for anchor texts and associate them with their href. Generates tuple(href_string, first_byte, byte_length, anchor_text)
Below is the the instruction that describes the task: ### Input: byte-based state machine extractor of anchor tags, so we can compute byte offsets for anchor texts and associate them with their href. Generates tuple(href_string, first_byte, byte_length, anchor_text) ### Response: d...
def store_lines(self, key, content): '''like store_iter, but appends a newline to each chunk of content''' return self.store_iter( key, (data + '\n'.encode('utf-8') for data in content))
like store_iter, but appends a newline to each chunk of content
Below is the the instruction that describes the task: ### Input: like store_iter, but appends a newline to each chunk of content ### Response: def store_lines(self, key, content): '''like store_iter, but appends a newline to each chunk of content''' return self.store_iter( ...
def _example_number_anywhere_for_type(num_type): """Gets a valid number for the specified number type (it may belong to any country). Arguments: num_type -- The type of number that is needed. Returns a valid number for the specified type. Returns None when the metadata does not contain such inform...
Gets a valid number for the specified number type (it may belong to any country). Arguments: num_type -- The type of number that is needed. Returns a valid number for the specified type. Returns None when the metadata does not contain such information. This should only happen when no numbers of th...
Below is the the instruction that describes the task: ### Input: Gets a valid number for the specified number type (it may belong to any country). Arguments: num_type -- The type of number that is needed. Returns a valid number for the specified type. Returns None when the metadata does not contai...
def state(self, state): """Set state.""" self._state = state self._manager[ATTR_STATE] = state _LOGGER.info('state changed to %s', state)
Set state.
Below is the the instruction that describes the task: ### Input: Set state. ### Response: def state(self, state): """Set state.""" self._state = state self._manager[ATTR_STATE] = state _LOGGER.info('state changed to %s', state)
def triangle(self, params=None, query=None, extent=0.999, **kwargs): """ Makes a nifty corner plot. Uses :func:`triangle.corner`. :param params: (optional) Names of columns (from :attr:`StarModel.samples`) to plot. If ``None``, then it will plo...
Makes a nifty corner plot. Uses :func:`triangle.corner`. :param params: (optional) Names of columns (from :attr:`StarModel.samples`) to plot. If ``None``, then it will plot samples of the parameters used in the MCMC fit-- that is, mass, age, [Fe/H], and...
Below is the the instruction that describes the task: ### Input: Makes a nifty corner plot. Uses :func:`triangle.corner`. :param params: (optional) Names of columns (from :attr:`StarModel.samples`) to plot. If ``None``, then it will plot samples of the paramete...
def parse_fasta_annotations(fastas, annot_tables, trans_table): """ parse gene call information from Prodigal fasta output """ if annot_tables is not False: annots = {} for table in annot_tables: for cds in open(table): ID, start, end, strand = cds.strip().spl...
parse gene call information from Prodigal fasta output
Below is the the instruction that describes the task: ### Input: parse gene call information from Prodigal fasta output ### Response: def parse_fasta_annotations(fastas, annot_tables, trans_table): """ parse gene call information from Prodigal fasta output """ if annot_tables is not False: ...
def get_type_string(self, data, type_string): """ Gets type string. Finds the type string for 'data' contained in ``python_type_strings`` using its ``type``. Non-``None`` 'type_string` overrides whatever type string is looked up. The override makes it easier for subclasses to co...
Gets type string. Finds the type string for 'data' contained in ``python_type_strings`` using its ``type``. Non-``None`` 'type_string` overrides whatever type string is looked up. The override makes it easier for subclasses to convert something that the parent marshaller can wri...
Below is the the instruction that describes the task: ### Input: Gets type string. Finds the type string for 'data' contained in ``python_type_strings`` using its ``type``. Non-``None`` 'type_string` overrides whatever type string is looked up. The override makes it easier for subcl...
def clean(amount): """ Converts a number to a number with decimal point. :param str amount: The input number. :rtype: str """ # Return empty input immediately. if not amount: return amount if re.search(r'[\. ][0-9]{3},[0-9]{1,2}$', amount): ...
Converts a number to a number with decimal point. :param str amount: The input number. :rtype: str
Below is the the instruction that describes the task: ### Input: Converts a number to a number with decimal point. :param str amount: The input number. :rtype: str ### Response: def clean(amount): """ Converts a number to a number with decimal point. :param str amount: Th...
def save_existing_iam_env_vars(self): """Backup IAM environment variables for later restoration.""" for i in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN']: if i in self.env_vars: self.env_vars['OLD_' + i] = self.env_vars[i]
Backup IAM environment variables for later restoration.
Below is the the instruction that describes the task: ### Input: Backup IAM environment variables for later restoration. ### Response: def save_existing_iam_env_vars(self): """Backup IAM environment variables for later restoration.""" for i in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', ...
def InitiateEnrolment(self): """Initiate the enrollment process. We do not sent more than one enrollment request every 10 minutes. Note that we still communicate to the server in fast poll mode, but these requests are not carrying any payload. """ logging.debug("sending enrollment request") ...
Initiate the enrollment process. We do not sent more than one enrollment request every 10 minutes. Note that we still communicate to the server in fast poll mode, but these requests are not carrying any payload.
Below is the the instruction that describes the task: ### Input: Initiate the enrollment process. We do not sent more than one enrollment request every 10 minutes. Note that we still communicate to the server in fast poll mode, but these requests are not carrying any payload. ### Response: def Initiat...
def getQuotes(symbols): ''' get real-time quotes (index, last trade price, last trade time, etc) for stocks, using google api: http://finance.google.com/finance/info?client=ig&q=symbols Unlike python package 'yahoo-finance' (15 min delay), There is no delay for NYSE and NASDAQ stocks in 'googlefinance' pac...
get real-time quotes (index, last trade price, last trade time, etc) for stocks, using google api: http://finance.google.com/finance/info?client=ig&q=symbols Unlike python package 'yahoo-finance' (15 min delay), There is no delay for NYSE and NASDAQ stocks in 'googlefinance' package. example: quotes = get...
Below is the the instruction that describes the task: ### Input: get real-time quotes (index, last trade price, last trade time, etc) for stocks, using google api: http://finance.google.com/finance/info?client=ig&q=symbols Unlike python package 'yahoo-finance' (15 min delay), There is no delay for NYSE and NAS...
def train(self, data_iterator): """Train a keras model on a worker """ optimizer = get_optimizer(self.master_optimizer) self.model = model_from_yaml(self.yaml, self.custom_objects) self.model.compile(optimizer=optimizer, loss=self.master_loss, metrics=s...
Train a keras model on a worker
Below is the the instruction that describes the task: ### Input: Train a keras model on a worker ### Response: def train(self, data_iterator): """Train a keras model on a worker """ optimizer = get_optimizer(self.master_optimizer) self.model = model_from_yaml(self.yaml, self.custom_...
def get_stddevs(self, mag, imt, stddev_types, num_sites): """ Returns the total standard deviation """ stddevs = [] for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES if stddev_type == const.StdDev.TOTAL: ...
Returns the total standard deviation
Below is the the instruction that describes the task: ### Input: Returns the total standard deviation ### Response: def get_stddevs(self, mag, imt, stddev_types, num_sites): """ Returns the total standard deviation """ stddevs = [] for stddev_type in stddev_types: ...
def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_arp_holder = ET.SubElement(config, "hide-arp-holder", xmlns="urn:brocade.com:mgmt:brocade-arp") arp_entry = ET.SubElement(hide_arp_...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_arp_holder = ET.SubElement(config, ...
def _handleLegacyResult(result): """ make sure the result is backward compatible """ if not isinstance(result, dict): warnings.warn('The Gerrit status callback uses the old way to ' 'communicate results. The outcome might be not what is ' 'expected.')...
make sure the result is backward compatible
Below is the the instruction that describes the task: ### Input: make sure the result is backward compatible ### Response: def _handleLegacyResult(result): """ make sure the result is backward compatible """ if not isinstance(result, dict): warnings.warn('The Gerrit status callback uses the...
def config( state, host, key, value, repo=None, ): ''' Manage git config for a repository or globally. + key: the key of the config to ensure + value: the value this key should have + repo: specify the git repo path to edit local config (defaults to global) ''' existing_config = ho...
Manage git config for a repository or globally. + key: the key of the config to ensure + value: the value this key should have + repo: specify the git repo path to edit local config (defaults to global)
Below is the the instruction that describes the task: ### Input: Manage git config for a repository or globally. + key: the key of the config to ensure + value: the value this key should have + repo: specify the git repo path to edit local config (defaults to global) ### Response: def config( stat...
def extractPrintSaveIntermittens(): """ This function will print out the intermittents onto the screen for casual viewing. It will also print out where the giant summary dictionary is going to be stored. :return: None """ # extract intermittents from collected failed tests global g_summary...
This function will print out the intermittents onto the screen for casual viewing. It will also print out where the giant summary dictionary is going to be stored. :return: None
Below is the the instruction that describes the task: ### Input: This function will print out the intermittents onto the screen for casual viewing. It will also print out where the giant summary dictionary is going to be stored. :return: None ### Response: def extractPrintSaveIntermittens(): """ ...
def padded(self, padding): """Return a new Rect padded (smaller) by padding on all sides Parameters ---------- padding : float The padding. Returns ------- rect : instance of Rect The padded rectangle. """ return Rect(pos=...
Return a new Rect padded (smaller) by padding on all sides Parameters ---------- padding : float The padding. Returns ------- rect : instance of Rect The padded rectangle.
Below is the the instruction that describes the task: ### Input: Return a new Rect padded (smaller) by padding on all sides Parameters ---------- padding : float The padding. Returns ------- rect : instance of Rect The padded rectangle. ### R...
def enforce_timezone(self, value): """ When `self.default_timezone` is `None`, always return naive datetimes. When `self.default_timezone` is not `None`, always return aware datetimes. """ field_timezone = getattr(self, 'timezone', self.default_timezone()) if (field_time...
When `self.default_timezone` is `None`, always return naive datetimes. When `self.default_timezone` is not `None`, always return aware datetimes.
Below is the the instruction that describes the task: ### Input: When `self.default_timezone` is `None`, always return naive datetimes. When `self.default_timezone` is not `None`, always return aware datetimes. ### Response: def enforce_timezone(self, value): """ When `self.default_timezone...
def populate_slug(instance, field): ''' Populate a slug field if needed. ''' value = getattr(instance, field.db_field) try: previous = instance.__class__.objects.get(id=instance.id) except Exception: previous = None # Field value has changed changed = field.db_field in ...
Populate a slug field if needed.
Below is the the instruction that describes the task: ### Input: Populate a slug field if needed. ### Response: def populate_slug(instance, field): ''' Populate a slug field if needed. ''' value = getattr(instance, field.db_field) try: previous = instance.__class__.objects.get(id=insta...
def reload_functions(self): """ Replace functions in namespace with functions from edited_source. """ with LiveExecution.lock: if self.edited_source: tree = ast.parse(self.edited_source) for f in [n for n in ast.walk(tree) if isinstance(n, ast....
Replace functions in namespace with functions from edited_source.
Below is the the instruction that describes the task: ### Input: Replace functions in namespace with functions from edited_source. ### Response: def reload_functions(self): """ Replace functions in namespace with functions from edited_source. """ with LiveExecution.lock: ...
def fetch_trades_since(self, since: int) -> List[Trade]: """Fetch trades since given timestamp.""" return self._fetch_since('trades', self.market.code)(self._trades_since)(since)
Fetch trades since given timestamp.
Below is the the instruction that describes the task: ### Input: Fetch trades since given timestamp. ### Response: def fetch_trades_since(self, since: int) -> List[Trade]: """Fetch trades since given timestamp.""" return self._fetch_since('trades', self.market.code)(self._trades_since)(since)
def renumber_atoms(self): """Reset the molecule's atoms :attr:`number` to be 1-indexed""" if self.atoms: # reset the mapping self._anumb_to_atom = {} for i,atom in enumerate(self.atoms): atom.number = i+1 # starting from 1 else: ...
Reset the molecule's atoms :attr:`number` to be 1-indexed
Below is the the instruction that describes the task: ### Input: Reset the molecule's atoms :attr:`number` to be 1-indexed ### Response: def renumber_atoms(self): """Reset the molecule's atoms :attr:`number` to be 1-indexed""" if self.atoms: # reset the mapping self._anumb_...
def clone(self, repo, ref, deps=()): """Clone the given url and checkout the specific ref.""" if os.path.isdir(repo): repo = os.path.abspath(repo) def clone_strategy(directory): env = git.no_git_env() def _git_cmd(*args): cmd_output('git', *...
Clone the given url and checkout the specific ref.
Below is the the instruction that describes the task: ### Input: Clone the given url and checkout the specific ref. ### Response: def clone(self, repo, ref, deps=()): """Clone the given url and checkout the specific ref.""" if os.path.isdir(repo): repo = os.path.abspath(repo) ...
def get_term_after(aterm): """ Returns a uw_sws.models.Term object, for the term after the term given. """ next_year = aterm.year if aterm.quarter == "autumn": next_quarter = QUARTER_SEQ[0] else: next_quarter = QUARTER_SEQ[QUARTER_SEQ.index(aterm.quarter) + 1] if next_qu...
Returns a uw_sws.models.Term object, for the term after the term given.
Below is the the instruction that describes the task: ### Input: Returns a uw_sws.models.Term object, for the term after the term given. ### Response: def get_term_after(aterm): """ Returns a uw_sws.models.Term object, for the term after the term given. """ next_year = aterm.year if ate...
def _attempt_slice_retry(self, shard_state, tstate): """Attempt to retry this slice. This method may modify shard_state and tstate to prepare for retry or fail. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. Returns: A _TA...
Attempt to retry this slice. This method may modify shard_state and tstate to prepare for retry or fail. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. Returns: A _TASK_DIRECTIVE enum. RETRY_SLICE if slice should be retried. ...
Below is the the instruction that describes the task: ### Input: Attempt to retry this slice. This method may modify shard_state and tstate to prepare for retry or fail. Args: shard_state: model.ShardState for current shard. tstate: model.TransientShardState for current shard. Returns: ...
def length(self,threshold=0.2,phys=False,ang=False,tdisrupt=None, **kwargs): """ NAME: length PURPOSE: calculate the length of the stream INPUT: threshold - threshold down from the density near the progenitor at which to define the 'en...
NAME: length PURPOSE: calculate the length of the stream INPUT: threshold - threshold down from the density near the progenitor at which to define the 'end' of the stream phys= (False) if True, return the length in physical kpc ang= (False) i...
Below is the the instruction that describes the task: ### Input: NAME: length PURPOSE: calculate the length of the stream INPUT: threshold - threshold down from the density near the progenitor at which to define the 'end' of the stream phys= (False) ...
def eigtransform(self, sequences, right=True, mode='clip'): r"""Transform a list of sequences by projecting the sequences onto the first `n_timescales` dynamical eigenvectors. Parameters ---------- sequences : list of array-like List of sequences, or a single sequenc...
r"""Transform a list of sequences by projecting the sequences onto the first `n_timescales` dynamical eigenvectors. Parameters ---------- sequences : list of array-like List of sequences, or a single sequence. Each sequence should be a 1D iterable of state labels...
Below is the the instruction that describes the task: ### Input: r"""Transform a list of sequences by projecting the sequences onto the first `n_timescales` dynamical eigenvectors. Parameters ---------- sequences : list of array-like List of sequences, or a single sequen...
def cassist(self,dc,dt,dt2,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous data assisted method, with the recommended combination of multiple tests. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the numbe...
Calculates probability of gene i regulating gene j with continuous data assisted method, with the recommended combination of multiple tests. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the number of secondary targets (dt2) is large. (Check program warn...
Below is the the instruction that describes the task: ### Input: Calculates probability of gene i regulating gene j with continuous data assisted method, with the recommended combination of multiple tests. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions whe...
def _parse_template(self, code, label): ''' Pare smart indented templates Takes a template a returns a list of sub-templates, taking in account the indentation of the original code based on the first line indentation(0) Special treatment of whitespace: returns special Offset and...
Pare smart indented templates Takes a template a returns a list of sub-templates, taking in account the indentation of the original code based on the first line indentation(0) Special treatment of whitespace: returns special Offset and INTERNAL_WHITESPACE, so the generation can be configurable ...
Below is the the instruction that describes the task: ### Input: Pare smart indented templates Takes a template a returns a list of sub-templates, taking in account the indentation of the original code based on the first line indentation(0) Special treatment of whitespace: returns special O...
def _redirect_with_params(url_name, *args, **kwargs): """Helper method to create a redirect response with URL params. This builds a redirect string that converts kwargs into a query string. Args: url_name: The name of the url to redirect to. kwargs: the query string param and their val...
Helper method to create a redirect response with URL params. This builds a redirect string that converts kwargs into a query string. Args: url_name: The name of the url to redirect to. kwargs: the query string param and their values to build. Returns: A properly formatted redi...
Below is the the instruction that describes the task: ### Input: Helper method to create a redirect response with URL params. This builds a redirect string that converts kwargs into a query string. Args: url_name: The name of the url to redirect to. kwargs: the query string param and t...
def _reverse_annotations(old_record, new_record): """ Copy annotations form old_record to new_record, reversing any lists / tuples / strings. """ # Copy the annotations over for k, v in list(old_record.annotations.items()): # Trim if appropriate if isinstance(v, (tuple, list)) an...
Copy annotations form old_record to new_record, reversing any lists / tuples / strings.
Below is the the instruction that describes the task: ### Input: Copy annotations form old_record to new_record, reversing any lists / tuples / strings. ### Response: def _reverse_annotations(old_record, new_record): """ Copy annotations form old_record to new_record, reversing any lists / tuples /...
def get_messages(self, locale=None): """ Get a dictionary of translated messages """ if locale is None: locale = self.locale if self.translator: def translate(error): return self.translator.translate(error, locale) else: def translate(...
Get a dictionary of translated messages
Below is the the instruction that describes the task: ### Input: Get a dictionary of translated messages ### Response: def get_messages(self, locale=None): """ Get a dictionary of translated messages """ if locale is None: locale = self.locale if self.translator: de...
def _euler_to_q(self, euler): """ Create q array from euler angles :param euler: array [roll, pitch, yaw] in rad :returns: array q which represents a quaternion [w, x, y, z] """ assert(len(euler) == 3) phi = euler[0] theta = euler[1] psi = euler[2]...
Create q array from euler angles :param euler: array [roll, pitch, yaw] in rad :returns: array q which represents a quaternion [w, x, y, z]
Below is the the instruction that describes the task: ### Input: Create q array from euler angles :param euler: array [roll, pitch, yaw] in rad :returns: array q which represents a quaternion [w, x, y, z] ### Response: def _euler_to_q(self, euler): """ Create q array from euler angl...
def direction_cossim(layer, vec, batch=None): """Visualize a direction (cossine similarity)""" def inner(T): act_mags = tf.sqrt(tf.reduce_sum(T(layer)**2, -1, keepdims=True)) vec_mag = tf.sqrt(tf.reduce_sum(vec**2)) mags = act_mags * vec_mag if batch is None: return tf.reduce_mean(T(layer) * v...
Visualize a direction (cossine similarity)
Below is the the instruction that describes the task: ### Input: Visualize a direction (cossine similarity) ### Response: def direction_cossim(layer, vec, batch=None): """Visualize a direction (cossine similarity)""" def inner(T): act_mags = tf.sqrt(tf.reduce_sum(T(layer)**2, -1, keepdims=True)) vec_ma...
def astype(self, dtype): """Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object which is a view on the same ...
Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object which is a view on the same underlying chunk data. Modifying any...
Below is the the instruction that describes the task: ### Input: Returns a view that does on the fly type conversion of the underlying data. Parameters ---------- dtype : string or dtype NumPy dtype. Notes ----- This method returns a new Array object whi...
def fit(self, X, y=None): ''' Learn the linear transformation to flipped eigenvalues. Parameters ---------- X : array, shape [n, n] The *symmetric* input similarities. If X is asymmetric, it will be treated as if it were symmetric based on its lower-trian...
Learn the linear transformation to flipped eigenvalues. Parameters ---------- X : array, shape [n, n] The *symmetric* input similarities. If X is asymmetric, it will be treated as if it were symmetric based on its lower-triangular part.
Below is the the instruction that describes the task: ### Input: Learn the linear transformation to flipped eigenvalues. Parameters ---------- X : array, shape [n, n] The *symmetric* input similarities. If X is asymmetric, it will be treated as if it were symmetric b...
def all(self): """ Returns list with vids of all indexed partitions. """ partitions = [] query = text(""" SELECT dataset_vid, vid FROM partition_index;""") for result in self.execute(query): dataset_vid, vid = result partitions.append(Par...
Returns list with vids of all indexed partitions.
Below is the the instruction that describes the task: ### Input: Returns list with vids of all indexed partitions. ### Response: def all(self): """ Returns list with vids of all indexed partitions. """ partitions = [] query = text(""" SELECT dataset_vid, vid FROM pa...
def utf8(value: Union[None, str, bytes]) -> Optional[bytes]: # noqa: F811 """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES):...
Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8.
Below is the the instruction that describes the task: ### Input: Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. ### Response: def utf8(value: Union[None, str, bytes]) -> ...
def eigenvalues_(self): """The eigenvalues associated with each principal component.""" utils.validation.check_is_fitted(self, 's_') return np.square(self.s_).tolist()
The eigenvalues associated with each principal component.
Below is the the instruction that describes the task: ### Input: The eigenvalues associated with each principal component. ### Response: def eigenvalues_(self): """The eigenvalues associated with each principal component.""" utils.validation.check_is_fitted(self, 's_') return np.square(self...
def map_udp_port(public_port, private_port, lifetime=3600, gateway_ip=None, retry=9, use_exception=True): """A high-level wrapper to map_port() that requests a mapping for a public UDP port on the NAT to a private UDP port on this host. Returns the complete response on success. ...
A high-level wrapper to map_port() that requests a mapping for a public UDP port on the NAT to a private UDP port on this host. Returns the complete response on success. public_port - the public port of the mapping requested private_port - the private port of the mappi...
Below is the the instruction that describes the task: ### Input: A high-level wrapper to map_port() that requests a mapping for a public UDP port on the NAT to a private UDP port on this host. Returns the complete response on success. public_port - the public port of the mappin...
def unsign_filters_and_actions(sign, dotted_model_name): """Return the list of filters and actions for dotted_model_name.""" permissions = signing.loads(sign) return permissions.get(dotted_model_name, [])
Return the list of filters and actions for dotted_model_name.
Below is the the instruction that describes the task: ### Input: Return the list of filters and actions for dotted_model_name. ### Response: def unsign_filters_and_actions(sign, dotted_model_name): """Return the list of filters and actions for dotted_model_name.""" permissions = signing.loads(sign) ret...
def find_by_fields(self, table, queryset={}): ''' 从数据库里查询 符合多个条件的记录 Args: table: 表名字 str queryset : key 字段 value 值 dict return: 成功: [dict] 保存的记录 失败: -1 并打印返回报错信息 ''' querys = "" for k, v in que...
从数据库里查询 符合多个条件的记录 Args: table: 表名字 str queryset : key 字段 value 值 dict return: 成功: [dict] 保存的记录 失败: -1 并打印返回报错信息
Below is the the instruction that describes the task: ### Input: 从数据库里查询 符合多个条件的记录 Args: table: 表名字 str queryset : key 字段 value 值 dict return: 成功: [dict] 保存的记录 失败: -1 并打印返回报错信息 ### Response: def find_by_fields(self, table, queryset={}): ''' ...
def migrate_all(): """ Create schema migrations for all apps specified in INSTALLED_APPS, then run a migrate command. """ if 'south' in settings.INSTALLED_APPS: return _south_migrate_all() from django.core.management.commands import makemigrations, migrate schema_args = [sys.executab...
Create schema migrations for all apps specified in INSTALLED_APPS, then run a migrate command.
Below is the the instruction that describes the task: ### Input: Create schema migrations for all apps specified in INSTALLED_APPS, then run a migrate command. ### Response: def migrate_all(): """ Create schema migrations for all apps specified in INSTALLED_APPS, then run a migrate command. """...
def classical_risk(riskinputs, riskmodel, param, monitor): """ Compute and return the average losses for each asset. :param riskinputs: :class:`openquake.risklib.riskinput.RiskInput` objects :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param ...
Compute and return the average losses for each asset. :param riskinputs: :class:`openquake.risklib.riskinput.RiskInput` objects :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param param: dictionary of extra parameters :param monitor: ...
Below is the the instruction that describes the task: ### Input: Compute and return the average losses for each asset. :param riskinputs: :class:`openquake.risklib.riskinput.RiskInput` objects :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param pa...
def find_resources(library, session, query): """Queries a VISA system to locate the resources associated with a specified interface. Corresponds to viFindRsrc function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session (unuse...
Queries a VISA system to locate the resources associated with a specified interface. Corresponds to viFindRsrc function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session (unused, just to uniform signatures). :param query: A ...
Below is the the instruction that describes the task: ### Input: Queries a VISA system to locate the resources associated with a specified interface. Corresponds to viFindRsrc function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to...
def _set_ipv6_ve_intf_cmds(self, v, load=False): """ Setter method for ipv6_ve_intf_cmds, mapped from YANG variable /rbridge_id/interface/ve/ipv6/ipv6_ve_intf_cmds (container) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_ve_intf_cmds is considered as a private ...
Setter method for ipv6_ve_intf_cmds, mapped from YANG variable /rbridge_id/interface/ve/ipv6/ipv6_ve_intf_cmds (container) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_ve_intf_cmds is considered as a private method. Backends looking to populate this variable should ...
Below is the the instruction that describes the task: ### Input: Setter method for ipv6_ve_intf_cmds, mapped from YANG variable /rbridge_id/interface/ve/ipv6/ipv6_ve_intf_cmds (container) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_ve_intf_cmds is considered as a pr...