idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
6,500
def GetNetworkDetails ( network , alias = None , location = None ) : if alias is None : alias = clc . v1 . Account . GetAlias ( ) if location is None : location = clc . v1 . Account . GetLocation ( ) r = clc . v1 . API . Call ( 'post' , 'Network/GetNetworkDetails' , { 'AccountAlias' : alias , 'Location' : location , 'Name' : network } ) if int ( r [ 'StatusCode' ] ) == 0 : return ( r [ 'NetworkDetails' ] [ 'IPAddresses' ] )
Gets the details for a Network and its IP Addresses .
6,501
def get_variable_from_exception ( exception , variable_name ) : for frame in reversed ( trace ( ) ) : try : frame_variable = frame [ 0 ] . f_locals [ variable_name ] except KeyError : pass else : return frame_variable else : raise KeyError ( "Variable '%s' not in any stack frames" , variable_name )
Grab the variable from closest frame in the stack
6,502
def force_delete_key ( address ) : address_object = Address . objects . get ( address = address ) address_object . key . delete ( ) address_object . delete ( )
Delete the key from the keyring and the Key and Address objects from the database
6,503
def __wrap_accepted_val ( self , value ) : if isinstance ( value , tuple ) : value = list ( value ) elif not isinstance ( value , list ) : value = [ value ] return value
Wrap accepted value in the list if yet not wrapped .
6,504
def __validate_args ( self , func_name , args , kwargs ) : from pyvalid . validators import Validator for i , ( arg_name , accepted_values ) in enumerate ( self . accepted_args ) : if i < len ( args ) : value = args [ i ] else : if arg_name in kwargs : value = kwargs [ arg_name ] elif i in self . optional_args : continue else : raise InvalidArgumentNumberError ( func_name ) is_valid = False for accepted_val in accepted_values : is_validator = ( isinstance ( accepted_val , Validator ) or ( isinstance ( accepted_val , MethodType ) and hasattr ( accepted_val , '__func__' ) and isinstance ( accepted_val . __func__ , Validator ) ) ) if is_validator : is_valid = accepted_val ( value ) elif isinstance ( accepted_val , type ) : is_valid = isinstance ( value , accepted_val ) else : is_valid = value == accepted_val if is_valid : break if not is_valid : ord_num = self . __ordinal ( i + 1 ) raise ArgumentValidationError ( ord_num , func_name , value , accepted_values )
Compare value of each required argument with list of accepted values .
6,505
def __ordinal ( self , num ) : if 10 <= num % 100 < 20 : return str ( num ) + 'th' else : ord_info = { 1 : 'st' , 2 : 'nd' , 3 : 'rd' } . get ( num % 10 , 'th' ) return '{}{}' . format ( num , ord_info )
Returns the ordinal number of a given integer as a string . eg . 1 - > 1st 2 - > 2nd 3 - > 3rd etc .
6,506
def get_file ( self , name , save_to , add_to_cache = True , force_refresh = False , _lock_exclusive = False ) : uname , version = split_name ( name ) lock = None if self . local_store : lock = self . lock_manager . lock_for ( uname ) if _lock_exclusive : lock . lock_exclusive ( ) else : lock . lock_shared ( ) else : add_to_cache = False t = time . time ( ) logger . debug ( ' downloading %s' , name ) try : if not self . remote_store or ( version is not None and not force_refresh ) : try : if self . local_store and self . local_store . exists ( name ) : return self . local_store . get_file ( name , save_to ) except Exception : if self . remote_store : logger . warning ( "Error getting '%s' from local store" , name , exc_info = True ) else : raise if self . remote_store : if not _lock_exclusive and add_to_cache : if lock : lock . unlock ( ) return self . get_file ( name , save_to , add_to_cache , _lock_exclusive = True ) vname = self . remote_store . get_file ( name , save_to ) if add_to_cache : self . _add_to_cache ( vname , save_to ) return vname raise FiletrackerError ( "File not available: %s" % name ) finally : if lock : lock . close ( ) logger . debug ( ' processed %s in %.2fs' , name , time . time ( ) - t )
Retrieves file identified by name .
6,507
def get_stream ( self , name , force_refresh = False , serve_from_cache = False ) : uname , version = split_name ( name ) lock = None if self . local_store : lock = self . lock_manager . lock_for ( uname ) lock . lock_shared ( ) try : if not self . remote_store or ( version is not None and not force_refresh ) : try : if self . local_store and self . local_store . exists ( name ) : return self . local_store . get_stream ( name ) except Exception : if self . remote_store : logger . warning ( "Error getting '%s' from local store" , name , exc_info = True ) else : raise if self . remote_store : if self . local_store and serve_from_cache : if version is None : version = self . remote_store . file_version ( name ) if version : name = versioned_name ( uname , version ) if force_refresh or not self . local_store . exists ( name ) : ( stream , vname ) = self . remote_store . get_stream ( name ) name = self . local_store . add_stream ( vname , stream ) return self . local_store . get_stream ( name ) return self . remote_store . get_stream ( name ) raise FiletrackerError ( "File not available: %s" % name ) finally : if lock : lock . close ( )
Retrieves file identified by name in streaming mode .
6,508
def file_version ( self , name ) : if self . remote_store : return self . remote_store . file_version ( name ) else : return self . local_store . file_version ( name )
Returns the newest available version number of the file .
6,509
def file_size ( self , name , force_refresh = False ) : uname , version = split_name ( name ) t = time . time ( ) logger . debug ( ' querying size of %s' , name ) try : if not self . remote_store or ( version is not None and not force_refresh ) : try : if self . local_store and self . local_store . exists ( name ) : return self . local_store . file_size ( name ) except Exception : if self . remote_store : logger . warning ( "Error getting '%s' from local store" , name , exc_info = True ) else : raise if self . remote_store : return self . remote_store . file_size ( name ) raise FiletrackerError ( "File not available: %s" % name ) finally : logger . debug ( ' processed %s in %.2fs' , name , time . time ( ) - t )
Returns the size of the file .
6,510
def put_file ( self , name , filename , to_local_store = True , to_remote_store = True , compress_hint = True ) : if not to_local_store and not to_remote_store : raise ValueError ( "Neither to_local_store nor to_remote_store set " "in a call to filetracker.Client.put_file" ) check_name ( name ) lock = None if self . local_store : lock = self . lock_manager . lock_for ( name ) lock . lock_exclusive ( ) try : if ( to_local_store or not self . remote_store ) and self . local_store : versioned_name = self . local_store . add_file ( name , filename ) if ( to_remote_store or not self . local_store ) and self . remote_store : versioned_name = self . remote_store . add_file ( name , filename , compress_hint = compress_hint ) finally : if lock : lock . close ( ) return versioned_name
Adds file filename to the filetracker under the name name .
6,511
def delete_file ( self , name ) : if self . local_store : lock = self . lock_manager . lock_for ( name ) lock . lock_exclusive ( ) try : self . local_store . delete_file ( name ) finally : lock . close ( ) if self . remote_store : self . remote_store . delete_file ( name )
Deletes the file identified by name along with its metadata .
6,512
def list_local_files ( self ) : result = [ ] if self . local_store : result . extend ( self . local_store . list_files ( ) ) return result
Returns list of all stored local files .
6,513
def load_checkers ( ) : for loader , name , _ in pkgutil . iter_modules ( [ os . path . join ( __path__ [ 0 ] , 'checkers' ) ] ) : loader . find_module ( name ) . load_module ( name )
Load the checkers
6,514
def check ( operations , loud = False ) : if not CHECKERS : load_checkers ( ) roll_call = [ ] everything_ok = True if loud and operations : title = "Preflyt Checklist" sys . stderr . write ( "{}\n{}\n" . format ( title , "=" * len ( title ) ) ) for operation in operations : if operation . get ( 'checker' ) not in CHECKERS : raise CheckerNotFoundError ( operation ) checker_cls = CHECKERS [ operation [ 'checker' ] ] args = { k : v for k , v in operation . items ( ) if k != 'checker' } checker = checker_cls ( ** args ) success , message = checker . check ( ) if not success : everything_ok = False roll_call . append ( { "check" : operation , "success" : success , "message" : message } ) if loud : sys . stderr . write ( " {}\n" . format ( pformat_check ( success , operation , message ) ) ) return everything_ok , roll_call
Check all the things
6,515
def verify ( operations , loud = False ) : everything_ok , roll_call = check ( operations , loud = loud ) if not everything_ok : raise CheckFailedException ( roll_call ) return roll_call
Check all the things and be assertive about it
6,516
def deci2sexa ( deci , pre = 3 , trunc = False , lower = None , upper = None , b = False , upper_trim = False ) : if lower is not None and upper is not None : deci = normalize ( deci , lower = lower , upper = upper , b = b ) sign = 1 if deci < 0 : deci = abs ( deci ) sign = - 1 hd , f1 = divmod ( deci , 1 ) mm , f2 = divmod ( f1 * 60.0 , 1 ) sf = f2 * 60.0 fp = 10 ** pre if trunc : ss , _ = divmod ( sf * fp , 1 ) else : ss = round ( sf * fp , 0 ) ss = int ( ss ) if ss == 60 * fp : mm += 1 ss = 0 if mm == 60 : hd += 1 mm = 0 hd = int ( hd ) mm = int ( mm ) if lower is not None and upper is not None and upper_trim : if hd == upper : hd = int ( lower ) if hd == 0 and mm == 0 and ss == 0 : sign = 1 ss /= float ( fp ) return ( sign , hd , mm , ss )
Returns the sexagesimal representation of a decimal number .
6,517
def sexa2deci ( sign , hd , mm , ss , todeg = False ) : divisors = [ 1.0 , 60.0 , 3600.0 ] d = 0.0 if sign not in ( - 1 , 1 ) : raise ValueError ( "Sign has to be -1 or 1." ) sexages = [ sign , hd , mm , ss ] for i , divis in zip ( sexages [ 1 : ] , divisors ) : d += i / divis d *= sexages [ 0 ] if todeg : d = h2d ( d ) return d
Combine sexagesimal components into a decimal number .
6,518
def fmt_angle ( val , s1 = " " , s2 = " " , s3 = "" , pre = 3 , trunc = False , lower = None , upper = None , b = False , upper_trim = False ) : x = deci2sexa ( val , pre = pre , trunc = trunc , lower = lower , upper = upper , upper_trim = upper_trim , b = b ) left_digits_plus_deci_point = 3 if pre > 0 else 2 p = "{3:0" + "{0}.{1}" . format ( pre + left_digits_plus_deci_point , pre ) + "f}" + s3 p = "{0}{1:02d}" + s1 + "{2:02d}" + s2 + p return p . format ( "-" if x [ 0 ] < 0 else "+" , * x [ 1 : ] )
Return sexagesimal string of given angle in degrees or hours .
6,519
def phmsdms ( hmsdms ) : units = None sign = None pattern1 = re . compile ( r"([-+]?[0-9]*\.?[0-9]+[^0-9\-+]*)" ) pattern2 = re . compile ( r"([-+]?[0-9]*\.?[0-9]+)" ) hmsdms = hmsdms . lower ( ) hdlist = pattern1 . findall ( hmsdms ) parts = [ None , None , None ] def _fill_right_not_none ( ) : rp = reversed ( parts ) for i , j in enumerate ( rp ) : if j is not None : break if i == 0 : raise ValueError ( "Invalid string." ) elif i == 1 : parts [ 2 ] = v elif i == 2 : if parts [ 0 ] is None : parts [ 0 ] = v else : parts [ 1 ] = v for valun in hdlist : try : v = float ( valun ) _fill_right_not_none ( ) except ValueError : if "hh" in valun or "h" in valun : m = pattern2 . search ( valun ) parts [ 0 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) units = "hours" if "dd" in valun or "d" in valun : m = pattern2 . search ( valun ) parts [ 0 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) units = "degrees" if "mm" in valun or "m" in valun : m = pattern2 . search ( valun ) parts [ 1 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) if "ss" in valun or "s" in valun : m = pattern2 . search ( valun ) parts [ 2 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) if "'" in valun : m = pattern2 . search ( valun ) parts [ 1 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) if '"' in valun : m = pattern2 . search ( valun ) parts [ 2 ] = float ( valun [ m . start ( ) : m . end ( ) ] ) if ":" in valun : v = valun . replace ( ":" , "" ) v = float ( v ) _fill_right_not_none ( ) if not units : units = "degrees" for i in parts : if i and i < 0.0 : if sign is None : sign = - 1 else : raise ValueError ( "Only one number can be negative." ) if sign is None : sign = 1 vals = [ abs ( i ) if i is not None else 0.0 for i in parts ] return dict ( sign = sign , units = units , vals = vals , parts = parts )
Parse a string containing a sexagesimal number .
6,520
def pposition ( hd , details = False ) : p = re . split ( r"[^\d\-+.]*" , hd ) if len ( p ) not in [ 2 , 6 ] : raise ValueError ( "Input must contain either 2 or 6 numbers." ) if len ( p ) == 2 : x , y = float ( p [ 0 ] ) , float ( p [ 1 ] ) if details : numvals = 2 raw_x = p [ 0 ] raw_y = p [ 1 ] elif len ( p ) == 6 : x_p = phmsdms ( " " . join ( p [ : 3 ] ) ) x = sexa2deci ( x_p [ 'sign' ] , * x_p [ 'vals' ] ) y_p = phmsdms ( " " . join ( p [ 3 : ] ) ) y = sexa2deci ( y_p [ 'sign' ] , * y_p [ 'vals' ] ) if details : raw_x = x_p raw_y = y_p numvals = 6 if details : result = dict ( x = x , y = y , numvals = numvals , raw_x = raw_x , raw_y = raw_y ) else : result = x , y return result
Parse string into angular position .
6,521
def sep ( a1 , b1 , a2 , b2 ) : tol = 1e-15 v = CartesianVector . from_spherical ( 1.0 , a1 , b1 ) v2 = CartesianVector . from_spherical ( 1.0 , a2 , b2 ) d = v . dot ( v2 ) c = v . cross ( v2 ) . mod res = math . atan2 ( c , d ) if abs ( res ) < tol : return 0.0 else : return res
Angular spearation between two points on a unit sphere .
6,522
def normalize_sphere ( alpha , delta ) : v = CartesianVector . from_spherical ( r = 1.0 , alpha = d2r ( alpha ) , delta = d2r ( delta ) ) angles = v . normalized_angles return r2d ( angles [ 0 ] ) , r2d ( angles [ 1 ] )
Normalize angles of a point on a sphere .
6,523
def from_spherical ( cls , r = 1.0 , alpha = 0.0 , delta = 0.0 ) : x = r * math . cos ( delta ) * math . cos ( alpha ) y = r * math . cos ( delta ) * math . sin ( alpha ) z = r * math . sin ( delta ) return cls ( x = x , y = y , z = z )
Construct Cartesian vector from spherical coordinates .
6,524
def cross ( self , v ) : n = self . __class__ ( ) n . x = self . y * v . z - self . z * v . y n . y = - ( self . x * v . z - self . z * v . x ) n . z = self . x * v . y - self . y * v . x return n
Cross product of two vectors .
6,525
def mod ( self ) : return math . sqrt ( self . x ** 2 + self . y ** 2 + self . z ** 2 )
Modulus of vector .
6,526
def sep ( self , p ) : return sep ( self . alpha . r , self . delta . r , p . alpha . r , p . delta . r )
Angular spearation between objects in radians .
6,527
def bear ( self , p ) : return bear ( self . alpha . r , self . delta . r , p . alpha . r , p . delta . r )
Find position angle between objects in radians .
6,528
def get_chunk ( self , chunk_id ) : if chunk_id in self . idx : return Cchunk ( self . idx [ chunk_id ] , self . type ) else : return None
Returns the chunk object for the supplied identifier
6,529
def add_chunk ( self , chunk_obj ) : if chunk_obj . get_id ( ) in self . idx : raise ValueError ( "Chunk with id {} already exists!" . format ( chunk_obj . get_id ( ) ) ) self . node . append ( chunk_obj . get_node ( ) ) self . idx [ chunk_obj . get_id ( ) ] = chunk_obj
Adds a chunk object to the layer
6,530
def display_col_dp ( dp_list , attr_name ) : print ( ) print ( "---------- {:s} ----------" . format ( attr_name ) ) print ( [ getattr ( dp , attr_name ) for dp in dp_list ] )
show a value assocciated with an attribute for each DataProperty instance in the dp_list
6,531
def delay ( self , dl = 0 ) : if dl is None : time . sleep ( self . dl ) elif dl < 0 : sys . stderr . write ( "delay cannot less than zero, this takes no effects.\n" ) else : time . sleep ( dl )
Delay for dl seconds .
6,532
def scroll_up ( self , n , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . m . scroll ( vertical = n ) self . delay ( post_dl )
Scroll up n times .
6,533
def scroll_right ( self , n , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . m . scroll ( horizontal = n ) self . delay ( post_dl )
Scroll right n times .
6,534
def tap_key ( self , key_name , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : key = self . _parse_key ( key_name ) self . delay ( pre_dl ) self . k . tap_key ( key , n , interval ) self . delay ( post_dl )
Tap a key on keyboard for n times with interval seconds of interval . Key is declared by it s name
6,535
def enter ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . enter_key , n , interval ) self . delay ( post_dl )
Press enter key n times .
6,536
def backspace ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . backspace_key , n , interval ) self . delay ( post_dl )
Press backspace key n times .
6,537
def space ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . space_key , n ) self . delay ( post_dl )
Press white space key n times .
6,538
def fn ( self , i , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . function_keys [ i ] , n , interval ) self . delay ( post_dl )
Press Fn key n times .
6,539
def tab ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . tab_key , n , interval ) self . delay ( post_dl )
Tap tab key for n times with interval seconds of interval .
6,540
def up ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . up_key , n , interval ) self . delay ( post_dl )
Press up key n times .
6,541
def down ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . down_key , n , interval ) self . delay ( post_dl )
Press down key n times .
6,542
def left ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . left_key , n , interval ) self . delay ( post_dl )
Press left key n times
6,543
def right ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . right_key , n , interval ) self . delay ( post_dl )
Press right key n times .
6,544
def delete ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . delete_key , n , interval ) self . delay ( post_dl )
Pres delete key n times .
6,545
def insert ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . insert_key , n , interval ) self . delay ( post_dl )
Pres insert key n times .
6,546
def home ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . home_key , n , interval ) self . delay ( post_dl )
Pres home key n times .
6,547
def end ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . end_key , n , interval ) self . delay ( post_dl )
Press end key n times .
6,548
def page_up ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . page_up_key , n , interval ) self . delay ( post_dl )
Pres page_up key n times .
6,549
def page_down ( self , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . tap_key ( self . k . page_down , n , interval ) self . delay ( post_dl )
Pres page_down key n times .
6,550
def press_and_tap ( self , press_key , tap_key , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : press_key = self . _parse_key ( press_key ) tap_key = self . _parse_key ( tap_key ) self . delay ( pre_dl ) self . k . press_key ( press_key ) self . k . tap_key ( tap_key , n , interval ) self . k . release_key ( press_key ) self . delay ( post_dl )
Press combination of two keys like Ctrl + C Alt + F4 . The second key could be tapped for multiple time .
6,551
def press_two_and_tap ( self , press_key1 , press_key2 , tap_key , n = 1 , interval = 0 , pre_dl = None , post_dl = None ) : press_key1 = self . _parse_key ( press_key1 ) press_key2 = self . _parse_key ( press_key2 ) tap_key = self . _parse_key ( tap_key ) self . delay ( pre_dl ) self . k . press_key ( press_key1 ) self . k . press_key ( press_key2 ) self . k . tap_key ( tap_key , n , interval ) self . k . release_key ( press_key1 ) self . k . release_key ( press_key2 ) self . delay ( post_dl )
Press combination of three keys like Ctrl + Shift + C The tap key could be tapped for multiple time .
6,552
def ctrl_c ( self , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . press_key ( self . k . control_key ) self . k . tap_key ( "c" ) self . k . release_key ( self . k . control_key ) self . delay ( post_dl )
Press Ctrl + C usually for copy .
6,553
def ctrl_fn ( self , i , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . press_key ( self . k . control_key ) self . k . tap_key ( self . k . function_keys [ i ] ) self . k . release_key ( self . k . control_key ) self . delay ( post_dl )
Press Ctrl + Fn1 ~ 12 once .
6,554
def alt_fn ( self , i , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . press_key ( self . k . alt_key ) self . k . tap_key ( self . k . function_keys [ i ] ) self . k . release_key ( self . k . alt_key ) self . delay ( post_dl )
Press Alt + Fn1 ~ 12 once .
6,555
def shift_fn ( self , i , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . press_key ( self . k . shift_key ) self . k . tap_key ( self . k . function_keys [ i ] ) self . k . release_key ( self . k . shift_key ) self . delay ( post_dl )
Press Shift + Fn1 ~ 12 once .
6,556
def alt_tab ( self , n = 1 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . press_key ( self . k . alt_key ) self . k . tap_key ( self . k . tab_key , n = n , interval = 0.1 ) self . k . release_key ( self . k . alt_key ) self . delay ( post_dl )
Press Alt + Tab once usually for switching between windows . Tab can be tapped for n times default once .
6,557
def type_string ( self , text , interval = 0 , pre_dl = None , post_dl = None ) : self . delay ( pre_dl ) self . k . type_string ( text , interval ) self . delay ( post_dl )
Enter strings .
6,558
def Servers ( self , cached = True ) : if not hasattr ( self , '_servers' ) or not cached : self . _servers = [ ] for server in self . servers_lst : self . _servers . append ( Server ( id = server , alias = self . alias , session = self . session ) ) return ( self . _servers )
Returns list of server objects populates if necessary .
6,559
def Account ( self ) : return ( clc . v2 . Account ( alias = self . alias , session = self . session ) )
Return account object for account containing this server .
6,560
def Group ( self ) : return ( clc . v2 . Group ( id = self . groupId , alias = self . alias , session = self . session ) )
Return group object for group containing this server .
6,561
def Disks ( self ) : if not self . disks : self . disks = clc . v2 . Disks ( server = self , disks_lst = self . data [ 'details' ] [ 'disks' ] , session = self . session ) return ( self . disks )
Return disks object associated with server .
6,562
def PublicIPs ( self ) : if not self . public_ips : self . public_ips = clc . v2 . PublicIPs ( server = self , public_ips_lst = self . ip_addresses , session = self . session ) return ( self . public_ips )
Returns PublicIPs object associated with the server .
6,563
def PriceUnits ( self ) : try : units = clc . v2 . API . Call ( 'GET' , 'billing/%s/serverPricing/%s' % ( self . alias , self . name ) , session = self . session ) except clc . APIFailedResponse : raise ( clc . ServerDeletedException ) return ( { 'cpu' : units [ 'cpu' ] , 'memory' : units [ 'memoryGB' ] , 'storage' : units [ 'storageGB' ] , 'managed_os' : units [ 'managedOS' ] , } )
Returns the hourly unit component prices for this server .
6,564
def PriceHourly ( self ) : units = self . PriceUnits ( ) return ( units [ 'cpu' ] * self . cpu + units [ 'memory' ] * self . memory + units [ 'storage' ] * self . storage + units [ 'managed_os' ] )
Returns the total hourly price for the server .
6,565
def Credentials ( self ) : return ( clc . v2 . API . Call ( 'GET' , 'servers/%s/%s/credentials' % ( self . alias , self . name ) , session = self . session ) )
Returns the administrative credentials for this server .
6,566
def ExecutePackage ( self , package_id , parameters = { } ) : return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'operations/%s/servers/executePackage' % ( self . alias ) , json . dumps ( { 'servers' : [ self . id ] , 'package' : { 'packageId' : package_id , 'parameters' : parameters } } ) , session = self . session ) , alias = self . alias , session = self . session ) )
Execute an existing Bluerprint package on the server .
6,567
def AddNIC ( self , network_id , ip = '' ) : return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'servers/%s/%s/networks' % ( self . alias , self . id ) , json . dumps ( { 'networkId' : network_id , 'ipAddress' : ip } ) , session = self . session ) , alias = self . alias , session = self . session ) )
Add a NIC from the provided network to server and if provided assign a provided IP address
6,568
def RemoveNIC ( self , network_id ) : return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'DELETE' , 'servers/%s/%s/networks/%s' % ( self . alias , self . id , network_id ) , session = self . session ) , alias = self . alias , session = self . session ) )
Remove the NIC associated with the provided network from the server .
6,569
def DeleteSnapshot ( self , names = None ) : if names is None : names = self . GetSnapshots ( ) requests_lst = [ ] for name in names : name_links = [ obj [ 'links' ] for obj in self . data [ 'details' ] [ 'snapshots' ] if obj [ 'name' ] == name ] [ 0 ] requests_lst . append ( clc . v2 . Requests ( clc . v2 . API . Call ( 'DELETE' , [ obj [ 'href' ] for obj in name_links if obj [ 'rel' ] == 'delete' ] [ 0 ] , session = self . session ) , alias = self . alias , session = self . session ) ) return ( sum ( requests_lst ) )
Removes an existing Hypervisor level snapshot .
6,570
def RestoreSnapshot ( self , name = None ) : if not len ( self . data [ 'details' ] [ 'snapshots' ] ) : raise ( clc . CLCException ( "No snapshots exist" ) ) if name is None : name = self . GetSnapshots ( ) [ 0 ] name_links = [ obj [ 'links' ] for obj in self . data [ 'details' ] [ 'snapshots' ] if obj [ 'name' ] == name ] [ 0 ] return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , [ obj [ 'href' ] for obj in name_links if obj [ 'rel' ] == 'restore' ] [ 0 ] , session = self . session ) , alias = self . alias , session = self . session ) )
Restores an existing Hypervisor level snapshot .
6,571
def Create ( name , template , group_id , network_id , cpu = None , memory = None , alias = None , password = None , ip_address = None , storage_type = "standard" , type = "standard" , primary_dns = None , secondary_dns = None , additional_disks = [ ] , custom_fields = [ ] , ttl = None , managed_os = False , description = None , source_server_password = None , cpu_autoscale_policy_id = None , anti_affinity_policy_id = None , packages = [ ] , configuration_id = None , session = None ) : if not alias : alias = clc . v2 . Account . GetAlias ( session = session ) if not description : description = name if type . lower ( ) != "baremetal" : if not cpu or not memory : group = clc . v2 . Group ( id = group_id , alias = alias , session = session ) if not cpu and group . Defaults ( "cpu" ) : cpu = group . Defaults ( "cpu" ) elif not cpu : raise ( clc . CLCException ( "No default CPU defined" ) ) if not memory and group . Defaults ( "memory" ) : memory = group . Defaults ( "memory" ) elif not memory : raise ( clc . CLCException ( "No default Memory defined" ) ) if type . lower ( ) == "standard" and storage_type . lower ( ) not in ( "standard" , "premium" ) : raise ( clc . CLCException ( "Invalid type/storage_type combo" ) ) if type . lower ( ) == "hyperscale" and storage_type . lower ( ) != "hyperscale" : raise ( clc . CLCException ( "Invalid type/storage_type combo" ) ) if type . lower ( ) == "baremetal" : type = "bareMetal" if ttl and ttl <= 3600 : raise ( clc . CLCException ( "ttl must be greater than 3600 seconds" ) ) if ttl : ttl = clc . v2 . time_utils . SecondsToZuluTS ( int ( time . time ( ) ) + ttl ) payload = { 'name' : name , 'description' : description , 'groupId' : group_id , 'primaryDNS' : primary_dns , 'secondaryDNS' : secondary_dns , 'networkId' : network_id , 'password' : password , 'type' : type , 'customFields' : custom_fields } if type == 'bareMetal' : payload . update ( { 'configurationId' : configuration_id , 'osType' : template } ) else : payload . update ( { 'sourceServerId' : template , 'isManagedOS' : managed_os , 'ipAddress' : ip_address , 'sourceServerPassword' : source_server_password , 'cpu' : cpu , 'cpuAutoscalePolicyId' : cpu_autoscale_policy_id , 'memoryGB' : memory , 'storageType' : storage_type , 'antiAffinityPolicyId' : anti_affinity_policy_id , 'additionalDisks' : additional_disks , 'ttl' : ttl , 'packages' : packages } ) return clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'servers/%s' % ( alias ) , json . dumps ( payload ) , session = session ) , alias = alias , session = session )
Creates a new server .
6,572
def Clone ( self , network_id , name = None , cpu = None , memory = None , group_id = None , alias = None , password = None , ip_address = None , storage_type = None , type = None , primary_dns = None , secondary_dns = None , custom_fields = None , ttl = None , managed_os = False , description = None , source_server_password = None , cpu_autoscale_policy_id = None , anti_affinity_policy_id = None , packages = [ ] , count = 1 ) : if not name : name = re . search ( "%s(.+)\d{2}$" % self . alias , self . name ) . group ( 1 ) if not cpu : cpu = self . cpu if not memory : memory = self . memory if not group_id : group_id = self . group_id if not alias : alias = self . alias if not source_server_password : source_server_password = self . Credentials ( ) [ 'password' ] if not password : password = source_server_password if not storage_type : storage_type = self . storage_type if not type : type = self . type if not storage_type : storage_type = self . storage_type if not custom_fields and len ( self . custom_fields ) : custom_fields = self . custom_fields if not description : description = self . description requests_lst = [ ] for i in range ( 0 , count ) : requests_lst . append ( Server . Create ( name = name , cpu = cpu , memory = memory , group_id = group_id , network_id = network_id , alias = self . alias , password = password , ip_address = ip_address , storage_type = storage_type , type = type , primary_dns = primary_dns , secondary_dns = secondary_dns , custom_fields = custom_fields , ttl = ttl , managed_os = managed_os , description = description , source_server_password = source_server_password , cpu_autoscale_policy_id = cpu_autoscale_policy_id , anti_affinity_policy_id = anti_affinity_policy_id , packages = packages , template = self . id , session = self . session ) ) return ( sum ( requests_lst ) )
Creates one or more clones of existing server .
6,573
def ConvertToTemplate ( self , visibility , description = None , password = None ) : if visibility not in ( 'private' , 'shared' ) : raise ( clc . CLCException ( "Invalid visibility - must be private or shared" ) ) if not password : password = self . Credentials ( ) [ 'password' ] if not description : description = self . description return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'servers/%s/%s/convertToTemplate' % ( self . alias , self . id ) , json . dumps ( { "description" : description , "visibility" : visibility , "password" : password } ) , session = self . session ) , alias = self . alias , session = self . session ) )
Converts existing server to a template .
6,574
def Change ( self , cpu = None , memory = None , description = None , group_id = None ) : if group_id : groupId = group_id else : groupId = None payloads = [ ] requests = [ ] for key in ( "cpu" , "memory" , "description" , "groupId" ) : if locals ( ) [ key ] : requests . append ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . alias , self . id ) , json . dumps ( [ { "op" : "set" , "member" : key , "value" : locals ( ) [ key ] } ] ) , session = self . session ) , alias = self . alias , session = self . session ) ) if len ( requests ) : self . dirty = True return ( sum ( requests ) )
Change existing server object .
6,575
def SetPassword ( self , password ) : if self . data [ 'status' ] != "active" : raise ( clc . CLCException ( "Server must be powered on to change password" ) ) return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . alias , self . id ) , json . dumps ( [ { "op" : "set" , "member" : "password" , "value" : { "current" : self . Credentials ( ) [ 'password' ] , "password" : password } } ] ) , session = self . session ) , alias = self . alias , session = self . session ) )
Request change of password .
6,576
def Delete ( self ) : return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'DELETE' , 'servers/%s/%s' % ( self . alias , self . id ) , session = self . session ) , alias = self . alias , session = self . session ) )
Delete server .
6,577
def Get ( self , key ) : for public_ip in self . public_ips : if public_ip . id == key : return ( public_ip ) elif key == public_ip . internal : return ( public_ip )
Get public_ip by providing either the public or the internal IP address .
6,578
def Add ( self , ports , source_restrictions = None , private_ip = None ) : payload = { 'ports' : [ ] } for port in ports : if 'port_to' in port : payload [ 'ports' ] . append ( { 'protocol' : port [ 'protocol' ] , 'port' : port [ 'port' ] , 'portTo' : port [ 'port_to' ] } ) else : payload [ 'ports' ] . append ( { 'protocol' : port [ 'protocol' ] , 'port' : port [ 'port' ] } ) if source_restrictions : payload [ 'sourceRestrictions' ] = source_restrictions if private_ip : payload [ 'internalIPAddress' ] = private_ip return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'servers/%s/%s/publicIPAddresses' % ( self . server . alias , self . server . id ) , json . dumps ( payload ) , session = self . session ) , alias = self . server . alias , session = self . session ) )
Add new public_ip .
6,579
def _Load ( self , cached = True ) : if not self . data or not cached : self . data = clc . v2 . API . Call ( 'GET' , 'servers/%s/%s/publicIPAddresses/%s' % ( self . parent . server . alias , self . parent . server . id , self . id ) , session = self . session ) self . data [ '_ports' ] = self . data [ 'ports' ] self . data [ 'ports' ] = [ ] for port in self . data [ '_ports' ] : if 'portTo' in port : self . ports . append ( Port ( self , port [ 'protocol' ] , port [ 'port' ] , port [ 'portTo' ] ) ) else : self . ports . append ( Port ( self , port [ 'protocol' ] , port [ 'port' ] ) ) self . data [ '_source_restrictions' ] = self . data [ 'sourceRestrictions' ] self . data [ 'source_restrictions' ] = [ ] for source_restriction in self . data [ '_source_restrictions' ] : self . source_restrictions . append ( SourceRestriction ( self , source_restriction [ 'cidr' ] ) ) return ( self . data )
Performs a full load of all PublicIP metadata .
6,580
def Delete ( self ) : public_ip_set = [ { 'public_ipId' : o . id } for o in self . parent . public_ips if o != self ] self . parent . public_ips = [ o for o in self . parent . public_ips if o != self ] return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'DELETE' , 'servers/%s/%s/publicIPAddresses/%s' % ( self . parent . server . alias , self . parent . server . id , self . id ) , session = self . session ) , alias = self . parent . server . alias , session = self . session ) )
Delete public IP .
6,581
def Update ( self ) : return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PUT' , 'servers/%s/%s/publicIPAddresses/%s' % ( self . parent . server . alias , self . parent . server . id , self . id ) , json . dumps ( { 'ports' : [ o . ToDict ( ) for o in self . ports ] , 'sourceRestrictions' : [ o . ToDict ( ) for o in self . source_restrictions ] } ) , session = self . session ) , alias = self . parent . server . alias , session = self . session ) )
Commit current PublicIP definition to cloud .
6,582
def AddPort ( self , protocol , port , port_to = None ) : self . ports . append ( Port ( self , protocol , port , port_to ) ) return ( self . Update ( ) )
Add and commit a single port .
6,583
def AddPorts ( self , ports ) : for port in ports : if 'port_to' in port : self . ports . append ( Port ( self , port [ 'protocol' ] , port [ 'port' ] , port [ 'port_to' ] ) ) else : self . ports . append ( Port ( self , port [ 'protocol' ] , port [ 'port' ] ) ) return ( self . Update ( ) )
Create one or more port access policies .
6,584
def AddSourceRestriction ( self , cidr ) : self . source_restrictions . append ( SourceRestriction ( self , cidr ) ) return ( self . Update ( ) )
Add and commit a single source IP restriction policy .
6,585
def AddSourceRestrictions ( self , cidrs ) : for cidr in cidrs : self . source_restrictions . append ( SourceRestriction ( self , cidr ) ) return ( self . Update ( ) )
Create one or more CIDR source restriction policies .
6,586
def Delete ( self ) : self . public_ip . ports = [ o for o in self . public_ip . ports if o != self ] return ( self . public_ip . Update ( ) )
Delete this port and commit change to cloud .
6,587
def Delete ( self ) : self . public_ip . source_restrictions = [ o for o in self . public_ip . source_restrictions if o != self ] return ( self . public_ip . Update ( ) )
Delete this source restriction and commit change to cloud .
6,588
def tile_bbox ( self , tile_indices ) : ( z , x , y ) = tile_indices topleft = ( x * self . tilesize , ( y + 1 ) * self . tilesize ) bottomright = ( ( x + 1 ) * self . tilesize , y * self . tilesize ) nw = self . unproject_pixels ( topleft , z ) se = self . unproject_pixels ( bottomright , z ) return nw + se
Returns the WGS84 bbox of the specified tile
6,589
def unproject ( self , xy ) : ( x , y ) = xy lng = x / EARTH_RADIUS * RAD_TO_DEG lat = 2 * atan ( exp ( y / EARTH_RADIUS ) ) - pi / 2 * RAD_TO_DEG return ( lng , lat )
Returns the coordinates from position in meters
6,590
def from_entrypoint_output ( json_encoder , handler_output ) : response = { 'body' : '' , 'content_type' : 'text/plain' , 'headers' : { } , 'status_code' : 200 , 'body_encoding' : 'text' , } if isinstance ( handler_output , str ) : response [ 'body' ] = handler_output elif isinstance ( handler_output , tuple ) and len ( handler_output ) == 2 : response [ 'status_code' ] = handler_output [ 0 ] if isinstance ( handler_output [ 1 ] , str ) : response [ 'body' ] = handler_output [ 1 ] else : response [ 'body' ] = json_encoder ( handler_output [ 1 ] ) response [ 'content_type' ] = 'application/json' elif isinstance ( handler_output , dict ) or isinstance ( handler_output , list ) : response [ 'content_type' ] = 'application/json' response [ 'body' ] = json_encoder ( handler_output ) elif isinstance ( handler_output , Response ) : if isinstance ( handler_output . body , dict ) : response [ 'body' ] = json . dumps ( handler_output . body ) response [ 'content_type' ] = 'application/json' else : response [ 'body' ] = handler_output . body response [ 'content_type' ] = handler_output . content_type response [ 'headers' ] = handler_output . headers response [ 'status_code' ] = handler_output . status_code else : response [ 'body' ] = handler_output if isinstance ( response [ 'body' ] , bytes ) : response [ 'body' ] = base64 . b64encode ( response [ 'body' ] ) . decode ( 'ascii' ) response [ 'body_encoding' ] = 'base64' return response
Given a handler output s type generates a response towards the processor
6,591
def check_python_architecture ( pythondir , target_arch_str ) : pyth_str = subprocess . check_output ( [ pythondir + 'python' , '-c' , 'import platform; print platform.architecture()[0]' ] ) if pyth_str [ : 2 ] != target_arch_str : raise Exception ( "Wrong architecture of target python. Expected arch is" + target_arch_str )
functions check architecture of target python
6,592
def downzip ( url , destination = './sample_data/' ) : logmsg = "downloading from '" + url + "'" print ( logmsg ) logger . debug ( logmsg ) local_file_name = os . path . join ( destination , 'tmp.zip' ) urllibr . urlretrieve ( url , local_file_name ) datafile = zipfile . ZipFile ( local_file_name ) datafile . extractall ( destination ) remove ( local_file_name )
Download unzip and delete .
6,593
def checksum ( path , hashfunc = 'md5' ) : import checksumdir hash_func = checksumdir . HASH_FUNCS . get ( hashfunc ) if not hash_func : raise NotImplementedError ( '{} not implemented.' . format ( hashfunc ) ) if os . path . isdir ( path ) : return checksumdir . dirhash ( path , hashfunc = hashfunc ) hashvalues = [ ] path_list = glob . glob ( path ) logger . debug ( "path_list " + str ( path_list ) ) for path in path_list : if os . path . isfile ( path ) : hashvalues . append ( checksumdir . _filehash ( path , hashfunc = hash_func ) ) logger . debug ( str ( hashvalues ) ) hash = checksumdir . _reduce_hash ( hashvalues , hashfunc = hash_func ) return hash
Return checksum given by path . Wildcards can be used in check sum . Function is strongly dependent on checksumdir package by cakepietoast .
6,594
def Get ( self , key ) : for disk in self . disks : if disk . id == key : return ( disk ) elif key in disk . partition_paths : return ( disk )
Get disk by providing mount point or ID
6,595
def Search ( self , key ) : results = [ ] for disk in self . disks : if disk . id . lower ( ) . find ( key . lower ( ) ) != - 1 : results . append ( disk ) elif key . lower ( ) in disk . partition_paths : results . append ( disk ) return ( results )
Search disk list by partial mount point or ID
6,596
def Add ( self , size , path = None , type = "partitioned" ) : if type == "partitioned" and not path : raise ( clc . CLCException ( "Must specify path to mount new disk" ) ) disk_set = [ { 'diskId' : o . id , 'sizeGB' : o . size } for o in self . disks ] disk_set . append ( { 'sizeGB' : size , 'type' : type , 'path' : path } ) self . disks . append ( Disk ( id = int ( time . time ( ) ) , parent = self , disk_obj = { 'sizeGB' : size , 'partitionPaths' : [ path ] } , session = self . session ) ) self . size = size self . server . dirty = True return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . server . alias , self . server . id ) , json . dumps ( [ { "op" : "set" , "member" : "disks" , "value" : disk_set } ] ) , session = self . session ) , alias = self . server . alias , session = self . session ) )
Add new disk .
6,597
def Grow ( self , size ) : if size > 1024 : raise ( clc . CLCException ( "Cannot grow disk beyond 1024GB" ) ) if size <= self . size : raise ( clc . CLCException ( "New size must exceed current disk size" ) ) disk_set = [ { 'diskId' : o . id , 'sizeGB' : o . size } for o in self . parent . disks if o != self ] self . size = size disk_set . append ( { 'diskId' : self . id , 'sizeGB' : self . size } ) self . parent . server . dirty = True return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . parent . server . alias , self . parent . server . id ) , json . dumps ( [ { "op" : "set" , "member" : "disks" , "value" : disk_set } ] ) , session = self . session ) , alias = self . parent . server . alias , session = self . session ) )
Grow disk to the newly specified size .
6,598
def Delete ( self ) : disk_set = [ { 'diskId' : o . id , 'sizeGB' : o . size } for o in self . parent . disks if o != self ] self . parent . disks = [ o for o in self . parent . disks if o != self ] self . parent . server . dirty = True return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'PATCH' , 'servers/%s/%s' % ( self . parent . server . alias , self . parent . server . id ) , json . dumps ( [ { "op" : "set" , "member" : "disks" , "value" : disk_set } ] ) , session = self . session ) , alias = self . parent . server . alias , session = self . session ) )
Delete disk .
6,599
def file_digest ( source ) : hash_sha256 = hashlib . sha256 ( ) should_close = False if isinstance ( source , six . string_types ) : should_close = True source = open ( source , 'rb' ) for chunk in iter ( lambda : source . read ( _BUFFER_SIZE ) , b'' ) : hash_sha256 . update ( chunk ) if should_close : source . close ( ) return hash_sha256 . hexdigest ( )
Calculates SHA256 digest of a file .