idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
238,300 | def expandEntitiesFromEmail ( e ) : email = { } email [ "type" ] = "i3visio.email" email [ "value" ] = e email [ "attributes" ] = [ ] alias = { } alias [ "type" ] = "i3visio.alias" alias [ "value" ] = e . split ( "@" ) [ 0 ] alias [ "attributes" ] = [ ] domain = { } domain [ "type" ] = "i3visio.domain" domain [ "value"... | Method that receives an email an creates linked entities |
238,301 | def getNumberTLD ( ) : total = 0 for typeTld in TLD . keys ( ) : total += len ( TLD [ typeTld ] ) return total | Counting the total number of TLD being processed . |
238,302 | def getWhoisInfo ( domain ) : new = [ ] try : emails = { } emails [ "type" ] = "i3visio.alias" emails [ "value" ] = str ( domain . split ( "." ) [ 0 ] ) emails [ "attributes" ] = [ ] new . append ( emails ) except : pass info = whois . whois ( domain ) if info . status == None : raise Exception ( "UnknownDomainError: "... | Method that trie to recover the whois info from a domain . |
238,303 | def createDomains ( tlds , nicks = None , nicksFile = None ) : domain_candidates = [ ] if nicks != None : for n in nicks : for t in tlds : tmp = { "domain" : n + t [ "tld" ] , "type" : t [ "type" ] , "tld" : t [ "tld" ] } domain_candidates . append ( tmp ) elif nicksFile != None : with open ( nicksFile , "r" ) as iF : ... | Method that globally permits to generate the domains to be checked . |
238,304 | def weCanCheckTheseDomains ( email ) : notWorking = [ "@aol.com" , "@bk.ru" , "@breakthru.com" , "@gmx." , "@hotmail.co" , "@inbox.com" , "@latinmail.com" , "@libero.it" , "@mail.ru" , "@mail2tor.com" , "@outlook.com" , "@rambler.ru" , "@rocketmail.com" , "@starmedia.com" , "@ukr.net" "@yahoo." , "@ymail." ] for n in n... | Method that verifies if a domain can be safely verified . |
238,305 | def grabEmails ( emails = None , emailsFile = None , nicks = None , nicksFile = None , domains = EMAIL_DOMAINS , excludeDomains = [ ] ) : email_candidates = [ ] if emails != None : email_candidates = emails elif emailsFile != None : with open ( emailsFile , "r" ) as iF : email_candidates = iF . read ( ) . splitlines ( ... | Method that generates a list of emails . |
238,306 | def processMailList ( platformNames = [ ] , emails = [ ] ) : platforms = platform_selection . getPlatformsByName ( platformNames , mode = "mailfy" ) results = [ ] for e in emails : for pla in platforms : entities = pla . getInfo ( query = e , mode = "mailfy" ) if entities != { } : results += json . loads ( entities ) r... | Method to perform the email search . |
238,307 | def pool_function ( args ) : is_valid = True try : checker = emailahoy . VerifyEmail ( ) status , message = checker . verify_email_smtp ( args , from_host = 'gmail.com' , from_email = 'sample@gmail.com' ) if status == 250 : print ( "\t[*] Verification of '{}' status: {}. Details:\n\t\t{}" . format ( general . success (... | A wrapper for being able to launch all the threads . |
238,308 | def recoverURL ( self , url ) : self . setUserAgent ( ) if "https://" in url : self . setProxy ( protocol = "https" ) else : self . setProxy ( protocol = "http" ) if ".onion" in url : try : pass except : pass url = url . replace ( ".onion" , ".onion.cab" ) try : recurso = self . br . open ( url ) except : return None h... | Public method to recover a resource . |
238,309 | def setNewPassword ( self , url , username , password ) : self . br . add_password ( url , username , password ) | Public method to manually set the credentials for a url in the browser . |
238,310 | def setProxy ( self , protocol = "http" ) : try : new = { protocol : self . proxies [ protocol ] } self . br . set_proxies ( new ) except : pass | Public method to set a proxy for the browser . |
238,311 | def setUserAgent ( self , uA = None ) : logger = logging . getLogger ( "osrframework.utils" ) if not uA : if self . userAgents : logger = logging . debug ( "Selecting a new random User Agent." ) uA = random . choice ( self . userAgents ) else : logger = logging . debug ( "No user agent was inserted." ) return False sel... | This method will be called whenever a new query will be executed . |
238,312 | def main ( args ) : tAW = TwitterAPIWrapper ( ) if args . type == "get_all_docs" : results = tAW . get_all_docs ( args . query ) elif args . type == "get_user" : results = tAW . get_user ( args . query ) elif args . type == "get_followers" : results = tAW . get_followers ( args . query ) print "... %s followers downloa... | Query manager . |
238,313 | def _rate_limit_status ( self , api = None , mode = None ) : if api == None : api = self . connectToAPI ( ) if mode == None : print json . dumps ( api . rate_limit_status ( ) , indent = 2 ) raw_input ( "<Press ENTER>" ) else : while True : allLimits = api . rate_limit_status ( ) if mode == "get_user" : limit = allLimit... | Verifying the API limits |
238,314 | def get_followers ( self , query ) : api = self . _connectToAPI ( ) self . _rate_limit_status ( api = api , mode = "get_followers" ) try : friends_ids = api . followers_ids ( query ) except : return [ ] return friends_ids | Method to get the followers of a user . |
238,315 | def get_friends ( self , query ) : api = self . _connectToAPI ( ) self . _rate_limit_status ( api = api , mode = "get_friends" ) try : friends_ids = api . friends_ids ( query ) except : return [ ] return friends_ids | Method to get the friends of a user . |
238,316 | def get_user ( self , screen_name ) : api = self . _connectToAPI ( ) self . _rate_limit_status ( api = api , mode = "get_user" ) aux = [ ] try : user = api . get_user ( screen_name ) aux . append ( user . _json ) except tweepy . error . TweepError as e : pass res = [ ] for a in aux : res . append ( self . _processUser ... | Method to perform the usufy searches . |
238,317 | def search_users ( self , query , n = 20 , maxUsers = 60 ) : api = self . _connectToAPI ( ) self . _rate_limit_status ( api = api , mode = "search_users" ) aux = [ ] page = 0 try : newUsers = api . search_users ( query , n , page ) for n in newUsers : aux . append ( n . _json ) while len ( aux ) < maxUsers & len ( newU... | Method to perform the searchfy searches . |
238,318 | def validate_categories ( categories ) : if not set ( categories ) <= Source . categories : invalid = list ( set ( categories ) - Source . categories ) raise ValueError ( 'Invalid categories: %s' % invalid ) | Take an iterable of source categories and raise ValueError if some of them are invalid . |
238,319 | def checkIfHashIsCracked ( hash = None ) : apiURL = "http://md5db.net/api/" + str ( hash ) . lower ( ) try : data = urllib2 . urlopen ( apiURL ) . read ( ) return data except : return [ ] | Method that checks if the given hash is stored in the md5db . net website . |
238,320 | def fuzzUsufy ( fDomains = None , fFuzzStruct = None ) : if fFuzzStruct == None : fuzzingStructures = [ "http://<DOMAIN>/<USERNAME>" , "http://<DOMAIN>/~<USERNAME>" , "http://<DOMAIN>/?action=profile;user=<USERNAME>" , "http://<DOMAIN>/causes/author/<USERNAME>" , "http://<DOMAIN>/channel/<USERNAME>" , "http://<DOMAIN>/... | Method to guess the usufy path against a list of domains or subdomains . |
238,321 | def _prepare_filtering_params ( domain = None , category = None , sponsored_source = None , has_field = None , has_fields = None , query_params_match = None , query_person_match = None , ** kwargs ) : if query_params_match not in ( None , True ) : raise ValueError ( 'query_params_match can only be `True`' ) if query_pe... | Transform the params to the API format return a list of params . |
238,322 | def validate_query_params ( self , strict = True ) : if not ( self . api_key or default_api_key ) : raise ValueError ( 'API key is missing' ) if strict and self . query_params_mode not in ( None , 'and' , 'or' ) : raise ValueError ( 'query_params_match should be one of "and"/"or"' ) if not self . person . is_searchable... | Check if the request is valid and can be sent raise ValueError if not . strict is a boolean argument that defaults to True which means an exception is raised on every invalid query parameter if set to False an exception is raised only when the search request cannot be performed because required query params are missing... |
238,323 | def group_records_by_domain ( self ) : key_function = lambda record : record . source . domain return self . group_records ( key_function ) | Return the records grouped by the domain they came from . The return value is a dict a key in this dict is a domain and the value is a list of all the records with this domain . |
238,324 | def group_records_by_category ( self ) : Source . validate_categories ( categories ) key_function = lambda record : record . source . category return self . group_records ( key_function ) | Return the records grouped by the category of their source . The return value is a dict a key in this dict is a category and the value is a list of all the records with this category . |
238,325 | def from_dict ( d ) : warnings_ = d . get ( 'warnings' , [ ] ) query = d . get ( 'query' ) or None if query : query = Person . from_dict ( query ) person = d . get ( 'person' ) or None if person : person = Person . from_dict ( person ) records = d . get ( 'records' ) if records : records = [ Record . from_dict ( record... | Transform the dict to a response object and return the response . |
238,326 | def to_dict ( self ) : d = { } if self . warnings : d [ 'warnings' ] = self . warnings if self . query is not None : d [ 'query' ] = self . query . to_dict ( ) if self . person is not None : d [ 'person' ] = self . person . to_dict ( ) if self . records : d [ 'records' ] = [ record . to_dict ( ) for record in self . re... | Return a dict representation of the response . |
238,327 | def from_dict ( cls , d ) : kwargs = { } for key , val in d . iteritems ( ) : if key . startswith ( 'display' ) : continue if key . startswith ( '@' ) : key = key [ 1 : ] if key == 'type' : key = 'type_' elif key == 'valid_since' : val = str_to_datetime ( val ) elif key == 'date_range' : val = DateRange . from_dict ( v... | Transform the dict to a field object and return the field . |
238,328 | def to_dict ( self ) : d = { } if self . valid_since is not None : d [ '@valid_since' ] = datetime_to_str ( self . valid_since ) for attr_list , prefix in [ ( self . attributes , '@' ) , ( self . children , '' ) ] : for attr in attr_list : value = getattr ( self , attr ) if isinstance ( value , Serializable ) : value =... | Return a dict representation of the field . |
238,329 | def is_searchable ( self ) : first = alpha_chars ( self . first or u'' ) last = alpha_chars ( self . last or u'' ) raw = alpha_chars ( self . raw or u'' ) return ( len ( first ) >= 2 and len ( last ) >= 2 ) or len ( raw ) >= 4 | A bool value that indicates whether the name is a valid name to search by . |
238,330 | def is_searchable ( self ) : return self . raw or ( self . is_valid_country and ( not self . state or self . is_valid_state ) ) | A bool value that indicates whether the address is a valid address to search by . |
238,331 | def is_valid_state ( self ) : return self . is_valid_country and self . country . upper ( ) in STATES and self . state is not None and self . state . upper ( ) in STATES [ self . country . upper ( ) ] | A bool value that indicates whether the object s state is a valid state code . |
238,332 | def to_dict ( self ) : d = Field . to_dict ( self ) if self . display_international : d [ 'display_international' ] = self . display_international return d | Extend Field . to_dict take the display_international attribute . |
238,333 | def is_valid_email ( self ) : return bool ( self . address and Email . re_email . match ( self . address ) ) | A bool value that indicates whether the address is a valid email address . Note that the check is done be matching to the regular expression at Email . re_email which is very basic and far from covering end - cases ... |
238,334 | def age ( self ) : if self . date_range is None : return dob = self . date_range . middle today = datetime . date . today ( ) if ( today . month , today . day ) < ( dob . month , dob . day ) : return today . year - dob . year - 1 else : return today . year - dob . year | int the estimated age of the person . Note that A DOB object is based on a date - range and the exact date is usually unknown so for age calculation the the middle of the range is assumed to be the real date - of - birth . |
238,335 | def age_range ( self ) : if self . date_range is None : return None , None start_date = DateRange ( self . date_range . start , self . date_range . start ) end_date = DateRange ( self . date_range . end , self . date_range . end ) start_age = DOB ( date_range = end_date ) . age end_age = DOB ( date_range = start_date )... | A tuple of two ints - the minimum and maximum age of the person . |
238,336 | def from_age_range ( start_age , end_age ) : if start_age < 0 or end_age < 0 : raise ValueError ( 'start_age and end_age can\'t be negative' ) if start_age > end_age : start_age , end_age = end_age , start_age today = datetime . date . today ( ) try : start_date = today . replace ( year = today . year - end_age - 1 ) e... | Take a person s minimal and maximal age and return a new DOB object suitable for him . |
238,337 | def from_dict ( cls , d ) : relationship = super ( cls , cls ) . from_dict ( d ) if relationship . name is not None : relationship . name = Name . from_dict ( relationship . name ) return relationship | Extend Field . from_dict and also load the name from the dict . |
238,338 | def from_dict ( d ) : start = d . get ( 'start' ) end = d . get ( 'end' ) if not ( start and end ) : raise ValueError ( 'DateRange must have both start and end' ) start = str_to_date ( start ) end = str_to_date ( end ) return DateRange ( start , end ) | Transform the dict to a DateRange object . |
238,339 | def to_dict ( self ) : d = { } d [ 'start' ] = date_to_str ( self . start ) d [ 'end' ] = date_to_str ( self . end ) return d | Transform the date - range to a dict . |
238,340 | def enumerateURL ( urlDict , outputFolder , startIndex = 0 , maxErrors = 100 ) : for i , url in enumerate ( urlDict . keys ( ) ) : domain = re . findall ( "://(.*)/" , url ) [ 0 ] index = startIndex consecutiveErrors = 0 i3Browser = browser . Browser ( ) while consecutiveErrors <= maxErrors : newQuery = url . replace (... | Function that performs the enumeration itself . |
238,341 | def checkIfEmailWasHacked ( email = None , sleepSeconds = 1 ) : time . sleep ( sleepSeconds ) print ( "\t[*] Bypassing Cloudflare Restriction..." ) ua = 'osrframework 0.18' useragent = { 'User-Agent' : ua } cookies , user_agent = cfscrape . get_tokens ( 'https://haveibeenpwned.com/api/v2/breachedaccount/test@example.co... | Method that checks if the given email is stored in the HIBP website . |
238,342 | def get_page ( url ) : request = Request ( url ) request . add_header ( 'User-Agent' , 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)' ) cookie_jar . add_cookie_header ( request ) response = urlopen ( request ) cookie_jar . extract_cookies ( response , request ) html = response . read ( ) response . close ( ) cook... | Request the given URL and return the response page using the cookie jar . |
238,343 | def search ( query , tld = 'com' , lang = 'en' , num = 10 , start = 0 , stop = None , pause = 2.0 , only_standard = False ) : global BeautifulSoup if BeautifulSoup is None : try : from bs4 import BeautifulSoup except ImportError : from BeautifulSoup import BeautifulSoup hashes = set ( ) query = quote_plus ( query ) get... | Search the given query string using Google . |
238,344 | def add_fields ( self , fields ) : for field in fields : cls = field . __class__ try : container = FieldsContainer . class_container [ cls ] except KeyError : raise ValueError ( 'Object of type %s is an invalid field' % cls ) getattr ( self , container ) . append ( field ) | Add the fields to their corresponding container . fields is an iterable of field objects from osrframework . thirdparties . pipl_com . lib . fields . |
238,345 | def all_fields ( self ) : return [ field for container in FieldsContainer . class_container . values ( ) for field in getattr ( self , container ) ] | A list with all the fields contained in this object . |
238,346 | def fields_from_dict ( d ) : class_container = FieldsContainer . class_container fields = [ field_cls . from_dict ( field_dict ) for field_cls , container in class_container . iteritems ( ) for field_dict in d . get ( container , [ ] ) ] return fields | Load the fields from the dict return a list with all the fields . |
238,347 | def fields_to_dict ( self ) : d = { } for container in FieldsContainer . class_container . values ( ) : fields = getattr ( self , container ) if fields : d [ container ] = [ field . to_dict ( ) for field in fields ] return d | Transform the object to a dict and return the dict . |
238,348 | def from_dict ( d ) : query_params_match = d . get ( '@query_params_match' ) query_person_match = d . get ( '@query_person_match' ) valid_since = d . get ( '@valid_since' ) if valid_since : valid_since = str_to_datetime ( valid_since ) source = Source . from_dict ( d . get ( 'source' , { } ) ) fields = Record . fields_... | Transform the dict to a record object and return the record . |
238,349 | def to_dict ( self ) : d = { } if self . query_params_match is not None : d [ '@query_params_match' ] = self . query_params_match if self . query_person_match is not None : d [ '@query_person_match' ] = self . query_person_match if self . valid_since is not None : d [ '@valid_since' ] = datetime_to_str ( self . valid_s... | Return a dict representation of the record . |
238,350 | def is_searchable ( self ) : filter_func = lambda field : field . is_searchable return bool ( filter ( filter_func , self . names ) or filter ( filter_func , self . emails ) or filter ( filter_func , self . phones ) or filter ( filter_func , self . usernames ) ) | A bool value that indicates whether the person has enough data and can be sent as a query to the API . |
238,351 | def from_dict ( d ) : query_params_match = d . get ( '@query_params_match' ) sources = [ Source . from_dict ( source ) for source in d . get ( 'sources' , [ ] ) ] fields = Person . fields_from_dict ( d ) return Person ( fields = fields , sources = sources , query_params_match = query_params_match ) | Transform the dict to a person object and return the person . |
238,352 | def to_dict ( self ) : d = { } if self . query_params_match is not None : d [ '@query_params_match' ] = self . query_params_match if self . sources : d [ 'sources' ] = [ source . to_dict ( ) for source in self . sources ] d . update ( self . fields_to_dict ( ) ) return d | Return a dict representation of the person . |
238,353 | def processPhoneList ( platformNames = [ ] , numbers = [ ] , excludePlatformNames = [ ] ) : platforms = platform_selection . getPlatformsByName ( platformNames , mode = "phonefy" , excludePlatformNames = excludePlatformNames ) results = [ ] for num in numbers : for pla in platforms : entities = pla . getInfo ( query = ... | Method to perform searchs on a series of numbers . |
238,354 | def createURL ( self , word , mode = "phonefy" ) : try : return self . modes [ mode ] [ "url" ] . format ( placeholder = urllib . pathname2url ( word ) ) except : if mode == "base" : if word [ 0 ] == "/" : return self . baseURL + word [ 1 : ] , word else : return self . baseURL + word else : try : return self . url [ m... | Method to create the URL replacing the word in the appropriate URL . |
238,355 | def launchQueryForMode ( self , query = None , mode = None ) : qURL = self . createURL ( word = query , mode = mode ) i3Browser = browser . Browser ( ) try : if self . needsCredentials [ mode ] : self . _getAuthenticated ( i3Browser , qURL ) data = i3Browser . recoverURL ( qURL ) else : data = i3Browser . recoverURL ( ... | Method that launches an i3Browser to collect data . |
238,356 | def getInfo ( self , query = None , process = False , mode = "phonefy" , qURI = None ) : results = [ ] data = "" if self . _modeIsValid ( mode = mode ) and self . _isValidQuery ( query , mode = mode ) : if mode in [ "mailfy" , "phonefy" , "searchfy" , "usufy" ] : try : results = getattr ( self , "do_{}" . format ( mode... | Method that checks the presence of a given query and recovers the first list of complains . |
238,357 | def _modeIsValid ( self , mode ) : try : return mode in self . modes . keys ( ) except AttributeError as e : if mode in self . isValidMode . keys ( ) : if mode in self . isValidMode . keys ( ) : return True return False | Verification of whether the mode is a correct option to be used . |
238,358 | def _getAuthenticated ( self , browser , url ) : try : if len ( self . creds ) > 0 : c = random . choice ( self . creds ) [ 0 ] browser . setNewPassword ( url , c . user , c . password ) return True else : raise NoCredentialsException ( str ( self ) ) except AttributeError as e : raise BadImplementationError ( str ( e ... | Getting authenticated . |
238,359 | def _isValidQuery ( self , query , mode = "phonefy" ) : try : validator = self . modes [ mode ] . get ( "query_validator" ) if validator : try : compiledRegexp = re . compile ( "^{expr}$" . format ( expr = validator ) ) return compiledRegexp . match ( query ) except AttributeError as e : return True except AttributeErr... | Method to verify if a given query is processable by the platform . |
238,360 | def _somethingFound ( self , data , mode = "phonefy" ) : if data : try : for text in self . notFoundText [ mode ] : if text in data : return False return True except AttributeError as e : verifier = self . modes . get ( mode ) if verifier : if verifier . get ( "not_found_text" , "" ) in data : return False else : retur... | Verifying if something was found . |
238,361 | def do_phonefy ( self , query , ** kwargs ) : results = [ ] test = self . check_phonefy ( query , kwargs ) if test : r = { "type" : "i3visio.phone" , "value" : self . platformName + " - " + query , "attributes" : [ ] } try : aux = { "type" : "i3visio.uri" , "value" : self . createURL ( query , mode = "phonefy" ) , "att... | Verifying a phonefy query in this platform . |
238,362 | def process_usufy ( self , data ) : mode = "usufy" info = [ ] try : verifier = self . modes . get ( mode , { } ) . get ( "extra_fields" , { } ) for field in verifier . keys ( ) : regexp = verifier [ field ] values = re . findall ( regexp , data ) for val in values : aux = { } aux [ "type" ] = field aux [ "value" ] = va... | Method to process and extract the entities of a usufy |
238,363 | def doBenchmark ( plats ) : logger = logging . getLogger ( "osrframework.utils" ) res = { } args = [ ] tries = [ 1 , 4 , 8 , 16 , 24 , 32 , 40 , 48 , 56 , 64 ] logger . info ( "The test is starting recovering webpages by creating the following series of threads: " + str ( tries ) ) for i in tries : print "Testing creat... | Perform the benchmark ... |
238,364 | def changePermissionsRecursively ( path , uid , gid ) : os . chown ( path , uid , gid ) for item in os . listdir ( path ) : itempath = os . path . join ( path , item ) if os . path . isfile ( itempath ) : try : os . chown ( itempath , uid , gid ) except Exception as e : pass os . chmod ( itempath , 600 ) elif os . path... | Function to recursively change the user id and group id . |
238,365 | def getConfigPath ( configFileName = None ) : paths = { } applicationPath = "./" if sys . platform == 'win32' : applicationPath = os . path . expanduser ( os . path . join ( '~\\' , 'OSRFramework' ) ) else : applicationPath = os . path . expanduser ( os . path . join ( '~/' , '.config' , 'OSRFramework' ) ) paths = { "a... | Auxiliar function to get the configuration paths depending on the system |
238,366 | def returnListOfConfigurationValues ( util ) : VALUES = { } configPath = os . path . join ( getConfigPath ( ) [ "appPath" ] , "general.cfg" ) if not os . path . exists ( configPath ) : defaultConfigPath = os . path . join ( getConfigPath ( ) [ "appPathDefaults" ] , "general.cfg" ) try : with open ( defaultConfigPath ) ... | Method that recovers the configuration information about each program |
238,367 | def performSearch ( platformNames = [ ] , queries = [ ] , process = False , excludePlatformNames = [ ] ) : platforms = platform_selection . getPlatformsByName ( platformNames , mode = "searchfy" , excludePlatformNames = excludePlatformNames ) results = [ ] for q in queries : for pla in platforms : entities = pla . getI... | Method to perform the search itself on the different platforms . |
238,368 | def getAllPlatformNames ( mode ) : platOptions = [ ] if mode in [ "phonefy" , "usufy" , "searchfy" , "mailfy" ] : allPlatforms = getAllPlatformObjects ( mode = mode ) for p in allPlatforms : try : parameter = p . parameterName except : parameter = p . platformName . lower ( ) if parameter not in platOptions : platOptio... | Method that defines the whole list of available parameters . |
238,369 | def from_json ( cls , json_str ) : d = json . loads ( json_str ) return cls . from_dict ( d ) | Deserialize the object from a JSON string . |
238,370 | def createEmails ( nicks = None , nicksFile = None ) : candidate_emails = set ( ) if nicks != None : for n in nicks : for e in email_providers . domains : candidate_emails . add ( "{}@{}" . format ( n , e ) ) elif nicksFile != None : with open ( nicksFile , "r" ) as iF : nicks = iF . read ( ) . splitlines ( ) for n in ... | Method that globally permits to generate the emails to be checked . |
238,371 | def checkIPFromAlias ( alias = None ) : headers = { "Content-type" : "text/html" , "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" , "Accept-Encoding" : " gzip, deflate" , "Accept-Language" : " es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3" , "Connection" : "keep-alive" , "DNT" : "1" , "Host" : "www.... | Method that checks if the given alias is currently connected to Skype and returns its IP address . |
238,372 | def get_form ( self , request , obj = None , ** kwargs ) : Form = type ( str ( 'ExtSharableForm' ) , ( SharableCascadeForm , kwargs . pop ( 'form' , self . form ) ) , { } ) Form . base_fields [ 'shared_glossary' ] . limit_choices_to = dict ( plugin_type = self . __class__ . __name__ ) kwargs . update ( form = Form ) re... | Extend the form for the given plugin with the form SharableCascadeForm |
238,373 | def get_min_max_bounds ( self ) : bound = Bound ( 999999.0 , 0.0 ) for bp in Breakpoint : bound . extend ( self . get_bound ( bp ) ) return { 'min' : bound . min , 'max' : bound . max } | Return a dict of min - and max - values for the given column . This is required to estimate the bounds of images . |
238,374 | def create_proxy_model ( name , model_mixins , base_model , attrs = None , module = None ) : from django . apps import apps class Meta : proxy = True app_label = 'cmsplugin_cascade' name = str ( name + 'Model' ) try : Model = apps . get_registered_model ( Meta . app_label , name ) except LookupError : bases = model_mix... | Create a Django Proxy Model on the fly to be used by any Cascade Plugin . |
238,375 | def _get_parent_classes_transparent ( cls , slot , page , instance = None ) : parent_classes = super ( CascadePluginBase , cls ) . get_parent_classes ( slot , page , instance ) if parent_classes is None : if cls . get_require_parent ( slot , page ) is False : return parent_classes = [ ] parent_classes = set ( parent_cl... | Return all parent classes including those marked as transparent . |
238,376 | def extend_children ( self , parent , wanted_children , child_class , child_glossary = None ) : from cms . api import add_plugin current_children = parent . get_num_children ( ) for _ in range ( current_children , wanted_children ) : child = add_plugin ( parent . placeholder , child_class , parent . language , target =... | Extend the number of children so that the parent object contains wanted children . No child will be removed if wanted_children is smaller than the current number of children . |
238,377 | def get_parent_instance ( self , request = None , obj = None ) : try : parent_id = obj . parent_id except AttributeError : try : parent_id = self . parent . id except AttributeError : if request : parent_id = request . GET . get ( 'plugin_parent' , None ) if parent_id is None : from cms . models import CMSPlugin try : ... | Get the parent model instance corresponding to this plugin . When adding a new plugin the parent might not be available . Therefore as fallback pass in the request object . |
238,378 | def in_edit_mode ( self , request , placeholder ) : toolbar = getattr ( request , 'toolbar' , None ) edit_mode = getattr ( toolbar , 'edit_mode' , False ) and getattr ( placeholder , 'is_editable' , True ) if edit_mode : edit_mode = placeholder . has_change_permission ( request . user ) return edit_mode | Returns True if the plugin is in edit mode . |
238,379 | def _get_previous_open_tag ( self , obj ) : prev_instance = self . get_previous_instance ( obj ) if prev_instance and prev_instance . plugin_type == self . __class__ . __name__ : return prev_instance . glossary . get ( 'open_tag' ) | Return the open tag of the previous sibling |
238,380 | def check_unique_element_id ( cls , instance , element_id ) : try : element_ids = instance . placeholder . page . cascadepage . glossary . get ( 'element_ids' , { } ) except ( AttributeError , ObjectDoesNotExist ) : pass else : if element_id : for key , value in element_ids . items ( ) : if str ( key ) != str ( instanc... | Check for uniqueness of the given element_id for the current page . Return None if instance is not yet associated with a page . |
238,381 | def rectify_partial_form_field ( base_field , partial_form_fields ) : base_field . label = '' base_field . help_text = '' for fieldset in partial_form_fields : if not isinstance ( fieldset , ( list , tuple ) ) : fieldset = [ fieldset ] for field in fieldset : base_field . validators . append ( field . run_validators ) | In base_field reset the attributes label and help_text since they are overriden by the partial field . Additionally from the list or list of lists of partial_form_fields append the bound validator methods to the given base field . |
238,382 | def validate_link ( link_data ) : from django . apps import apps try : Model = apps . get_model ( * link_data [ 'model' ] . split ( '.' ) ) Model . objects . get ( pk = link_data [ 'pk' ] ) except Model . DoesNotExist : raise ValidationError ( _ ( "Unable to link onto '{0}'." ) . format ( Model . __name__ ) ) | Check if the given model exists otherwise raise a Validation error |
238,383 | def parse_responsive_length ( responsive_length ) : responsive_length = responsive_length . strip ( ) if responsive_length . endswith ( 'px' ) : return ( int ( responsive_length . rstrip ( 'px' ) ) , None ) elif responsive_length . endswith ( '%' ) : return ( None , float ( responsive_length . rstrip ( '%' ) ) / 100 ) ... | Takes a string containing a length definition in pixels or percent and parses it to obtain a computational length . It returns a tuple where the first element is the length in pixels and the second element is its length in percent divided by 100 . Note that one of both returned elements is None . |
238,384 | def get_css_classes ( cls , instance ) : css_classes = [ ] if hasattr ( cls , 'default_css_class' ) : css_classes . append ( cls . default_css_class ) for attr in getattr ( cls , 'default_css_attributes' , [ ] ) : css_class = instance . glossary . get ( attr ) if isinstance ( css_class , six . string_types ) : css_clas... | Returns a list of CSS classes to be added as class = ... to the current HTML tag . |
238,385 | def get_inline_styles ( cls , instance ) : inline_styles = getattr ( cls , 'default_inline_styles' , { } ) css_style = instance . glossary . get ( 'inline_styles' ) if css_style : inline_styles . update ( css_style ) return inline_styles | Returns a dictionary of CSS attributes to be added as style = ... to the current HTML tag . |
238,386 | def get_html_tag_attributes ( cls , instance ) : attributes = getattr ( cls , 'html_tag_attributes' , { } ) return dict ( ( attr , instance . glossary . get ( key , '' ) ) for key , attr in attributes . items ( ) ) | Returns a dictionary of attributes which shall be added to the current HTML tag . This method normally is called by the models s property method html_tag_ attributes which enriches the HTML tag with those attributes converted to a list as attr1 = val1 attr2 = val2 ... . |
238,387 | def compile_validation_pattern ( self , units = None ) : if units is None : units = list ( self . POSSIBLE_UNITS ) else : for u in units : if u not in self . POSSIBLE_UNITS : raise ValidationError ( '{} is not a valid unit for a size field' . format ( u ) ) regex = re . compile ( r'^(-?\d+)({})$' . format ( '|' . join ... | Assure that passed in units are valid size units or if missing use all possible units . Return a tuple with a regular expression to be used for validating and an error message in case this validation failed . |
238,388 | def unset_required_for ( cls , sharable_fields ) : if 'link_content' in cls . base_fields and 'link_content' not in sharable_fields : cls . base_fields [ 'link_content' ] . required = False if 'link_type' in cls . base_fields and 'link' not in sharable_fields : cls . base_fields [ 'link_type' ] . required = False | Fields borrowed by SharedGlossaryAdmin to build its temporary change form only are required if they are declared in sharable_fields . Otherwise just deactivate them . |
238,389 | def assure_relation ( cls , cms_page ) : try : cms_page . cascadepage except cls . DoesNotExist : cls . objects . create ( extended_object = cms_page ) | Assure that we have a foreign key relation pointing from CascadePage onto CMSPage . |
238,390 | def compute_media_queries ( element ) : parent_glossary = element . get_parent_glossary ( ) element . glossary [ 'container_max_widths' ] = max_widths = { } element . glossary [ 'media_queries' ] = media_queries = { } breakpoints = element . glossary . get ( 'breakpoints' , parent_glossary . get ( 'breakpoints' , [ ] )... | For e given Cascade element compute the current media queries for each breakpoint even for nested containers rows and columns . |
238,391 | def get_element_ids ( self , prefix_id ) : if isinstance ( self . widget , widgets . MultiWidget ) : ids = [ '{0}_{1}_{2}' . format ( prefix_id , self . name , field_name ) for field_name in self . widget ] elif isinstance ( self . widget , ( widgets . SelectMultiple , widgets . RadioSelect ) ) : ids = [ '{0}_{1}_{2}' ... | Returns a single or a list of element ids one for each input widget of this field |
238,392 | def get_context_override ( self , request ) : context_override = super ( EmulateUserModelMixin , self ) . get_context_override ( request ) try : if request . user . is_staff : user = self . UserModel . objects . get ( pk = request . session [ 'emulate_user_id' ] ) context_override . update ( user = user ) except ( self... | Override the request object with an emulated user . |
238,393 | def emulate_users ( self , request ) : def display_as_link ( self , obj ) : try : identifier = getattr ( user_model_admin , list_display_link ) ( obj ) except AttributeError : identifier = admin . utils . lookup_field ( list_display_link , obj , model_admin = self ) [ 2 ] emulate_user_id = request . session . get ( 'em... | The list view |
238,394 | def pre_migrate ( cls , sender = None , ** kwargs ) : ContentType = apps . get_model ( 'contenttypes' , 'ContentType' ) try : queryset = ContentType . objects . filter ( app_label = sender . label ) for ctype in queryset . exclude ( model__in = sender . get_proxy_models ( ) . keys ( ) ) : model = ctype . model_class ( ... | Iterate over contenttypes and remove those not in proxy models |
238,395 | def post_migrate ( cls , sender = None , ** kwargs ) : ContentType = apps . get_model ( 'contenttypes' , 'ContentType' ) for model_name , proxy_model in sender . get_proxy_models ( ) . items ( ) : ctype , created = ContentType . objects . get_or_create ( app_label = sender . label , model = model_name ) if created : se... | Iterate over fake_proxy_models and add contenttypes and permissions for missing proxy models if this has not been done by Django yet |
238,396 | def grant_permissions ( self , proxy_model ) : ContentType = apps . get_model ( 'contenttypes' , 'ContentType' ) try : Permission = apps . get_model ( 'auth' , 'Permission' ) except LookupError : return searched_perms = [ ] ctype = ContentType . objects . get_for_model ( proxy_model ) for perm in self . default_permiss... | Create the default permissions for the just added proxy model |
238,397 | def revoke_permissions ( self , ctype ) : ContentType = apps . get_model ( 'contenttypes' , 'ContentType' ) try : Permission = apps . get_model ( 'auth' , 'Permission' ) except LookupError : return codenames = [ '{0}_{1}' . format ( perm , ctype ) for perm in self . default_permissions ] cascade_element = apps . get_mo... | Remove all permissions for the content type to be removed |
238,398 | def to_file ( file , array ) : try : array . tofile ( file ) except ( TypeError , IOError , UnsupportedOperation ) : file . write ( array . tostring ( ) ) | Wrapper around ndarray . tofile to support any file - like object |
238,399 | def write_segment ( self , objects ) : segment = TdmsSegment ( objects ) segment . write ( self . _file ) | Write a segment of data to a TDMS file |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.