code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _showItemContextMenu(self, item, point, col): """Callback for contextMenuRequested() signal. Pops up item menu, if defined""" menu = getattr(item, '_menu', None) if menu: settitle = getattr(item, '_set_menu_title', None) if settitle: settitle() ...
Callback for contextMenuRequested() signal. Pops up item menu, if defined
Below is the the instruction that describes the task: ### Input: Callback for contextMenuRequested() signal. Pops up item menu, if defined ### Response: def _showItemContextMenu(self, item, point, col): """Callback for contextMenuRequested() signal. Pops up item menu, if defined""" menu = getattr(i...
def info(message, *args, **kwargs): """ write a message to stdout """ if 'end' in kwargs: end = kwargs['end'] else: end = '\n' if len(args) == 0: sys.stdout.write(message) else: sys.stdout.write(message % args) sys.stdout.write(end) sys.stdout.flush(...
write a message to stdout
Below is the the instruction that describes the task: ### Input: write a message to stdout ### Response: def info(message, *args, **kwargs): """ write a message to stdout """ if 'end' in kwargs: end = kwargs['end'] else: end = '\n' if len(args) == 0: sys.stdout.wri...
def friendships_destroy(self, user_id=None, screen_name=None): """ Allows the authenticating user to unfollow the specified user. https://dev.twitter.com/docs/api/1.1/post/friendships/destroy :param str user_id: The screen name of the user for whom to unfollow. Required if ...
Allows the authenticating user to unfollow the specified user. https://dev.twitter.com/docs/api/1.1/post/friendships/destroy :param str user_id: The screen name of the user for whom to unfollow. Required if ``screen_name`` isn't given. :param str screen_name: ...
Below is the the instruction that describes the task: ### Input: Allows the authenticating user to unfollow the specified user. https://dev.twitter.com/docs/api/1.1/post/friendships/destroy :param str user_id: The screen name of the user for whom to unfollow. Required if ``...
def frame_msg_ipc(body, header=None, raw_body=False): # pylint: disable=unused-argument ''' Frame the given message with our wire protocol for IPC For IPC, we don't need to be backwards compatible, so use the more efficient "use_bin_type=True" on Python 3. ''' framed_msg = {} if header is ...
Frame the given message with our wire protocol for IPC For IPC, we don't need to be backwards compatible, so use the more efficient "use_bin_type=True" on Python 3.
Below is the the instruction that describes the task: ### Input: Frame the given message with our wire protocol for IPC For IPC, we don't need to be backwards compatible, so use the more efficient "use_bin_type=True" on Python 3. ### Response: def frame_msg_ipc(body, header=None, raw_body=False): # pylin...
def getBetas(idxPrc, aryPrfTc, lstAllMdlInd, aryFuncChnk, aryBstIndChnk, betaSw, queOut): """Calculate voxel betas and R^2 for the best model. Parameters ---------- idxPrc : TODO (?) aryPrfTc : np.array, shape (?)...
Calculate voxel betas and R^2 for the best model. Parameters ---------- idxPrc : TODO (?) aryPrfTc : np.array, shape (?) Population receptive field time courses. lstAllMdlInd : list List of the indices of all models. aryFuncChnk : TODO Chunk of something(?) a...
Below is the the instruction that describes the task: ### Input: Calculate voxel betas and R^2 for the best model. Parameters ---------- idxPrc : TODO (?) aryPrfTc : np.array, shape (?) Population receptive field time courses. lstAllMdlInd : list List of the indices of a...
def parse_pkginfo(line, osarch=None): ''' A small helper to parse an rpm/repoquery command's output. Returns a pkginfo namedtuple. ''' try: name, epoch, version, release, arch, repoid, install_time = line.split('_|-') # Handle unpack errors (should never happen with the queryformat we ar...
A small helper to parse an rpm/repoquery command's output. Returns a pkginfo namedtuple.
Below is the the instruction that describes the task: ### Input: A small helper to parse an rpm/repoquery command's output. Returns a pkginfo namedtuple. ### Response: def parse_pkginfo(line, osarch=None): ''' A small helper to parse an rpm/repoquery command's output. Returns a pkginfo namedtuple. ...
def format_close(code: int, reason: str) -> str: """ Display a human-readable version of the close code and reason. """ if 3000 <= code < 4000: explanation = "registered" elif 4000 <= code < 5000: explanation = "private use" else: explanation = CLOSE_CODES.get(code, "un...
Display a human-readable version of the close code and reason.
Below is the the instruction that describes the task: ### Input: Display a human-readable version of the close code and reason. ### Response: def format_close(code: int, reason: str) -> str: """ Display a human-readable version of the close code and reason. """ if 3000 <= code < 4000: exp...
def get_context(self): """ returns the context dict for this statement :rtype: dict """ ctx = {} for clause in self.where_clauses or []: clause.update_context(ctx) return ctx
returns the context dict for this statement :rtype: dict
Below is the the instruction that describes the task: ### Input: returns the context dict for this statement :rtype: dict ### Response: def get_context(self): """ returns the context dict for this statement :rtype: dict """ ctx = {} for clause in self.where_c...
def _create_all_tables(self): """ Creates all the required tables by calling the required functions. :return: """ self._create_post_table() self._create_tag_table() self._create_tag_posts_table() self._create_user_posts_table()
Creates all the required tables by calling the required functions. :return:
Below is the the instruction that describes the task: ### Input: Creates all the required tables by calling the required functions. :return: ### Response: def _create_all_tables(self): """ Creates all the required tables by calling the required functions. :return: """ ...
def _process_module_needs(self, modules): """Adds the module and its dependencies to the result list in dependency order.""" result = list(modules) for i, module in enumerate(modules): #It is possible that the parser couldn't find it, if so #we can't create the executable...
Adds the module and its dependencies to the result list in dependency order.
Below is the the instruction that describes the task: ### Input: Adds the module and its dependencies to the result list in dependency order. ### Response: def _process_module_needs(self, modules): """Adds the module and its dependencies to the result list in dependency order.""" result = list(modu...
def print_torrent(self): """ Print the details of a torrent """ print('Title: %s' % self.title) print('URL: %s' % self.url) print('Category: %s' % self.category) print('Sub-Category: %s' % self.sub_category) print('Magnet Link: %s' % self.magnet_link) ...
Print the details of a torrent
Below is the the instruction that describes the task: ### Input: Print the details of a torrent ### Response: def print_torrent(self): """ Print the details of a torrent """ print('Title: %s' % self.title) print('URL: %s' % self.url) print('Category: %s' % self.categ...
def install(args: List[str]) -> None: """`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16....
`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16.9MB 53kB/s Installing collected packa...
Below is the the instruction that describes the task: ### Input: `pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB)...
def discover_roku(): """ Search LAN for available Roku devices. Returns a Roku object. """ print("Searching for Roku devices within LAN ...") rokus = Roku.discover() if not rokus: print("Unable to discover Roku devices. " + "Try again, or manually specify the IP address with " + ...
Search LAN for available Roku devices. Returns a Roku object.
Below is the the instruction that describes the task: ### Input: Search LAN for available Roku devices. Returns a Roku object. ### Response: def discover_roku(): """ Search LAN for available Roku devices. Returns a Roku object. """ print("Searching for Roku devices within LAN ...") rokus = Roku.discov...
def get_registered(option_hooks=None, event_hooks=None, command_hooks=None, root_access=None, task_active=True): """ Returns a generator of registered plugins matching filters. `option_hooks` Boolean to include or exclude plugins using option hooks. ...
Returns a generator of registered plugins matching filters. `option_hooks` Boolean to include or exclude plugins using option hooks. `event_hooks` Boolean to include or exclude task event plugins. `command_hooks` Boolean to include or exclude command plugins....
Below is the the instruction that describes the task: ### Input: Returns a generator of registered plugins matching filters. `option_hooks` Boolean to include or exclude plugins using option hooks. `event_hooks` Boolean to include or exclude task event plugins. `comm...
def parse_definition(self, class_): """Parse a definition and return its value in a `class_` object.""" start = self.line self.consume(tk.NAME) name = self.current.value self.log.debug("parsing %s '%s'", class_.__name__, name) self.stream.move() if self.current.ki...
Parse a definition and return its value in a `class_` object.
Below is the the instruction that describes the task: ### Input: Parse a definition and return its value in a `class_` object. ### Response: def parse_definition(self, class_): """Parse a definition and return its value in a `class_` object.""" start = self.line self.consume(tk.NAME) ...
def _check_align(self): """Check if alignment has been specified, set default one if not """ if not hasattr(self, "_align"): self._align = ["l"]*self._row_size if not hasattr(self, "_valign"): self._valign = ["t"]*self._row_size
Check if alignment has been specified, set default one if not
Below is the the instruction that describes the task: ### Input: Check if alignment has been specified, set default one if not ### Response: def _check_align(self): """Check if alignment has been specified, set default one if not """ if not hasattr(self, "_align"): self._align ...
def noise_normalization_from_noise_map_and_mask(noise_map, mask): """Compute the noise-map normalization terms of a list of masked 1D noise-maps, summing the noise_map vale in every pixel as: [Noise_Term] = sum(log(2*pi*[Noise]**2.0)) Parameters ---------- noise_map : np.ndarray The ma...
Compute the noise-map normalization terms of a list of masked 1D noise-maps, summing the noise_map vale in every pixel as: [Noise_Term] = sum(log(2*pi*[Noise]**2.0)) Parameters ---------- noise_map : np.ndarray The masked noise-map of the observed data. mask : np.ndarray The ma...
Below is the the instruction that describes the task: ### Input: Compute the noise-map normalization terms of a list of masked 1D noise-maps, summing the noise_map vale in every pixel as: [Noise_Term] = sum(log(2*pi*[Noise]**2.0)) Parameters ---------- noise_map : np.ndarray The masked...
def show_guidance_msg(self, unique_id, input_lines, hash_key, guidance_flag=False): """ Based on the student's answer (input_lines), we grab each associated message if its corresponding misunderstanding's count is above the threshold """ if self.load_err...
Based on the student's answer (input_lines), we grab each associated message if its corresponding misunderstanding's count is above the threshold
Below is the the instruction that describes the task: ### Input: Based on the student's answer (input_lines), we grab each associated message if its corresponding misunderstanding's count is above the threshold ### Response: def show_guidance_msg(self, unique_id, input_lines, hash_key, ...
def eslint_supportdir(self, task_workdir): """ Returns the path where the ESLint is bootstrapped. :param string task_workdir: The task's working directory :returns: The path where ESLint is bootstrapped and whether or not it is configured :rtype: (string, bool) """ bootstrapped_support_path = o...
Returns the path where the ESLint is bootstrapped. :param string task_workdir: The task's working directory :returns: The path where ESLint is bootstrapped and whether or not it is configured :rtype: (string, bool)
Below is the the instruction that describes the task: ### Input: Returns the path where the ESLint is bootstrapped. :param string task_workdir: The task's working directory :returns: The path where ESLint is bootstrapped and whether or not it is configured :rtype: (string, bool) ### Response: def esli...
def get_curie_map(url): """ Get CURIE prefix map from SciGraph cypher/curies endpoint """ curie_map = {} response = requests.get(url) if response.status_code == 200: curie_map = response.json() else: curie_map = {} return curie_map
Get CURIE prefix map from SciGraph cypher/curies endpoint
Below is the the instruction that describes the task: ### Input: Get CURIE prefix map from SciGraph cypher/curies endpoint ### Response: def get_curie_map(url): """ Get CURIE prefix map from SciGraph cypher/curies endpoint """ curie_map = {} response = requests.get(url) if response.status_c...
def download(url, save_to_file=True, save_dir=".", filename=None, block_size=64000, overwrite=False, quiet=False): """ Download a given URL to either file or memory :param url: Full url (with protocol) of path to download :param save_to_file: boolean if it should be saved to file or not ...
Download a given URL to either file or memory :param url: Full url (with protocol) of path to download :param save_to_file: boolean if it should be saved to file or not :param save_dir: location of saved file, default is current working dir :param filename: filename to save as :param block_size: do...
Below is the the instruction that describes the task: ### Input: Download a given URL to either file or memory :param url: Full url (with protocol) of path to download :param save_to_file: boolean if it should be saved to file or not :param save_dir: location of saved file, default is current working d...
def __download(self, url, loaded_schemata, options): """Download the schema.""" try: reader = DocumentReader(options) d = reader.open(url) root = d.root() root.set("url", url) return self.schema.instance(root, url, loaded_schemata, options) ...
Download the schema.
Below is the the instruction that describes the task: ### Input: Download the schema. ### Response: def __download(self, url, loaded_schemata, options): """Download the schema.""" try: reader = DocumentReader(options) d = reader.open(url) root = d.root() ...
def _target_stmt(self, stmt: object) -> tuple: """ takes the target key from kwargs and processes it to aid in the generation of a model statement :param stmt: str, list, or dict that contains the model information. :return: tuple of strings one for the class statement one for the model ...
takes the target key from kwargs and processes it to aid in the generation of a model statement :param stmt: str, list, or dict that contains the model information. :return: tuple of strings one for the class statement one for the model statements
Below is the the instruction that describes the task: ### Input: takes the target key from kwargs and processes it to aid in the generation of a model statement :param stmt: str, list, or dict that contains the model information. :return: tuple of strings one for the class statement one for the mode...
def import_data( self, resource_group_name, name, files, format=None, custom_headers=None, raw=False, polling=True, **operation_config): """Import data into Redis cache. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param name: T...
Import data into Redis cache. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param name: The name of the Redis cache. :type name: str :param files: files to import. :type files: list[str] :param format: File format. ...
Below is the the instruction that describes the task: ### Input: Import data into Redis cache. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param name: The name of the Redis cache. :type name: str :param files: files to import. ...
def get_subscription_labels(self, userPk): """Returns a list with all the labels the user is subscribed to""" r = self._request('subscriptions/' + str(userPk)) if r: s = r.json() return s return []
Returns a list with all the labels the user is subscribed to
Below is the the instruction that describes the task: ### Input: Returns a list with all the labels the user is subscribed to ### Response: def get_subscription_labels(self, userPk): """Returns a list with all the labels the user is subscribed to""" r = self._request('subscriptions/' + str(userPk))...
def parse_uri(self, uri=None): ''' parses and cleans up possible uri inputs, return instance of rdflib.term.URIRef Args: uri (rdflib.term.URIRef,str): input URI Returns: rdflib.term.URIRef ''' # no uri provided, assume root if not uri: return rdflib.term.URIRef(self.root) # string uri prov...
parses and cleans up possible uri inputs, return instance of rdflib.term.URIRef Args: uri (rdflib.term.URIRef,str): input URI Returns: rdflib.term.URIRef
Below is the the instruction that describes the task: ### Input: parses and cleans up possible uri inputs, return instance of rdflib.term.URIRef Args: uri (rdflib.term.URIRef,str): input URI Returns: rdflib.term.URIRef ### Response: def parse_uri(self, uri=None): ''' parses and cleans up possible ...
def write_summaries(self, tagged_data, experiment_name, run_name): """Transactionally writes the given tagged summary data to the DB. Args: tagged_data: map from tag to TagData instances. experiment_name: name of experiment. run_name: name of run. """ logger.debug('Writing summaries f...
Transactionally writes the given tagged summary data to the DB. Args: tagged_data: map from tag to TagData instances. experiment_name: name of experiment. run_name: name of run.
Below is the the instruction that describes the task: ### Input: Transactionally writes the given tagged summary data to the DB. Args: tagged_data: map from tag to TagData instances. experiment_name: name of experiment. run_name: name of run. ### Response: def write_summaries(self, tagged_da...
def face_encodings(face_image, known_face_locations=None, num_jitters=1): """ Given an image, return the 128-dimension face encoding for each face in the image. :param face_image: The image that contains one or more faces :param known_face_locations: Optional - the bounding boxes of each face if you al...
Given an image, return the 128-dimension face encoding for each face in the image. :param face_image: The image that contains one or more faces :param known_face_locations: Optional - the bounding boxes of each face if you already know them. :param num_jitters: How many times to re-sample the face when cal...
Below is the the instruction that describes the task: ### Input: Given an image, return the 128-dimension face encoding for each face in the image. :param face_image: The image that contains one or more faces :param known_face_locations: Optional - the bounding boxes of each face if you already know them. ...
def start_logging(Name, region=None, key=None, keyid=None, profile=None): ''' Start logging for a trail Returns {started: true} if the trail was started and returns {started: False} if the trail was not started. CLI Example: .. code-block:: bash salt myminion boto_cloudtra...
Start logging for a trail Returns {started: true} if the trail was started and returns {started: False} if the trail was not started. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.start_logging my_trail
Below is the the instruction that describes the task: ### Input: Start logging for a trail Returns {started: true} if the trail was started and returns {started: False} if the trail was not started. CLI Example: .. code-block:: bash salt myminion boto_cloudtrail.start_logging my_trail ##...
def serialize_acquire_mutex(self, spec): """ Serializer for :meth:`SpiffWorkflow.specs.AcquireMutex`. """ elem = etree.Element('acquire-mutex') self.serialize_task_spec(spec, elem) SubElement(elem, 'mutex').text = spec.mutex return elem
Serializer for :meth:`SpiffWorkflow.specs.AcquireMutex`.
Below is the the instruction that describes the task: ### Input: Serializer for :meth:`SpiffWorkflow.specs.AcquireMutex`. ### Response: def serialize_acquire_mutex(self, spec): """ Serializer for :meth:`SpiffWorkflow.specs.AcquireMutex`. """ elem = etree.Element('acquire-mutex') ...
def view(self, view): ''' View the wiki. ''' kwd = { 'pager': '', 'editable': self.editable(), } self.render('wiki_page/wiki_view.html', postinfo=view, kwd=kwd, userinfo=self.userinfo)
View the wiki.
Below is the the instruction that describes the task: ### Input: View the wiki. ### Response: def view(self, view): ''' View the wiki. ''' kwd = { 'pager': '', 'editable': self.editable(), } self.render('wiki_page/wiki_view.html', ...
def show_view(self): """ Show :attr:`LoginForm` form. """ self.current.output['login_process'] = True if self.current.is_auth: self._do_upgrade() else: self.current.output['forms'] = LoginForm(current=self.current).serialize()
Show :attr:`LoginForm` form.
Below is the the instruction that describes the task: ### Input: Show :attr:`LoginForm` form. ### Response: def show_view(self): """ Show :attr:`LoginForm` form. """ self.current.output['login_process'] = True if self.current.is_auth: self._do_upgrade() e...
def newton(self, start_x=None, tolerance=1.0e-6): """ Optimise value of x using newton gauss """ if start_x is None: start_x = self._analytical_fitter.fit(self._c) return optimise_newton(start_x, self._a, self._c, tolerance)
Optimise value of x using newton gauss
Below is the the instruction that describes the task: ### Input: Optimise value of x using newton gauss ### Response: def newton(self, start_x=None, tolerance=1.0e-6): """ Optimise value of x using newton gauss """ if start_x is None: start_x = self._analytical_fitter.fi...
def make_query(self, return_score=False): """Return the index of the sample to be queried and labeled and selection score of each sample. Read-only. No modification to the internal states. Returns ------- ask_id : int The index of the next unlabeled sample t...
Return the index of the sample to be queried and labeled and selection score of each sample. Read-only. No modification to the internal states. Returns ------- ask_id : int The index of the next unlabeled sample to be queried and labeled. score : list of (i...
Below is the the instruction that describes the task: ### Input: Return the index of the sample to be queried and labeled and selection score of each sample. Read-only. No modification to the internal states. Returns ------- ask_id : int The index of the next un...
def collection_get_options(collection_name, **kwargs): ''' Get collection options Additional parameters (kwargs) may be passed, they will be proxied to http.query CLI Example: .. code-block:: bash salt '*' solrcloud.collection_get_options collection_name ''' cluster = cluster_st...
Get collection options Additional parameters (kwargs) may be passed, they will be proxied to http.query CLI Example: .. code-block:: bash salt '*' solrcloud.collection_get_options collection_name
Below is the the instruction that describes the task: ### Input: Get collection options Additional parameters (kwargs) may be passed, they will be proxied to http.query CLI Example: .. code-block:: bash salt '*' solrcloud.collection_get_options collection_name ### Response: def collection_g...
async def _transmit(self): """ Transmit outbound data. """ # send FORWARD TSN if self._forward_tsn_chunk is not None: await self._send_chunk(self._forward_tsn_chunk) self._forward_tsn_chunk = None # ensure T3 is running if not self...
Transmit outbound data.
Below is the the instruction that describes the task: ### Input: Transmit outbound data. ### Response: async def _transmit(self): """ Transmit outbound data. """ # send FORWARD TSN if self._forward_tsn_chunk is not None: await self._send_chunk(self._forward_tsn_c...
def _write_stop_to_stop_network_edges(net, file_name, data=True, fmt=None): """ Write out a network Parameters ---------- net: networkx.DiGraph base_name: str path to the filename (without extension) data: bool, optional whether or not to write out any edge data present ...
Write out a network Parameters ---------- net: networkx.DiGraph base_name: str path to the filename (without extension) data: bool, optional whether or not to write out any edge data present fmt: str, optional If "csv" write out the network in csv format.
Below is the the instruction that describes the task: ### Input: Write out a network Parameters ---------- net: networkx.DiGraph base_name: str path to the filename (without extension) data: bool, optional whether or not to write out any edge data present fmt: str, optional ...
def dfs_edges(G, start, depth_limit=1, get_only=True, get_path=False): """Deepest first search.""" depth_limit = depth_limit - 1 # creates unsigned int array (2 Byte) output_nodes = array('L') output_depth = array('I') # creates float array (4 Byte) output_weights = array('f') apath = [...
Deepest first search.
Below is the the instruction that describes the task: ### Input: Deepest first search. ### Response: def dfs_edges(G, start, depth_limit=1, get_only=True, get_path=False): """Deepest first search.""" depth_limit = depth_limit - 1 # creates unsigned int array (2 Byte) output_nodes = array('L') ...
def prepare_request(self, method, url, body=''): """Prepare the request body and headers :returns: headers of the signed request """ headers = { 'Content-type': 'application/json', } # Note: we don't pass body to sign() since it's only for bodies that ...
Prepare the request body and headers :returns: headers of the signed request
Below is the the instruction that describes the task: ### Input: Prepare the request body and headers :returns: headers of the signed request ### Response: def prepare_request(self, method, url, body=''): """Prepare the request body and headers :returns: headers of the signed request ...
def save(self, running=None): """ save or update this cached gear into the Ariane server cache :param running: the new running value. if None ignored :return: """ LOGGER.debug("InjectorCachedGear.save") ret = True if running is not None: self....
save or update this cached gear into the Ariane server cache :param running: the new running value. if None ignored :return:
Below is the the instruction that describes the task: ### Input: save or update this cached gear into the Ariane server cache :param running: the new running value. if None ignored :return: ### Response: def save(self, running=None): """ save or update this cached gear into the Aria...
def mk_example(): """mk_example: book example for the single item lot sizing""" T = 5 _,f,c,d,h = multidict({ 1 : [3,1,5,1], 2 : [3,1,7,1], 3 : [3,3,3,1], 4 : [3,3,6,1], 5 : [3,3,4,1], }) return T,f,c,d,h
mk_example: book example for the single item lot sizing
Below is the the instruction that describes the task: ### Input: mk_example: book example for the single item lot sizing ### Response: def mk_example(): """mk_example: book example for the single item lot sizing""" T = 5 _,f,c,d,h = multidict({ 1 : [3,1,5,1], 2 : [3,1,7,1], 3 ...
def _proxy_conf_file(proxyfile, test): ''' Check if proxy conf exists and update ''' changes_old = [] changes_new = [] success = True if not os.path.exists(proxyfile): try: if not test: changes_new.append(_write_proxy_conf(proxyfile)) msg =...
Check if proxy conf exists and update
Below is the the instruction that describes the task: ### Input: Check if proxy conf exists and update ### Response: def _proxy_conf_file(proxyfile, test): ''' Check if proxy conf exists and update ''' changes_old = [] changes_new = [] success = True if not os.path.exists(proxyfile): ...
def _compare_areas(self, datasets=None, compare_func=max): """Get for the provided datasets. Args: datasets (iterable): Datasets whose areas will be compared. Can be either `xarray.DataArray` objects or identifiers to get th...
Get for the provided datasets. Args: datasets (iterable): Datasets whose areas will be compared. Can be either `xarray.DataArray` objects or identifiers to get the DataArrays from the current Scene. ...
Below is the the instruction that describes the task: ### Input: Get for the provided datasets. Args: datasets (iterable): Datasets whose areas will be compared. Can be either `xarray.DataArray` objects or identifiers to get the...
def linked(base_dir: str, rr_id: str) -> str: """ Get, from the specified directory, the path to the tails file associated with the input revocation registry identifier, or None for no such file. :param base_dir: base directory for tails files, thereafter split by cred def id :p...
Get, from the specified directory, the path to the tails file associated with the input revocation registry identifier, or None for no such file. :param base_dir: base directory for tails files, thereafter split by cred def id :param rr_id: rev reg id :return: (stringified) path to tail...
Below is the the instruction that describes the task: ### Input: Get, from the specified directory, the path to the tails file associated with the input revocation registry identifier, or None for no such file. :param base_dir: base directory for tails files, thereafter split by cred def id ...
def _ee_decode(self, msg): """EE: Entry/exit timer report.""" return {'area': int(msg[4:5])-1, 'is_exit': msg[5:6] == '0', 'timer1': int(msg[6:9]), 'timer2': int(msg[9:12]), 'armed_status': msg[12:13]}
EE: Entry/exit timer report.
Below is the the instruction that describes the task: ### Input: EE: Entry/exit timer report. ### Response: def _ee_decode(self, msg): """EE: Entry/exit timer report.""" return {'area': int(msg[4:5])-1, 'is_exit': msg[5:6] == '0', 'timer1': int(msg[6:9]), 'timer2': int(msg[9:12]), ...
def get_activity_objective_bank_assignment_session(self, proxy): """Gets the session for assigning activity to objective bank mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ActivityObjectiveBankAssignmentSession) - an ``ActivityObjectiveBankAssignment...
Gets the session for assigning activity to objective bank mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ActivityObjectiveBankAssignmentSession) - an ``ActivityObjectiveBankAssignmentSession`` raise: NullArgument - ``proxy`` is ``null`` raise...
Below is the the instruction that describes the task: ### Input: Gets the session for assigning activity to objective bank mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ActivityObjectiveBankAssignmentSession) - an ``ActivityObjectiveBankAssignmentSession...
def edf_totdev(N, m, alpha): """ Equivalent degrees of freedom for Total Deviation FIXME: what is the right behavior for alpha outside 0,-1,-2? NIST SP1065 page 41, Table 7 """ alpha = int(alpha) if alpha in [0, -1, -2]: # alpha 0 WFM # alpha -1 FFM # al...
Equivalent degrees of freedom for Total Deviation FIXME: what is the right behavior for alpha outside 0,-1,-2? NIST SP1065 page 41, Table 7
Below is the the instruction that describes the task: ### Input: Equivalent degrees of freedom for Total Deviation FIXME: what is the right behavior for alpha outside 0,-1,-2? NIST SP1065 page 41, Table 7 ### Response: def edf_totdev(N, m, alpha): """ Equivalent degrees of freedom for ...
def orderAction(self, order:QA_Order): """ 委托回报 """ return self.pms[order.code][order.order_id].receive_order(order)
委托回报
Below is the the instruction that describes the task: ### Input: 委托回报 ### Response: def orderAction(self, order:QA_Order): """ 委托回报 """ return self.pms[order.code][order.order_id].receive_order(order)
def plot_ticks(ax, tick_fontsize=12, xticks=None, xticks_args=None, yticks=None, yticks_args=None, zticks=None, zticks_args=None): """Function that defines the labels options of a matplotlib plot. Args: ax: matplotlib axes tick_fontsize (int): Define...
Function that defines the labels options of a matplotlib plot. Args: ax: matplotlib axes tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure xticks_arg(dict): Passsed into matplotlib as xticks arguments ...
Below is the the instruction that describes the task: ### Input: Function that defines the labels options of a matplotlib plot. Args: ax: matplotlib axes tick_fontsize (int): Defines the size of the ticks' font xticks([list of ticks]): Defines the values of x ticks in the figure ...
def download(self, name: str, force: bool = False ) -> bool: """ Attempts to download a given Docker image. If `force=True`, then any previously installed version of the image (described by the instructions) will be replaced by the image...
Attempts to download a given Docker image. If `force=True`, then any previously installed version of the image (described by the instructions) will be replaced by the image on DockerHub. Parameters: name: the name of the Docker image. Returns: `True` if successf...
Below is the the instruction that describes the task: ### Input: Attempts to download a given Docker image. If `force=True`, then any previously installed version of the image (described by the instructions) will be replaced by the image on DockerHub. Parameters: name: the name ...
def on_lstClassifications_itemSelectionChanged(self): """Update classification description label and unlock the Next button. .. note:: This is an automatic Qt slot executed when the field selection changes. """ self.clear_further_steps() classification = self.selected...
Update classification description label and unlock the Next button. .. note:: This is an automatic Qt slot executed when the field selection changes.
Below is the the instruction that describes the task: ### Input: Update classification description label and unlock the Next button. .. note:: This is an automatic Qt slot executed when the field selection changes. ### Response: def on_lstClassifications_itemSelectionChanged(self): """U...
def _detect_database_platform(self): """ Detects and sets the database platform. Evaluates custom platform class and version in order to set the correct platform. :raises InvalidPlatformSpecified: if an invalid platform was specified for this connection. """ version = s...
Detects and sets the database platform. Evaluates custom platform class and version in order to set the correct platform. :raises InvalidPlatformSpecified: if an invalid platform was specified for this connection.
Below is the the instruction that describes the task: ### Input: Detects and sets the database platform. Evaluates custom platform class and version in order to set the correct platform. :raises InvalidPlatformSpecified: if an invalid platform was specified for this connection. ### Response: def ...
def get_modifier_from_signature(self, modifier_signature): """ Return a modifier from a signature Args: modifier_name (str): signature of the modifier Returns: Modifier """ return next((m for m in self.modifiers if m.full_name == modifier_signa...
Return a modifier from a signature Args: modifier_name (str): signature of the modifier Returns: Modifier
Below is the the instruction that describes the task: ### Input: Return a modifier from a signature Args: modifier_name (str): signature of the modifier Returns: Modifier ### Response: def get_modifier_from_signature(self, modifier_signature): """ Return ...
def find_token(request, token_type, service, **kwargs): """ The access token can be in a number of places. There are priority rules as to which one to use, abide by those: 1 If it's among the request parameters use that 2 If among the extra keyword arguments 3 Acquired by a previous run service...
The access token can be in a number of places. There are priority rules as to which one to use, abide by those: 1 If it's among the request parameters use that 2 If among the extra keyword arguments 3 Acquired by a previous run service. :param request: :param token_type: :param service: ...
Below is the the instruction that describes the task: ### Input: The access token can be in a number of places. There are priority rules as to which one to use, abide by those: 1 If it's among the request parameters use that 2 If among the extra keyword arguments 3 Acquired by a previous run servic...
def mul_inv(a, b): """ Modular inversion a mod b :param a: :param b: :return: """ b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a // b a, b = b, a % b x0, x1 = x1 - q * x0, x0 ...
Modular inversion a mod b :param a: :param b: :return:
Below is the the instruction that describes the task: ### Input: Modular inversion a mod b :param a: :param b: :return: ### Response: def mul_inv(a, b): """ Modular inversion a mod b :param a: :param b: :return: """ b0 = b x0, ...
def derive_and_set_name_fields_and_slug( self, set_name_sort=True, set_slug=True ): """ Override this method from `CreatorBase` to handle additional name fields for Person creators. This method is called during `save()` """ super(PersonCreator, self).derive_a...
Override this method from `CreatorBase` to handle additional name fields for Person creators. This method is called during `save()`
Below is the the instruction that describes the task: ### Input: Override this method from `CreatorBase` to handle additional name fields for Person creators. This method is called during `save()` ### Response: def derive_and_set_name_fields_and_slug( self, set_name_sort=True, set_slug=Tru...
def __compare_parameters(self, width, height, zoom, parameters): """Compare parameters for equality Checks if a cached image is existing, the the dimensions agree and finally if the properties are equal. If so, True is returned, else False, :param width: The width of the image :...
Compare parameters for equality Checks if a cached image is existing, the the dimensions agree and finally if the properties are equal. If so, True is returned, else False, :param width: The width of the image :param height: The height of the image :param zoom: The current scale...
Below is the the instruction that describes the task: ### Input: Compare parameters for equality Checks if a cached image is existing, the the dimensions agree and finally if the properties are equal. If so, True is returned, else False, :param width: The width of the image :param h...
def readList(self, register, length): """Read a length number of bytes from the specified register. Results will be returned as a bytearray.""" results = self._bus.read_i2c_block_data(self._address, register, length) self._logger.debug("Read the following from register 0x%02X: %s", ...
Read a length number of bytes from the specified register. Results will be returned as a bytearray.
Below is the the instruction that describes the task: ### Input: Read a length number of bytes from the specified register. Results will be returned as a bytearray. ### Response: def readList(self, register, length): """Read a length number of bytes from the specified register. Results wi...
def default_links_factory_with_additional(additional_links): """Generate a links generation factory with the specified additional links. :param additional_links: A dict of link names to links to be added to the returned object. :returns: A link generation factory. """ def factory(pid, **...
Generate a links generation factory with the specified additional links. :param additional_links: A dict of link names to links to be added to the returned object. :returns: A link generation factory.
Below is the the instruction that describes the task: ### Input: Generate a links generation factory with the specified additional links. :param additional_links: A dict of link names to links to be added to the returned object. :returns: A link generation factory. ### Response: def default_lin...
def rangize_supplement(spans,lngth): ''' spans = [(0, 3), (4, 7), (8, 10), (11, 12), (13, 16), (17, 20)] rangize_supplement(spans,24) ''' rslt = [] si = 0 ei = spans[0][0] if(si == ei): pass else: rslt.append((si,ei)) prev_ei = spans[0][1] for...
spans = [(0, 3), (4, 7), (8, 10), (11, 12), (13, 16), (17, 20)] rangize_supplement(spans,24)
Below is the the instruction that describes the task: ### Input: spans = [(0, 3), (4, 7), (8, 10), (11, 12), (13, 16), (17, 20)] rangize_supplement(spans,24) ### Response: def rangize_supplement(spans,lngth): ''' spans = [(0, 3), (4, 7), (8, 10), (11, 12), (13, 16), (17, 20)] rangize_su...
def _read_password_from_pgpass( *, passfile: typing.Optional[pathlib.Path], hosts: typing.List[str], ports: typing.List[int], database: str, user: str): """Parse the pgpass file and return the matching password. :return: Password string, if found, ``None`` otherw...
Parse the pgpass file and return the matching password. :return: Password string, if found, ``None`` otherwise.
Below is the the instruction that describes the task: ### Input: Parse the pgpass file and return the matching password. :return: Password string, if found, ``None`` otherwise. ### Response: def _read_password_from_pgpass( *, passfile: typing.Optional[pathlib.Path], hosts: typing.List[...
def main(*argv): """ main driver of program """ try: # Inputs # adminUsername = argv[0] adminPassword = argv[1] siteURL = argv[2] groupTitle = argv[3] groupTags = argv[4] description = argv[5] access = argv[6] # Logic #...
main driver of program
Below is the the instruction that describes the task: ### Input: main driver of program ### Response: def main(*argv): """ main driver of program """ try: # Inputs # adminUsername = argv[0] adminPassword = argv[1] siteURL = argv[2] groupTitle = argv[3] ...
def write(models, out=None, base=None, propertybase=None, shorteners=None, logger=logging): ''' models - input Versa models from which output is generated. Must be a sequence object, not an iterator ''' assert out is not None #Output stream required if not isinstance(models, list): m...
models - input Versa models from which output is generated. Must be a sequence object, not an iterator
Below is the the instruction that describes the task: ### Input: models - input Versa models from which output is generated. Must be a sequence object, not an iterator ### Response: def write(models, out=None, base=None, propertybase=None, shorteners=None, logger=logging): ''' models - inpu...
def day_to_month(timeperiod): """:param timeperiod: as string in YYYYMMDD00 format :return string in YYYYMM0000 format""" t = datetime.strptime(timeperiod, SYNERGY_DAILY_PATTERN) return t.strftime(SYNERGY_MONTHLY_PATTERN)
:param timeperiod: as string in YYYYMMDD00 format :return string in YYYYMM0000 format
Below is the the instruction that describes the task: ### Input: :param timeperiod: as string in YYYYMMDD00 format :return string in YYYYMM0000 format ### Response: def day_to_month(timeperiod): """:param timeperiod: as string in YYYYMMDD00 format :return string in YYYYMM0000 format""" t = datetime...
def get_initial_states(self, input_var, init_state=None): """ :type input_var: T.var :rtype: dict """ initial_states = {} for state in self.state_names: if state != "state" or not init_state: if self._input_type == 'sequence' and input_var.ndim...
:type input_var: T.var :rtype: dict
Below is the the instruction that describes the task: ### Input: :type input_var: T.var :rtype: dict ### Response: def get_initial_states(self, input_var, init_state=None): """ :type input_var: T.var :rtype: dict """ initial_states = {} for state in self.stat...
def download_loci(self): """ Uses a multi-threaded approach to download allele files """ # Setup the multiprocessing pool. pool = multiprocessing.Pool(processes=self.threads) # Map the list of loci URLs to the download method pool.map(self.download_threads, self.l...
Uses a multi-threaded approach to download allele files
Below is the the instruction that describes the task: ### Input: Uses a multi-threaded approach to download allele files ### Response: def download_loci(self): """ Uses a multi-threaded approach to download allele files """ # Setup the multiprocessing pool. pool = multiproce...
def revert_to(self): ''' method to revert resource to this version by issuing PATCH Args: None Returns: None: sends PATCH request, and refreshes parent resource ''' # send patch response = self.resource.repo.api.http_request('PATCH', self.uri) # if response 204 if response.status_code == 20...
method to revert resource to this version by issuing PATCH Args: None Returns: None: sends PATCH request, and refreshes parent resource
Below is the the instruction that describes the task: ### Input: method to revert resource to this version by issuing PATCH Args: None Returns: None: sends PATCH request, and refreshes parent resource ### Response: def revert_to(self): ''' method to revert resource to this version by issuing PATCH...
def run_main(workdir, config_file=None, fc_dir=None, run_info_yaml=None, parallel=None, workflow=None): """Run variant analysis, handling command line options. """ # Set environment to standard to use periods for decimals and avoid localization os.environ["LC_ALL"] = "C" os.environ["LC"...
Run variant analysis, handling command line options.
Below is the the instruction that describes the task: ### Input: Run variant analysis, handling command line options. ### Response: def run_main(workdir, config_file=None, fc_dir=None, run_info_yaml=None, parallel=None, workflow=None): """Run variant analysis, handling command line options. ""...
def _build_url_rewriter(cls, session: AppSession): '''Build URL rewriter if needed.''' if session.args.escaped_fragment or session.args.strip_session_id: return session.factory.new( 'URLRewriter', hash_fragment=session.args.escaped_fragment, se...
Build URL rewriter if needed.
Below is the the instruction that describes the task: ### Input: Build URL rewriter if needed. ### Response: def _build_url_rewriter(cls, session: AppSession): '''Build URL rewriter if needed.''' if session.args.escaped_fragment or session.args.strip_session_id: return session.factory.n...
def cummax(self, axis=None, skipna=True, *args, **kwargs): """Perform a cumulative maximum across the DataFrame. Args: axis (int): The axis to take maximum on. skipna (bool): True to skip NA values, false otherwise. Returns: The cumulative maximum of...
Perform a cumulative maximum across the DataFrame. Args: axis (int): The axis to take maximum on. skipna (bool): True to skip NA values, false otherwise. Returns: The cumulative maximum of the DataFrame.
Below is the the instruction that describes the task: ### Input: Perform a cumulative maximum across the DataFrame. Args: axis (int): The axis to take maximum on. skipna (bool): True to skip NA values, false otherwise. Returns: The cumulative maximum of t...
def get_versioned_viewname(self, viewname, request): """ Prefix viewname with full namespace bananas:vX.Y: """ namespace = request.resolver_match.namespace if namespace: viewname = "{}:{}".format(namespace, viewname) return viewname
Prefix viewname with full namespace bananas:vX.Y:
Below is the the instruction that describes the task: ### Input: Prefix viewname with full namespace bananas:vX.Y: ### Response: def get_versioned_viewname(self, viewname, request): """ Prefix viewname with full namespace bananas:vX.Y: """ namespace = request.resolver_match.namespac...
def clients(self, protocol=None, groups=None): """Returns a list of :py:class:`.Client` for the specific query by the user. Keyword Parameters: protocol Ignored. groups The groups (types) to which the clients belong either from ('Genuine', 'Impostor') Note that 'eval' is an alias fo...
Returns a list of :py:class:`.Client` for the specific query by the user. Keyword Parameters: protocol Ignored. groups The groups (types) to which the clients belong either from ('Genuine', 'Impostor') Note that 'eval' is an alias for 'Genuine'. If no groups are specified, then bo...
Below is the the instruction that describes the task: ### Input: Returns a list of :py:class:`.Client` for the specific query by the user. Keyword Parameters: protocol Ignored. groups The groups (types) to which the clients belong either from ('Genuine', 'Impostor') Note that 'eval'...
def run(self, *args, **kwargs): """ Connect and run bot in event loop. """ self.eventloop.run_until_complete(self.connect(*args, **kwargs)) try: self.eventloop.run_forever() finally: self.eventloop.stop()
Connect and run bot in event loop.
Below is the the instruction that describes the task: ### Input: Connect and run bot in event loop. ### Response: def run(self, *args, **kwargs): """ Connect and run bot in event loop. """ self.eventloop.run_until_complete(self.connect(*args, **kwargs)) try: self.eventloop.run_f...
def put(self, key, value): '''Stores the object named by `key`. Follows links.''' # if value is a link, don't follow links if self._link_for_value(value): super(SymlinkDatastore, self).put(key, value) return # if `key` points to a symlink, need to follow it. current_value = super(Symlin...
Stores the object named by `key`. Follows links.
Below is the the instruction that describes the task: ### Input: Stores the object named by `key`. Follows links. ### Response: def put(self, key, value): '''Stores the object named by `key`. Follows links.''' # if value is a link, don't follow links if self._link_for_value(value): super(SymlinkD...
def on_touch_down(self, touch): """Check for collisions and select an appropriate entity.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: return if not self.collide_point(*touch.pos): return touch.push() touch.apply_transform_2d(self.to_loc...
Check for collisions and select an appropriate entity.
Below is the the instruction that describes the task: ### Input: Check for collisions and select an appropriate entity. ### Response: def on_touch_down(self, touch): """Check for collisions and select an appropriate entity.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: ...
def start(self): """ instanciate request session with authent :return: """ LOGGER.debug("rest.Driver.start") self.session = requests.Session() self.session.auth = (self.user, self.password)
instanciate request session with authent :return:
Below is the the instruction that describes the task: ### Input: instanciate request session with authent :return: ### Response: def start(self): """ instanciate request session with authent :return: """ LOGGER.debug("rest.Driver.start") self.session = reques...
def get_comment_lookup_session(self): """Gets the ``OsidSession`` associated with the comment lookup service. return: (osid.commenting.CommentLookupSession) - a ``CommentLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``suppor...
Gets the ``OsidSession`` associated with the comment lookup service. return: (osid.commenting.CommentLookupSession) - a ``CommentLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_comment_lookup()`` is ``false`...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the comment lookup service. return: (osid.commenting.CommentLookupSession) - a ``CommentLookupSession`` raise: OperationFailed - unable to complete request raise: Unim...
def unstack(self, unstacker_func, fill_value): """Return a blockmanager with all blocks unstacked. Parameters ---------- unstacker_func : callable A (partially-applied) ``pd.core.reshape._Unstacker`` class. fill_value : Any fill_value for newly introduced...
Return a blockmanager with all blocks unstacked. Parameters ---------- unstacker_func : callable A (partially-applied) ``pd.core.reshape._Unstacker`` class. fill_value : Any fill_value for newly introduced missing values. Returns ------- ...
Below is the the instruction that describes the task: ### Input: Return a blockmanager with all blocks unstacked. Parameters ---------- unstacker_func : callable A (partially-applied) ``pd.core.reshape._Unstacker`` class. fill_value : Any fill_value for newly...
def intersects_segment(self, seg): """ Returns True if any segmentlist in self intersects the segment, otherwise returns False. """ return any(value.intersects_segment(seg) for value in self.itervalues())
Returns True if any segmentlist in self intersects the segment, otherwise returns False.
Below is the the instruction that describes the task: ### Input: Returns True if any segmentlist in self intersects the segment, otherwise returns False. ### Response: def intersects_segment(self, seg): """ Returns True if any segmentlist in self intersects the segment, otherwise returns False. """ ret...
def calculate_concat_output_shapes(operator): ''' Allowed input/output patterns are 1. [N_1, C, H, W], ..., [N_n, C, H, W] ---> [N_1 + ... + N_n, C, H, W] 2. [N, C_1, H, W], ..., [N, C_n, H, W] ---> [N, C_1 + ... + C_n, H, W] ''' check_input_and_output_numbers(operator, input_count_range...
Allowed input/output patterns are 1. [N_1, C, H, W], ..., [N_n, C, H, W] ---> [N_1 + ... + N_n, C, H, W] 2. [N, C_1, H, W], ..., [N, C_n, H, W] ---> [N, C_1 + ... + C_n, H, W]
Below is the the instruction that describes the task: ### Input: Allowed input/output patterns are 1. [N_1, C, H, W], ..., [N_n, C, H, W] ---> [N_1 + ... + N_n, C, H, W] 2. [N, C_1, H, W], ..., [N, C_n, H, W] ---> [N, C_1 + ... + C_n, H, W] ### Response: def calculate_concat_output_shapes(operator)...
def clearkml(self): '''Clear the kmls from the map''' #go through all the current layers and remove them for layer in self.curlayers: self.mpstate.map.remove_object(layer) for layer in self.curtextlayers: self.mpstate.map.remove_object(layer) self.allayers...
Clear the kmls from the map
Below is the the instruction that describes the task: ### Input: Clear the kmls from the map ### Response: def clearkml(self): '''Clear the kmls from the map''' #go through all the current layers and remove them for layer in self.curlayers: self.mpstate.map.remove_object(layer) ...
def _outputs(self): """List of layers containing outputs from the IF. :returns: A list of vector layers. :rtype: list """ layers = OrderedDict() layers[layer_purpose_exposure_summary['key']] = ( self._exposure_summary) layers[layer_purpose_aggregate_h...
List of layers containing outputs from the IF. :returns: A list of vector layers. :rtype: list
Below is the the instruction that describes the task: ### Input: List of layers containing outputs from the IF. :returns: A list of vector layers. :rtype: list ### Response: def _outputs(self): """List of layers containing outputs from the IF. :returns: A list of vector layers. ...
def nltides_gw_phase_difference(f, f0, amplitude, n, m1, m2): """Calculate the gravitational-wave phase shift bwtween f and f_coalescence = infinity due to non-linear tides. To compute the phase shift between e.g. f_low and f_isco, call this function twice and compute the difference. Parameters ...
Calculate the gravitational-wave phase shift bwtween f and f_coalescence = infinity due to non-linear tides. To compute the phase shift between e.g. f_low and f_isco, call this function twice and compute the difference. Parameters ---------- f: float or numpy.array Frequency from which ...
Below is the the instruction that describes the task: ### Input: Calculate the gravitational-wave phase shift bwtween f and f_coalescence = infinity due to non-linear tides. To compute the phase shift between e.g. f_low and f_isco, call this function twice and compute the difference. Parameters ...
def _build_arg_list(self, **kwargs): """Build list of arguments from the dict; keys must be valid gromacs flags.""" arglist = [] for flag, value in kwargs.items(): # XXX: check flag against allowed values flag = str(flag) if flag.startswith('_'): ...
Build list of arguments from the dict; keys must be valid gromacs flags.
Below is the the instruction that describes the task: ### Input: Build list of arguments from the dict; keys must be valid gromacs flags. ### Response: def _build_arg_list(self, **kwargs): """Build list of arguments from the dict; keys must be valid gromacs flags.""" arglist = [] for flag...
def angle(array_of_xyzs): """ Calculates angle between three coordinate points (I could not find a package that does this but if one exists that would probably be better). Used for Angle constraints. """ ab = array_of_xyzs[0] - array_of_xyzs[1] cb = array_of_xyzs[2] - array_of_xyzs[1] retur...
Calculates angle between three coordinate points (I could not find a package that does this but if one exists that would probably be better). Used for Angle constraints.
Below is the the instruction that describes the task: ### Input: Calculates angle between three coordinate points (I could not find a package that does this but if one exists that would probably be better). Used for Angle constraints. ### Response: def angle(array_of_xyzs): """ Calculates angle between...
def restore_review_history_for_affected_objects(portal): """Applies the review history for objects that are bound to new senaite_* workflows """ logger.info("Restoring review_history ...") query = dict(portal_type=NEW_SENAITE_WORKFLOW_BINDINGS) brains = api.search(query, UID_CATALOG) total =...
Applies the review history for objects that are bound to new senaite_* workflows
Below is the the instruction that describes the task: ### Input: Applies the review history for objects that are bound to new senaite_* workflows ### Response: def restore_review_history_for_affected_objects(portal): """Applies the review history for objects that are bound to new senaite_* workflows ...
def create_signed_tx(network, spendables, payables, wifs=[], fee="standard", lock_time=0, version=1, **kwargs): """ This convenience function calls :func:`create_tx` and :func:`sign_tx` in turn. Read the documentation for those functions for information on the parameters. Usage:: ...
This convenience function calls :func:`create_tx` and :func:`sign_tx` in turn. Read the documentation for those functions for information on the parameters. Usage:: >>> spendables = spendables_for_address("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH") >>> wifs = ["KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9...
Below is the the instruction that describes the task: ### Input: This convenience function calls :func:`create_tx` and :func:`sign_tx` in turn. Read the documentation for those functions for information on the parameters. Usage:: >>> spendables = spendables_for_address("1BgGZ9tcN4rm9KBzDn7KprQz87S...
def pretty_descriptor(self): """ assemble a long member name from access flags, type, argument types, exceptions as applicable """ f = " ".join(self.pretty_access_flags()) p = self.pretty_type() n = self.get_name() t = ",".join(self.pretty_exceptions()) ...
assemble a long member name from access flags, type, argument types, exceptions as applicable
Below is the the instruction that describes the task: ### Input: assemble a long member name from access flags, type, argument types, exceptions as applicable ### Response: def pretty_descriptor(self): """ assemble a long member name from access flags, type, argument types, exceptio...
def first(self, x): """Returns first found index of given value (or list of values).""" def _find(x): try: return self.all.index(str(x)) except ValueError: return None if _is_collection(x): for item in x: found...
Returns first found index of given value (or list of values).
Below is the the instruction that describes the task: ### Input: Returns first found index of given value (or list of values). ### Response: def first(self, x): """Returns first found index of given value (or list of values).""" def _find(x): try: return self.all.index(...
def is_empty(self): ''' Return `True` if form is valid and contains an empty lookup. ''' return (self.is_valid() and not self.simple_lookups and not self.complex_conditions and not self.extra_conditions)
Return `True` if form is valid and contains an empty lookup.
Below is the the instruction that describes the task: ### Input: Return `True` if form is valid and contains an empty lookup. ### Response: def is_empty(self): ''' Return `True` if form is valid and contains an empty lookup. ''' return (self.is_valid() and not self.simpl...
def sorted_enums(self) -> List[Tuple[str, int]]: """Return list of enum items sorted by value.""" return sorted(self.enum.items(), key=lambda x: x[1])
Return list of enum items sorted by value.
Below is the the instruction that describes the task: ### Input: Return list of enum items sorted by value. ### Response: def sorted_enums(self) -> List[Tuple[str, int]]: """Return list of enum items sorted by value.""" return sorted(self.enum.items(), key=lambda x: x[1])
def leaveChat(self, chat_id): """ See: https://core.telegram.org/bots/api#leavechat """ p = _strip(locals()) return self._api_request('leaveChat', _rectify(p))
See: https://core.telegram.org/bots/api#leavechat
Below is the the instruction that describes the task: ### Input: See: https://core.telegram.org/bots/api#leavechat ### Response: def leaveChat(self, chat_id): """ See: https://core.telegram.org/bots/api#leavechat """ p = _strip(locals()) return self._api_request('leaveChat', _rectify(p))
def _freq_parser(self, freq): """Parse timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", """ freq = freq.lower().strip() valid_keywords = [ "day...
Parse timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w",
Below is the the instruction that describes the task: ### Input: Parse timedelta. Valid keywords "days", "day", "d", "hours", "hour", "h", "minutes", "minute", "min", "m", "seconds", "second", "sec", "s", "weeks", "week", "w", ### Response: def _freq_parser(self, freq): """Parse ti...
def process_exception(self, request, exception): """Catches internal Horizon exception classes such as NotAuthorized, NotFound and Http302 and handles them gracefully. """ if isinstance(exception, (exceptions.NotAuthorized, exceptions.NotAuthenticated))...
Catches internal Horizon exception classes such as NotAuthorized, NotFound and Http302 and handles them gracefully.
Below is the the instruction that describes the task: ### Input: Catches internal Horizon exception classes such as NotAuthorized, NotFound and Http302 and handles them gracefully. ### Response: def process_exception(self, request, exception): """Catches internal Horizon exception classes such as N...
def _read_config(config_location): """ Read configuration for logging from a json file. Merges the read dictionary to LOGGING_CONFIG. :param config_location: Location of file. :return: nothing. """ global LOGGING_CONFIG with open(config_location, "r") as config_loc: cfg_file = json....
Read configuration for logging from a json file. Merges the read dictionary to LOGGING_CONFIG. :param config_location: Location of file. :return: nothing.
Below is the the instruction that describes the task: ### Input: Read configuration for logging from a json file. Merges the read dictionary to LOGGING_CONFIG. :param config_location: Location of file. :return: nothing. ### Response: def _read_config(config_location): """ Read configuration for lo...
def evaluate_version_bump(current_version: str, force: str = None) -> Optional[str]: """ Reads git log since last release to find out if should be a major, minor or patch release. :param current_version: A string with the current version number. :param force: A string with the bump level that should be...
Reads git log since last release to find out if should be a major, minor or patch release. :param current_version: A string with the current version number. :param force: A string with the bump level that should be forced. :return: A string with either major, minor or patch if there should be a release. If...
Below is the the instruction that describes the task: ### Input: Reads git log since last release to find out if should be a major, minor or patch release. :param current_version: A string with the current version number. :param force: A string with the bump level that should be forced. :return: A stri...
def tweet(ctx, message): """Sends a tweet directly to your timeline""" if not valid_tweet(message): click.echo("Message is too long for twitter.") click.echo("Message:" + message) ctx.exit(2) if not ctx.obj['DRYRUN']: ctx.obj['TWEEPY_API'].update_status(message) else: ...
Sends a tweet directly to your timeline
Below is the the instruction that describes the task: ### Input: Sends a tweet directly to your timeline ### Response: def tweet(ctx, message): """Sends a tweet directly to your timeline""" if not valid_tweet(message): click.echo("Message is too long for twitter.") click.echo("Message:" + m...
def write(self, data): """! @brief Write bytes into the connection.""" # If nobody is connected, act like all data was written anyway. if self.connected is None: return 0 data = to_bytes_safe(data) size = len(data) remaining = size while remaining: ...
! @brief Write bytes into the connection.
Below is the the instruction that describes the task: ### Input: ! @brief Write bytes into the connection. ### Response: def write(self, data): """! @brief Write bytes into the connection.""" # If nobody is connected, act like all data was written anyway. if self.connected is None: ...
def find(self, upload_id, **kwargs): """ Finds an upload by ID. """ return super(UploadsProxy, self).find(upload_id, file_upload=True)
Finds an upload by ID.
Below is the the instruction that describes the task: ### Input: Finds an upload by ID. ### Response: def find(self, upload_id, **kwargs): """ Finds an upload by ID. """ return super(UploadsProxy, self).find(upload_id, file_upload=True)
def __squid_to_guid(self, squid): ''' Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUID provided. ...
Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUID provided.
Below is the the instruction that describes the task: ### Input: Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUI...