idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
51,300
def update_redis ( project : str , environment : str , feature : str , state : str ) -> None : try : hosts = RedisWrapper . connection_string_parser ( os . environ . get ( 'REDIS_HOSTS' ) ) except RuntimeError as ex : LOG . error ( ex ) sys . exit ( 1 ) for host in hosts : LOG . info ( "connecting to %s:%s" , host . ho...
Update redis state for a feature flag .
51,301
def update_ld_api ( project : str , environment : str , feature : str , state : str ) : ld_api = LaunchDarklyApi ( os . environ . get ( 'LD_API_KEY' ) , project , environment ) if valid_state ( state ) : if state . lower ( ) == 'off' : new_state = False else : new_state = True ld_api . update_flag ( new_state , feature...
Execute command against the LaunchDarkly API .
51,302
def generate_relay_config ( project ) : ld_api = LaunchDarklyApi ( os . environ . get ( 'LD_API_KEY' ) , project_key = project ) config = ConfigGenerator ( ) envs = ld_api . get_environments ( project ) config . generate_relay_config ( envs )
Generate Relay Proxy Configuration .
51,303
def dicomdir_info ( dirpath , * args , ** kwargs ) : dr = DicomReader ( dirpath = dirpath , * args , ** kwargs ) info = dr . dicomdirectory . get_stats_of_series_in_dir ( ) return info
Get information about series in dir
51,304
def is_dicom_dir ( datapath ) : retval = False datapath = op . expanduser ( datapath ) for f in os . listdir ( datapath ) : if f . endswith ( ( ".dcm" , ".DCM" ) ) : retval = True return True try : pydicom . read_file ( os . path . join ( datapath , f ) ) retval = True except Exception as e : logger . warning ( "Unable...
Check if in dir is one or more dicom file . We use two methods . First is based on dcm extension detection .
51,305
def files_in_dir ( dirpath , wildcard = "*" , startpath = None ) : import glob filelist = [ ] if startpath is not None : completedirpath = os . path . join ( startpath , dirpath ) else : completedirpath = dirpath if os . path . exists ( completedirpath ) : logger . info ( 'completedirpath = ' + completedirpath ) else :...
Function generates list of files from specific dir
51,306
def get_slice_location ( dcmdata , teil = None ) : slice_location = None if hasattr ( dcmdata , 'SliceLocation' ) : try : slice_location = float ( dcmdata . SliceLocation ) except Exception as exc : logger . info ( "It is not possible to use SliceLocation" ) logger . debug ( traceback . format_exc ( ) ) if slice_locati...
get location of the slice
51,307
def get_overlay ( self ) : overlay = { } dcmlist = self . files_in_serie for i in range ( len ( dcmlist ) ) : onefile = dcmlist [ i ] logger . info ( "reading '%s'" % onefile ) data = self . _read_file ( onefile ) if len ( overlay ) == 0 : for i_overlay in range ( 0 , 50 ) : try : data2d = decode_overlay_slice ( data ,...
Function make 3D data from dicom file slices . There are usualy more overlays in the data .
51,308
def get_stats_of_series_in_dir ( self , study_id = None ) : if study_id is not None : logger . error ( "study_id tag is not implemented yet" ) return import numpy as np dcmdir = self . files_with_info series_info = { line [ 'SeriesNumber' ] : line for line in dcmdir } try : dcmdirseries = [ line [ 'SeriesNumber' ] for ...
Dicom series staticstics input is dcmdir not dirpath Information is generated from dicomdir . pkl and first files of series
51,309
def print_series_info ( self , series_info , minimal_series_number = 1 ) : strinfo = '' if len ( series_info ) > minimal_series_number : for serie_number in series_info . keys ( ) : strl = get_one_serie_info ( series_info , serie_number ) strinfo = strinfo + strl + '\n' return strinfo
Print series_info from dcmdirstats
51,310
def __prepare_info_from_dicomdir_file ( self , writedicomdirfile = True ) : createdcmdir = True dicomdirfile = os . path . join ( self . dirpath , self . dicomdir_filename ) ftype = 'pickle' if os . path . exists ( dicomdirfile ) : try : dcmdirplus = misc . obj_from_file ( dicomdirfile , ftype ) if dcmdirplus [ 'versio...
Check if exists dicomdir file and load it or cerate it
51,311
def series_in_dir ( self ) : countsd = { } for line in self . files_with_info : if "SeriesNumber" in line : sn = line [ 'SeriesNumber' ] else : sn = None if sn in countsd : countsd [ sn ] += 1 else : countsd [ sn ] = 1 bins = list ( countsd ) counts = list ( countsd . values ( ) ) return counts , bins
input is dcmdir not dirpath
51,312
def get_sorted_series_files ( self , startpath = "" , series_number = None , return_files_with_info = False , sort_keys = "SliceLocation" , return_files = True , remove_doubled_slice_locations = True ) : dcmdir = self . files_with_info [ : ] if series_number is not None : dcmdir = [ line for line in dcmdir if line [ 'S...
Function returns sorted list of dicom files . File paths are organized by SeriesUID StudyUID and FrameUID
51,313
def _create_dicomdir_info ( self ) : filelist = files_in_dir ( self . dirpath ) files = [ ] metadataline = { } for filepath in filelist : head , teil = os . path . split ( filepath ) dcmdata = None if os . path . isdir ( filepath ) : logger . debug ( "Subdirectory found in series dir is ignored: " + str ( filepath ) ) ...
Function crates list of all files in dicom dir with all IDs
51,314
def python_parser ( self , obj , * args ) : attr , args = args [ 0 ] , args [ 1 : ] item = getattr ( obj , attr ) if callable ( item ) : item = item ( * args ) return [ item ]
operate a python obj
51,315
def parse ( self ) : self . tree = self . _build_tree ( self . html_contents ) self . stylesheet = self . parser . parse_stylesheet ( self . css_contents ) self . cleaned_css = self . _clean_css ( )
Parses the CSS contents and returns the cleaned CSS as a string
51,316
def rel_to_abs ( self , base_url ) : self . cleaned_css = self . rel_to_abs_re . sub ( lambda match : "url('%s')" % urljoin ( base_url , match . group ( 'path' ) . strip ( '\'"' ) ) , self . cleaned_css )
Converts relative links from css contents to absolute links
51,317
def _clean_css ( self ) : css_rules = [ ] for rule in self . stylesheet . rules : try : cleaned_rule = self . _clean_rule ( rule ) if cleaned_rule is not None : css_rules . append ( cleaned_rule ) except : css_rules . append ( rule ) return self . _build_css ( css_rules )
Returns the cleaned CSS
51,318
def _clean_rule ( self , rule ) : if rule . at_keyword is not None : return rule cleaned_token_list = [ ] for token_list in split_on_comma ( rule . selector ) : if self . _token_list_matches_tree ( token_list ) : if len ( cleaned_token_list ) > 0 : cleaned_token_list . append ( cssselect . parser . Token ( 'DELIM' , ',...
Cleans a css Rule by removing Selectors without matches on the tree Returns None if the whole rule do not match
51,319
def _token_list_matches_tree ( self , token_list ) : try : parsed_selector = cssselect . parse ( '' . join ( token . as_css ( ) for token in token_list ) ) [ 0 ] return bool ( self . tree . xpath ( self . xpath_translator . selector_to_xpath ( parsed_selector ) ) ) except : return True
Returns whether the token list matches the HTML tree
51,320
def _rule_as_string ( self , rule ) : if isinstance ( rule , RuleSet ) : return '%s{%s}' % ( self . _selector_as_string ( rule . selector ) , self . _declarations_as_string ( rule . declarations ) ) elif isinstance ( rule , ImportRule ) : return "@import url('%s') %s;" % ( rule . uri , ',' . join ( rule . media ) ) eli...
Converts a tinycss rule to a formatted CSS string
51,321
def _selector_as_string ( self , selector ) : return ',' . join ( '' . join ( token . as_css ( ) for token in strip_whitespace ( token_list ) ) for token_list in split_on_comma ( selector ) )
Returns a selector as a CSS string
51,322
def _declarations_as_string ( self , declarations ) : return '' . join ( '%s:%s%s;' % ( d . name , d . value . as_css ( ) , ' !' + d . priority if d . priority else '' ) for d in declarations )
Returns a list of declarations as a formatted CSS string
51,323
def envars_to_markdown ( envars , title = "Environment" ) : markdown = '' if envars not in [ None , '' , [ ] ] : markdown += '\n## %s\n' % title for envar in envars : markdown += ' - **%s**: %s\n' % ( envar [ 0 ] , envar [ 1 ] ) return markdown
generate a markdown list of a list of environment variable tuples
51,324
def get_default_commands ( self ) : commands = Application . get_default_commands ( self ) self . add ( ConstantsCommand ( ) ) self . add ( LoaderCommand ( ) ) self . add ( PyStratumCommand ( ) ) self . add ( WrapperCommand ( ) ) return commands
Returns the default commands of this application .
51,325
def discover ( service = "ssdp:all" , timeout = 1 , retries = 2 , ipAddress = "239.255.255.250" , port = 1900 ) : socket . setdefaulttimeout ( timeout ) messages = [ ] if isinstance ( service , str ) : services = [ service ] elif isinstance ( service , list ) : services = service for service in services : message = 'M-...
Discovers UPnP devices in the local network .
51,326
def discoverParticularHost ( host , service = "ssdp:all" , deviceDefinitionURL = None , timeout = 1 , retries = 2 , ipAddress = "239.255.255.250" , port = 1900 , proxies = None ) : ipResults = socket . getaddrinfo ( host , 80 ) if len ( ipResults ) == 0 : return None ipAddresses = [ ] for ipAdrTupple in ipResults : ipA...
Discover a particular host and find the best response .
51,327
def rateServiceTypeInResult ( discoveryResponse ) : if discoveryResponse is None : return 0 serviceType = discoveryResponse . service if serviceType . startswith ( "urn:dslforum-org:device" ) : return 11 if serviceType . startswith ( "urn:dslforum-org:service" ) : return 10 if serviceType . startswith ( "urn:dslforum-o...
Gives a quality rating for a given service type in a result higher is better .
51,328
def download ( self , url , file_name , headers = None , show_progress = True ) : fd , tmp_file = tempfile . mkstemp ( prefix = ( "%s.tmp." % file_name ) ) os . close ( fd ) verify = self . _verify ( ) if requests . head ( url , verify = verify ) . status_code in [ 200 , 401 ] : response = self . stream ( url , headers...
stream to a temporary file rename on successful completion
51,329
def getControlURL ( self , serviceType , default = None ) : if serviceType in self . __deviceServiceDefinitions . keys ( ) : return self . __deviceServiceDefinitions [ serviceType ] [ "controlURL" ] if self . __deviceXMLInitialized : raise ValueError ( "Device do not support given serviceType: " + serviceType ) return ...
Returns the control URL for a given service type .
51,330
def getEventSubURL ( self , serviceType , default = None ) : if serviceType in self . __deviceServiceDefinitions . keys ( ) : return self . __deviceServiceDefinitions [ serviceType ] [ "eventSubURL" ] if self . __deviceXMLInitialized : raise ValueError ( "Device do not support given serviceType: " + serviceType ) retur...
Returns the event URL for a given service type .
51,331
def execute ( self , uri , namespace , action , timeout = 2 , ** kwargs ) : if not uri : raise ValueError ( "No action URI has been defined." ) if not namespace : raise ValueError ( "No namespace has been defined." ) if not action : raise ValueError ( "No action has been defined." ) header = { 'Content-Type' : 'text/xm...
Executes a given action with optional arguments .
51,332
def _extractErrorString ( request ) : errorStr = "" tag = None try : root = ET . fromstring ( request . text . encode ( 'utf-8' ) ) tag = root [ 0 ] [ 0 ] except : return errorStr for element in tag . getiterator ( ) : tagName = element . tag . lower ( ) if tagName . endswith ( "string" ) : errorStr += element . text +...
Extract error string from a failed UPnP call .
51,333
def setupTR64Device ( self , deviceType ) : if deviceType . lower ( ) != "fritz.box" : raise ValueError ( "Unknown device type given." ) self . __deviceServiceDefinitions = { } self . __deviceXMLInitialized = False self . deviceServiceDefinitions [ "urn:dslforum-org:service:DeviceConfig:1" ] = { "controlURL" : "/upnp/c...
Setup actions for known devices .
51,334
def loadDeviceDefinitions ( self , urlOfXMLDefinition , timeout = 3 ) : proxies = { } if self . __httpsProxy : proxies = { "https" : self . __httpsProxy } if self . __httpProxy : proxies = { "http" : self . __httpProxy } headers = { "User-Agent" : "Mozilla/5.0; SimpleTR64-1" } auth = None if self . __password : auth = ...
Loads the device definitions from a given URL which points to the root XML in the device .
51,335
def _loadDeviceDefinitions ( self , urlOfXMLDefinition , xml ) : url = urlparse ( urlOfXMLDefinition ) baseURIPath = url . path . rpartition ( '/' ) [ 0 ] + "/" try : root = ET . fromstring ( xml ) except Exception as e : raise ValueError ( "Can not parse CPE definitions '" + urlOfXMLDefinition + "': " + str ( e ) ) se...
Internal call to parse the XML of the device definition .
51,336
def _iterateToFindSCPDElements ( self , element , baseURIPath ) : for child in element . getchildren ( ) : tagName = child . tag . lower ( ) if tagName . endswith ( 'servicelist' ) : self . _processServiceList ( child , baseURIPath ) elif tagName . endswith ( 'devicetype' ) : if "deviceType" not in self . __deviceInfor...
Internal method to iterate through device definition XML tree .
51,337
def _processServiceList ( self , serviceList , baseURIPath ) : for service in serviceList . getchildren ( ) : if not service . tag . lower ( ) . endswith ( "service" ) : raise ValueError ( "Non service tag in servicelist: " + service . tag ) serviceType = None controlURL = None scpdURL = None eventURL = None for child ...
Internal method to iterate in the device definition XML tree through the service list .
51,338
def _loadSCPD ( self , serviceType , timeout ) : if serviceType not in self . __deviceServiceDefinitions . keys ( ) : raise ValueError ( "Can not load SCPD, no service type defined for: " + serviceType ) if "scpdURL" not in self . __deviceServiceDefinitions [ serviceType ] . keys ( ) : raise ValueError ( "No SCPD URL d...
Internal method to load the action definitions .
51,339
def createFromURL ( urlOfXMLDefinition ) : url = urlparse ( urlOfXMLDefinition ) if not url . port : if url . scheme . lower ( ) == "https" : port = 443 else : port = 80 else : port = url . port return Wifi ( url . hostname , port , url . scheme )
Factory method to create a DeviceTR64 from an URL to the XML device definitions .
51,340
def getWifiInfo ( self , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "getWifiInfo" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetInfo" , timeout = timeout ) return WifiBasicInfo ( results )
Execute GetInfo action to get Wifi basic information s .
51,341
def getTotalAssociations ( self , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "getTotalAssociations" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetTotalAssociations" , timeout = timeout ) return int ( results [ "NewTot...
Execute GetTotalAssociations action to get the amount of associated Wifi clients .
51,342
def getGenericAssociatedDeviceInfo ( self , index , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "getGenericAssociatedDeviceInfo" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetGenericAssociatedDeviceInfo" , timeout = ti...
Execute GetGenericAssociatedDeviceInfo action to get detailed information about a Wifi client .
51,343
def getSpecificAssociatedDeviceInfo ( self , macAddress , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "getSpecificAssociatedDeviceInfo" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) results = self . execute ( uri , namespace , "GetSpecificAssociatedDeviceInfo" , time...
Execute GetSpecificAssociatedDeviceInfo action to get detailed information about a Wifi client .
51,344
def setEnable ( self , status , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "setEnable" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) if status : setStatus = 1 else : setStatus = 0 self . execute ( uri , namespace , "SetEnable" , timeout = timeout , NewEnable = setSt...
Set enable status for a Wifi interface be careful you don t cut yourself off .
51,345
def setChannel ( self , channel , wifiInterfaceId = 1 , timeout = 1 ) : namespace = Wifi . getServiceType ( "setChannel" ) + str ( wifiInterfaceId ) uri = self . getControlURL ( namespace ) self . execute ( uri , namespace , "SetChannel" , timeout = timeout , NewChannel = channel )
Set the channel of this Wifi interface
51,346
def enabled_checker ( func ) : @ wraps ( func ) def wrap ( self , * args , ** kwargs ) : if self . allowed_methods and isinstance ( self . allowed_methods , list ) and func . __name__ not in self . allowed_methods : raise Exception ( "Method {} is disabled" . format ( func . __name__ ) ) return func ( self , * args , *...
Access decorator which checks if a RPC method is enabled by our configuration
51,347
async def list_vms ( self , preset ) : vmshepherd = self . request . app . vmshepherd preset = vmshepherd . preset_manager . get_preset ( preset ) result_vms = { vm . id : { 'ip' : vm . ip [ 0 ] , 'state' : vm . state . value } for vm in preset . vms } return preset . count , result_vms
Listing virtual machines in a given preset
51,348
async def terminate_vm ( self , preset , vm_id ) : vmshepherd = self . request . app . vmshepherd preset = vmshepherd . preset_manager . get_preset ( preset ) await preset . iaas . terminate_vm ( vm_id ) return 'OK'
Discard vm in specified preset
51,349
async def get_vm_metadata ( self , preset , vm_id ) : vmshepherd = self . request . app . vmshepherd preset = vmshepherd . preset_manager . get_preset ( preset ) vm_info = await preset . iaas . get_vm ( vm_id ) ret_info = copy . deepcopy ( vm_info . metadata ) if vm_info . metadata else { } ret_info [ 'tags' ] = vm_inf...
Get vm metadata
51,350
def linkify ( text , attrs = { } ) : def separate_parentheses ( s ) : start = re_find ( r'^\(*' , s ) end = re_find ( r'\)*$' , s ) n = min ( len ( start ) , len ( end ) ) if n : return s [ : n ] , s [ n : - n ] , s [ - n : ] else : return '' , s , '' def link_repl ( url , proto = 'http://' ) : opening , url , closing ...
Convert URL - like and email - like strings into links .
51,351
def get_environments ( self , project_key : str ) -> dict : try : resp = self . client . get_project ( project_key ) except launchdarkly_api . rest . ApiException as ex : msg = "Unable to get environments." resp = "API response was {0} {1}." . format ( ex . status , ex . reason ) LOG . error ( "%s %s" , msg , resp ) sy...
Retrieve all environments for a given project .
51,352
def update_flag ( self , state : str , feature_key : str ) -> launchdarkly_api . FeatureFlag : build_env = "/environments/" + self . environment_key + "/on" patch_comment = [ { "op" : "replace" , "path" : build_env , "value" : state } ] try : resp = self . feature . patch_feature_flag ( self . project_key , feature_key...
Update the flag status for the specified feature flag .
51,353
def _write_result_handler ( self , routine ) : self . _write_line ( 'ret = {}' ) self . _write_execute_rows ( routine ) self . _write_line ( 'for row in rows:' ) num_of_dict = len ( routine [ 'columns' ] ) i = 0 while i < num_of_dict : value = "row['{0!s}']" . format ( routine [ 'columns' ] [ i ] ) stack = '' j = 0 whi...
Generates code for calling the stored routine in the wrapper method .
51,354
def _log_query ( query ) : query = query . strip ( ) if os . linesep in query : MetadataDataLayer . io . log_very_verbose ( 'Executing query:' ) MetadataDataLayer . io . log_very_verbose ( '<sql>{0}</sql>' . format ( query ) ) else : MetadataDataLayer . io . log_very_verbose ( 'Executing query: <sql>{0}</sql>' . format...
Logs the query on the console .
51,355
def request_token ( self , board ) : nonce = str ( uuid . uuid4 ( ) ) data = { 'scopes' : 'write' , 'client_id' : self . client_id , 'application_name' : 'HelpMe' , 'public_key' : self . public_key . replace ( "'" , "" ) , 'nonce' : nonce } url = ( board + "/user-api-key/new?scopes=write&application_name=HelpMe&public_...
send a public key to request a token . When we call this function we already have an RSA key at self . key
51,356
def create_post ( self , title , body , board , category , username ) : category_url = "%s/categories.json" % board response = requests . get ( category_url ) if response . status_code != 200 : print ( 'Error with retrieving %s' % category_url ) sys . exit ( 1 ) categories = response . json ( ) [ 'category_list' ] [ 'c...
create a Discourse post given a title body board and token .
51,357
def main ( self , config_filename , file_names = None ) : self . _io . title ( 'Loader' ) if file_names : self . __load_list ( config_filename , file_names ) else : self . __load_all ( config_filename ) if self . error_file_names : self . __log_overview_errors ( ) return 1 else : return 0
Loads stored routines into the current schema .
51,358
def __log_overview_errors ( self ) : if self . error_file_names : self . _io . warning ( 'Routines in the files below are not loaded:' ) self . _io . listing ( sorted ( self . error_file_names ) )
Show info about sources files of stored routines that were not loaded successfully .
51,359
def _add_replace_pair ( self , name , value , quote ) : key = '@' + name + '@' key = key . lower ( ) class_name = value . __class__ . __name__ if class_name in [ 'int' , 'float' ] : value = str ( value ) elif class_name in [ 'bool' ] : value = '1' if value else '0' elif class_name in [ 'str' ] : if quote : value = "'" ...
Adds a replace part to the map of replace pairs .
51,360
def __load_list ( self , config_filename , file_names ) : self . _read_configuration_file ( config_filename ) self . connect ( ) self . find_source_files_from_list ( file_names ) self . _get_column_type ( ) self . __read_stored_routine_metadata ( ) self . __get_constants ( ) self . _get_old_stored_routine_info ( ) self...
Loads all stored routines in a list into the RDBMS instance .
51,361
def __find_source_files ( self ) : for dir_path , _ , files in os . walk ( self . _source_directory ) : for name in files : if name . lower ( ) . endswith ( self . _source_file_extension ) : basename = os . path . splitext ( os . path . basename ( name ) ) [ 0 ] relative_path = os . path . relpath ( os . path . join ( ...
Searches recursively for all source files in a directory .
51,362
def __read_stored_routine_metadata ( self ) : if os . path . isfile ( self . _pystratum_metadata_filename ) : with open ( self . _pystratum_metadata_filename , 'r' ) as file : self . _pystratum_metadata = json . load ( file )
Reads the metadata of stored routines from the metadata file .
51,363
def __remove_obsolete_metadata ( self ) : clean = { } for key , _ in self . _source_file_names . items ( ) : if key in self . _pystratum_metadata : clean [ key ] = self . _pystratum_metadata [ key ] self . _pystratum_metadata = clean
Removes obsolete entries from the metadata of all stored routines .
51,364
def __write_stored_routine_metadata ( self ) : with open ( self . _pystratum_metadata_filename , 'w' ) as stream : json . dump ( self . _pystratum_metadata , stream , indent = 4 , sort_keys = True )
Writes the metadata of all stored routines to the metadata file .
51,365
def find_source_files_from_list ( self , file_names ) : for file_name in file_names : if os . path . exists ( file_name ) : routine_name = os . path . splitext ( os . path . basename ( file_name ) ) [ 0 ] if routine_name not in self . _source_file_names : self . _source_file_names [ routine_name ] = file_name else : se...
Finds all source files that actually exists from a list of file names .
51,366
def __get_constants ( self ) : helper = ConstantClass ( self . _constants_class_name , self . _io ) helper . reload ( ) constants = helper . constants ( ) for name , value in constants . items ( ) : self . _add_replace_pair ( name , value , True ) self . _io . text ( 'Read {0} constants for substitution from <fso>{1}</...
Gets the constants from the class that acts like a namespace for constants and adds them to the replace pairs .
51,367
async def terminate ( self ) : logging . debug ( 'Terminate: %s' , self ) self . state = VmState . TERMINATED return await self . manager . terminate_vm ( self . id )
Terminate vm .
51,368
def init_logger ( name = "" , handler_path_levels = None , level = logging . INFO , formatter = None , formatter_str = None , datefmt = "%Y-%m-%d %H:%M:%S" , ) : levels = { "NOTSET" : logging . NOTSET , "DEBUG" : logging . DEBUG , "INFO" : logging . INFO , "WARNING" : logging . WARNING , "ERROR" : logging . ERROR , "CR...
Add a default handler for logger .
51,369
def get_fields ( model ) : try : if hasattr ( model , "knockout_fields" ) : fields = model . knockout_fields ( ) else : try : fields = model_to_dict ( model ) . keys ( ) except Exception as e : fields = model . _meta . get_fields ( ) return fields except Exception as e : logger . exception ( e ) return [ ]
Returns a Model s knockout_fields or the default set of field names .
51,370
def get_object_data ( obj , fields , safe ) : temp_dict = dict ( ) for field in fields : try : attribute = getattr ( obj , str ( field ) ) if isinstance ( attribute , list ) and all ( [ isinstance ( item , models . Model ) for item in attribute ] ) : temp_dict [ field ] = [ ] for item in attribute : temp_dict [ field ]...
Given an object and a list of fields recursively build an object for serialization .
51,371
def ko_model ( model , field_names = None , data = None ) : try : if isinstance ( model , str ) : modelName = model else : modelName = model . __class__ . __name__ if field_names : fields = field_names else : fields = get_fields ( model ) if hasattr ( model , "comparator" ) : comparator = str ( model . comparator ( ) )...
Given a model returns the Knockout Model and the Knockout ViewModel . Takes optional field names and data .
51,372
def ko_bindings ( model ) : try : if isinstance ( model , str ) : modelName = model else : modelName = model . __class__ . __name__ modelBindingsString = "ko.applyBindings(new " + modelName + "ViewModel(), $('#" + modelName . lower ( ) + "s')[0]);" return modelBindingsString except Exception as e : logger . error ( e )...
Given a model returns the Knockout data bindings .
51,373
def ko_data ( queryset , field_names = None , name = None , safe = False , return_json = False ) : try : try : queryset_instance = queryset [ 0 ] except TypeError as e : queryset_instance = queryset queryset = [ queryset ] except IndexError as e : if not isinstance ( queryset , list ) : queryset_instance = queryset . m...
Given a QuerySet return just the serialized representation based on the knockout_fields as JavaScript .
51,374
def ko ( queryset , field_names = None ) : try : koDataString = ko_data ( queryset , field_names ) koModelString = ko_model ( queryset [ 0 ] . __class__ . __name__ , field_names , data = True ) koBindingsString = ko_bindings ( queryset [ 0 ] ) koString = koDataString + '\n' + koModelString + '\n' + koBindingsString ret...
Converts a Django QuerySet into a complete Knockout implementation .
51,375
def generate_keypair ( keypair_file ) : from Crypto . PublicKey import RSA key = RSA . generate ( 2048 ) keypair_dir = os . path . dirname ( keypair_file ) if not os . path . exists ( keypair_dir ) : os . makedirs ( keypair_dir ) with open ( keypair_file , 'wb' ) as filey : filey . write ( key . exportKey ( 'PEM' ) ) r...
generate_keypair is used by some of the helpers that need a keypair . The function should be used if the client doesn t have the attribute self . key . We generate the key and return it .
51,376
def __message ( expected_row_count , actual_row_count , query ) : query = query . strip ( ) message = 'Wrong number of rows selected' message += os . linesep message += 'Expected number of rows: {}' . format ( expected_row_count ) message += os . linesep message += 'Actual number of rows: {}' . format ( actual_row_coun...
Composes the exception message .
51,377
def main ( args , extras ) : from helpme . main import get_helper name = args . command if name in HELPME_HELPERS : helper = get_helper ( name = name ) if args . asciinema is not None : if os . path . exists ( args . asciinema ) : helper . data [ 'record_asciinema' ] = args . asciinema helper . run ( positionals = extr...
This is the actual driver for the helper .
51,378
def extract ( self , html_contents , css_contents = None , base_url = None ) : html_extractor = self . html_extractor ( html_contents , self . _xpaths_to_keep , self . _xpaths_to_discard ) has_matches = html_extractor . parse ( ) if has_matches : if base_url is not None : html_extractor . rel_to_abs ( base_url ) cleane...
Extracts the cleaned html tree as a string and only css rules matching the cleaned html tree
51,379
def __add ( self , dest , xpath ) : assert isinstance ( xpath , string_types ) dest . append ( xpath )
Adds a Xpath expression to the dest list
51,380
def _write_line ( self , line = None ) : if line is None : self . _write ( "\n" ) if self . __indent_level > 1 : self . __indent_level -= 1 elif line == '' : self . _write ( "\n" ) else : line = ( ' ' * 4 * self . __indent_level ) + line if line [ - 1 : ] == ':' : self . __indent_level += 1 self . _write ( line + "\n" ...
Appends a line of code to the generated code and adjust the indent level of the generated code .
51,381
def write_routine_method ( self , routine ) : if self . _lob_as_string_flag : return self . _write_routine_method_without_lob ( routine ) else : if self . is_lob_parameter ( routine [ 'parameters' ] ) : return self . _write_routine_method_with_lob ( routine ) else : return self . _write_routine_method_without_lob ( rou...
Returns a complete wrapper method .
51,382
def _write_docstring_parameters ( self , routine ) : if routine [ 'pydoc' ] [ 'parameters' ] : self . _write_line ( '' ) for param in routine [ 'pydoc' ] [ 'parameters' ] : lines = param [ 'description' ] . split ( os . linesep ) self . _write_line ( ':param {0} {1}: {2}' . format ( param [ 'python_type' ] , param [ 'p...
Writes the parameters part of the docstring for the wrapper method of a stored routine .
51,383
def __write_docstring_return_type ( self ) : rtype = self . _get_docstring_return_type ( ) if rtype : self . _write_line ( '' ) self . _write_line ( ':rtype: {0}' . format ( rtype ) )
Writes the return type part of the docstring for the wrapper method of a stored routine .
51,384
def __write_docstring ( self , routine ) : self . _write_line ( '' )
Writes the docstring for the wrapper method of a stored routine .
51,385
def _get_wrapper_args ( routine ) : ret = '' for parameter_info in routine [ 'parameters' ] : if ret : ret += ', ' ret += parameter_info [ 'name' ] return ret
Returns code for the parameters of the wrapper method for the stored routine .
51,386
def generate_relay_config ( self , environments : list ) -> None : template = self . env . get_template ( 'ld-relay.conf.jinja' ) with open ( 'ld-relay.conf' , 'w' ) as ld_relay_config : template = template . render ( envs = environments ) ld_relay_config . write ( template )
Generate ld - relay . conf file .
51,387
def __load ( self ) : parts = self . __class_name . split ( '.' ) module_name = "." . join ( parts [ : - 1 ] ) module = __import__ ( module_name ) modules = [ ] for comp in parts [ 1 : ] : module = getattr ( module , comp ) modules . append ( module ) self . __module = modules [ - 2 ]
Loads dynamically the class that acts like a namespace for constants .
51,388
def constants ( self ) : ret = { } name = self . __class_name . split ( '.' ) [ - 1 ] constant_class = getattr ( self . __module , name ) for name , value in constant_class . __dict__ . items ( ) : if re . match ( r'^[A-Z][A-Z0-9_]*$' , name ) : ret [ name ] = value return ret
Gets the constants from the class that acts like a namespace for constants .
51,389
def source_with_constants ( self , constants ) : old_lines = self . source ( ) . split ( "\n" ) info = self . __extract_info ( old_lines ) new_lines = old_lines [ 0 : info [ 'start_line' ] ] for constant , value in sorted ( constants . items ( ) ) : new_lines . append ( "{0}{1} = {2}" . format ( info [ 'indent' ] , str...
Returns the source of the module with the class that acts like a namespace for constants with new constants .
51,390
def get_configfile_user ( ) : from helpme . defaults import HELPME_CLIENT_SECRETS if not os . path . exists ( HELPME_CLIENT_SECRETS ) : bot . debug ( 'Generating settings file at %s' % HELPME_CLIENT_SECRETS ) config_dir = os . path . dirname ( HELPME_CLIENT_SECRETS ) if not os . path . exists ( config_dir ) : mkdir_p (...
return the full path for the user configuration file . If doesn t exist create it for the user .
51,391
def remove_user_setting ( self , section , name , save = False ) : configfile = get_configfile_user ( ) return _remove_setting ( section , name , configfile , save )
remove a setting from the user config
51,392
def _load_config ( configfile , section = None ) : if os . path . exists ( configfile ) : config = read_config ( configfile ) if section is not None : if section in config : return config . _sections [ section ] else : bot . warning ( '%s not found in %s' % ( section , configfile ) ) return config
general function to load and return a configuration given a helper name . This function is used for both the user config and global help me config files .
51,393
def get_settings ( self ) : config = self . _load_config_user ( ) if self . name in config : return config [ self . name ]
get all settings for a client if defined in config .
51,394
def run ( app , argv = sys . argv , extra_args = None ) : if app not in argv [ : 2 ] : argv . insert ( 1 , app ) if len ( argv ) < 3 and 'test' not in argv [ : 2 ] : argv . insert ( 2 , 'test' ) if extra_args : argv . extend ( extra_args ) return runner ( argv )
Run commands in a plain django environment
51,395
def cms ( app , argv = sys . argv , extra_args = None ) : try : import cms except ImportError : print ( 'runner.cms is available only if django CMS is installed' ) raise if app not in argv [ : 2 ] : argv . insert ( 1 , app ) if len ( argv ) < 3 and 'test' not in argv [ : 2 ] : argv . insert ( 2 , 'test' ) if '--cms' no...
Run commands in a django cMS environment
51,396
def parse ( self ) : self . tree = self . _build_tree ( self . html_contents ) self . elts_to_keep = self . _get_elements_to_keep ( ) self . elts_to_discard = self . _get_elements_to_discard ( ) self . elts_to_remove = [ ] is_root = self . _is_keep ( self . tree ) has_descendant = self . _has_keep_elt_in_descendants ( ...
Returns a cleaned lxml ElementTree
51,397
def rel_to_abs ( self , base_url ) : strip_attributes ( self . tree , 'target' ) self . tree . rewrite_links ( lambda link : urljoin ( base_url , link ) if not link . startswith ( self . rel_to_abs_excluded_prefixes ) else link ) onclick_elements = self . tree . xpath ( '//*[@onclick]' ) for element in onclick_elements...
Converts relative links from html contents to absolute links
51,398
def _get_elements ( self , source ) : return list ( chain ( * [ self . tree . xpath ( xpath ) for xpath in source ] ) )
Returns the list of HtmlElements for the source
51,399
def _parse_element ( self , elt , parent_is_keep = False ) : for e in elt . iterchildren ( ) : is_discard_element = self . _is_discard ( e ) is_keep_element = self . _is_keep ( e ) if is_discard_element and not is_keep_element : self . elts_to_remove . append ( e ) continue if not parent_is_keep : if is_keep_element : ...
Parses an Element recursively