idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
22,800
def wrap ( cls , meth ) : async def inner ( * args , ** kwargs ) : sock = await meth ( * args , ** kwargs ) return cls ( sock ) return inner
Wraps a connection opening method in this class .
22,801
async def set ( self , * args , ** kwargs ) : return await _maybe_await ( self . event . set ( * args , ** kwargs ) )
Sets the value of the event .
22,802
def register ( self , library : str , cbl : Callable [ [ '_AsyncLib' ] , None ] ) : self . _handlers [ library ] = cbl
Registers a callable to set up a library .
22,803
async def trio_open_connection ( host , port , * , ssl = False , ** kwargs ) : import trio if not ssl : sock = await trio . open_tcp_stream ( host , port ) else : if isinstance ( ssl , bool ) : ssl_context = None else : ssl_context = ssl sock = await trio . open_ssl_over_tcp_stream ( host , port , ssl_context = ssl_con...
Allows connections to be made that may or may not require ssl . Somewhat surprisingly trio doesn t have an abstraction for this like curio even though it s fairly trivial to write . Down the line hopefully .
22,804
def agent ( state , host , server = None , port = None ) : args = [ ] if server : args . append ( '--server=%s' % server ) if port : args . append ( '--masterport=%s' % port ) yield 'puppet agent -t %s' % ' ' . join ( args )
Run puppet agent
22,805
def load_config ( deploy_dir ) : config = Config ( ) config_filename = path . join ( deploy_dir , 'config.py' ) if path . exists ( config_filename ) : extract_file_config ( config_filename , config ) exec_file ( config_filename ) return config
Loads any local config . py file .
22,806
def load_deploy_config ( deploy_filename , config = None ) : if not config : config = Config ( ) if not deploy_filename : return if path . exists ( deploy_filename ) : extract_file_config ( deploy_filename , config ) return config
Loads any local config overrides in the deploy file .
22,807
def parse_iptables_rule ( line ) : bits = line . split ( ) definition = { } key = None args = [ ] not_arg = False def add_args ( ) : arg_string = ' ' . join ( args ) if key in IPTABLES_ARGS : definition_key = ( 'not_{0}' . format ( IPTABLES_ARGS [ key ] ) if not_arg else IPTABLES_ARGS [ key ] ) definition [ definition_...
Parse one iptables rule . Returns a dict where each iptables code argument is mapped to a name using IPTABLES_ARGS .
22,808
def add_op ( state , op_func , * args , ** kwargs ) : frameinfo = get_caller_frameinfo ( ) kwargs [ 'frameinfo' ] = frameinfo for host in state . inventory : op_func ( state , host , * args , ** kwargs )
Prepare & add an operation to pyinfra . state by executing it on all hosts .
22,809
def add_deploy ( state , deploy_func , * args , ** kwargs ) : frameinfo = get_caller_frameinfo ( ) kwargs [ 'frameinfo' ] = frameinfo for host in state . inventory : deploy_func ( state , host , * args , ** kwargs )
Prepare & add an deploy to pyinfra . state by executing it on all hosts .
22,810
def setup_arguments ( arguments ) : for key in ( '--parallel' , '--port' , '--fail-percent' ) : if arguments [ key ] : try : arguments [ key ] = int ( arguments [ key ] ) except ValueError : raise CliError ( '{0} is not a valid integer for {1}' . format ( arguments [ key ] , key , ) ) if arguments [ '--run' ] : op , ar...
Prepares argumnents output by docopt .
22,811
def sql ( state , host , sql , database = None , mysql_user = None , mysql_password = None , mysql_host = None , mysql_port = None , ) : yield make_execute_mysql_command ( sql , database = database , user = mysql_user , password = mysql_password , host = mysql_host , port = mysql_port , )
Execute arbitrary SQL against MySQL .
22,812
def dump ( state , host , remote_filename , database = None , mysql_user = None , mysql_password = None , mysql_host = None , mysql_port = None , ) : yield '{0} > {1}' . format ( make_mysql_command ( executable = 'mysqldump' , database = database , user = mysql_user , password = mysql_password , host = mysql_host , por...
Dump a MySQL database into a . sql file . Requires mysqldump .
22,813
def get_host ( self , name , default = NoHostError ) : if name in self . hosts : return self . hosts [ name ] if default is NoHostError : raise NoHostError ( 'No such host: {0}' . format ( name ) ) return default
Get a single host by name .
22,814
def get_group ( self , name , default = NoGroupError ) : if name in self . groups : return self . groups [ name ] if default is NoGroupError : raise NoGroupError ( 'No such group: {0}' . format ( name ) ) return default
Get a list of hosts belonging to a group .
22,815
def get_groups_data ( self , groups ) : data = { } for group in groups : data . update ( self . get_group_data ( group ) ) return data
Gets aggregated data from a list of groups . Vars are collected in order so for any groups which define the same var twice the last group s value will hold .
22,816
def get_deploy_data ( self ) : if self . state and self . state . deploy_data : return self . state . deploy_data return { }
Gets any default data attached to the current deploy if any .
22,817
def config ( state , host , key , value , repo = None , ) : existing_config = host . fact . git_config ( repo ) if key not in existing_config or existing_config [ key ] != value : if repo is None : yield 'git config --global {0} "{1}"' . format ( key , value ) else : yield 'cd {0} && git config --local {1} "{2}"' . for...
Manage git config for a repository or globally .
22,818
def include ( filename , hosts = False , when = True ) : if not pyinfra . is_cli : raise PyinfraError ( 'local.include is only available in CLI mode.' ) if not when : return if hosts is not False : hosts = ensure_host_list ( hosts , inventory = pseudo_state . inventory ) if pseudo_host not in hosts : return if pseudo_s...
Executes a local python file within the pyinfra . pseudo_state . deploy_dir directory .
22,819
def send ( self , request , stem = None ) : if stem is not None : request . url = request . url + "/" + stem . lstrip ( "/" ) prepped = self . session . prepare_request ( request ) settings = self . session . merge_environment_settings ( url = prepped . url , proxies = { } , stream = None , verify = None , cert = None ...
Prepare and send a request
22,820
def list ( self ) : request = requests . Request ( 'GET' , 'https://api.github.com/gists' , headers = { 'Accept-Encoding' : 'identity, deflate, compress, gzip' , 'User-Agent' : 'python-requests/1.2.0' , 'Accept' : 'application/vnd.github.v3.base64' , } , params = { 'access_token' : self . token , 'per_page' : 100 , } ,...
Returns a list of the users gists as GistInfo objects
22,821
def create ( self , request , desc , files , public = False ) : request . data = json . dumps ( { "description" : desc , "public" : public , "files" : files , } ) return self . send ( request ) . json ( ) [ 'html_url' ]
Creates a gist
22,822
def files ( self , request , id ) : gist = self . send ( request , id ) . json ( ) return gist [ 'files' ]
Returns a list of files in the gist
22,823
def content ( self , request , id ) : gist = self . send ( request , id ) . json ( ) def convert ( data ) : return base64 . b64decode ( data ) . decode ( 'utf-8' ) content = { } for name , data in gist [ 'files' ] . items ( ) : content [ name ] = convert ( data [ 'content' ] ) return content
Returns the content of the gist
22,824
def archive ( self , request , id ) : gist = self . send ( request , id ) . json ( ) with tarfile . open ( '{}.tar.gz' . format ( id ) , mode = 'w:gz' ) as archive : for name , data in gist [ 'files' ] . items ( ) : with tempfile . NamedTemporaryFile ( 'w+' ) as fp : fp . write ( data [ 'content' ] ) fp . flush ( ) arc...
Create an archive of a gist
22,825
def edit ( self , request , id ) : with pushd ( tempfile . gettempdir ( ) ) : try : self . clone ( id ) with pushd ( id ) : files = [ f for f in os . listdir ( '.' ) if os . path . isfile ( f ) ] quoted = [ '"{}"' . format ( f ) for f in files ] os . system ( "{} {}" . format ( self . editor , ' ' . join ( quoted ) ) )...
Edit a gist
22,826
def description ( self , request , id , description ) : request . data = json . dumps ( { "description" : description } ) return self . send ( request , id ) . json ( ) [ 'html_url' ]
Updates the description of a gist
22,827
def clone ( self , id , name = None ) : url = 'git@gist.github.com:/{}' . format ( id ) if name is None : os . system ( 'git clone {}' . format ( url ) ) else : os . system ( 'git clone {} {}' . format ( url , name ) )
Clone a gist
22,828
def command ( state , host , hostname , command , ssh_user = None ) : connection_target = hostname if ssh_user : connection_target = '@' . join ( ( ssh_user , hostname ) ) yield 'ssh {0} "{1}"' . format ( connection_target , command )
Execute commands on other servers over SSH .
22,829
def upload ( state , host , hostname , filename , remote_filename = None , use_remote_sudo = False , ssh_keyscan = False , ssh_user = None , ) : remote_filename = remote_filename or filename connection_target = hostname if ssh_user : connection_target = '@' . join ( ( ssh_user , hostname ) ) if ssh_keyscan : yield keys...
Upload files to other servers using scp .
22,830
def download ( state , host , hostname , filename , local_filename = None , force = False , ssh_keyscan = False , ssh_user = None , ) : local_filename = local_filename or filename local_file_info = host . fact . file ( local_filename ) if local_file_info is False : raise OperationError ( 'Local destination {0} already ...
Download files from other servers using scp .
22,831
def pop_op_kwargs ( state , kwargs ) : meta_kwargs = state . deploy_kwargs or { } def get_kwarg ( key , default = None ) : return kwargs . pop ( key , meta_kwargs . get ( key , default ) ) env = state . config . ENV . copy ( ) env . update ( get_kwarg ( 'env' , { } ) ) hosts = get_kwarg ( 'hosts' ) hosts = ensure_host_...
Pop and return operation global keyword arguments .
22,832
def get_template ( filename_or_string , is_string = False ) : cache_key = sha1_hash ( filename_or_string ) if is_string else filename_or_string if cache_key in TEMPLATES : return TEMPLATES [ cache_key ] if is_string : template_string = filename_or_string else : with open ( filename_or_string , 'r' ) as file_io : templa...
Gets a jinja2 Template object for the input filename or string with caching based on the filename of the template or the SHA1 of the input string .
22,833
def underscore ( name ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
Transform CamelCase - > snake_case .
22,834
def sha1_hash ( string ) : hasher = sha1 ( ) hasher . update ( string . encode ( ) ) return hasher . hexdigest ( )
Return the SHA1 of the input string .
22,835
def make_command ( command , env = None , su_user = None , sudo = False , sudo_user = None , preserve_sudo_env = False , ) : debug_meta = { } for key , value in ( ( 'sudo' , sudo ) , ( 'sudo_user' , sudo_user ) , ( 'su_user' , su_user ) , ( 'env' , env ) , ) : if value : debug_meta [ key ] = value logger . debug ( 'Bui...
Builds a shell command with various kwargs .
22,836
def make_hash ( obj ) : if isinstance ( obj , ( set , tuple , list ) ) : hash_string = '' . join ( [ make_hash ( e ) for e in obj ] ) elif isinstance ( obj , dict ) : hash_string = '' . join ( '' . join ( ( key , make_hash ( value ) ) ) for key , value in six . iteritems ( obj ) ) else : hash_string = ( '_PYINFRA_CONST...
Make a hash from an arbitrary nested dictionary list tuple or set used to generate ID s for operations based on their name & arguments .
22,837
def get_file_sha1 ( filename_or_io ) : file_data = get_file_io ( filename_or_io ) cache_key = file_data . cache_key if cache_key and cache_key in FILE_SHAS : return FILE_SHAS [ cache_key ] with file_data as file_io : hasher = sha1 ( ) buff = file_io . read ( BLOCKSIZE ) while len ( buff ) > 0 : if isinstance ( buff , s...
Calculates the SHA1 of a file or file object using a buffer to handle larger files .
22,838
def read_buffer ( io , print_output = False , print_func = None ) : def _print ( line ) : if print_output : if print_func : formatted_line = print_func ( line ) else : formatted_line = line encoded_line = unicode ( formatted_line ) . encode ( 'utf-8' ) print ( encoded_line ) out = [ ] for line in io : if not isinstance...
Reads a file - like buffer object into lines and optionally prints the output .
22,839
def start ( state , host , ctid , force = False ) : args = [ '{0}' . format ( ctid ) ] if force : args . append ( '--force' ) yield 'vzctl start {0}' . format ( ' ' . join ( args ) )
Start OpenVZ containers .
22,840
def stop ( state , host , ctid ) : args = [ '{0}' . format ( ctid ) ] yield 'vzctl stop {0}' . format ( ' ' . join ( args ) )
Stop OpenVZ containers .
22,841
def restart ( state , host , ctid , force = False ) : yield stop ( state , host , ctid ) yield start ( state , host , ctid , force = force )
Restart OpenVZ containers .
22,842
def create ( state , host , ctid , template = None ) : current_containers = host . fact . openvz_containers if ctid in current_containers : raise OperationError ( 'An OpenVZ container with CTID {0} already exists' . format ( ctid ) , ) args = [ '{0}' . format ( ctid ) ] if template : args . append ( '--ostemplate {0}' ...
Create OpenVZ containers .
22,843
def set ( state , host , ctid , save = True , ** settings ) : args = [ '{0}' . format ( ctid ) ] if save : args . append ( '--save' ) for key , value in six . iteritems ( settings ) : if isinstance ( value , list ) : args . extend ( '--{0} {1}' . format ( key , v ) for v in value ) else : args . append ( '--{0} {1}' . ...
Set OpenVZ container details .
22,844
def exec_file ( filename , return_locals = False , is_deploy_code = False ) : if filename not in PYTHON_CODES : with open ( filename , 'r' ) as f : code = f . read ( ) code = compile ( code , filename , 'exec' ) PYTHON_CODES [ filename ] = code data = { '__file__' : filename , 'state' : pseudo_state , } exec ( PYTHON_C...
Execute a Python file and optionally return it s attributes as a dict .
22,845
def shell ( state , host , commands , chdir = None ) : if isinstance ( commands , six . string_types ) : commands = [ commands ] for command in commands : if chdir : yield 'cd {0} && ({1})' . format ( chdir , command ) else : yield command
Run raw shell code .
22,846
def script ( state , host , filename , chdir = None ) : temp_file = state . get_temp_filename ( filename ) yield files . put ( state , host , filename , temp_file ) yield chmod ( temp_file , '+x' ) if chdir : yield 'cd {0} && {1}' . format ( chdir , temp_file ) else : yield temp_file
Upload and execute a local script on the remote host .
22,847
def script_template ( state , host , template_filename , chdir = None , ** data ) : temp_file = state . get_temp_filename ( template_filename ) yield files . template ( state , host , template_filename , temp_file , ** data ) yield chmod ( temp_file , '+x' ) if chdir : yield 'cd {0} && {1}' . format ( chdir , temp_file...
Generate upload and execute a local script template on the remote host .
22,848
def hostname ( state , host , hostname , hostname_file = None ) : if hostname_file is None : os = host . fact . os if os == 'Linux' : hostname_file = '/etc/hostname' elif os == 'OpenBSD' : hostname_file = '/etc/myname' current_hostname = host . fact . hostname if current_hostname != hostname : yield 'hostname {0}' . fo...
Set the system hostname .
22,849
def sysctl ( state , host , name , value , persist = False , persist_file = '/etc/sysctl.conf' , ) : string_value = ( ' ' . join ( value ) if isinstance ( value , list ) else value ) existing_value = host . fact . sysctl . get ( name ) if not existing_value or existing_value != value : yield 'sysctl {0}={1}' . format (...
Edit sysctl configuration .
22,850
def download ( state , host , source_url , destination , user = None , group = None , mode = None , cache_time = None , force = False , ) : info = host . fact . file ( destination ) if info is False : raise OperationError ( 'Destination {0} already exists and is not a file' . format ( destination ) , ) download = force...
Download files from remote locations .
22,851
def replace ( state , host , name , match , replace , flags = None ) : yield sed_replace ( name , match , replace , flags = flags )
A simple shortcut for replacing text in files with sed .
22,852
def sync ( state , host , source , destination , user = None , group = None , mode = None , delete = False , exclude = None , exclude_dir = None , add_deploy_dir = True , ) : if not source . endswith ( path . sep ) : source = '{0}{1}' . format ( source , path . sep ) if add_deploy_dir and state . deploy_dir : source = ...
Syncs a local directory with a remote one with delete support . Note that delete will remove extra files on the remote side but not extra directories .
22,853
def put ( state , host , local_filename , remote_filename , user = None , group = None , mode = None , add_deploy_dir = True , ) : if hasattr ( local_filename , 'read' ) : local_file = local_filename else : if add_deploy_dir and state . deploy_dir : local_filename = path . join ( state . deploy_dir , local_filename ) l...
Copy a local file to the remote system .
22,854
def template ( state , host , template_filename , remote_filename , user = None , group = None , mode = None , ** data ) : if state . deploy_dir : template_filename = path . join ( state . deploy_dir , template_filename ) data [ 'host' ] = host data [ 'inventory' ] = state . inventory try : output = get_template ( temp...
Generate a template and write it to the remote system .
22,855
def sql ( state , host , sql , database = None , postgresql_user = None , postgresql_password = None , postgresql_host = None , postgresql_port = None , ) : yield make_execute_psql_command ( sql , database = database , user = postgresql_user , password = postgresql_password , host = postgresql_host , port = postgresql_...
Execute arbitrary SQL against PostgreSQL .
22,856
def dump ( state , host , remote_filename , database = None , postgresql_user = None , postgresql_password = None , postgresql_host = None , postgresql_port = None , ) : yield '{0} > {1}' . format ( make_psql_command ( executable = 'pg_dump' , database = database , user = postgresql_user , password = postgresql_passwor...
Dump a PostgreSQL database into a . sql file . Requires mysqldump .
22,857
def get_fact ( state , host , name ) : if callable ( getattr ( FACTS [ name ] , 'command' , None ) ) : def wrapper ( * args ) : fact_data = get_facts ( state , name , args = args , ensure_hosts = ( host , ) ) return fact_data . get ( host ) return wrapper else : fact_data = get_facts ( state , name , ensure_hosts = ( h...
Wrapper around get_facts returning facts for one host or a function that does .
22,858
def key ( state , host , key = None , keyserver = None , keyid = None ) : if key : if urlparse ( key ) . scheme : yield 'wget -O- {0} | apt-key add -' . format ( key ) else : yield 'apt-key add {0}' . format ( key ) if keyserver and keyid : yield 'apt-key adv --keyserver {0} --recv-keys {1}' . format ( keyserver , keyi...
Add apt gpg keys with apt - key .
22,859
def update ( state , host , cache_time = None , touch_periodic = False ) : if cache_time : cache_info = host . fact . file ( APT_UPDATE_FILENAME ) host_cache_time = host . fact . date . replace ( tzinfo = None ) - timedelta ( seconds = cache_time ) if cache_info and cache_info [ 'mtime' ] and cache_info [ 'mtime' ] > h...
Updates apt repos .
22,860
def run_shell_command ( state , host , command , get_pty = False , timeout = None , print_output = False , ** command_kwargs ) : command = make_command ( command , ** command_kwargs ) logger . debug ( ' . format ( command ) ) if print_output : print ( '{0}>>> {1}' . format ( host . print_prefix , command ) ) process = ...
Execute a command on the local machine .
22,861
def upstart ( state , host , name , running = True , restarted = False , reloaded = False , command = None , enabled = None , ) : yield _handle_service_control ( name , host . fact . upstart_status , 'initctl {1} {0}' , running , restarted , reloaded , command , ) if enabled is True : yield files . file ( state , host ...
Manage the state of upstart managed services .
22,862
def service ( state , host , * args , ** kwargs ) : if host . fact . which ( 'systemctl' ) : yield systemd ( state , host , * args , ** kwargs ) return if host . fact . which ( 'initctl' ) : yield upstart ( state , host , * args , ** kwargs ) return if host . fact . directory ( '/etc/init.d' ) : yield d ( state , host ...
Manage the state of services . This command checks for the presence of all the init systems pyinfra can handle and executes the relevant operation . See init system sepcific operation for arguments .
22,863
def connect ( state , host , for_fact = None ) : kwargs = _make_paramiko_kwargs ( state , host ) logger . debug ( 'Connecting to: {0} ({1})' . format ( host . name , kwargs ) ) hostname = kwargs . pop ( 'hostname' , host . data . ssh_hostname or host . name , ) try : client = SSHClient ( ) client . set_missing_host_key...
Connect to a single host . Returns the SSH client if succesful . Stateless by design so can be run in parallel .
22,864
def run_shell_command ( state , host , command , get_pty = False , timeout = None , print_output = False , ** command_kwargs ) : command = make_command ( command , ** command_kwargs ) logger . debug ( 'Running command on {0}: (pty={1}) {2}' . format ( host . name , get_pty , command , ) ) if print_output : print ( '{0}...
Execute a command on the specified host .
22,865
def put_file ( state , host , filename_or_io , remote_filename , sudo = False , sudo_user = None , su_user = None , print_output = False , ) : if sudo or su_user : temp_file = state . get_temp_filename ( remote_filename ) _put_file ( host , filename_or_io , temp_file ) if print_output : print ( '{0}file uploaded: {1}' ...
Upload file - ios to the specified host using SFTP . Supports uploading files with sudo by uploading to a temporary directory then moving & chowning .
22,866
def deploy ( self , name , kwargs , data , line_number , in_deploy = True ) : if self . deploy_name : name = _make_name ( self . deploy_name , name ) old_in_deploy = self . in_deploy old_deploy_name = self . deploy_name old_deploy_kwargs = self . deploy_kwargs old_deploy_data = self . deploy_data old_deploy_line_number...
Wraps a group of operations as a deploy this should not be used directly instead use pyinfra . api . deploy . deploy .
22,867
def activate_host ( self , host ) : logger . debug ( 'Activating host: {0}' . format ( host ) ) self . activated_hosts . add ( host ) self . active_hosts . add ( host )
Flag a host as active .
22,868
def fail_hosts ( self , hosts_to_fail , activated_count = None ) : if not hosts_to_fail : return activated_count = activated_count or len ( self . activated_hosts ) logger . debug ( 'Failing hosts: {0}' . format ( ', ' . join ( ( host . name for host in hosts_to_fail ) , ) ) ) self . active_hosts -= hosts_to_fail activ...
Flag a set of hosts as failed error for config . FAIL_PERCENT .
22,869
def is_host_in_limit ( self , host ) : limit_hosts = self . limit_hosts if not isinstance ( limit_hosts , list ) : return True return host in limit_hosts
Returns a boolean indicating if the host is within the current state limit .
22,870
def get_temp_filename ( self , hash_key = None ) : if not hash_key : hash_key = six . text_type ( uuid4 ( ) ) temp_filename = '{0}/{1}' . format ( self . config . TEMP_DIR , sha1_hash ( hash_key ) , ) return temp_filename
Generate a temporary filename for this deploy .
22,871
def _run_server_ops ( state , host , progress = None ) : logger . debug ( 'Running all ops on {0}' . format ( host ) ) for op_hash in state . get_op_order ( ) : op_meta = state . op_meta [ op_hash ] logger . info ( ' . format ( click . style ( ' , 'blue' ) , click . style ( ', ' . join ( op_meta [ 'names' ] ) , bold = ...
Run all ops for a single server .
22,872
def _run_serial_ops ( state ) : for host in list ( state . inventory ) : host_operations = product ( [ host ] , state . get_op_order ( ) ) with progress_spinner ( host_operations ) as progress : try : _run_server_ops ( state , host , progress = progress , ) except PyinfraError : state . fail_hosts ( { host } )
Run all ops for all servers one server at a time .
22,873
def _run_no_wait_ops ( state ) : hosts_operations = product ( state . inventory , state . get_op_order ( ) ) with progress_spinner ( hosts_operations ) as progress : greenlets = [ state . pool . spawn ( _run_server_ops , state , host , progress = progress , ) for host in state . inventory ] gevent . joinall ( greenlets...
Run all ops for all servers at once .
22,874
def _run_single_op ( state , op_hash ) : op_meta = state . op_meta [ op_hash ] op_types = [ ] if op_meta [ 'serial' ] : op_types . append ( 'serial' ) if op_meta [ 'run_once' ] : op_types . append ( 'run once' ) logger . info ( '{0} {1} {2}' . format ( click . style ( ' . format ( ' {0} ' . format ( ', ' . join ( op_ty...
Run a single operation for all servers . Can be configured to run in serial .
22,875
def run_ops ( state , serial = False , no_wait = False ) : state . deploying = True if serial : _run_serial_ops ( state ) elif no_wait : _run_no_wait_ops ( state ) for op_hash in state . get_op_order ( ) : _run_single_op ( state , op_hash )
Runs all operations across all servers in a configurable manner .
22,876
def serve ( service_brokers : Union [ List [ ServiceBroker ] , ServiceBroker ] , credentials : Union [ List [ BrokerCredentials ] , BrokerCredentials , None ] , logger : logging . Logger = logging . root , port = 5000 , debug = False ) : from gevent . pywsgi import WSGIServer from flask import Flask app = Flask ( __nam...
Starts flask with the given brokers . You can provide a list or just one ServiceBroker
22,877
def multi_ping ( dest_addrs , timeout , retry = 0 , ignore_lookup_errors = False ) : retry = int ( retry ) if retry < 0 : retry = 0 timeout = float ( timeout ) if timeout < 0.1 : raise MultiPingError ( "Timeout < 0.1 seconds not allowed" ) retry_timeout = float ( timeout ) / ( retry + 1 ) if retry_timeout < 0.1 : raise...
Combine send and receive measurement into single function .
22,878
def _checksum ( self , msg ) : def carry_around_add ( a , b ) : c = a + b return ( c & 0xffff ) + ( c >> 16 ) s = 0 for i in range ( 0 , len ( msg ) , 2 ) : w = ( msg [ i ] << 8 ) + msg [ i + 1 ] s = carry_around_add ( s , w ) s = ~ s & 0xffff return s
Calculate the checksum of a packet .
22,879
def send ( self ) : if not self . _receive_has_been_called : all_addrs = self . _dest_addrs else : all_addrs = [ a for ( i , a ) in list ( self . _id_to_addr . items ( ) ) if i in self . _remaining_ids ] if self . _last_used_id is None : self . _last_used_id = int ( time . time ( ) ) & 0xffff for addr in all_addrs : se...
Send pings to multiple addresses ensuring unique IDs for each request .
22,880
def _read_all_from_socket ( self , timeout ) : pkts = [ ] try : self . _sock . settimeout ( timeout ) while True : p = self . _sock . recv ( 64 ) pkts . append ( ( bytearray ( p ) , time . time ( ) ) ) self . _sock . settimeout ( 0 ) except socket . timeout : pass except socket . error as e : if e . errno == errno . EW...
Read all packets we currently can on the socket .
22,881
async def get ( self ) : try : return self . _parse ( await self . read_registers ( 0 , 16 ) ) except TimeoutError : return { 'ip' : self . ip , 'connected' : False }
Get current state from the Midas gas detector .
22,882
def _parse ( self , registers ) : result = { 'ip' : self . ip , 'connected' : True } decoder = BinaryPayloadDecoder . fromRegisters ( registers , byteorder = Endian . Big , wordorder = Endian . Little ) b = [ decoder . decode_bits ( ) , decoder . decode_bits ( ) ] reg_40001 = b [ 1 ] + b [ 0 ] monitor_integer = sum ( 1...
Parse the response returning a dictionary .
22,883
async def _connect ( self ) : self . waiting = True await self . client . start ( self . ip ) self . waiting = False if self . client . protocol is None : raise IOError ( "Could not connect to '{}'." . format ( self . ip ) ) self . open = True
Start asynchronous reconnect loop .
22,884
async def read_registers ( self , address , count ) : registers = [ ] while count > 124 : r = await self . _request ( 'read_holding_registers' , address , 124 ) registers += r . registers address , count = address + 124 , count - 124 r = await self . _request ( 'read_holding_registers' , address , count ) registers += ...
Read modbus registers .
22,885
async def write_register ( self , address , value , skip_encode = False ) : await self . _request ( 'write_registers' , address , value , skip_encode = skip_encode )
Write a modbus register .
22,886
async def write_registers ( self , address , values , skip_encode = False ) : while len ( values ) > 62 : await self . _request ( 'write_registers' , address , values , skip_encode = skip_encode ) address , values = address + 124 , values [ 62 : ] await self . _request ( 'write_registers' , address , values , skip_enco...
Write modbus registers .
22,887
async def _request ( self , method , * args , ** kwargs ) : if not self . open : await self . _connect ( ) while self . waiting : await asyncio . sleep ( 0.1 ) if self . client . protocol is None or not self . client . protocol . connected : raise TimeoutError ( "Not connected to device." ) try : future = getattr ( sel...
Send a request to the device and awaits a response .
22,888
def _close ( self ) : self . client . stop ( ) self . open = False self . waiting = False
Close the TCP connection .
22,889
def command_line ( ) : import argparse import asyncio import json parser = argparse . ArgumentParser ( description = "Read a Honeywell Midas gas " "detector state from the command line." ) parser . add_argument ( 'address' , help = "The IP address of the gas detector." ) args = parser . parse_args ( ) async def get ( )...
Command - line tool for Midas gas detector communication .
22,890
def build_masked_loss ( loss_function , mask_value ) : def masked_loss_function ( y_true , y_pred ) : mask = K . cast ( K . not_equal ( y_true , mask_value ) , K . floatx ( ) ) return loss_function ( y_true * mask , y_pred * mask ) return masked_loss_function
Builds a loss function that masks based on targets
22,891
def Run ( self ) : if not self . executable : logging . error ( 'Could not locate "%s"' % self . long_name ) return 0 finfo = os . stat ( self . executable ) self . date = time . localtime ( finfo [ stat . ST_MTIME ] ) logging . info ( 'Running: %s %s </dev/null 2>&1' % ( self . executable , FLAGS . help_flag ) ) ( chi...
Run it and collect output .
22,892
def Parse ( self ) : ( start_line , lang ) = self . ParseDesc ( ) if start_line < 0 : return if 'python' == lang : self . ParsePythonFlags ( start_line ) elif 'c' == lang : self . ParseCFlags ( start_line ) elif 'java' == lang : self . ParseJavaFlags ( start_line )
Parse program output .
22,893
def ParseDesc ( self , start_line = 0 ) : exec_mod_start = self . executable + ':' after_blank = 0 start_line = 0 for start_line in range ( start_line , len ( self . output ) ) : line = self . output [ start_line ] . rstrip ( ) if ( 'flags:' == line and len ( self . output ) > start_line + 1 and '' == self . output [ s...
Parse the initial description .
22,894
def ParseCFlags ( self , start_line = 0 ) : modname = None modlist = [ ] flag = None for line_num in range ( start_line , len ( self . output ) ) : line = self . output [ line_num ] . rstrip ( ) if not line : if flag : modlist . append ( flag ) flag = None continue mobj = self . module_c_re . match ( line ) if mobj : m...
Parse C style flags .
22,895
def Filter ( self ) : if not self . desc : self . short_desc = '' return for i in range ( len ( self . desc ) ) : if self . desc [ i ] . find ( self . executable ) >= 0 : self . desc [ i ] = self . desc [ i ] . replace ( self . executable , self . name ) self . short_desc = self . desc [ 0 ] word_list = self . short_de...
Filter parsed data to create derived fields .
22,896
def Output ( self ) : self . Open ( ) self . Header ( ) self . Body ( ) self . Footer ( )
Output all sections of the page .
22,897
def GetFlagSuggestions ( attempt , longopt_list ) : if len ( attempt ) <= 2 or not longopt_list : return [ ] option_names = [ v . split ( '=' ) [ 0 ] for v in longopt_list ] distances = [ ( _DamerauLevenshtein ( attempt , option [ 0 : len ( attempt ) ] ) , option ) for option in option_names ] distances . sort ( key = ...
Get helpful similar matches for an invalid flag .
22,898
def _DamerauLevenshtein ( a , b ) : memo = { } def Distance ( x , y ) : if ( x , y ) in memo : return memo [ x , y ] if not x : d = len ( y ) elif not y : d = len ( x ) else : d = min ( Distance ( x [ 1 : ] , y ) + 1 , Distance ( x , y [ 1 : ] ) + 1 , Distance ( x [ 1 : ] , y [ 1 : ] ) + ( x [ 0 ] != y [ 0 ] ) ) if len...
Damerau - Levenshtein edit distance from a to b .
22,899
def FlagDictToArgs ( flag_map ) : for key , value in six . iteritems ( flag_map ) : if value is None : yield '--%s' % key elif isinstance ( value , bool ) : if value : yield '--%s' % key else : yield '--no%s' % key elif isinstance ( value , ( bytes , type ( u'' ) ) ) : yield '--%s=%s' % ( key , value ) else : try : yie...
Convert a dict of values into process call parameters .