sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def bitdepth(self): """The number of bits per sample in the audio encoding (an int). Only available for certain file formats (zero where unavailable). """ if hasattr(self.mgfile.info, 'bits_per_sample'): return self.mgfile.info.bits_per_sample return 0
The number of bits per sample in the audio encoding (an int). Only available for certain file formats (zero where unavailable).
entailment
def channels(self): """The number of channels in the audio (an int).""" if hasattr(self.mgfile.info, 'channels'): return self.mgfile.info.channels return 0
The number of channels in the audio (an int).
entailment
def bitrate(self): """The number of bits per seconds used in the audio coding (an int). If this is provided explicitly by the compressed file format, this is a precise reflection of the encoding. Otherwise, it is estimated from the on-disk file size. In this case, some imprecisio...
The number of bits per seconds used in the audio coding (an int). If this is provided explicitly by the compressed file format, this is a precise reflection of the encoding. Otherwise, it is estimated from the on-disk file size. In this case, some imprecision is possible because the file...
entailment
def fromfits(infilename, hdu = 0, verbose = True): """ Reads a FITS file and returns a 2D numpy array of the data. Use hdu to specify which HDU you want (default = primary = 0) """ pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True) pixelarray = np.asarray(pixelarray).transpose()...
Reads a FITS file and returns a 2D numpy array of the data. Use hdu to specify which HDU you want (default = primary = 0)
entailment
def tofits(outfilename, pixelarray, hdr = None, verbose = True): """ Takes a 2D numpy array and write it into a FITS file. If you specify a header (pyfits format, as returned by fromfits()) it will be used for the image. You can give me boolean numpy arrays, I will convert them into 8 bit integers. ...
Takes a 2D numpy array and write it into a FITS file. If you specify a header (pyfits format, as returned by fromfits()) it will be used for the image. You can give me boolean numpy arrays, I will convert them into 8 bit integers.
entailment
def subsample(a): # this is more a generic function then a method ... """ Returns a 2x2-subsampled version of array a (no interpolation, just cutting pixels in 4). The version below is directly from the scipy cookbook on rebinning : U{http://www.scipy.org/Cookbook/Rebinning} There is ndimage.zoom(cu...
Returns a 2x2-subsampled version of array a (no interpolation, just cutting pixels in 4). The version below is directly from the scipy cookbook on rebinning : U{http://www.scipy.org/Cookbook/Rebinning} There is ndimage.zoom(cutout.array, 2, order=0, prefilter=False), but it makes funny borders.
entailment
def rebin2x2(a): """ Wrapper around rebin that actually rebins 2 by 2 """ inshape = np.array(a.shape) if not (inshape % 2 == np.zeros(2)).all(): # Modulo check to see if size is even raise RuntimeError, "I want even image shapes !" return rebin(a, inshape/2)
Wrapper around rebin that actually rebins 2 by 2
entailment
def labelmask(self, verbose = None): """ Finds and labels the cosmic "islands" and returns a list of dicts containing their positions. This is made on purpose for visualizations a la f2n.drawstarslist, but could be useful anyway. """ if verbose == None: verbose = self...
Finds and labels the cosmic "islands" and returns a list of dicts containing their positions. This is made on purpose for visualizations a la f2n.drawstarslist, but could be useful anyway.
entailment
def getdilatedmask(self, size=3): """ Returns a morphologically dilated copy of the current mask. size = 3 or 5 decides how to dilate. """ if size == 3: dilmask = ndimage.morphology.binary_dilation(self.mask, structure=growkernel, iterations=1, mask=None, output=None,...
Returns a morphologically dilated copy of the current mask. size = 3 or 5 decides how to dilate.
entailment
def clean(self, mask = None, verbose = None): """ Given the mask, we replace the actual problematic pixels with the masked 5x5 median value. This mimics what is done in L.A.Cosmic, but it's a bit harder to do in python, as there is no readymade masked median. So for now we do a loop... ...
Given the mask, we replace the actual problematic pixels with the masked 5x5 median value. This mimics what is done in L.A.Cosmic, but it's a bit harder to do in python, as there is no readymade masked median. So for now we do a loop... Saturated stars, if calculated, are also masked : they are ...
entailment
def findsatstars(self, verbose = None): """ Uses the satlevel to find saturated stars (not cosmics !), and puts the result as a mask in self.satstars. This can then be used to avoid these regions in cosmic detection and cleaning procedures. Slow ... """ if verbose == None...
Uses the satlevel to find saturated stars (not cosmics !), and puts the result as a mask in self.satstars. This can then be used to avoid these regions in cosmic detection and cleaning procedures. Slow ...
entailment
def getsatstars(self, verbose = None): """ Returns the mask of saturated stars after finding them if not yet done. Intended mainly for external use. """ if verbose == None: verbose = self.verbose if not self.satlevel > 0: raise RuntimeError, "Canno...
Returns the mask of saturated stars after finding them if not yet done. Intended mainly for external use.
entailment
def guessbackgroundlevel(self): """ Estimates the background level. This could be used to fill pixels in large cosmics. """ if self.backgroundlevel == None: self.backgroundlevel = np.median(self.rawarray.ravel()) return self.backgroundlevel
Estimates the background level. This could be used to fill pixels in large cosmics.
entailment
def lacosmiciteration(self, verbose = None): """ Performs one iteration of the L.A.Cosmic algorithm. It operates on self.cleanarray, and afterwards updates self.mask by adding the newly detected cosmics to the existing self.mask. Cleaning is not made automatically ! You have to call ...
Performs one iteration of the L.A.Cosmic algorithm. It operates on self.cleanarray, and afterwards updates self.mask by adding the newly detected cosmics to the existing self.mask. Cleaning is not made automatically ! You have to call clean() after each iteration. This way you can run it...
entailment
def run(self, maxiter = 4, verbose = False): """ Full artillery :-) - Find saturated stars - Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found) Stops if no cosmics are found or if maxiter is reached. """ if self.satlev...
Full artillery :-) - Find saturated stars - Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found) Stops if no cosmics are found or if maxiter is reached.
entailment
def search_project_root(): """ Search your Django project root. returns: - path:string Django project root path """ while True: current = os.getcwd() if pathlib.Path("Miragefile.py").is_file() or pathlib.Path("Miragefile").is_file(): ...
Search your Django project root. returns: - path:string Django project root path
entailment
def search_app_root(): """ Search your Django application root returns: - (String) Django application root path """ while True: current = os.getcwd() if pathlib.Path("apps.py").is_file(): return current elif pathl...
Search your Django application root returns: - (String) Django application root path
entailment
def in_app() -> bool: """ Judge where current working directory is in Django application or not. returns: - (Bool) cwd is in app dir returns True """ try: MirageEnvironment.set_import_root() import apps if os.path.isfile("apps.py")...
Judge where current working directory is in Django application or not. returns: - (Bool) cwd is in app dir returns True
entailment
def update_cached_fields(*args): """ Calls update_cached_fields() for each object passed in as argument. Supports also iterable objects by checking __iter__ attribute. :param args: List of objects :return: None """ for a in args: if a is not None: if hasattr(a, '__iter__'...
Calls update_cached_fields() for each object passed in as argument. Supports also iterable objects by checking __iter__ attribute. :param args: List of objects :return: None
entailment
def update_cached_fields_pre_save(self, update_fields: list): """ Call on pre_save signal for objects (to automatically refresh on save). :param update_fields: list of fields to update """ if self.id and update_fields is None: self.update_cached_fields(commit=False, e...
Call on pre_save signal for objects (to automatically refresh on save). :param update_fields: list of fields to update
entailment
def start(name): # type: (str) -> None """ Start working on a new hotfix. This will create a new branch off master called hotfix/<name>. Args: name (str): The name of the new feature. """ hotfix_branch = 'hotfix/' + common.to_branch_name(name) master = conf.get('git.mas...
Start working on a new hotfix. This will create a new branch off master called hotfix/<name>. Args: name (str): The name of the new feature.
entailment
def finish(): # type: () -> None """ Merge current feature into develop. """ pretend = context.get('pretend', False) if not pretend and (git.staged() or git.unstaged()): log.err( "You have uncommitted changes in your repo!\n" "You need to stash them before you merge the ...
Merge current feature into develop.
entailment
def merged(): # type: () -> None """ Cleanup a remotely merged branch. """ develop = conf.get('git.devel_branch', 'develop') master = conf.get('git.master_branch', 'master') branch = git.current_branch(refresh=True) common.assert_branch_type('hotfix') # Pull master with the merged hotfix ...
Cleanup a remotely merged branch.
entailment
def run(self): """ Run the shell command Returns: ShellCommand: return this ShellCommand instance for chaining """ if not self.block: self.output = [] self.error = [] self.thread = threading.Thread(target=self.run_non_blocking) ...
Run the shell command Returns: ShellCommand: return this ShellCommand instance for chaining
entailment
def send(self, value): """ Send text to stdin. Can only be used on non blocking commands Args: value (str): the text to write on stdin Raises: TypeError: If command is blocking Returns: ShellCommand: return this ShellCommand instance for chain...
Send text to stdin. Can only be used on non blocking commands Args: value (str): the text to write on stdin Raises: TypeError: If command is blocking Returns: ShellCommand: return this ShellCommand instance for chaining
entailment
def poll_output(self): """ Append lines from stdout to self.output. Returns: list: The lines added since last call """ if self.block: return self.output new_list = self.output[self.old_output_size:] self.old_output_size += len(new_list) ...
Append lines from stdout to self.output. Returns: list: The lines added since last call
entailment
def poll_error(self): """ Append lines from stderr to self.errors. Returns: list: The lines added since last call """ if self.block: return self.error new_list = self.error[self.old_error_size:] self.old_error_size += len(new_list) ...
Append lines from stderr to self.errors. Returns: list: The lines added since last call
entailment
def kill(self): """ Kill the current non blocking command Raises: TypeError: If command is blocking """ if self.block: raise TypeError(NON_BLOCKING_ERROR_MESSAGE) try: self.process.kill() except ProcessLookupError as exc: ...
Kill the current non blocking command Raises: TypeError: If command is blocking
entailment
def wait_for(self, pattern, timeout=None): """ Block until a pattern have been found in stdout and stderr Args: pattern(:class:`~re.Pattern`): The pattern to search timeout(int): Maximum number of second to wait. If None, wait infinitely Raises: Tim...
Block until a pattern have been found in stdout and stderr Args: pattern(:class:`~re.Pattern`): The pattern to search timeout(int): Maximum number of second to wait. If None, wait infinitely Raises: TimeoutError: When timeout is reach
entailment
def is_running(self): """ Check if the command is currently running Returns: bool: True if running, else False """ if self.block: return False return self.thread.is_alive() or self.process.poll() is None
Check if the command is currently running Returns: bool: True if running, else False
entailment
def print_live_output(self): ''' Block and print the output of the command Raises: TypeError: If command is blocking ''' if self.block: raise TypeError(NON_BLOCKING_ERROR_MESSAGE) else: while self.thread.is_alive() or self.old_output_s...
Block and print the output of the command Raises: TypeError: If command is blocking
entailment
def run(self, command, block=True, cwd=None, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE): """ Create an instance of :class:`~ShellCommand` and run it Args: command (str): :class:`~ShellCommand` block (bool): See :class:`~ShellCommand` ...
Create an instance of :class:`~ShellCommand` and run it Args: command (str): :class:`~ShellCommand` block (bool): See :class:`~ShellCommand` cwd (str): Override the runner cwd. Useb by the :class:`~ShellCommand` instance
entailment
def bces(x1, x2, x1err=[], x2err=[], cerr=[], logify=True, model='yx', \ bootstrap=5000, verbose='normal', full_output=True): """ Bivariate, Correlated Errors and intrinsic Scatter (BCES) translated from the FORTRAN code by Christina Bird and Matthew Bershady (Akritas & Bershady, 1996) Lin...
Bivariate, Correlated Errors and intrinsic Scatter (BCES) translated from the FORTRAN code by Christina Bird and Matthew Bershady (Akritas & Bershady, 1996) Linear regression in the presence of heteroscedastic errors on both variables and intrinsic scatter Parameters ---------- x1 ...
entailment
def scatter(slope, zero, x1, x2, x1err=[], x2err=[]): """ Used mainly to measure scatter for the BCES best-fit """ n = len(x1) x2pred = zero + slope * x1 s = sum((x2 - x2pred) ** 2) / (n - 1) if len(x2err) == n: s_obs = sum((x2err / x2) ** 2) / n s0 = s - s_obs print num...
Used mainly to measure scatter for the BCES best-fit
entailment
def kelly(x1, x2, x1err=[], x2err=[], cerr=[], logify=True, miniter=5000, maxiter=1e5, metro=True, silent=True): """ Python wrapper for the linear regression MCMC of Kelly (2007). Requires pidly (http://astronomy.sussex.ac.uk/~anthonys/pidly/) and an IDL license. Parameters ...
Python wrapper for the linear regression MCMC of Kelly (2007). Requires pidly (http://astronomy.sussex.ac.uk/~anthonys/pidly/) and an IDL license. Parameters ---------- x1 : array of floats Independent variable, or observable x2 : array of floats ...
entailment
def mcmc(x1, x2, x1err=[], x2err=[], po=(1,1,0.5), logify=True, nsteps=5000, nwalkers=100, nburn=500, output='full'): """ Use emcee to find the best-fit linear relation or power law accounting for measurement uncertainties and intrinsic scatter Parameters ---------- x1 : array...
Use emcee to find the best-fit linear relation or power law accounting for measurement uncertainties and intrinsic scatter Parameters ---------- x1 : array of floats Independent variable, or observable x2 : array of floats Dependent variable ...
entailment
def mle(x1, x2, x1err=[], x2err=[], cerr=[], s_int=True, po=(1,0,0.1), verbose=False, logify=True, full_output=False): """ Maximum Likelihood Estimation of best-fit parameters Parameters ---------- x1, x2 : float arrays the independent and dependent variables. x...
Maximum Likelihood Estimation of best-fit parameters Parameters ---------- x1, x2 : float arrays the independent and dependent variables. x1err, x2err : float arrays (optional) measurement uncertainties on independent and dependent variables....
entailment
def to_log(x1, x2, x1err, x2err): """ Take linear measurements and uncertainties and transform to log values. """ logx1 = numpy.log10(numpy.array(x1)) logx2 = numpy.log10(numpy.array(x2)) x1err = numpy.log10(numpy.array(x1)+numpy.array(x1err)) - logx1 x2err = numpy.log10(numpy.array(x2)+num...
Take linear measurements and uncertainties and transform to log values.
entailment
def wrap_paths(paths): # type: (list[str]) -> str """ Put quotes around all paths and join them with space in-between. """ if isinstance(paths, string_types): raise ValueError( "paths cannot be a string. " "Use array with one element instead." ) return ' '.join('"...
Put quotes around all paths and join them with space in-between.
entailment
def filtered_walk(path, include=None, exclude=None): # type: (str, List[str], List[str]) -> Generator[str] """ Walk recursively starting at *path* excluding files matching *exclude* Args: path (str): A starting path. This has to be an existing directory. include (list[str]): ...
Walk recursively starting at *path* excluding files matching *exclude* Args: path (str): A starting path. This has to be an existing directory. include (list[str]): A white list of glob patterns. If given, only files that match those globs will be yielded (filter...
entailment
def match_globs(path, patterns): # type: (str, List[str]) -> bool """ Test whether the given *path* matches any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of glob string patterns to test against. If *path* m...
Test whether the given *path* matches any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of glob string patterns to test against. If *path* matches any of those patters, it will return True. Returns: ...
entailment
def search_globs(path, patterns): # type: (str, List[str]) -> bool """ Test whether the given *path* contains any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of glob string patterns to test against. If *path*...
Test whether the given *path* contains any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of glob string patterns to test against. If *path* matches any of those patters, it will return True. Returns: ...
entailment
def write_file(path, content, mode='w'): # type: (Text, Union[Text,bytes], Text) -> None """ --pretend aware file writing. You can always write files manually but you should always handle the --pretend case. Args: path (str): content (str): mode (str): """ from pelt...
--pretend aware file writing. You can always write files manually but you should always handle the --pretend case. Args: path (str): content (str): mode (str):
entailment
def lint_cli(ctx, exclude, skip_untracked, commit_only): # type: (click.Context, List[str], bool, bool) -> None """ Run pep8 and pylint on all project files. You can configure the linting paths using the lint.paths config variable. This should be a list of paths that will be linted. If a path to a dire...
Run pep8 and pylint on all project files. You can configure the linting paths using the lint.paths config variable. This should be a list of paths that will be linted. If a path to a directory is given, all files in that directory and it's subdirectories will be used. The pep8 and pylint config pa...
entailment
def run_command(command, timeout_sec=3600.0, output=True): """Runs a command using the subprocess module :param command: List containing the command and all args :param timeout_sec (float) seconds to wait before killing the command. :param output (bool) True collects output, False ignores outpu...
Runs a command using the subprocess module :param command: List containing the command and all args :param timeout_sec (float) seconds to wait before killing the command. :param output (bool) True collects output, False ignores output :return: Dict containing the command output and return code ...
entailment
def get_ip_addresses(): """Gets the ip addresses from ifconfig :return: (dict) of devices and aliases with the IPv4 address """ log = logging.getLogger(mod_logger + '.get_ip_addresses') command = ['/sbin/ifconfig'] try: result = run_command(command) except CommandError: rai...
Gets the ip addresses from ifconfig :return: (dict) of devices and aliases with the IPv4 address
entailment
def get_mac_address(device_index=0): """Returns the Mac Address given a device index :param device_index: (int) Device index :return: (str) Mac address or None """ log = logging.getLogger(mod_logger + '.get_mac_address') command = ['ip', 'addr', 'show', 'eth{d}'.format(d=device_index)] log....
Returns the Mac Address given a device index :param device_index: (int) Device index :return: (str) Mac address or None
entailment
def chmod(path, mode, recursive=False): """Emulates bash chmod command This method sets the file permissions to the specified mode. :param path: (str) Full path to the file or directory :param mode: (str) Mode to be set (e.g. 0755) :param recursive: (bool) Set True to make a recursive call :re...
Emulates bash chmod command This method sets the file permissions to the specified mode. :param path: (str) Full path to the file or directory :param mode: (str) Mode to be set (e.g. 0755) :param recursive: (bool) Set True to make a recursive call :return: int exit code of the chmod command :r...
entailment
def mkdir_p(path): """Emulates 'mkdir -p' in bash :param path: (str) Path to create :return: None :raises CommandError """ log = logging.getLogger(mod_logger + '.mkdir_p') if not isinstance(path, basestring): msg = 'path argument is not a string' log.error(msg) raise...
Emulates 'mkdir -p' in bash :param path: (str) Path to create :return: None :raises CommandError
entailment
def source(script): """Emulates 'source' command in bash :param script: (str) Full path to the script to source :return: Updated environment :raises CommandError """ log = logging.getLogger(mod_logger + '.source') if not isinstance(script, basestring): msg = 'script argument must be...
Emulates 'source' command in bash :param script: (str) Full path to the script to source :return: Updated environment :raises CommandError
entailment
def yum_update(downloadonly=False, dest_dir='/tmp'): """Run a yum update on this system This public method runs the yum -y update command to update packages from yum. If downloadonly is set to true, the yum updates will be downloaded to the specified dest_dir. :param dest_dir: (str) Full path to t...
Run a yum update on this system This public method runs the yum -y update command to update packages from yum. If downloadonly is set to true, the yum updates will be downloaded to the specified dest_dir. :param dest_dir: (str) Full path to the download directory :param downloadonly: Boolean :...
entailment
def yum_install(packages, downloadonly=False, dest_dir='/tmp'): """Installs (or downloads) a list of packages from yum This public method installs a list of packages from yum or downloads the packages to the specified destination directory using the yum-downloadonly yum plugin. :param downloadonly...
Installs (or downloads) a list of packages from yum This public method installs a list of packages from yum or downloads the packages to the specified destination directory using the yum-downloadonly yum plugin. :param downloadonly: Boolean, set to only download the package and not install it ...
entailment
def rpm_install(install_dir): """This method installs all RPM files in a specific dir :param install_dir: (str) Full path to the directory :return int exit code form the rpm command :raises CommandError """ log = logging.getLogger(mod_logger + '.rpm_install') # Type checks on the args ...
This method installs all RPM files in a specific dir :param install_dir: (str) Full path to the directory :return int exit code form the rpm command :raises CommandError
entailment
def sed(file_path, pattern, replace_str, g=0): """Python impl of the bash sed command This method emulates the functionality of a bash sed command. :param file_path: (str) Full path to the file to be edited :param pattern: (str) Search pattern to replace as a regex :param replace_str: (str) String...
Python impl of the bash sed command This method emulates the functionality of a bash sed command. :param file_path: (str) Full path to the file to be edited :param pattern: (str) Search pattern to replace as a regex :param replace_str: (str) String to replace the pattern :param g: (int) Whether to...
entailment
def zip_dir(dir_path, zip_file): """Creates a zip file of a directory tree This method creates a zip archive using the directory tree dir_path and adds to zip_file output. :param dir_path: (str) Full path to directory to be zipped :param zip_file: (str) Full path to the output zip file :return...
Creates a zip file of a directory tree This method creates a zip archive using the directory tree dir_path and adds to zip_file output. :param dir_path: (str) Full path to directory to be zipped :param zip_file: (str) Full path to the output zip file :return: None :raises CommandError
entailment
def get_ip(interface=0): """This method return the IP address :param interface: (int) Interface number (e.g. 0 for eth0) :return: (str) IP address or None """ log = logging.getLogger(mod_logger + '.get_ip') log.info('Getting the IP address for this system...') ip_address = None try: ...
This method return the IP address :param interface: (int) Interface number (e.g. 0 for eth0) :return: (str) IP address or None
entailment
def update_hosts_file(ip, entry): """Updates the /etc/hosts file for the specified ip This method updates the /etc/hosts file for the specified IP address with the specified entry. :param ip: (str) IP address to be added or updated :param entry: (str) Hosts file entry to be added :return: None...
Updates the /etc/hosts file for the specified ip This method updates the /etc/hosts file for the specified IP address with the specified entry. :param ip: (str) IP address to be added or updated :param entry: (str) Hosts file entry to be added :return: None :raises CommandError
entailment
def set_hostname(new_hostname, pretty_hostname=None): """Sets this hosts hostname This method updates /etc/sysconfig/network and calls the hostname command to set a hostname on a Linux system. :param new_hostname: (str) New hostname :param pretty_hostname: (str) new pretty hostname, set to the sam...
Sets this hosts hostname This method updates /etc/sysconfig/network and calls the hostname command to set a hostname on a Linux system. :param new_hostname: (str) New hostname :param pretty_hostname: (str) new pretty hostname, set to the same as new_hostname if not provided :return (int) e...
entailment
def set_ntp_server(server): """Sets the NTP server on Linux :param server: (str) NTP server IP or hostname :return: None :raises CommandError """ log = logging.getLogger(mod_logger + '.set_ntp_server') # Ensure the hostname is a str if not isinstance(server, basestring): msg = ...
Sets the NTP server on Linux :param server: (str) NTP server IP or hostname :return: None :raises CommandError
entailment
def copy_ifcfg_file(source_interface, dest_interface): """Copies an existing ifcfg network script to another :param source_interface: String (e.g. 1) :param dest_interface: String (e.g. 0:0) :return: None :raises TypeError, OSError """ log = logging.getLogger(mod_logger + '.copy_ifcfg_file'...
Copies an existing ifcfg network script to another :param source_interface: String (e.g. 1) :param dest_interface: String (e.g. 0:0) :return: None :raises TypeError, OSError
entailment
def remove_ifcfg_file(device_index='0'): """Removes the ifcfg file at the specified device index and restarts the network service :param device_index: (int) Device Index :return: None :raises CommandError """ log = logging.getLogger(mod_logger + '.remove_ifcfg_file') if not isinstance(d...
Removes the ifcfg file at the specified device index and restarts the network service :param device_index: (int) Device Index :return: None :raises CommandError
entailment
def add_nat_rule(port, source_interface, dest_interface): """Adds a NAT rule to iptables :param port: String or int port number :param source_interface: String (e.g. 1) :param dest_interface: String (e.g. 0:0) :return: None :raises: TypeError, OSError """ log = logging.getLogger(mod_log...
Adds a NAT rule to iptables :param port: String or int port number :param source_interface: String (e.g. 1) :param dest_interface: String (e.g. 0:0) :return: None :raises: TypeError, OSError
entailment
def service_network_restart(): """Restarts the network service on linux :return: None :raises CommandError """ log = logging.getLogger(mod_logger + '.service_network_restart') command = ['service', 'network', 'restart'] time.sleep(5) try: result = run_command(command) tim...
Restarts the network service on linux :return: None :raises CommandError
entailment
def save_iptables(rules_file='/etc/sysconfig/iptables'): """Saves iptables rules to the provided rules file :return: None :raises OSError """ log = logging.getLogger(mod_logger + '.save_iptables') # Run iptables-save to get the output command = ['iptables-save'] log.debug('Running comm...
Saves iptables rules to the provided rules file :return: None :raises OSError
entailment
def get_remote_host_environment_variable(host, environment_variable): """Retrieves the value of an environment variable of a remote host over SSH :param host: (str) host to query :param environment_variable: (str) variable to query :return: (str) value of the environment variable :raises: TypeE...
Retrieves the value of an environment variable of a remote host over SSH :param host: (str) host to query :param environment_variable: (str) variable to query :return: (str) value of the environment variable :raises: TypeError, CommandError
entailment
def set_remote_host_environment_variable(host, variable_name, variable_value, env_file='/etc/bashrc'): """Sets an environment variable on the remote host in the specified environment file :param host: (str) host to set environment variable on :param variable_name: (str) name of the variable :param ...
Sets an environment variable on the remote host in the specified environment file :param host: (str) host to set environment variable on :param variable_name: (str) name of the variable :param variable_value: (str) value of the variable :param env_file: (str) full path to the environment file to se...
entailment
def run_remote_command(host, command, timeout_sec=5.0): """Retrieves the value of an environment variable of a remote host over SSH :param host: (str) host to query :param command: (str) command :param timeout_sec (float) seconds to wait before killing the command. :return: (str) command output...
Retrieves the value of an environment variable of a remote host over SSH :param host: (str) host to query :param command: (str) command :param timeout_sec (float) seconds to wait before killing the command. :return: (str) command output :raises: TypeError, CommandError
entailment
def check_remote_host_marker_file(host, file_path): """Queries a remote host over SSH to check for existence of a marker file :param host: (str) host to query :param file_path: (str) path to the marker file :return: (bool) True if the marker file exists :raises: TypeError, CommandError """ ...
Queries a remote host over SSH to check for existence of a marker file :param host: (str) host to query :param file_path: (str) path to the marker file :return: (bool) True if the marker file exists :raises: TypeError, CommandError
entailment
def restore_iptables(firewall_rules): """Restores and saves firewall rules from the firewall_rules file :param firewall_rules: (str) Full path to the firewall rules file :return: None :raises OSError """ log = logging.getLogger(mod_logger + '.restore_iptables') log.info('Restoring firewall ...
Restores and saves firewall rules from the firewall_rules file :param firewall_rules: (str) Full path to the firewall rules file :return: None :raises OSError
entailment
def remove_default_gateway(): """Removes Default Gateway configuration from /etc/sysconfig/network and restarts networking :return: None :raises: OSError """ log = logging.getLogger(mod_logger + '.remove_default_gateway') # Ensure the network script exists network_script = '/etc/sy...
Removes Default Gateway configuration from /etc/sysconfig/network and restarts networking :return: None :raises: OSError
entailment
def is_systemd(): """Determines whether this system uses systemd :return: (bool) True if this distro has systemd """ os_family = platform.system() if os_family != 'Linux': raise OSError('This method is only supported on Linux, found OS: {o}'.format(o=os_family)) linux_distro, linux_vers...
Determines whether this system uses systemd :return: (bool) True if this distro has systemd
entailment
def manage_service(service_name, service_action='status', systemd=None, output=True): """Use to run Linux sysv or systemd service commands :param service_name (str) name of the service to start :param service_action (str) action to perform on the service :param systemd (bool) True if the command should...
Use to run Linux sysv or systemd service commands :param service_name (str) name of the service to start :param service_action (str) action to perform on the service :param systemd (bool) True if the command should use systemd :param output (bool) True to print output :return: None :raises: OSE...
entailment
def system_reboot(wait_time_sec=20): """Reboots the system after a specified wait time. Must be run as root :param wait_time_sec: (int) number of sec to wait before performing the reboot :return: None :raises: SystemRebootError, SystemRebootTimeoutError """ log = logging.getLogger(mod_logger +...
Reboots the system after a specified wait time. Must be run as root :param wait_time_sec: (int) number of sec to wait before performing the reboot :return: None :raises: SystemRebootError, SystemRebootTimeoutError
entailment
def main(): """Sample usage for this python module This main method simply illustrates sample usage for this python module. :return: None """ mkdir_p('/tmp/test/test') source('/root/.bash_profile') yum_install(['httpd', 'git']) yum_install(['httpd', 'git'], dest_dir='/tmp/test/test...
Sample usage for this python module This main method simply illustrates sample usage for this python module. :return: None
entailment
def log_event(name: str, request: Request=None, data=None, ip=None): """ Logs consistent event for easy parsing/analysis. :param name: Name of the event. Will be logged as EVENT_XXX with XXX in capitals. :param request: Django REST framework Request (optional) :param data: Even data (optional) :...
Logs consistent event for easy parsing/analysis. :param name: Name of the event. Will be logged as EVENT_XXX with XXX in capitals. :param request: Django REST framework Request (optional) :param data: Even data (optional) :param ip: Even IP (optional)
entailment
def aes_b64_encrypt(value, secret, block_size=AES.block_size): """ AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt ...
AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELF...
entailment
def aes_b64_decrypt(value, secret, block_size=AES.block_size): """ AES decrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES decrypted @value .. from vital.security import aes_encrypt, aes_decrypt ...
AES decrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES decrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELF...
entailment
def aes_encrypt(value, secret, block_size=AES.block_size): """ AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#bytes) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt ...
AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#bytes) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWE...
entailment
def aes_decrypt(value, secret, block_size=AES.block_size): """ AES decrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES decrypted @value .. from vital.security import aes_encrypt, aes_decrypt ae...
AES decrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES decrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELF...
entailment
def aes_pad(s, block_size=32, padding='{'): """ Adds padding to get the correct block sizes for AES encryption @s: #str being AES encrypted or decrypted @block_size: the AES block size @padding: character to pad with -> padded #str .. from vital.security import...
Adds padding to get the correct block sizes for AES encryption @s: #str being AES encrypted or decrypted @block_size: the AES block size @padding: character to pad with -> padded #str .. from vital.security import aes_pad aes_pad("swing") # ...
entailment
def lscmp(a, b): """ Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix, so this is helpful against timing attacks. .. from vital.security import lscmp lscmp("ringo", "starr") # -> False ls...
Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix, so this is helpful against timing attacks. .. from vital.security import lscmp lscmp("ringo", "starr") # -> False lscmp("ringo", "ringo") ...
entailment
def cookie(data, key_salt='', secret=None, digestmod=None): """ Encodes or decodes a signed cookie. @data: cookie data @key_salt: HMAC key signing salt @secret: HMAC signing secret key @digestmod: hashing algorithm to sign with, recommended >=sha256 -> HMAC signed or unsigne...
Encodes or decodes a signed cookie. @data: cookie data @key_salt: HMAC key signing salt @secret: HMAC signing secret key @digestmod: hashing algorithm to sign with, recommended >=sha256 -> HMAC signed or unsigned cookie data .. from vital.security import coo...
entailment
def strkey(val, chaffify=1, keyspace=string.ascii_letters + string.digits): """ Converts integers to a sequence of strings, and reverse. This is not intended to obfuscate numbers in any kind of cryptographically secure way, in fact it's the opposite. It's for predictable, reversable, obfusca...
Converts integers to a sequence of strings, and reverse. This is not intended to obfuscate numbers in any kind of cryptographically secure way, in fact it's the opposite. It's for predictable, reversable, obfuscation. It can also be used to transform a random bit integer to a string of t...
entailment
def chars_in(bits, keyspace): """ .. log2(keyspace^x_chars) = bits log(keyspace^x_chars) = log(2) * bits exp(log(keyspace^x_chars)) = exp(log(2) * bits) x_chars = log(exp(log(2) * bits)) / log(keyspace) .. -> (#int) number of characters in @bits of entropy given the @...
.. log2(keyspace^x_chars) = bits log(keyspace^x_chars) = log(2) * bits exp(log(keyspace^x_chars)) = exp(log(2) * bits) x_chars = log(exp(log(2) * bits)) / log(keyspace) .. -> (#int) number of characters in @bits of entropy given the @keyspace
entailment
def bits_in(length, keyspace): """ |log2(keyspace^length) = bits| -> (#float) number of bits of entropy in @length of characters for a given a @keyspace """ keyspace = len(keyspace) length_per_cycle = 64 if length > length_per_cycle: bits = 0 length_processed = 0 ...
|log2(keyspace^length) = bits| -> (#float) number of bits of entropy in @length of characters for a given a @keyspace
entailment
def iter_random_chars(bits, keyspace=string.ascii_letters + string.digits + '#/.', rng=None): """ Yields a cryptographically secure random key of desired @bits of entropy within @keyspace using :class:random.SystemRandom @bits: (#int) minimum bits of entr...
Yields a cryptographically secure random key of desired @bits of entropy within @keyspace using :class:random.SystemRandom @bits: (#int) minimum bits of entropy @keyspace: (#str) or iterable allowed output chars .. from vital.security import iter_rand for char ...
entailment
def randkey(bits, keyspace=string.ascii_letters + string.digits + '#/.', rng=None): """ Returns a cryptographically secure random key of desired @bits of entropy within @keyspace using :class:random.SystemRandom @bits: (#int) minimum bits of entropy @keyspace: (#str) or iterable...
Returns a cryptographically secure random key of desired @bits of entropy within @keyspace using :class:random.SystemRandom @bits: (#int) minimum bits of entropy @keyspace: (#str) or iterable allowed output chars @rng: the random number generator to use. Defaults to :class:r...
entailment
def randstr(size, keyspace=string.ascii_letters + string.digits, rng=None): """ Returns a cryptographically secure random string of desired @size (in character length) within @keyspace using :class:random.SystemRandom @size: (#int) number of random characters to generate @keyspace: (#str) o...
Returns a cryptographically secure random string of desired @size (in character length) within @keyspace using :class:random.SystemRandom @size: (#int) number of random characters to generate @keyspace: (#str) or iterable allowed output chars @rng: the random number generator to use. De...
entailment
def parse_requirements(filename): """ load requirements from a pip requirements file """ lineiter = (line.strip() for line in open(filename)) return (line for line in lineiter if line and not line.startswith("#"))
load requirements from a pip requirements file
entailment
def round_sig(x, n, scien_notation = False): if x < 0: x = x * -1 symbol = '-' else: symbol = '' '''round floating point x to n significant figures''' if type(n) is not types.IntType: raise TypeError, "n must be an integer" try: x = float(x) exce...
round floating point x to n significant figures
entailment
def round_sig_error(x, ex, n, paren=False): '''Find ex rounded to n sig-figs and make the floating point x match the number of decimals. If [paren], the string is returned as quantity(error) format''' stex = round_sig(ex,n) if stex.find('.') < 0: extra_zeros = len(stex) - n sigfigs ...
Find ex rounded to n sig-figs and make the floating point x match the number of decimals. If [paren], the string is returned as quantity(error) format
entailment
def format_table(cols, errors, n, labels=None, headers=None, latex=False): '''Format a table such that the errors have n significant figures. [cols] and [errors] should be a list of 1D arrays that correspond to data and errors in columns. [n] is the number of significant figures to keep in the errors....
Format a table such that the errors have n significant figures. [cols] and [errors] should be a list of 1D arrays that correspond to data and errors in columns. [n] is the number of significant figures to keep in the errors. [labels] is an optional column of strings that will be in the first column. ...
entailment
def round_sig_error2(x, ex1, ex2, n): '''Find min(ex1,ex2) rounded to n sig-figs and make the floating point x and max(ex,ex2) match the number of decimals.''' minerr = min(ex1,ex2) minstex = round_sig(minerr,n) if minstex.find('.') < 0: extra_zeros = len(minstex) - n sigfigs = len(s...
Find min(ex1,ex2) rounded to n sig-figs and make the floating point x and max(ex,ex2) match the number of decimals.
entailment
def send_to_azure_multi_threads(instance, data, nb_threads=4, replace=True, types=None, primary_key=(), sub_commit=False): """ data = { "table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist, "columns_name" : [first_colum...
data = { "table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist, "columns_name" : [first_column_name,second_column_name,...,last_column_name], "rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...] }
entailment
def send_to_azure(instance, data, thread_number, sub_commit, table_info, nb_threads): """ data = { "table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist, "columns_name" : [first_column_name,second_column_name,...,last_column_name], "rows" : [[...
data = { "table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist, "columns_name" : [first_column_name,second_column_name,...,last_column_name], "rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...] }
entailment
def create(self, items=[], taxes=[], custom_data=[]): """Adds the items to the invoice Format of 'items': [ InvoiceItem( name="VIP Ticket", quantity= 2, unit_price= "3500", total_price= "7000", description= "VIP Tickets f...
Adds the items to the invoice Format of 'items': [ InvoiceItem( name="VIP Ticket", quantity= 2, unit_price= "3500", total_price= "7000", description= "VIP Tickets for the Party" } ,... ]
entailment
def confirm(self, token=None): """Returns the status of the invoice STATUSES: pending, completed, cancelled """ _token = token if token else self._response.get("token") return self._process('checkout-invoice/confirm/' + str(_token))
Returns the status of the invoice STATUSES: pending, completed, cancelled
entailment
def add_taxes(self, taxes): """Appends the data to the 'taxes' key in the request object 'taxes' should be in format: [("tax_name", "tax_amount")] For example: [("Other TAX", 700), ("VAT", 5000)] """ # fixme: how to resolve duplicate tax names _idx = len(self.tax...
Appends the data to the 'taxes' key in the request object 'taxes' should be in format: [("tax_name", "tax_amount")] For example: [("Other TAX", 700), ("VAT", 5000)]
entailment
def add_item(self, item): """Updates the list of items in the current transaction""" _idx = len(self.items) self.items.update({"item_" + str(_idx + 1): item})
Updates the list of items in the current transaction
entailment
def _prepare_data(self): """Formats the data in the current transaction for processing""" total_amount = self.total_amount or self.calculate_total_amt() self._data = { "invoice": { "items": self.__encode_items(self.items), "taxes": self.taxes, ...
Formats the data in the current transaction for processing
entailment