idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
61,500
def parse ( self , data ) : graph = self . _init_graph ( ) for link in data . get_inner_links ( ) : if link . status != libcnml . libcnml . Status . WORKING : continue interface_a , interface_b = link . getLinkedInterfaces ( ) source = interface_a . ipv4 dest = interface_b . ipv4 graph . add_edge ( source , dest , weight = 1 ) return graph
Converts a CNML structure to a NetworkX Graph object which is then returned .
61,501
def parse ( self , data ) : graph = self . _init_graph ( ) if 'topology' not in data : raise ParserError ( 'Parse error, "topology" key not found' ) elif 'mid' not in data : raise ParserError ( 'Parse error, "mid" key not found' ) if 'config' in data : version_info = data [ 'config' ] [ 'olsrdVersion' ] . replace ( ' ' , '' ) . split ( '-' ) self . version = version_info [ 1 ] if 'hash_' in version_info [ - 1 ] : version_info [ - 1 ] = version_info [ - 1 ] . split ( 'hash_' ) [ - 1 ] self . revision = version_info [ - 1 ] alias_dict = { } for node in data [ 'mid' ] : local_addresses = [ alias [ 'ipAddress' ] for alias in node [ 'aliases' ] ] alias_dict [ node [ 'ipAddress' ] ] = local_addresses for link in data [ 'topology' ] : try : source = link [ 'lastHopIP' ] target = link [ 'destinationIP' ] cost = link [ 'tcEdgeCost' ] properties = { 'link_quality' : link [ 'linkQuality' ] , 'neighbor_link_quality' : link [ 'neighborLinkQuality' ] } except KeyError as e : raise ParserError ( 'Parse error, "%s" key not found' % e ) for node in [ source , target ] : if node not in alias_dict : continue graph . add_node ( node , local_addresses = alias_dict [ node ] ) if cost == float ( 'inf' ) : continue cost = float ( cost ) / 1024.0 graph . add_edge ( source , target , weight = cost , ** properties ) return graph
Converts a dict representing an OLSR 0 . 6 . x topology to a NetworkX Graph object which is then returned . Additionally checks for config data in order to determine version and revision .
61,502
def _txtinfo_to_jsoninfo ( self , data ) : data = data . replace ( 'INFINITE' , 'inf' ) lines = data . split ( '\n' ) try : start = lines . index ( 'Table: Topology' ) + 2 end = lines [ start : ] . index ( '' ) + start except ValueError : raise ParserError ( 'Unrecognized format' ) topology_lines = lines [ start : end ] topology = [ ] for line in topology_lines : values = line . split ( '\t' ) topology . append ( { 'destinationIP' : values [ 0 ] , 'lastHopIP' : values [ 1 ] , 'linkQuality' : float ( values [ 2 ] ) , 'neighborLinkQuality' : float ( values [ 3 ] ) , 'tcEdgeCost' : float ( values [ 4 ] ) * 1024.0 } ) try : start = lines . index ( 'Table: MID' ) + 2 end = lines [ start : ] . index ( '' ) + start except ValueError : raise ParserError ( 'Unrecognized format' ) mid_lines = lines [ start : end ] mid = [ ] for line in mid_lines : values = line . split ( '\t' ) node = values [ 0 ] aliases = values [ 1 ] . split ( ';' ) mid . append ( { 'ipAddress' : node , 'aliases' : [ { 'ipAddress' : alias } for alias in aliases ] } ) return { 'topology' : topology , 'mid' : mid }
converts olsr 1 txtinfo format to jsoninfo
61,503
def check_for_launchpad ( old_vendor , name , urls ) : if old_vendor != "pypi" : return '' for url in urls : try : return re . match ( r"https?://launchpad.net/([\w.\-]+)" , url ) . groups ( ) [ 0 ] except AttributeError : continue return ''
Check if the project is hosted on launchpad .
61,504
def check_switch_vendor ( old_vendor , name , urls , _depth = 0 ) : if _depth > 3 : return "" new_name = check_for_launchpad ( old_vendor , name , urls ) if new_name : return "launchpad" , new_name return "" , ""
Check if the project should switch vendors . E . g project pushed on pypi but changelog on launchpad .
61,505
def check_pil ( func ) : def __wrapper ( * args , ** kwargs ) : root = kwargs . get ( 'root' ) if not Image : if root and root . get_opt ( 'warn' ) : warn ( "Images manipulation require PIL" ) return 'none' return func ( * args , ** kwargs ) return __wrapper
PIL module checking decorator .
61,506
def _mix ( color1 , color2 , weight = 0.5 , ** kwargs ) : weight = float ( weight ) c1 = color1 . value c2 = color2 . value p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight w = p * 2 - 1 a = c1 [ 3 ] - c2 [ 3 ] w1 = ( ( w if ( w * a == - 1 ) else ( w + a ) / ( 1 + w * a ) ) + 1 ) / 2.0 w2 = 1 - w1 q = [ w1 , w1 , w1 , p ] r = [ w2 , w2 , w2 , 1 - p ] return ColorValue ( [ c1 [ i ] * q [ i ] + c2 [ i ] * r [ i ] for i in range ( 4 ) ] )
Mixes two colors together .
61,507
def _hsla ( h , s , l , a , ** kwargs ) : res = colorsys . hls_to_rgb ( float ( h ) , float ( l ) , float ( s ) ) return ColorValue ( [ x * 255.0 for x in res ] + [ float ( a ) ] )
HSL with alpha channel color value .
61,508
def _hue ( color , ** kwargs ) : h = colorsys . rgb_to_hls ( * [ x / 255.0 for x in color . value [ : 3 ] ] ) [ 0 ] return NumberValue ( h * 360.0 )
Get hue value of HSL color .
61,509
def _lightness ( color , ** kwargs ) : l = colorsys . rgb_to_hls ( * [ x / 255.0 for x in color . value [ : 3 ] ] ) [ 1 ] return NumberValue ( ( l * 100 , '%' ) )
Get lightness value of HSL color .
61,510
def _saturation ( color , ** kwargs ) : s = colorsys . rgb_to_hls ( * [ x / 255.0 for x in color . value [ : 3 ] ] ) [ 2 ] return NumberValue ( ( s * 100 , '%' ) )
Get saturation value of HSL color .
61,511
def load ( path , cache = None , precache = False ) : parser = Stylesheet ( cache ) return parser . load ( path , precache = precache )
Parse from file .
61,512
def parse ( self , target ) : if isinstance ( target , ContentNode ) : if target . name : self . parent = target self . name . parse ( self ) self . name += target . name target . ruleset . append ( self ) self . root . cache [ 'rset' ] [ str ( self . name ) . split ( ) [ 0 ] ] . add ( self ) super ( Ruleset , self ) . parse ( target )
Parse nested rulesets and save it in cache .
61,513
def parse ( self , target ) : if not isinstance ( target , Node ) : parent = ContentNode ( None , None , [ ] ) parent . parse ( target ) target = parent super ( Declaration , self ) . parse ( target ) self . name = str ( self . data [ 0 ] ) while isinstance ( target , Declaration ) : self . name = '-' . join ( ( str ( target . data [ 0 ] ) , self . name ) ) target = target . parent self . expr = ' ' . join ( str ( n ) for n in self . data [ 2 : ] if not isinstance ( n , Declaration ) ) if self . expr : target . declareset . append ( self )
Parse nested declaration .
61,514
def parse ( self , target ) : super ( VarDefinition , self ) . parse ( target ) if isinstance ( self . parent , ParseNode ) : self . parent . ctx . update ( { self . name : self . expression . value } ) self . root . set_var ( self )
Update root and parent context .
61,515
def set_var ( self , vardef ) : if not ( vardef . default and self . cache [ 'ctx' ] . get ( vardef . name ) ) : self . cache [ 'ctx' ] [ vardef . name ] = vardef . expression . value
Set variable to global stylesheet context .
61,516
def set_opt ( self , name , value ) : self . cache [ 'opts' ] [ name ] = value if name == 'compress' : self . cache [ 'delims' ] = self . def_delims if not value else ( '' , '' , '' )
Set option .
61,517
def update ( self , cache ) : self . cache [ 'delims' ] = cache . get ( 'delims' ) self . cache [ 'opts' ] . update ( cache . get ( 'opts' ) ) self . cache [ 'rset' ] . update ( cache . get ( 'rset' ) ) self . cache [ 'mix' ] . update ( cache . get ( 'mix' ) ) map ( self . set_var , cache [ 'ctx' ] . values ( ) )
Update self cache from other .
61,518
def scan ( src ) : assert isinstance ( src , ( unicode_ , bytes_ ) ) try : nodes = STYLESHEET . parseString ( src , parseAll = True ) return nodes except ParseBaseException : err = sys . exc_info ( ) [ 1 ] print ( err . line , file = sys . stderr ) print ( " " * ( err . column - 1 ) + "^" , file = sys . stderr ) print ( err , file = sys . stderr ) sys . exit ( 1 )
Scan scss from string and return nodes .
61,519
def loads ( self , src ) : assert isinstance ( src , ( unicode_ , bytes_ ) ) nodes = self . scan ( src . strip ( ) ) self . parse ( nodes ) return '' . join ( map ( str , nodes ) )
Compile css from scss string .
61,520
def load ( self , f , precache = None ) : precache = precache or self . get_opt ( 'cache' ) or False nodes = None if isinstance ( f , file_ ) : path = os . path . abspath ( f . name ) else : path = os . path . abspath ( f ) f = open ( f ) cache_path = os . path . splitext ( path ) [ 0 ] + '.ccss' if precache and os . path . exists ( cache_path ) : ptime = os . path . getmtime ( cache_path ) ttime = os . path . getmtime ( path ) if ptime > ttime : dump = open ( cache_path , 'rb' ) . read ( ) nodes = pickle . loads ( dump ) if not nodes : src = f . read ( ) nodes = self . scan ( src . strip ( ) ) if precache : f = open ( cache_path , 'wb' ) pickle . dump ( nodes , f , protocol = 1 ) self . parse ( nodes ) return '' . join ( map ( str , nodes ) )
Compile scss from file . File is string path of file object .
61,521
def load_config ( filename , filepath = '' ) : FILE = path . join ( filepath , filename ) try : cfg . read ( FILE ) global _loaded _loaded = True except : print ( "configfile not found." )
Loads config file
61,522
def emoji ( string ) : __entities = { } __value = [ ] __mean = [ ] __location = [ ] flag = True try : pro_string = str ( string ) for pos , ej in enumerate ( pro_string ) : if ej in emo_unicode . UNICODE_EMO : try : __value . append ( ej ) __mean . append ( emo_unicode . UNICODE_EMO [ ej ] ) __location . append ( [ pos , pos ] ) except Exception as e : flag = False __entities . append ( { "flag" : False } ) return __entities except Exception as e : flag = False __entities . append ( { "flag" : False } ) return __entities if len ( __value ) < 1 : flag = False __entities = { 'value' : __value , 'mean' : __mean , 'location' : __location , 'flag' : flag } return __entities
emot . emoji is use to detect emoji from text
61,523
def emoticons ( string ) : __entities = [ ] flag = True try : pattern = u'(' + u'|' . join ( k for k in emo_unicode . EMOTICONS ) + u')' __entities = [ ] __value = [ ] __location = [ ] matches = re . finditer ( r"%s" % pattern , str ( string ) ) for et in matches : __value . append ( et . group ( ) . strip ( ) ) __location . append ( [ et . start ( ) , et . end ( ) ] ) __mean = [ ] for each in __value : __mean . append ( emo_unicode . EMOTICONS_EMO [ each ] ) if len ( __value ) < 1 : flag = False __entities = { 'value' : __value , 'location' : __location , 'mean' : __mean , 'flag' : flag } except Exception as e : __entities = [ { 'flag' : False } ] return __entities return __entities
emot . emoticons is use to detect emoticons from text
61,524
def init_app ( self , app , add_context_processor = True ) : if not hasattr ( app , 'login_manager' ) : self . login_manager . init_app ( app , add_context_processor = add_context_processor ) self . login_manager . login_message = None self . login_manager . needs_refresh_message = None self . login_manager . unauthorized_handler ( self . unauthorized_callback )
Initialize with app configuration
61,525
def login_url ( self , params = None , ** kwargs ) : kwargs . setdefault ( 'response_type' , 'code' ) kwargs . setdefault ( 'access_type' , 'online' ) if 'prompt' not in kwargs : kwargs . setdefault ( 'approval_prompt' , 'auto' ) scopes = kwargs . pop ( 'scopes' , self . scopes . split ( ',' ) ) if USERINFO_PROFILE_SCOPE not in scopes : scopes . append ( USERINFO_PROFILE_SCOPE ) redirect_uri = kwargs . pop ( 'redirect_uri' , self . redirect_uri ) state = self . sign_params ( params or { } ) return GOOGLE_OAUTH2_AUTH_URL + '?' + urlencode ( dict ( client_id = self . client_id , scope = ' ' . join ( scopes ) , redirect_uri = redirect_uri , state = state , ** kwargs ) )
Return login url with params encoded in state
61,526
def unauthorized_callback ( self ) : return redirect ( self . login_url ( params = dict ( next = request . url ) ) )
Redirect to login url with next param set as request . url
61,527
def get_access_token ( self , refresh_token ) : token = requests . post ( GOOGLE_OAUTH2_TOKEN_URL , data = dict ( refresh_token = refresh_token , grant_type = 'refresh_token' , client_id = self . client_id , client_secret = self . client_secret , ) ) . json ( ) if not token or token . get ( 'error' ) : return return token
Use a refresh token to obtain a new access token
61,528
def oauth2callback ( self , view_func ) : @ wraps ( view_func ) def decorated ( * args , ** kwargs ) : params = { } if 'state' in request . args : params . update ( ** self . parse_state ( request . args . get ( 'state' ) ) ) if params . pop ( 'sig' , None ) != make_secure_token ( ** params ) : return self . login_manager . unauthorized ( ) code = request . args . get ( 'code' ) if code : token = self . exchange_code ( code , url_for ( request . endpoint , _external = True , _scheme = self . redirect_scheme , ) , ) userinfo = self . get_userinfo ( token [ 'access_token' ] ) params . update ( token = token , userinfo = userinfo ) else : if params : params . update ( dict ( request . args . items ( ) ) ) else : return return view_func ( ** params ) return decorated
Decorator for OAuth2 callback . Calls GoogleLogin . login then passes results to view_func .
61,529
def complete ( text , state ) : for cmd in COMMANDS : if cmd . startswith ( text ) : if not state : return cmd else : state -= 1
Auto complete scss constructions in interactive mode .
61,530
def validate_args ( self ) : from . . mixins import ModelMixin for arg in ( "instance" , "decider" , "identifier" , "fields" , "default_language" ) : if getattr ( self , arg ) is None : raise AttributeError ( "%s must not be None" % arg ) if not isinstance ( self . instance , ( ModelMixin , ) ) : raise ImproperlyConfigured ( '"instance" argument must be a Linguist model' ) if not issubclass ( self . decider , ( models . Model , ) ) : raise ImproperlyConfigured ( '"decider" argument must be a valid Django model' )
Validates arguments .
61,531
def active_language ( self ) : if self . _language is not None : return self . _language current = utils . get_language ( ) if current in self . supported_languages : return current return self . default_language
Returns active language .
61,532
def translation_instances ( self ) : return [ instance for k , v in six . iteritems ( self . instance . _linguist_translations ) for instance in v . values ( ) ]
Returns translation instances .
61,533
def get_cache ( self , instance , translation = None , language = None , field_name = None , field_value = None , ) : is_new = bool ( instance . pk is None ) try : cached_obj = instance . _linguist_translations [ field_name ] [ language ] if not cached_obj . field_name : cached_obj . field_name = field_name if not cached_obj . language : cached_obj . language = language if not cached_obj . identifier : cached_obj . identifier = self . instance . linguist_identifier except KeyError : cached_obj = None if not is_new : if translation is None : try : translation = self . decider . objects . get ( identifier = self . instance . linguist_identifier , object_id = self . instance . pk , language = language , field_name = field_name , ) except self . decider . DoesNotExist : pass if cached_obj is None : if translation is not None : cached_obj = CachedTranslation . from_object ( translation ) else : cached_obj = CachedTranslation ( instance = instance , language = language , field_name = field_name , field_value = field_value , ) instance . _linguist_translations [ cached_obj . field_name ] [ cached_obj . language ] = cached_obj return cached_obj
Returns translation from cache .
61,534
def set_cache ( self , instance = None , translation = None , language = None , field_name = None , field_value = None , ) : if instance is not None and translation is not None : cached_obj = CachedTranslation . from_object ( translation ) instance . _linguist_translations [ translation . field_name ] [ translation . language ] = cached_obj return cached_obj if instance is None : instance = self . instance cached_obj = self . get_cache ( instance , translation = translation , field_value = field_value , language = language , field_name = field_name , ) if field_value is None and cached_obj . field_value : cached_obj . deleted = True if field_value != cached_obj . field_value : cached_obj . has_changed = True cached_obj . field_value = field_value return cached_obj
Add a new translation into the cache .
61,535
def _filter_or_exclude ( self , negate , * args , ** kwargs ) : from . models import Translation new_args = self . get_cleaned_args ( args ) new_kwargs = self . get_cleaned_kwargs ( kwargs ) translation_args = self . get_translation_args ( args ) translation_kwargs = self . get_translation_kwargs ( kwargs ) has_linguist_args = self . has_linguist_args ( args ) has_linguist_kwargs = self . has_linguist_kwargs ( kwargs ) if translation_args or translation_kwargs : ids = list ( set ( Translation . objects . filter ( * translation_args , ** translation_kwargs ) . values_list ( "object_id" , flat = True ) ) ) if ids : new_kwargs [ "id__in" ] = ids has_kwargs = has_linguist_kwargs and not ( new_kwargs or new_args ) has_args = has_linguist_args and not ( new_args or new_kwargs ) if has_kwargs or has_args : return self . _clone ( ) . none ( ) return super ( QuerySetMixin , self ) . _filter_or_exclude ( negate , * new_args , ** new_kwargs )
Overrides default behavior to handle linguist fields .
61,536
def has_linguist_kwargs ( self , kwargs ) : for k in kwargs : if self . is_linguist_lookup ( k ) : return True return False
Parses the given kwargs and returns True if they contain linguist lookups .
61,537
def has_linguist_args ( self , args ) : linguist_args = [ ] for arg in args : condition = self . _get_linguist_condition ( arg ) if condition : linguist_args . append ( condition ) return bool ( linguist_args )
Parses the given args and returns True if they contain linguist lookups .
61,538
def get_translation_args ( self , args ) : translation_args = [ ] for arg in args : condition = self . _get_linguist_condition ( arg , transform = True ) if condition : translation_args . append ( condition ) return translation_args
Returns linguist args from model args .
61,539
def is_linguist_lookup ( self , lookup ) : field = utils . get_field_name_from_lookup ( lookup ) if ( field not in self . concrete_field_names and field in self . linguist_field_names ) : return True return False
Returns true if the given lookup is a valid linguist lookup .
61,540
def _get_linguist_condition ( self , condition , reverse = False , transform = False ) : if isinstance ( condition , Q ) : children = [ ] for child in condition . children : parsed = self . _get_linguist_condition ( condition = child , reverse = reverse , transform = transform ) if parsed is not None : if ( isinstance ( parsed , Q ) and parsed . children ) or isinstance ( parsed , tuple ) : children . append ( parsed ) new_condition = copy . deepcopy ( condition ) new_condition . children = children return new_condition lookup , value = condition is_linguist = self . is_linguist_lookup ( lookup ) if transform and is_linguist : return Q ( ** utils . get_translation_lookup ( self . model . _linguist . identifier , lookup , value ) ) if ( reverse and not is_linguist ) or ( not reverse and is_linguist ) : return condition
Parses Q tree and returns linguist lookups or model lookups if reverse is True .
61,541
def get_cleaned_args ( self , args ) : if not args : return args cleaned_args = [ ] for arg in args : condition = self . _get_linguist_condition ( arg , True ) if condition : cleaned_args . append ( condition ) return cleaned_args
Returns positional arguments for related model query .
61,542
def get_cleaned_kwargs ( self , kwargs ) : cleaned_kwargs = kwargs . copy ( ) if kwargs is not None : for k in kwargs : if self . is_linguist_lookup ( k ) : del cleaned_kwargs [ k ] return cleaned_kwargs
Returns concrete field lookups .
61,543
def with_translations ( self , ** kwargs ) : force = kwargs . pop ( "force" , False ) if self . _prefetch_translations_done and force is False : return self self . _prefetched_translations_cache = utils . get_grouped_translations ( self , ** kwargs ) self . _prefetch_translations_done = True return self . _clone ( )
Prefetches translations .
61,544
def available_languages ( self ) : from . models import Translation return ( Translation . objects . filter ( identifier = self . linguist_identifier , object_id = self . pk ) . values_list ( "language" , flat = True ) . distinct ( ) . order_by ( "language" ) )
Returns available languages .
61,545
def delete_translations ( self , language = None ) : from . models import Translation return Translation . objects . delete_translations ( obj = self , language = language )
Deletes related translations .
61,546
def override_language ( self , language ) : previous_language = self . _linguist . language self . _linguist . language = language yield self . _linguist . language = previous_language
Context manager to override the instance language .
61,547
def validate_meta ( meta ) : if not isinstance ( meta , ( dict , ) ) : raise TypeError ( 'Model Meta "linguist" must be a dict' ) required_keys = ( "identifier" , "fields" ) for key in required_keys : if key not in meta : raise KeyError ( 'Model Meta "linguist" dict requires %s to be defined' , key ) if not isinstance ( meta [ "fields" ] , ( list , tuple ) ) : raise ImproperlyConfigured ( "Linguist Meta's fields attribute must be a list or tuple" )
Validates Linguist Meta attribute .
61,548
def default_value_setter ( field ) : def default_value_func_setter ( self , value ) : localized_field = utils . build_localized_field_name ( field , self . _linguist . active_language ) setattr ( self , localized_field , value ) return default_value_func_setter
When setting to the name of the field itself the value in the current language will be set .
61,549
def field_factory ( base_class ) : from . fields import TranslationField class TranslationFieldField ( TranslationField , base_class ) : pass TranslationFieldField . __name__ = "Translation%s" % base_class . __name__ return TranslationFieldField
Takes a field base class and wrap it with TranslationField class .
61,550
def create_translation_field ( translated_field , language ) : cls_name = translated_field . __class__ . __name__ if not isinstance ( translated_field , tuple ( SUPPORTED_FIELDS . keys ( ) ) ) : raise ImproperlyConfigured ( "%s is not supported by Linguist." % cls_name ) translation_class = field_factory ( translated_field . __class__ ) kwargs = get_translation_class_kwargs ( translated_field . __class__ ) return translation_class ( translated_field = translated_field , language = language , ** kwargs )
Takes the original field a given language a decider model and return a Field class for model .
61,551
def connect ( self ) : if self . connected : raise RuntimeError ( '{} is connected already' . format ( self . __class__ . __name__ ) ) if self . closed : raise RuntimeError ( '{} is closed already' . format ( self . __class__ . __name__ ) ) self . connected = True self . _connect ( )
Connect to the drone .
61,552
def close ( self ) : if not self . connected : return if self . closed : return self . closed = True self . _close ( )
Exit all threads and disconnect the drone .
61,553
def _set_flags ( self , ** flags ) : self . _flags = enum . IntEnum ( '_flags' , flags ) self . __dict__ . update ( self . _flags . __members__ ) self . _patch_flag_doc ( )
Set the flags of this argument .
61,554
def delete_translations ( sender , instance , ** kwargs ) : if issubclass ( sender , ( ModelMixin , ) ) : instance . _linguist . decider . objects . filter ( identifier = instance . linguist_identifier , object_id = instance . pk ) . delete ( )
Deletes related instance s translations when instance is deleted .
61,555
def draw_tree ( node , child_iter = lambda n : n . children , text_str = str ) : return LeftAligned ( traverse = Traversal ( get_text = text_str , get_children = child_iter ) , draw = LegacyStyle ( ) ) ( node )
Support asciitree 0 . 2 API .
61,556
def get_language ( ) : lang = _get_language ( ) if not lang : return get_fallback_language ( ) langs = [ l [ 0 ] for l in settings . SUPPORTED_LANGUAGES ] if lang not in langs and "-" in lang : lang = lang . split ( "-" ) [ 0 ] if lang in langs : return lang return settings . DEFAULT_LANGUAGE
Returns an active language code that is guaranteed to be in settings . SUPPORTED_LANGUAGES .
61,557
def activate_language ( instances , language ) : language = ( language if language in get_supported_languages ( ) else get_fallback_language ( ) ) for instance in instances : instance . activate_language ( language )
Activates the given language for the given instances .
61,558
def load_class ( class_path , setting_name = None ) : if not isinstance ( class_path , six . string_types ) : try : class_path , app_label = class_path except : if setting_name : raise exceptions . ImproperlyConfigured ( CLASS_PATH_ERROR % ( setting_name , setting_name ) ) else : raise exceptions . ImproperlyConfigured ( CLASS_PATH_ERROR % ( "this setting" , "It" ) ) try : class_module , class_name = class_path . rsplit ( "." , 1 ) except ValueError : if setting_name : txt = "%s isn't a valid module. Check your %s setting" % ( class_path , setting_name , ) else : txt = "%s isn't a valid module." % class_path raise exceptions . ImproperlyConfigured ( txt ) try : mod = import_module ( class_module ) except ImportError as e : if setting_name : txt = 'Error importing backend %s: "%s". Check your %s setting' % ( class_module , e , setting_name , ) else : txt = 'Error importing backend %s: "%s".' % ( class_module , e ) raise exceptions . ImproperlyConfigured ( txt ) try : clazz = getattr ( mod , class_name ) except AttributeError : if setting_name : txt = ( 'Backend module "%s" does not define a "%s" class. Check' " your %s setting" % ( class_module , class_name , setting_name ) ) else : txt = 'Backend module "%s" does not define a "%s" class.' % ( class_module , class_name , ) raise exceptions . ImproperlyConfigured ( txt ) return clazz
Loads a class given a class_path . The setting value may be a string or a tuple . The setting_name parameter is only there for pretty error output and therefore is optional .
61,559
def get_translation_lookup ( identifier , field , value ) : parts = field . split ( "__" ) transformers = parts [ 1 : ] if len ( parts ) > 1 else None field_name = parts [ 0 ] language = get_fallback_language ( ) name_parts = parts [ 0 ] . split ( "_" ) if len ( name_parts ) > 1 : supported_languages = get_supported_languages ( ) last_part = name_parts [ - 1 ] if last_part in supported_languages : field_name = "_" . join ( name_parts [ : - 1 ] ) language = last_part else : field_name = "_" . join ( name_parts ) value_lookup = ( "field_value" if transformers is None else "field_value__%s" % "__" . join ( transformers ) ) lookup = { "field_name" : field_name , "identifier" : identifier , "language" : language } lookup [ value_lookup ] = value return lookup
Mapper that takes a language field its value and returns the related lookup for Translation model .
61,560
def get_grouped_translations ( instances , ** kwargs ) : grouped_translations = collections . defaultdict ( list ) if not instances : return grouped_translations if not isinstance ( instances , collections . Iterable ) : instances = [ instances ] if isinstance ( instances , QuerySet ) : model = instances . model else : model = instances [ 0 ] . _meta . model instances_ids = [ ] for instance in instances : instances_ids . append ( instance . pk ) if instance . _meta . model != model : raise Exception ( "You cannot use different model instances, only one authorized." ) from . models import Translation from . mixins import ModelMixin decider = model . _meta . linguist . get ( "decider" , Translation ) identifier = model . _meta . linguist . get ( "identifier" , None ) chunks_length = kwargs . get ( "chunks_length" , None ) populate_missing = kwargs . get ( "populate_missing" , True ) if identifier is None : raise Exception ( 'You must define Linguist "identifier" meta option' ) lookup = dict ( identifier = identifier ) for kwarg in ( "field_names" , "languages" ) : value = kwargs . get ( kwarg , None ) if value is not None : if not isinstance ( value , ( list , tuple ) ) : value = [ value ] lookup [ "%s__in" % kwarg [ : - 1 ] ] = value if chunks_length is not None : translations_qs = [ ] for ids in utils . chunks ( instances_ids , chunks_length ) : ids_lookup = copy . copy ( lookup ) ids_lookup [ "object_id__in" ] = ids translations_qs . append ( decider . objects . filter ( ** ids_lookup ) ) translations = itertools . chain . from_iterable ( translations_qs ) else : lookup [ "object_id__in" ] = instances_ids translations = decider . objects . filter ( ** lookup ) for translation in translations : grouped_translations [ translation . object_id ] . append ( translation ) return grouped_translations
Takes instances and returns grouped translations ready to be set in cache .
61,561
def get_free_udp_port ( ) : import socket sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) sock . bind ( ( 'localhost' , 0 ) ) addr = sock . getsockname ( ) sock . close ( ) return addr [ 1 ]
Get a free UDP port .
61,562
def get_available_languages ( self , obj ) : return obj . available_languages if obj is not None else self . model . objects . none ( )
Returns available languages for current object .
61,563
def languages_column ( self , obj ) : languages = self . get_available_languages ( obj ) return '<span class="available-languages">{0}</span>' . format ( " " . join ( languages ) )
Adds languages columns .
61,564
def prefetch_translations ( instances , ** kwargs ) : from . mixins import ModelMixin if not isinstance ( instances , collections . Iterable ) : instances = [ instances ] populate_missing = kwargs . get ( "populate_missing" , True ) grouped_translations = utils . get_grouped_translations ( instances , ** kwargs ) if not grouped_translations and populate_missing : for instance in instances : instance . populate_missing_translations ( ) for instance in instances : if ( issubclass ( instance . __class__ , ModelMixin ) and instance . pk in grouped_translations ) : for translation in grouped_translations [ instance . pk ] : instance . _linguist . set_cache ( instance = instance , translation = translation ) if populate_missing : instance . populate_missing_translations ( )
Prefetches translations for the given instances . Can be useful for a list of instances .
61,565
def get_translations ( self , obj , language = None ) : lookup = { "identifier" : obj . linguist_identifier , "object_id" : obj . pk } if language is not None : lookup [ "language" ] = language return self . get_queryset ( ) . filter ( ** lookup )
Shorcut method to retrieve translations for a given object .
61,566
def takeoff ( self ) : self . send ( at . REF ( at . REF . input . start ) )
Sends the takeoff command .
61,567
def emergency ( self ) : self . send ( at . REF ( at . REF . input . select ) )
Sends the emergency command .
61,568
def move ( self , * , forward = 0 , backward = 0 , left = 0 , right = 0 , up = 0 , down = 0 , cw = 0 , ccw = 0 ) : self . _move ( roll = right - left , pitch = backward - forward , gaz = up - down , yaw = cw - ccw )
Moves the drone .
61,569
def encode ( number , checksum = False , split = 0 ) : number = int ( number ) if number < 0 : raise ValueError ( "number '%d' is not a positive integer" % number ) split = int ( split ) if split < 0 : raise ValueError ( "split '%d' is not a positive integer" % split ) check_symbol = '' if checksum : check_symbol = encode_symbols [ number % check_base ] if number == 0 : return '0' + check_symbol symbol_string = '' while number > 0 : remainder = number % base number //= base symbol_string = encode_symbols [ remainder ] + symbol_string symbol_string = symbol_string + check_symbol if split : chunks = [ ] for pos in range ( 0 , len ( symbol_string ) , split ) : chunks . append ( symbol_string [ pos : pos + split ] ) symbol_string = '-' . join ( chunks ) return symbol_string
Encode an integer into a symbol string .
61,570
def decode ( symbol_string , checksum = False , strict = False ) : symbol_string = normalize ( symbol_string , strict = strict ) if checksum : symbol_string , check_symbol = symbol_string [ : - 1 ] , symbol_string [ - 1 ] number = 0 for symbol in symbol_string : number = number * base + decode_symbols [ symbol ] if checksum : check_value = decode_symbols [ check_symbol ] modulo = number % check_base if check_value != modulo : raise ValueError ( "invalid check symbol '%s' for string '%s'" % ( check_symbol , symbol_string ) ) return number
Decode an encoded symbol string .
61,571
def normalize ( symbol_string , strict = False ) : if isinstance ( symbol_string , string_types ) : if not PY3 : try : symbol_string = symbol_string . encode ( 'ascii' ) except UnicodeEncodeError : raise ValueError ( "string should only contain ASCII characters" ) else : raise TypeError ( "string is of invalid type %s" % symbol_string . __class__ . __name__ ) norm_string = symbol_string . replace ( '-' , '' ) . translate ( normalize_symbols ) . upper ( ) if not valid_symbols . match ( norm_string ) : raise ValueError ( "string '%s' contains invalid characters" % norm_string ) if strict and norm_string != symbol_string : raise ValueError ( "string '%s' requires normalization" % symbol_string ) return norm_string
Normalize an encoded symbol string .
61,572
def setup_requires ( ) : from pkg_resources import parse_version required = [ 'cython>=0.24.0' ] numpy_requirement = 'numpy>=1.7.1' try : import numpy except Exception : required . append ( numpy_requirement ) else : if parse_version ( numpy . __version__ ) < parse_version ( '1.7.1' ) : required . append ( numpy_requirement ) return required
Return required packages
61,573
def _build_block_context ( template , context ) : if BLOCK_CONTEXT_KEY not in context . render_context : context . render_context [ BLOCK_CONTEXT_KEY ] = BlockContext ( ) block_context = context . render_context [ BLOCK_CONTEXT_KEY ] for node in template . nodelist : if isinstance ( node , ExtendsNode ) : compiled_parent = node . get_parent ( context ) block_context . add_blocks ( { n . name : n for n in compiled_parent . nodelist . get_nodes_by_type ( BlockNode ) } ) _build_block_context ( compiled_parent , context ) return compiled_parent if not isinstance ( node , TextNode ) : break
Populate the block context with BlockNodes from parent templates .
61,574
def _render_template_block_nodelist ( nodelist , block_name , context ) : for node in nodelist : if isinstance ( node , BlockNode ) : context . render_context [ BLOCK_CONTEXT_KEY ] . push ( node . name , node ) if node . name == block_name : return node . render ( context ) for attr in node . child_nodelists : try : new_nodelist = getattr ( node , attr ) except AttributeError : continue try : return _render_template_block_nodelist ( new_nodelist , block_name , context ) except BlockNotFound : continue raise BlockNotFound ( "block with name '%s' does not exist" % block_name )
Recursively iterate over a node to find the wanted block .
61,575
def render_block_to_string ( template_name , block_name , context = None ) : if isinstance ( template_name , ( tuple , list ) ) : t = loader . select_template ( template_name ) else : t = loader . get_template ( template_name ) context = context or { } if isinstance ( t , DjangoTemplate ) : return django_render_block ( t , block_name , context ) elif isinstance ( t , Jinja2Template ) : from render_block . jinja2 import jinja2_render_block return jinja2_render_block ( t , block_name , context ) else : raise UnsupportedEngine ( 'Can only render blocks from the Django template backend.' )
Loads the given template_name and renders the given block with the given dictionary as context . Returns a string .
61,576
def get_host_path ( root , path , instance = None ) : r_val = resolve_value ( path ) if isinstance ( r_val , dict ) : r_instance = instance or 'default' r_path = resolve_value ( r_val . get ( r_instance ) ) if not r_path : raise ValueError ( "No path defined for instance {0}." . format ( r_instance ) ) else : r_path = r_val r_root = resolve_value ( root ) if r_path and r_root and ( r_path [ 0 ] != posixpath . sep ) : return posixpath . join ( r_root , r_path ) return r_path
Generates the host path for a container volume . If the given path is a dictionary uses the entry of the instance name .
61,577
def run_actions ( self , actions ) : policy = self . _policy for action in actions : config_id = action . config_id config_type = config_id . config_type client_config = policy . clients [ action . client_name ] client = client_config . get_client ( ) c_map = policy . container_maps [ config_id . map_name ] if config_type == ItemType . CONTAINER : config = c_map . get_existing ( config_id . config_name ) item_name = policy . cname ( config_id . map_name , config_id . config_name , config_id . instance_name ) elif config_type == ItemType . VOLUME : a_parent_name = config_id . config_name if c_map . use_attached_parent_name else None item_name = policy . aname ( config_id . map_name , config_id . instance_name , parent_name = a_parent_name ) if client_config . features [ 'volumes' ] : config = c_map . get_existing_volume ( config_id . config_name ) else : config = c_map . get_existing ( config_id . config_name ) elif config_type == ItemType . NETWORK : config = c_map . get_existing_network ( config_id . config_name ) item_name = policy . nname ( config_id . map_name , config_id . config_name ) elif config_type == ItemType . IMAGE : config = None item_name = format_image_tag ( config_id . config_name , config_id . instance_name ) else : raise ValueError ( "Invalid configuration type." , config_id . config_type ) for action_type in action . action_types : try : a_method = self . action_methods [ ( config_type , action_type ) ] except KeyError : raise ActionTypeException ( config_id , action_type ) action_config = ActionConfig ( action . client_name , action . config_id , client_config , client , c_map , config ) try : res = a_method ( action_config , item_name , ** action . extra_data ) except Exception : exc_info = sys . exc_info ( ) raise ActionException ( exc_info , action . client_name , config_id , action_type ) if res is not None : yield ActionOutput ( action . client_name , config_id , action_type , res )
Runs the given lists of attached actions and instance actions on the client .
61,578
def from_client ( cls , client ) : if hasattr ( client , 'client_configuration' ) : return client . client_configuration kwargs = { 'client' : client } for attr in cls . init_kwargs : if hasattr ( client , attr ) : kwargs [ attr ] = getattr ( client , attr ) if hasattr ( client , 'api_version' ) : kwargs [ 'version' ] = client . api_version return cls ( ** kwargs )
Constructs a configuration object from an existing client instance . If the client has already been created with a configuration object returns that instance .
61,579
def get_init_kwargs ( self ) : init_kwargs = { } for k in self . init_kwargs : if k in self . core_property_set : init_kwargs [ k ] = getattr ( self , k ) elif k in self : init_kwargs [ k ] = self [ k ] return init_kwargs
Generates keyword arguments for creating a new Docker client instance .
61,580
def get_client ( self ) : client = self . _client if not client : self . _client = client = self . client_constructor ( ** self . get_init_kwargs ( ) ) client . client_configuration = self updated_version = getattr ( client , 'api_version' , None ) if updated_version : self . version = updated_version return client
Retrieves or creates a client instance from this configuration object . If instantiated from this configuration the resulting object is also cached in the property client and a reference to this configuration is stored on the client object .
61,581
def exec_commands ( self , action , c_name , run_cmds , ** kwargs ) : client = action . client exec_results = [ ] for run_cmd in run_cmds : cmd = run_cmd . cmd cmd_user = run_cmd . user log . debug ( "Creating exec command in container %s with user %s: %s." , c_name , cmd_user , cmd ) ec_kwargs = self . get_exec_create_kwargs ( action , c_name , cmd , cmd_user ) create_result = client . exec_create ( ** ec_kwargs ) if create_result : e_id = create_result [ 'Id' ] log . debug ( "Starting exec command with id %s." , e_id ) es_kwargs = self . get_exec_start_kwargs ( action , c_name , e_id ) client . exec_start ( ** es_kwargs ) exec_results . append ( create_result ) else : log . debug ( "Exec command was created, but did not return an id. Assuming that it has been started." ) if exec_results : return exec_results return None
Runs a single command inside a container .
61,582
def exec_container_commands ( self , action , c_name , ** kwargs ) : config_cmds = action . config . exec_commands if not config_cmds : return None return self . exec_commands ( action , c_name , run_cmds = config_cmds )
Runs all configured commands of a container configuration inside the container instance .
61,583
def prepare_path ( path , replace_space , replace_sep , expandvars , expanduser ) : r_path = path if expandvars : r_path = os . path . expandvars ( r_path ) if expanduser : r_path = os . path . expanduser ( r_path ) if replace_sep and os . sep != posixpath . sep : r_path = r_path . replace ( os . path . sep , posixpath . sep ) if replace_space : r_path = r_path . replace ( ' ' , '\\ ' ) return r_path
Performs os . path replacement operations on a path string .
61,584
def format_command ( cmd , shell = False ) : def _split_cmd ( ) : line = None for part in cmd . split ( ' ' ) : line = part if line is None else '{0} {1}' . format ( line , part ) if part [ - 1 ] != '\\' : yield line line = None if line is not None : yield line if cmd in ( [ ] , '' ) : return '[]' if shell : if isinstance ( cmd , ( list , tuple ) ) : return ' ' . join ( cmd ) elif isinstance ( cmd , six . string_types ) : return cmd else : if isinstance ( cmd , ( list , tuple ) ) : return json . dumps ( map ( six . text_type , cmd ) ) elif isinstance ( cmd , six . string_types ) : return json . dumps ( list ( _split_cmd ( ) ) ) raise ValueError ( "Invalid type of command string or sequence: {0}" . format ( cmd ) )
Converts a command line to the notation as used in a Dockerfile CMD and ENTRYPOINT command . In shell notation this returns a simple string whereas by default it returns a JSON - list format with the command and arguments .
61,585
def format_expose ( expose ) : if isinstance ( expose , six . string_types ) : return expose , elif isinstance ( expose , collections . Iterable ) : return map ( six . text_type , expose ) return six . text_type ( expose ) ,
Converts a port number or multiple port numbers as used in the Dockerfile EXPOSE command to a tuple .
61,586
def add_file ( self , src_path , dst_path = None , ctx_path = None , replace_space = True , expandvars = False , expanduser = False , remove_final = False ) : if dst_path is None : head , tail = os . path . split ( src_path ) if not tail : tail = os . path . split ( head ) [ 1 ] if not tail : ValueError ( "Could not generate target path from input '{0}'; needs to be specified explicitly." ) target_path = tail else : target_path = dst_path source_path = prepare_path ( src_path , False , False , expandvars , expanduser ) target_path = prepare_path ( target_path , replace_space , True , expandvars , expanduser ) if ctx_path : context_path = prepare_path ( ctx_path , replace_space , True , expandvars , expanduser ) else : context_path = target_path self . prefix ( 'ADD' , context_path , target_path ) self . _files . append ( ( source_path , context_path ) ) if remove_final : self . _remove_files . add ( target_path ) return context_path
Adds a file to the Docker build . An ADD command is inserted and the path is stored for later packaging of the context tarball .
61,587
def write ( self , input_str ) : self . check_not_finalized ( ) if isinstance ( input_str , six . binary_type ) : self . fileobj . write ( input_str ) else : self . fileobj . write ( input_str . encode ( 'utf-8' ) )
Adds content to the Dockerfile .
61,588
def merge_dependency ( self , item , resolve_parent , parents ) : dep = [ ] for parent_key in parents : if item == parent_key : raise CircularDependency ( item , True ) if parent_key . config_type == ItemType . CONTAINER : parent_dep = resolve_parent ( parent_key ) if item in parent_dep : raise CircularDependency ( item ) merge_list ( dep , parent_dep ) merge_list ( dep , parents ) return dep
Merge dependencies of current configuration with further dependencies ; in this instance it means that in case of container configuration first parent dependencies are checked and then immediate dependencies of the current configuration should be added to the list but without duplicating any entries .
61,589
def load_map ( stream , name = None , check_integrity = True , check_duplicates = True ) : map_dict = yaml . safe_load ( stream ) if isinstance ( map_dict , dict ) : map_name = name or map_dict . pop ( 'name' , None ) if not map_name : raise ValueError ( "No map name provided, and none found in YAML stream." ) return ContainerMap ( map_name , map_dict , check_integrity = check_integrity , check_duplicates = check_duplicates ) raise ValueError ( "Valid map could not be decoded." )
Loads a ContainerMap configuration from a YAML document stream .
61,590
def load_clients ( stream , configuration_class = ClientConfiguration ) : client_dict = yaml . safe_load ( stream ) if isinstance ( client_dict , dict ) : return { client_name : configuration_class ( ** client_config ) for client_name , client_config in six . iteritems ( client_dict ) } raise ValueError ( "Valid configuration could not be decoded." )
Loads client configurations from a YAML document stream .
61,591
def load_map_file ( filename , name = None , check_integrity = True ) : if name == '' : base_name = os . path . basename ( filename ) map_name , __ , __ = os . path . basename ( base_name ) . rpartition ( os . path . extsep ) else : map_name = name with open ( filename , 'r' ) as f : return load_map ( f , name = map_name , check_integrity = check_integrity )
Loads a ContainerMap configuration from a YAML file .
61,592
def load_clients_file ( filename , configuration_class = ClientConfiguration ) : with open ( filename , 'r' ) as f : return load_clients ( f , configuration_class = configuration_class )
Loads client configurations from a YAML file .
61,593
def get_state_generator ( self , action_name , policy , kwargs ) : state_generator_cls = self . generators [ action_name ] [ 0 ] state_generator = state_generator_cls ( policy , kwargs ) return state_generator
Returns the state generator to be used for the given action .
61,594
def get_action_generator ( self , action_name , policy , kwargs ) : action_generator_cls = self . generators [ action_name ] [ 1 ] action_generator = action_generator_cls ( policy , kwargs ) return action_generator
Returns the action generator to be used for the given action .
61,595
def get_states ( self , action_name , config_name , instances = None , map_name = None , ** kwargs ) : policy = self . get_policy ( ) _set_forced_update_ids ( kwargs , policy . container_maps , map_name or self . _default_map , instances ) state_generator = self . get_state_generator ( action_name , policy , kwargs ) log . debug ( "Remaining kwargs passed to client actions: %s" , kwargs ) config_ids = get_map_config_ids ( config_name , policy . container_maps , map_name or self . _default_map , instances ) log . debug ( "Generating states for configurations: %s" , config_ids ) return state_generator . get_states ( config_ids )
Returns a generator of states in relation to the indicated action .
61,596
def get_actions ( self , action_name , config_name , instances = None , map_name = None , ** kwargs ) : policy = self . get_policy ( ) action_generator = self . get_action_generator ( action_name , policy , kwargs ) for state in self . get_states ( action_name , config_name , instances = instances , map_name = map_name , ** kwargs ) : log . debug ( "Evaluating state: %s." , state ) actions = action_generator . get_state_actions ( state , ** kwargs ) if actions : log . debug ( "Running actions: %s" , actions ) yield actions else : log . debug ( "No actions returned." )
Returns the entire set of actions performed for the indicated action name .
61,597
def create ( self , container , instances = None , map_name = None , ** kwargs ) : return self . run_actions ( 'create' , container , instances = instances , map_name = map_name , ** kwargs )
Creates container instances for a container configuration .
61,598
def start ( self , container , instances = None , map_name = None , ** kwargs ) : return self . run_actions ( 'start' , container , instances = instances , map_name = map_name , ** kwargs )
Starts instances for a container configuration .
61,599
def restart ( self , container , instances = None , map_name = None , ** kwargs ) : return self . run_actions ( 'restart' , container , instances = instances , map_name = map_name , ** kwargs )
Restarts instances for a container configuration .