code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def verify_file(self, path, destination, verify='none'): """Tries to verify if path has same checksum as destination. Valid options for verify is 'raw', 'sha1' or 'none' """ content = from_file(path) log.info('Verifying using %s...' % verify) if verify == 'raw': ...
Tries to verify if path has same checksum as destination. Valid options for verify is 'raw', 'sha1' or 'none'
Below is the the instruction that describes the task: ### Input: Tries to verify if path has same checksum as destination. Valid options for verify is 'raw', 'sha1' or 'none' ### Response: def verify_file(self, path, destination, verify='none'): """Tries to verify if path has same checksum as d...
def needed_inputs(self): """ List all the needed inputs of a configured engine >>> engine = Engine("op1", "op2") >>> engine.op1.setup(in_name="in", out_name="middle", required=False) >>> engine.op2.setup(in_name="middle", out_name="out") >>> engine.op1.append(lambda x:x+2) ...
List all the needed inputs of a configured engine >>> engine = Engine("op1", "op2") >>> engine.op1.setup(in_name="in", out_name="middle", required=False) >>> engine.op2.setup(in_name="middle", out_name="out") >>> engine.op1.append(lambda x:x+2) >>> engine.op2.append(lambda x:x*2...
Below is the the instruction that describes the task: ### Input: List all the needed inputs of a configured engine >>> engine = Engine("op1", "op2") >>> engine.op1.setup(in_name="in", out_name="middle", required=False) >>> engine.op2.setup(in_name="middle", out_name="out") >>> engin...
def row(self): """ Returns the periodic table row of the element. """ z = self.Z total = 0 if 57 <= z <= 71: return 8 elif 89 <= z <= 103: return 9 for i in range(len(_pt_row_sizes)): total += _pt_row_sizes[i] ...
Returns the periodic table row of the element.
Below is the the instruction that describes the task: ### Input: Returns the periodic table row of the element. ### Response: def row(self): """ Returns the periodic table row of the element. """ z = self.Z total = 0 if 57 <= z <= 71: return 8 eli...
def clear(self): """ Clears the settings for this XML format. """ self._xroot = ElementTree.Element('settings') self._xroot.set('version', '1.0') self._xstack = [self._xroot]
Clears the settings for this XML format.
Below is the the instruction that describes the task: ### Input: Clears the settings for this XML format. ### Response: def clear(self): """ Clears the settings for this XML format. """ self._xroot = ElementTree.Element('settings') self._xroot.set('version', '1.0') ...
def get_apex(self, lat, height=None): """ Calculate apex height Parameters ----------- lat : (float) Latitude in degrees height : (float or NoneType) Height above the surface of the earth in km or NoneType to use reference height (default=None...
Calculate apex height Parameters ----------- lat : (float) Latitude in degrees height : (float or NoneType) Height above the surface of the earth in km or NoneType to use reference height (default=None) Returns ---------- apex...
Below is the the instruction that describes the task: ### Input: Calculate apex height Parameters ----------- lat : (float) Latitude in degrees height : (float or NoneType) Height above the surface of the earth in km or NoneType to use reference h...
def caption_mentions(self) -> List[str]: """List of all lowercased profiles that are mentioned in the Post's caption, without preceeding @.""" if not self.caption: return [] # This regular expression is from jStassen, adjusted to use Python's \w to support Unicode # http://bl...
List of all lowercased profiles that are mentioned in the Post's caption, without preceeding @.
Below is the the instruction that describes the task: ### Input: List of all lowercased profiles that are mentioned in the Post's caption, without preceeding @. ### Response: def caption_mentions(self) -> List[str]: """List of all lowercased profiles that are mentioned in the Post's caption, without precee...
def get_conversations(self, **kwargs): """ Return list of conversations for the current user, most resent ones first. :calls: `GET /api/v1/conversations \ <https://canvas.instructure.com/doc/api/conversations.html#method.conversations.index>`_ :rtype: :class:`canvasapi.paginate...
Return list of conversations for the current user, most resent ones first. :calls: `GET /api/v1/conversations \ <https://canvas.instructure.com/doc/api/conversations.html#method.conversations.index>`_ :rtype: :class:`canvasapi.paginated_list.PaginatedList` of \ :class:`canvasapi.conver...
Below is the the instruction that describes the task: ### Input: Return list of conversations for the current user, most resent ones first. :calls: `GET /api/v1/conversations \ <https://canvas.instructure.com/doc/api/conversations.html#method.conversations.index>`_ :rtype: :class:`canvasap...
def disassociate_notification_template(self, job_template, notification_template, status): """Disassociate a notification template from this job template. =====API DOCS===== Disassociate a notification template from this job template. :param j...
Disassociate a notification template from this job template. =====API DOCS===== Disassociate a notification template from this job template. :param job_template: The job template to disassociate from. :type job_template: str :param notification_template: The notification templa...
Below is the the instruction that describes the task: ### Input: Disassociate a notification template from this job template. =====API DOCS===== Disassociate a notification template from this job template. :param job_template: The job template to disassociate from. :type job_templa...
def write(self, outfile, rows): """Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` ...
Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` values. If `interlace` is specified (when ...
Below is the the instruction that describes the task: ### Input: Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.widt...
def demo_login(self, auth=None, url=None): """Authenticate with a "Share Your Class" URL using a demo user. You may provide either the entire ``url`` or simply the ``auth`` parameter. :param url: Example - "https://piazza.com/demo_login?nid=hbj11a1gcvl1s6&auth=06c111b" :param a...
Authenticate with a "Share Your Class" URL using a demo user. You may provide either the entire ``url`` or simply the ``auth`` parameter. :param url: Example - "https://piazza.com/demo_login?nid=hbj11a1gcvl1s6&auth=06c111b" :param auth: Example - "06c111b"
Below is the the instruction that describes the task: ### Input: Authenticate with a "Share Your Class" URL using a demo user. You may provide either the entire ``url`` or simply the ``auth`` parameter. :param url: Example - "https://piazza.com/demo_login?nid=hbj11a1gcvl1s6&auth=06c111b" ...
def file_download_using_requests(self,url): '''It will download file specified by url using requests module''' file_name=url.split('/')[-1] if os.path.exists(os.path.join(os.getcwd(),file_name)): print 'File already exists' return #print 'Downloading file %s '%file_name #print 'Downloading from %s'%url...
It will download file specified by url using requests module
Below is the the instruction that describes the task: ### Input: It will download file specified by url using requests module ### Response: def file_download_using_requests(self,url): '''It will download file specified by url using requests module''' file_name=url.split('/')[-1] if os.path.exists(os.path.jo...
def make_undirected(self): "Make a digraph into an undirected graph by adding symmetric edges." for a in self.dict.keys(): for (b, distance) in self.dict[a].items(): self.connect1(b, a, distance)
Make a digraph into an undirected graph by adding symmetric edges.
Below is the the instruction that describes the task: ### Input: Make a digraph into an undirected graph by adding symmetric edges. ### Response: def make_undirected(self): "Make a digraph into an undirected graph by adding symmetric edges." for a in self.dict.keys(): for (b, distance) ...
def remove(self, interval): """ Removes an interval from the tree, if present. If not, raises ValueError. Completes in O(log n) time. """ #self.verify() if interval not in self: #print(self.all_intervals) raise ValueError self.top_...
Removes an interval from the tree, if present. If not, raises ValueError. Completes in O(log n) time.
Below is the the instruction that describes the task: ### Input: Removes an interval from the tree, if present. If not, raises ValueError. Completes in O(log n) time. ### Response: def remove(self, interval): """ Removes an interval from the tree, if present. If not, raises ...
def size(self, width=None, height=None): u'''Set/get window size.''' sc = System.Console if width is not None and height is not None: sc.BufferWidth, sc.BufferHeight = width,height else: return sc.BufferWidth, sc.BufferHeight if width is not None ...
u'''Set/get window size.
Below is the the instruction that describes the task: ### Input: u'''Set/get window size. ### Response: def size(self, width=None, height=None): u'''Set/get window size.''' sc = System.Console if width is not None and height is not None: sc.BufferWidth, sc.BufferHeight = wid...
def get_function_url(self, function): """ Registers the given callable in the system (if it isn't already) and returns the URL that can be used to invoke the given function from remote. """ assert self._opened, "RPC System is not opened" logging.debug("get_function_url(%s...
Registers the given callable in the system (if it isn't already) and returns the URL that can be used to invoke the given function from remote.
Below is the the instruction that describes the task: ### Input: Registers the given callable in the system (if it isn't already) and returns the URL that can be used to invoke the given function from remote. ### Response: def get_function_url(self, function): """ Registers the given callab...
def convert_obatoms_to_molecule(self, atoms, residue_name=None, site_property="ff_map"): """ Convert list of openbabel atoms to MOlecule. Args: atoms ([OBAtom]): list of OBAtom objects residue_name (str): the key in self.map_residue_to_mol. Usec to restor...
Convert list of openbabel atoms to MOlecule. Args: atoms ([OBAtom]): list of OBAtom objects residue_name (str): the key in self.map_residue_to_mol. Usec to restore the site properties in the final packed molecule. site_property (str): the site property to be ...
Below is the the instruction that describes the task: ### Input: Convert list of openbabel atoms to MOlecule. Args: atoms ([OBAtom]): list of OBAtom objects residue_name (str): the key in self.map_residue_to_mol. Usec to restore the site properties in the final packe...
def freqEigvalRatio(self,isotropic=False): """ NAME: freqEigvalRatio PURPOSE: calculate the ratio between the largest and 2nd-to-largest (in abs) eigenvalue of sqrt(dO/dJ^T V_J dO/dJ) (if this is big, a 1D stream will form) INPUT: ...
NAME: freqEigvalRatio PURPOSE: calculate the ratio between the largest and 2nd-to-largest (in abs) eigenvalue of sqrt(dO/dJ^T V_J dO/dJ) (if this is big, a 1D stream will form) INPUT: isotropic= (False), if True, return the ratio assuming an i...
Below is the the instruction that describes the task: ### Input: NAME: freqEigvalRatio PURPOSE: calculate the ratio between the largest and 2nd-to-largest (in abs) eigenvalue of sqrt(dO/dJ^T V_J dO/dJ) (if this is big, a 1D stream will form) INPUT: ...
def require_representation(self, req): """Require raw representation dictionary from falcon request object. This does not perform any field parsing or validation but only uses allowed content-encoding handler to decode content body. Note: Currently only JSON is allowed as c...
Require raw representation dictionary from falcon request object. This does not perform any field parsing or validation but only uses allowed content-encoding handler to decode content body. Note: Currently only JSON is allowed as content type. Args: req (falco...
Below is the the instruction that describes the task: ### Input: Require raw representation dictionary from falcon request object. This does not perform any field parsing or validation but only uses allowed content-encoding handler to decode content body. Note: Currently only J...
def getPassage(self, urn, inventory=None, context=None): """ Retrieve a passage :param urn: URN identifying the text's passage (Minimum depth : 1) :type urn: text :param inventory: Name of the inventory :type inventory: text :param context: Number of citation units at th...
Retrieve a passage :param urn: URN identifying the text's passage (Minimum depth : 1) :type urn: text :param inventory: Name of the inventory :type inventory: text :param context: Number of citation units at the same level of the citation hierarchy as the requested urn, immediat...
Below is the the instruction that describes the task: ### Input: Retrieve a passage :param urn: URN identifying the text's passage (Minimum depth : 1) :type urn: text :param inventory: Name of the inventory :type inventory: text :param context: Number of citation units at th...
def one_to_many(clsname, **kw): """Use an event to build a one-to-many relationship on a class. This makes use of the :meth:`.References._reference_table` method to generate a full foreign key relationship from the remote table. """ @declared_attr def o2m(cls): cls._references((clsname...
Use an event to build a one-to-many relationship on a class. This makes use of the :meth:`.References._reference_table` method to generate a full foreign key relationship from the remote table.
Below is the the instruction that describes the task: ### Input: Use an event to build a one-to-many relationship on a class. This makes use of the :meth:`.References._reference_table` method to generate a full foreign key relationship from the remote table. ### Response: def one_to_many(clsname, **kw): ...
def _get_salt_params(): ''' Try to get all sort of parameters for Server Density server info. NOTE: Missing publicDNS and publicIPs parameters. There might be way of getting them with salt-cloud. ''' all_stats = __salt__['status.all_status']() all_grains = __salt__['grains.items']() par...
Try to get all sort of parameters for Server Density server info. NOTE: Missing publicDNS and publicIPs parameters. There might be way of getting them with salt-cloud.
Below is the the instruction that describes the task: ### Input: Try to get all sort of parameters for Server Density server info. NOTE: Missing publicDNS and publicIPs parameters. There might be way of getting them with salt-cloud. ### Response: def _get_salt_params(): ''' Try to get all sort of ...
def load(self): """ Load table data from a Google Spreadsheet. This method consider :py:attr:`.source` as a path to the credential JSON file to access Google Sheets API. The method automatically search the header row start from :py:attr:`.start_row`. The condition of th...
Load table data from a Google Spreadsheet. This method consider :py:attr:`.source` as a path to the credential JSON file to access Google Sheets API. The method automatically search the header row start from :py:attr:`.start_row`. The condition of the header row is that all of ...
Below is the the instruction that describes the task: ### Input: Load table data from a Google Spreadsheet. This method consider :py:attr:`.source` as a path to the credential JSON file to access Google Sheets API. The method automatically search the header row start from :py:attr:...
def hls_palette(n_colors=6, h=.01, l=.6, s=.65): """ Get a set of evenly spaced colors in HLS hue space. h, l, and s should be between 0 and 1 Parameters ---------- n_colors : int number of colors in the palette h : float first hue l : float lightness s : f...
Get a set of evenly spaced colors in HLS hue space. h, l, and s should be between 0 and 1 Parameters ---------- n_colors : int number of colors in the palette h : float first hue l : float lightness s : float saturation Returns ------- palette ...
Below is the the instruction that describes the task: ### Input: Get a set of evenly spaced colors in HLS hue space. h, l, and s should be between 0 and 1 Parameters ---------- n_colors : int number of colors in the palette h : float first hue l : float lightness ...
def _get_buckets_cache_filename(): ''' Return the filename of the cache for bucket contents. Create the path if it does not exist. ''' cache_dir = _get_cache_dir() if not os.path.exists(cache_dir): os.makedirs(cache_dir) return os.path.join(cache_dir, 'buckets_files.cache')
Return the filename of the cache for bucket contents. Create the path if it does not exist.
Below is the the instruction that describes the task: ### Input: Return the filename of the cache for bucket contents. Create the path if it does not exist. ### Response: def _get_buckets_cache_filename(): ''' Return the filename of the cache for bucket contents. Create the path if it does not exis...
def send_message(self,message): """ Send awamp message to the server. We don't wait for a response here. Just fire out a message """ if self._state == STATE_DISCONNECTED: raise Exception("WAMP is currently disconnected!") message = message.as_str() logger....
Send awamp message to the server. We don't wait for a response here. Just fire out a message
Below is the the instruction that describes the task: ### Input: Send awamp message to the server. We don't wait for a response here. Just fire out a message ### Response: def send_message(self,message): """ Send awamp message to the server. We don't wait for a response here. Just f...
def add_options(cls, parser: OptionManager) -> None: """ ``flake8`` api method to register new plugin options. See :class:`.Configuration` docs for detailed options reference. Arguments: parser: ``flake8`` option parser instance. """ parser.add_option( ...
``flake8`` api method to register new plugin options. See :class:`.Configuration` docs for detailed options reference. Arguments: parser: ``flake8`` option parser instance.
Below is the the instruction that describes the task: ### Input: ``flake8`` api method to register new plugin options. See :class:`.Configuration` docs for detailed options reference. Arguments: parser: ``flake8`` option parser instance. ### Response: def add_options(cls, parser: Opti...
def delete_asset(self, asset_id): """Deletes an ``Asset``. arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to remove raise: NotFound - ``asset_id`` not found raise: NullArgument - ``asset_id`` is ``null`` raise: OperationFailed - unable to complete ...
Deletes an ``Asset``. arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to remove raise: NotFound - ``asset_id`` not found raise: NullArgument - ``asset_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - au...
Below is the the instruction that describes the task: ### Input: Deletes an ``Asset``. arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to remove raise: NotFound - ``asset_id`` not found raise: NullArgument - ``asset_id`` is ``null`` raise: OperationFail...
def editor_js_initialization(selector, **extra_settings): """ Return script tag with initialization code. """ init_template = loader.get_template( settings.MARKDOWN_EDITOR_INIT_TEMPLATE) options = dict( previewParserPath=reverse('django_markdown_preview'), **settings.MARKDOWN_EDITO...
Return script tag with initialization code.
Below is the the instruction that describes the task: ### Input: Return script tag with initialization code. ### Response: def editor_js_initialization(selector, **extra_settings): """ Return script tag with initialization code. """ init_template = loader.get_template( settings.MARKDOWN_EDITOR_INI...
def user_record(uid, type=0): """获取用户的播放列表,必须登录 :param uid: 用户的ID,可通过登录或者其他接口获取 :param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData """ if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_RECORD' r.data = {'type': type, 'uid': uid, "csrf_token": ""} r.send()...
获取用户的播放列表,必须登录 :param uid: 用户的ID,可通过登录或者其他接口获取 :param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData
Below is the the instruction that describes the task: ### Input: 获取用户的播放列表,必须登录 :param uid: 用户的ID,可通过登录或者其他接口获取 :param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData ### Response: def user_record(uid, type=0): """获取用户的播放列表,必须登录 :param uid: 用户的ID,可通过登录或者其他接口获取 :param type: (optional) 数据类型,0:获取所有...
def delete_archive_file(self): """ Delete the directory containing the constructed archive """ logger.debug("Deleting %s", self.archive_tmp_dir) shutil.rmtree(self.archive_tmp_dir, True)
Delete the directory containing the constructed archive
Below is the the instruction that describes the task: ### Input: Delete the directory containing the constructed archive ### Response: def delete_archive_file(self): """ Delete the directory containing the constructed archive """ logger.debug("Deleting %s", self.archive_tmp_dir) ...
def resample(img, hdr, target_spacing, bspline_order=3, mode='constant'): """ Re-sample an image to a new voxel-spacing. Parameters ---------- img : array_like The image. hdr : object The image header. target_spacing : number or se...
Re-sample an image to a new voxel-spacing. Parameters ---------- img : array_like The image. hdr : object The image header. target_spacing : number or sequence of numbers The target voxel spacing to achieve. If a single number, isotrop...
Below is the the instruction that describes the task: ### Input: Re-sample an image to a new voxel-spacing. Parameters ---------- img : array_like The image. hdr : object The image header. target_spacing : number or sequence of numbers ...
def as_bash_array(self) -> str: """Return a representation as a bash array. This creates a string formatted as a bash array containing all the commands in the job. """ return_string = "( \\\n" for command in self: return_string += '"' + str(command) + '" \\\n' ...
Return a representation as a bash array. This creates a string formatted as a bash array containing all the commands in the job.
Below is the the instruction that describes the task: ### Input: Return a representation as a bash array. This creates a string formatted as a bash array containing all the commands in the job. ### Response: def as_bash_array(self) -> str: """Return a representation as a bash array. This ...
def _refresh(self): """Refresh the API token using the currently bound credentials. This is simply a convenience method to be invoked automatically if authentication fails during normal client use. """ # Request and set a new API token. new_token = self.authenticate(self...
Refresh the API token using the currently bound credentials. This is simply a convenience method to be invoked automatically if authentication fails during normal client use.
Below is the the instruction that describes the task: ### Input: Refresh the API token using the currently bound credentials. This is simply a convenience method to be invoked automatically if authentication fails during normal client use. ### Response: def _refresh(self): """Refresh the A...
def _buildStartOpts(self, streamUrl, playList=False): """ Builds the options to pass to subprocess.""" if playList: opts = [self.PLAYER_CMD, "-quiet", "-playlist", streamUrl] else: opts = [self.PLAYER_CMD, "-quiet", streamUrl] if self.USE_PROFILE == -1: ...
Builds the options to pass to subprocess.
Below is the the instruction that describes the task: ### Input: Builds the options to pass to subprocess. ### Response: def _buildStartOpts(self, streamUrl, playList=False): """ Builds the options to pass to subprocess.""" if playList: opts = [self.PLAYER_CMD, "-quiet", "-playlist", st...
def list_blobs( self, max_results=None, page_token=None, prefix=None, delimiter=None, versions=None, projection="noAcl", fields=None, client=None, ): """Return an iterator used to find blobs in the bucket. If :attr:`user_projec...
Return an iterator used to find blobs in the bucket. If :attr:`user_project` is set, bills the API request to that project. :type max_results: int :param max_results: (Optional) The maximum number of blobs in each page of results from this request. Non-positive values a...
Below is the the instruction that describes the task: ### Input: Return an iterator used to find blobs in the bucket. If :attr:`user_project` is set, bills the API request to that project. :type max_results: int :param max_results: (Optional) The maximum number of blobs in each...
def get_instance(self, payload): """ Build an instance of TerminatingSipDomainInstance :param dict payload: Payload response from the API :returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainInstance :rtype: twilio.rest.trunking.v1.trunk.terminatin...
Build an instance of TerminatingSipDomainInstance :param dict payload: Payload response from the API :returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainInstance :rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainInstance
Below is the the instruction that describes the task: ### Input: Build an instance of TerminatingSipDomainInstance :param dict payload: Payload response from the API :returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainInstance :rtype: twilio.rest.trunking.v1....
def fcomplete(text, state): """Readline completion function: Filenames""" text = os.path.expanduser(text) head, tail = os.path.split(text) search_dir = os.path.join('.', head) candidates = [s for s in os.listdir(search_dir) if s.startswith(tail)] if state >= len(candidates): return No...
Readline completion function: Filenames
Below is the the instruction that describes the task: ### Input: Readline completion function: Filenames ### Response: def fcomplete(text, state): """Readline completion function: Filenames""" text = os.path.expanduser(text) head, tail = os.path.split(text) search_dir = os.path.join('.', head) ...
def update_from_object(self, obj, criterion=lambda key: key.isupper()): """ Update dict from the attributes of a module, class or other object. By default only attributes with all-uppercase names will be retrieved. Use the ``criterion`` argument to modify that behaviour. :arg o...
Update dict from the attributes of a module, class or other object. By default only attributes with all-uppercase names will be retrieved. Use the ``criterion`` argument to modify that behaviour. :arg obj: Either the actual module/object, or its absolute name, e.g. 'my_app.settings...
Below is the the instruction that describes the task: ### Input: Update dict from the attributes of a module, class or other object. By default only attributes with all-uppercase names will be retrieved. Use the ``criterion`` argument to modify that behaviour. :arg obj: Either the actual m...
def apply2(self, func, *args, **kwargs): """ Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWra...
Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: LinearWrap: ``LinearWrap(func(args[0], self.tensor(), *args[1:], **kwa...
Below is the the instruction that describes the task: ### Input: Apply a function on the wrapped tensor. The tensor will be the second argument of func. This is because many symbolic functions (such as tensorpack's layers) takes 'scope' as the first argument. Returns: L...
def get_threadline_theming(self, thread): """ looks up theming info a threadline displaying a given thread. This wraps around :meth:`~alot.settings.theme.Theme.get_threadline_theming`, filling in the current colour mode. :param thread: thread to theme :type thread: alot....
looks up theming info a threadline displaying a given thread. This wraps around :meth:`~alot.settings.theme.Theme.get_threadline_theming`, filling in the current colour mode. :param thread: thread to theme :type thread: alot.db.thread.Thread
Below is the the instruction that describes the task: ### Input: looks up theming info a threadline displaying a given thread. This wraps around :meth:`~alot.settings.theme.Theme.get_threadline_theming`, filling in the current colour mode. :param thread: thread to theme :type thread...
def updateNetwork(self, dhcp='dhcp', ipaddress=None, netmask=None, gateway=None, dns=None): """Change the current network settings.""" return self.__post('/api/updateNetwork', ...
Change the current network settings.
Below is the the instruction that describes the task: ### Input: Change the current network settings. ### Response: def updateNetwork(self, dhcp='dhcp', ipaddress=None, netmask=None, gateway=None, dns=None...
def makeXsl(filename): """ Helper that creates a XSLT stylesheet """ pkg = 'cnxml2html' package = ''.join(['.' + x for x in __name__.split('.')[:-1]])[1:] if package != '': pkg = package + '.' + pkg path = pkg_resources.resource_filename(pkg, filename) xml = etree.parse(path) return etree.XSLT(xml)
Helper that creates a XSLT stylesheet
Below is the the instruction that describes the task: ### Input: Helper that creates a XSLT stylesheet ### Response: def makeXsl(filename): """ Helper that creates a XSLT stylesheet """ pkg = 'cnxml2html' package = ''.join(['.' + x for x in __name__.split('.')[:-1]])[1:] if package != '': pkg = packa...
async def get_user(self, username, secret_key=None): """Get a user by name. :param str username: Username :param str secret_key: Issued by juju when add or reset user password :returns: A :class:`~juju.user.User` instance """ client_facade = client.UserManage...
Get a user by name. :param str username: Username :param str secret_key: Issued by juju when add or reset user password :returns: A :class:`~juju.user.User` instance
Below is the the instruction that describes the task: ### Input: Get a user by name. :param str username: Username :param str secret_key: Issued by juju when add or reset user password :returns: A :class:`~juju.user.User` instance ### Response: async def get_user(self, username...
def __delete(self, key): ''' Delete file key from database ''' with self.get_conn() as conn: try: c = conn.cursor() c.execute("DELETE FROM cache_entries WHERE key = ?", (key,)) conn.commit() except: getLogger...
Delete file key from database
Below is the the instruction that describes the task: ### Input: Delete file key from database ### Response: def __delete(self, key): ''' Delete file key from database ''' with self.get_conn() as conn: try: c = conn.cursor() c.execute("DELETE FROM...
def show_floating_ip(kwargs=None, call=None): ''' Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ''' if call != 'function': log.error( ...
Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
Below is the the instruction that describes the task: ### Input: Show the details of a floating IP .. versionadded:: 2016.3.0 CLI Examples: .. code-block:: bash salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47' ### Response: def show_floating_ip(kwargs=None, ca...
def connection_lost(self, exc): """Stop when connection is lost.""" if exc: self.log.exception('disconnected due to exception') else: self.log.info('disconnected because of close/abort.') self._closed.set()
Stop when connection is lost.
Below is the the instruction that describes the task: ### Input: Stop when connection is lost. ### Response: def connection_lost(self, exc): """Stop when connection is lost.""" if exc: self.log.exception('disconnected due to exception') else: self.log.info('disconnec...
def create_single_button_clone(self, submit_text='Submit', submit_css_class='btn-primary', read_form_data=True, form_type=None): """ This will create a copy of this form, with all of inputs replaced with hidden inputs, and with a single submit button. This all...
This will create a copy of this form, with all of inputs replaced with hidden inputs, and with a single submit button. This allows you to easily create a "button" that will submit a post request which is identical to the current state of the form. You could then, if required, change some of the...
Below is the the instruction that describes the task: ### Input: This will create a copy of this form, with all of inputs replaced with hidden inputs, and with a single submit button. This allows you to easily create a "button" that will submit a post request which is identical to the current state...
def seek(self, offset, whence=os.SEEK_SET): """Seeks to an offset within the file-like object. Args: offset (int): offset to seek to. whence (Optional(int)): value that indicates whether offset is an absolute or relative position within the file. Raises: IOError: if the seek fa...
Seeks to an offset within the file-like object. Args: offset (int): offset to seek to. whence (Optional(int)): value that indicates whether offset is an absolute or relative position within the file. Raises: IOError: if the seek failed. OSError: if the seek failed.
Below is the the instruction that describes the task: ### Input: Seeks to an offset within the file-like object. Args: offset (int): offset to seek to. whence (Optional(int)): value that indicates whether offset is an absolute or relative position within the file. Raises: IOErr...
def run(self, train_set, valid_set=None, test_set=None, train_size=None, epoch_controllers=None): """ Run until the end. :param epoch_controllers: deprecated """ epoch_controllers = epoch_controllers if epoch_controllers else [] epoch_controllers += self._epoch_controller...
Run until the end. :param epoch_controllers: deprecated
Below is the the instruction that describes the task: ### Input: Run until the end. :param epoch_controllers: deprecated ### Response: def run(self, train_set, valid_set=None, test_set=None, train_size=None, epoch_controllers=None): """ Run until the end. :param epoch_controllers: d...
def _toolkit_get_topk_bottomk(values, k=5): """ Returns a tuple of the top k values from the positive and negative values in a SArray Parameters ---------- values : SFrame of model coefficients k: Maximum number of largest positive and k lowest negative numbers to return Returns -...
Returns a tuple of the top k values from the positive and negative values in a SArray Parameters ---------- values : SFrame of model coefficients k: Maximum number of largest positive and k lowest negative numbers to return Returns ------- (topk_positive, bottomk_positive) : tuple ...
Below is the the instruction that describes the task: ### Input: Returns a tuple of the top k values from the positive and negative values in a SArray Parameters ---------- values : SFrame of model coefficients k: Maximum number of largest positive and k lowest negative numbers to return ...
def build_payload(self, payload): """ Build payload of message. """ for segment in self.segments: segment.pack(payload, commit=self.autocommit)
Build payload of message.
Below is the the instruction that describes the task: ### Input: Build payload of message. ### Response: def build_payload(self, payload): """ Build payload of message. """ for segment in self.segments: segment.pack(payload, commit=self.autocommit)
def show_page_groups(self, url, group_id): """ Show page. Retrieve the content of a wiki page """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = group_id # REQUIRED - PATH -...
Show page. Retrieve the content of a wiki page
Below is the the instruction that describes the task: ### Input: Show page. Retrieve the content of a wiki page ### Response: def show_page_groups(self, url, group_id): """ Show page. Retrieve the content of a wiki page """ path = {} data = {} ...
def program_word(self, offset, word): """ .. _program_word: Write the word ``word`` to the memory at offset ``offset``. Used to write the boot code. Might raise AddressError_, if the offset exceeds the address space. """ if(offset >= self.size): raise AddressError("Offset({}) not in address space({...
.. _program_word: Write the word ``word`` to the memory at offset ``offset``. Used to write the boot code. Might raise AddressError_, if the offset exceeds the address space.
Below is the the instruction that describes the task: ### Input: .. _program_word: Write the word ``word`` to the memory at offset ``offset``. Used to write the boot code. Might raise AddressError_, if the offset exceeds the address space. ### Response: def program_word(self, offset, word): """ .. _pr...
def ids(args): """ %prog ids cdhit.clstr Get the representative ids from clstr file. """ p = OptionParser(ids.__doc__) p.add_option("--prefix", type="int", help="Find rep id for prefix of len [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: ...
%prog ids cdhit.clstr Get the representative ids from clstr file.
Below is the the instruction that describes the task: ### Input: %prog ids cdhit.clstr Get the representative ids from clstr file. ### Response: def ids(args): """ %prog ids cdhit.clstr Get the representative ids from clstr file. """ p = OptionParser(ids.__doc__) p.add_option("--prefi...
def maintained_selection(): """Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... node.setSelected(on=False, clear_all_selected=True) >>> # Selection restored """ previous_selection = hou.selectedNodes() t...
Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... node.setSelected(on=False, clear_all_selected=True) >>> # Selection restored
Below is the the instruction that describes the task: ### Input: Maintain selection during context Example: >>> with maintained_selection(): ... # Modify selection ... node.setSelected(on=False, clear_all_selected=True) >>> # Selection restored ### Response: def maintai...
def hash(self, id): """ Creates a unique filename in the cache for the id. """ h = md5(id).hexdigest() return os.path.join(self.path, h+self.type)
Creates a unique filename in the cache for the id.
Below is the the instruction that describes the task: ### Input: Creates a unique filename in the cache for the id. ### Response: def hash(self, id): """ Creates a unique filename in the cache for the id. """ h = md5(id).hexdigest() return os.path.join(self.path, h+self.type)
def time_context_from_timex(timex): """Return a TimeContext object given a timex entry.""" time_text = timex.get('text') constraint = timex['intervals'][0] start = _get_time_stamp(constraint.get('start')) end = _get_time_stamp(constraint.get('end')) duration = constraint['duration'] tc = Tim...
Return a TimeContext object given a timex entry.
Below is the the instruction that describes the task: ### Input: Return a TimeContext object given a timex entry. ### Response: def time_context_from_timex(timex): """Return a TimeContext object given a timex entry.""" time_text = timex.get('text') constraint = timex['intervals'][0] start = _get_ti...
def move_file_to_file(old_path, new_path): """Moves file from old location to new one :param old_path: path of file to move :param new_path: new path """ try: os.rename(old_path, new_path) except: old_file = os.path.basename(old_path) ...
Moves file from old location to new one :param old_path: path of file to move :param new_path: new path
Below is the the instruction that describes the task: ### Input: Moves file from old location to new one :param old_path: path of file to move :param new_path: new path ### Response: def move_file_to_file(old_path, new_path): """Moves file from old location to new one :param old_p...
def create(self, **kwargs): """ Create Instantiates and persists new model populated from provided arguments :param kwargs: varargs, data to populate with :return: object, persisted new instance of model """ model = self.new(**kwar...
Create Instantiates and persists new model populated from provided arguments :param kwargs: varargs, data to populate with :return: object, persisted new instance of model
Below is the the instruction that describes the task: ### Input: Create Instantiates and persists new model populated from provided arguments :param kwargs: varargs, data to populate with :return: object, persisted new instance of model ### Response: def cre...
def get_duration_measures(source_file_path, output_path=None, phonemic=False, semantic=False, quiet=False, similarity_file = None, threshold = None): """Parses ...
Parses input arguments and runs clustering algorithm. :param source_file_path: Required. Location of the .csv or .TextGrid file to be analyzed. :param output_path: Path to which to write the resultant csv file. If left None, path will be set to the source_file_path. If set to False, no file wi...
Below is the the instruction that describes the task: ### Input: Parses input arguments and runs clustering algorithm. :param source_file_path: Required. Location of the .csv or .TextGrid file to be analyzed. :param output_path: Path to which to write the resultant csv file. If left None, p...
def _esfilter2sqlwhere(db, esfilter): """ CONVERT ElassticSearch FILTER TO SQL FILTER db - REQUIRED TO PROPERLY QUOTE VALUES AND COLUMN NAMES """ esfilter = wrap(esfilter) if esfilter is True: return SQL_TRUE elif esfilter["and"]: return sql_iso(SQL_AND.join([esfilter2sqlwhe...
CONVERT ElassticSearch FILTER TO SQL FILTER db - REQUIRED TO PROPERLY QUOTE VALUES AND COLUMN NAMES
Below is the the instruction that describes the task: ### Input: CONVERT ElassticSearch FILTER TO SQL FILTER db - REQUIRED TO PROPERLY QUOTE VALUES AND COLUMN NAMES ### Response: def _esfilter2sqlwhere(db, esfilter): """ CONVERT ElassticSearch FILTER TO SQL FILTER db - REQUIRED TO PROPERLY QUOTE VA...
def get_source_from_contracts_list(self, contracts): """ get the source data from the contracts list :param contracts: the list of contracts :return: """ if contracts is None or len(contracts) == 0: return if isinstance(contracts[0], SolidityContract):...
get the source data from the contracts list :param contracts: the list of contracts :return:
Below is the the instruction that describes the task: ### Input: get the source data from the contracts list :param contracts: the list of contracts :return: ### Response: def get_source_from_contracts_list(self, contracts): """ get the source data from the contracts list :p...
def _CalculateNTFSTimeHash(self, file_entry): """Calculates an MD5 from the date and time value of a NTFS file entry. Args: file_entry (dfvfs.FileEntry): file entry. Returns: str: hexadecimal representation of the MD5 hash value of the date and time values of the file entry. """ ...
Calculates an MD5 from the date and time value of a NTFS file entry. Args: file_entry (dfvfs.FileEntry): file entry. Returns: str: hexadecimal representation of the MD5 hash value of the date and time values of the file entry.
Below is the the instruction that describes the task: ### Input: Calculates an MD5 from the date and time value of a NTFS file entry. Args: file_entry (dfvfs.FileEntry): file entry. Returns: str: hexadecimal representation of the MD5 hash value of the date and time values of the file...
def persist(self): ''' Persist the modified schedule into <<configdir>>/<<default_include>>/_schedule.conf ''' config_dir = self.opts.get('conf_dir', None) if config_dir is None and 'conf_file' in self.opts: config_dir = os.path.dirname(self.opts['conf_file']) ...
Persist the modified schedule into <<configdir>>/<<default_include>>/_schedule.conf
Below is the the instruction that describes the task: ### Input: Persist the modified schedule into <<configdir>>/<<default_include>>/_schedule.conf ### Response: def persist(self): ''' Persist the modified schedule into <<configdir>>/<<default_include>>/_schedule.conf ''' config_di...
def call(self, method, params): """synchronous call. send a request and wait for a response. return a result. or raise RPCError exception if the peer sends us an error. """ msgid = self._endpoint.send_request(method, params) while True: if not self._e...
synchronous call. send a request and wait for a response. return a result. or raise RPCError exception if the peer sends us an error.
Below is the the instruction that describes the task: ### Input: synchronous call. send a request and wait for a response. return a result. or raise RPCError exception if the peer sends us an error. ### Response: def call(self, method, params): """synchronous call. send a r...
def find_ip(family=AF_INET, flavour="opendns"): """Find the publicly visible IP address of the current system. This uses public DNS infrastructure that implement a special DNS "hack" to return the IP address of the requester rather than some other address. :param family: address family, optional, defa...
Find the publicly visible IP address of the current system. This uses public DNS infrastructure that implement a special DNS "hack" to return the IP address of the requester rather than some other address. :param family: address family, optional, default AF_INET (ipv4) :param flavour: selector for pub...
Below is the the instruction that describes the task: ### Input: Find the publicly visible IP address of the current system. This uses public DNS infrastructure that implement a special DNS "hack" to return the IP address of the requester rather than some other address. :param family: address family, ...
def from_pb(cls, operation_pb, client, **caller_metadata): """Factory: construct an instance from a protobuf. :type operation_pb: :class:`~google.longrunning.operations_pb2.Operation` :param operation_pb: Protobuf to be parsed. :type client: object: must provide ``_operati...
Factory: construct an instance from a protobuf. :type operation_pb: :class:`~google.longrunning.operations_pb2.Operation` :param operation_pb: Protobuf to be parsed. :type client: object: must provide ``_operations_stub`` accessor. :param client: The client used to poll fo...
Below is the the instruction that describes the task: ### Input: Factory: construct an instance from a protobuf. :type operation_pb: :class:`~google.longrunning.operations_pb2.Operation` :param operation_pb: Protobuf to be parsed. :type client: object: must provide ``_operatio...
def getScreenDetails(self): """ Return list of attached monitors For each monitor (as dict), ``monitor["rect"]`` represents the screen as positioned in virtual screen. List is returned in device order, with the first element (0) representing the primary monitor. """ prim...
Return list of attached monitors For each monitor (as dict), ``monitor["rect"]`` represents the screen as positioned in virtual screen. List is returned in device order, with the first element (0) representing the primary monitor.
Below is the the instruction that describes the task: ### Input: Return list of attached monitors For each monitor (as dict), ``monitor["rect"]`` represents the screen as positioned in virtual screen. List is returned in device order, with the first element (0) representing the primary moni...
def nr_genes(self, build=None): """Return the number of hgnc genes in collection If build is used, return the number of genes of a certain build Returns: result() """ if build: LOG.info("Fetching all genes from build %s", build) else: ...
Return the number of hgnc genes in collection If build is used, return the number of genes of a certain build Returns: result()
Below is the the instruction that describes the task: ### Input: Return the number of hgnc genes in collection If build is used, return the number of genes of a certain build Returns: result() ### Response: def nr_genes(self, build=None): """Return the number of hgnc g...
def close_websockets(self): """ Close websocket connection to remote browser.""" self.log.info("Websocket Teardown called") for key in list(self.soclist.keys()): if self.soclist[key]: self.soclist[key].close() self.soclist.pop(key)
Close websocket connection to remote browser.
Below is the the instruction that describes the task: ### Input: Close websocket connection to remote browser. ### Response: def close_websockets(self): """ Close websocket connection to remote browser.""" self.log.info("Websocket Teardown called") for key in list(self.soclist.keys()): if self.soclist[key...
def commit(self): """Actually publish all of the messages on the active batch. .. note:: This method is non-blocking. It opens a new thread, which calls :meth:`_commit`, which does block. This synchronously sets the batch status to "starting", and then opens a ...
Actually publish all of the messages on the active batch. .. note:: This method is non-blocking. It opens a new thread, which calls :meth:`_commit`, which does block. This synchronously sets the batch status to "starting", and then opens a new thread, which handles act...
Below is the the instruction that describes the task: ### Input: Actually publish all of the messages on the active batch. .. note:: This method is non-blocking. It opens a new thread, which calls :meth:`_commit`, which does block. This synchronously sets the batch status ...
def _eval_once(saver, summary_writer, top_1_op, top_5_op, summary_op): """Runs Eval once. Args: saver: Saver. summary_writer: Summary writer. top_1_op: Top 1 op. top_5_op: Top 5 op. summary_op: Summary op. """ with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpo...
Runs Eval once. Args: saver: Saver. summary_writer: Summary writer. top_1_op: Top 1 op. top_5_op: Top 5 op. summary_op: Summary op.
Below is the the instruction that describes the task: ### Input: Runs Eval once. Args: saver: Saver. summary_writer: Summary writer. top_1_op: Top 1 op. top_5_op: Top 5 op. summary_op: Summary op. ### Response: def _eval_once(saver, summary_writer, top_1_op, top_5_op, summary_op): """Runs ...
def handle_offchain_secretreveal( target_state: TargetTransferState, state_change: ReceiveSecretReveal, channel_state: NettingChannelState, pseudo_random_generator: random.Random, block_number: BlockNumber, ) -> TransitionResult[TargetTransferState]: """ Validates and handles...
Validates and handles a ReceiveSecretReveal state change.
Below is the the instruction that describes the task: ### Input: Validates and handles a ReceiveSecretReveal state change. ### Response: def handle_offchain_secretreveal( target_state: TargetTransferState, state_change: ReceiveSecretReveal, channel_state: NettingChannelState, pseudo...
def set_textcolor(self, color): """set color for labels and axis text""" self.textcolor = color self.relabel() if callable(self.theme_color_callback): self.theme_color_callback(color, 'text')
set color for labels and axis text
Below is the the instruction that describes the task: ### Input: set color for labels and axis text ### Response: def set_textcolor(self, color): """set color for labels and axis text""" self.textcolor = color self.relabel() if callable(self.theme_color_callback): self.t...
def cut(text, length=50, replace_with="…"): """ Shortens text to @length, appends @replace_with to end of string if the string length is > @length @text: #str text to shortens @length: #int max length of string @replace_with: #str to replace chars beyond @length with .. ...
Shortens text to @length, appends @replace_with to end of string if the string length is > @length @text: #str text to shortens @length: #int max length of string @replace_with: #str to replace chars beyond @length with .. from vital.debug import cut cut...
Below is the the instruction that describes the task: ### Input: Shortens text to @length, appends @replace_with to end of string if the string length is > @length @text: #str text to shortens @length: #int max length of string @replace_with: #str to replace chars beyond @length wit...
def pars_in_groups(self): """ return a dictionary of parameter names in each parameter group. Returns: dictionary """ pargp = self.par_groups allpars = dict() for cpg in pargp: allpars[cpg] = [i for i in self.parameter_data.loc[self.param...
return a dictionary of parameter names in each parameter group. Returns: dictionary
Below is the the instruction that describes the task: ### Input: return a dictionary of parameter names in each parameter group. Returns: dictionary ### Response: def pars_in_groups(self): """ return a dictionary of parameter names in each parameter group. Returns: ...
async def request(self, request, addr, integrity_key=None, retransmissions=None): """ Execute a STUN transaction and return the response. """ assert request.transaction_id not in self.transactions if integrity_key is not None: request.add_message_integrity(integrity_...
Execute a STUN transaction and return the response.
Below is the the instruction that describes the task: ### Input: Execute a STUN transaction and return the response. ### Response: async def request(self, request, addr, integrity_key=None, retransmissions=None): """ Execute a STUN transaction and return the response. """ assert req...
def split_title(self, title, splitter): """\ Split the title to best part possible """ large_text_length = 0 large_text_index = 0 title_pieces = splitter.split(title) # find the largest title piece for i in range(len(title_pieces)): current = ...
\ Split the title to best part possible
Below is the the instruction that describes the task: ### Input: \ Split the title to best part possible ### Response: def split_title(self, title, splitter): """\ Split the title to best part possible """ large_text_length = 0 large_text_index = 0 title_piec...
def make_app(predictor: Predictor, field_names: List[str] = None, static_dir: str = None, sanitizer: Callable[[JsonDict], JsonDict] = None, title: str = "AllenNLP Demo") -> Flask: """ Creates a Flask app that serves up the provided ``Predictor`` along with...
Creates a Flask app that serves up the provided ``Predictor`` along with a front-end for interacting with it. If you want to use the built-in bare-bones HTML, you must provide the field names for the inputs (which will be used both as labels and as the keys in the JSON that gets sent to the predictor)....
Below is the the instruction that describes the task: ### Input: Creates a Flask app that serves up the provided ``Predictor`` along with a front-end for interacting with it. If you want to use the built-in bare-bones HTML, you must provide the field names for the inputs (which will be used both as lab...
def get_all_nodes(self, simrun_addr, stmt_idx): """ Get all DDG nodes matching the given basic block address and statement index. """ nodes=[] for n in self.graph.nodes(): if n.simrun_addr == simrun_addr and n.stmt_idx == stmt_idx: nodes.add(n) ...
Get all DDG nodes matching the given basic block address and statement index.
Below is the the instruction that describes the task: ### Input: Get all DDG nodes matching the given basic block address and statement index. ### Response: def get_all_nodes(self, simrun_addr, stmt_idx): """ Get all DDG nodes matching the given basic block address and statement index. """ ...
def HandleFilterMaxComponentLimit(handle, lfilter): """ Method checks the filter count and if the filter count exceeds the maxComponents(number of filters), then the given filter objects get distributed among small groups and then again binded together in complex filters(like and , or) so that the count of filt...
Method checks the filter count and if the filter count exceeds the maxComponents(number of filters), then the given filter objects get distributed among small groups and then again binded together in complex filters(like and , or) so that the count of filters can be reduced.
Below is the the instruction that describes the task: ### Input: Method checks the filter count and if the filter count exceeds the maxComponents(number of filters), then the given filter objects get distributed among small groups and then again binded together in complex filters(like and , or) so that the coun...
def emulate_seek(fd, offset, chunk=CHUNK): """ Emulates a seek on an object that does not support it The seek is emulated by reading and discarding bytes until specified offset is reached. The ``offset`` argument is in bytes from start of file. The ``chunk`` argument can be used to adjust the size...
Emulates a seek on an object that does not support it The seek is emulated by reading and discarding bytes until specified offset is reached. The ``offset`` argument is in bytes from start of file. The ``chunk`` argument can be used to adjust the size of the chunks in which read operation is perfo...
Below is the the instruction that describes the task: ### Input: Emulates a seek on an object that does not support it The seek is emulated by reading and discarding bytes until specified offset is reached. The ``offset`` argument is in bytes from start of file. The ``chunk`` argument can be used ...
def fields_to_dict(self): """Transform the object to a dict and return the dict.""" d = {} for container in FieldsContainer.class_container.values(): fields = getattr(self, container) if fields: d[container] = [field.to_dict() for field in fields] ...
Transform the object to a dict and return the dict.
Below is the the instruction that describes the task: ### Input: Transform the object to a dict and return the dict. ### Response: def fields_to_dict(self): """Transform the object to a dict and return the dict.""" d = {} for container in FieldsContainer.class_container.values(): ...
def json_decoder(content, *args, **kwargs): """ Json decoder parser to be used by service_client """ if not content: return None json_value = content.decode() return json.loads(json_value)
Json decoder parser to be used by service_client
Below is the the instruction that describes the task: ### Input: Json decoder parser to be used by service_client ### Response: def json_decoder(content, *args, **kwargs): """ Json decoder parser to be used by service_client """ if not content: return None json_value = content.decode() ...
def _validate_opts(opts): ''' Check that all of the types of values passed into the config are of the right types ''' def format_multi_opt(valid_type): try: num_types = len(valid_type) except TypeError: # Bare type name won't have a length, return the name of ...
Check that all of the types of values passed into the config are of the right types
Below is the the instruction that describes the task: ### Input: Check that all of the types of values passed into the config are of the right types ### Response: def _validate_opts(opts): ''' Check that all of the types of values passed into the config are of the right types ''' def format...
def Reboot(self, destination=b''): """Reboot the device. Args: destination: Specify 'bootloader' for fastboot. """ self.protocol_handler.Open(self._handle, b'reboot:%s' % destination)
Reboot the device. Args: destination: Specify 'bootloader' for fastboot.
Below is the the instruction that describes the task: ### Input: Reboot the device. Args: destination: Specify 'bootloader' for fastboot. ### Response: def Reboot(self, destination=b''): """Reboot the device. Args: destination: Specify 'bootloader' for fastboot. ...
def get_active_state(self) -> Optional[str]: """Get the name of the active run state from the ZoneMinder API.""" for state in self.get_run_states(): if state.active: return state.name return None
Get the name of the active run state from the ZoneMinder API.
Below is the the instruction that describes the task: ### Input: Get the name of the active run state from the ZoneMinder API. ### Response: def get_active_state(self) -> Optional[str]: """Get the name of the active run state from the ZoneMinder API.""" for state in self.get_run_states(): ...
def set_itunes_duration(self): """Parses duration from itunes tags and sets value""" try: self.itunes_duration = self.soup.find('itunes:duration').string except AttributeError: self.itunes_duration = None
Parses duration from itunes tags and sets value
Below is the the instruction that describes the task: ### Input: Parses duration from itunes tags and sets value ### Response: def set_itunes_duration(self): """Parses duration from itunes tags and sets value""" try: self.itunes_duration = self.soup.find('itunes:duration').string ...
def hybrid_forward(self, F, x, sampled_values, label, weight, bias): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = F.reshape(label, shape=(-1,)) # (num_sampled+batch_size,) ids = F.concat(sampled_candidates, label, dim=0) ...
Forward computation.
Below is the the instruction that describes the task: ### Input: Forward computation. ### Response: def hybrid_forward(self, F, x, sampled_values, label, weight, bias): """Forward computation.""" sampled_candidates, _, _ = sampled_values # (batch_size,) label = F.reshape(label, shap...
def check_without_your_collusion(text): """Check the textself.""" err = "misc.illogic.collusion" msg = "It's impossible to defraud yourself. Try 'aquiescence'." regex = "without your collusion" return existence_check( text, [regex], err, msg, require_padding=False, offset=-1)
Check the textself.
Below is the the instruction that describes the task: ### Input: Check the textself. ### Response: def check_without_your_collusion(text): """Check the textself.""" err = "misc.illogic.collusion" msg = "It's impossible to defraud yourself. Try 'aquiescence'." regex = "without your collusion" ...
def get_quadwell_data(ntraj=10, nstep=10000, x0=0., nskip=1, dt=0.001, kT=1.0, mass=1.0, damping=1.0): r""" Performs a Brownian dynamics simulation in the Prinz potential (quad well). Parameters ---------- ntraj: int, default=10 how many realizations will be computed nstep: int, default=100...
r""" Performs a Brownian dynamics simulation in the Prinz potential (quad well). Parameters ---------- ntraj: int, default=10 how many realizations will be computed nstep: int, default=10000 number of time steps x0: float, default 0 starting point for sampling nskip: int...
Below is the the instruction that describes the task: ### Input: r""" Performs a Brownian dynamics simulation in the Prinz potential (quad well). Parameters ---------- ntraj: int, default=10 how many realizations will be computed nstep: int, default=10000 number of time steps x0...
def compare_enums(autogen_context, upgrade_ops, schema_names): """ Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG schema for every definde Enum, then generate SyncEnumValuesOp migrations for each defined enum that has grown new entries when compared to its declared versio...
Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG schema for every definde Enum, then generate SyncEnumValuesOp migrations for each defined enum that has grown new entries when compared to its declared version. Enums that don't exist in the database yet are ignored, since S...
Below is the the instruction that describes the task: ### Input: Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG schema for every definde Enum, then generate SyncEnumValuesOp migrations for each defined enum that has grown new entries when compared to its declared version. ...
def create_choice_model(data, alt_id_col, obs_id_col, choice_col, specification, model_type, intercept_ref_pos=None, shape_ref_pos=None, ...
Parameters ---------- data : string or pandas dataframe. If `data` is a string, it should be an absolute or relative path to a CSV file containing the long format data for this choice model. Note long format has one row per available alternative for each observation. If `data` is...
Below is the the instruction that describes the task: ### Input: Parameters ---------- data : string or pandas dataframe. If `data` is a string, it should be an absolute or relative path to a CSV file containing the long format data for this choice model. Note long format has one row...
def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ''' Helper function to call initdb ''' if runas is None: if 'FreeBSD' in __grains__['os_family...
Helper function to call initdb
Below is the the instruction that describes the task: ### Input: Helper function to call initdb ### Response: def _run_initdb(name, auth='password', user=None, password=None, encoding='UTF8', locale=None, runas=None, waldir=None, checksums=False): ...
def write_county_estimate(self, table, variable, code, datum): """ Creates new estimate from a census series. Data has following signature from API: { 'B00001_001E': '5373', 'NAME': 'Anderson County, Texas', 'county': '001', 'state': '4...
Creates new estimate from a census series. Data has following signature from API: { 'B00001_001E': '5373', 'NAME': 'Anderson County, Texas', 'county': '001', 'state': '48' }
Below is the the instruction that describes the task: ### Input: Creates new estimate from a census series. Data has following signature from API: { 'B00001_001E': '5373', 'NAME': 'Anderson County, Texas', 'county': '001', 'state': '48' } #...
def random_get_int(rnd: Optional[tcod.random.Random], mi: int, ma: int) -> int: """Return a random integer in the range: ``mi`` <= n <= ``ma``. The result is affected by calls to :any:`random_set_distribution`. Args: rnd (Optional[Random]): A Random instance, or None to use the default. lo...
Return a random integer in the range: ``mi`` <= n <= ``ma``. The result is affected by calls to :any:`random_set_distribution`. Args: rnd (Optional[Random]): A Random instance, or None to use the default. low (int): The lower bound of the random range, inclusive. high (int): The upper ...
Below is the the instruction that describes the task: ### Input: Return a random integer in the range: ``mi`` <= n <= ``ma``. The result is affected by calls to :any:`random_set_distribution`. Args: rnd (Optional[Random]): A Random instance, or None to use the default. low (int): The lower...
def clean(self, text, guess=True, format=None, **kwargs): """The classic: date parsing, every which way.""" # handle date/datetime before converting to text. date = self._clean_datetime(text) if date is not None: return date text = stringify(text) if text is ...
The classic: date parsing, every which way.
Below is the the instruction that describes the task: ### Input: The classic: date parsing, every which way. ### Response: def clean(self, text, guess=True, format=None, **kwargs): """The classic: date parsing, every which way.""" # handle date/datetime before converting to text. date = sel...
async def postprocess_websocket( self, response: Optional[Response], websocket_context: Optional[WebsocketContext]=None, ) -> Response: """Postprocess the websocket acting on the response. Arguments: response: The response after the websocket is finalized. ...
Postprocess the websocket acting on the response. Arguments: response: The response after the websocket is finalized. webcoket_context: The websocket context, optional as Flask omits this argument.
Below is the the instruction that describes the task: ### Input: Postprocess the websocket acting on the response. Arguments: response: The response after the websocket is finalized. webcoket_context: The websocket context, optional as Flask omits this argument. ### ...
def vzero(v): """ Indicate whether a 3-vector is the zero vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vzero_c.html :param v: Vector to be tested :type v: 3-Element Array of floats :return: true if and only if v is the zero vector :rtype: bool """ v = stypes.toD...
Indicate whether a 3-vector is the zero vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vzero_c.html :param v: Vector to be tested :type v: 3-Element Array of floats :return: true if and only if v is the zero vector :rtype: bool
Below is the the instruction that describes the task: ### Input: Indicate whether a 3-vector is the zero vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vzero_c.html :param v: Vector to be tested :type v: 3-Element Array of floats :return: true if and only if v is the zero vector ...
def whitespace_around_keywords(logical_line): r"""Avoid extraneous whitespace around keywords. Okay: True and False E271: True and False E272: True and False E273: True and\tFalse E274: True\tand False """ for match in KEYWORD_REGEX.finditer(logical_line): before, after = matc...
r"""Avoid extraneous whitespace around keywords. Okay: True and False E271: True and False E272: True and False E273: True and\tFalse E274: True\tand False
Below is the the instruction that describes the task: ### Input: r"""Avoid extraneous whitespace around keywords. Okay: True and False E271: True and False E272: True and False E273: True and\tFalse E274: True\tand False ### Response: def whitespace_around_keywords(logical_line): r"""Avo...