code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def trim_struct_time(st, strip_time=False): """ Return a `struct_time` based on the one provided but with the extra fields `tm_wday`, `tm_yday`, and `tm_isdst` reset to default values. If `strip_time` is set to true the time value are also set to zero: `tm_hour`, `tm_min`, and `tm_sec`. """ ...
Return a `struct_time` based on the one provided but with the extra fields `tm_wday`, `tm_yday`, and `tm_isdst` reset to default values. If `strip_time` is set to true the time value are also set to zero: `tm_hour`, `tm_min`, and `tm_sec`.
Below is the the instruction that describes the task: ### Input: Return a `struct_time` based on the one provided but with the extra fields `tm_wday`, `tm_yday`, and `tm_isdst` reset to default values. If `strip_time` is set to true the time value are also set to zero: `tm_hour`, `tm_min`, and `tm_sec`...
def fix_e131(self, result): """Fix indentation undistinguish from the next logical line.""" num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] spaces_to_add = num_indent_spaces - len(_get_indentation(target)) ...
Fix indentation undistinguish from the next logical line.
Below is the the instruction that describes the task: ### Input: Fix indentation undistinguish from the next logical line. ### Response: def fix_e131(self, result): """Fix indentation undistinguish from the next logical line.""" num_indent_spaces = int(result['info'].split()[1]) line_index ...
def get_referenced_object(self): """ :rtype: core.BunqModel :raise: BunqException """ if self._BunqMeFundraiserResult is not None: return self._BunqMeFundraiserResult if self._BunqMeTab is not None: return self._BunqMeTab if self._BunqMe...
:rtype: core.BunqModel :raise: BunqException
Below is the the instruction that describes the task: ### Input: :rtype: core.BunqModel :raise: BunqException ### Response: def get_referenced_object(self): """ :rtype: core.BunqModel :raise: BunqException """ if self._BunqMeFundraiserResult is not None: ...
def _SendTerminationMessage(self, status=None): """This notifies the parent flow of our termination.""" if not self.runner_args.request_state.session_id: # No parent flow, nothing to do here. return if status is None: status = rdf_flows.GrrStatus() client_resources = self.context.cli...
This notifies the parent flow of our termination.
Below is the the instruction that describes the task: ### Input: This notifies the parent flow of our termination. ### Response: def _SendTerminationMessage(self, status=None): """This notifies the parent flow of our termination.""" if not self.runner_args.request_state.session_id: # No parent flow, ...
def compress (input_filename, output_filename=None, verbose=False): """compress(input_filename, output_filename=None, verbose=False) -> integer Uses zlib to compress input_filename and store the result in output_filename. The size of output_filename is returned on success; zero is returned on failure. The ...
compress(input_filename, output_filename=None, verbose=False) -> integer Uses zlib to compress input_filename and store the result in output_filename. The size of output_filename is returned on success; zero is returned on failure. The input file is compressed in one fell swoop. The output_filename defaul...
Below is the the instruction that describes the task: ### Input: compress(input_filename, output_filename=None, verbose=False) -> integer Uses zlib to compress input_filename and store the result in output_filename. The size of output_filename is returned on success; zero is returned on failure. The inpu...
def benchmark_file( filename, compiler, include_dirs, (progress_from, progress_to), iter_count, extra_flags = ''): """Benchmark one file""" time_sum = 0 mem_sum = 0 for nth_run in xrange(0, iter_count): (time_spent, mem_used) = benchmark_command( '{0} -std=c++11 {1} -...
Benchmark one file
Below is the the instruction that describes the task: ### Input: Benchmark one file ### Response: def benchmark_file( filename, compiler, include_dirs, (progress_from, progress_to), iter_count, extra_flags = ''): """Benchmark one file""" time_sum = 0 mem_sum = 0 for nth_run in xrang...
def mixed_density(qubits: Union[int, Qubits]) -> Density: """Returns the completely mixed density matrix""" N, qubits = qubits_count_tuple(qubits) matrix = np.eye(2**N) / 2**N return Density(matrix, qubits)
Returns the completely mixed density matrix
Below is the the instruction that describes the task: ### Input: Returns the completely mixed density matrix ### Response: def mixed_density(qubits: Union[int, Qubits]) -> Density: """Returns the completely mixed density matrix""" N, qubits = qubits_count_tuple(qubits) matrix = np.eye(2**N) / 2**N ...
def load_exports(self, args=None): """Load all export modules in the 'exports' folder.""" if args is None: return False header = "glances_" # Build the export module available list args_var = vars(locals()['args']) for item in os.listdir(exports_path): ...
Load all export modules in the 'exports' folder.
Below is the the instruction that describes the task: ### Input: Load all export modules in the 'exports' folder. ### Response: def load_exports(self, args=None): """Load all export modules in the 'exports' folder.""" if args is None: return False header = "glances_" # B...
async def disable(self, ctx, *, command: str): """Disables a command for this server. You must have Manage Server permissions or the Bot Admin role to use this command. """ command = command.lower() if command in ('enable', 'disable'): return await self.bot....
Disables a command for this server. You must have Manage Server permissions or the Bot Admin role to use this command.
Below is the the instruction that describes the task: ### Input: Disables a command for this server. You must have Manage Server permissions or the Bot Admin role to use this command. ### Response: async def disable(self, ctx, *, command: str): """Disables a command for this server. ...
def normalize_spl_by_average(self, db): """ Normalize the values in the AudioSegment so that its `spl` property gives `db`. .. note:: This method is currently broken - it returns an AudioSegment whose values are much smaller than reasonable, yet which yield an SPL valu...
Normalize the values in the AudioSegment so that its `spl` property gives `db`. .. note:: This method is currently broken - it returns an AudioSegment whose values are much smaller than reasonable, yet which yield an SPL value that equals the given `db`. Such an Audi...
Below is the the instruction that describes the task: ### Input: Normalize the values in the AudioSegment so that its `spl` property gives `db`. .. note:: This method is currently broken - it returns an AudioSegment whose values are much smaller than reasonable, yet which yield an...
def get_nodes(self, coord, coords): """Get the variables containing the definition of the nodes Parameters ---------- coord: xarray.Coordinate The mesh variable coords: dict The coordinates to use to get node coordinates""" def get_coord(coord): ...
Get the variables containing the definition of the nodes Parameters ---------- coord: xarray.Coordinate The mesh variable coords: dict The coordinates to use to get node coordinates
Below is the the instruction that describes the task: ### Input: Get the variables containing the definition of the nodes Parameters ---------- coord: xarray.Coordinate The mesh variable coords: dict The coordinates to use to get node coordinates ### Response...
def put_archive(self, container, path, data): """ Insert a file or folder in an existing container using a tar archive as source. Args: container (str): The container where the file(s) will be extracted path (str): Path inside the container where the file(s) will...
Insert a file or folder in an existing container using a tar archive as source. Args: container (str): The container where the file(s) will be extracted path (str): Path inside the container where the file(s) will be extracted. Must exist. data (bytes...
Below is the the instruction that describes the task: ### Input: Insert a file or folder in an existing container using a tar archive as source. Args: container (str): The container where the file(s) will be extracted path (str): Path inside the container where the file(s) w...
def viewer_has_liked(self) -> Optional[bool]: """Whether the viewer has liked the post, or None if not logged in.""" if not self._context.is_logged_in: return None if 'likes' in self._node and 'viewer_has_liked' in self._node['likes']: return self._node['likes']['viewer_h...
Whether the viewer has liked the post, or None if not logged in.
Below is the the instruction that describes the task: ### Input: Whether the viewer has liked the post, or None if not logged in. ### Response: def viewer_has_liked(self) -> Optional[bool]: """Whether the viewer has liked the post, or None if not logged in.""" if not self._context.is_logged_in: ...
def channel_in_frame(channel, framefile): """Determine whether a channel is stored in this framefile **Requires:** |LDAStools.frameCPP|_ Parameters ---------- channel : `str` name of channel to find framefile : `str` path of GWF file to test Returns ------- infram...
Determine whether a channel is stored in this framefile **Requires:** |LDAStools.frameCPP|_ Parameters ---------- channel : `str` name of channel to find framefile : `str` path of GWF file to test Returns ------- inframe : `bool` whether this channel is includ...
Below is the the instruction that describes the task: ### Input: Determine whether a channel is stored in this framefile **Requires:** |LDAStools.frameCPP|_ Parameters ---------- channel : `str` name of channel to find framefile : `str` path of GWF file to test Returns ...
def to_json(self, buffer_or_path=None, indent=2): """ Parameters ---------- buffer_or_path: buffer or path, default None output to write into. If None, will return a json string. indent: int, default 2 Defines the indentation of the json Returns ...
Parameters ---------- buffer_or_path: buffer or path, default None output to write into. If None, will return a json string. indent: int, default 2 Defines the indentation of the json Returns ------- None, or a json string (if buffer_or_path is No...
Below is the the instruction that describes the task: ### Input: Parameters ---------- buffer_or_path: buffer or path, default None output to write into. If None, will return a json string. indent: int, default 2 Defines the indentation of the json Returns ...
def to_dict(self): """ Returns a dictionary representation of the dataset. """ d = dict(doses=self.doses, ns=self.ns, incidences=self.incidences) d.update(self.kwargs) return d
Returns a dictionary representation of the dataset.
Below is the the instruction that describes the task: ### Input: Returns a dictionary representation of the dataset. ### Response: def to_dict(self): """ Returns a dictionary representation of the dataset. """ d = dict(doses=self.doses, ns=self.ns, incidences=self.incidences) ...
def sql_key(self, generation, sql, params, order, result_type, using='default'): """ Return the specific cache key for the sql query described by the pieces of the query and the generation key. """ # these keys will always look pretty opaque suffix = self....
Return the specific cache key for the sql query described by the pieces of the query and the generation key.
Below is the the instruction that describes the task: ### Input: Return the specific cache key for the sql query described by the pieces of the query and the generation key. ### Response: def sql_key(self, generation, sql, params, order, result_type, using='default'): """ Re...
def load(self, data): """Add a bunch of data. Must be in chronological order. But it doesn't need to all be from the same branch, as long as each branch is chronological of itself. """ branches = defaultdict(list) for row in data: branches[row[-4]].append(ro...
Add a bunch of data. Must be in chronological order. But it doesn't need to all be from the same branch, as long as each branch is chronological of itself.
Below is the the instruction that describes the task: ### Input: Add a bunch of data. Must be in chronological order. But it doesn't need to all be from the same branch, as long as each branch is chronological of itself. ### Response: def load(self, data): """Add a bunch of data. Must be i...
def len(self, queue_name): """ Returns the length of the queue. :param queue_name: The name of the queue. Usually handled by the ``Gator`` instance. :type queue_name: string :returns: The length of the queue :rtype: integer """ try: ...
Returns the length of the queue. :param queue_name: The name of the queue. Usually handled by the ``Gator`` instance. :type queue_name: string :returns: The length of the queue :rtype: integer
Below is the the instruction that describes the task: ### Input: Returns the length of the queue. :param queue_name: The name of the queue. Usually handled by the ``Gator`` instance. :type queue_name: string :returns: The length of the queue :rtype: integer ### Response...
def say( text = None, preference_program = "festival", background = False, silent = True, filepath = None ): """ Say specified text to speakers or to file, as specified. Determine the program to use based on the specified program preference...
Say specified text to speakers or to file, as specified. Determine the program to use based on the specified program preference and availability, then say the text to speakers or synthesize speech of the text and save it to file, as specified.
Below is the the instruction that describes the task: ### Input: Say specified text to speakers or to file, as specified. Determine the program to use based on the specified program preference and availability, then say the text to speakers or synthesize speech of the text and save it to file, as specif...
def rpc(_cloud_rpc_name, **params): """ 调用 LeanEngine 上的远程代码 与 cloud.run 类似,但是允许传入 leancloud.Object 作为参数,也允许传入 leancloud.Object 作为结果 :param name: 需要调用的远程 Cloud Code 的名称 :type name: basestring :param params: 调用参数 :return: 调用结果 """ encoded_params = {} for key, value in params.items...
调用 LeanEngine 上的远程代码 与 cloud.run 类似,但是允许传入 leancloud.Object 作为参数,也允许传入 leancloud.Object 作为结果 :param name: 需要调用的远程 Cloud Code 的名称 :type name: basestring :param params: 调用参数 :return: 调用结果
Below is the the instruction that describes the task: ### Input: 调用 LeanEngine 上的远程代码 与 cloud.run 类似,但是允许传入 leancloud.Object 作为参数,也允许传入 leancloud.Object 作为结果 :param name: 需要调用的远程 Cloud Code 的名称 :type name: basestring :param params: 调用参数 :return: 调用结果 ### Response: def rpc(_cloud_rpc_name, **par...
def ensemble_simulations( t, y0=None, volume=1.0, model=None, solver='ode', is_netfree=False, species_list=None, without_reset=False, return_type='matplotlib', opt_args=(), opt_kwargs=None, structures=None, rndseed=None, n=1, nproc=None, method=None, errorbar=True, **kwargs): """ Run sim...
Run simulations multiple times and return its ensemble. Arguments are almost same with ``ecell4.util.simulation.run_simulation``. `observers` and `progressbar` is not available here. Parameters ---------- n : int, optional A number of runs. Default is 1. nproc : int, optional A ...
Below is the the instruction that describes the task: ### Input: Run simulations multiple times and return its ensemble. Arguments are almost same with ``ecell4.util.simulation.run_simulation``. `observers` and `progressbar` is not available here. Parameters ---------- n : int, optional ...
def bind_unique(reference, query_list, min_overlap=12, right=True): '''(5' or 3' region on reference sequence that uniquely matches the reverse complement of the associated (5' or 3') region of one sequence in a list of query sequences. :param reference: Reference sequence. :type reference: coral.D...
(5' or 3' region on reference sequence that uniquely matches the reverse complement of the associated (5' or 3') region of one sequence in a list of query sequences. :param reference: Reference sequence. :type reference: coral.DNA :param query_list: List of query sequences. :type query_list: co...
Below is the the instruction that describes the task: ### Input: (5' or 3' region on reference sequence that uniquely matches the reverse complement of the associated (5' or 3') region of one sequence in a list of query sequences. :param reference: Reference sequence. :type reference: coral.DNA ...
def _resolve_formatter(self, attr): """Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability. Return a ``ParametrizingString`` or a ``FormattingString``. """ if attr in COLORS: return self._resolve_color(at...
Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability. Return a ``ParametrizingString`` or a ``FormattingString``.
Below is the the instruction that describes the task: ### Input: Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability. Return a ``ParametrizingString`` or a ``FormattingString``. ### Response: def _resolve_formatter(self, attr): ...
def strip_lastharaka(text): """Strip the last Haraka from arabic word except Shadda. The striped marks are : - FATHA, DAMMA, KASRA - SUKUN - FATHATAN, DAMMATAN, KASRATAN @param text: arabic text. @type text: unicode. @return: return a striped text. @rtype: unicode. ...
Strip the last Haraka from arabic word except Shadda. The striped marks are : - FATHA, DAMMA, KASRA - SUKUN - FATHATAN, DAMMATAN, KASRATAN @param text: arabic text. @type text: unicode. @return: return a striped text. @rtype: unicode.
Below is the the instruction that describes the task: ### Input: Strip the last Haraka from arabic word except Shadda. The striped marks are : - FATHA, DAMMA, KASRA - SUKUN - FATHATAN, DAMMATAN, KASRATAN @param text: arabic text. @type text: unicode. @return: return a st...
def _iter_process_command(mapping, pid, max_depth): """Iterator to traverse up the tree, yielding `argv[0]` of each process. """ for _ in range(max_depth): try: proc = mapping[pid] except KeyError: # We've reached the root process. Give up. break try: ...
Iterator to traverse up the tree, yielding `argv[0]` of each process.
Below is the the instruction that describes the task: ### Input: Iterator to traverse up the tree, yielding `argv[0]` of each process. ### Response: def _iter_process_command(mapping, pid, max_depth): """Iterator to traverse up the tree, yielding `argv[0]` of each process. """ for _ in range(max_depth)...
def area(poly): """Calculation of zone area""" poly_xy = [] num = len(poly) for i in range(num): poly[i] = poly[i][0:2] + (0,) poly_xy.append(poly[i]) return surface.area(poly)
Calculation of zone area
Below is the the instruction that describes the task: ### Input: Calculation of zone area ### Response: def area(poly): """Calculation of zone area""" poly_xy = [] num = len(poly) for i in range(num): poly[i] = poly[i][0:2] + (0,) poly_xy.append(poly[i]) return surface.area(poly...
def models_list(self, api_url=None, offset=0, limit=-1, properties=None): """Get list of model resources from a SCO-API. Parameters ---------- api_url : string, optional Base Url of the SCO-API. Uses default API if argument not present. offset : int, optional ...
Get list of model resources from a SCO-API. Parameters ---------- api_url : string, optional Base Url of the SCO-API. Uses default API if argument not present. offset : int, optional Starting offset for returned list items limit : int, optional ...
Below is the the instruction that describes the task: ### Input: Get list of model resources from a SCO-API. Parameters ---------- api_url : string, optional Base Url of the SCO-API. Uses default API if argument not present. offset : int, optional Starting of...
def make_file_exist(self, filename=None): """Make the directory exist, then touch the file If the filename is None, then use self.name as filename """ if filename is None: path_to_file = FilePath(self) path_to_file.make_file_exist() return path_to_fil...
Make the directory exist, then touch the file If the filename is None, then use self.name as filename
Below is the the instruction that describes the task: ### Input: Make the directory exist, then touch the file If the filename is None, then use self.name as filename ### Response: def make_file_exist(self, filename=None): """Make the directory exist, then touch the file If the filename i...
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name" in the specified app. If the name does not contain an app name (no colon), an empty list is returned. The parent FilesystemLoader.load_template_source() will take ...
Returns the absolute paths to "template_name" in the specified app. If the name does not contain an app name (no colon), an empty list is returned. The parent FilesystemLoader.load_template_source() will take care of the actual loading for us.
Below is the the instruction that describes the task: ### Input: Returns the absolute paths to "template_name" in the specified app. If the name does not contain an app name (no colon), an empty list is returned. The parent FilesystemLoader.load_template_source() will take care of th...
def hostname(self, value): """ The hostname where the log message was created. Should be the first part of the hostname, or an IP address. Should NOT be set to a fully qualified domain name. """ if value is None: value = socket.gethostname() ...
The hostname where the log message was created. Should be the first part of the hostname, or an IP address. Should NOT be set to a fully qualified domain name.
Below is the the instruction that describes the task: ### Input: The hostname where the log message was created. Should be the first part of the hostname, or an IP address. Should NOT be set to a fully qualified domain name. ### Response: def hostname(self, value): """ The ...
def build_distribution(): """Build distributions of the code.""" result = invoke.run('python setup.py sdist bdist_egg bdist_wheel', warn=True, hide=True) if result.ok: print("[{}GOOD{}] Distribution built without errors." .format(GOOD_COLOR, RESET_COLOR)) el...
Build distributions of the code.
Below is the the instruction that describes the task: ### Input: Build distributions of the code. ### Response: def build_distribution(): """Build distributions of the code.""" result = invoke.run('python setup.py sdist bdist_egg bdist_wheel', warn=True, hide=True) if result.ok:...
def calculate_indent(text): """ :param text: :type text: str :return: """ indent = 0 for c in text: if c is '\t': raise ValueError() if c is not ' ': return indent,text[indent:] indent += 1 return indent,''
:param text: :type text: str :return:
Below is the the instruction that describes the task: ### Input: :param text: :type text: str :return: ### Response: def calculate_indent(text): """ :param text: :type text: str :return: """ indent = 0 for c in text: if c is '\t': raise ValueError() i...
def bam_region_to_fasta(data, sample, proc1, chrom, region_start, region_end): """ Take the chromosome position, and start and end bases and return sequences of all reads that overlap these sites. This is the command we're building: samtools view -b 1A_sorted.bam 1:116202035-116202060 | \ ...
Take the chromosome position, and start and end bases and return sequences of all reads that overlap these sites. This is the command we're building: samtools view -b 1A_sorted.bam 1:116202035-116202060 | \ samtools bam2fq <options> - -b : output bam format -0 : ...
Below is the the instruction that describes the task: ### Input: Take the chromosome position, and start and end bases and return sequences of all reads that overlap these sites. This is the command we're building: samtools view -b 1A_sorted.bam 1:116202035-116202060 | \ samtools bam2fq <optio...
def template_response(self, template_name, headers={}, **values): """ Constructs a response, allowing custom template name and content_type """ response = make_response( self.render_template(template_name, **values)) for field, value in headers.items(): r...
Constructs a response, allowing custom template name and content_type
Below is the the instruction that describes the task: ### Input: Constructs a response, allowing custom template name and content_type ### Response: def template_response(self, template_name, headers={}, **values): """ Constructs a response, allowing custom template name and content_type ""...
def lpc(x, N=None): """Linear Predictor Coefficients. :param x: :param int N: default is length(X) - 1 :Details: Finds the coefficients :math:`A=(1, a(2), \dots a(N+1))`, of an Nth order forward linear predictor that predicts the current value value of the real-valued time series x based ...
Linear Predictor Coefficients. :param x: :param int N: default is length(X) - 1 :Details: Finds the coefficients :math:`A=(1, a(2), \dots a(N+1))`, of an Nth order forward linear predictor that predicts the current value value of the real-valued time series x based on past samples: .. ma...
Below is the the instruction that describes the task: ### Input: Linear Predictor Coefficients. :param x: :param int N: default is length(X) - 1 :Details: Finds the coefficients :math:`A=(1, a(2), \dots a(N+1))`, of an Nth order forward linear predictor that predicts the current value value o...
def _generate_fixed_param_names(self, param_names: List[str], strategy: str) -> List[str]: """ Generate a fixed parameter list given a list of all parameter names and a strategy. """ # Number of encoder/decoder layers in model. if isinstance(self.config.config_encoder, Em...
Generate a fixed parameter list given a list of all parameter names and a strategy.
Below is the the instruction that describes the task: ### Input: Generate a fixed parameter list given a list of all parameter names and a strategy. ### Response: def _generate_fixed_param_names(self, param_names: List[str], strategy: str) -> List[str]: """ Generate a fixed parameter list g...
def parse_redir(self, redir_cmd): """ Parse a command :redir content. """ redir_cmd_str = redir_cmd['str'] matched = re.match(r'redir?!?\s*(=>>?\s*)(\S+)', redir_cmd_str) if matched: redir_cmd_op = matched.group(1) redir_cmd_body = matched.group(2) a...
Parse a command :redir content.
Below is the the instruction that describes the task: ### Input: Parse a command :redir content. ### Response: def parse_redir(self, redir_cmd): """ Parse a command :redir content. """ redir_cmd_str = redir_cmd['str'] matched = re.match(r'redir?!?\s*(=>>?\s*)(\S+)', redir_cmd_str) ...
def get_server_alerts(call=None, for_output=True, **kwargs): ''' Return a list of alerts from CLC as reported by their infra ''' for key, value in kwargs.items(): servername = "" if key == "servername": servername = value creds = get_creds() clc.v2.SetCredentials(cred...
Return a list of alerts from CLC as reported by their infra
Below is the the instruction that describes the task: ### Input: Return a list of alerts from CLC as reported by their infra ### Response: def get_server_alerts(call=None, for_output=True, **kwargs): ''' Return a list of alerts from CLC as reported by their infra ''' for key, value in kwargs.items(...
def error(self,stanza): """ Called when an error stanza is received. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `pyxmpp.stanza.Stanza` """ err=stanza.get_error() self.__logger.debug("Error from: %r Condition: %r" ...
Called when an error stanza is received. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `pyxmpp.stanza.Stanza`
Below is the the instruction that describes the task: ### Input: Called when an error stanza is received. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `pyxmpp.stanza.Stanza` ### Response: def error(self,stanza): """ Called when an error ...
def instruction_BNE(self, opcode, ea): """ Tests the state of the Z (zero) bit and causes a branch if it is clear. When used after a subtract or compare operation on any binary values, this instruction will branch if the register is, or would be, not equal to the memory register....
Tests the state of the Z (zero) bit and causes a branch if it is clear. When used after a subtract or compare operation on any binary values, this instruction will branch if the register is, or would be, not equal to the memory register. source code forms: BNE dd; LBNE DDDD CC ...
Below is the the instruction that describes the task: ### Input: Tests the state of the Z (zero) bit and causes a branch if it is clear. When used after a subtract or compare operation on any binary values, this instruction will branch if the register is, or would be, not equal to the memory...
def callback(self, request, **kwargs): """ Called from the Service when the user accept to activate it :param request: request object :return: callback url :rtype: string , path to the template """ return super(ServiceTrello, self).callback(request...
Called from the Service when the user accept to activate it :param request: request object :return: callback url :rtype: string , path to the template
Below is the the instruction that describes the task: ### Input: Called from the Service when the user accept to activate it :param request: request object :return: callback url :rtype: string , path to the template ### Response: def callback(self, request, **kwargs): ""...
def validate_platform_dependencies(self): """Check all jvm targets in the context, throwing an error or warning if there are bad targets. If there are errors, this method fails slow rather than fails fast -- that is, it continues checking the rest of the targets before spitting error messages. This is usef...
Check all jvm targets in the context, throwing an error or warning if there are bad targets. If there are errors, this method fails slow rather than fails fast -- that is, it continues checking the rest of the targets before spitting error messages. This is useful, because it's nice to have a comprehensive...
Below is the the instruction that describes the task: ### Input: Check all jvm targets in the context, throwing an error or warning if there are bad targets. If there are errors, this method fails slow rather than fails fast -- that is, it continues checking the rest of the targets before spitting error me...
def set_gid(self): """Change the group of the running process""" if self.group: gid = getgrnam(self.group).gr_gid try: os.setgid(gid) except Exception: message = ("Unable to switch ownership to {0}:{1}. " + "D...
Change the group of the running process
Below is the the instruction that describes the task: ### Input: Change the group of the running process ### Response: def set_gid(self): """Change the group of the running process""" if self.group: gid = getgrnam(self.group).gr_gid try: os.setgid(gid) ...
def all(self, res): "Get resources using a filter condition" B = get_backend() return B.get_objects(B.get_concrete(res))
Get resources using a filter condition
Below is the the instruction that describes the task: ### Input: Get resources using a filter condition ### Response: def all(self, res): "Get resources using a filter condition" B = get_backend() return B.get_objects(B.get_concrete(res))
def _service_is_chkconfig(name): ''' Return True if the service is managed by chkconfig. ''' cmdline = '/sbin/chkconfig --list {0}'.format(name) return __salt__['cmd.retcode'](cmdline, python_shell=False, ignore_retcode=True) == 0
Return True if the service is managed by chkconfig.
Below is the the instruction that describes the task: ### Input: Return True if the service is managed by chkconfig. ### Response: def _service_is_chkconfig(name): ''' Return True if the service is managed by chkconfig. ''' cmdline = '/sbin/chkconfig --list {0}'.format(name) return __salt__['cm...
def signal_list_names(type_): """Returns a list of signal names for the given type :param type\\_: :type type\\_: :obj:`GObject.GType` :returns: A list of signal names :rtype: :obj:`list` """ ids = signal_list_ids(type_) return tuple(GObjectModule.signal_name(i) for i in ids)
Returns a list of signal names for the given type :param type\\_: :type type\\_: :obj:`GObject.GType` :returns: A list of signal names :rtype: :obj:`list`
Below is the the instruction that describes the task: ### Input: Returns a list of signal names for the given type :param type\\_: :type type\\_: :obj:`GObject.GType` :returns: A list of signal names :rtype: :obj:`list` ### Response: def signal_list_names(type_): """Returns a list of signal na...
def arg_parser(self, passed_args=None): """Setup argument Parsing. If preset args are to be specified use the ``passed_args`` tuple. :param passed_args: ``list`` :return: ``dict`` """ parser, subpar, remaining_argv = self._setup_parser() if not isinstance(passed...
Setup argument Parsing. If preset args are to be specified use the ``passed_args`` tuple. :param passed_args: ``list`` :return: ``dict``
Below is the the instruction that describes the task: ### Input: Setup argument Parsing. If preset args are to be specified use the ``passed_args`` tuple. :param passed_args: ``list`` :return: ``dict`` ### Response: def arg_parser(self, passed_args=None): """Setup argument Parsing...
def _filter_validate(filepath, location, values, validate): """Generator for validate() results called against all given values. On errors, fields are warned about and ignored, unless strict mode is set in which case a compiler error is raised. """ for value in values: if not isinstance(valu...
Generator for validate() results called against all given values. On errors, fields are warned about and ignored, unless strict mode is set in which case a compiler error is raised.
Below is the the instruction that describes the task: ### Input: Generator for validate() results called against all given values. On errors, fields are warned about and ignored, unless strict mode is set in which case a compiler error is raised. ### Response: def _filter_validate(filepath, location, value...
def build_clustbits(data, ipyclient, force): """ Reconstitutes clusters from .utemp and htemp files and writes them to chunked files for aligning in muscle. """ ## If you run this step then we clear all tmp .fa and .indel.h5 files if os.path.exists(data.tmpdir): shutil.rmtree(data.tmpdi...
Reconstitutes clusters from .utemp and htemp files and writes them to chunked files for aligning in muscle.
Below is the the instruction that describes the task: ### Input: Reconstitutes clusters from .utemp and htemp files and writes them to chunked files for aligning in muscle. ### Response: def build_clustbits(data, ipyclient, force): """ Reconstitutes clusters from .utemp and htemp files and writes them ...
def _lower_non_existent_context_field_filters(match_traversals, visitor_fn): """Return new match traversals, lowering filters involving non-existent ContextFields. Expressions involving non-existent ContextFields are evaluated to TrueLiteral. BinaryCompositions, where one of the operands is lowered to a Tr...
Return new match traversals, lowering filters involving non-existent ContextFields. Expressions involving non-existent ContextFields are evaluated to TrueLiteral. BinaryCompositions, where one of the operands is lowered to a TrueLiteral, are lowered appropriately based on the present operator (u'||' and u'...
Below is the the instruction that describes the task: ### Input: Return new match traversals, lowering filters involving non-existent ContextFields. Expressions involving non-existent ContextFields are evaluated to TrueLiteral. BinaryCompositions, where one of the operands is lowered to a TrueLiteral, ...
def _get_rows(self, options): """Return only those data rows that should be printed, based on slicing and sorting. Arguments: options - dictionary of option settings.""" if options["oldsortslice"]: rows = copy.deepcopy(self._rows[options["start"]:options["end"]]) e...
Return only those data rows that should be printed, based on slicing and sorting. Arguments: options - dictionary of option settings.
Below is the the instruction that describes the task: ### Input: Return only those data rows that should be printed, based on slicing and sorting. Arguments: options - dictionary of option settings. ### Response: def _get_rows(self, options): """Return only those data rows that should be ...
def save_indexed_audio(self, indexed_audio_file_abs_path): """ Writes the corrected timestamps to a file. Timestamps are a python dictionary. Parameters ---------- indexed_audio_file_abs_path : str """ with open(indexed_audio_file_abs_path, "wb") as f: ...
Writes the corrected timestamps to a file. Timestamps are a python dictionary. Parameters ---------- indexed_audio_file_abs_path : str
Below is the the instruction that describes the task: ### Input: Writes the corrected timestamps to a file. Timestamps are a python dictionary. Parameters ---------- indexed_audio_file_abs_path : str ### Response: def save_indexed_audio(self, indexed_audio_file_abs_path): "...
def path_shift(script_name, path_info, shift=1): ''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift....
Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction....
Below is the the instruction that describes the task: ### Input: Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragmen...
def dropEvent(self, event): """Reimplement Qt method Unpack dropped data and handle it""" source = event.mimeData() # The second check is necessary when mimedata2url(source) # returns None. # Fixes issue 7742 if source.hasUrls() and mimedata2url(source): ...
Reimplement Qt method Unpack dropped data and handle it
Below is the the instruction that describes the task: ### Input: Reimplement Qt method Unpack dropped data and handle it ### Response: def dropEvent(self, event): """Reimplement Qt method Unpack dropped data and handle it""" source = event.mimeData() # The second check ...
def generate_query(self): """ Reduces multiple queries into a single usable query """ query = Q() ORed = [] for form in self._non_deleted_forms: if not hasattr(form, 'cleaned_data'): continue if form.cleaned_data['field'] == "_OR": ...
Reduces multiple queries into a single usable query
Below is the the instruction that describes the task: ### Input: Reduces multiple queries into a single usable query ### Response: def generate_query(self): """ Reduces multiple queries into a single usable query """ query = Q() ORed = [] for form in self._non_deleted_forms: ...
def load_config(filename=None, section_option_dict={}): """ This function returns a Bunch object from the stated config file. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NOTE: The values are not evaluated by default. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!...
This function returns a Bunch object from the stated config file. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NOTE: The values are not evaluated by default. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! filename: The desired...
Below is the the instruction that describes the task: ### Input: This function returns a Bunch object from the stated config file. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! NOTE: The values are not evaluated by default. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!...
def _propagate_url(self): """Ensure self.url contains full transport://interface:port""" if self.url: iface = self.url.split('://',1) if len(iface) == 2: self.transport,iface = iface iface = iface.split(':') self.ip = iface[0] i...
Ensure self.url contains full transport://interface:port
Below is the the instruction that describes the task: ### Input: Ensure self.url contains full transport://interface:port ### Response: def _propagate_url(self): """Ensure self.url contains full transport://interface:port""" if self.url: iface = self.url.split('://',1) if le...
def _inferSchemaFromList(self, data, names=None): """ Infer schema from list of Row or tuple. :param data: list of Row or tuple :param names: list of column names :return: :class:`pyspark.sql.types.StructType` """ if not data: raise ValueError("can no...
Infer schema from list of Row or tuple. :param data: list of Row or tuple :param names: list of column names :return: :class:`pyspark.sql.types.StructType`
Below is the the instruction that describes the task: ### Input: Infer schema from list of Row or tuple. :param data: list of Row or tuple :param names: list of column names :return: :class:`pyspark.sql.types.StructType` ### Response: def _inferSchemaFromList(self, data, names=None): ...
def scale_tax_scales(self, factor): """Scale all the MarginalRateTaxScales in the node.""" assert isinstance(factor, (float, int)) scaled_tax_scale = self.copy() return scaled_tax_scale.multiply_thresholds(factor)
Scale all the MarginalRateTaxScales in the node.
Below is the the instruction that describes the task: ### Input: Scale all the MarginalRateTaxScales in the node. ### Response: def scale_tax_scales(self, factor): """Scale all the MarginalRateTaxScales in the node.""" assert isinstance(factor, (float, int)) scaled_tax_scale = self.copy() ...
def sortedbyAge(self): ''' Sorting the pop. base of the age ''' ageAll = numpy.zeros(self.length) for i in range(self.length): ageAll[i] = self.Ind[i].age ageSorted = ageAll.argsort() return ageSorted[::-1]
Sorting the pop. base of the age
Below is the the instruction that describes the task: ### Input: Sorting the pop. base of the age ### Response: def sortedbyAge(self): ''' Sorting the pop. base of the age ''' ageAll = numpy.zeros(self.length) for i in range(self.length): ageAll[i] = self.Ind[i].age ageSorted = ageAll.argsort() re...
def update(dest, variation, path=None): """ Deep merges dictionary object variation into dest, dest keys in variation will be assigned new values from variation :param dest: :param variation: :param path: :return: """ if dest is None: r...
Deep merges dictionary object variation into dest, dest keys in variation will be assigned new values from variation :param dest: :param variation: :param path: :return:
Below is the the instruction that describes the task: ### Input: Deep merges dictionary object variation into dest, dest keys in variation will be assigned new values from variation :param dest: :param variation: :param path: :return: ### Response: def update(dest, variation...
def _read_rec_with_var( self, colnums, rows, dtype, offsets, isvar, vstorage): """ Read columns from a table into a rec array, including variable length columns. This is special because, for efficiency, it involves reading from the main table as normal but skipping the colum...
Read columns from a table into a rec array, including variable length columns. This is special because, for efficiency, it involves reading from the main table as normal but skipping the columns in the array that are variable. Then reading the variable length columns, with accounting f...
Below is the the instruction that describes the task: ### Input: Read columns from a table into a rec array, including variable length columns. This is special because, for efficiency, it involves reading from the main table as normal but skipping the columns in the array that are variable....
def flushOutBoxes(self) -> None: """ Clear the outBoxes and transmit batched messages to remotes. """ removedRemotes = [] for rid, msgs in self.outBoxes.items(): try: dest = self.remotes[rid].name except KeyError: removedRem...
Clear the outBoxes and transmit batched messages to remotes.
Below is the the instruction that describes the task: ### Input: Clear the outBoxes and transmit batched messages to remotes. ### Response: def flushOutBoxes(self) -> None: """ Clear the outBoxes and transmit batched messages to remotes. """ removedRemotes = [] for rid, msgs...
def diff(self, n): """Print the differences between the two files """ if os.path.isfile(n[:-4]): diff1 = Utils().read_file(n[:-4]).splitlines() if os.path.isfile(n): diff2 = Utils().read_file(n).splitlines() lines, l, c = [], 0, 0 for a, b in itert...
Print the differences between the two files
Below is the the instruction that describes the task: ### Input: Print the differences between the two files ### Response: def diff(self, n): """Print the differences between the two files """ if os.path.isfile(n[:-4]): diff1 = Utils().read_file(n[:-4]).splitlines() if o...
def _get_server_name(self, handle, service_profile_mo, ucsm_ip): """Get the contents of the 'Name' field associated with UCS Server. When a valid connection hande to UCS Manager is handed in, the Name field associated with a UCS Server is returned. """ try: resolved_...
Get the contents of the 'Name' field associated with UCS Server. When a valid connection hande to UCS Manager is handed in, the Name field associated with a UCS Server is returned.
Below is the the instruction that describes the task: ### Input: Get the contents of the 'Name' field associated with UCS Server. When a valid connection hande to UCS Manager is handed in, the Name field associated with a UCS Server is returned. ### Response: def _get_server_name(self, handle, ser...
def _merge_files(self, input_files, output_file): """Combine the input files to a big output file""" # we assume that all the input files have the same charset with open(output_file, mode='wb') as out: for input_file in input_files: out.write(open(input_file, mode='rb...
Combine the input files to a big output file
Below is the the instruction that describes the task: ### Input: Combine the input files to a big output file ### Response: def _merge_files(self, input_files, output_file): """Combine the input files to a big output file""" # we assume that all the input files have the same charset with op...
def parse_package_extended(identifier): """ Parses the extended package syntax and returns a tuple of (package, hash, version, tag). """ match = EXTENDED_PACKAGE_RE.match(identifier) if match is None: raise ValueError full_name, pkg_hash, version, tag = match.groups() team, user, na...
Parses the extended package syntax and returns a tuple of (package, hash, version, tag).
Below is the the instruction that describes the task: ### Input: Parses the extended package syntax and returns a tuple of (package, hash, version, tag). ### Response: def parse_package_extended(identifier): """ Parses the extended package syntax and returns a tuple of (package, hash, version, tag). ""...
def main(): """ Discards all pairs of sentences which can't be decoded by latin-1 encoder. It aims to filter out sentences with rare unicode glyphs and pairs which are most likely not valid English-German sentences. Examples of discarded sentences: ✿★★★Hommage au king de la pop ★★★✿ ✿★★★Q...
Discards all pairs of sentences which can't be decoded by latin-1 encoder. It aims to filter out sentences with rare unicode glyphs and pairs which are most likely not valid English-German sentences. Examples of discarded sentences: ✿★★★Hommage au king de la pop ★★★✿ ✿★★★Que son âme repos... ...
Below is the the instruction that describes the task: ### Input: Discards all pairs of sentences which can't be decoded by latin-1 encoder. It aims to filter out sentences with rare unicode glyphs and pairs which are most likely not valid English-German sentences. Examples of discarded sentences: ...
def transform(self, X, y=None, sample_weight=None): ''' Transforms the time series data into segments Note this transformation changes the number of samples in the data If y is provided, it is segmented and transformed to align to the new samples as per ``y_func`` Current...
Transforms the time series data into segments Note this transformation changes the number of samples in the data If y is provided, it is segmented and transformed to align to the new samples as per ``y_func`` Currently sample weights always returned as None Parameters --...
Below is the the instruction that describes the task: ### Input: Transforms the time series data into segments Note this transformation changes the number of samples in the data If y is provided, it is segmented and transformed to align to the new samples as per ``y_func`` Currently ...
def begin_training(self, get_gold_tuples=None, sgd=None, component_cfg=None, **cfg): """Allocate models, pre-process training data and acquire a trainer and optimizer. Used as a contextmanager. get_gold_tuples (function): Function returning gold data component_cfg (dict): Config paramet...
Allocate models, pre-process training data and acquire a trainer and optimizer. Used as a contextmanager. get_gold_tuples (function): Function returning gold data component_cfg (dict): Config parameters for specific components. **cfg: Config parameters. RETURNS: An optimizer. ...
Below is the the instruction that describes the task: ### Input: Allocate models, pre-process training data and acquire a trainer and optimizer. Used as a contextmanager. get_gold_tuples (function): Function returning gold data component_cfg (dict): Config parameters for specific components...
def wgs84_to_pixel(lng, lat, transform, utm_epsg=None, truncate=True): """ Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be calculated it automatically. :param lng: longitude of point :type lng: float :param lat: latitude of point :...
Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be calculated it automatically. :param lng: longitude of point :type lng: float :param lat: latitude of point :type lat: float :param transform: georeferencing transform of the image, e....
Below is the the instruction that describes the task: ### Input: Convert WGS84 coordinates to pixel image coordinates given transform and UTM CRS. If no CRS is given it will be calculated it automatically. :param lng: longitude of point :type lng: float :param lat: latitude of point :type lat: ...
def get_description(self): """ Get transaction description (for logging purposes) """ if self.card: card_description = self.card.get_description() else: card_description = 'Cardless' if card_description: card_description += ' | ' ...
Get transaction description (for logging purposes)
Below is the the instruction that describes the task: ### Input: Get transaction description (for logging purposes) ### Response: def get_description(self): """ Get transaction description (for logging purposes) """ if self.card: card_description = self.card.get_descript...
def create_signature(self, base_url, payload=None): """ Creates unique signature for request. Make sure ALL 'GET' and 'POST' data is already included before creating the signature or receiver won't be able to re-create it. :param base_url: The url you'll using for yo...
Creates unique signature for request. Make sure ALL 'GET' and 'POST' data is already included before creating the signature or receiver won't be able to re-create it. :param base_url: The url you'll using for your request. :param payload: The POST data that you'l...
Below is the the instruction that describes the task: ### Input: Creates unique signature for request. Make sure ALL 'GET' and 'POST' data is already included before creating the signature or receiver won't be able to re-create it. :param base_url: The url you'll using for your ...
def _add_slide_number(self, slide_no): """Add the slide number to the output if enabled.""" if self.builder.config.slide_numbers: self.body.append( '\n<div class="slide-no">%s</div>\n' % (slide_no,), )
Add the slide number to the output if enabled.
Below is the the instruction that describes the task: ### Input: Add the slide number to the output if enabled. ### Response: def _add_slide_number(self, slide_no): """Add the slide number to the output if enabled.""" if self.builder.config.slide_numbers: self.body.append( ...
def allowed_classes(self): """Iterate over the allowed classes for this slot. The Python equivalent of the CLIPS slot-allowed-classes function. """ data = clips.data.DataObject(self._env) lib.EnvSlotAllowedClasses( self._env, self._cls, self._name, data.byref) ...
Iterate over the allowed classes for this slot. The Python equivalent of the CLIPS slot-allowed-classes function.
Below is the the instruction that describes the task: ### Input: Iterate over the allowed classes for this slot. The Python equivalent of the CLIPS slot-allowed-classes function. ### Response: def allowed_classes(self): """Iterate over the allowed classes for this slot. The Python equival...
def _commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1] != item[:i+1]: prefix = prefix[:i] if i == 0: ...
Given a list of pathnames, returns the longest common leading component
Below is the the instruction that describes the task: ### Input: Given a list of pathnames, returns the longest common leading component ### Response: def _commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' prefix = m[0] for item i...
def has_property(obj, name): """ Checks if object has a property with specified name. :param obj: an object to introspect. :param name: a name of the property to check. :return: true if the object has the property and false if it doesn't. """ if obj == None: ...
Checks if object has a property with specified name. :param obj: an object to introspect. :param name: a name of the property to check. :return: true if the object has the property and false if it doesn't.
Below is the the instruction that describes the task: ### Input: Checks if object has a property with specified name. :param obj: an object to introspect. :param name: a name of the property to check. :return: true if the object has the property and false if it doesn't. ### Response: def...
def get_mass_distribution(bestMasses, scaleFactor, massRangeParams, metricParams, fUpper, numJumpPoints=100, chirpMassJumpFac=0.0001, etaJumpFac=0.01, spin1zJumpFac=0.01, spin2zJumpFac=0.01): """ Given a set ...
Given a set of masses, this function will create a set of points nearby in the mass space and map these to the xi space. Parameters ----------- bestMasses : list Contains [ChirpMass, eta, spin1z, spin2z]. Points will be placed around tjos scaleFactor : float This parameter d...
Below is the the instruction that describes the task: ### Input: Given a set of masses, this function will create a set of points nearby in the mass space and map these to the xi space. Parameters ----------- bestMasses : list Contains [ChirpMass, eta, spin1z, spin2z]. Points will be placed...
def splitport (host, port=0): """Split optional port number from host. If host has no port number, the given default port is returned. @param host: host name @ptype host: string @param port: the port number (default 0) @ptype port: int @return: tuple of (host, port) @rtype: tuple of (s...
Split optional port number from host. If host has no port number, the given default port is returned. @param host: host name @ptype host: string @param port: the port number (default 0) @ptype port: int @return: tuple of (host, port) @rtype: tuple of (string, int)
Below is the the instruction that describes the task: ### Input: Split optional port number from host. If host has no port number, the given default port is returned. @param host: host name @ptype host: string @param port: the port number (default 0) @ptype port: int @return: tuple of (hos...
def _add_rg(unmapped_file, config, names): """Add the missing RG header.""" picard = broad.runner_from_path("picard", config) rg_fixed = picard.run_fn("picard_fix_rgs", unmapped_file, names) return rg_fixed
Add the missing RG header.
Below is the the instruction that describes the task: ### Input: Add the missing RG header. ### Response: def _add_rg(unmapped_file, config, names): """Add the missing RG header.""" picard = broad.runner_from_path("picard", config) rg_fixed = picard.run_fn("picard_fix_rgs", unmapped_file, names) re...
def read(self): """ Validate pidfile and make it stale if needed""" if not self.fname: return try: with open(self.fname, "r") as f: wpid = int(f.read() or 0) if wpid <= 0: return return wpid excep...
Validate pidfile and make it stale if needed
Below is the the instruction that describes the task: ### Input: Validate pidfile and make it stale if needed ### Response: def read(self): """ Validate pidfile and make it stale if needed""" if not self.fname: return try: with open(self.fname, "r") as f: ...
def w_func(self, X, d, n): """Evaluate the (possibly recursive) warping function and its derivatives. Parameters ---------- X : array, (`M`,) The points (from dimension `d`) to evaluate the warping function at. d : int The dimension to warp. ...
Evaluate the (possibly recursive) warping function and its derivatives. Parameters ---------- X : array, (`M`,) The points (from dimension `d`) to evaluate the warping function at. d : int The dimension to warp. n : int The derivative ...
Below is the the instruction that describes the task: ### Input: Evaluate the (possibly recursive) warping function and its derivatives. Parameters ---------- X : array, (`M`,) The points (from dimension `d`) to evaluate the warping function at. d : int ...
def retarget(songs, duration, music_labels=None, out_labels=None, out_penalty=None, volume=None, volume_breakpoints=None, springs=None, constraints=None, min_beats=None, max_beats=None, fade_in_len=3.0, fade_out_len=5.0, **kwargs): """Retarget a song ...
Retarget a song to a duration given input and output labels on the music. Suppose you like one section of a song, say, the guitar solo, and you want to create a three minute long version of the solo. Suppose the guitar solo occurs from the 150 second mark to the 200 second mark in the original song...
Below is the the instruction that describes the task: ### Input: Retarget a song to a duration given input and output labels on the music. Suppose you like one section of a song, say, the guitar solo, and you want to create a three minute long version of the solo. Suppose the guitar solo occurs fro...
def mirror(self, tables, dest_url): """ miror a set of `tables` from `dest_url` Returns a new Genome object Parameters ---------- tables : list an iterable of tables dest_url: str a dburl string, e.g. 'sqlite:///local.db' """ ...
miror a set of `tables` from `dest_url` Returns a new Genome object Parameters ---------- tables : list an iterable of tables dest_url: str a dburl string, e.g. 'sqlite:///local.db'
Below is the the instruction that describes the task: ### Input: miror a set of `tables` from `dest_url` Returns a new Genome object Parameters ---------- tables : list an iterable of tables dest_url: str a dburl string, e.g. 'sqlite:///local.db' #...
def timex_spans(self): """The list of spans of ``timexes`` layer elements.""" if not self.is_tagged(TIMEXES): self.tag_timexes() return self.spans(TIMEXES)
The list of spans of ``timexes`` layer elements.
Below is the the instruction that describes the task: ### Input: The list of spans of ``timexes`` layer elements. ### Response: def timex_spans(self): """The list of spans of ``timexes`` layer elements.""" if not self.is_tagged(TIMEXES): self.tag_timexes() return self.spans(TIME...
def parse_time_indices(s): """Parse a string as time indices. Args: s: A valid slicing string for time indices. E.g., '-1', '[:]', ':', '2:10' Returns: A slice object. Raises: ValueError: If `s` does not represent valid time indices. """ if not s.startswith('['): s = '[' + s + ']' parse...
Parse a string as time indices. Args: s: A valid slicing string for time indices. E.g., '-1', '[:]', ':', '2:10' Returns: A slice object. Raises: ValueError: If `s` does not represent valid time indices.
Below is the the instruction that describes the task: ### Input: Parse a string as time indices. Args: s: A valid slicing string for time indices. E.g., '-1', '[:]', ':', '2:10' Returns: A slice object. Raises: ValueError: If `s` does not represent valid time indices. ### Response: def parse_t...
def create_schema(alembic_config_ini=None): """Create the database schema. :param alembic_config_ini: When provided, stamp with the current revision version. """ Base.metadata.create_all() if alembic_config_ini: from alembic.config import Config from alembic import command ...
Create the database schema. :param alembic_config_ini: When provided, stamp with the current revision version.
Below is the the instruction that describes the task: ### Input: Create the database schema. :param alembic_config_ini: When provided, stamp with the current revision version. ### Response: def create_schema(alembic_config_ini=None): """Create the database schema. :param alembic_config_ini: When ...
def _lswitch_select_open(self, context, switches=None, **kwargs): """Selects an open lswitch for a network. Note that it does not select the most full switch, but merely one with ports available. """ if switches is not None: for res in switches["results"]: ...
Selects an open lswitch for a network. Note that it does not select the most full switch, but merely one with ports available.
Below is the the instruction that describes the task: ### Input: Selects an open lswitch for a network. Note that it does not select the most full switch, but merely one with ports available. ### Response: def _lswitch_select_open(self, context, switches=None, **kwargs): """Selects an open...
def get_raw_token(self, header): """ Extracts an unvalidated JSON web token from the given "Authorization" header value. """ parts = header.split() if len(parts) == 0: # Empty AUTHORIZATION header sent return None if parts[0] not in AUTH_...
Extracts an unvalidated JSON web token from the given "Authorization" header value.
Below is the the instruction that describes the task: ### Input: Extracts an unvalidated JSON web token from the given "Authorization" header value. ### Response: def get_raw_token(self, header): """ Extracts an unvalidated JSON web token from the given "Authorization" header value....
def order_queryset(self, queryset): """ Orders the passed in queryset, returning a new queryset in response. By default uses the _order query parameter. """ order = self.derive_ordering() # if we get our order from the request # make sure it is a valid field in ...
Orders the passed in queryset, returning a new queryset in response. By default uses the _order query parameter.
Below is the the instruction that describes the task: ### Input: Orders the passed in queryset, returning a new queryset in response. By default uses the _order query parameter. ### Response: def order_queryset(self, queryset): """ Orders the passed in queryset, returning a new queryset in...
def form_invalid(self, form, forms, open_tabs, position_form_default): """ Called if a form is invalid. Re-renders the context data with the data-filled forms and errors. """ # return self.render_to_response( self.get_context_data( form = form, forms = forms ) ) return self.rende...
Called if a form is invalid. Re-renders the context data with the data-filled forms and errors.
Below is the the instruction that describes the task: ### Input: Called if a form is invalid. Re-renders the context data with the data-filled forms and errors. ### Response: def form_invalid(self, form, forms, open_tabs, position_form_default): """ Called if a form is invalid. Re-renders the conte...
def load_map(stream, name=None, check_integrity=True, check_duplicates=True): """ Loads a ContainerMap configuration from a YAML document stream. :param stream: YAML stream. :type stream: file :param name: Name of the ContainerMap. If not provided, will be attempted to read from a ``name`` attribut...
Loads a ContainerMap configuration from a YAML document stream. :param stream: YAML stream. :type stream: file :param name: Name of the ContainerMap. If not provided, will be attempted to read from a ``name`` attribute on the document root level. :type name: unicode | str :param check_integri...
Below is the the instruction that describes the task: ### Input: Loads a ContainerMap configuration from a YAML document stream. :param stream: YAML stream. :type stream: file :param name: Name of the ContainerMap. If not provided, will be attempted to read from a ``name`` attribute on the docume...
def generate_local_port(): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L63.""" global _PREVIOUS_LOCAL_PORT if _PREVIOUS_LOCAL_PORT is None: try: with contextlib.closing(socket.socket(getattr(socket, 'AF_NETLINK', -1), socket.SOCK_RAW)) as s: s.bind((...
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L63.
Below is the the instruction that describes the task: ### Input: https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L63. ### Response: def generate_local_port(): """https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L63.""" global _PREVIOUS_LOCAL_PORT if _PREVIOUS_LOCAL_PORT is ...
def _cat_probs(self, log_probs): """Get a list of num_components batchwise probabilities.""" which_softmax = tf.nn.log_softmax if log_probs else tf.nn.softmax cat_probs = which_softmax(self.cat.logits) cat_probs = tf.unstack(cat_probs, num=self.num_components, axis=-1) return cat_probs
Get a list of num_components batchwise probabilities.
Below is the the instruction that describes the task: ### Input: Get a list of num_components batchwise probabilities. ### Response: def _cat_probs(self, log_probs): """Get a list of num_components batchwise probabilities.""" which_softmax = tf.nn.log_softmax if log_probs else tf.nn.softmax cat_probs =...
def _prepair(self): '''Try to connect to the given dbus services. If successful it will return a callable dbus proxy and those arguments. ''' try: sessionbus = dbus.SessionBus() systembus = dbus.SystemBus() except: return (None, None) ...
Try to connect to the given dbus services. If successful it will return a callable dbus proxy and those arguments.
Below is the the instruction that describes the task: ### Input: Try to connect to the given dbus services. If successful it will return a callable dbus proxy and those arguments. ### Response: def _prepair(self): '''Try to connect to the given dbus services. If successful it will return a ...
def _generate_time_steps(self, trajectory_list): """Transforms time step observations to frames of a video.""" for time_step in env_problem.EnvProblem._generate_time_steps( self, trajectory_list): # Convert the rendered observations from numpy to png format. frame_np = np.array(time_step.pop...
Transforms time step observations to frames of a video.
Below is the the instruction that describes the task: ### Input: Transforms time step observations to frames of a video. ### Response: def _generate_time_steps(self, trajectory_list): """Transforms time step observations to frames of a video.""" for time_step in env_problem.EnvProblem._generate_time_steps(...
def enqueue(self, destination, frame): """ Store message (frame) for specified destinationination. @param destination: The destinationination queue name for this message (frame). @type destination: C{str} @param frame: The message (frame) to send to specified destinationination...
Store message (frame) for specified destinationination. @param destination: The destinationination queue name for this message (frame). @type destination: C{str} @param frame: The message (frame) to send to specified destinationination. @type frame: C{stompclient.frame.Frame}
Below is the the instruction that describes the task: ### Input: Store message (frame) for specified destinationination. @param destination: The destinationination queue name for this message (frame). @type destination: C{str} @param frame: The message (frame) to send to specified destinat...
def process_track(file_struct, boundaries_id, labels_id, config, annotator_id=0): """Prepares the parameters, runs the algorithms, and saves results. Parameters ---------- file_struct: `msaf.io.FileStruct` FileStruct containing the paths of the input files (audio file, ...
Prepares the parameters, runs the algorithms, and saves results. Parameters ---------- file_struct: `msaf.io.FileStruct` FileStruct containing the paths of the input files (audio file, features file, reference file, output estimation file). boundaries_id: str Identifier of the b...
Below is the the instruction that describes the task: ### Input: Prepares the parameters, runs the algorithms, and saves results. Parameters ---------- file_struct: `msaf.io.FileStruct` FileStruct containing the paths of the input files (audio file, features file, reference file, output...
def get_codons( variant, trimmed_cdna_ref, trimmed_cdna_alt, sequence_from_start_codon, cds_offset): """ Returns indices of first and last reference codons affected by the variant, as well as the actual sequence of the mutated codons which replace those reference ...
Returns indices of first and last reference codons affected by the variant, as well as the actual sequence of the mutated codons which replace those reference codons. Parameters ---------- variant : Variant trimmed_cdna_ref : str Trimmed reference cDNA nucleotides affected by the varia...
Below is the the instruction that describes the task: ### Input: Returns indices of first and last reference codons affected by the variant, as well as the actual sequence of the mutated codons which replace those reference codons. Parameters ---------- variant : Variant trimmed_cdna_ref :...