code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _call_marginalizevlos(self,o,**kwargs): """Call the DF, marginalizing over line-of-sight velocity""" #Get d, l, vperp l= o.ll(obs=[1.,0.,0.],ro=1.)*_DEGTORAD vperp= o.vll(ro=1.,vo=1.,obs=[1.,0.,0.,0.,0.,0.]) R= o.R(use_physical=False) phi= o.phi(use_physical=False) ...
Call the DF, marginalizing over line-of-sight velocity
Below is the the instruction that describes the task: ### Input: Call the DF, marginalizing over line-of-sight velocity ### Response: def _call_marginalizevlos(self,o,**kwargs): """Call the DF, marginalizing over line-of-sight velocity""" #Get d, l, vperp l= o.ll(obs=[1.,0.,0.],ro=1.)*_DEGT...
def _sections_to_variance_sections(self, sections_over_time): '''Computes the variance of corresponding sections over time. Returns: a list of np arrays. ''' variance_sections = [] for i in range(len(sections_over_time[0])): time_sections = [sections[i] for sections in sections_over_ti...
Computes the variance of corresponding sections over time. Returns: a list of np arrays.
Below is the the instruction that describes the task: ### Input: Computes the variance of corresponding sections over time. Returns: a list of np arrays. ### Response: def _sections_to_variance_sections(self, sections_over_time): '''Computes the variance of corresponding sections over time. Ret...
def get_system_path(): """Return the path that Windows will search for dlls.""" _bpath = [] if is_win: try: import win32api except ImportError: logger.warn("Cannot determine your Windows or System directories") logger.warn("Please add them to your PATH if ...
Return the path that Windows will search for dlls.
Below is the the instruction that describes the task: ### Input: Return the path that Windows will search for dlls. ### Response: def get_system_path(): """Return the path that Windows will search for dlls.""" _bpath = [] if is_win: try: import win32api except ImportError: ...
def find_stack_elements(self, module, module_name="", _visited_modules=None): """ This function goes through the given container and returns the stack elements. Each stack element is represented by a tuple: ( container_name, element_name, stack_element) The tuples are returne...
This function goes through the given container and returns the stack elements. Each stack element is represented by a tuple: ( container_name, element_name, stack_element) The tuples are returned in an array
Below is the the instruction that describes the task: ### Input: This function goes through the given container and returns the stack elements. Each stack element is represented by a tuple: ( container_name, element_name, stack_element) The tuples are returned in an array ### Response: ...
def site_name(self, site_name): """Function that sets and checks the site name and set url. Parameters: site_name (str): The site name in 'SITE_LIST', default sites. Raises: PybooruError: When 'site_name' isn't valid. """ if site_name in SITE_LIST: ...
Function that sets and checks the site name and set url. Parameters: site_name (str): The site name in 'SITE_LIST', default sites. Raises: PybooruError: When 'site_name' isn't valid.
Below is the the instruction that describes the task: ### Input: Function that sets and checks the site name and set url. Parameters: site_name (str): The site name in 'SITE_LIST', default sites. Raises: PybooruError: When 'site_name' isn't valid. ### Response: def site_na...
def get_corpus(self): """获取语料库 Return: corpus -- 语料库,str类型 """ # 正向判定 corpus = [] cd = 0 tag = None for i in range(0, self.init_corpus[0][0]): init_unit = self.unit_raw[self.init_corpus[0][0] - i] cdm = CDM(i...
获取语料库 Return: corpus -- 语料库,str类型
Below is the the instruction that describes the task: ### Input: 获取语料库 Return: corpus -- 语料库,str类型 ### Response: def get_corpus(self): """获取语料库 Return: corpus -- 语料库,str类型 """ # 正向判定 corpus = [] cd = 0 ta...
def list_menu(self, options, title="Choose a value", message="Choose a value", default=None, **kwargs): """ Show a single-selection list menu Usage: C{dialog.list_menu(options, title="Choose a value", message="Choose a value", default=None, **kwargs)} @param options: li...
Show a single-selection list menu Usage: C{dialog.list_menu(options, title="Choose a value", message="Choose a value", default=None, **kwargs)} @param options: list of options (strings) for the dialog @param title: window title for the dialog @param message: message dis...
Below is the the instruction that describes the task: ### Input: Show a single-selection list menu Usage: C{dialog.list_menu(options, title="Choose a value", message="Choose a value", default=None, **kwargs)} @param options: list of options (strings) for the dialog @param t...
def parse_extends(self): """ For each part, create the inheritance parts from the ' extends ' """ # To be able to manage multiple extends, you need to # destroy the actual node and create many nodes that have # mono extend. The first one gets all the css rules for...
For each part, create the inheritance parts from the ' extends '
Below is the the instruction that describes the task: ### Input: For each part, create the inheritance parts from the ' extends ' ### Response: def parse_extends(self): """ For each part, create the inheritance parts from the ' extends ' """ # To be able to manage multiple extends, ...
def add_sparql_line_nums(sparql): """ Returns a sparql query with line numbers prepended """ lines = sparql.split("\n") return "\n".join(["%s %s" % (i + 1, line) for i, line in enumerate(lines)])
Returns a sparql query with line numbers prepended
Below is the the instruction that describes the task: ### Input: Returns a sparql query with line numbers prepended ### Response: def add_sparql_line_nums(sparql): """ Returns a sparql query with line numbers prepended """ lines = sparql.split("\n") return "\n".join(["%s %s" % (i + 1, line) for...
def _get_raw_data(self, name): """Find file holding data and return its content.""" # try legacy first, then hdf5 filestem = '' for filestem, list_fvar in self._files.items(): if name in list_fvar: break fieldfile = self.step.sdat.filename(filestem, se...
Find file holding data and return its content.
Below is the the instruction that describes the task: ### Input: Find file holding data and return its content. ### Response: def _get_raw_data(self, name): """Find file holding data and return its content.""" # try legacy first, then hdf5 filestem = '' for filestem, list_fvar in se...
def dateparser(self, dformat='%d/%m/%Y'): """ Returns a date parser for pandas """ def dateparse(dates): return [pd.datetime.strptime(d, dformat) for d in dates] return dateparse
Returns a date parser for pandas
Below is the the instruction that describes the task: ### Input: Returns a date parser for pandas ### Response: def dateparser(self, dformat='%d/%m/%Y'): """ Returns a date parser for pandas """ def dateparse(dates): return [pd.datetime.strptime(d, dformat) for d in dat...
def parse_token(response): """ parse the responses containing the tokens Parameters ---------- response : str The response containing the tokens Returns ------- dict The parsed tokens """ items = response.split("&") items = [item.split("=") for item in items...
parse the responses containing the tokens Parameters ---------- response : str The response containing the tokens Returns ------- dict The parsed tokens
Below is the the instruction that describes the task: ### Input: parse the responses containing the tokens Parameters ---------- response : str The response containing the tokens Returns ------- dict The parsed tokens ### Response: def parse_token(response): """ pa...
def rebase_all_branches(self): """ Rebase all branches, if possible. """ col_width = max(len(b.name) for b in self.branches) + 1 if self.repo.head.is_detached: raise GitError("You're not currently on a branch. I'm exiting" " in case you're in the middl...
Rebase all branches, if possible.
Below is the the instruction that describes the task: ### Input: Rebase all branches, if possible. ### Response: def rebase_all_branches(self): """ Rebase all branches, if possible. """ col_width = max(len(b.name) for b in self.branches) + 1 if self.repo.head.is_detached: ra...
def register_observer(self, observer, events=None): """Register a listener function. :param observer: external listener function :param events: tuple or list of relevant events (default=None) """ if events is not None and not isinstance(events, (tuple, list)): events...
Register a listener function. :param observer: external listener function :param events: tuple or list of relevant events (default=None)
Below is the the instruction that describes the task: ### Input: Register a listener function. :param observer: external listener function :param events: tuple or list of relevant events (default=None) ### Response: def register_observer(self, observer, events=None): """Register a listener...
def ladderize(self, direction=0): """ Ladderize tree (order descendants) so that top child has fewer descendants than the bottom child in a left to right tree plot. To reverse this pattern use direction=1. """ nself = deepcopy(self) nself.treenode.ladderize(dire...
Ladderize tree (order descendants) so that top child has fewer descendants than the bottom child in a left to right tree plot. To reverse this pattern use direction=1.
Below is the the instruction that describes the task: ### Input: Ladderize tree (order descendants) so that top child has fewer descendants than the bottom child in a left to right tree plot. To reverse this pattern use direction=1. ### Response: def ladderize(self, direction=0): """ ...
def OSPFNeighborState_originator_switch_info_switchIpV4Address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") OSPFNeighborState = ET.SubElement(config, "OSPFNeighborState", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_inf...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def OSPFNeighborState_originator_switch_info_switchIpV4Address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") OSPFNeighborState = ET.SubElement(config, "OSPF...
def oauth_manager(self, oauth_manager): """Use the oauth manager to enable oauth for API :param oauth_manager: the oauth manager """ @self.app.before_request def before_request(): endpoint = request.endpoint resource = self.app.view_functions[endpoint].vi...
Use the oauth manager to enable oauth for API :param oauth_manager: the oauth manager
Below is the the instruction that describes the task: ### Input: Use the oauth manager to enable oauth for API :param oauth_manager: the oauth manager ### Response: def oauth_manager(self, oauth_manager): """Use the oauth manager to enable oauth for API :param oauth_manager: the oauth man...
def heightmap_clamp(hm: np.ndarray, mi: float, ma: float) -> None: """Clamp all values on this heightmap between ``mi`` and ``ma`` Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. mi (float): The lower bound to clamp to. ma (float): The upper bound to clamp t...
Clamp all values on this heightmap between ``mi`` and ``ma`` Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. mi (float): The lower bound to clamp to. ma (float): The upper bound to clamp to. .. deprecated:: 2.0 Do ``hm.clip(mi, ma)`` instead.
Below is the the instruction that describes the task: ### Input: Clamp all values on this heightmap between ``mi`` and ``ma`` Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. mi (float): The lower bound to clamp to. ma (float): The upper bound to clamp to. ...
async def _unsubscribe(self, channels, is_mask): """Unsubscribe from given channel.""" vanished = [] if channels: for channel in channels: key = channel, is_mask self._channels.remove(key) self._plugin._subscriptions[key].remove(self._q...
Unsubscribe from given channel.
Below is the the instruction that describes the task: ### Input: Unsubscribe from given channel. ### Response: async def _unsubscribe(self, channels, is_mask): """Unsubscribe from given channel.""" vanished = [] if channels: for channel in channels: key = channel...
def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. '...
Make a web call to the GitHub API and deal with paginated results.
Below is the the instruction that describes the task: ### Input: Make a web call to the GitHub API and deal with paginated results. ### Response: def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, ...
def from_spcm(filepath, name=None, *, delimiter=",", parent=None, verbose=True) -> Data: """Create a ``Data`` object from a Becker & Hickl spcm file (ASCII-exported, ``.asc``). If provided, setup parameters are stored in the ``attrs`` dictionary of the ``Data`` object. See the `spcm`__ software hompage fo...
Create a ``Data`` object from a Becker & Hickl spcm file (ASCII-exported, ``.asc``). If provided, setup parameters are stored in the ``attrs`` dictionary of the ``Data`` object. See the `spcm`__ software hompage for more info. __ http://www.becker-hickl.com/software/spcm.htm Parameters ---------...
Below is the the instruction that describes the task: ### Input: Create a ``Data`` object from a Becker & Hickl spcm file (ASCII-exported, ``.asc``). If provided, setup parameters are stored in the ``attrs`` dictionary of the ``Data`` object. See the `spcm`__ software hompage for more info. __ http:/...
def hdate(self): """Return the hebrew date.""" if self._last_updated == "hdate": return self._hdate return conv.jdn_to_hdate(self._jdn)
Return the hebrew date.
Below is the the instruction that describes the task: ### Input: Return the hebrew date. ### Response: def hdate(self): """Return the hebrew date.""" if self._last_updated == "hdate": return self._hdate return conv.jdn_to_hdate(self._jdn)
def basis(self, n): """ Chebyshev basis functions T_n. """ if n == 0: return self(np.array([1.])) vals = np.ones(n+1) vals[1::2] = -1 return self(vals)
Chebyshev basis functions T_n.
Below is the the instruction that describes the task: ### Input: Chebyshev basis functions T_n. ### Response: def basis(self, n): """ Chebyshev basis functions T_n. """ if n == 0: return self(np.array([1.])) vals = np.ones(n+1) vals[1::2] = -1 ret...
def snapshot(self): """Return a new library item which is a copy of this one with any dynamic behavior made static.""" display_item = self.__class__() display_item.display_type = self.display_type # metadata display_item._set_persistent_property_value("title", self._get_persisten...
Return a new library item which is a copy of this one with any dynamic behavior made static.
Below is the the instruction that describes the task: ### Input: Return a new library item which is a copy of this one with any dynamic behavior made static. ### Response: def snapshot(self): """Return a new library item which is a copy of this one with any dynamic behavior made static.""" display_...
def fuzz(self, obj): """ Perform the fuzzing """ buf = list(obj) FuzzFactor = random.randrange(1, len(buf)) numwrites=random.randrange(math.ceil((float(len(buf)) / FuzzFactor)))+1 for j in range(numwrites): self.random_action(buf) return self.s...
Perform the fuzzing
Below is the the instruction that describes the task: ### Input: Perform the fuzzing ### Response: def fuzz(self, obj): """ Perform the fuzzing """ buf = list(obj) FuzzFactor = random.randrange(1, len(buf)) numwrites=random.randrange(math.ceil((float(len(buf)) / Fuzz...
def position_at_end(self, block): """ Position at the end of the basic *block*. """ self._block = block self._anchor = len(block.instructions)
Position at the end of the basic *block*.
Below is the the instruction that describes the task: ### Input: Position at the end of the basic *block*. ### Response: def position_at_end(self, block): """ Position at the end of the basic *block*. """ self._block = block self._anchor = len(block.instructions)
def _get_transitions(self, probs, indexes, tree_idxs, batch_info, forward_steps=1, discount_factor=1.0): """ Return batch of frames for given indexes """ if forward_steps > 1: transition_arrays = self.backend.get_transitions_forward_steps(indexes, forward_steps, discount_factor) else...
Return batch of frames for given indexes
Below is the the instruction that describes the task: ### Input: Return batch of frames for given indexes ### Response: def _get_transitions(self, probs, indexes, tree_idxs, batch_info, forward_steps=1, discount_factor=1.0): """ Return batch of frames for given indexes """ if forward_steps > 1: ...
def safe_write(filename, blob): """ A two-step write. :param filename: full path :param blob: binary data :return: None """ temp_file = filename + '.saving' with open(temp_file, 'bw') as f: f.write(blob) os.rename(temp_file, filename)
A two-step write. :param filename: full path :param blob: binary data :return: None
Below is the the instruction that describes the task: ### Input: A two-step write. :param filename: full path :param blob: binary data :return: None ### Response: def safe_write(filename, blob): """ A two-step write. :param filename: full path :param blob: binary data :return: None ...
def get_FEC(molecule_list, temperature, pressure, electronic_energy='Default'): """Returns the Gibbs free energy corrections to be added to raw reaction energies. Parameters ---------- molecule_list : list of strings temperature : numeric temperature in K pressure : numeric press...
Returns the Gibbs free energy corrections to be added to raw reaction energies. Parameters ---------- molecule_list : list of strings temperature : numeric temperature in K pressure : numeric pressure in mbar Returns ------- G_H, G_OH : Gibbs free energy of proton and hy...
Below is the the instruction that describes the task: ### Input: Returns the Gibbs free energy corrections to be added to raw reaction energies. Parameters ---------- molecule_list : list of strings temperature : numeric temperature in K pressure : numeric pressure in mbar R...
def get_amr_line(input_f): """ Read the file containing AMRs. AMRs are separated by a blank line. Each call of get_amr_line() returns the next available AMR (in one-line form). Note: this function does not verify if the AMR is valid """ cur_amr = [] has_content =...
Read the file containing AMRs. AMRs are separated by a blank line. Each call of get_amr_line() returns the next available AMR (in one-line form). Note: this function does not verify if the AMR is valid
Below is the the instruction that describes the task: ### Input: Read the file containing AMRs. AMRs are separated by a blank line. Each call of get_amr_line() returns the next available AMR (in one-line form). Note: this function does not verify if the AMR is valid ### Response: def get_amr_line(i...
def _maybe_replace_path(self, match): """ Regex replacement method that will sub paths when needed """ path = match.group(0) if self._should_replace(path): return self._replace_path(path) else: return path
Regex replacement method that will sub paths when needed
Below is the the instruction that describes the task: ### Input: Regex replacement method that will sub paths when needed ### Response: def _maybe_replace_path(self, match): """ Regex replacement method that will sub paths when needed """ path = match.group(0) if self._should_replace(path):...
def _ctypes_out(parameter): """Returns a parameter variable declaration for an output variable for the specified parameter. """ if (parameter.dimension is not None and ":" in parameter.dimension and "out" in parameter.direction and ("allocatable" in parameter.modifiers or ...
Returns a parameter variable declaration for an output variable for the specified parameter.
Below is the the instruction that describes the task: ### Input: Returns a parameter variable declaration for an output variable for the specified parameter. ### Response: def _ctypes_out(parameter): """Returns a parameter variable declaration for an output variable for the specified parameter. """...
def _index_entities(self): ''' Sets current instance's entities based on the existing index. Note: Only entity key/value pairs common to all rows in all contained Variables are returned. E.g., if a Collection contains Variables extracted from runs 1, 2 and 3 from subject '01', t...
Sets current instance's entities based on the existing index. Note: Only entity key/value pairs common to all rows in all contained Variables are returned. E.g., if a Collection contains Variables extracted from runs 1, 2 and 3 from subject '01', the returned dict will be {'...
Below is the the instruction that describes the task: ### Input: Sets current instance's entities based on the existing index. Note: Only entity key/value pairs common to all rows in all contained Variables are returned. E.g., if a Collection contains Variables extracted from runs 1...
def resolve_objects(cls, objects, skip_cached_urls=False): """ Make sure all AnyUrlValue objects from a set of objects is resolved in bulk. This avoids making a query per item. :param objects: A list or queryset of models. :param skip_cached_urls: Whether to avoid prefetching da...
Make sure all AnyUrlValue objects from a set of objects is resolved in bulk. This avoids making a query per item. :param objects: A list or queryset of models. :param skip_cached_urls: Whether to avoid prefetching data that has it's URL cached.
Below is the the instruction that describes the task: ### Input: Make sure all AnyUrlValue objects from a set of objects is resolved in bulk. This avoids making a query per item. :param objects: A list or queryset of models. :param skip_cached_urls: Whether to avoid prefetching data that ha...
def solve_buffer(self, addr, nbytes, constrain=False): """ Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to concretize it :param int address: Address of buffer to concretize :param int nbytes: Size of buffer to concretize :param bool cons...
Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to concretize it :param int address: Address of buffer to concretize :param int nbytes: Size of buffer to concretize :param bool constrain: If True, constrain the buffer to the concretized value :retu...
Below is the the instruction that describes the task: ### Input: Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to concretize it :param int address: Address of buffer to concretize :param int nbytes: Size of buffer to concretize :param bool constrain:...
async def send_ssh_job_info(self, job_id: BackendJobId, host: str, port: int, key: str): """ Send info about the SSH debug connection to the backend/client. Must be called *at most once* for each job. :exception JobNotRunningException: is raised when the job is not running anymore (send_job_resu...
Send info about the SSH debug connection to the backend/client. Must be called *at most once* for each job. :exception JobNotRunningException: is raised when the job is not running anymore (send_job_result already called) :exception TooManyCallsException: is raised when this function has been called mor...
Below is the the instruction that describes the task: ### Input: Send info about the SSH debug connection to the backend/client. Must be called *at most once* for each job. :exception JobNotRunningException: is raised when the job is not running anymore (send_job_result already called) :exception To...
def getMajorMinor(deviceName, dmsetupLs): """ Given output of dmsetup ls this will return themajor:minor (block name) of the device deviceName """ startingIndex = string.rindex(dmsetupLs, deviceName) + len(deviceName) endingIndex = string.index(dmsetupLs[startingIndex:], "\n") + startingIndex ...
Given output of dmsetup ls this will return themajor:minor (block name) of the device deviceName
Below is the the instruction that describes the task: ### Input: Given output of dmsetup ls this will return themajor:minor (block name) of the device deviceName ### Response: def getMajorMinor(deviceName, dmsetupLs): """ Given output of dmsetup ls this will return themajor:minor (block name) of th...
def update(self): """Request an updated set of data from casper.jxml.""" response = self.jss.session.post(self.url, data=self.auth) response_xml = ElementTree.fromstring(response.text.encode("utf_8")) # Remove previous data, if any, and then add in response's XML. self.clear() ...
Request an updated set of data from casper.jxml.
Below is the the instruction that describes the task: ### Input: Request an updated set of data from casper.jxml. ### Response: def update(self): """Request an updated set of data from casper.jxml.""" response = self.jss.session.post(self.url, data=self.auth) response_xml = ElementTree.from...
def postinit(self, targets=None, value=None, type_annotation=None): """Do some setup after initialisation. :param targets: What is being assigned to. :type targets: list(NodeNG) or None :param value: The value being assigned to the variables. :type: NodeNG or None """ ...
Do some setup after initialisation. :param targets: What is being assigned to. :type targets: list(NodeNG) or None :param value: The value being assigned to the variables. :type: NodeNG or None
Below is the the instruction that describes the task: ### Input: Do some setup after initialisation. :param targets: What is being assigned to. :type targets: list(NodeNG) or None :param value: The value being assigned to the variables. :type: NodeNG or None ### Response: def post...
def rem_or(self, start, end, instr, target=None, include_beyond_target=False): """ Find all <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be spe...
Find all <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be specified which must match precisely. Return a list with indexes to them or [] if none found.
Below is the the instruction that describes the task: ### Input: Find all <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be specified which must match precis...
def _type_size(ty): """ Calculate `static` type size """ if ty[0] in ('int', 'uint', 'bytesM', 'function'): return 32 elif ty[0] in ('tuple'): result = 0 for ty_i in ty[1]: result += ABI._type_size(ty_i) return result elif t...
Calculate `static` type size
Below is the the instruction that describes the task: ### Input: Calculate `static` type size ### Response: def _type_size(ty): """ Calculate `static` type size """ if ty[0] in ('int', 'uint', 'bytesM', 'function'): return 32 elif ty[0] in ('tuple'): result = 0 ...
def get_environment(id=None, name=None): """ Get a specific Environment by name or ID """ data = get_environment_raw(id, name) if data: return utils.format_json(data)
Get a specific Environment by name or ID
Below is the the instruction that describes the task: ### Input: Get a specific Environment by name or ID ### Response: def get_environment(id=None, name=None): """ Get a specific Environment by name or ID """ data = get_environment_raw(id, name) if data: return utils.format_json(data)
def _compile_proto(full_path, dest): 'Helper to compile protobuf files' proto_path = os.path.dirname(full_path) protoc_args = [find_protoc(), '--python_out={}'.format(dest), '--proto_path={}'.format(proto_path), full_path] proc = subprocess...
Helper to compile protobuf files
Below is the the instruction that describes the task: ### Input: Helper to compile protobuf files ### Response: def _compile_proto(full_path, dest): 'Helper to compile protobuf files' proto_path = os.path.dirname(full_path) protoc_args = [find_protoc(), '--python_out={}'.format(d...
def permute(self, qubits: Qubits) -> 'Gate': """Permute the order of the qubits""" vec = self.vec.permute(qubits) return Gate(vec.tensor, qubits=vec.qubits)
Permute the order of the qubits
Below is the the instruction that describes the task: ### Input: Permute the order of the qubits ### Response: def permute(self, qubits: Qubits) -> 'Gate': """Permute the order of the qubits""" vec = self.vec.permute(qubits) return Gate(vec.tensor, qubits=vec.qubits)
def remove_role_from_user(self, user, role): """ Removes role from user """ user.remove_role(role) self.save(user) events.user_lost_role_event.send(user, role=role)
Removes role from user
Below is the the instruction that describes the task: ### Input: Removes role from user ### Response: def remove_role_from_user(self, user, role): """ Removes role from user """ user.remove_role(role) self.save(user) events.user_lost_role_event.send(user, role=role)
def tabulate( obj, v_level_indexes=None, h_level_indexes=None, v_level_visibility=None, h_level_visibility=None, v_level_sort_keys=None, h_level_sort_keys=None, v_level_titles=None, h_level_titles=None, empty="", ): """Render a nested data structure into a two-dimensional tab...
Render a nested data structure into a two-dimensional table. Args: obj: The indexable data structure to be rendered, which can either be a non-string sequence or a mapping containing other sequences and mappings nested to arbitrarily many levels, with all the leaf items ...
Below is the the instruction that describes the task: ### Input: Render a nested data structure into a two-dimensional table. Args: obj: The indexable data structure to be rendered, which can either be a non-string sequence or a mapping containing other sequences and mappings ne...
def compute_mpnn_qkv(node_states, total_key_depth, total_value_depth, num_transforms): """Computes query, key and value for edge matrices. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidd...
Computes query, key and value for edge matrices. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidden states. Let K be the size of the attention keys/queries (total_key_depth). Let V be the size of the attention values (total_value_depth). Let T be...
Below is the the instruction that describes the task: ### Input: Computes query, key and value for edge matrices. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidden states. Let K be the size of the attention keys/queries (total_key_depth). Let ...
def function_info(function_index=1, function_name=None, line_number=None): """ This will return the class_name and function_name of the function traced back two functions. :param function_index: int of how many frames back the program should look (2 will give the parent of t...
This will return the class_name and function_name of the function traced back two functions. :param function_index: int of how many frames back the program should look (2 will give the parent of the caller) :param function_name: str of what function to look for (should ...
Below is the the instruction that describes the task: ### Input: This will return the class_name and function_name of the function traced back two functions. :param function_index: int of how many frames back the program should look (2 will give the parent of the caller) :pa...
def nasm_null_safe_mutable_data_finalizer(env, code, data): """ Simple data allocation strategy that expects the code to be in a writable segment. We just append the data to the end of the code. """ if data or env.buffers: # Determine length of nullify + shellcode and adjust data pointer ...
Simple data allocation strategy that expects the code to be in a writable segment. We just append the data to the end of the code.
Below is the the instruction that describes the task: ### Input: Simple data allocation strategy that expects the code to be in a writable segment. We just append the data to the end of the code. ### Response: def nasm_null_safe_mutable_data_finalizer(env, code, data): """ Simple data allocation strate...
def datetime_to_year_quarter(dt): """ Args: dt: a datetime Returns: tuple of the datetime's year and quarter """ year = dt.year quarter = int(math.ceil(float(dt.month)/3)) return (year, quarter)
Args: dt: a datetime Returns: tuple of the datetime's year and quarter
Below is the the instruction that describes the task: ### Input: Args: dt: a datetime Returns: tuple of the datetime's year and quarter ### Response: def datetime_to_year_quarter(dt): """ Args: dt: a datetime Returns: tuple of the datetime's year and quarter """ ...
def __allocate_neuron_patterns(self, start_iteration, stop_iteration): """! @brief Allocates observation transposed matrix of neurons that is limited by specified periods of simulation. @details Matrix where state of each neuron is denoted by zero/one in line with Heaviside function on each i...
! @brief Allocates observation transposed matrix of neurons that is limited by specified periods of simulation. @details Matrix where state of each neuron is denoted by zero/one in line with Heaviside function on each iteration. @return (list) Transposed observation matrix that is l...
Below is the the instruction that describes the task: ### Input: ! @brief Allocates observation transposed matrix of neurons that is limited by specified periods of simulation. @details Matrix where state of each neuron is denoted by zero/one in line with Heaviside function on each iteration. ...
def resume_session_logging(self): """Resume session logging.""" self._chain.ctrl.set_session_log(self.session_fd) self.log("Session logging resumed")
Resume session logging.
Below is the the instruction that describes the task: ### Input: Resume session logging. ### Response: def resume_session_logging(self): """Resume session logging.""" self._chain.ctrl.set_session_log(self.session_fd) self.log("Session logging resumed")
def page(self, status=values.unset, iccid=values.unset, rate_plan=values.unset, e_id=values.unset, sim_registration_code=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of SimInstance records from...
Retrieve a single page of SimInstance records from the API. Request is executed immediately :param unicode status: The status :param unicode iccid: The iccid :param unicode rate_plan: The rate_plan :param unicode e_id: The e_id :param unicode sim_registration_code: The s...
Below is the the instruction that describes the task: ### Input: Retrieve a single page of SimInstance records from the API. Request is executed immediately :param unicode status: The status :param unicode iccid: The iccid :param unicode rate_plan: The rate_plan :param unico...
def render_traceback(self, excid=None): """render one or all of my tracebacks to a list of lines""" lines = [] if excid is None: for (en,ev,etb,ei) in self.elist: lines.append(self._get_engine_str(ei)) lines.extend((etb or 'No traceback available').spl...
render one or all of my tracebacks to a list of lines
Below is the the instruction that describes the task: ### Input: render one or all of my tracebacks to a list of lines ### Response: def render_traceback(self, excid=None): """render one or all of my tracebacks to a list of lines""" lines = [] if excid is None: for (en,ev,etb,ei...
def resolve_parameter_refs(self, input_dict, parameters): """ Substitute references found within the string of `Fn::Sub` intrinsic function :param input_dict: Dictionary representing the Fn::Sub function. Must contain only one key and it should be `Fn::Sub`. Ex: {"Fn::Sub": ...} ...
Substitute references found within the string of `Fn::Sub` intrinsic function :param input_dict: Dictionary representing the Fn::Sub function. Must contain only one key and it should be `Fn::Sub`. Ex: {"Fn::Sub": ...} :param parameters: Dictionary of parameter values for substitution ...
Below is the the instruction that describes the task: ### Input: Substitute references found within the string of `Fn::Sub` intrinsic function :param input_dict: Dictionary representing the Fn::Sub function. Must contain only one key and it should be `Fn::Sub`. Ex: {"Fn::Sub": ...} :pa...
def log_init(level): """Set up a logger that catches all channels and logs it to stdout. This is used to set up logging when testing. """ log = logging.getLogger() hdlr = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s') hdlr.se...
Set up a logger that catches all channels and logs it to stdout. This is used to set up logging when testing.
Below is the the instruction that describes the task: ### Input: Set up a logger that catches all channels and logs it to stdout. This is used to set up logging when testing. ### Response: def log_init(level): """Set up a logger that catches all channels and logs it to stdout. This is used to...
def create(self, validated_data): """ Perform the enrollment for existing enterprise customer users, or create the pending objects for new users. """ enterprise_customer = self.context.get('enterprise_customer') lms_user = validated_data.get('lms_user_id') tpa_user = vali...
Perform the enrollment for existing enterprise customer users, or create the pending objects for new users.
Below is the the instruction that describes the task: ### Input: Perform the enrollment for existing enterprise customer users, or create the pending objects for new users. ### Response: def create(self, validated_data): """ Perform the enrollment for existing enterprise customer users, or create t...
def get_metric(self, slug): """Get the current values for a metric. Returns a dictionary with metric values accumulated for the seconds, minutes, hours, day, week, month, and year. """ results = OrderedDict() granularities = self._granularities() keys = self._bu...
Get the current values for a metric. Returns a dictionary with metric values accumulated for the seconds, minutes, hours, day, week, month, and year.
Below is the the instruction that describes the task: ### Input: Get the current values for a metric. Returns a dictionary with metric values accumulated for the seconds, minutes, hours, day, week, month, and year. ### Response: def get_metric(self, slug): """Get the current values for a m...
def _init_polling(self): """ Bootstrap polling for throttler. To avoid spiky traffic from throttler clients, we use a random delay before the first poll. """ with self.lock: if not self.running: return r = random.Random() ...
Bootstrap polling for throttler. To avoid spiky traffic from throttler clients, we use a random delay before the first poll.
Below is the the instruction that describes the task: ### Input: Bootstrap polling for throttler. To avoid spiky traffic from throttler clients, we use a random delay before the first poll. ### Response: def _init_polling(self): """ Bootstrap polling for throttler. To avoi...
def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.utils.path.which('prtconf') if cmd: data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep for dest, ...
Return CPU information for AIX systems
Below is the the instruction that describes the task: ### Input: Return CPU information for AIX systems ### Response: def _aix_cpudata(): ''' Return CPU information for AIX systems ''' # Provides: # cpuarch # num_cpus # cpu_model # cpu_flags grains = {} cmd = salt.ut...
def team_scores(self, team_scores, time, show_datetime, use_12_hour_format): """Prints the teams scores in a pretty format""" for score in team_scores["matches"]: if score["status"] == "FINISHED": click.secho("%s\t" % score["utcDate"].split('T')[0], ...
Prints the teams scores in a pretty format
Below is the the instruction that describes the task: ### Input: Prints the teams scores in a pretty format ### Response: def team_scores(self, team_scores, time, show_datetime, use_12_hour_format): """Prints the teams scores in a pretty format""" for score in team_scores["matches"]: if...
def _parse_dependencies(string): """ This function actually parses the dependencies are sorts them into the buildable and given dependencies """ contents = _get_contents_between(string, '(', ')') unsorted_dependencies = contents.split(',') _check_parameters(unsorted_dependencies, ('?',)) ...
This function actually parses the dependencies are sorts them into the buildable and given dependencies
Below is the the instruction that describes the task: ### Input: This function actually parses the dependencies are sorts them into the buildable and given dependencies ### Response: def _parse_dependencies(string): """ This function actually parses the dependencies are sorts them into the buildabl...
def posthoc_mannwhitney(a, val_col=None, group_col=None, use_continuity=True, alternative='two-sided', p_adjust=None, sort=True): '''Pairwise comparisons with Mann-Whitney rank test. Parameters ---------- a : array_like or pandas DataFrame object An array, any object exposing the array interfa...
Pairwise comparisons with Mann-Whitney rank test. Parameters ---------- a : array_like or pandas DataFrame object An array, any object exposing the array interface or a pandas DataFrame. Array must be two-dimensional. val_col : str, optional Name of a DataFrame column that cont...
Below is the the instruction that describes the task: ### Input: Pairwise comparisons with Mann-Whitney rank test. Parameters ---------- a : array_like or pandas DataFrame object An array, any object exposing the array interface or a pandas DataFrame. Array must be two-dimensional. ...
def parse_line(line): """ Parses a byte string like: PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n to a `ProxyInfo`. """ if not line.startswith(b'PROXY'): raise exc.InvalidLine('Missing "PROXY" prefix', line) if not line.endswith(CRLF): raise exc.InvalidLine('Missing...
Parses a byte string like: PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n to a `ProxyInfo`.
Below is the the instruction that describes the task: ### Input: Parses a byte string like: PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n to a `ProxyInfo`. ### Response: def parse_line(line): """ Parses a byte string like: PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n to a...
def run(self, ds, skip_checks, *checker_names): """ Runs this CheckSuite on the dataset with all the passed Checker instances. Returns a dictionary mapping checker names to a 2-tuple of their grouped scores and errors/exceptions while running checks. """ ret_val = {} ch...
Runs this CheckSuite on the dataset with all the passed Checker instances. Returns a dictionary mapping checker names to a 2-tuple of their grouped scores and errors/exceptions while running checks.
Below is the the instruction that describes the task: ### Input: Runs this CheckSuite on the dataset with all the passed Checker instances. Returns a dictionary mapping checker names to a 2-tuple of their grouped scores and errors/exceptions while running checks. ### Response: def run(self, ds, skip_check...
def get_symbol(network, num_classes, from_layers, num_filters, sizes, ratios, strides, pads, normalizations=-1, steps=[], min_filter=128, nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs): """Build network for testing SSD Parameters ---------- network : str ...
Build network for testing SSD Parameters ---------- network : str base network symbol name num_classes : int number of object classes not including background from_layers : list of str feature extraction layers, use '' for add extra layers For example: from_l...
Below is the the instruction that describes the task: ### Input: Build network for testing SSD Parameters ---------- network : str base network symbol name num_classes : int number of object classes not including background from_layers : list of str feature extraction la...
def new_task(func): """ Runs the decorated function in a new task """ @wraps(func) async def wrapper(self, *args, **kwargs): loop = get_event_loop() loop.create_task(func(self, *args, **kwargs)) return wrapper
Runs the decorated function in a new task
Below is the the instruction that describes the task: ### Input: Runs the decorated function in a new task ### Response: def new_task(func): """ Runs the decorated function in a new task """ @wraps(func) async def wrapper(self, *args, **kwargs): loop = get_event_loop() loop.cre...
def send_invoice_email(self, invoice_id, email_dict): """ Sends an invoice by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param invoice_id: the invoice id :param email_dict: the...
Sends an invoice by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param invoice_id: the invoice id :param email_dict: the email dict :return dict
Below is the the instruction that describes the task: ### Input: Sends an invoice by email If you want to send your email to more than one persons do: 'recipients': {'to': ['bykof@me.com', 'mbykovski@seibert-media.net']}} :param invoice_id: the invoice id :param email_dict: the emai...
def _parse_argv(argv=copy(sys.argv)): """return argv as a parsed dictionary, looks like the following: app --option1 likethis --option2 likethat --flag -> {'option1': 'likethis', 'option2': 'likethat', 'flag': True} """ cfg = DotDict() cfg_files = [] argv = argv[1:] # Skip command n...
return argv as a parsed dictionary, looks like the following: app --option1 likethis --option2 likethat --flag -> {'option1': 'likethis', 'option2': 'likethat', 'flag': True}
Below is the the instruction that describes the task: ### Input: return argv as a parsed dictionary, looks like the following: app --option1 likethis --option2 likethat --flag -> {'option1': 'likethis', 'option2': 'likethat', 'flag': True} ### Response: def _parse_argv(argv=copy(sys.argv)): """r...
def brown(num_points=1024, b2=1.0, fs=1.0): """ Brownian or random walk (diffusion) noise with 1/f^2 PSD (not really a color... rather Brownian or random-walk) N = number of samples b2 = desired PSD is b2*f^-2 fs = sampling frequency we integrate white-noise to get Brownian...
Brownian or random walk (diffusion) noise with 1/f^2 PSD (not really a color... rather Brownian or random-walk) N = number of samples b2 = desired PSD is b2*f^-2 fs = sampling frequency we integrate white-noise to get Brownian noise.
Below is the the instruction that describes the task: ### Input: Brownian or random walk (diffusion) noise with 1/f^2 PSD (not really a color... rather Brownian or random-walk) N = number of samples b2 = desired PSD is b2*f^-2 fs = sampling frequency we integrate white-nois...
def feature_types(self): """Distinct types (``type_``) in :class:`.models.Feature` :return: all distinct feature types :rtype: list[str] """ r = self.session.query(distinct(models.Feature.type_)).all() return [x[0] for x in r]
Distinct types (``type_``) in :class:`.models.Feature` :return: all distinct feature types :rtype: list[str]
Below is the the instruction that describes the task: ### Input: Distinct types (``type_``) in :class:`.models.Feature` :return: all distinct feature types :rtype: list[str] ### Response: def feature_types(self): """Distinct types (``type_``) in :class:`.models.Feature` :return: a...
def to_dict(self, labels=None): """Convert LogEvent object to a dictionary.""" output = {} if labels is None: labels = ['line_str', 'split_tokens', 'datetime', 'operation', 'thread', 'namespace', 'nscanned', 'ntoreturn', 'nreturned', 'ninse...
Convert LogEvent object to a dictionary.
Below is the the instruction that describes the task: ### Input: Convert LogEvent object to a dictionary. ### Response: def to_dict(self, labels=None): """Convert LogEvent object to a dictionary.""" output = {} if labels is None: labels = ['line_str', 'split_tokens', 'datetime',...
def get(tree, name): """ Return a float value attribute NAME from TREE. """ if name in tree: value = tree[name] else: return float("nan") try: a = float(value) except ValueError: a = float("nan") return a
Return a float value attribute NAME from TREE.
Below is the the instruction that describes the task: ### Input: Return a float value attribute NAME from TREE. ### Response: def get(tree, name): """ Return a float value attribute NAME from TREE. """ if name in tree: value = tree[name] else: return float("nan") try: a ...
def _generate_time_steps(self, trajectory_list): """A generator to yield single time-steps from a list of trajectories.""" for single_trajectory in trajectory_list: assert isinstance(single_trajectory, trajectory.Trajectory) # Skip writing trajectories that have only a single time-step -- this ...
A generator to yield single time-steps from a list of trajectories.
Below is the the instruction that describes the task: ### Input: A generator to yield single time-steps from a list of trajectories. ### Response: def _generate_time_steps(self, trajectory_list): """A generator to yield single time-steps from a list of trajectories.""" for single_trajectory in trajectory_l...
def set_schedule(self, zone_info): """Sets the schedule for this zone""" # must only POST json, otherwise server API handler raises exceptions try: json.loads(zone_info) except ValueError as error: raise ValueError("zone_info must be valid JSON: ", error) ...
Sets the schedule for this zone
Below is the the instruction that describes the task: ### Input: Sets the schedule for this zone ### Response: def set_schedule(self, zone_info): """Sets the schedule for this zone""" # must only POST json, otherwise server API handler raises exceptions try: json.loads(zone_info...
def check_hash(path, file_hash): ''' Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versioncha...
Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument. .. versionchanged:: 2016.11.4 For this and newer ...
Below is the the instruction that describes the task: ### Input: Check if a file matches the given hash string Returns ``True`` if the hash matches, otherwise ``False``. path Path to a file local to the minion. hash The hash to check against the file specified in the ``path`` argument...
def getIteratorSetting(self, login, tableName, iteratorName, scope): """ Parameters: - login - tableName - iteratorName - scope """ self.send_getIteratorSetting(login, tableName, iteratorName, scope) return self.recv_getIteratorSetting()
Parameters: - login - tableName - iteratorName - scope
Below is the the instruction that describes the task: ### Input: Parameters: - login - tableName - iteratorName - scope ### Response: def getIteratorSetting(self, login, tableName, iteratorName, scope): """ Parameters: - login - tableName - iteratorName - scope "...
def first(self, expression, order_expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None): """Return the first element of a binned `expression`, where the values each bin are sorted by `order_expression`. Example: >>> import vaex ...
Return the first element of a binned `expression`, where the values each bin are sorted by `order_expression`. Example: >>> import vaex >>> df = vaex.example() >>> df.first(df.x, df.y, shape=8) >>> df.first(df.x, df.y, shape=8, binby=[df.y]) >>> df.first(df.x, df.y, sha...
Below is the the instruction that describes the task: ### Input: Return the first element of a binned `expression`, where the values each bin are sorted by `order_expression`. Example: >>> import vaex >>> df = vaex.example() >>> df.first(df.x, df.y, shape=8) >>> df.first(df...
def primers(self): """ Read in the primer file, and create a properly formatted output file that takes any degenerate bases into account """ with open(self.formattedprimers, 'w') as formatted: for record in SeqIO.parse(self.primerfile, 'fasta'): # from...
Read in the primer file, and create a properly formatted output file that takes any degenerate bases into account
Below is the the instruction that describes the task: ### Input: Read in the primer file, and create a properly formatted output file that takes any degenerate bases into account ### Response: def primers(self): """ Read in the primer file, and create a properly formatted output file that t...
def collectstatic(settings_module, bin_env=None, no_post_process=False, ignore=None, dry_run=False, clear=False, link=False, no_default_ignore=False, pythonpath=None, ...
Collect static files from each of your applications into a single location that can easily be served in production. CLI Example: .. code-block:: bash salt '*' django.collectstatic <settings_module>
Below is the the instruction that describes the task: ### Input: Collect static files from each of your applications into a single location that can easily be served in production. CLI Example: .. code-block:: bash salt '*' django.collectstatic <settings_module> ### Response: def collectstat...
def save_to_object(self): """Saves the current model state to a Python object. It also saves to disk but does not return the checkpoint path. Returns: Object holding checkpoint data. """ tmpdir = tempfile.mkdtemp("save_to_object", dir=self.logdir) checkpoint...
Saves the current model state to a Python object. It also saves to disk but does not return the checkpoint path. Returns: Object holding checkpoint data.
Below is the the instruction that describes the task: ### Input: Saves the current model state to a Python object. It also saves to disk but does not return the checkpoint path. Returns: Object holding checkpoint data. ### Response: def save_to_object(self): """Saves the curren...
def generate_np(self, x, **kwargs): """ Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image ...
Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array of shape (n, **image shape) for initial target images. Required f...
Below is the the instruction that describes the task: ### Input: Generate adversarial images in a for loop. :param y: An array of shape (n, nb_classes) for true labels. :param y_target: An array of shape (n, nb_classes) for target labels. Required for targeted attack. :param image_target: An array ...
def init(**kwargs): """Initialize the specified names in the specified databases. The general process is as follows: - Ensure the database in question exists - Ensure all tables exist in the database. """ # TODO: Iterate through all engines in name set. database = kwargs.pop('database'...
Initialize the specified names in the specified databases. The general process is as follows: - Ensure the database in question exists - Ensure all tables exist in the database.
Below is the the instruction that describes the task: ### Input: Initialize the specified names in the specified databases. The general process is as follows: - Ensure the database in question exists - Ensure all tables exist in the database. ### Response: def init(**kwargs): """Initialize the...
def numbafy(fn, args, compiler="jit", **nbkws): """ Compile a string, sympy expression or symengine expression using numba. Not all functions are supported by Python's numerical package (numpy). For difficult cases, valid Python code (as string) may be more suitable than symbolic expressions coming...
Compile a string, sympy expression or symengine expression using numba. Not all functions are supported by Python's numerical package (numpy). For difficult cases, valid Python code (as string) may be more suitable than symbolic expressions coming from sympy, symengine, etc. When compiling vectorized f...
Below is the the instruction that describes the task: ### Input: Compile a string, sympy expression or symengine expression using numba. Not all functions are supported by Python's numerical package (numpy). For difficult cases, valid Python code (as string) may be more suitable than symbolic expressio...
def del_handler(self, handle): """ Remove the handle registered for `handle` :raises KeyError: The handle wasn't registered. """ _, _, _, respondent = self._handle_map.pop(handle) if respondent: self._handles_by_respondent[respondent].discard(hand...
Remove the handle registered for `handle` :raises KeyError: The handle wasn't registered.
Below is the the instruction that describes the task: ### Input: Remove the handle registered for `handle` :raises KeyError: The handle wasn't registered. ### Response: def del_handler(self, handle): """ Remove the handle registered for `handle` :raises KeyError: ...
def keep_alive_timeout_callback(self): """ Check if elapsed time since last response exceeds our configured maximum keep alive timeout value and if so, close the transport pipe and let the response writer handle the error. :return: None """ time_elapsed = time() ...
Check if elapsed time since last response exceeds our configured maximum keep alive timeout value and if so, close the transport pipe and let the response writer handle the error. :return: None
Below is the the instruction that describes the task: ### Input: Check if elapsed time since last response exceeds our configured maximum keep alive timeout value and if so, close the transport pipe and let the response writer handle the error. :return: None ### Response: def keep_alive_ti...
def enumerate_spans(sentence: List[T], offset: int = 0, max_span_width: int = None, min_span_width: int = 1, filter_function: Callable[[List[T]], bool] = None) -> List[Tuple[int, int]]: """ Given a sentence, return all token spans w...
Given a sentence, return all token spans within the sentence. Spans are `inclusive`. Additionally, you can provide a maximum and minimum span width, which will be used to exclude spans outside of this range. Finally, you can provide a function mapping ``List[T] -> bool``, which will be applied to every...
Below is the the instruction that describes the task: ### Input: Given a sentence, return all token spans within the sentence. Spans are `inclusive`. Additionally, you can provide a maximum and minimum span width, which will be used to exclude spans outside of this range. Finally, you can provide a fun...
def calc_synch_snu_ujy(b, ne, delta, sinth, width, elongation, dist, ghz, E0=1.): """Calculate a flux density from pure gyrosynchrotron emission. This combines Dulk (1985) equations 40 and 41, which are fitting functions assuming a power-law electron population, with standard radiative transfer through...
Calculate a flux density from pure gyrosynchrotron emission. This combines Dulk (1985) equations 40 and 41, which are fitting functions assuming a power-law electron population, with standard radiative transfer through a uniform medium. Arguments are: b Magnetic field strength in Gauss ne ...
Below is the the instruction that describes the task: ### Input: Calculate a flux density from pure gyrosynchrotron emission. This combines Dulk (1985) equations 40 and 41, which are fitting functions assuming a power-law electron population, with standard radiative transfer through a uniform medium. A...
def GetArtifactsForCollection(os_name, artifact_list): """Wrapper for the ArtifactArranger. Extend the artifact list by dependencies and sort the artifacts to resolve the dependencies. Args: os_name: String specifying the OS name. artifact_list: List of requested artifact names. Returns: A list...
Wrapper for the ArtifactArranger. Extend the artifact list by dependencies and sort the artifacts to resolve the dependencies. Args: os_name: String specifying the OS name. artifact_list: List of requested artifact names. Returns: A list of artifacts such that if they are collected in the given o...
Below is the the instruction that describes the task: ### Input: Wrapper for the ArtifactArranger. Extend the artifact list by dependencies and sort the artifacts to resolve the dependencies. Args: os_name: String specifying the OS name. artifact_list: List of requested artifact names. Returns: ...
def _int_from_str(string): """ Convert string into integer Raise: TypeError if string is not a valid integer """ float_num = float(string) int_num = int(float_num) if float_num == int_num: return int_num else: # Needed to handle pseudos with fractional charge ...
Convert string into integer Raise: TypeError if string is not a valid integer
Below is the the instruction that describes the task: ### Input: Convert string into integer Raise: TypeError if string is not a valid integer ### Response: def _int_from_str(string): """ Convert string into integer Raise: TypeError if string is not a valid integer """ flo...
def refill(self, from_address, to_address, nfees, ntokens, password, min_confirmations=6, sync=False): """ Refill wallets with the necessary fuel to perform spool transactions Args: from_address (Tuple[str]): Federation wallet address. Fuels the wallets with tokens and fees. All tra...
Refill wallets with the necessary fuel to perform spool transactions Args: from_address (Tuple[str]): Federation wallet address. Fuels the wallets with tokens and fees. All transactions to wallets holding a particular piece should come from the Federation wallet to_addre...
Below is the the instruction that describes the task: ### Input: Refill wallets with the necessary fuel to perform spool transactions Args: from_address (Tuple[str]): Federation wallet address. Fuels the wallets with tokens and fees. All transactions to wallets holding a particu...
def iter_callback_properties(self): """ Iterator to loop over all callback properties. """ for name in dir(self): if self.is_callback_property(name): yield name, getattr(type(self), name)
Iterator to loop over all callback properties.
Below is the the instruction that describes the task: ### Input: Iterator to loop over all callback properties. ### Response: def iter_callback_properties(self): """ Iterator to loop over all callback properties. """ for name in dir(self): if self.is_callback_property(na...
def sign(self, storepass=None, keypass=None, keystore=None, apk=None, alias=None, name='app'): """ Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default. :param storepass(str): keystore file storepass :param keypass(str): keystore file...
Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default. :param storepass(str): keystore file storepass :param keypass(str): keystore file keypass :param keystore(str): keystore file path :param apk(str): apk file path to be signed :...
Below is the the instruction that describes the task: ### Input: Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default. :param storepass(str): keystore file storepass :param keypass(str): keystore file keypass :param keystore(str): key...
def _get_opstr(op, cls): """ Find the operation string, if any, to pass to numexpr for this operation. Parameters ---------- op : binary operator cls : class Returns ------- op_str : string or None """ # numexpr is available for non-sparse classes subtyp = getattr(c...
Find the operation string, if any, to pass to numexpr for this operation. Parameters ---------- op : binary operator cls : class Returns ------- op_str : string or None
Below is the the instruction that describes the task: ### Input: Find the operation string, if any, to pass to numexpr for this operation. Parameters ---------- op : binary operator cls : class Returns ------- op_str : string or None ### Response: def _get_opstr(op, cls): """ ...
def to_ipa(s): """Convert *s* to IPA.""" identity = identify(s) if identity == IPA: return s elif identity == PINYIN: return pinyin_to_ipa(s) elif identity == ZHUYIN: return zhuyin_to_ipa(s) else: raise ValueError("String is not a valid Chinese transcription.")
Convert *s* to IPA.
Below is the the instruction that describes the task: ### Input: Convert *s* to IPA. ### Response: def to_ipa(s): """Convert *s* to IPA.""" identity = identify(s) if identity == IPA: return s elif identity == PINYIN: return pinyin_to_ipa(s) elif identity == ZHUYIN: retur...
def sanitizeString(name): """Cleans string in preparation for splitting for use as a pairtree identifier.""" newString = name # string cleaning, pass 1 replaceTable = [ ('^', '^5e'), # we need to do this one first ('"', '^22'), ('<', '^3c'), ('?', '^3f'), ('*...
Cleans string in preparation for splitting for use as a pairtree identifier.
Below is the the instruction that describes the task: ### Input: Cleans string in preparation for splitting for use as a pairtree identifier. ### Response: def sanitizeString(name): """Cleans string in preparation for splitting for use as a pairtree identifier.""" newString = name # string clea...
def is_instance_running(self, instance_id): """ Check if the instance is up and running. :param str instance_id: instance identifier :return: bool - True if running, False otherwise """ self._init_az_api() # Here, it's always better if we update the instance. ...
Check if the instance is up and running. :param str instance_id: instance identifier :return: bool - True if running, False otherwise
Below is the the instruction that describes the task: ### Input: Check if the instance is up and running. :param str instance_id: instance identifier :return: bool - True if running, False otherwise ### Response: def is_instance_running(self, instance_id): """ Check if the instanc...
def from_series(self, series, add_index_column=True): """ Set tabular attributes to the writer from :py:class:`pandas.Series`. Following attributes are set by the method: - :py:attr:`~.headers` - :py:attr:`~.value_matrix` - :py:attr:`~.type_hints` Ar...
Set tabular attributes to the writer from :py:class:`pandas.Series`. Following attributes are set by the method: - :py:attr:`~.headers` - :py:attr:`~.value_matrix` - :py:attr:`~.type_hints` Args: series(pandas.Series): Input pandas.Series...
Below is the the instruction that describes the task: ### Input: Set tabular attributes to the writer from :py:class:`pandas.Series`. Following attributes are set by the method: - :py:attr:`~.headers` - :py:attr:`~.value_matrix` - :py:attr:`~.type_hints` Args: ...
def _move_file_with_sizecheck(tx_file, final_file): """Move transaction file to final location, with size checks avoiding failed transfers. Creates an empty file with '.bcbiotmp' extention in the destination location, which serves as a flag. If a file like that is present, it means that...
Move transaction file to final location, with size checks avoiding failed transfers. Creates an empty file with '.bcbiotmp' extention in the destination location, which serves as a flag. If a file like that is present, it means that transaction didn't finish successfully.
Below is the the instruction that describes the task: ### Input: Move transaction file to final location, with size checks avoiding failed transfers. Creates an empty file with '.bcbiotmp' extention in the destination location, which serves as a flag. If a file like that is present, it ...
def text_to_title(value): """when a title is required, generate one from the value""" title = None if not value: return title words = value.split(" ") keep_words = [] for word in words: if word.endswith(".") or word.endswith(":"): keep_words.append(word) i...
when a title is required, generate one from the value
Below is the the instruction that describes the task: ### Input: when a title is required, generate one from the value ### Response: def text_to_title(value): """when a title is required, generate one from the value""" title = None if not value: return title words = value.split(" ") kee...