repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
get_ip_prefixes_from_bird
def get_ip_prefixes_from_bird(filename): """Build a list of IP prefixes found in Bird configuration. Arguments: filename (str): The absolute path of the Bird configuration file. Notes: It can only parse a file with the following format define ACAST_PS_ADVERTISE = ...
python
def get_ip_prefixes_from_bird(filename): """Build a list of IP prefixes found in Bird configuration. Arguments: filename (str): The absolute path of the Bird configuration file. Notes: It can only parse a file with the following format define ACAST_PS_ADVERTISE = ...
Build a list of IP prefixes found in Bird configuration. Arguments: filename (str): The absolute path of the Bird configuration file. Notes: It can only parse a file with the following format define ACAST_PS_ADVERTISE = [ 10.189.200.155/32, ...
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L624-L652
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
reconfigure_bird
def reconfigure_bird(cmd): """Reconfigure BIRD daemon. Arguments: cmd (string): A command to trigger a reconfiguration of Bird daemon Notes: Runs 'birdc configure' to reconfigure BIRD. Some useful information on how birdc tool works: -- Returns a non-zero exit code only...
python
def reconfigure_bird(cmd): """Reconfigure BIRD daemon. Arguments: cmd (string): A command to trigger a reconfiguration of Bird daemon Notes: Runs 'birdc configure' to reconfigure BIRD. Some useful information on how birdc tool works: -- Returns a non-zero exit code only...
Reconfigure BIRD daemon. Arguments: cmd (string): A command to trigger a reconfiguration of Bird daemon Notes: Runs 'birdc configure' to reconfigure BIRD. Some useful information on how birdc tool works: -- Returns a non-zero exit code only when it can't access BIRD ...
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L725-L778
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
write_temp_bird_conf
def write_temp_bird_conf(dummy_ip_prefix, config_file, variable_name, prefixes): """Write in a temporary file the list of IP-Prefixes. A failure to create and write the temporary file will exit main program. Arguments: dumm...
python
def write_temp_bird_conf(dummy_ip_prefix, config_file, variable_name, prefixes): """Write in a temporary file the list of IP-Prefixes. A failure to create and write the temporary file will exit main program. Arguments: dumm...
Write in a temporary file the list of IP-Prefixes. A failure to create and write the temporary file will exit main program. Arguments: dummy_ip_prefix (str): The dummy IP prefix, which must be always config_file (str): The file name of bird configuration variable_name (str): The name o...
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L781-L827
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
archive_bird_conf
def archive_bird_conf(config_file, changes_counter): """Keep a history of Bird configuration files. Arguments: config_file (str): file name of bird configuration changes_counter (int): number of configuration files to keep in the history """ log = logging.getLogger(PROGRAM_NAME)...
python
def archive_bird_conf(config_file, changes_counter): """Keep a history of Bird configuration files. Arguments: config_file (str): file name of bird configuration changes_counter (int): number of configuration files to keep in the history """ log = logging.getLogger(PROGRAM_NAME)...
Keep a history of Bird configuration files. Arguments: config_file (str): file name of bird configuration changes_counter (int): number of configuration files to keep in the history
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L830-L861
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
update_pidfile
def update_pidfile(pidfile): """Update pidfile. Notice: We should call this function only after we have successfully acquired a lock and never before. It exits main program if it fails to parse and/or write pidfile. Arguments: pidfile (str): pidfile to update """ t...
python
def update_pidfile(pidfile): """Update pidfile. Notice: We should call this function only after we have successfully acquired a lock and never before. It exits main program if it fails to parse and/or write pidfile. Arguments: pidfile (str): pidfile to update """ t...
Update pidfile. Notice: We should call this function only after we have successfully acquired a lock and never before. It exits main program if it fails to parse and/or write pidfile. Arguments: pidfile (str): pidfile to update
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L864-L904
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
write_pid
def write_pid(pidfile): """Write processID to the pidfile. Notice: It exits main program if it fails to write pidfile. Arguments: pidfile (str): pidfile to update """ pid = str(os.getpid()) try: with open(pidfile, mode='w') as _file: print("writing processI...
python
def write_pid(pidfile): """Write processID to the pidfile. Notice: It exits main program if it fails to write pidfile. Arguments: pidfile (str): pidfile to update """ pid = str(os.getpid()) try: with open(pidfile, mode='w') as _file: print("writing processI...
Write processID to the pidfile. Notice: It exits main program if it fails to write pidfile. Arguments: pidfile (str): pidfile to update
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L907-L923
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
shutdown
def shutdown(pidfile, signalnb=None, frame=None): """Clean up pidfile upon shutdown. Notice: We should register this function as signal handler for the following termination signals: SIGHUP SIGTERM SIGABRT SIGINT Arguments: pidfile (s...
python
def shutdown(pidfile, signalnb=None, frame=None): """Clean up pidfile upon shutdown. Notice: We should register this function as signal handler for the following termination signals: SIGHUP SIGTERM SIGABRT SIGINT Arguments: pidfile (s...
Clean up pidfile upon shutdown. Notice: We should register this function as signal handler for the following termination signals: SIGHUP SIGTERM SIGABRT SIGINT Arguments: pidfile (str): pidfile to remove signalnb (int): The ID of ...
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L926-L949
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
setup_logger
def setup_logger(config): """Configure the logging environment. Notice: By default logging will go to STDOUT and messages for unhandled exceptions or crashes will go to STDERR. If log_file and/or log_server is set then we don't log to STDOUT. Messages for unhandled exceptions or...
python
def setup_logger(config): """Configure the logging environment. Notice: By default logging will go to STDOUT and messages for unhandled exceptions or crashes will go to STDERR. If log_file and/or log_server is set then we don't log to STDOUT. Messages for unhandled exceptions or...
Configure the logging environment. Notice: By default logging will go to STDOUT and messages for unhandled exceptions or crashes will go to STDERR. If log_file and/or log_server is set then we don't log to STDOUT. Messages for unhandled exceptions or crashes can only go to either ST...
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L952-L1059
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
run_custom_bird_reconfigure
def run_custom_bird_reconfigure(operation): """Reconfigure BIRD daemon by running a custom command. It adds one argument to the command, either "up" or "down". If command times out then we kill it. In order to avoid leaving any orphan processes, that may have been started by the command, we start a new...
python
def run_custom_bird_reconfigure(operation): """Reconfigure BIRD daemon by running a custom command. It adds one argument to the command, either "up" or "down". If command times out then we kill it. In order to avoid leaving any orphan processes, that may have been started by the command, we start a new...
Reconfigure BIRD daemon by running a custom command. It adds one argument to the command, either "up" or "down". If command times out then we kill it. In order to avoid leaving any orphan processes, that may have been started by the command, we start a new session when we invoke the command and then we...
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L1206-L1248
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
AddOperation.update
def update(self, prefixes): """Add a value to the list. Arguments: prefixes(list): A list to add the value """ if self.ip_prefix not in prefixes: prefixes.append(self.ip_prefix) self.log.info("announcing %s for %s", self.ip_prefix, self.name) ...
python
def update(self, prefixes): """Add a value to the list. Arguments: prefixes(list): A list to add the value """ if self.ip_prefix not in prefixes: prefixes.append(self.ip_prefix) self.log.info("announcing %s for %s", self.ip_prefix, self.name) ...
Add a value to the list. Arguments: prefixes(list): A list to add the value
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L690-L701
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
CustomLogger.write
def write(self, string): """Erase newline from a string and write to the logger.""" string = string.rstrip() if string: # Don't log empty lines self.logger.critical(string)
python
def write(self, string): """Erase newline from a string and write to the logger.""" string = string.rstrip() if string: # Don't log empty lines self.logger.critical(string)
Erase newline from a string and write to the logger.
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L1097-L1101
unixsurfer/anycast_healthchecker
anycast_healthchecker/utils.py
CustomJsonFormatter.process_log_record
def process_log_record(self, log_record): """Add customer record keys and rename threadName key.""" log_record["version"] = __version__ log_record["program"] = PROGRAM_NAME log_record["service_name"] = log_record.pop('threadName', None) # return jsonlogger.JsonFormatter.process_l...
python
def process_log_record(self, log_record): """Add customer record keys and rename threadName key.""" log_record["version"] = __version__ log_record["program"] = PROGRAM_NAME log_record["service_name"] = log_record.pop('threadName', None) # return jsonlogger.JsonFormatter.process_l...
Add customer record keys and rename threadName key.
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L1176-L1183
sashahart/vex
vex/main.py
get_vexrc
def get_vexrc(options, environ): """Get a representation of the contents of the config file. :returns: a Vexrc instance. """ # Complain if user specified nonexistent file with --config. # But we don't want to complain just because ~/.vexrc doesn't exist. if options.config and not os.pat...
python
def get_vexrc(options, environ): """Get a representation of the contents of the config file. :returns: a Vexrc instance. """ # Complain if user specified nonexistent file with --config. # But we don't want to complain just because ~/.vexrc doesn't exist. if options.config and not os.pat...
Get a representation of the contents of the config file. :returns: a Vexrc instance.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L15-L27
sashahart/vex
vex/main.py
get_cwd
def get_cwd(options): """Discover what directory the command should run in. """ if not options.cwd: return None if not os.path.exists(options.cwd): raise exceptions.InvalidCwd( "can't --cwd to invalid path {0!r}".format(options.cwd)) return options.cwd
python
def get_cwd(options): """Discover what directory the command should run in. """ if not options.cwd: return None if not os.path.exists(options.cwd): raise exceptions.InvalidCwd( "can't --cwd to invalid path {0!r}".format(options.cwd)) return options.cwd
Discover what directory the command should run in.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L30-L38
sashahart/vex
vex/main.py
get_virtualenv_path
def get_virtualenv_path(ve_base, ve_name): """Check a virtualenv path, raising exceptions to explain problems. """ if not ve_base: raise exceptions.NoVirtualenvsDirectory( "could not figure out a virtualenvs directory. " "make sure $HOME is set, or $WORKON_HOME," ...
python
def get_virtualenv_path(ve_base, ve_name): """Check a virtualenv path, raising exceptions to explain problems. """ if not ve_base: raise exceptions.NoVirtualenvsDirectory( "could not figure out a virtualenvs directory. " "make sure $HOME is set, or $WORKON_HOME," ...
Check a virtualenv path, raising exceptions to explain problems.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L53-L88
sashahart/vex
vex/main.py
get_command
def get_command(options, vexrc, environ): """Get a command to run. :returns: a list of strings representing a command to be passed to Popen. """ command = options.rest if not command: command = vexrc.get_shell(environ) if command and command[0].startswith('--'): raise ex...
python
def get_command(options, vexrc, environ): """Get a command to run. :returns: a list of strings representing a command to be passed to Popen. """ command = options.rest if not command: command = vexrc.get_shell(environ) if command and command[0].startswith('--'): raise ex...
Get a command to run. :returns: a list of strings representing a command to be passed to Popen.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L91-L106
sashahart/vex
vex/main.py
_main
def _main(environ, argv): """Logic for main(), with less direct system interaction. Routines called here raise InvalidArgument with messages that should be delivered on stderr, to be caught by main. """ options = get_options(argv) if options.version: return handle_version() vexrc = ...
python
def _main(environ, argv): """Logic for main(), with less direct system interaction. Routines called here raise InvalidArgument with messages that should be delivered on stderr, to be caught by main. """ options = get_options(argv) if options.version: return handle_version() vexrc = ...
Logic for main(), with less direct system interaction. Routines called here raise InvalidArgument with messages that should be delivered on stderr, to be caught by main.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L130-L182
sashahart/vex
vex/main.py
main
def main(): """The main command-line entry point, with system interactions. """ argv = sys.argv[1:] returncode = 1 try: returncode = _main(os.environ, argv) except exceptions.InvalidArgument as error: if error.message: sys.stderr.write("Error: " + error.message + '\n'...
python
def main(): """The main command-line entry point, with system interactions. """ argv = sys.argv[1:] returncode = 1 try: returncode = _main(os.environ, argv) except exceptions.InvalidArgument as error: if error.message: sys.stderr.write("Error: " + error.message + '\n'...
The main command-line entry point, with system interactions.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L185-L197
unixsurfer/anycast_healthchecker
contrib/nagios/check_anycast_healthchecker.py
get_processid
def get_processid(config): """Return process id of anycast-healthchecker. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. Returns: The process id found in the pid file Raises: ValueError in the following cases - p...
python
def get_processid(config): """Return process id of anycast-healthchecker. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. Returns: The process id found in the pid file Raises: ValueError in the following cases - p...
Return process id of anycast-healthchecker. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. Returns: The process id found in the pid file Raises: ValueError in the following cases - pidfile option is missing from the ...
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/contrib/nagios/check_anycast_healthchecker.py#L22-L63
unixsurfer/anycast_healthchecker
contrib/nagios/check_anycast_healthchecker.py
parse_services
def parse_services(config, services): """Parse configuration to return number of enabled service checks. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. services (list): A list of section names which holds configuration for each se...
python
def parse_services(config, services): """Parse configuration to return number of enabled service checks. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. services (list): A list of section names which holds configuration for each se...
Parse configuration to return number of enabled service checks. Arguments: config (obj): A configparser object with the configuration of anycast-healthchecker. services (list): A list of section names which holds configuration for each service check Returns: A number (i...
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/contrib/nagios/check_anycast_healthchecker.py#L90-L109
unixsurfer/anycast_healthchecker
contrib/nagios/check_anycast_healthchecker.py
main
def main(): """Run check. anycast-healthchecker is a multi-threaded software and for each service check it holds a thread. If a thread dies then the service is not monitored anymore and the route for the IP associated with service it wont be withdrawn in case service goes down in the meantime. ...
python
def main(): """Run check. anycast-healthchecker is a multi-threaded software and for each service check it holds a thread. If a thread dies then the service is not monitored anymore and the route for the IP associated with service it wont be withdrawn in case service goes down in the meantime. ...
Run check. anycast-healthchecker is a multi-threaded software and for each service check it holds a thread. If a thread dies then the service is not monitored anymore and the route for the IP associated with service it wont be withdrawn in case service goes down in the meantime.
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/contrib/nagios/check_anycast_healthchecker.py#L112-L184
sashahart/vex
vex/shell_config.py
scary_path
def scary_path(path): """Whitelist the WORKON_HOME strings we're willing to substitute in to strings that we provide for user's shell to evaluate. If it smells at all bad, return True. """ if not path: return True assert isinstance(path, bytes) return not NOT_SCARY.match(path)
python
def scary_path(path): """Whitelist the WORKON_HOME strings we're willing to substitute in to strings that we provide for user's shell to evaluate. If it smells at all bad, return True. """ if not path: return True assert isinstance(path, bytes) return not NOT_SCARY.match(path)
Whitelist the WORKON_HOME strings we're willing to substitute in to strings that we provide for user's shell to evaluate. If it smells at all bad, return True.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/shell_config.py#L22-L31
sashahart/vex
vex/shell_config.py
shell_config_for
def shell_config_for(shell, vexrc, environ): """return completion config for the named shell. """ here = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(here, 'shell_configs', shell) try: with open(path, 'rb') as inp: data = inp.read() except FileNotFoundError ...
python
def shell_config_for(shell, vexrc, environ): """return completion config for the named shell. """ here = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(here, 'shell_configs', shell) try: with open(path, 'rb') as inp: data = inp.read() except FileNotFoundError ...
return completion config for the named shell.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/shell_config.py#L34-L49
sashahart/vex
vex/shell_config.py
handle_shell_config
def handle_shell_config(shell, vexrc, environ): """Carry out the logic of the --shell-config option. """ from vex import shell_config data = shell_config.shell_config_for(shell, vexrc, environ) if not data: raise exceptions.OtherShell("unknown shell: {0!r}".format(shell)) if hasattr(sys....
python
def handle_shell_config(shell, vexrc, environ): """Carry out the logic of the --shell-config option. """ from vex import shell_config data = shell_config.shell_config_for(shell, vexrc, environ) if not data: raise exceptions.OtherShell("unknown shell: {0!r}".format(shell)) if hasattr(sys....
Carry out the logic of the --shell-config option.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/shell_config.py#L52-L63
unixsurfer/anycast_healthchecker
anycast_healthchecker/servicecheck.py
ServiceCheck._run_check
def _run_check(self): """Execute a check command. Returns: True if the exit code of the command is 0 otherwise False. """ cmd = shlex.split(self.config['check_cmd']) self.log.info("running %s", ' '.join(cmd)) proc = subprocess.Popen(cmd, stdout=subprocess.PI...
python
def _run_check(self): """Execute a check command. Returns: True if the exit code of the command is 0 otherwise False. """ cmd = shlex.split(self.config['check_cmd']) self.log.info("running %s", ' '.join(cmd)) proc = subprocess.Popen(cmd, stdout=subprocess.PI...
Execute a check command. Returns: True if the exit code of the command is 0 otherwise False.
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L88-L123
unixsurfer/anycast_healthchecker
anycast_healthchecker/servicecheck.py
ServiceCheck._ip_assigned
def _ip_assigned(self): """Check if IP prefix is assigned to loopback interface. Returns: True if IP prefix found assigned otherwise False. """ output = [] cmd = [ '/sbin/ip', 'address', 'show', 'dev', self...
python
def _ip_assigned(self): """Check if IP prefix is assigned to loopback interface. Returns: True if IP prefix found assigned otherwise False. """ output = [] cmd = [ '/sbin/ip', 'address', 'show', 'dev', self...
Check if IP prefix is assigned to loopback interface. Returns: True if IP prefix found assigned otherwise False.
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L125-L193
unixsurfer/anycast_healthchecker
anycast_healthchecker/servicecheck.py
ServiceCheck._check_disabled
def _check_disabled(self): """Check if health check is disabled. It logs a message if health check is disabled and it also adds an item to the action queue based on 'on_disabled' setting. Returns: True if check is disabled otherwise False. """ if self.confi...
python
def _check_disabled(self): """Check if health check is disabled. It logs a message if health check is disabled and it also adds an item to the action queue based on 'on_disabled' setting. Returns: True if check is disabled otherwise False. """ if self.confi...
Check if health check is disabled. It logs a message if health check is disabled and it also adds an item to the action queue based on 'on_disabled' setting. Returns: True if check is disabled otherwise False.
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L195-L220
unixsurfer/anycast_healthchecker
anycast_healthchecker/servicecheck.py
ServiceCheck.run
def run(self): """Wrap _run method.""" # Catch all possible exceptions raised by the running thread # and let parent process know about it. try: self._run() except Exception: # pylint: disable=broad-except self.action.put( ServiceCheckDied...
python
def run(self): """Wrap _run method.""" # Catch all possible exceptions raised by the running thread # and let parent process know about it. try: self._run() except Exception: # pylint: disable=broad-except self.action.put( ServiceCheckDied...
Wrap _run method.
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L222-L231
unixsurfer/anycast_healthchecker
anycast_healthchecker/servicecheck.py
ServiceCheck._run
def _run(self): """Discovers the health of a service. Runs until it is being killed from main program and is responsible to put an item into the queue based on the status of the health check. The status of service is consider UP after a number of consecutive successful health ch...
python
def _run(self): """Discovers the health of a service. Runs until it is being killed from main program and is responsible to put an item into the queue based on the status of the health check. The status of service is consider UP after a number of consecutive successful health ch...
Discovers the health of a service. Runs until it is being killed from main program and is responsible to put an item into the queue based on the status of the health check. The status of service is consider UP after a number of consecutive successful health checks, in that case it asks ...
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L233-L337
unixsurfer/anycast_healthchecker
anycast_healthchecker/main.py
main
def main(): """Parse CLI and starts main program.""" args = docopt(__doc__, version=__version__) if args['--print']: for section in DEFAULT_OPTIONS: print("[{}]".format(section)) for key, value in DEFAULT_OPTIONS[section].items(): print("{k} = {v}".format(k=ke...
python
def main(): """Parse CLI and starts main program.""" args = docopt(__doc__, version=__version__) if args['--print']: for section in DEFAULT_OPTIONS: print("[{}]".format(section)) for key, value in DEFAULT_OPTIONS[section].items(): print("{k} = {v}".format(k=ke...
Parse CLI and starts main program.
https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/main.py#L38-L98
sashahart/vex
vex/run.py
get_environ
def get_environ(environ, defaults, ve_path): """Make an environment to run with. """ # Copy the parent environment, add in defaults from .vexrc. env = environ.copy() env.update(defaults) # Leaving in existing PYTHONHOME can cause some errors if 'PYTHONHOME' in env: del env['PYTHONHO...
python
def get_environ(environ, defaults, ve_path): """Make an environment to run with. """ # Copy the parent environment, add in defaults from .vexrc. env = environ.copy() env.update(defaults) # Leaving in existing PYTHONHOME can cause some errors if 'PYTHONHOME' in env: del env['PYTHONHO...
Make an environment to run with.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/run.py#L10-L64
sashahart/vex
vex/run.py
run
def run(command, env, cwd): """Run the given command. """ assert command if cwd: assert os.path.exists(cwd) if platform.system() == "Windows": exe = distutils.spawn.find_executable(command[0], path=env['PATH']) if exe: command[0] = exe _, command_name = os.pat...
python
def run(command, env, cwd): """Run the given command. """ assert command if cwd: assert os.path.exists(cwd) if platform.system() == "Windows": exe = distutils.spawn.find_executable(command[0], path=env['PATH']) if exe: command[0] = exe _, command_name = os.pat...
Run the given command.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/run.py#L67-L88
sashahart/vex
vex/config.py
extract_key_value
def extract_key_value(line, environ): """Return key, value from given line if present, else return None. """ segments = line.split("=", 1) if len(segments) < 2: return None key, value = segments # foo passes through as-is (with spaces stripped) # '{foo}' passes through literally ...
python
def extract_key_value(line, environ): """Return key, value from given line if present, else return None. """ segments = line.split("=", 1) if len(segments) < 2: return None key, value = segments # foo passes through as-is (with spaces stripped) # '{foo}' passes through literally ...
Return key, value from given line if present, else return None.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L129-L147
sashahart/vex
vex/config.py
parse_vexrc
def parse_vexrc(inp, environ): """Iterator yielding key/value pairs from given stream. yields tuples of heading, key, value. """ heading = None errors = [] with inp: for line_number, line in enumerate(inp): line = line.decode("utf-8") if not line.strip(): ...
python
def parse_vexrc(inp, environ): """Iterator yielding key/value pairs from given stream. yields tuples of heading, key, value. """ heading = None errors = [] with inp: for line_number, line in enumerate(inp): line = line.decode("utf-8") if not line.strip(): ...
Iterator yielding key/value pairs from given stream. yields tuples of heading, key, value.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L150-L175
sashahart/vex
vex/config.py
Vexrc.from_file
def from_file(cls, path, environ): """Make a Vexrc instance from given file in given environ. """ instance = cls() instance.read(path, environ) return instance
python
def from_file(cls, path, environ): """Make a Vexrc instance from given file in given environ. """ instance = cls() instance.read(path, environ) return instance
Make a Vexrc instance from given file in given environ.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L54-L59
sashahart/vex
vex/config.py
Vexrc.read
def read(self, path, environ): """Read data from file into this vexrc instance. """ try: inp = open(path, 'rb') except FileNotFoundError as error: if error.errno != 2: raise return None parsing = parse_vexrc(inp, environ) ...
python
def read(self, path, environ): """Read data from file into this vexrc instance. """ try: inp = open(path, 'rb') except FileNotFoundError as error: if error.errno != 2: raise return None parsing = parse_vexrc(inp, environ) ...
Read data from file into this vexrc instance.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L61-L76
sashahart/vex
vex/config.py
Vexrc.get_ve_base
def get_ve_base(self, environ): """Find a directory to look for virtualenvs in. """ # set ve_base to a path we can look for virtualenvs: # 1. .vexrc # 2. WORKON_HOME (as defined for virtualenvwrapper's benefit) # 3. $HOME/.virtualenvs # (unless we got --path, then...
python
def get_ve_base(self, environ): """Find a directory to look for virtualenvs in. """ # set ve_base to a path we can look for virtualenvs: # 1. .vexrc # 2. WORKON_HOME (as defined for virtualenvwrapper's benefit) # 3. $HOME/.virtualenvs # (unless we got --path, then...
Find a directory to look for virtualenvs in.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L78-L108
sashahart/vex
vex/config.py
Vexrc.get_shell
def get_shell(self, environ): """Find a command to run. """ command = self.headings[self.default_heading].get('shell') if not command and os.name != 'nt': command = environ.get('SHELL', '') command = shlex.split(command) if command else None return command
python
def get_shell(self, environ): """Find a command to run. """ command = self.headings[self.default_heading].get('shell') if not command and os.name != 'nt': command = environ.get('SHELL', '') command = shlex.split(command) if command else None return command
Find a command to run.
https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L110-L117
rndusr/torf
torf/_torrent.py
Torrent.files
def files(self): """ Yield relative file paths specified in :attr:`metainfo` Each paths starts with :attr:`name`. Note that the paths may not exist. See :attr:`filepaths` for existing files. """ info = self.metainfo['info'] if 'length' in info: # Sing...
python
def files(self): """ Yield relative file paths specified in :attr:`metainfo` Each paths starts with :attr:`name`. Note that the paths may not exist. See :attr:`filepaths` for existing files. """ info = self.metainfo['info'] if 'length' in info: # Sing...
Yield relative file paths specified in :attr:`metainfo` Each paths starts with :attr:`name`. Note that the paths may not exist. See :attr:`filepaths` for existing files.
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L193-L208
rndusr/torf
torf/_torrent.py
Torrent.filepaths
def filepaths(self): """ Yield absolute paths to existing files in :attr:`path` Any files that match patterns in :attr:`exclude` as well as hidden and empty files are not included. """ if self.path is not None: yield from utils.filepaths(self.path, exclude=se...
python
def filepaths(self): """ Yield absolute paths to existing files in :attr:`path` Any files that match patterns in :attr:`exclude` as well as hidden and empty files are not included. """ if self.path is not None: yield from utils.filepaths(self.path, exclude=se...
Yield absolute paths to existing files in :attr:`path` Any files that match patterns in :attr:`exclude` as well as hidden and empty files are not included.
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L211-L220
rndusr/torf
torf/_torrent.py
Torrent.filetree
def filetree(self): """ :attr:`files` as a dictionary tree Each node is a ``dict`` that maps directory/file names to child nodes. Each child node is a ``dict`` for directories and ``None`` for files. If :attr:`path` is ``None``, this is an empty ``dict``. """ tr...
python
def filetree(self): """ :attr:`files` as a dictionary tree Each node is a ``dict`` that maps directory/file names to child nodes. Each child node is a ``dict`` for directories and ``None`` for files. If :attr:`path` is ``None``, this is an empty ``dict``. """ tr...
:attr:`files` as a dictionary tree Each node is a ``dict`` that maps directory/file names to child nodes. Each child node is a ``dict`` for directories and ``None`` for files. If :attr:`path` is ``None``, this is an empty ``dict``.
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L223-L244
rndusr/torf
torf/_torrent.py
Torrent.size
def size(self): """ Total size of content in bytes or ``None`` if :attr:`path` is ``None`` """ if 'length' in self.metainfo['info']: # Singlefile return self.metainfo['info']['length'] elif 'files' in self.metainfo['info']: # Multifile torrent return su...
python
def size(self): """ Total size of content in bytes or ``None`` if :attr:`path` is ``None`` """ if 'length' in self.metainfo['info']: # Singlefile return self.metainfo['info']['length'] elif 'files' in self.metainfo['info']: # Multifile torrent return su...
Total size of content in bytes or ``None`` if :attr:`path` is ``None``
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L247-L255
rndusr/torf
torf/_torrent.py
Torrent.piece_size
def piece_size(self): """ Piece size/length or ``None`` If set to ``None``, :attr:`calculate_piece_size` is called. If :attr:`size` returns ``None``, this also returns ``None``. Setting this property sets ``piece length`` in :attr:`metainfo`\ ``['info']``. """ ...
python
def piece_size(self): """ Piece size/length or ``None`` If set to ``None``, :attr:`calculate_piece_size` is called. If :attr:`size` returns ``None``, this also returns ``None``. Setting this property sets ``piece length`` in :attr:`metainfo`\ ``['info']``. """ ...
Piece size/length or ``None`` If set to ``None``, :attr:`calculate_piece_size` is called. If :attr:`size` returns ``None``, this also returns ``None``. Setting this property sets ``piece length`` in :attr:`metainfo`\ ``['info']``.
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L258-L274
rndusr/torf
torf/_torrent.py
Torrent.calculate_piece_size
def calculate_piece_size(self): """ Calculate and add ``piece length`` to ``info`` in :attr:`metainfo` The piece size is calculated so that there are no more than :attr:`MAX_PIECES` pieces unless it is larger than :attr:`MAX_PIECE_SIZE`, in which case there is no limit on the nu...
python
def calculate_piece_size(self): """ Calculate and add ``piece length`` to ``info`` in :attr:`metainfo` The piece size is calculated so that there are no more than :attr:`MAX_PIECES` pieces unless it is larger than :attr:`MAX_PIECE_SIZE`, in which case there is no limit on the nu...
Calculate and add ``piece length`` to ``info`` in :attr:`metainfo` The piece size is calculated so that there are no more than :attr:`MAX_PIECES` pieces unless it is larger than :attr:`MAX_PIECE_SIZE`, in which case there is no limit on the number of pieces. :raises RuntimeErro...
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L293-L309
rndusr/torf
torf/_torrent.py
Torrent.pieces
def pieces(self): """ Number of pieces the content is split into or ``None`` if :attr:`piece_size` returns ``None`` """ if self.piece_size is None: return None else: return math.ceil(self.size / self.piece_size)
python
def pieces(self): """ Number of pieces the content is split into or ``None`` if :attr:`piece_size` returns ``None`` """ if self.piece_size is None: return None else: return math.ceil(self.size / self.piece_size)
Number of pieces the content is split into or ``None`` if :attr:`piece_size` returns ``None``
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L312-L320
rndusr/torf
torf/_torrent.py
Torrent.name
def name(self): """ Name of the torrent Default to last item in :attr:`path` or ``None`` if :attr:`path` is ``None``. Setting this property sets or removes ``name`` in :attr:`metainfo`\ ``['info']``. """ if 'name' not in self.metainfo['info'] and self.pa...
python
def name(self): """ Name of the torrent Default to last item in :attr:`path` or ``None`` if :attr:`path` is ``None``. Setting this property sets or removes ``name`` in :attr:`metainfo`\ ``['info']``. """ if 'name' not in self.metainfo['info'] and self.pa...
Name of the torrent Default to last item in :attr:`path` or ``None`` if :attr:`path` is ``None``. Setting this property sets or removes ``name`` in :attr:`metainfo`\ ``['info']``.
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L323-L335
rndusr/torf
torf/_torrent.py
Torrent.trackers
def trackers(self): """ List of tiers of announce URLs or ``None`` for no trackers A tier is either a single announce URL (:class:`str`) or an :class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce URLs. Setting this property sets or removes ``announce`` an...
python
def trackers(self): """ List of tiers of announce URLs or ``None`` for no trackers A tier is either a single announce URL (:class:`str`) or an :class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce URLs. Setting this property sets or removes ``announce`` an...
List of tiers of announce URLs or ``None`` for no trackers A tier is either a single announce URL (:class:`str`) or an :class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce URLs. Setting this property sets or removes ``announce`` and ``announce-list`` in :attr:`me...
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L345-L365
rndusr/torf
torf/_torrent.py
Torrent.infohash
def infohash(self): """SHA1 info hash""" self.validate() info = self.convert()[b'info'] return sha1(bencode(info)).hexdigest()
python
def infohash(self): """SHA1 info hash""" self.validate() info = self.convert()[b'info'] return sha1(bencode(info)).hexdigest()
SHA1 info hash
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L548-L552
rndusr/torf
torf/_torrent.py
Torrent.infohash_base32
def infohash_base32(self): """Base32 encoded SHA1 info hash""" self.validate() info = self.convert()[b'info'] return b32encode(sha1(bencode(info)).digest())
python
def infohash_base32(self): """Base32 encoded SHA1 info hash""" self.validate() info = self.convert()[b'info'] return b32encode(sha1(bencode(info)).digest())
Base32 encoded SHA1 info hash
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L555-L559
rndusr/torf
torf/_torrent.py
Torrent.generate
def generate(self, callback=None, interval=0): """ Hash pieces and report progress to `callback` This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all pieces are hashed successfully. :param callable callback: Callable with signature ``(torrent, filepath, ...
python
def generate(self, callback=None, interval=0): """ Hash pieces and report progress to `callback` This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all pieces are hashed successfully. :param callable callback: Callable with signature ``(torrent, filepath, ...
Hash pieces and report progress to `callback` This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all pieces are hashed successfully. :param callable callback: Callable with signature ``(torrent, filepath, pieces_done, pieces_total)``; if `callback` returns anything ...
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L593-L641
rndusr/torf
torf/_torrent.py
Torrent.convert
def convert(self): """ Return :attr:`metainfo` with all keys encoded to :class:`bytes` and all values encoded to :class:`bytes`, :class:`int`, :class:`list` or :class:`OrderedDict` :raises MetainfoError: on values that cannot be converted properly """ try: ...
python
def convert(self): """ Return :attr:`metainfo` with all keys encoded to :class:`bytes` and all values encoded to :class:`bytes`, :class:`int`, :class:`list` or :class:`OrderedDict` :raises MetainfoError: on values that cannot be converted properly """ try: ...
Return :attr:`metainfo` with all keys encoded to :class:`bytes` and all values encoded to :class:`bytes`, :class:`int`, :class:`list` or :class:`OrderedDict` :raises MetainfoError: on values that cannot be converted properly
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L707-L718
rndusr/torf
torf/_torrent.py
Torrent.validate
def validate(self): """ Check if all mandatory keys exist in :attr:`metainfo` and are of expected types The necessary values are documented here: | http://bittorrent.org/beps/bep_0003.html | https://wiki.theory.org/index.php/BitTorrentSpecification#Metainfo_File_...
python
def validate(self): """ Check if all mandatory keys exist in :attr:`metainfo` and are of expected types The necessary values are documented here: | http://bittorrent.org/beps/bep_0003.html | https://wiki.theory.org/index.php/BitTorrentSpecification#Metainfo_File_...
Check if all mandatory keys exist in :attr:`metainfo` and are of expected types The necessary values are documented here: | http://bittorrent.org/beps/bep_0003.html | https://wiki.theory.org/index.php/BitTorrentSpecification#Metainfo_File_Structure Note that ``announce`...
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L720-L796
rndusr/torf
torf/_torrent.py
Torrent.dump
def dump(self, validate=True): """ Create bencoded :attr:`metainfo` (i.e. the content of a torrent file) :param bool validate: Whether to run :meth:`validate` first :return: :attr:`metainfo` as bencoded :class:`bytes` """ if validate: self.validate() ...
python
def dump(self, validate=True): """ Create bencoded :attr:`metainfo` (i.e. the content of a torrent file) :param bool validate: Whether to run :meth:`validate` first :return: :attr:`metainfo` as bencoded :class:`bytes` """ if validate: self.validate() ...
Create bencoded :attr:`metainfo` (i.e. the content of a torrent file) :param bool validate: Whether to run :meth:`validate` first :return: :attr:`metainfo` as bencoded :class:`bytes`
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L798-L808
rndusr/torf
torf/_torrent.py
Torrent.write_stream
def write_stream(self, stream, validate=True): """ Write :attr:`metainfo` to a file-like object Before any data is written, `stream` is truncated if possible. :param stream: Writable file-like object (e.g. :class:`io.BytesIO`) :param bool validate: Whether to run :meth:`validat...
python
def write_stream(self, stream, validate=True): """ Write :attr:`metainfo` to a file-like object Before any data is written, `stream` is truncated if possible. :param stream: Writable file-like object (e.g. :class:`io.BytesIO`) :param bool validate: Whether to run :meth:`validat...
Write :attr:`metainfo` to a file-like object Before any data is written, `stream` is truncated if possible. :param stream: Writable file-like object (e.g. :class:`io.BytesIO`) :param bool validate: Whether to run :meth:`validate` first :raises WriteError: if writing to `stream` fails ...
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L810-L832
rndusr/torf
torf/_torrent.py
Torrent.write
def write(self, filepath, validate=True, overwrite=False, mode=0o666): """ Write :attr:`metainfo` to torrent file This method is essentially equivalent to: >>> with open('my.torrent', 'wb') as f: ... f.write(torrent.dump()) :param filepath: Path of the torrent file...
python
def write(self, filepath, validate=True, overwrite=False, mode=0o666): """ Write :attr:`metainfo` to torrent file This method is essentially equivalent to: >>> with open('my.torrent', 'wb') as f: ... f.write(torrent.dump()) :param filepath: Path of the torrent file...
Write :attr:`metainfo` to torrent file This method is essentially equivalent to: >>> with open('my.torrent', 'wb') as f: ... f.write(torrent.dump()) :param filepath: Path of the torrent file :param bool validate: Whether to run :meth:`validate` first :param bool ov...
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L834-L865
rndusr/torf
torf/_torrent.py
Torrent.magnet
def magnet(self, name=True, size=True, trackers=True, tracker=False, validate=True): """ BTIH Magnet URI :param bool name: Whether to include the name :param bool size: Whether to include the size :param bool trackers: Whether to include all trackers :param bool tracker:...
python
def magnet(self, name=True, size=True, trackers=True, tracker=False, validate=True): """ BTIH Magnet URI :param bool name: Whether to include the name :param bool size: Whether to include the size :param bool trackers: Whether to include all trackers :param bool tracker:...
BTIH Magnet URI :param bool name: Whether to include the name :param bool size: Whether to include the size :param bool trackers: Whether to include all trackers :param bool tracker: Whether to include only the first tracker of the first tier (overrides `trackers`) :...
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L867-L895
rndusr/torf
torf/_torrent.py
Torrent.read_stream
def read_stream(cls, stream, validate=True): """ Read torrent metainfo from file-like object :param stream: Readable file-like object (e.g. :class:`io.BytesIO`) :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if rea...
python
def read_stream(cls, stream, validate=True): """ Read torrent metainfo from file-like object :param stream: Readable file-like object (e.g. :class:`io.BytesIO`) :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if rea...
Read torrent metainfo from file-like object :param stream: Readable file-like object (e.g. :class:`io.BytesIO`) :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if reading from `stream` fails :raises ParseError: if `stream` ...
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L903-L963
rndusr/torf
torf/_torrent.py
Torrent.read
def read(cls, filepath, validate=True): """ Read torrent metainfo from file :param filepath: Path of the torrent file :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if reading from `filepath` fails :raises ...
python
def read(cls, filepath, validate=True): """ Read torrent metainfo from file :param filepath: Path of the torrent file :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if reading from `filepath` fails :raises ...
Read torrent metainfo from file :param filepath: Path of the torrent file :param bool validate: Whether to run :meth:`validate` on the new Torrent object :raises ReadError: if reading from `filepath` fails :raises ParseError: if `filepath` does not contain a valid bencoded ...
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L966-L988
rndusr/torf
torf/_torrent.py
Torrent.copy
def copy(self): """ Return a new object with the same metainfo Internally, this simply copies the internal metainfo dictionary with :func:`copy.deepcopy` and gives it to the new instance. """ from copy import deepcopy cp = type(self)() cp._metainfo = deep...
python
def copy(self): """ Return a new object with the same metainfo Internally, this simply copies the internal metainfo dictionary with :func:`copy.deepcopy` and gives it to the new instance. """ from copy import deepcopy cp = type(self)() cp._metainfo = deep...
Return a new object with the same metainfo Internally, this simply copies the internal metainfo dictionary with :func:`copy.deepcopy` and gives it to the new instance.
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L990-L1000
rndusr/torf
torf/_utils.py
validated_url
def validated_url(url): """Return url if valid, raise URLError otherwise""" try: u = urlparse(url) u.port # Trigger 'invalid port' exception except Exception: raise error.URLError(url) else: if not u.scheme or not u.netloc: raise error.URLError(url) r...
python
def validated_url(url): """Return url if valid, raise URLError otherwise""" try: u = urlparse(url) u.port # Trigger 'invalid port' exception except Exception: raise error.URLError(url) else: if not u.scheme or not u.netloc: raise error.URLError(url) r...
Return url if valid, raise URLError otherwise
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L38-L48
rndusr/torf
torf/_utils.py
read_chunks
def read_chunks(filepath, chunk_size): """Generator that yields chunks from file""" try: with open(filepath, 'rb') as f: while True: chunk = f.read(chunk_size) if chunk: yield chunk else: break # EOF ...
python
def read_chunks(filepath, chunk_size): """Generator that yields chunks from file""" try: with open(filepath, 'rb') as f: while True: chunk = f.read(chunk_size) if chunk: yield chunk else: break # EOF ...
Generator that yields chunks from file
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L51-L62
rndusr/torf
torf/_utils.py
calc_piece_size
def calc_piece_size(total_size, max_pieces, min_piece_size, max_piece_size): """Calculate piece size""" ps = 1 << max(0, math.ceil(math.log(total_size / max_pieces, 2))) if ps < min_piece_size: ps = min_piece_size if ps > max_piece_size: ps = max_piece_size return ps
python
def calc_piece_size(total_size, max_pieces, min_piece_size, max_piece_size): """Calculate piece size""" ps = 1 << max(0, math.ceil(math.log(total_size / max_pieces, 2))) if ps < min_piece_size: ps = min_piece_size if ps > max_piece_size: ps = max_piece_size return ps
Calculate piece size
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L65-L72
rndusr/torf
torf/_utils.py
is_power_of_2
def is_power_of_2(num): """Return whether `num` is a power of two""" log = math.log2(num) return int(log) == float(log)
python
def is_power_of_2(num): """Return whether `num` is a power of two""" log = math.log2(num) return int(log) == float(log)
Return whether `num` is a power of two
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L75-L78
rndusr/torf
torf/_utils.py
is_hidden
def is_hidden(path): """Whether file or directory is hidden""" for name in path.split(os.sep): if name != '.' and name != '..' and name and name[0] == '.': return True return False
python
def is_hidden(path): """Whether file or directory is hidden""" for name in path.split(os.sep): if name != '.' and name != '..' and name and name[0] == '.': return True return False
Whether file or directory is hidden
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L81-L86
rndusr/torf
torf/_utils.py
filepaths
def filepaths(path, exclude=(), hidden=True, empty=True): """ Return list of absolute, sorted file paths path: Path to file or directory exclude: List of file name patterns to exclude hidden: Whether to include hidden files empty: Whether to include empty files Raise PathNotFoundError if p...
python
def filepaths(path, exclude=(), hidden=True, empty=True): """ Return list of absolute, sorted file paths path: Path to file or directory exclude: List of file name patterns to exclude hidden: Whether to include hidden files empty: Whether to include empty files Raise PathNotFoundError if p...
Return list of absolute, sorted file paths path: Path to file or directory exclude: List of file name patterns to exclude hidden: Whether to include hidden files empty: Whether to include empty files Raise PathNotFoundError if path doesn't exist.
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L96-L136
rndusr/torf
torf/_utils.py
key_exists_in_list_or_dict
def key_exists_in_list_or_dict(key, lst_or_dct): """True if `lst_or_dct[key]` does not raise an Exception""" if isinstance(lst_or_dct, dict) and key in lst_or_dct: return True elif isinstance(lst_or_dct, list): min_i, max_i = 0, len(lst_or_dct) if min_i <= key < max_i: re...
python
def key_exists_in_list_or_dict(key, lst_or_dct): """True if `lst_or_dct[key]` does not raise an Exception""" if isinstance(lst_or_dct, dict) and key in lst_or_dct: return True elif isinstance(lst_or_dct, list): min_i, max_i = 0, len(lst_or_dct) if min_i <= key < max_i: re...
True if `lst_or_dct[key]` does not raise an Exception
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L139-L147
rndusr/torf
torf/_utils.py
assert_type
def assert_type(lst_or_dct, keys, exp_types, must_exist=True, check=None): """ Raise MetainfoError is not of a particular type lst_or_dct: list or dict instance keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a value exp_types: Sequence of types that the value s...
python
def assert_type(lst_or_dct, keys, exp_types, must_exist=True, check=None): """ Raise MetainfoError is not of a particular type lst_or_dct: list or dict instance keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a value exp_types: Sequence of types that the value s...
Raise MetainfoError is not of a particular type lst_or_dct: list or dict instance keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a value exp_types: Sequence of types that the value specified by `keys` must be an instance of must_exist: Whether to rai...
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L149-L188
reincubate/ricloud
ricloud/utils.py
error_message_and_exit
def error_message_and_exit(message, error_result): """Prints error messages in blue, the failed task result and quits.""" if message: error_message(message) puts(json.dumps(error_result, indent=2)) sys.exit(1)
python
def error_message_and_exit(message, error_result): """Prints error messages in blue, the failed task result and quits.""" if message: error_message(message) puts(json.dumps(error_result, indent=2)) sys.exit(1)
Prints error messages in blue, the failed task result and quits.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L82-L87
reincubate/ricloud
ricloud/utils.py
print_prompt_values
def print_prompt_values(values, message=None, sub_attr=None): """Prints prompt title and choices with a bit of formatting.""" if message: prompt_message(message) for index, entry in enumerate(values): if sub_attr: line = '{:2d}: {}'.format(index, getattr(utf8(entry), sub_attr)) ...
python
def print_prompt_values(values, message=None, sub_attr=None): """Prints prompt title and choices with a bit of formatting.""" if message: prompt_message(message) for index, entry in enumerate(values): if sub_attr: line = '{:2d}: {}'.format(index, getattr(utf8(entry), sub_attr)) ...
Prints prompt title and choices with a bit of formatting.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L90-L102
reincubate/ricloud
ricloud/utils.py
prompt_for_input
def prompt_for_input(message, input_type=None): """Prints prompt instruction and does basic input parsing.""" while True: output = prompt.query(message) if input_type: try: output = input_type(output) except ValueError: error_message('Inva...
python
def prompt_for_input(message, input_type=None): """Prints prompt instruction and does basic input parsing.""" while True: output = prompt.query(message) if input_type: try: output = input_type(output) except ValueError: error_message('Inva...
Prints prompt instruction and does basic input parsing.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L105-L119
reincubate/ricloud
ricloud/utils.py
prompt_for_choice
def prompt_for_choice(values, message, input_type=int, output_type=None): """Prints prompt with a list of choices to choose from.""" output = None while not output: index = prompt_for_input(message, input_type=input_type) try: output = utf8(values[index]) except IndexErr...
python
def prompt_for_choice(values, message, input_type=int, output_type=None): """Prints prompt with a list of choices to choose from.""" output = None while not output: index = prompt_for_input(message, input_type=input_type) try: output = utf8(values[index]) except IndexErr...
Prints prompt with a list of choices to choose from.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L122-L137
reincubate/ricloud
ricloud/object_store.py
ObjectStore._retrieve_result
def _retrieve_result(endpoints, token_header): """Prepare the request list and execute them concurrently.""" request_list = [ (url, token_header) for (task_id, url) in endpoints ] responses = concurrent_get(request_list) # Quick sanity check asse...
python
def _retrieve_result(endpoints, token_header): """Prepare the request list and execute them concurrently.""" request_list = [ (url, token_header) for (task_id, url) in endpoints ] responses = concurrent_get(request_list) # Quick sanity check asse...
Prepare the request list and execute them concurrently.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/object_store.py#L62-L78
reincubate/ricloud
ricloud/asmaster_api.py
AsmasterApi._build_endpoint
def _build_endpoint(self, endpoint_name): """Generate an enpoint url from a setting name. Args: endpoint_name(str): setting name for the enpoint to build Returns: (str) url enpoint """ endpoint_relative = settings.get('asmaster_endpoints', endpoint_name)...
python
def _build_endpoint(self, endpoint_name): """Generate an enpoint url from a setting name. Args: endpoint_name(str): setting name for the enpoint to build Returns: (str) url enpoint """ endpoint_relative = settings.get('asmaster_endpoints', endpoint_name)...
Generate an enpoint url from a setting name. Args: endpoint_name(str): setting name for the enpoint to build Returns: (str) url enpoint
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L33-L43
reincubate/ricloud
ricloud/asmaster_api.py
AsmasterApi._set_allowed_services_and_actions
def _set_allowed_services_and_actions(self, services): """Expect services to be a list of service dictionaries, each with `name` and `actions` keys.""" for service in services: self.services[service['name']] = {} for action in service['actions']: name = action.po...
python
def _set_allowed_services_and_actions(self, services): """Expect services to be a list of service dictionaries, each with `name` and `actions` keys.""" for service in services: self.services[service['name']] = {} for action in service['actions']: name = action.po...
Expect services to be a list of service dictionaries, each with `name` and `actions` keys.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L59-L66
reincubate/ricloud
ricloud/asmaster_api.py
AsmasterApi.list_subscriptions
def list_subscriptions(self, service): """Asks for a list of all subscribed accounts and devices, along with their statuses.""" data = { 'service': service, } return self._perform_post_request(self.list_subscriptions_endpoint, data, self.token_header)
python
def list_subscriptions(self, service): """Asks for a list of all subscribed accounts and devices, along with their statuses.""" data = { 'service': service, } return self._perform_post_request(self.list_subscriptions_endpoint, data, self.token_header)
Asks for a list of all subscribed accounts and devices, along with their statuses.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L84-L89
reincubate/ricloud
ricloud/asmaster_api.py
AsmasterApi.subscribe_account
def subscribe_account(self, username, password, service): """Subscribe an account for a service. """ data = { 'service': service, 'username': username, 'password': password, } return self._perform_post_request(self.subscribe_account_endpoint, ...
python
def subscribe_account(self, username, password, service): """Subscribe an account for a service. """ data = { 'service': service, 'username': username, 'password': password, } return self._perform_post_request(self.subscribe_account_endpoint, ...
Subscribe an account for a service.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L91-L100
reincubate/ricloud
ricloud/asmaster_api.py
AsmasterApi.reset_subscription_since
def reset_subscription_since(self, account_id, datetime_str): """Handler for `--reset-subscription-since` command. Args: account_id(int): id of the account to reset. datetime_str(str): string representing the datetime used in the next poll to retrieve data since....
python
def reset_subscription_since(self, account_id, datetime_str): """Handler for `--reset-subscription-since` command. Args: account_id(int): id of the account to reset. datetime_str(str): string representing the datetime used in the next poll to retrieve data since....
Handler for `--reset-subscription-since` command. Args: account_id(int): id of the account to reset. datetime_str(str): string representing the datetime used in the next poll to retrieve data since. Returns: (str) json encoded response. NOTE...
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L154-L173
reincubate/ricloud
ricloud/asmaster_api.py
AsmasterApi._parse_response
def _parse_response(response, post_request=False): """Treat the response from ASApi. The json is dumped before checking the status as even if the response is not properly formed we are in trouble. """ try: data = response.json() except: msg = 'Unh...
python
def _parse_response(response, post_request=False): """Treat the response from ASApi. The json is dumped before checking the status as even if the response is not properly formed we are in trouble. """ try: data = response.json() except: msg = 'Unh...
Treat the response from ASApi. The json is dumped before checking the status as even if the response is not properly formed we are in trouble.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L176-L196
reincubate/ricloud
ricloud/asmaster_listener.py
AsmasterDownloadFileHandler.file_id_to_file_name
def file_id_to_file_name(file_id): """Sometimes file ids are not the file names on the device, but are instead generated by the API. These are not guaranteed to be valid file names so need hashing. """ if len(file_id) == 40 and re.match("^[a-f0-9]+$", file_id): return file_id...
python
def file_id_to_file_name(file_id): """Sometimes file ids are not the file names on the device, but are instead generated by the API. These are not guaranteed to be valid file names so need hashing. """ if len(file_id) == 40 and re.match("^[a-f0-9]+$", file_id): return file_id...
Sometimes file ids are not the file names on the device, but are instead generated by the API. These are not guaranteed to be valid file names so need hashing.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_listener.py#L216-L223
reincubate/ricloud
ricloud/clients/base.py
sync
def sync(func): """Decorator to make a task synchronous.""" sync_timeout = 3600 # Match standard synchronous timeout. def wraps(*args, **kwargs): task = func(*args, **kwargs) task.wait_for_result(timeout=sync_timeout) result = json.loads(task.result) return result retu...
python
def sync(func): """Decorator to make a task synchronous.""" sync_timeout = 3600 # Match standard synchronous timeout. def wraps(*args, **kwargs): task = func(*args, **kwargs) task.wait_for_result(timeout=sync_timeout) result = json.loads(task.result) return result retu...
Decorator to make a task synchronous.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/clients/base.py#L4-L14
reincubate/ricloud
ricloud/samples/live_sample.py
SampleLiveICloudApplication.fetch_data
def fetch_data(self): """Prompt for a data type choice and execute the `fetch_data` task. The results are saved to a file in json format. """ choices = self.available_data choices.insert(0, 'All') selected_data_type = utils.select_item( choices, '...
python
def fetch_data(self): """Prompt for a data type choice and execute the `fetch_data` task. The results are saved to a file in json format. """ choices = self.available_data choices.insert(0, 'All') selected_data_type = utils.select_item( choices, '...
Prompt for a data type choice and execute the `fetch_data` task. The results are saved to a file in json format.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/live_sample.py#L22-L58
reincubate/ricloud
ricloud/samples/icloud_sample.py
SampleICloudApplication.log_in
def log_in(self): """Perform the `log_in` task to setup the API session for future data requests.""" if not self.password: # Password wasn't give, ask for it now self.password = getpass.getpass('Password: ') utils.pending_message('Performing login...') login_res...
python
def log_in(self): """Perform the `log_in` task to setup the API session for future data requests.""" if not self.password: # Password wasn't give, ask for it now self.password = getpass.getpass('Password: ') utils.pending_message('Performing login...') login_res...
Perform the `log_in` task to setup the API session for future data requests.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/icloud_sample.py#L43-L59
reincubate/ricloud
ricloud/samples/icloud_sample.py
SampleICloudApplication.handle_failed_login
def handle_failed_login(self, login_result): """If Two Factor Authentication (2FA/2SV) is enabled, the initial login will fail with a predictable error. Catching this error allows us to begin the authentication process. Other types of errors can be treated in a similar way. """ ...
python
def handle_failed_login(self, login_result): """If Two Factor Authentication (2FA/2SV) is enabled, the initial login will fail with a predictable error. Catching this error allows us to begin the authentication process. Other types of errors can be treated in a similar way. """ ...
If Two Factor Authentication (2FA/2SV) is enabled, the initial login will fail with a predictable error. Catching this error allows us to begin the authentication process. Other types of errors can be treated in a similar way.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/icloud_sample.py#L61-L74
reincubate/ricloud
ricloud/samples/icloud_sample.py
SampleICloudApplication.get_devices
def get_devices(self): """Execute the `get_devices` task and store the results in `self.devices`.""" utils.pending_message('Fetching device list...') get_devices_task = self.client.devices( account=self.account ) # We wait for device list info as this sample relies ...
python
def get_devices(self): """Execute the `get_devices` task and store the results in `self.devices`.""" utils.pending_message('Fetching device list...') get_devices_task = self.client.devices( account=self.account ) # We wait for device list info as this sample relies ...
Execute the `get_devices` task and store the results in `self.devices`.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/icloud_sample.py#L113-L127
reincubate/ricloud
ricloud/samples/icloud_sample.py
SampleICloudApplication.download_files
def download_files(self, files): """This method uses the `download_file` task to retrieve binary files such as attachments, images and videos. Notice that this method does not wait for the tasks it creates to return a result synchronously. """ utils.pending_message( ...
python
def download_files(self, files): """This method uses the `download_file` task to retrieve binary files such as attachments, images and videos. Notice that this method does not wait for the tasks it creates to return a result synchronously. """ utils.pending_message( ...
This method uses the `download_file` task to retrieve binary files such as attachments, images and videos. Notice that this method does not wait for the tasks it creates to return a result synchronously.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/icloud_sample.py#L183-L226
reincubate/ricloud
ricloud/api.py
Api.register_account
def register_account(self, username, service): """Register an account against a service. The account that we're querying must be referenced during any future task requests - so we know which account to link the task too. """ data = { 'service': service, ...
python
def register_account(self, username, service): """Register an account against a service. The account that we're querying must be referenced during any future task requests - so we know which account to link the task too. """ data = { 'service': service, ...
Register an account against a service. The account that we're querying must be referenced during any future task requests - so we know which account to link the task too.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L79-L90
reincubate/ricloud
ricloud/api.py
Api.perform_task
def perform_task(self, service, task_name, account, payload, callback=None): """Submit a task to the API. The task is executed asyncronously, and a Task object is returned. """ data = { 'service': service, 'action': task_name, 'account': account, ...
python
def perform_task(self, service, task_name, account, payload, callback=None): """Submit a task to the API. The task is executed asyncronously, and a Task object is returned. """ data = { 'service': service, 'action': task_name, 'account': account, ...
Submit a task to the API. The task is executed asyncronously, and a Task object is returned.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L92-L108
reincubate/ricloud
ricloud/api.py
Api.task_status
def task_status(self, task_id): """Find the status of a task.""" data = { 'task_ids': task_id, } return self._perform_post_request(self.task_status_endpoint, data, self.token_header)
python
def task_status(self, task_id): """Find the status of a task.""" data = { 'task_ids': task_id, } return self._perform_post_request(self.task_status_endpoint, data, self.token_header)
Find the status of a task.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L110-L115
reincubate/ricloud
ricloud/api.py
Api.result_consumed
def result_consumed(self, task_id): """Report the result as successfully consumed.""" logger.debug('Sending result consumed message.') data = { 'task_ids': task_id, } return self._perform_post_request(self.results_consumed_endpoint, data, self.token_header)
python
def result_consumed(self, task_id): """Report the result as successfully consumed.""" logger.debug('Sending result consumed message.') data = { 'task_ids': task_id, } return self._perform_post_request(self.results_consumed_endpoint, data, self.token_header)
Report the result as successfully consumed.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L117-L123
reincubate/ricloud
ricloud/api.py
Api._parse_response
def _parse_response(response, post_request=False): """Treat the response from ASApi. The json is dumped before checking the status as even if the response is not properly formed we are in trouble. TODO: Streamline error checking. """ data = response.json() if n...
python
def _parse_response(response, post_request=False): """Treat the response from ASApi. The json is dumped before checking the status as even if the response is not properly formed we are in trouble. TODO: Streamline error checking. """ data = response.json() if n...
Treat the response from ASApi. The json is dumped before checking the status as even if the response is not properly formed we are in trouble. TODO: Streamline error checking.
https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L152-L168
nitmir/django-cas-server
cas_server/models.py
FederateSLO.clean_deleted_sessions
def clean_deleted_sessions(cls): """remove old :class:`FederateSLO` object for which the session do not exists anymore""" for federate_slo in cls.objects.all(): if not SessionStore(session_key=federate_slo.session_key).get('authenticated'): federate_slo.delete()
python
def clean_deleted_sessions(cls): """remove old :class:`FederateSLO` object for which the session do not exists anymore""" for federate_slo in cls.objects.all(): if not SessionStore(session_key=federate_slo.session_key).get('authenticated'): federate_slo.delete()
remove old :class:`FederateSLO` object for which the session do not exists anymore
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/models.py#L231-L235
nitmir/django-cas-server
cas_server/models.py
NewVersionWarning.send_mails
def send_mails(cls): """ For each new django-cas-server version, if the current instance is not up to date send one mail to ``settings.ADMINS``. """ if settings.CAS_NEW_VERSION_EMAIL_WARNING and settings.ADMINS: try: obj = cls.objects.get() ...
python
def send_mails(cls): """ For each new django-cas-server version, if the current instance is not up to date send one mail to ``settings.ADMINS``. """ if settings.CAS_NEW_VERSION_EMAIL_WARNING and settings.ADMINS: try: obj = cls.objects.get() ...
For each new django-cas-server version, if the current instance is not up to date send one mail to ``settings.ADMINS``.
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/models.py#L1072-L1117
nitmir/django-cas-server
cas_server/cas.py
CASClientBase.get_login_url
def get_login_url(self): """Generates CAS login URL""" params = {'service': self.service_url} if self.renew: params.update({'renew': 'true'}) params.update(self.extra_login_params) url = urllib_parse.urljoin(self.server_url, 'login') query = urllib_parse.urle...
python
def get_login_url(self): """Generates CAS login URL""" params = {'service': self.service_url} if self.renew: params.update({'renew': 'true'}) params.update(self.extra_login_params) url = urllib_parse.urljoin(self.server_url, 'login') query = urllib_parse.urle...
Generates CAS login URL
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/cas.py#L93-L102
nitmir/django-cas-server
cas_server/cas.py
CASClientBase.get_logout_url
def get_logout_url(self, redirect_url=None): """Generates CAS logout URL""" url = urllib_parse.urljoin(self.server_url, 'logout') if redirect_url: params = {self.logout_redirect_param_name: redirect_url} url += '?' + urllib_parse.urlencode(params) return url
python
def get_logout_url(self, redirect_url=None): """Generates CAS logout URL""" url = urllib_parse.urljoin(self.server_url, 'logout') if redirect_url: params = {self.logout_redirect_param_name: redirect_url} url += '?' + urllib_parse.urlencode(params) return url
Generates CAS logout URL
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/cas.py#L104-L110
nitmir/django-cas-server
cas_server/cas.py
CASClientBase.get_proxy_url
def get_proxy_url(self, pgt): """Returns proxy url, given the proxy granting ticket""" params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url}) return "%s/proxy?%s" % (self.server_url, params)
python
def get_proxy_url(self, pgt): """Returns proxy url, given the proxy granting ticket""" params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url}) return "%s/proxy?%s" % (self.server_url, params)
Returns proxy url, given the proxy granting ticket
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/cas.py#L112-L115
nitmir/django-cas-server
cas_server/cas.py
CASClientBase.get_proxy_ticket
def get_proxy_ticket(self, pgt): """Returns proxy ticket given the proxy granting ticket""" response = urllib_request.urlopen(self.get_proxy_url(pgt)) if response.code == 200: from lxml import etree root = etree.fromstring(response.read()) tickets = root.xpath...
python
def get_proxy_ticket(self, pgt): """Returns proxy ticket given the proxy granting ticket""" response = urllib_request.urlopen(self.get_proxy_url(pgt)) if response.code == 200: from lxml import etree root = etree.fromstring(response.read()) tickets = root.xpath...
Returns proxy ticket given the proxy granting ticket
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/cas.py#L117-L135
nitmir/django-cas-server
cas_server/cas.py
CASClientV1.verify_ticket
def verify_ticket(self, ticket): """Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure. """ params = [('ticket', ticket), ('service', self.service_url)] if self.renew: params.append(('renew', 'true')) url = (urllib_parse.u...
python
def verify_ticket(self, ticket): """Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure. """ params = [('ticket', ticket), ('service', self.service_url)] if self.renew: params.append(('renew', 'true')) url = (urllib_parse.u...
Verifies CAS 1.0 authentication ticket. Returns username on success and None on failure.
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/cas.py#L151-L171
nitmir/django-cas-server
cas_server/cas.py
CASClientV2.verify_ticket
def verify_ticket(self, ticket): """Verifies CAS 2.0+/3.0+ XML-based authentication ticket and returns extended attributes""" (response, charset) = self.get_verification_response(ticket) return self.verify_response(response, charset)
python
def verify_ticket(self, ticket): """Verifies CAS 2.0+/3.0+ XML-based authentication ticket and returns extended attributes""" (response, charset) = self.get_verification_response(ticket) return self.verify_response(response, charset)
Verifies CAS 2.0+/3.0+ XML-based authentication ticket and returns extended attributes
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/cas.py#L185-L188
nitmir/django-cas-server
cas_server/cas.py
CASClientWithSAMLV1.get_saml_assertion
def get_saml_assertion(cls, ticket): """ http://www.jasig.org/cas/protocol#samlvalidate-cas-3.0 SAML request values: RequestID [REQUIRED]: unique identifier for the request IssueInstant [REQUIRED]: timestamp of the request samlp:AssertionArtifact...
python
def get_saml_assertion(cls, ticket): """ http://www.jasig.org/cas/protocol#samlvalidate-cas-3.0 SAML request values: RequestID [REQUIRED]: unique identifier for the request IssueInstant [REQUIRED]: timestamp of the request samlp:AssertionArtifact...
http://www.jasig.org/cas/protocol#samlvalidate-cas-3.0 SAML request values: RequestID [REQUIRED]: unique identifier for the request IssueInstant [REQUIRED]: timestamp of the request samlp:AssertionArtifact [REQUIRED]: the valid CAS Service Ticket obt...
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/cas.py#L371-L394
nitmir/django-cas-server
cas_server/auth.py
LdapAuthUser.get_conn
def get_conn(cls): """Return a connection object to the ldap database""" conn = cls._conn if conn is None or conn.closed: conn = ldap3.Connection( settings.CAS_LDAP_SERVER, settings.CAS_LDAP_USER, settings.CAS_LDAP_PASSWORD, ...
python
def get_conn(cls): """Return a connection object to the ldap database""" conn = cls._conn if conn is None or conn.closed: conn = ldap3.Connection( settings.CAS_LDAP_SERVER, settings.CAS_LDAP_USER, settings.CAS_LDAP_PASSWORD, ...
Return a connection object to the ldap database
https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/auth.py#L272-L284