_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q18400
shrink_text_file
train
def shrink_text_file(filename, max_size, removal_marker=None): """Shrink a text file to approximately maxSize bytes by removing lines from the middle of the file. """ file_size = os.path.getsize(filename) assert file_size > max_size # We partition the file into 3 parts: # A) start: maxSize/...
python
{ "resource": "" }
q18401
read_file
train
def read_file(*path): """ Read the full content of a file. """ with open(os.path.join(*path)) as f: return f.read().strip()
python
{ "resource": "" }
q18402
add_files_to_git_repository
train
def add_files_to_git_repository(base_dir, files, description): """ Add and commit all files given in a list into a git repository in the base_dir directory. Nothing is done if the git repository has local changes. @param files: the files to commit @param description: the commit message """ ...
python
{ "resource": "" }
q18403
setup_logging
train
def setup_logging(format="%(asctime)s - %(levelname)s - %(message)s", level='INFO'): """Setup the logging framework with a basic configuration""" try: import coloredlogs coloredlogs.install(fmt=format, level=level) except ImportError: logging.basicConfig(format=format, level=level)
python
{ "resource": "" }
q18404
_Worker.execute
train
def execute(self, run): """ This function executes the tool with a sourcefile with options. It also calls functions for output before and after the run. """ self.output_handler.output_before_run(run) benchmark = self.benchmark memlimit = benchmark.rlimits.get(MEM...
python
{ "resource": "" }
q18405
CPUThrottleCheck.has_throttled
train
def has_throttled(self): """ Check whether any of the CPU cores monitored by this instance has throttled since this instance was created. @return a boolean value """ for file, value in self.cpu_throttle_count.items(): try: new_value = int(util....
python
{ "resource": "" }
q18406
SwapCheck.has_swapped
train
def has_swapped(self): """ Check whether any swapping occured on this system since this instance was created. @return a boolean value """ new_values = self._read_swap_count() for key, new_value in new_values.items(): old_value = self.swap_count.get(key, 0) ...
python
{ "resource": "" }
q18407
add_basic_executor_options
train
def add_basic_executor_options(argument_parser): """Add some basic options for an executor to an argparse argument_parser.""" argument_parser.add_argument("args", nargs="+", metavar="ARG", help='command line to run (prefix with "--" to ensure all arguments are treated correctly)') argument_parser.ad...
python
{ "resource": "" }
q18408
BaseExecutor._kill_process
train
def _kill_process(self, pid, sig=signal.SIGKILL): """Try to send signal to given process.""" try: os.kill(pid, sig) except OSError as e: if e.errno == errno.ESRCH: # process itself returned and exited before killing logging.debug("Failure %s while killing ...
python
{ "resource": "" }
q18409
BaseExecutor._start_execution
train
def _start_execution(self, args, stdin, stdout, stderr, env, cwd, temp_dir, cgroups, parent_setup_fn, child_setup_fn, parent_cleanup_fn): """Actually start the tool and the measurements. @param parent_setup_fn a function without parameters that is called in the parent process ...
python
{ "resource": "" }
q18410
BaseExecutor._wait_for_process
train
def _wait_for_process(self, pid, name): """Wait for the given process to terminate. @return tuple of exit code and resource usage """ try: logging.debug("Waiting for process %s with pid %s", name, pid) unused_pid, exitcode, ru_child = os.wait4(pid, 0) ...
python
{ "resource": "" }
q18411
xml_to_string
train
def xml_to_string(elem, qualified_name=None, public_id=None, system_id=None): """ Return a pretty-printed XML string for the Element. Also allows setting a document type. """ from xml.dom import minidom rough_string = ET.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) ...
python
{ "resource": "" }
q18412
Tool.program_files
train
def program_files(self, executable): """ Determine the file paths to be adopted """ if self._get_version() == 6: paths = self.REQUIRED_PATHS_6 elif self._get_version() > 6: paths = self.REQUIRED_PATHS_7_1 return paths
python
{ "resource": "" }
q18413
substitute_vars
train
def substitute_vars(oldList, runSet=None, sourcefile=None): """ This method replaces special substrings from a list of string and return a new list. """ keyValueList = [] if runSet: benchmark = runSet.benchmark # list with tuples (key, value): 'key' is replaced by 'value' ...
python
{ "resource": "" }
q18414
load_task_definition_file
train
def load_task_definition_file(task_def_file): """Open and parse a task-definition file in YAML format.""" try: with open(task_def_file) as f: task_def = yaml.safe_load(f) except OSError as e: raise BenchExecException("Cannot open task-definition file: " + str(e)) except yaml....
python
{ "resource": "" }
q18415
load_tool_info
train
def load_tool_info(tool_name): """ Load the tool-info class. @param tool_name: The name of the tool-info module. Either a full Python package name or a name within the benchexec.tools package. @return: A tuple of the full name of the used tool-info module and an instance of the tool-info class. ...
python
{ "resource": "" }
q18416
RunSet.create_run_from_task_definition
train
def create_run_from_task_definition( self, task_def_file, options, propertyfile, required_files_pattern): """Create a Run from a task definition in yaml format""" task_def = load_task_definition_file(task_def_file) def expand_patterns_from_tag(tag): result = [] ...
python
{ "resource": "" }
q18417
RunSet.expand_filename_pattern
train
def expand_filename_pattern(self, pattern, base_dir, sourcefile=None): """ The function expand_filename_pattern expands a filename pattern to a sorted list of filenames. The pattern can contain variables and wildcards. If base_dir is given and pattern is not absolute, base_dir and patter...
python
{ "resource": "" }
q18418
Run._analyze_result
train
def _analyze_result(self, exitcode, output, isTimeout, termination_reason): """Return status according to result and output of tool.""" # Ask tool info. tool_status = None if exitcode is not None: logging.debug("My subprocess returned %s.", exitcode) tool_status ...
python
{ "resource": "" }
q18419
Run._is_timeout
train
def _is_timeout(self): ''' try to find out whether the tool terminated because of a timeout ''' if self.cputime is None: is_cpulimit = False else: rlimits = self.runSet.benchmark.rlimits if SOFTTIMELIMIT in rlimits: limit = rlimits[SOFTTIMELIMI...
python
{ "resource": "" }
q18420
expected_results_of_file
train
def expected_results_of_file(filename): """Create a dict of property->ExpectedResult from information encoded in a filename.""" results = {} for (filename_part, (expected_result, for_properties)) in _FILE_RESULTS.items(): if filename_part in filename: expected_result_class = get_result_c...
python
{ "resource": "" }
q18421
_svcomp_score
train
def _svcomp_score(category, result): """ Return the achieved score of a task according to the SV-COMP scoring scheme. @param category: result category as determined by get_result_category @param result: the result given by the tool """ assert result is not None result_class = get_result_clas...
python
{ "resource": "" }
q18422
score_for_task
train
def score_for_task(properties, category, result): """ Return the possible score of task, depending on whether the result is correct or not. """ assert result is not None if properties and Property.create_from_names(properties).is_svcomp: return _svcomp_score(category, result) return None
python
{ "resource": "" }
q18423
get_result_category
train
def get_result_category(expected_results, result, properties): ''' This function determines the relation between actual result and expected result for the given file and properties. @param filename: The file name of the input file. @param result: The result given by the tool (needs to be one of the ...
python
{ "resource": "" }
q18424
Property.create
train
def create(cls, propertyfile, allow_unknown): """ Create a Property instance by attempting to parse the given property file. @param propertyfile: A file name of a property file @param allow_unknown: Whether to accept unknown properties """ with open(propertyfile) as f: ...
python
{ "resource": "" }
q18425
Property.create_from_names
train
def create_from_names(cls, property_names): """ Create a Property instance from a list of well-known property names @param property_names: a non-empty list of property names """ assert property_names if len(property_names) == 1: name = property_names[0] ...
python
{ "resource": "" }
q18426
get_file_list
train
def get_file_list(shortFile): """ The function get_file_list expands a short filename to a sorted list of filenames. The short filename can contain variables and wildcards. """ if "://" in shortFile: # seems to be a URL return [shortFile] # expand tilde and variables expandedFile = ...
python
{ "resource": "" }
q18427
open_url_seekable
train
def open_url_seekable(path_url, mode='rt'): """Open a URL and ensure that the result is seekable, copying it into a buffer if necessary.""" logging.debug("Making request to '%s'", path_url) response = urllib.request.urlopen(path_url) logging.debug("Got response %s", response.info()) try: ...
python
{ "resource": "" }
q18428
format_options
train
def format_options(options): '''Helper function for formatting the content of the options line''' # split on one of the following tokens: ' -' or '[[' or ']]' lines = [''] for token in re.split(r'( -|\[\[|\]\])', options): if token in ['[[',']]']: lines.append(token) line...
python
{ "resource": "" }
q18429
prettylist
train
def prettylist(list_): """ Filter out duplicate values while keeping order. """ if not list_: return '' values = set() uniqueList = [] for entry in list_: if not entry in values: values.add(entry) uniqueList.append(entry) return uniqueList[0] if...
python
{ "resource": "" }
q18430
get_column_type
train
def get_column_type(column, column_values): """ Returns the type of the given column based on its row values on the given RunSetResult. @param column: the column to return the correct ColumnType for @param column_values: the column values to consider @return: a tuple of a type object describing the ...
python
{ "resource": "" }
q18431
_get_decimal_digits
train
def _get_decimal_digits(decimal_number_match, number_of_significant_digits): """ Returns the amount of decimal digits of the given regex match, considering the number of significant digits for the provided column. @param decimal_number_match: a regex match of a decimal number, resulting from REGEX_MEAS...
python
{ "resource": "" }
q18432
_find_cgroup_mounts
train
def _find_cgroup_mounts(): """ Return the information which subsystems are mounted where. @return a generator of tuples (subsystem, mountpoint) """ try: with open('/proc/mounts', 'rt') as mountsFile: for mount in mountsFile: mount = mount.split(' ') ...
python
{ "resource": "" }
q18433
_register_process_with_cgrulesengd
train
def _register_process_with_cgrulesengd(pid): """Tell cgrulesengd daemon to not move the given process into other cgroups, if libcgroup is available. """ # Logging/printing from inside preexec_fn would end up in the output file, # not in the correct logger, thus it is disabled here. from ctypes i...
python
{ "resource": "" }
q18434
Cgroup.create_fresh_child_cgroup
train
def create_fresh_child_cgroup(self, *subsystems): """ Create child cgroups of the current cgroup for at least the given subsystems. @return: A Cgroup instance representing the new child cgroup(s). """ assert set(subsystems).issubset(self.per_subsystem.keys()) createdCgrou...
python
{ "resource": "" }
q18435
Cgroup.add_task
train
def add_task(self, pid): """ Add a process to the cgroups represented by this instance. """ _register_process_with_cgrulesengd(pid) for cgroup in self.paths: with open(os.path.join(cgroup, 'tasks'), 'w') as tasksFile: tasksFile.write(str(pid))
python
{ "resource": "" }
q18436
Cgroup.get_all_tasks
train
def get_all_tasks(self, subsystem): """ Return a generator of all PIDs currently in this cgroup for the given subsystem. """ with open(os.path.join(self.per_subsystem[subsystem], 'tasks'), 'r') as tasksFile: for line in tasksFile: yield int(line)
python
{ "resource": "" }
q18437
Cgroup.kill_all_tasks_recursively
train
def kill_all_tasks_recursively(self, kill_process_fn): """ Kill all tasks in this cgroup and all its children cgroups forcefully. Additionally, the children cgroups will be deleted. """ def kill_all_tasks_in_cgroup_recursively(cgroup): files = [os.path.join(cgroup,f) ...
python
{ "resource": "" }
q18438
Cgroup.has_value
train
def has_value(self, subsystem, option): """ Check whether the given value exists in the given subsystem. Does not make a difference whether the value is readable, writable, or both. Do not include the subsystem name in the option name. Only call this method if the given subsystem...
python
{ "resource": "" }
q18439
Cgroup.get_value
train
def get_value(self, subsystem, option): """ Read the given value from the given subsystem. Do not include the subsystem name in the option name. Only call this method if the given subsystem is available. """ assert subsystem in self, 'Subsystem {} is missing'.format(subsy...
python
{ "resource": "" }
q18440
Cgroup.get_file_lines
train
def get_file_lines(self, subsystem, option): """ Read the lines of the given file from the given subsystem. Do not include the subsystem name in the option name. Only call this method if the given subsystem is available. """ assert subsystem in self with open(os.p...
python
{ "resource": "" }
q18441
Cgroup.get_key_value_pairs
train
def get_key_value_pairs(self, subsystem, filename): """ Read the lines of the given file from the given subsystem and split the lines into key-value pairs. Do not include the subsystem name in the option name. Only call this method if the given subsystem is available. """...
python
{ "resource": "" }
q18442
Cgroup.set_value
train
def set_value(self, subsystem, option, value): """ Write the given value for the given subsystem. Do not include the subsystem name in the option name. Only call this method if the given subsystem is available. """ assert subsystem in self util.write_file(str(valu...
python
{ "resource": "" }
q18443
Cgroup.remove
train
def remove(self): """ Remove all cgroups this instance represents from the system. This instance is afterwards not usable anymore! """ for cgroup in self.paths: remove_cgroup(cgroup) del self.paths del self.per_subsystem
python
{ "resource": "" }
q18444
parse_time_arg
train
def parse_time_arg(s): """ Parse a time stamp in the "year-month-day hour-minute" format. """ try: return time.strptime(s, "%Y-%m-%d %H:%M") except ValueError as e: raise argparse.ArgumentTypeError(e)
python
{ "resource": "" }
q18445
BenchExec.start
train
def start(self, argv): """ Start BenchExec. @param argv: command-line options for BenchExec """ parser = self.create_argument_parser() self.config = parser.parse_args(argv[1:]) for arg in self.config.files: if not os.path.exists(arg) or not os.path.is...
python
{ "resource": "" }
q18446
BenchExec.execute_benchmark
train
def execute_benchmark(self, benchmark_file): """ Execute a single benchmark as defined in a file. If called directly, ensure that config and executor attributes are set up. @param benchmark_file: the name of a benchmark-definition XML file @return: a result value from the executo...
python
{ "resource": "" }
q18447
BenchExec.check_existing_results
train
def check_existing_results(self, benchmark): """ Check and abort if the target directory for the benchmark results already exists in order to avoid overwriting results. """ if os.path.exists(benchmark.log_folder): sys.exit('Output directory {0} already exists, will no...
python
{ "resource": "" }
q18448
BenchExec.stop
train
def stop(self): """ Stop the execution of a benchmark. This instance cannot be used anymore afterwards. Timely termination is not guaranteed, and this method may return before everything is terminated. """ self.stopped_by_interrupt = True if self.executor...
python
{ "resource": "" }
q18449
allocate_stack
train
def allocate_stack(size=DEFAULT_STACK_SIZE): """Allocate some memory that can be used as a stack. @return: a ctypes void pointer to the *top* of the stack. """ # Allocate memory with appropriate flags for a stack as in https://blog.fefe.de/?ts=a85c8ba7 base = libc.mmap( None, size + ...
python
{ "resource": "" }
q18450
execute_in_namespace
train
def execute_in_namespace(func, use_network_ns=True): """Execute a function in a child process in separate namespaces. @param func: a parameter-less function returning an int (which will be the process' exit value) @return: the PID of the created child process """ flags = (signal.SIGCHLD | li...
python
{ "resource": "" }
q18451
activate_network_interface
train
def activate_network_interface(iface): """Bring up the given network interface. @raise OSError: if interface does not exist or permissions are missing """ iface = iface.encode() SIOCGIFFLAGS = 0x8913 # /usr/include/bits/ioctls.h SIOCSIFFLAGS = 0x8914 # /usr/include/bits/ioctls.h IFF_UP = 0x...
python
{ "resource": "" }
q18452
get_mount_points
train
def get_mount_points(): """Get all current mount points of the system. Changes to the mount points during iteration may be reflected in the result. @return a generator of (source, target, fstype, options), where options is a list of bytes instances, and the others are bytes instances (this avoids en...
python
{ "resource": "" }
q18453
remount_with_additional_flags
train
def remount_with_additional_flags(mountpoint, existing_options, mountflags): """Remount an existing mount point with additional flags. @param mountpoint: the mount point as bytes @param existing_options: dict with current mount existing_options as bytes @param mountflags: int with additional mount exist...
python
{ "resource": "" }
q18454
make_bind_mount
train
def make_bind_mount(source, target, recursive=False, private=False, read_only=False): """Make a bind mount. @param source: the source directory as bytes @param target: the target directory as bytes @param recursive: whether to also recursively bind mount all mounts below source @param private: wheth...
python
{ "resource": "" }
q18455
drop_capabilities
train
def drop_capabilities(keep=[]): """ Drop all capabilities this process has. @param keep: list of capabilities to not drop """ capdata = (libc.CapData * 2)() for cap in keep: capdata[0].effective |= (1 << cap) capdata[0].permitted |= (1 << cap) libc.capset(ctypes.byref(libc.Ca...
python
{ "resource": "" }
q18456
forward_all_signals_async
train
def forward_all_signals_async(target_pid, process_name): """Install all signal handler that forwards all signals to the given process.""" def forwarding_signal_handler(signum): _forward_signal(signum, process_name, forwarding_signal_handler.target_pid) # Somehow we get a Python SystemError sometime...
python
{ "resource": "" }
q18457
wait_for_child_and_forward_all_signals
train
def wait_for_child_and_forward_all_signals(child_pid, process_name): """Wait for a child to terminate and in the meantime forward all signals the current process receives to this child. @return a tuple of exit code and resource usage of the child as given by os.waitpid """ assert _HAS_SIGWAIT bl...
python
{ "resource": "" }
q18458
close_open_fds
train
def close_open_fds(keep_files=[]): """Close all open file descriptors except those in a given set. @param keep_files: an iterable of file descriptors or file-like objects. """ keep_fds = set() for file in keep_files: if isinstance(file, int): keep_fds.add(file) else: ...
python
{ "resource": "" }
q18459
setup_container_system_config
train
def setup_container_system_config(basedir, mountdir=None): """Create a minimal system configuration for use in a container. @param basedir: The directory where the configuration files should be placed as bytes. @param mountdir: If present, bind mounts to the configuration files will be added below t...
python
{ "resource": "" }
q18460
Tool.cmdline
train
def cmdline(self, executable, options, tasks, propertyfile=None, rlimits={}): """ Compose the command line to execute from the name of the executable, the user-specified options, and the inputfile to analyze. This method can get overridden, if, for example, some options should be...
python
{ "resource": "" }
q18461
FileWriter.append
train
def append(self, newContent, keep=True): """ Add content to the represented file. If keep is False, the new content will be forgotten during the next call to this method. """ content = self.__content + newContent if keep: self.__content = content ...
python
{ "resource": "" }
q18462
format_energy_results
train
def format_energy_results(energy): """Take the result of an energy measurement and return a flat dictionary that contains all values.""" if not energy: return {} result = {} cpuenergy = Decimal(0) for pkg, domains in energy.items(): for domain, value in domains.items(): i...
python
{ "resource": "" }
q18463
EnergyMeasurement.start
train
def start(self): """Starts the external measurement program.""" assert not self.is_running(), 'Attempted to start an energy measurement while one was already running.' self._measurement_process = subprocess.Popen( [self._executable, '-r'], stdout=subprocess.PIPE, ...
python
{ "resource": "" }
q18464
EnergyMeasurement.stop
train
def stop(self): """Stops the external measurement program and returns the measurement result, if the measurement was running.""" consumed_energy = collections.defaultdict(dict) if not self.is_running(): return None # cpu-energy-meter expects SIGINT to stop and report ...
python
{ "resource": "" }
q18465
AuthController.login
train
def login(self): """ Show login form. """ if request.method != 'POST': cfg = NipapConfig() try: c.welcome_message = cfg.get('www', 'welcome_message') except NoOptionError: pass return render('login.html') ...
python
{ "resource": "" }
q18466
XhrController.extract_prefix_attr
train
def extract_prefix_attr(cls, req): """ Extract prefix attributes from arbitary dict. """ # TODO: add more? attr = {} if 'id' in req: attr['id'] = int(req['id']) if 'prefix' in req: attr['prefix'] = req['prefix'] if 'pool' in req: ...
python
{ "resource": "" }
q18467
XhrController.extract_pool_attr
train
def extract_pool_attr(cls, req): """ Extract pool attributes from arbitary dict. """ attr = {} if 'id' in req: attr['id'] = int(req['id']) if 'name' in req: attr['name'] = req['name'] if 'description' in req: attr['description'] = req[...
python
{ "resource": "" }
q18468
XhrController.list_vrf
train
def list_vrf(self): """ List VRFs and return JSON encoded result. """ try: vrfs = VRF.list() except NipapError, e: return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__}) return json.dumps(vrfs, cls=NipapJSONEncoder)
python
{ "resource": "" }
q18469
XhrController.add_vrf
train
def add_vrf(self): """ Add a new VRF to NIPAP and return its data. """ v = VRF() if 'rt' in request.json: v.rt = validate_string(request.json, 'rt') if 'name' in request.json: v.name = validate_string(request.json, 'name') if 'description' in requ...
python
{ "resource": "" }
q18470
XhrController.list_pool
train
def list_pool(self): """ List pools and return JSON encoded result. """ # fetch attributes from request.json attr = XhrController.extract_pool_attr(request.json) try: pools = Pool.list(attr) except NipapError, e: return json.dumps({'error': 1, 'm...
python
{ "resource": "" }
q18471
XhrController.list_prefix
train
def list_prefix(self): """ List prefixes and return JSON encoded result. """ # fetch attributes from request.json attr = XhrController.extract_prefix_attr(request.json) try: prefixes = Prefix.list(attr) except NipapError, e: return json.dumps({'e...
python
{ "resource": "" }
q18472
XhrController.search_prefix
train
def search_prefix(self): """ Search prefixes. Does not yet incorporate all the functions of the search_prefix API function due to difficulties with transferring a complete 'dict-to-sql' encoded data structure. Instead, a list of prefix attributes can be given which will be ...
python
{ "resource": "" }
q18473
XhrController.smart_search_prefix
train
def smart_search_prefix(self): """ Perform a smart search. The smart search function tries extract a query from a text string. This query is then passed to the search_prefix function, which performs the search. """ search_options = {} extra_query = N...
python
{ "resource": "" }
q18474
XhrController.add_current_vrf
train
def add_current_vrf(self): """ Add VRF to filter list session variable """ vrf_id = request.json['vrf_id'] if vrf_id is not None: if vrf_id == 'null': vrf = VRF() else: vrf_id = int(vrf_id) vrf = VRF.get(vrf_id) ...
python
{ "resource": "" }
q18475
XhrController.del_current_vrf
train
def del_current_vrf(self): """ Remove VRF to filter list session variable """ vrf_id = int(request.json['vrf_id']) if vrf_id in session['current_vrfs']: del session['current_vrfs'][vrf_id] session.save() return json.dumps(session.get('current_vrfs', {})...
python
{ "resource": "" }
q18476
XhrController.get_current_vrfs
train
def get_current_vrfs(self): """ Return VRF filter list from session variable Before returning list, make a search for all VRFs currently in the list to verify that they still exist. """ # Verify that all currently selected VRFs still exists cur_vrfs = session.ge...
python
{ "resource": "" }
q18477
XhrController.list_tags
train
def list_tags(self): """ List Tags and return JSON encoded result. """ try: tags = Tags.list() except NipapError, e: return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__}) return json.dumps(tags, cls=NipapJSONEncoder)
python
{ "resource": "" }
q18478
NipapConfig.read_file
train
def read_file(self): """ Read the configuration file """ # don't try to parse config file if we don't have one set if not self._cfg_path: return try: cfg_fp = open(self._cfg_path, 'r') self.readfp(cfg_fp) except IOError as exc: ...
python
{ "resource": "" }
q18479
VersionController.index
train
def index(self): """ Display NIPAP version info """ c.pynipap_version = pynipap.__version__ try: c.nipapd_version = pynipap.nipapd_version() except: c.nipapd_version = 'unknown' c.nipap_db_version = pynipap.nipap_db_version() return rende...
python
{ "resource": "" }
q18480
AuthFactory._init_backends
train
def _init_backends(self): """ Initialize auth backends. """ # fetch auth backends from config file self._backends = {} for section in self._config.sections(): # does the section define an auth backend? section_components = section.rsplit('.', 1) ...
python
{ "resource": "" }
q18481
SqliteAuth._create_database
train
def _create_database(self): """ Set up database Creates tables required for the authentication module. """ self._logger.info('creating user database') sql = '''CREATE TABLE IF NOT EXISTS user ( username NOT NULL PRIMARY KEY, pwd_salt NOT NULL, ...
python
{ "resource": "" }
q18482
SqliteAuth.get_user
train
def get_user(self, username): """ Fetch the user from the database The function will return None if the user is not found """ sql = '''SELECT * FROM user WHERE username = ?''' self._db_curs.execute(sql, (username, )) user = self._db_curs.fetchone() return us...
python
{ "resource": "" }
q18483
SqliteAuth.modify_user
train
def modify_user(self, username, data): """ Modify user in SQLite database. Since username is used as primary key and we only have a single argument for it we can't modify the username right now. """ if 'password' in data: # generate salt char_set ...
python
{ "resource": "" }
q18484
SqliteAuth._gen_hash
train
def _gen_hash(self, password, salt): """ Generate password hash. """ # generate hash h = hashlib.sha1() h.update(salt) h.update(password) return h.hexdigest()
python
{ "resource": "" }
q18485
requires_rw
train
def requires_rw(f): """ Adds readwrite authorization This will check if the user is a readonly user and if so reject the query. Apply this decorator to readwrite functions. """ @wraps(f) def decorated(*args, **kwargs): auth = args[1] if auth.readonly: logger...
python
{ "resource": "" }
q18486
_parse_expires
train
def _parse_expires(expires): """ Parse the 'expires' attribute, guessing what format it is in and returning a datetime """ # none is used to signify positive infinity if expires is None or expires in ('never', 'infinity'): return 'infinity' try: return dateutil.parser.parse(...
python
{ "resource": "" }
q18487
Nipap._register_inet
train
def _register_inet(self, oid=None, conn_or_curs=None): """ Create the INET type and an Inet adapter.""" from psycopg2 import extensions as _ext if not oid: oid = 869 _ext.INET = _ext.new_type((oid, ), "INET", lambda data, cursor: data and Inet(data) or None) ...
python
{ "resource": "" }
q18488
Nipap._is_ipv4
train
def _is_ipv4(self, ip): """ Return true if given arg is a valid IPv4 address """ try: p = IPy.IP(ip) except ValueError: return False if p.version() == 4: return True return False
python
{ "resource": "" }
q18489
Nipap._connect_db
train
def _connect_db(self): """ Open database connection """ # Get database configuration db_args = {} db_args['host'] = self._cfg.get('nipapd', 'db_host') db_args['database'] = self._cfg.get('nipapd', 'db_name') db_args['user'] = self._cfg.get('nipapd', 'db_user') ...
python
{ "resource": "" }
q18490
Nipap._get_updated_rows
train
def _get_updated_rows(self, auth, function): """ Get rows updated by last update query * `function` [function] Function to use for searching (one of the search_* functions). Helper function used to fetch all rows which was updated by the latest UPDATE ... RE...
python
{ "resource": "" }
q18491
Nipap._get_query_parts
train
def _get_query_parts(self, query_str, search_options=None): """ Split a query string into its parts """ if search_options is None: search_options = {} if query_str is None: raise NipapValueError("'query_string' must not be None") # find query parts ...
python
{ "resource": "" }
q18492
Nipap._get_db_version
train
def _get_db_version(self): """ Get the schema version of the nipap psql db. """ dbname = self._cfg.get('nipapd', 'db_name') self._execute("SELECT description FROM pg_shdescription JOIN pg_database ON objoid = pg_database.oid WHERE datname = '%s'" % dbname) comment = self._curs_p...
python
{ "resource": "" }
q18493
Nipap._db_install
train
def _db_install(self, db_name): """ Install nipap database schema """ self._logger.info("Installing NIPAP database schemas into db") self._execute(db_schema.ip_net % (db_name)) self._execute(db_schema.functions) self._execute(db_schema.triggers)
python
{ "resource": "" }
q18494
Nipap._db_upgrade
train
def _db_upgrade(self, db_name): """ Upgrade nipap database schema """ current_db_version = self._get_db_version() self._execute(db_schema.functions) for i in range(current_db_version, nipap.__db_version__): self._logger.info("Upgrading DB schema:", i, "to", i+1) ...
python
{ "resource": "" }
q18495
Nipap._expand_vrf_spec
train
def _expand_vrf_spec(self, spec): """ Expand VRF specification to SQL. id [integer] internal database id of VRF name [string] name of VRF A VRF is referenced either by its internal database id or by its name. Both are used for ex...
python
{ "resource": "" }
q18496
Nipap.list_vrf
train
def list_vrf(self, auth, spec=None): """ Return a list of VRFs matching `spec`. * `auth` [BaseAuth] AAA options. * `spec` [vrf_spec] A VRF specification. If omitted, all VRFs are returned. Returns a list of dicts. This is the doc...
python
{ "resource": "" }
q18497
Nipap._get_vrf
train
def _get_vrf(self, auth, spec, prefix = 'vrf_'): """ Get a VRF based on prefix spec Shorthand function to reduce code in the functions below, since more or less all of them needs to perform the actions that are specified here. The major difference to :func:`list...
python
{ "resource": "" }
q18498
Nipap.edit_vrf
train
def edit_vrf(self, auth, spec, attr): """ Update VRFs matching `spec` with attributes `attr`. * `auth` [BaseAuth] AAA options. * `spec` [vrf_spec] Attibutes specifying what VRF to edit. * `attr` [vrf_attr] Dict specifying field...
python
{ "resource": "" }
q18499
Nipap.smart_search_vrf
train
def smart_search_vrf(self, auth, query_str, search_options=None, extra_query=None): """ Perform a smart search on VRF list. * `auth` [BaseAuth] AAA options. * `query_str` [string] Search string * `search_options` [options_dict] ...
python
{ "resource": "" }