repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
i3visio/osrframework
osrframework/utils/general.py
expandEntitiesFromEmail
def expandEntitiesFromEmail(e): """ Method that receives an email an creates linked entities Args: ----- e: Email to verify. Returns: -------- Three different values: email, alias and domain in a list. """ # Grabbing the email email = {} email["type"] = "i3visio.email" email["value"] = e email["attributes"] = [] # Grabbing the alias alias = {} alias["type"] = "i3visio.alias" alias["value"] = e.split("@")[0] alias["attributes"] = [] # Grabbing the domain domain= {} domain["type"] = "i3visio.domain" domain["value"] = e.split("@")[1] domain["attributes"] = [] return [email, alias, domain]
python
def expandEntitiesFromEmail(e): """ Method that receives an email an creates linked entities Args: ----- e: Email to verify. Returns: -------- Three different values: email, alias and domain in a list. """ # Grabbing the email email = {} email["type"] = "i3visio.email" email["value"] = e email["attributes"] = [] # Grabbing the alias alias = {} alias["type"] = "i3visio.alias" alias["value"] = e.split("@")[0] alias["attributes"] = [] # Grabbing the domain domain= {} domain["type"] = "i3visio.domain" domain["value"] = e.split("@")[1] domain["attributes"] = [] return [email, alias, domain]
[ "def", "expandEntitiesFromEmail", "(", "e", ")", ":", "# Grabbing the email", "email", "=", "{", "}", "email", "[", "\"type\"", "]", "=", "\"i3visio.email\"", "email", "[", "\"value\"", "]", "=", "e", "email", "[", "\"attributes\"", "]", "=", "[", "]", "# Grabbing the alias", "alias", "=", "{", "}", "alias", "[", "\"type\"", "]", "=", "\"i3visio.alias\"", "alias", "[", "\"value\"", "]", "=", "e", ".", "split", "(", "\"@\"", ")", "[", "0", "]", "alias", "[", "\"attributes\"", "]", "=", "[", "]", "# Grabbing the domain", "domain", "=", "{", "}", "domain", "[", "\"type\"", "]", "=", "\"i3visio.domain\"", "domain", "[", "\"value\"", "]", "=", "e", ".", "split", "(", "\"@\"", ")", "[", "1", "]", "domain", "[", "\"attributes\"", "]", "=", "[", "]", "return", "[", "email", ",", "alias", ",", "domain", "]" ]
Method that receives an email an creates linked entities Args: ----- e: Email to verify. Returns: -------- Three different values: email, alias and domain in a list.
[ "Method", "that", "receives", "an", "email", "an", "creates", "linked", "entities" ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L842-L872
train
238,300
i3visio/osrframework
osrframework/domainfy.py
getNumberTLD
def getNumberTLD(): """ Counting the total number of TLD being processed. """ total = 0 for typeTld in TLD.keys(): total+= len(TLD[typeTld]) return total
python
def getNumberTLD(): """ Counting the total number of TLD being processed. """ total = 0 for typeTld in TLD.keys(): total+= len(TLD[typeTld]) return total
[ "def", "getNumberTLD", "(", ")", ":", "total", "=", "0", "for", "typeTld", "in", "TLD", ".", "keys", "(", ")", ":", "total", "+=", "len", "(", "TLD", "[", "typeTld", "]", ")", "return", "total" ]
Counting the total number of TLD being processed.
[ "Counting", "the", "total", "number", "of", "TLD", "being", "processed", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/domainfy.py#L63-L70
train
238,301
i3visio/osrframework
osrframework/domainfy.py
getWhoisInfo
def getWhoisInfo(domain): """ Method that trie to recover the whois info from a domain. Args: ----- domain: The domain to verify. Returns: -------- dict: A dictionary containing the result as an i3visio entity with its `value`, `type` and `attributes`. """ new = [] # Grabbing the aliases 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: " + domain + " could not be resolved.") # Grabbing the emails try: emails = {} emails["type"] = "i3visio.email" if type(info.emails) is not list: aux = [info.emails] emails["value"] = json.dumps(aux) else: emails["value"] = json.dumps(info.emails) emails["attributes"] = [] new.append(emails) except: pass # Grabbing the country try: tmp = {} tmp["type"] = "i3visio.location.country" tmp["value"] = str(info.country) tmp["attributes"] = [] new.append(tmp) except: pass # Grabbing the regitrar try: tmp = {} tmp["type"] = "i3visio.registrar" tmp["value"] = str(info.registrar) tmp["attributes"] = [] new.append(tmp) except: pass # Grabbing the regitrar try: tmp = {} tmp["type"] = "i3visio.fullname" try: tmp["value"] = str(info.name) except: tmp["value"] = info.name tmp["attributes"] = [] new.append(tmp) except: pass return new
python
def getWhoisInfo(domain): """ Method that trie to recover the whois info from a domain. Args: ----- domain: The domain to verify. Returns: -------- dict: A dictionary containing the result as an i3visio entity with its `value`, `type` and `attributes`. """ new = [] # Grabbing the aliases 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: " + domain + " could not be resolved.") # Grabbing the emails try: emails = {} emails["type"] = "i3visio.email" if type(info.emails) is not list: aux = [info.emails] emails["value"] = json.dumps(aux) else: emails["value"] = json.dumps(info.emails) emails["attributes"] = [] new.append(emails) except: pass # Grabbing the country try: tmp = {} tmp["type"] = "i3visio.location.country" tmp["value"] = str(info.country) tmp["attributes"] = [] new.append(tmp) except: pass # Grabbing the regitrar try: tmp = {} tmp["type"] = "i3visio.registrar" tmp["value"] = str(info.registrar) tmp["attributes"] = [] new.append(tmp) except: pass # Grabbing the regitrar try: tmp = {} tmp["type"] = "i3visio.fullname" try: tmp["value"] = str(info.name) except: tmp["value"] = info.name tmp["attributes"] = [] new.append(tmp) except: pass return new
[ "def", "getWhoisInfo", "(", "domain", ")", ":", "new", "=", "[", "]", "# Grabbing the aliases", "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: \"", "+", "domain", "+", "\" could not be resolved.\"", ")", "# Grabbing the emails", "try", ":", "emails", "=", "{", "}", "emails", "[", "\"type\"", "]", "=", "\"i3visio.email\"", "if", "type", "(", "info", ".", "emails", ")", "is", "not", "list", ":", "aux", "=", "[", "info", ".", "emails", "]", "emails", "[", "\"value\"", "]", "=", "json", ".", "dumps", "(", "aux", ")", "else", ":", "emails", "[", "\"value\"", "]", "=", "json", ".", "dumps", "(", "info", ".", "emails", ")", "emails", "[", "\"attributes\"", "]", "=", "[", "]", "new", ".", "append", "(", "emails", ")", "except", ":", "pass", "# Grabbing the country", "try", ":", "tmp", "=", "{", "}", "tmp", "[", "\"type\"", "]", "=", "\"i3visio.location.country\"", "tmp", "[", "\"value\"", "]", "=", "str", "(", "info", ".", "country", ")", "tmp", "[", "\"attributes\"", "]", "=", "[", "]", "new", ".", "append", "(", "tmp", ")", "except", ":", "pass", "# Grabbing the regitrar", "try", ":", "tmp", "=", "{", "}", "tmp", "[", "\"type\"", "]", "=", "\"i3visio.registrar\"", "tmp", "[", "\"value\"", "]", "=", "str", "(", "info", ".", "registrar", ")", "tmp", "[", "\"attributes\"", "]", "=", "[", "]", "new", ".", "append", "(", "tmp", ")", "except", ":", "pass", "# Grabbing the regitrar", "try", ":", "tmp", "=", "{", "}", "tmp", "[", "\"type\"", "]", "=", "\"i3visio.fullname\"", "try", ":", "tmp", "[", "\"value\"", "]", "=", "str", "(", "info", ".", "name", ")", "except", ":", "tmp", "[", "\"value\"", "]", "=", "info", ".", "name", "tmp", "[", "\"attributes\"", "]", "=", "[", "]", "new", ".", "append", "(", "tmp", ")", "except", ":", "pass", "return", "new" ]
Method that trie to recover the whois info from a domain. Args: ----- domain: The domain to verify. Returns: -------- dict: A dictionary containing the result as an i3visio entity with its `value`, `type` and `attributes`.
[ "Method", "that", "trie", "to", "recover", "the", "whois", "info", "from", "a", "domain", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/domainfy.py#L73-L150
train
238,302
i3visio/osrframework
osrframework/domainfy.py
createDomains
def createDomains(tlds, nicks=None, nicksFile=None): """ Method that globally permits to generate the domains to be checked. Args: ----- tlds: List of tlds. nicks: List of aliases. nicksFile: The filepath to the aliases file. Returns: -------- list: list of domains to be checked. """ 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: nicks = iF.read().splitlines() for n in nicks: for t in tlds: tmp = { "domain" : n + t["tld"], "type" : t["type"], "tld": t["tld"] } domain_candidates.append(tmp) return domain_candidates
python
def createDomains(tlds, nicks=None, nicksFile=None): """ Method that globally permits to generate the domains to be checked. Args: ----- tlds: List of tlds. nicks: List of aliases. nicksFile: The filepath to the aliases file. Returns: -------- list: list of domains to be checked. """ 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: nicks = iF.read().splitlines() for n in nicks: for t in tlds: tmp = { "domain" : n + t["tld"], "type" : t["type"], "tld": t["tld"] } domain_candidates.append(tmp) return domain_candidates
[ "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", ":", "nicks", "=", "iF", ".", "read", "(", ")", ".", "splitlines", "(", ")", "for", "n", "in", "nicks", ":", "for", "t", "in", "tlds", ":", "tmp", "=", "{", "\"domain\"", ":", "n", "+", "t", "[", "\"tld\"", "]", ",", "\"type\"", ":", "t", "[", "\"type\"", "]", ",", "\"tld\"", ":", "t", "[", "\"tld\"", "]", "}", "domain_candidates", ".", "append", "(", "tmp", ")", "return", "domain_candidates" ]
Method that globally permits to generate the domains to be checked. Args: ----- tlds: List of tlds. nicks: List of aliases. nicksFile: The filepath to the aliases file. Returns: -------- list: list of domains to be checked.
[ "Method", "that", "globally", "permits", "to", "generate", "the", "domains", "to", "be", "checked", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/domainfy.py#L153-L188
train
238,303
i3visio/osrframework
osrframework/mailfy.py
weCanCheckTheseDomains
def weCanCheckTheseDomains(email): """ Method that verifies if a domain can be safely verified. Args: ----- email: the email whose domain will be verified. Returns: -------- bool: it represents whether the domain can be verified. """ # Known platform not to be working... 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." ] #notWorking = [] for n in notWorking: if n in email: print("\t[*] Verification of '{}' aborted. Details:\n\t\t{}".format(general.warning(email), "This domain CANNOT be verified using mailfy.")) return False emailDomains = EMAIL_DOMAINS safe = False for e in EMAIL_DOMAINS: if e in email: safe = True if not safe: print("\t[*] Verification of '{}' aborted. Details:\n\t\t{}".format(general.warning(email), "This domain CANNOT be verified using mailfy.")) return False return True
python
def weCanCheckTheseDomains(email): """ Method that verifies if a domain can be safely verified. Args: ----- email: the email whose domain will be verified. Returns: -------- bool: it represents whether the domain can be verified. """ # Known platform not to be working... 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." ] #notWorking = [] for n in notWorking: if n in email: print("\t[*] Verification of '{}' aborted. Details:\n\t\t{}".format(general.warning(email), "This domain CANNOT be verified using mailfy.")) return False emailDomains = EMAIL_DOMAINS safe = False for e in EMAIL_DOMAINS: if e in email: safe = True if not safe: print("\t[*] Verification of '{}' aborted. Details:\n\t\t{}".format(general.warning(email), "This domain CANNOT be verified using mailfy.")) return False return True
[ "def", "weCanCheckTheseDomains", "(", "email", ")", ":", "# Known platform not to be working...", "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.\"", "]", "#notWorking = []", "for", "n", "in", "notWorking", ":", "if", "n", "in", "email", ":", "print", "(", "\"\\t[*] Verification of '{}' aborted. Details:\\n\\t\\t{}\"", ".", "format", "(", "general", ".", "warning", "(", "email", ")", ",", "\"This domain CANNOT be verified using mailfy.\"", ")", ")", "return", "False", "emailDomains", "=", "EMAIL_DOMAINS", "safe", "=", "False", "for", "e", "in", "EMAIL_DOMAINS", ":", "if", "e", "in", "email", ":", "safe", "=", "True", "if", "not", "safe", ":", "print", "(", "\"\\t[*] Verification of '{}' aborted. Details:\\n\\t\\t{}\"", ".", "format", "(", "general", ".", "warning", "(", "email", ")", ",", "\"This domain CANNOT be verified using mailfy.\"", ")", ")", "return", "False", "return", "True" ]
Method that verifies if a domain can be safely verified. Args: ----- email: the email whose domain will be verified. Returns: -------- bool: it represents whether the domain can be verified.
[ "Method", "that", "verifies", "if", "a", "domain", "can", "be", "safely", "verified", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/mailfy.py#L112-L161
train
238,304
i3visio/osrframework
osrframework/mailfy.py
grabEmails
def grabEmails(emails=None, emailsFile=None, nicks=None, nicksFile=None, domains=EMAIL_DOMAINS, excludeDomains=[]): """ Method that generates a list of emails. Args: ----- emails: Any premade list of emails. emailsFile: Filepath to the emails file (one per line). nicks: A list of aliases. nicksFile: Filepath to the aliases file (one per line). domains: Domains where the aliases will be tested. excludeDomains: Domains to be excluded from the created list. Returns: -------- list: the list of emails that will be verified. """ email_candidates = [] if emails != None: email_candidates = emails elif emailsFile != None: # Reading the emails file with open(emailsFile, "r") as iF: email_candidates = iF.read().splitlines() elif nicks != None: # Iterating the list of nicks for n in nicks: # Iterating the list of possible domains to build the emails for d in domains: if d not in excludeDomains: email_candidates.append(n+"@"+d) elif nicksFile != None: # Reading the list of nicks with open(nicksFile, "r") as iF: nicks = iF.read().splitlines() # Iterating the list of nicks for n in nicks: # Iterating the list of possible domains to build the emails for d in domains: if d not in excludeDomains: email_candidates.append(n+"@"+d) return email_candidates
python
def grabEmails(emails=None, emailsFile=None, nicks=None, nicksFile=None, domains=EMAIL_DOMAINS, excludeDomains=[]): """ Method that generates a list of emails. Args: ----- emails: Any premade list of emails. emailsFile: Filepath to the emails file (one per line). nicks: A list of aliases. nicksFile: Filepath to the aliases file (one per line). domains: Domains where the aliases will be tested. excludeDomains: Domains to be excluded from the created list. Returns: -------- list: the list of emails that will be verified. """ email_candidates = [] if emails != None: email_candidates = emails elif emailsFile != None: # Reading the emails file with open(emailsFile, "r") as iF: email_candidates = iF.read().splitlines() elif nicks != None: # Iterating the list of nicks for n in nicks: # Iterating the list of possible domains to build the emails for d in domains: if d not in excludeDomains: email_candidates.append(n+"@"+d) elif nicksFile != None: # Reading the list of nicks with open(nicksFile, "r") as iF: nicks = iF.read().splitlines() # Iterating the list of nicks for n in nicks: # Iterating the list of possible domains to build the emails for d in domains: if d not in excludeDomains: email_candidates.append(n+"@"+d) return email_candidates
[ "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", ":", "# Reading the emails file", "with", "open", "(", "emailsFile", ",", "\"r\"", ")", "as", "iF", ":", "email_candidates", "=", "iF", ".", "read", "(", ")", ".", "splitlines", "(", ")", "elif", "nicks", "!=", "None", ":", "# Iterating the list of nicks", "for", "n", "in", "nicks", ":", "# Iterating the list of possible domains to build the emails", "for", "d", "in", "domains", ":", "if", "d", "not", "in", "excludeDomains", ":", "email_candidates", ".", "append", "(", "n", "+", "\"@\"", "+", "d", ")", "elif", "nicksFile", "!=", "None", ":", "# Reading the list of nicks", "with", "open", "(", "nicksFile", ",", "\"r\"", ")", "as", "iF", ":", "nicks", "=", "iF", ".", "read", "(", ")", ".", "splitlines", "(", ")", "# Iterating the list of nicks", "for", "n", "in", "nicks", ":", "# Iterating the list of possible domains to build the emails", "for", "d", "in", "domains", ":", "if", "d", "not", "in", "excludeDomains", ":", "email_candidates", ".", "append", "(", "n", "+", "\"@\"", "+", "d", ")", "return", "email_candidates" ]
Method that generates a list of emails. Args: ----- emails: Any premade list of emails. emailsFile: Filepath to the emails file (one per line). nicks: A list of aliases. nicksFile: Filepath to the aliases file (one per line). domains: Domains where the aliases will be tested. excludeDomains: Domains to be excluded from the created list. Returns: -------- list: the list of emails that will be verified.
[ "Method", "that", "generates", "a", "list", "of", "emails", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/mailfy.py#L164-L206
train
238,305
i3visio/osrframework
osrframework/mailfy.py
processMailList
def processMailList(platformNames=[], emails=[]): """ Method to perform the email search. Args: ----- platformNames: List of names of the platforms. emails: List of numbers to be queried. Return: ------- A list of verified emails. """ # Grabbing the <Platform> objects platforms = platform_selection.getPlatformsByName(platformNames, mode="mailfy") results = [] for e in emails: for pla in platforms: # This returns a json.txt! entities = pla.getInfo(query=e, mode="mailfy") if entities != {}: results += json.loads(entities) return results
python
def processMailList(platformNames=[], emails=[]): """ Method to perform the email search. Args: ----- platformNames: List of names of the platforms. emails: List of numbers to be queried. Return: ------- A list of verified emails. """ # Grabbing the <Platform> objects platforms = platform_selection.getPlatformsByName(platformNames, mode="mailfy") results = [] for e in emails: for pla in platforms: # This returns a json.txt! entities = pla.getInfo(query=e, mode="mailfy") if entities != {}: results += json.loads(entities) return results
[ "def", "processMailList", "(", "platformNames", "=", "[", "]", ",", "emails", "=", "[", "]", ")", ":", "# Grabbing the <Platform> objects", "platforms", "=", "platform_selection", ".", "getPlatformsByName", "(", "platformNames", ",", "mode", "=", "\"mailfy\"", ")", "results", "=", "[", "]", "for", "e", "in", "emails", ":", "for", "pla", "in", "platforms", ":", "# This returns a json.txt!", "entities", "=", "pla", ".", "getInfo", "(", "query", "=", "e", ",", "mode", "=", "\"mailfy\"", ")", "if", "entities", "!=", "{", "}", ":", "results", "+=", "json", ".", "loads", "(", "entities", ")", "return", "results" ]
Method to perform the email search. Args: ----- platformNames: List of names of the platforms. emails: List of numbers to be queried. Return: ------- A list of verified emails.
[ "Method", "to", "perform", "the", "email", "search", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/mailfy.py#L209-L232
train
238,306
i3visio/osrframework
osrframework/mailfy.py
pool_function
def pool_function(args): """ A wrapper for being able to launch all the threads. We will use python-emailahoy library for the verification. Args: ----- args: reception of the parameters for getPageWrapper as a tuple. Returns: -------- A dictionary representing whether the verification was ended successfully. The format is as follows: ``` {"platform": "str(domain["value"])", "status": "DONE", "data": aux} ``` """ 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(args), general.success("SUCCESS ({})".format(str(status))), message.replace('\n', '\n\t\t'))) is_valid = True else: print("\t[*] Verification of '{}' status: {}. Details:\n\t\t{}".format(general.error(args), general.error("FAILED ({})".format(str(status))), message.replace('\n', '\n\t\t'))) is_valid = False except Exception, e: print(general.warning("WARNING. An error was found when performing the search. You can omit this message.\n" + str(e))) is_valid = False aux = {} aux["type"] = "i3visio.profile" aux["value"] = "Email - " + args aux["attributes"] = general.expandEntitiesFromEmail(args) platform = aux["attributes"][2]["value"].title() aux["attributes"].append({ "type": "i3visio.platform", "value": platform, "attributes": [] } ) if is_valid: return {"platform": platform, "status": "DONE", "data": aux} else: return {"platform": platform, "status": "DONE", "data": {}}
python
def pool_function(args): """ A wrapper for being able to launch all the threads. We will use python-emailahoy library for the verification. Args: ----- args: reception of the parameters for getPageWrapper as a tuple. Returns: -------- A dictionary representing whether the verification was ended successfully. The format is as follows: ``` {"platform": "str(domain["value"])", "status": "DONE", "data": aux} ``` """ 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(args), general.success("SUCCESS ({})".format(str(status))), message.replace('\n', '\n\t\t'))) is_valid = True else: print("\t[*] Verification of '{}' status: {}. Details:\n\t\t{}".format(general.error(args), general.error("FAILED ({})".format(str(status))), message.replace('\n', '\n\t\t'))) is_valid = False except Exception, e: print(general.warning("WARNING. An error was found when performing the search. You can omit this message.\n" + str(e))) is_valid = False aux = {} aux["type"] = "i3visio.profile" aux["value"] = "Email - " + args aux["attributes"] = general.expandEntitiesFromEmail(args) platform = aux["attributes"][2]["value"].title() aux["attributes"].append({ "type": "i3visio.platform", "value": platform, "attributes": [] } ) if is_valid: return {"platform": platform, "status": "DONE", "data": aux} else: return {"platform": platform, "status": "DONE", "data": {}}
[ "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", "(", "args", ")", ",", "general", ".", "success", "(", "\"SUCCESS ({})\"", ".", "format", "(", "str", "(", "status", ")", ")", ")", ",", "message", ".", "replace", "(", "'\\n'", ",", "'\\n\\t\\t'", ")", ")", ")", "is_valid", "=", "True", "else", ":", "print", "(", "\"\\t[*] Verification of '{}' status: {}. Details:\\n\\t\\t{}\"", ".", "format", "(", "general", ".", "error", "(", "args", ")", ",", "general", ".", "error", "(", "\"FAILED ({})\"", ".", "format", "(", "str", "(", "status", ")", ")", ")", ",", "message", ".", "replace", "(", "'\\n'", ",", "'\\n\\t\\t'", ")", ")", ")", "is_valid", "=", "False", "except", "Exception", ",", "e", ":", "print", "(", "general", ".", "warning", "(", "\"WARNING. An error was found when performing the search. You can omit this message.\\n\"", "+", "str", "(", "e", ")", ")", ")", "is_valid", "=", "False", "aux", "=", "{", "}", "aux", "[", "\"type\"", "]", "=", "\"i3visio.profile\"", "aux", "[", "\"value\"", "]", "=", "\"Email - \"", "+", "args", "aux", "[", "\"attributes\"", "]", "=", "general", ".", "expandEntitiesFromEmail", "(", "args", ")", "platform", "=", "aux", "[", "\"attributes\"", "]", "[", "2", "]", "[", "\"value\"", "]", ".", "title", "(", ")", "aux", "[", "\"attributes\"", "]", ".", "append", "(", "{", "\"type\"", ":", "\"i3visio.platform\"", ",", "\"value\"", ":", "platform", ",", "\"attributes\"", ":", "[", "]", "}", ")", "if", "is_valid", ":", "return", "{", "\"platform\"", ":", "platform", ",", "\"status\"", ":", "\"DONE\"", ",", "\"data\"", ":", "aux", "}", "else", ":", "return", "{", "\"platform\"", ":", "platform", ",", "\"status\"", ":", "\"DONE\"", ",", "\"data\"", ":", "{", "}", "}" ]
A wrapper for being able to launch all the threads. We will use python-emailahoy library for the verification. Args: ----- args: reception of the parameters for getPageWrapper as a tuple. Returns: -------- A dictionary representing whether the verification was ended successfully. The format is as follows: ``` {"platform": "str(domain["value"])", "status": "DONE", "data": aux} ```
[ "A", "wrapper", "for", "being", "able", "to", "launch", "all", "the", "threads", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/mailfy.py#L235-L283
train
238,307
i3visio/osrframework
osrframework/utils/browser.py
Browser.recoverURL
def recoverURL(self, url): """ Public method to recover a resource. Args: ----- url: The URL to be collected. Returns: -------- Returns a resource that has to be read, for instance, with html = self.br.read() """ # Configuring user agents... self.setUserAgent() # Configuring proxies if "https://" in url: self.setProxy(protocol = "https") else: self.setProxy(protocol = "http") # Giving special treatment for .onion platforms if ".onion" in url: try: # TODO: configuring manually the tor bundle pass except: # TODO: capturing the error and eventually trying the tor2web approach #url = url.replace(".onion", ".tor2web.org") pass url = url.replace(".onion", ".onion.cab") # Opening the resource try: recurso = self.br.open(url) except: # Something happened. Maybe the request was forbidden? return None html = recurso.read() return html
python
def recoverURL(self, url): """ Public method to recover a resource. Args: ----- url: The URL to be collected. Returns: -------- Returns a resource that has to be read, for instance, with html = self.br.read() """ # Configuring user agents... self.setUserAgent() # Configuring proxies if "https://" in url: self.setProxy(protocol = "https") else: self.setProxy(protocol = "http") # Giving special treatment for .onion platforms if ".onion" in url: try: # TODO: configuring manually the tor bundle pass except: # TODO: capturing the error and eventually trying the tor2web approach #url = url.replace(".onion", ".tor2web.org") pass url = url.replace(".onion", ".onion.cab") # Opening the resource try: recurso = self.br.open(url) except: # Something happened. Maybe the request was forbidden? return None html = recurso.read() return html
[ "def", "recoverURL", "(", "self", ",", "url", ")", ":", "# Configuring user agents...", "self", ".", "setUserAgent", "(", ")", "# Configuring proxies", "if", "\"https://\"", "in", "url", ":", "self", ".", "setProxy", "(", "protocol", "=", "\"https\"", ")", "else", ":", "self", ".", "setProxy", "(", "protocol", "=", "\"http\"", ")", "# Giving special treatment for .onion platforms", "if", "\".onion\"", "in", "url", ":", "try", ":", "# TODO: configuring manually the tor bundle", "pass", "except", ":", "# TODO: capturing the error and eventually trying the tor2web approach", "#url = url.replace(\".onion\", \".tor2web.org\")", "pass", "url", "=", "url", ".", "replace", "(", "\".onion\"", ",", "\".onion.cab\"", ")", "# Opening the resource", "try", ":", "recurso", "=", "self", ".", "br", ".", "open", "(", "url", ")", "except", ":", "# Something happened. Maybe the request was forbidden?", "return", "None", "html", "=", "recurso", ".", "read", "(", ")", "return", "html" ]
Public method to recover a resource. Args: ----- url: The URL to be collected. Returns: -------- Returns a resource that has to be read, for instance, with html = self.br.read()
[ "Public", "method", "to", "recover", "a", "resource", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/browser.py#L141-L182
train
238,308
i3visio/osrframework
osrframework/utils/browser.py
Browser.setNewPassword
def setNewPassword(self, url, username, password): """ Public method to manually set the credentials for a url in the browser. """ self.br.add_password(url, username, password)
python
def setNewPassword(self, url, username, password): """ Public method to manually set the credentials for a url in the browser. """ self.br.add_password(url, username, password)
[ "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.
[ "Public", "method", "to", "manually", "set", "the", "credentials", "for", "a", "url", "in", "the", "browser", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/browser.py#L184-L188
train
238,309
i3visio/osrframework
osrframework/utils/browser.py
Browser.setProxy
def setProxy(self, protocol="http"): """ Public method to set a proxy for the browser. """ # Setting proxy try: new = { protocol: self.proxies[protocol]} self.br.set_proxies( new ) except: # No proxy defined for that protocol pass
python
def setProxy(self, protocol="http"): """ Public method to set a proxy for the browser. """ # Setting proxy try: new = { protocol: self.proxies[protocol]} self.br.set_proxies( new ) except: # No proxy defined for that protocol pass
[ "def", "setProxy", "(", "self", ",", "protocol", "=", "\"http\"", ")", ":", "# Setting proxy", "try", ":", "new", "=", "{", "protocol", ":", "self", ".", "proxies", "[", "protocol", "]", "}", "self", ".", "br", ".", "set_proxies", "(", "new", ")", "except", ":", "# No proxy defined for that protocol", "pass" ]
Public method to set a proxy for the browser.
[ "Public", "method", "to", "set", "a", "proxy", "for", "the", "browser", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/browser.py#L190-L200
train
238,310
i3visio/osrframework
osrframework/utils/browser.py
Browser.setUserAgent
def setUserAgent(self, uA=None): """ This method will be called whenever a new query will be executed. :param uA: Any User Agent that was needed to be inserted. This parameter is optional. :return: Returns True if a User Agent was inserted and False if no User Agent could be inserted. """ logger = logging.getLogger("osrframework.utils") if not uA: # Setting the User Agents if self.userAgents: # User-Agent (this is cheating, ok?) 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 #logger.debug("Setting the user agent:\t" + str(uA)) self.br.addheaders = [ ('User-agent', uA), ] #self.br.addheaders = [('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'), ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'), ('Accept-Encoding', 'none'), ('Accept-Language', 'es-es,es;q=0.8'), ('Connection', 'keep-alive')] #self.br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) return True
python
def setUserAgent(self, uA=None): """ This method will be called whenever a new query will be executed. :param uA: Any User Agent that was needed to be inserted. This parameter is optional. :return: Returns True if a User Agent was inserted and False if no User Agent could be inserted. """ logger = logging.getLogger("osrframework.utils") if not uA: # Setting the User Agents if self.userAgents: # User-Agent (this is cheating, ok?) 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 #logger.debug("Setting the user agent:\t" + str(uA)) self.br.addheaders = [ ('User-agent', uA), ] #self.br.addheaders = [('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'), ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'), ('Accept-Encoding', 'none'), ('Accept-Language', 'es-es,es;q=0.8'), ('Connection', 'keep-alive')] #self.br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) return True
[ "def", "setUserAgent", "(", "self", ",", "uA", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"osrframework.utils\"", ")", "if", "not", "uA", ":", "# Setting the User Agents", "if", "self", ".", "userAgents", ":", "# User-Agent (this is cheating, ok?)", "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", "#logger.debug(\"Setting the user agent:\\t\" + str(uA))", "self", ".", "br", ".", "addheaders", "=", "[", "(", "'User-agent'", ",", "uA", ")", ",", "]", "#self.br.addheaders = [('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'), ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'), ('Accept-Encoding', 'none'), ('Accept-Language', 'es-es,es;q=0.8'), ('Connection', 'keep-alive')]", "#self.br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)", "return", "True" ]
This method will be called whenever a new query will be executed. :param uA: Any User Agent that was needed to be inserted. This parameter is optional. :return: Returns True if a User Agent was inserted and False if no User Agent could be inserted.
[ "This", "method", "will", "be", "called", "whenever", "a", "new", "query", "will", "be", "executed", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/browser.py#L202-L228
train
238,311
i3visio/osrframework
osrframework/api/twitter_api.py
main
def main(args): """ Query manager. """ # Creating the instance tAW = TwitterAPIWrapper() # Selecting the query to be launched 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 downloaded... " % (len(results)) #write the csv with open('%s_followers.csv' % args.query, 'wb') as f: writer = csv.writer(f) for r in results: writer.writerow([args.query,str(r)]) elif args.type == "get_friends": results = tAW.get_friends(args.query) print "... %s friends downloaded... " % (len(results)) #write the csv with open('%s_friends.csv' % args.query, 'wb') as f: writer = csv.writer(f) for r in results: writer.writerow([args.query,str(r)]) elif args.type == "search_users": results = tAW.search_users(args.query) return results
python
def main(args): """ Query manager. """ # Creating the instance tAW = TwitterAPIWrapper() # Selecting the query to be launched 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 downloaded... " % (len(results)) #write the csv with open('%s_followers.csv' % args.query, 'wb') as f: writer = csv.writer(f) for r in results: writer.writerow([args.query,str(r)]) elif args.type == "get_friends": results = tAW.get_friends(args.query) print "... %s friends downloaded... " % (len(results)) #write the csv with open('%s_friends.csv' % args.query, 'wb') as f: writer = csv.writer(f) for r in results: writer.writerow([args.query,str(r)]) elif args.type == "search_users": results = tAW.search_users(args.query) return results
[ "def", "main", "(", "args", ")", ":", "# Creating the instance", "tAW", "=", "TwitterAPIWrapper", "(", ")", "# Selecting the query to be launched", "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 downloaded... \"", "%", "(", "len", "(", "results", ")", ")", "#write the csv", "with", "open", "(", "'%s_followers.csv'", "%", "args", ".", "query", ",", "'wb'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", "(", "f", ")", "for", "r", "in", "results", ":", "writer", ".", "writerow", "(", "[", "args", ".", "query", ",", "str", "(", "r", ")", "]", ")", "elif", "args", ".", "type", "==", "\"get_friends\"", ":", "results", "=", "tAW", ".", "get_friends", "(", "args", ".", "query", ")", "print", "\"... %s friends downloaded... \"", "%", "(", "len", "(", "results", ")", ")", "#write the csv", "with", "open", "(", "'%s_friends.csv'", "%", "args", ".", "query", ",", "'wb'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", "(", "f", ")", "for", "r", "in", "results", ":", "writer", ".", "writerow", "(", "[", "args", ".", "query", ",", "str", "(", "r", ")", "]", ")", "elif", "args", ".", "type", "==", "\"search_users\"", ":", "results", "=", "tAW", ".", "search_users", "(", "args", ".", "query", ")", "return", "results" ]
Query manager.
[ "Query", "manager", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/api/twitter_api.py#L775-L811
train
238,312
i3visio/osrframework
osrframework/api/twitter_api.py
TwitterAPIWrapper._rate_limit_status
def _rate_limit_status(self, api=None, mode=None): """ Verifying the API limits """ if api == None: api = self.connectToAPI() if mode == None: print json.dumps(api.rate_limit_status(), indent=2) raw_input("<Press ENTER>") else: # Testing if we have enough queries while True: allLimits = api.rate_limit_status() if mode == "get_user": limit = allLimits["resources"]["users"]["/users/show/:id"]["limit"] remaining = allLimits["resources"]["users"]["/users/show/:id"]["remaining"] reset = allLimits["resources"]["users"]["/users/show/:id"]["reset"] elif mode == "get_followers": limit = allLimits["resources"]["followers"]["/followers/ids"]["limit"] remaining = allLimits["resources"]["followers"]["/followers/ids"]["remaining"] reset = allLimits["resources"]["followers"]["/followers/ids"]["reset"] elif mode == "get_friends": limit = allLimits["resources"]["friends"]["/friends/ids"]["limit"] remaining = allLimits["resources"]["friends"]["/friends/ids"]["remaining"] reset = allLimits["resources"]["friends"]["/friends/ids"]["reset"] elif mode == "search_users": limit = allLimits["resources"]["users"]["/users/search"]["limit"] remaining = allLimits["resources"]["users"]["/users/search"]["remaining"] reset = allLimits["resources"]["users"]["/users/search"]["reset"] else: remaining = 1 """elif mode == "get_all_docs": limit = allLimits["resources"]REPLACEME["limit"] remaining = allLimits["resources"]REPLACEME["remaining"] reset = allLimits["resources"]REPLACEME["reset"]""" """elif mode == "get_users": limit = allLimits["resources"]REPLACEME["limit"] remaining = allLimits["resources"]REPLACEME["remaining"] reset = allLimits["resources"]REPLACEME["reset"] """ """else: remaining = 1""" # Checking if we have enough remaining queries if remaining > 0: #raw_input(str(remaining) + " queries yet...") break else: waitTime = 60 print "No more queries remaining, sleeping for " + str(waitTime) +" seconds..." time.sleep(waitTime) return 0
python
def _rate_limit_status(self, api=None, mode=None): """ Verifying the API limits """ if api == None: api = self.connectToAPI() if mode == None: print json.dumps(api.rate_limit_status(), indent=2) raw_input("<Press ENTER>") else: # Testing if we have enough queries while True: allLimits = api.rate_limit_status() if mode == "get_user": limit = allLimits["resources"]["users"]["/users/show/:id"]["limit"] remaining = allLimits["resources"]["users"]["/users/show/:id"]["remaining"] reset = allLimits["resources"]["users"]["/users/show/:id"]["reset"] elif mode == "get_followers": limit = allLimits["resources"]["followers"]["/followers/ids"]["limit"] remaining = allLimits["resources"]["followers"]["/followers/ids"]["remaining"] reset = allLimits["resources"]["followers"]["/followers/ids"]["reset"] elif mode == "get_friends": limit = allLimits["resources"]["friends"]["/friends/ids"]["limit"] remaining = allLimits["resources"]["friends"]["/friends/ids"]["remaining"] reset = allLimits["resources"]["friends"]["/friends/ids"]["reset"] elif mode == "search_users": limit = allLimits["resources"]["users"]["/users/search"]["limit"] remaining = allLimits["resources"]["users"]["/users/search"]["remaining"] reset = allLimits["resources"]["users"]["/users/search"]["reset"] else: remaining = 1 """elif mode == "get_all_docs": limit = allLimits["resources"]REPLACEME["limit"] remaining = allLimits["resources"]REPLACEME["remaining"] reset = allLimits["resources"]REPLACEME["reset"]""" """elif mode == "get_users": limit = allLimits["resources"]REPLACEME["limit"] remaining = allLimits["resources"]REPLACEME["remaining"] reset = allLimits["resources"]REPLACEME["reset"] """ """else: remaining = 1""" # Checking if we have enough remaining queries if remaining > 0: #raw_input(str(remaining) + " queries yet...") break else: waitTime = 60 print "No more queries remaining, sleeping for " + str(waitTime) +" seconds..." time.sleep(waitTime) return 0
[ "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", ":", "# Testing if we have enough queries", "while", "True", ":", "allLimits", "=", "api", ".", "rate_limit_status", "(", ")", "if", "mode", "==", "\"get_user\"", ":", "limit", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"users\"", "]", "[", "\"/users/show/:id\"", "]", "[", "\"limit\"", "]", "remaining", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"users\"", "]", "[", "\"/users/show/:id\"", "]", "[", "\"remaining\"", "]", "reset", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"users\"", "]", "[", "\"/users/show/:id\"", "]", "[", "\"reset\"", "]", "elif", "mode", "==", "\"get_followers\"", ":", "limit", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"followers\"", "]", "[", "\"/followers/ids\"", "]", "[", "\"limit\"", "]", "remaining", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"followers\"", "]", "[", "\"/followers/ids\"", "]", "[", "\"remaining\"", "]", "reset", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"followers\"", "]", "[", "\"/followers/ids\"", "]", "[", "\"reset\"", "]", "elif", "mode", "==", "\"get_friends\"", ":", "limit", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"friends\"", "]", "[", "\"/friends/ids\"", "]", "[", "\"limit\"", "]", "remaining", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"friends\"", "]", "[", "\"/friends/ids\"", "]", "[", "\"remaining\"", "]", "reset", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"friends\"", "]", "[", "\"/friends/ids\"", "]", "[", "\"reset\"", "]", "elif", "mode", "==", "\"search_users\"", ":", "limit", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"users\"", "]", "[", "\"/users/search\"", "]", "[", "\"limit\"", "]", "remaining", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"users\"", "]", "[", "\"/users/search\"", "]", "[", "\"remaining\"", "]", "reset", "=", "allLimits", "[", "\"resources\"", "]", "[", "\"users\"", "]", "[", "\"/users/search\"", "]", "[", "\"reset\"", "]", "else", ":", "remaining", "=", "1", "\"\"\"elif mode == \"get_all_docs\":\n limit = allLimits[\"resources\"]REPLACEME[\"limit\"]\n remaining = allLimits[\"resources\"]REPLACEME[\"remaining\"]\n reset = allLimits[\"resources\"]REPLACEME[\"reset\"]\"\"\"", "\"\"\"elif mode == \"get_users\":\n limit = allLimits[\"resources\"]REPLACEME[\"limit\"]\n remaining = allLimits[\"resources\"]REPLACEME[\"remaining\"]\n reset = allLimits[\"resources\"]REPLACEME[\"reset\"] \"\"\"", "\"\"\"else:\n remaining = 1\"\"\"", "# Checking if we have enough remaining queries", "if", "remaining", ">", "0", ":", "#raw_input(str(remaining) + \" queries yet...\")", "break", "else", ":", "waitTime", "=", "60", "print", "\"No more queries remaining, sleeping for \"", "+", "str", "(", "waitTime", ")", "+", "\" seconds...\"", "time", ".", "sleep", "(", "waitTime", ")", "return", "0" ]
Verifying the API limits
[ "Verifying", "the", "API", "limits" ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/api/twitter_api.py#L62-L113
train
238,313
i3visio/osrframework
osrframework/api/twitter_api.py
TwitterAPIWrapper.get_followers
def get_followers(self, query): """ Method to get the followers of a user. :param query: Query to be performed. :return: List of ids. """ # Connecting to the API api = self._connectToAPI() # Verifying the limits of the API self._rate_limit_status(api=api, mode="get_followers") # Making the call to the API try: friends_ids = api.followers_ids(query) except: return [] """res = [] # Extracting the information from each profile for a in aux: us= self.getUser(a) res.append(self._processUser(us))""" return friends_ids
python
def get_followers(self, query): """ Method to get the followers of a user. :param query: Query to be performed. :return: List of ids. """ # Connecting to the API api = self._connectToAPI() # Verifying the limits of the API self._rate_limit_status(api=api, mode="get_followers") # Making the call to the API try: friends_ids = api.followers_ids(query) except: return [] """res = [] # Extracting the information from each profile for a in aux: us= self.getUser(a) res.append(self._processUser(us))""" return friends_ids
[ "def", "get_followers", "(", "self", ",", "query", ")", ":", "# Connecting to the API", "api", "=", "self", ".", "_connectToAPI", "(", ")", "# Verifying the limits of the API", "self", ".", "_rate_limit_status", "(", "api", "=", "api", ",", "mode", "=", "\"get_followers\"", ")", "# Making the call to the API", "try", ":", "friends_ids", "=", "api", ".", "followers_ids", "(", "query", ")", "except", ":", "return", "[", "]", "\"\"\"res = []\n # Extracting the information from each profile\n for a in aux:\n us= self.getUser(a)\n res.append(self._processUser(us))\"\"\"", "return", "friends_ids" ]
Method to get the followers of a user. :param query: Query to be performed. :return: List of ids.
[ "Method", "to", "get", "the", "followers", "of", "a", "user", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/api/twitter_api.py#L641-L667
train
238,314
i3visio/osrframework
osrframework/api/twitter_api.py
TwitterAPIWrapper.get_friends
def get_friends(self, query): """ Method to get the friends of a user. :param query: Query to be performed. :return: List of users. """ # Connecting to the API api = self._connectToAPI() # Verifying the limits of the API self._rate_limit_status(api=api, mode="get_friends") # Making the call to the API try: friends_ids = api.friends_ids(query) except: return [] """res = [] # Extracting the information from each profile for a in aux: us= self.getUser(a) res.append(self._processUser(us))""" return friends_ids
python
def get_friends(self, query): """ Method to get the friends of a user. :param query: Query to be performed. :return: List of users. """ # Connecting to the API api = self._connectToAPI() # Verifying the limits of the API self._rate_limit_status(api=api, mode="get_friends") # Making the call to the API try: friends_ids = api.friends_ids(query) except: return [] """res = [] # Extracting the information from each profile for a in aux: us= self.getUser(a) res.append(self._processUser(us))""" return friends_ids
[ "def", "get_friends", "(", "self", ",", "query", ")", ":", "# Connecting to the API", "api", "=", "self", ".", "_connectToAPI", "(", ")", "# Verifying the limits of the API", "self", ".", "_rate_limit_status", "(", "api", "=", "api", ",", "mode", "=", "\"get_friends\"", ")", "# Making the call to the API", "try", ":", "friends_ids", "=", "api", ".", "friends_ids", "(", "query", ")", "except", ":", "return", "[", "]", "\"\"\"res = []\n # Extracting the information from each profile\n for a in aux:\n us= self.getUser(a)\n res.append(self._processUser(us))\"\"\"", "return", "friends_ids" ]
Method to get the friends of a user. :param query: Query to be performed. :return: List of users.
[ "Method", "to", "get", "the", "friends", "of", "a", "user", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/api/twitter_api.py#L669-L695
train
238,315
i3visio/osrframework
osrframework/api/twitter_api.py
TwitterAPIWrapper.get_user
def get_user(self, screen_name): """ Method to perform the usufy searches. :param screen_name: nickname to be searched. :return: User. """ # Connecting to the API api = self._connectToAPI() # Verifying the limits of the API self._rate_limit_status(api=api, mode="get_user") aux = [] try: user = api.get_user(screen_name) # Iterate through the results using user._json aux.append(user._json) except tweepy.error.TweepError as e: pass res = [] # Extracting the information from each profile for a in aux: res.append(self._processUser(a)) return res
python
def get_user(self, screen_name): """ Method to perform the usufy searches. :param screen_name: nickname to be searched. :return: User. """ # Connecting to the API api = self._connectToAPI() # Verifying the limits of the API self._rate_limit_status(api=api, mode="get_user") aux = [] try: user = api.get_user(screen_name) # Iterate through the results using user._json aux.append(user._json) except tweepy.error.TweepError as e: pass res = [] # Extracting the information from each profile for a in aux: res.append(self._processUser(a)) return res
[ "def", "get_user", "(", "self", ",", "screen_name", ")", ":", "# Connecting to the API", "api", "=", "self", ".", "_connectToAPI", "(", ")", "# Verifying the limits of the API", "self", ".", "_rate_limit_status", "(", "api", "=", "api", ",", "mode", "=", "\"get_user\"", ")", "aux", "=", "[", "]", "try", ":", "user", "=", "api", ".", "get_user", "(", "screen_name", ")", "# Iterate through the results using user._json", "aux", ".", "append", "(", "user", ".", "_json", ")", "except", "tweepy", ".", "error", ".", "TweepError", "as", "e", ":", "pass", "res", "=", "[", "]", "# Extracting the information from each profile", "for", "a", "in", "aux", ":", "res", ".", "append", "(", "self", ".", "_processUser", "(", "a", ")", ")", "return", "res" ]
Method to perform the usufy searches. :param screen_name: nickname to be searched. :return: User.
[ "Method", "to", "perform", "the", "usufy", "searches", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/api/twitter_api.py#L698-L724
train
238,316
i3visio/osrframework
osrframework/api/twitter_api.py
TwitterAPIWrapper.search_users
def search_users(self, query, n=20, maxUsers=60): """ Method to perform the searchfy searches. :param query: Query to be performed. :param n: Number of results per query. :param maxUsers: Max. number of users to be recovered. :return: List of users """ # Connecting to the API api = self._connectToAPI() # Verifying the limits of the API self._rate_limit_status(api=api, mode="search_users") aux = [] page = 0 # print "Getting page %s of new users..." % page+1 # Making the call to the API try: newUsers = api.search_users(query, n, page) for n in newUsers: aux.append(n._json) #keep grabbing tweets until there are no tweets left to grab while len(aux) < maxUsers & len(newUsers)>0: page+=1 print "Getting page %s of new users..." % page # Grabbing new Users newUsers = api.search_users(query, n, page) # Save the users found aux.extend(newUsers) except: pass res = [] # Extracting the information from each profile for a in aux: res.append(self._processUser(a)) return res
python
def search_users(self, query, n=20, maxUsers=60): """ Method to perform the searchfy searches. :param query: Query to be performed. :param n: Number of results per query. :param maxUsers: Max. number of users to be recovered. :return: List of users """ # Connecting to the API api = self._connectToAPI() # Verifying the limits of the API self._rate_limit_status(api=api, mode="search_users") aux = [] page = 0 # print "Getting page %s of new users..." % page+1 # Making the call to the API try: newUsers = api.search_users(query, n, page) for n in newUsers: aux.append(n._json) #keep grabbing tweets until there are no tweets left to grab while len(aux) < maxUsers & len(newUsers)>0: page+=1 print "Getting page %s of new users..." % page # Grabbing new Users newUsers = api.search_users(query, n, page) # Save the users found aux.extend(newUsers) except: pass res = [] # Extracting the information from each profile for a in aux: res.append(self._processUser(a)) return res
[ "def", "search_users", "(", "self", ",", "query", ",", "n", "=", "20", ",", "maxUsers", "=", "60", ")", ":", "# Connecting to the API", "api", "=", "self", ".", "_connectToAPI", "(", ")", "# Verifying the limits of the API", "self", ".", "_rate_limit_status", "(", "api", "=", "api", ",", "mode", "=", "\"search_users\"", ")", "aux", "=", "[", "]", "page", "=", "0", "# print \"Getting page %s of new users...\" % page+1", "# Making the call to the API", "try", ":", "newUsers", "=", "api", ".", "search_users", "(", "query", ",", "n", ",", "page", ")", "for", "n", "in", "newUsers", ":", "aux", ".", "append", "(", "n", ".", "_json", ")", "#keep grabbing tweets until there are no tweets left to grab", "while", "len", "(", "aux", ")", "<", "maxUsers", "&", "len", "(", "newUsers", ")", ">", "0", ":", "page", "+=", "1", "print", "\"Getting page %s of new users...\"", "%", "page", "# Grabbing new Users", "newUsers", "=", "api", ".", "search_users", "(", "query", ",", "n", ",", "page", ")", "# Save the users found", "aux", ".", "extend", "(", "newUsers", ")", "except", ":", "pass", "res", "=", "[", "]", "# Extracting the information from each profile", "for", "a", "in", "aux", ":", "res", ".", "append", "(", "self", ".", "_processUser", "(", "a", ")", ")", "return", "res" ]
Method to perform the searchfy searches. :param query: Query to be performed. :param n: Number of results per query. :param maxUsers: Max. number of users to be recovered. :return: List of users
[ "Method", "to", "perform", "the", "searchfy", "searches", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/api/twitter_api.py#L726-L772
train
238,317
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/source.py
Source.validate_categories
def validate_categories(categories): """Take an iterable of source categories and raise ValueError if some of them are invalid.""" if not set(categories) <= Source.categories: invalid = list(set(categories) - Source.categories) raise ValueError('Invalid categories: %s' % invalid)
python
def validate_categories(categories): """Take an iterable of source categories and raise ValueError if some of them are invalid.""" if not set(categories) <= Source.categories: invalid = list(set(categories) - Source.categories) raise ValueError('Invalid categories: %s' % invalid)
[ "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.
[ "Take", "an", "iterable", "of", "source", "categories", "and", "raise", "ValueError", "if", "some", "of", "them", "are", "invalid", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/source.py#L50-L55
train
238,318
i3visio/osrframework
osrframework/thirdparties/md5db_net/checkIfHashIsCracked.py
checkIfHashIsCracked
def checkIfHashIsCracked(hash=None): """ Method that checks if the given hash is stored in the md5db.net website. :param hash: hash to verify. :return: Resolved hash. If nothing was found, it will return an empty list. """ apiURL = "http://md5db.net/api/" + str(hash).lower() try: # Getting the result of the query from MD5db.net data = urllib2.urlopen(apiURL).read() return data except: # No information was found, then we return a null entity return []
python
def checkIfHashIsCracked(hash=None): """ Method that checks if the given hash is stored in the md5db.net website. :param hash: hash to verify. :return: Resolved hash. If nothing was found, it will return an empty list. """ apiURL = "http://md5db.net/api/" + str(hash).lower() try: # Getting the result of the query from MD5db.net data = urllib2.urlopen(apiURL).read() return data except: # No information was found, then we return a null entity return []
[ "def", "checkIfHashIsCracked", "(", "hash", "=", "None", ")", ":", "apiURL", "=", "\"http://md5db.net/api/\"", "+", "str", "(", "hash", ")", ".", "lower", "(", ")", "try", ":", "# Getting the result of the query from MD5db.net", "data", "=", "urllib2", ".", "urlopen", "(", "apiURL", ")", ".", "read", "(", ")", "return", "data", "except", ":", "# No information was found, then we return a null entity", "return", "[", "]" ]
Method that checks if the given hash is stored in the md5db.net website. :param hash: hash to verify. :return: Resolved hash. If nothing was found, it will return an empty list.
[ "Method", "that", "checks", "if", "the", "given", "hash", "is", "stored", "in", "the", "md5db", ".", "net", "website", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/md5db_net/checkIfHashIsCracked.py#L26-L46
train
238,319
i3visio/osrframework
osrframework/usufy.py
fuzzUsufy
def fuzzUsufy(fDomains = None, fFuzzStruct = None): """ Method to guess the usufy path against a list of domains or subdomains. Args: ----- fDomains: A list to strings containing the domains and (optionally) a nick. fFuzzStruct: A list to strings containing the transforms to be performed. Returns: -------- dict: A dictionary of the form of `{"domain": "url"}`. """ if fFuzzStruct == None: # Loading these structures by default fuzzingStructures = [ "http://<DOMAIN>/<USERNAME>", "http://<DOMAIN>/~<USERNAME>", "http://<DOMAIN>/?action=profile;user=<USERNAME>", "http://<DOMAIN>/causes/author/<USERNAME>", "http://<DOMAIN>/channel/<USERNAME>", "http://<DOMAIN>/community/profile/<USERNAME>", "http://<DOMAIN>/component/comprofiler/userprofiler/<USERNAME>", "http://<DOMAIN>/details/@<USERNAME>", "http://<DOMAIN>/foros/member.php?username=<USERNAME>", "http://<DOMAIN>/forum/member/<USERNAME>", "http://<DOMAIN>/forum/member.php?username=<USERNAME>", "http://<DOMAIN>/forum/profile.php?mode=viewprofile&u=<USERNAME>", "http://<DOMAIN>/home/<USERNAME>", "http://<DOMAIN>/index.php?action=profile;user=<USERNAME>", "http://<DOMAIN>/member_profile.php?u=<USERNAME>", "http://<DOMAIN>/member.php?username=<USERNAME>", "http://<DOMAIN>/members/?username=<USERNAME>", "http://<DOMAIN>/members/<USERNAME>", "http://<DOMAIN>/members/view/<USERNAME>", "http://<DOMAIN>/mi-espacio/<USERNAME>", "http://<DOMAIN>/u<USERNAME>", "http://<DOMAIN>/u/<USERNAME>", "http://<DOMAIN>/user-<USERNAME>", "http://<DOMAIN>/user/<USERNAME>", "http://<DOMAIN>/user/<USERNAME>.html", "http://<DOMAIN>/users/<USERNAME>", "http://<DOMAIN>/usr/<USERNAME>", "http://<DOMAIN>/usuario/<USERNAME>", "http://<DOMAIN>/usuarios/<USERNAME>", "http://<DOMAIN>/en/users/<USERNAME>", "http://<DOMAIN>/people/<USERNAME>", "http://<DOMAIN>/profil/<USERNAME>", "http://<DOMAIN>/profile/<USERNAME>", "http://<DOMAIN>/profile/page/<USERNAME>", "http://<DOMAIN>/rapidforum/index.php?action=profile;user=<USERNAME>", "http://<DOMAIN>/social/usuarios/<USERNAME>", "http://<USERNAME>.<DOMAIN>", "http://<USERNAME>.<DOMAIN>/user/" ] else: try: fuzzingStructures = fFuzzStruct.read().splitlines() except: print("Usufy could NOT open the following file: " + fFuzzStruct) res = {} lines = fDomains.read().splitlines() # Going through all the lines for l in lines: domain = l.split()[0] print("Performing tests for" + domain + "...") # selecting the number of nicks to be tested in this domain nick = l.split()[1] # possibleURLs found possibleURL = [] for struct in fuzzingStructures: # initiating list urlToTry = struct.replace("<DOMAIN>", domain) test = urlToTry.replace("<USERNAME>", nick.lower()) print("Processing "+ test + "...") i3Browser = browser.Browser() try: html = i3Browser.recoverURL(test) if nick in html: possibleURL.append(test) print(general.success("\tPossible usufy found!!!\n")) except: print("The resource could not be downloaded.") res[domain] = possibleURL print(json.dumps(res, indent = 2)) return res
python
def fuzzUsufy(fDomains = None, fFuzzStruct = None): """ Method to guess the usufy path against a list of domains or subdomains. Args: ----- fDomains: A list to strings containing the domains and (optionally) a nick. fFuzzStruct: A list to strings containing the transforms to be performed. Returns: -------- dict: A dictionary of the form of `{"domain": "url"}`. """ if fFuzzStruct == None: # Loading these structures by default fuzzingStructures = [ "http://<DOMAIN>/<USERNAME>", "http://<DOMAIN>/~<USERNAME>", "http://<DOMAIN>/?action=profile;user=<USERNAME>", "http://<DOMAIN>/causes/author/<USERNAME>", "http://<DOMAIN>/channel/<USERNAME>", "http://<DOMAIN>/community/profile/<USERNAME>", "http://<DOMAIN>/component/comprofiler/userprofiler/<USERNAME>", "http://<DOMAIN>/details/@<USERNAME>", "http://<DOMAIN>/foros/member.php?username=<USERNAME>", "http://<DOMAIN>/forum/member/<USERNAME>", "http://<DOMAIN>/forum/member.php?username=<USERNAME>", "http://<DOMAIN>/forum/profile.php?mode=viewprofile&u=<USERNAME>", "http://<DOMAIN>/home/<USERNAME>", "http://<DOMAIN>/index.php?action=profile;user=<USERNAME>", "http://<DOMAIN>/member_profile.php?u=<USERNAME>", "http://<DOMAIN>/member.php?username=<USERNAME>", "http://<DOMAIN>/members/?username=<USERNAME>", "http://<DOMAIN>/members/<USERNAME>", "http://<DOMAIN>/members/view/<USERNAME>", "http://<DOMAIN>/mi-espacio/<USERNAME>", "http://<DOMAIN>/u<USERNAME>", "http://<DOMAIN>/u/<USERNAME>", "http://<DOMAIN>/user-<USERNAME>", "http://<DOMAIN>/user/<USERNAME>", "http://<DOMAIN>/user/<USERNAME>.html", "http://<DOMAIN>/users/<USERNAME>", "http://<DOMAIN>/usr/<USERNAME>", "http://<DOMAIN>/usuario/<USERNAME>", "http://<DOMAIN>/usuarios/<USERNAME>", "http://<DOMAIN>/en/users/<USERNAME>", "http://<DOMAIN>/people/<USERNAME>", "http://<DOMAIN>/profil/<USERNAME>", "http://<DOMAIN>/profile/<USERNAME>", "http://<DOMAIN>/profile/page/<USERNAME>", "http://<DOMAIN>/rapidforum/index.php?action=profile;user=<USERNAME>", "http://<DOMAIN>/social/usuarios/<USERNAME>", "http://<USERNAME>.<DOMAIN>", "http://<USERNAME>.<DOMAIN>/user/" ] else: try: fuzzingStructures = fFuzzStruct.read().splitlines() except: print("Usufy could NOT open the following file: " + fFuzzStruct) res = {} lines = fDomains.read().splitlines() # Going through all the lines for l in lines: domain = l.split()[0] print("Performing tests for" + domain + "...") # selecting the number of nicks to be tested in this domain nick = l.split()[1] # possibleURLs found possibleURL = [] for struct in fuzzingStructures: # initiating list urlToTry = struct.replace("<DOMAIN>", domain) test = urlToTry.replace("<USERNAME>", nick.lower()) print("Processing "+ test + "...") i3Browser = browser.Browser() try: html = i3Browser.recoverURL(test) if nick in html: possibleURL.append(test) print(general.success("\tPossible usufy found!!!\n")) except: print("The resource could not be downloaded.") res[domain] = possibleURL print(json.dumps(res, indent = 2)) return res
[ "def", "fuzzUsufy", "(", "fDomains", "=", "None", ",", "fFuzzStruct", "=", "None", ")", ":", "if", "fFuzzStruct", "==", "None", ":", "# Loading these structures by default", "fuzzingStructures", "=", "[", "\"http://<DOMAIN>/<USERNAME>\"", ",", "\"http://<DOMAIN>/~<USERNAME>\"", ",", "\"http://<DOMAIN>/?action=profile;user=<USERNAME>\"", ",", "\"http://<DOMAIN>/causes/author/<USERNAME>\"", ",", "\"http://<DOMAIN>/channel/<USERNAME>\"", ",", "\"http://<DOMAIN>/community/profile/<USERNAME>\"", ",", "\"http://<DOMAIN>/component/comprofiler/userprofiler/<USERNAME>\"", ",", "\"http://<DOMAIN>/details/@<USERNAME>\"", ",", "\"http://<DOMAIN>/foros/member.php?username=<USERNAME>\"", ",", "\"http://<DOMAIN>/forum/member/<USERNAME>\"", ",", "\"http://<DOMAIN>/forum/member.php?username=<USERNAME>\"", ",", "\"http://<DOMAIN>/forum/profile.php?mode=viewprofile&u=<USERNAME>\"", ",", "\"http://<DOMAIN>/home/<USERNAME>\"", ",", "\"http://<DOMAIN>/index.php?action=profile;user=<USERNAME>\"", ",", "\"http://<DOMAIN>/member_profile.php?u=<USERNAME>\"", ",", "\"http://<DOMAIN>/member.php?username=<USERNAME>\"", ",", "\"http://<DOMAIN>/members/?username=<USERNAME>\"", ",", "\"http://<DOMAIN>/members/<USERNAME>\"", ",", "\"http://<DOMAIN>/members/view/<USERNAME>\"", ",", "\"http://<DOMAIN>/mi-espacio/<USERNAME>\"", ",", "\"http://<DOMAIN>/u<USERNAME>\"", ",", "\"http://<DOMAIN>/u/<USERNAME>\"", ",", "\"http://<DOMAIN>/user-<USERNAME>\"", ",", "\"http://<DOMAIN>/user/<USERNAME>\"", ",", "\"http://<DOMAIN>/user/<USERNAME>.html\"", ",", "\"http://<DOMAIN>/users/<USERNAME>\"", ",", "\"http://<DOMAIN>/usr/<USERNAME>\"", ",", "\"http://<DOMAIN>/usuario/<USERNAME>\"", ",", "\"http://<DOMAIN>/usuarios/<USERNAME>\"", ",", "\"http://<DOMAIN>/en/users/<USERNAME>\"", ",", "\"http://<DOMAIN>/people/<USERNAME>\"", ",", "\"http://<DOMAIN>/profil/<USERNAME>\"", ",", "\"http://<DOMAIN>/profile/<USERNAME>\"", ",", "\"http://<DOMAIN>/profile/page/<USERNAME>\"", ",", "\"http://<DOMAIN>/rapidforum/index.php?action=profile;user=<USERNAME>\"", ",", "\"http://<DOMAIN>/social/usuarios/<USERNAME>\"", ",", "\"http://<USERNAME>.<DOMAIN>\"", ",", "\"http://<USERNAME>.<DOMAIN>/user/\"", "]", "else", ":", "try", ":", "fuzzingStructures", "=", "fFuzzStruct", ".", "read", "(", ")", ".", "splitlines", "(", ")", "except", ":", "print", "(", "\"Usufy could NOT open the following file: \"", "+", "fFuzzStruct", ")", "res", "=", "{", "}", "lines", "=", "fDomains", ".", "read", "(", ")", ".", "splitlines", "(", ")", "# Going through all the lines", "for", "l", "in", "lines", ":", "domain", "=", "l", ".", "split", "(", ")", "[", "0", "]", "print", "(", "\"Performing tests for\"", "+", "domain", "+", "\"...\"", ")", "# selecting the number of nicks to be tested in this domain", "nick", "=", "l", ".", "split", "(", ")", "[", "1", "]", "# possibleURLs found", "possibleURL", "=", "[", "]", "for", "struct", "in", "fuzzingStructures", ":", "# initiating list", "urlToTry", "=", "struct", ".", "replace", "(", "\"<DOMAIN>\"", ",", "domain", ")", "test", "=", "urlToTry", ".", "replace", "(", "\"<USERNAME>\"", ",", "nick", ".", "lower", "(", ")", ")", "print", "(", "\"Processing \"", "+", "test", "+", "\"...\"", ")", "i3Browser", "=", "browser", ".", "Browser", "(", ")", "try", ":", "html", "=", "i3Browser", ".", "recoverURL", "(", "test", ")", "if", "nick", "in", "html", ":", "possibleURL", ".", "append", "(", "test", ")", "print", "(", "general", ".", "success", "(", "\"\\tPossible usufy found!!!\\n\"", ")", ")", "except", ":", "print", "(", "\"The resource could not be downloaded.\"", ")", "res", "[", "domain", "]", "=", "possibleURL", "print", "(", "json", ".", "dumps", "(", "res", ",", "indent", "=", "2", ")", ")", "return", "res" ]
Method to guess the usufy path against a list of domains or subdomains. Args: ----- fDomains: A list to strings containing the domains and (optionally) a nick. fFuzzStruct: A list to strings containing the transforms to be performed. Returns: -------- dict: A dictionary of the form of `{"domain": "url"}`.
[ "Method", "to", "guess", "the", "usufy", "path", "against", "a", "list", "of", "domains", "or", "subdomains", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/usufy.py#L50-L145
train
238,320
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/search.py
SearchAPIRequest._prepare_filtering_params
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): """Transform the params to the API format, return a list of params.""" if query_params_match not in (None, True): raise ValueError('query_params_match can only be `True`') if query_person_match not in (None, True): raise ValueError('query_person_match can only be `True`') params = [] if domain is not None: params.append('domain:%s' % domain) if category is not None: Source.validate_categories([category]) params.append('category:%s' % category) if sponsored_source is not None: params.append('sponsored_source:%s' % sponsored_source) if query_params_match is not None: params.append('query_params_match') if query_person_match is not None: params.append('query_person_match') has_fields = has_fields or [] if has_field is not None: has_fields.append(has_field) for has_field in has_fields: params.append('has_field:%s' % has_field.__name__) return params
python
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): """Transform the params to the API format, return a list of params.""" if query_params_match not in (None, True): raise ValueError('query_params_match can only be `True`') if query_person_match not in (None, True): raise ValueError('query_person_match can only be `True`') params = [] if domain is not None: params.append('domain:%s' % domain) if category is not None: Source.validate_categories([category]) params.append('category:%s' % category) if sponsored_source is not None: params.append('sponsored_source:%s' % sponsored_source) if query_params_match is not None: params.append('query_params_match') if query_person_match is not None: params.append('query_person_match') has_fields = has_fields or [] if has_field is not None: has_fields.append(has_field) for has_field in has_fields: params.append('has_field:%s' % has_field.__name__) return params
[ "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_person_match", "not", "in", "(", "None", ",", "True", ")", ":", "raise", "ValueError", "(", "'query_person_match can only be `True`'", ")", "params", "=", "[", "]", "if", "domain", "is", "not", "None", ":", "params", ".", "append", "(", "'domain:%s'", "%", "domain", ")", "if", "category", "is", "not", "None", ":", "Source", ".", "validate_categories", "(", "[", "category", "]", ")", "params", ".", "append", "(", "'category:%s'", "%", "category", ")", "if", "sponsored_source", "is", "not", "None", ":", "params", ".", "append", "(", "'sponsored_source:%s'", "%", "sponsored_source", ")", "if", "query_params_match", "is", "not", "None", ":", "params", ".", "append", "(", "'query_params_match'", ")", "if", "query_person_match", "is", "not", "None", ":", "params", ".", "append", "(", "'query_person_match'", ")", "has_fields", "=", "has_fields", "or", "[", "]", "if", "has_field", "is", "not", "None", ":", "has_fields", ".", "append", "(", "has_field", ")", "for", "has_field", "in", "has_fields", ":", "params", ".", "append", "(", "'has_field:%s'", "%", "has_field", ".", "__name__", ")", "return", "params" ]
Transform the params to the API format, return a list of params.
[ "Transform", "the", "params", "to", "the", "API", "format", "return", "a", "list", "of", "params", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/search.py#L180-L207
train
238,321
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/search.py
SearchAPIRequest.validate_query_params
def validate_query_params(self, strict=True): """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. """ 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: raise ValueError('No valid name/username/phone/email in request') if strict and self.person.unsearchable_fields: raise ValueError('Some fields are unsearchable: %s' % self.person.unsearchable_fields)
python
def validate_query_params(self, strict=True): """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. """ 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: raise ValueError('No valid name/username/phone/email in request') if strict and self.person.unsearchable_fields: raise ValueError('Some fields are unsearchable: %s' % self.person.unsearchable_fields)
[ "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", ":", "raise", "ValueError", "(", "'No valid name/username/phone/email in request'", ")", "if", "strict", "and", "self", ".", "person", ".", "unsearchable_fields", ":", "raise", "ValueError", "(", "'Some fields are unsearchable: %s'", "%", "self", ".", "person", ".", "unsearchable_fields", ")" ]
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.
[ "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", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/search.py#L322-L340
train
238,322
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/search.py
SearchAPIResponse.group_records_by_domain
def group_records_by_domain(self): """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. """ key_function = lambda record: record.source.domain return self.group_records(key_function)
python
def group_records_by_domain(self): """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. """ key_function = lambda record: record.source.domain return self.group_records(key_function)
[ "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.
[ "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", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/search.py#L532-L540
train
238,323
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/search.py
SearchAPIResponse.group_records_by_category
def group_records_by_category(self): """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. """ Source.validate_categories(categories) key_function = lambda record: record.source.category return self.group_records(key_function)
python
def group_records_by_category(self): """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. """ Source.validate_categories(categories) key_function = lambda record: record.source.category return self.group_records(key_function)
[ "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.
[ "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", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/search.py#L542-L551
train
238,324
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/search.py
SearchAPIResponse.from_dict
def from_dict(d): """Transform the dict to a response object and return the response.""" 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) for record in records] suggested_searches = d.get('suggested_searches') if suggested_searches: suggested_searches = [Record.from_dict(record) for record in suggested_searches] return SearchAPIResponse(query=query, person=person, records=records, suggested_searches=suggested_searches, warnings_=warnings_)
python
def from_dict(d): """Transform the dict to a response object and return the response.""" 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) for record in records] suggested_searches = d.get('suggested_searches') if suggested_searches: suggested_searches = [Record.from_dict(record) for record in suggested_searches] return SearchAPIResponse(query=query, person=person, records=records, suggested_searches=suggested_searches, warnings_=warnings_)
[ "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", ")", "for", "record", "in", "records", "]", "suggested_searches", "=", "d", ".", "get", "(", "'suggested_searches'", ")", "if", "suggested_searches", ":", "suggested_searches", "=", "[", "Record", ".", "from_dict", "(", "record", ")", "for", "record", "in", "suggested_searches", "]", "return", "SearchAPIResponse", "(", "query", "=", "query", ",", "person", "=", "person", ",", "records", "=", "records", ",", "suggested_searches", "=", "suggested_searches", ",", "warnings_", "=", "warnings_", ")" ]
Transform the dict to a response object and return the response.
[ "Transform", "the", "dict", "to", "a", "response", "object", "and", "return", "the", "response", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/search.py#L576-L594
train
238,325
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/search.py
SearchAPIResponse.to_dict
def to_dict(self): """Return a dict representation of the response.""" 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.records] if self.suggested_searches: d['suggested_searches'] = [record.to_dict() for record in self.suggested_searches] return d
python
def to_dict(self): """Return a dict representation of the response.""" 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.records] if self.suggested_searches: d['suggested_searches'] = [record.to_dict() for record in self.suggested_searches] return d
[ "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", ".", "records", "]", "if", "self", ".", "suggested_searches", ":", "d", "[", "'suggested_searches'", "]", "=", "[", "record", ".", "to_dict", "(", ")", "for", "record", "in", "self", ".", "suggested_searches", "]", "return", "d" ]
Return a dict representation of the response.
[ "Return", "a", "dict", "representation", "of", "the", "response", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/search.py#L596-L610
train
238,326
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
Field.from_dict
def from_dict(cls, d): """Transform the dict to a field object and return the field.""" kwargs = {} for key, val in d.iteritems(): if key.startswith('display'): # includes phone.display_international 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(val) kwargs[key.encode('ascii')] = val return cls(**kwargs)
python
def from_dict(cls, d): """Transform the dict to a field object and return the field.""" kwargs = {} for key, val in d.iteritems(): if key.startswith('display'): # includes phone.display_international 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(val) kwargs[key.encode('ascii')] = val return cls(**kwargs)
[ "def", "from_dict", "(", "cls", ",", "d", ")", ":", "kwargs", "=", "{", "}", "for", "key", ",", "val", "in", "d", ".", "iteritems", "(", ")", ":", "if", "key", ".", "startswith", "(", "'display'", ")", ":", "# includes phone.display_international\r", "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", "(", "val", ")", "kwargs", "[", "key", ".", "encode", "(", "'ascii'", ")", "]", "=", "val", "return", "cls", "(", "*", "*", "kwargs", ")" ]
Transform the dict to a field object and return the field.
[ "Transform", "the", "dict", "to", "a", "field", "object", "and", "return", "the", "field", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L87-L102
train
238,327
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
Field.to_dict
def to_dict(self): """Return a dict representation of the field.""" 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 = value.to_dict() if value or isinstance(value, (bool, int, long)): d[prefix + attr] = value if hasattr(self, 'display') and self.display: d['display'] = self.display return d
python
def to_dict(self): """Return a dict representation of the field.""" 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 = value.to_dict() if value or isinstance(value, (bool, int, long)): d[prefix + attr] = value if hasattr(self, 'display') and self.display: d['display'] = self.display return d
[ "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", "=", "value", ".", "to_dict", "(", ")", "if", "value", "or", "isinstance", "(", "value", ",", "(", "bool", ",", "int", ",", "long", ")", ")", ":", "d", "[", "prefix", "+", "attr", "]", "=", "value", "if", "hasattr", "(", "self", ",", "'display'", ")", "and", "self", ".", "display", ":", "d", "[", "'display'", "]", "=", "self", ".", "display", "return", "d" ]
Return a dict representation of the field.
[ "Return", "a", "dict", "representation", "of", "the", "field", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L104-L118
train
238,328
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
Name.is_searchable
def is_searchable(self): """A bool value that indicates whether the name is a valid name to search by.""" 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
python
def is_searchable(self): """A bool value that indicates whether the name is a valid name to search by.""" 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
[ "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.
[ "A", "bool", "value", "that", "indicates", "whether", "the", "name", "is", "a", "valid", "name", "to", "search", "by", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L163-L169
train
238,329
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
Address.is_searchable
def is_searchable(self): """A bool value that indicates whether the address is a valid address to search by.""" return self.raw or (self.is_valid_country and (not self.state or self.is_valid_state))
python
def is_searchable(self): """A bool value that indicates whether the address is a valid address to search by.""" return self.raw or (self.is_valid_country and (not self.state or self.is_valid_state))
[ "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.
[ "A", "bool", "value", "that", "indicates", "whether", "the", "address", "is", "a", "valid", "address", "to", "search", "by", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L233-L237
train
238,330
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
Address.is_valid_state
def is_valid_state(self): """A bool value that indicates whether the object's state is a valid state code.""" 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()]
python
def is_valid_state(self): """A bool value that indicates whether the object's state is a valid state code.""" 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()]
[ "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.
[ "A", "bool", "value", "that", "indicates", "whether", "the", "object", "s", "state", "is", "a", "valid", "state", "code", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L246-L251
train
238,331
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
Phone.to_dict
def to_dict(self): """Extend Field.to_dict, take the display_international attribute.""" d = Field.to_dict(self) if self.display_international: d['display_international'] = self.display_international return d
python
def to_dict(self): """Extend Field.to_dict, take the display_international attribute.""" d = Field.to_dict(self) if self.display_international: d['display_international'] = self.display_international return d
[ "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.
[ "Extend", "Field", ".", "to_dict", "take", "the", "display_international", "attribute", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L345-L350
train
238,332
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
Email.is_valid_email
def is_valid_email(self): """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... """ return bool(self.address and Email.re_email.match(self.address))
python
def is_valid_email(self): """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... """ return bool(self.address and Email.re_email.match(self.address))
[ "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...
[ "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", "..." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L383-L391
train
238,333
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
DOB.age
def age(self): """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. """ 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
python
def age(self): """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. """ 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
[ "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.
[ "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", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L619-L634
train
238,334
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
DOB.age_range
def age_range(self): """A tuple of two ints - the minimum and maximum age of the person.""" 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).age return start_age, end_age
python
def age_range(self): """A tuple of two ints - the minimum and maximum age of the person.""" 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).age return start_age, end_age
[ "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", ")", ".", "age", "return", "start_age", ",", "end_age" ]
A tuple of two ints - the minimum and maximum age of the person.
[ "A", "tuple", "of", "two", "ints", "-", "the", "minimum", "and", "maximum", "age", "of", "the", "person", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L637-L645
train
238,335
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
DOB.from_age_range
def from_age_range(start_age, end_age): """Take a person's minimal and maximal age and return a new DOB object suitable for him.""" 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) except ValueError: # February 29 start_date = today.replace(year=today.year - end_age - 1, day=28) start_date += datetime.timedelta(days=1) try: end_date = today.replace(year=today.year - start_age) except ValueError: # February 29 end_date = today.replace(year=today.year - start_age, day=28) date_range = DateRange(start_date, end_date) return DOB(date_range=date_range)
python
def from_age_range(start_age, end_age): """Take a person's minimal and maximal age and return a new DOB object suitable for him.""" 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) except ValueError: # February 29 start_date = today.replace(year=today.year - end_age - 1, day=28) start_date += datetime.timedelta(days=1) try: end_date = today.replace(year=today.year - start_age) except ValueError: # February 29 end_date = today.replace(year=today.year - start_age, day=28) date_range = DateRange(start_date, end_date) return DOB(date_range=date_range)
[ "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", ")", "except", "ValueError", ":", "# February 29\r", "start_date", "=", "today", ".", "replace", "(", "year", "=", "today", ".", "year", "-", "end_age", "-", "1", ",", "day", "=", "28", ")", "start_date", "+=", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "try", ":", "end_date", "=", "today", ".", "replace", "(", "year", "=", "today", ".", "year", "-", "start_age", ")", "except", "ValueError", ":", "# February 29\r", "end_date", "=", "today", ".", "replace", "(", "year", "=", "today", ".", "year", "-", "start_age", ",", "day", "=", "28", ")", "date_range", "=", "DateRange", "(", "start_date", ",", "end_date", ")", "return", "DOB", "(", "date_range", "=", "date_range", ")" ]
Take a person's minimal and maximal age and return a new DOB object suitable for him.
[ "Take", "a", "person", "s", "minimal", "and", "maximal", "age", "and", "return", "a", "new", "DOB", "object", "suitable", "for", "him", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L672-L695
train
238,336
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
Relationship.from_dict
def from_dict(cls, d): """Extend Field.from_dict and also load the name from the dict.""" relationship = super(cls, cls).from_dict(d) if relationship.name is not None: relationship.name = Name.from_dict(relationship.name) return relationship
python
def from_dict(cls, d): """Extend Field.from_dict and also load the name from the dict.""" relationship = super(cls, cls).from_dict(d) if relationship.name is not None: relationship.name = Name.from_dict(relationship.name) return relationship
[ "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.
[ "Extend", "Field", ".", "from_dict", "and", "also", "load", "the", "name", "from", "the", "dict", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L762-L767
train
238,337
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
DateRange.from_dict
def from_dict(d): """Transform the dict to a DateRange object.""" 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)
python
def from_dict(d): """Transform the dict to a DateRange object.""" 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)
[ "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.
[ "Transform", "the", "dict", "to", "a", "DateRange", "object", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L854-L862
train
238,338
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/fields.py
DateRange.to_dict
def to_dict(self): """Transform the date-range to a dict.""" d = {} d['start'] = date_to_str(self.start) d['end'] = date_to_str(self.end) return d
python
def to_dict(self): """Transform the date-range to a dict.""" d = {} d['start'] = date_to_str(self.start) d['end'] = date_to_str(self.end) return d
[ "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.
[ "Transform", "the", "date", "-", "range", "to", "a", "dict", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/fields.py#L864-L869
train
238,339
i3visio/osrframework
osrframework/enumeration.py
enumerateURL
def enumerateURL(urlDict, outputFolder, startIndex= 0, maxErrors = 100): """ Function that performs the enumeration itself. """ for i, url in enumerate(urlDict.keys()): # Grabbing domain name: domain = re.findall("://(.*)/", url)[0] # Defining the starting index index = startIndex # The app will stop when this value reaches maxErrors consecutiveErrors = 0 i3Browser = browser.Browser() # Main loop that checks if the maximum number of errors has been reached while consecutiveErrors <= maxErrors: # creating the new URL to download newQuery = url.replace("<INDEX>", str(index)) print(newQuery) # Downloading the file try: data = i3Browser.recoverURL(newQuery) filename = domain.replace("/", "|") + "_" + "-profile_" + str(index).rjust(10, "0") +".html" if urlDict[url] != None: if urlDict[url] in data: print(general.info("Storing resource as:\t" + filename + "...")) # The profile was found so we will store it: with open( outputFolder + "/" + filename, "w") as oF: oF.write(data) else: # The profile was found so we will store it: print(general.info("Storing resource as:\t" + filename + "...")) with open( outputFolder + "/" + filename, "w") as oF: oF.write(data) except: pass #logger.error("The resource could not be downloaded.") index+=1
python
def enumerateURL(urlDict, outputFolder, startIndex= 0, maxErrors = 100): """ Function that performs the enumeration itself. """ for i, url in enumerate(urlDict.keys()): # Grabbing domain name: domain = re.findall("://(.*)/", url)[0] # Defining the starting index index = startIndex # The app will stop when this value reaches maxErrors consecutiveErrors = 0 i3Browser = browser.Browser() # Main loop that checks if the maximum number of errors has been reached while consecutiveErrors <= maxErrors: # creating the new URL to download newQuery = url.replace("<INDEX>", str(index)) print(newQuery) # Downloading the file try: data = i3Browser.recoverURL(newQuery) filename = domain.replace("/", "|") + "_" + "-profile_" + str(index).rjust(10, "0") +".html" if urlDict[url] != None: if urlDict[url] in data: print(general.info("Storing resource as:\t" + filename + "...")) # The profile was found so we will store it: with open( outputFolder + "/" + filename, "w") as oF: oF.write(data) else: # The profile was found so we will store it: print(general.info("Storing resource as:\t" + filename + "...")) with open( outputFolder + "/" + filename, "w") as oF: oF.write(data) except: pass #logger.error("The resource could not be downloaded.") index+=1
[ "def", "enumerateURL", "(", "urlDict", ",", "outputFolder", ",", "startIndex", "=", "0", ",", "maxErrors", "=", "100", ")", ":", "for", "i", ",", "url", "in", "enumerate", "(", "urlDict", ".", "keys", "(", ")", ")", ":", "# Grabbing domain name:\r", "domain", "=", "re", ".", "findall", "(", "\"://(.*)/\"", ",", "url", ")", "[", "0", "]", "# Defining the starting index\r", "index", "=", "startIndex", "# The app will stop when this value reaches maxErrors\r", "consecutiveErrors", "=", "0", "i3Browser", "=", "browser", ".", "Browser", "(", ")", "# Main loop that checks if the maximum number of errors has been reached\r", "while", "consecutiveErrors", "<=", "maxErrors", ":", "# creating the new URL to download\r", "newQuery", "=", "url", ".", "replace", "(", "\"<INDEX>\"", ",", "str", "(", "index", ")", ")", "print", "(", "newQuery", ")", "# Downloading the file\r", "try", ":", "data", "=", "i3Browser", ".", "recoverURL", "(", "newQuery", ")", "filename", "=", "domain", ".", "replace", "(", "\"/\"", ",", "\"|\"", ")", "+", "\"_\"", "+", "\"-profile_\"", "+", "str", "(", "index", ")", ".", "rjust", "(", "10", ",", "\"0\"", ")", "+", "\".html\"", "if", "urlDict", "[", "url", "]", "!=", "None", ":", "if", "urlDict", "[", "url", "]", "in", "data", ":", "print", "(", "general", ".", "info", "(", "\"Storing resource as:\\t\"", "+", "filename", "+", "\"...\"", ")", ")", "# The profile was found so we will store it:\r", "with", "open", "(", "outputFolder", "+", "\"/\"", "+", "filename", ",", "\"w\"", ")", "as", "oF", ":", "oF", ".", "write", "(", "data", ")", "else", ":", "# The profile was found so we will store it:\r", "print", "(", "general", ".", "info", "(", "\"Storing resource as:\\t\"", "+", "filename", "+", "\"...\"", ")", ")", "with", "open", "(", "outputFolder", "+", "\"/\"", "+", "filename", ",", "\"w\"", ")", "as", "oF", ":", "oF", ".", "write", "(", "data", ")", "except", ":", "pass", "#logger.error(\"The resource could not be downloaded.\")\r", "index", "+=", "1" ]
Function that performs the enumeration itself.
[ "Function", "that", "performs", "the", "enumeration", "itself", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/enumeration.py#L36-L78
train
238,340
i3visio/osrframework
osrframework/thirdparties/haveibeenpwned_com/hibp.py
checkIfEmailWasHacked
def checkIfEmailWasHacked(email=None, sleepSeconds=1): """ Method that checks if the given email is stored in the HIBP website. This function automatically waits a second to avoid problems with the API rate limit. An example of the json received: ``` [{"Title":"Adobe","Name":"Adobe","Domain":"adobe.com","BreachDate":"2013-10-4","AddedDate":"2013-12-04T00:12Z","PwnCount":152445165,"Description":"The big one. In October 2013, 153 million Adobe accounts were breached with each containing an internal ID, username, email, <em>encrypted</em> password and a password hint in plain text. The password cryptography was poorly done and <a href=\"http://stricture-group.com/files/adobe-top100.txt\" target=\"_blank\">many were quickly resolved back to plain text</a>. The unencrypted hints also <a href=\"http://www.troyhunt.com/2013/11/adobe-credentials-and-serious.html\" target=\"_blank\">disclosed much about the passwords</a> adding further to the risk that hundreds of millions of Adobe customers already faced.","DataClasses":["Email addresses","Password hints","Passwords","Usernames"]}] ``` Args: ----- email: Email to verify in HIBP. Returns: -------- A python structure for the json received. If nothing was found, it will return an empty list. """ # Sleeping just a little bit 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.com', user_agent=ua) leaks = [] apiURL = "https://haveibeenpwned.com/api/v2/breachedaccount/{}".format(email) # Accessing the HIBP API time.sleep(sleepSeconds) # Building API query data = requests.get( apiURL, headers=useragent, cookies=cookies, verify=True ).text # Reading the text data onto python structures try: jsonData = json.loads(data) for e in jsonData: # Building the i3visio like structure new = {} new["value"] = "(HIBP) " + e.get("Name") + " - " + email new["type"] = "i3visio.profile" new["attributes"] = [ { "type": "i3visio.platform_leaked", "value": e.get("Name"), "attributes": [] }, { "type": "@source", "value": "haveibeenpwned.com", "attributes": [] }, { "type": "@source_uri", "value": apiURL, "attributes": [] }, { "type": "@pwn_count", "value": e.get("PwnCount"), "attributes": [] }, { "type": "@added_date", "value": e.get("AddedDate"), "attributes": [] }, { "type": "@breach_date", "value": e.get("BreachDate"), "attributes": [] }, { "type": "@description", "value": e.get("Description"), "attributes": [] } ] + general.expandEntitiesFromEmail(email) leaks.append(new) except ValueError: return [] except Exception: print("ERROR: Something happenned when using HIBP API.") return [] return leaks
python
def checkIfEmailWasHacked(email=None, sleepSeconds=1): """ Method that checks if the given email is stored in the HIBP website. This function automatically waits a second to avoid problems with the API rate limit. An example of the json received: ``` [{"Title":"Adobe","Name":"Adobe","Domain":"adobe.com","BreachDate":"2013-10-4","AddedDate":"2013-12-04T00:12Z","PwnCount":152445165,"Description":"The big one. In October 2013, 153 million Adobe accounts were breached with each containing an internal ID, username, email, <em>encrypted</em> password and a password hint in plain text. The password cryptography was poorly done and <a href=\"http://stricture-group.com/files/adobe-top100.txt\" target=\"_blank\">many were quickly resolved back to plain text</a>. The unencrypted hints also <a href=\"http://www.troyhunt.com/2013/11/adobe-credentials-and-serious.html\" target=\"_blank\">disclosed much about the passwords</a> adding further to the risk that hundreds of millions of Adobe customers already faced.","DataClasses":["Email addresses","Password hints","Passwords","Usernames"]}] ``` Args: ----- email: Email to verify in HIBP. Returns: -------- A python structure for the json received. If nothing was found, it will return an empty list. """ # Sleeping just a little bit 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.com', user_agent=ua) leaks = [] apiURL = "https://haveibeenpwned.com/api/v2/breachedaccount/{}".format(email) # Accessing the HIBP API time.sleep(sleepSeconds) # Building API query data = requests.get( apiURL, headers=useragent, cookies=cookies, verify=True ).text # Reading the text data onto python structures try: jsonData = json.loads(data) for e in jsonData: # Building the i3visio like structure new = {} new["value"] = "(HIBP) " + e.get("Name") + " - " + email new["type"] = "i3visio.profile" new["attributes"] = [ { "type": "i3visio.platform_leaked", "value": e.get("Name"), "attributes": [] }, { "type": "@source", "value": "haveibeenpwned.com", "attributes": [] }, { "type": "@source_uri", "value": apiURL, "attributes": [] }, { "type": "@pwn_count", "value": e.get("PwnCount"), "attributes": [] }, { "type": "@added_date", "value": e.get("AddedDate"), "attributes": [] }, { "type": "@breach_date", "value": e.get("BreachDate"), "attributes": [] }, { "type": "@description", "value": e.get("Description"), "attributes": [] } ] + general.expandEntitiesFromEmail(email) leaks.append(new) except ValueError: return [] except Exception: print("ERROR: Something happenned when using HIBP API.") return [] return leaks
[ "def", "checkIfEmailWasHacked", "(", "email", "=", "None", ",", "sleepSeconds", "=", "1", ")", ":", "# Sleeping just a little bit", "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.com'", ",", "user_agent", "=", "ua", ")", "leaks", "=", "[", "]", "apiURL", "=", "\"https://haveibeenpwned.com/api/v2/breachedaccount/{}\"", ".", "format", "(", "email", ")", "# Accessing the HIBP API", "time", ".", "sleep", "(", "sleepSeconds", ")", "# Building API query", "data", "=", "requests", ".", "get", "(", "apiURL", ",", "headers", "=", "useragent", ",", "cookies", "=", "cookies", ",", "verify", "=", "True", ")", ".", "text", "# Reading the text data onto python structures", "try", ":", "jsonData", "=", "json", ".", "loads", "(", "data", ")", "for", "e", "in", "jsonData", ":", "# Building the i3visio like structure", "new", "=", "{", "}", "new", "[", "\"value\"", "]", "=", "\"(HIBP) \"", "+", "e", ".", "get", "(", "\"Name\"", ")", "+", "\" - \"", "+", "email", "new", "[", "\"type\"", "]", "=", "\"i3visio.profile\"", "new", "[", "\"attributes\"", "]", "=", "[", "{", "\"type\"", ":", "\"i3visio.platform_leaked\"", ",", "\"value\"", ":", "e", ".", "get", "(", "\"Name\"", ")", ",", "\"attributes\"", ":", "[", "]", "}", ",", "{", "\"type\"", ":", "\"@source\"", ",", "\"value\"", ":", "\"haveibeenpwned.com\"", ",", "\"attributes\"", ":", "[", "]", "}", ",", "{", "\"type\"", ":", "\"@source_uri\"", ",", "\"value\"", ":", "apiURL", ",", "\"attributes\"", ":", "[", "]", "}", ",", "{", "\"type\"", ":", "\"@pwn_count\"", ",", "\"value\"", ":", "e", ".", "get", "(", "\"PwnCount\"", ")", ",", "\"attributes\"", ":", "[", "]", "}", ",", "{", "\"type\"", ":", "\"@added_date\"", ",", "\"value\"", ":", "e", ".", "get", "(", "\"AddedDate\"", ")", ",", "\"attributes\"", ":", "[", "]", "}", ",", "{", "\"type\"", ":", "\"@breach_date\"", ",", "\"value\"", ":", "e", ".", "get", "(", "\"BreachDate\"", ")", ",", "\"attributes\"", ":", "[", "]", "}", ",", "{", "\"type\"", ":", "\"@description\"", ",", "\"value\"", ":", "e", ".", "get", "(", "\"Description\"", ")", ",", "\"attributes\"", ":", "[", "]", "}", "]", "+", "general", ".", "expandEntitiesFromEmail", "(", "email", ")", "leaks", ".", "append", "(", "new", ")", "except", "ValueError", ":", "return", "[", "]", "except", "Exception", ":", "print", "(", "\"ERROR: Something happenned when using HIBP API.\"", ")", "return", "[", "]", "return", "leaks" ]
Method that checks if the given email is stored in the HIBP website. This function automatically waits a second to avoid problems with the API rate limit. An example of the json received: ``` [{"Title":"Adobe","Name":"Adobe","Domain":"adobe.com","BreachDate":"2013-10-4","AddedDate":"2013-12-04T00:12Z","PwnCount":152445165,"Description":"The big one. In October 2013, 153 million Adobe accounts were breached with each containing an internal ID, username, email, <em>encrypted</em> password and a password hint in plain text. The password cryptography was poorly done and <a href=\"http://stricture-group.com/files/adobe-top100.txt\" target=\"_blank\">many were quickly resolved back to plain text</a>. The unencrypted hints also <a href=\"http://www.troyhunt.com/2013/11/adobe-credentials-and-serious.html\" target=\"_blank\">disclosed much about the passwords</a> adding further to the risk that hundreds of millions of Adobe customers already faced.","DataClasses":["Email addresses","Password hints","Passwords","Usernames"]}] ``` Args: ----- email: Email to verify in HIBP. Returns: -------- A python structure for the json received. If nothing was found, it will return an empty list.
[ "Method", "that", "checks", "if", "the", "given", "email", "is", "stored", "in", "the", "HIBP", "website", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/haveibeenpwned_com/hibp.py#L30-L124
train
238,341
i3visio/osrframework
osrframework/searchengines/google.py
get_page
def get_page(url): """ Request the given URL and return the response page, using the cookie jar. @type url: str @param url: URL to retrieve. @rtype: str @return: Web page retrieved for the given URL. @raise IOError: An exception is raised on error. @raise urllib2.URLError: An exception is raised on error. @raise urllib2.HTTPError: An exception is raised on error. """ 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() cookie_jar.save() return html
python
def get_page(url): """ Request the given URL and return the response page, using the cookie jar. @type url: str @param url: URL to retrieve. @rtype: str @return: Web page retrieved for the given URL. @raise IOError: An exception is raised on error. @raise urllib2.URLError: An exception is raised on error. @raise urllib2.HTTPError: An exception is raised on error. """ 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() cookie_jar.save() return html
[ "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", "(", ")", "cookie_jar", ".", "save", "(", ")", "return", "html" ]
Request the given URL and return the response page, using the cookie jar. @type url: str @param url: URL to retrieve. @rtype: str @return: Web page retrieved for the given URL. @raise IOError: An exception is raised on error. @raise urllib2.URLError: An exception is raised on error. @raise urllib2.HTTPError: An exception is raised on error.
[ "Request", "the", "given", "URL", "and", "return", "the", "response", "page", "using", "the", "cookie", "jar", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/searchengines/google.py#L62-L85
train
238,342
i3visio/osrframework
osrframework/searchengines/google.py
search
def search(query, tld='com', lang='en', num=10, start=0, stop=None, pause=2.0, only_standard=False): """ Search the given query string using Google. @type query: str @param query: Query string. Must NOT be url-encoded. @type tld: str @param tld: Top level domain. @type lang: str @param lang: Languaje. @type num: int @param num: Number of results per page. @type start: int @param start: First result to retrieve. @type stop: int @param stop: Last result to retrieve. Use C{None} to keep searching forever. @type pause: float @param pause: Lapse to wait between HTTP requests. A lapse too long will make the search slow, but a lapse too short may cause Google to block your IP. Your mileage may vary! @type only_standard: bool @param only_standard: If C{True}, only returns the standard results from each page. If C{False}, it returns every possible link from each page, except for those that point back to Google itself. Defaults to C{False} for backwards compatibility with older versions of this module. @rtype: generator @return: Generator (iterator) that yields found URLs. If the C{stop} parameter is C{None} the iterator will loop forever. """ # Lazy import of BeautifulSoup. # Try to use BeautifulSoup 4 if available, fall back to 3 otherwise. global BeautifulSoup if BeautifulSoup is None: try: from bs4 import BeautifulSoup except ImportError: from BeautifulSoup import BeautifulSoup # Set of hashes for the results found. # This is used to avoid repeated results. hashes = set() # Prepare the search string. query = quote_plus(query) # Grab the cookie from the home page. get_page(url_home % vars()) # Prepare the URL of the first request. if start: if num == 10: url = url_next_page % vars() else: url = url_next_page_num % vars() else: if num == 10: url = url_search % vars() else: url = url_search_num % vars() # Loop until we reach the maximum result, if any (otherwise, loop forever). while not stop or start < stop: # Sleep between requests. time.sleep(pause) # Request the Google Search results page. html = get_page(url) # Parse the response and process every anchored URL. soup = BeautifulSoup(html) anchors = soup.find(id='search').findAll('a') for a in anchors: # Leave only the "standard" results if requested. # Otherwise grab all possible links. if only_standard and ( not a.parent or a.parent.name.lower() != "h3"): continue # Get the URL from the anchor tag. try: link = a['href'] except KeyError: continue # Filter invalid links and links pointing to Google itself. link = filter_result(link) if not link: continue # Discard repeated results. h = hash(link) if h in hashes: continue hashes.add(h) # Yield the result. yield link # End if there are no more results. if not soup.find(id='nav'): break # Prepare the URL for the next request. start += num if num == 10: url = url_next_page % vars() else: url = url_next_page_num % vars()
python
def search(query, tld='com', lang='en', num=10, start=0, stop=None, pause=2.0, only_standard=False): """ Search the given query string using Google. @type query: str @param query: Query string. Must NOT be url-encoded. @type tld: str @param tld: Top level domain. @type lang: str @param lang: Languaje. @type num: int @param num: Number of results per page. @type start: int @param start: First result to retrieve. @type stop: int @param stop: Last result to retrieve. Use C{None} to keep searching forever. @type pause: float @param pause: Lapse to wait between HTTP requests. A lapse too long will make the search slow, but a lapse too short may cause Google to block your IP. Your mileage may vary! @type only_standard: bool @param only_standard: If C{True}, only returns the standard results from each page. If C{False}, it returns every possible link from each page, except for those that point back to Google itself. Defaults to C{False} for backwards compatibility with older versions of this module. @rtype: generator @return: Generator (iterator) that yields found URLs. If the C{stop} parameter is C{None} the iterator will loop forever. """ # Lazy import of BeautifulSoup. # Try to use BeautifulSoup 4 if available, fall back to 3 otherwise. global BeautifulSoup if BeautifulSoup is None: try: from bs4 import BeautifulSoup except ImportError: from BeautifulSoup import BeautifulSoup # Set of hashes for the results found. # This is used to avoid repeated results. hashes = set() # Prepare the search string. query = quote_plus(query) # Grab the cookie from the home page. get_page(url_home % vars()) # Prepare the URL of the first request. if start: if num == 10: url = url_next_page % vars() else: url = url_next_page_num % vars() else: if num == 10: url = url_search % vars() else: url = url_search_num % vars() # Loop until we reach the maximum result, if any (otherwise, loop forever). while not stop or start < stop: # Sleep between requests. time.sleep(pause) # Request the Google Search results page. html = get_page(url) # Parse the response and process every anchored URL. soup = BeautifulSoup(html) anchors = soup.find(id='search').findAll('a') for a in anchors: # Leave only the "standard" results if requested. # Otherwise grab all possible links. if only_standard and ( not a.parent or a.parent.name.lower() != "h3"): continue # Get the URL from the anchor tag. try: link = a['href'] except KeyError: continue # Filter invalid links and links pointing to Google itself. link = filter_result(link) if not link: continue # Discard repeated results. h = hash(link) if h in hashes: continue hashes.add(h) # Yield the result. yield link # End if there are no more results. if not soup.find(id='nav'): break # Prepare the URL for the next request. start += num if num == 10: url = url_next_page % vars() else: url = url_next_page_num % vars()
[ "def", "search", "(", "query", ",", "tld", "=", "'com'", ",", "lang", "=", "'en'", ",", "num", "=", "10", ",", "start", "=", "0", ",", "stop", "=", "None", ",", "pause", "=", "2.0", ",", "only_standard", "=", "False", ")", ":", "# Lazy import of BeautifulSoup.\r", "# Try to use BeautifulSoup 4 if available, fall back to 3 otherwise.\r", "global", "BeautifulSoup", "if", "BeautifulSoup", "is", "None", ":", "try", ":", "from", "bs4", "import", "BeautifulSoup", "except", "ImportError", ":", "from", "BeautifulSoup", "import", "BeautifulSoup", "# Set of hashes for the results found.\r", "# This is used to avoid repeated results.\r", "hashes", "=", "set", "(", ")", "# Prepare the search string.\r", "query", "=", "quote_plus", "(", "query", ")", "# Grab the cookie from the home page.\r", "get_page", "(", "url_home", "%", "vars", "(", ")", ")", "# Prepare the URL of the first request.\r", "if", "start", ":", "if", "num", "==", "10", ":", "url", "=", "url_next_page", "%", "vars", "(", ")", "else", ":", "url", "=", "url_next_page_num", "%", "vars", "(", ")", "else", ":", "if", "num", "==", "10", ":", "url", "=", "url_search", "%", "vars", "(", ")", "else", ":", "url", "=", "url_search_num", "%", "vars", "(", ")", "# Loop until we reach the maximum result, if any (otherwise, loop forever).\r", "while", "not", "stop", "or", "start", "<", "stop", ":", "# Sleep between requests.\r", "time", ".", "sleep", "(", "pause", ")", "# Request the Google Search results page.\r", "html", "=", "get_page", "(", "url", ")", "# Parse the response and process every anchored URL.\r", "soup", "=", "BeautifulSoup", "(", "html", ")", "anchors", "=", "soup", ".", "find", "(", "id", "=", "'search'", ")", ".", "findAll", "(", "'a'", ")", "for", "a", "in", "anchors", ":", "# Leave only the \"standard\" results if requested.\r", "# Otherwise grab all possible links.\r", "if", "only_standard", "and", "(", "not", "a", ".", "parent", "or", "a", ".", "parent", ".", "name", ".", "lower", "(", ")", "!=", "\"h3\"", ")", ":", "continue", "# Get the URL from the anchor tag.\r", "try", ":", "link", "=", "a", "[", "'href'", "]", "except", "KeyError", ":", "continue", "# Filter invalid links and links pointing to Google itself.\r", "link", "=", "filter_result", "(", "link", ")", "if", "not", "link", ":", "continue", "# Discard repeated results.\r", "h", "=", "hash", "(", "link", ")", "if", "h", "in", "hashes", ":", "continue", "hashes", ".", "add", "(", "h", ")", "# Yield the result.\r", "yield", "link", "# End if there are no more results.\r", "if", "not", "soup", ".", "find", "(", "id", "=", "'nav'", ")", ":", "break", "# Prepare the URL for the next request.\r", "start", "+=", "num", "if", "num", "==", "10", ":", "url", "=", "url_next_page", "%", "vars", "(", ")", "else", ":", "url", "=", "url_next_page_num", "%", "vars", "(", ")" ]
Search the given query string using Google. @type query: str @param query: Query string. Must NOT be url-encoded. @type tld: str @param tld: Top level domain. @type lang: str @param lang: Languaje. @type num: int @param num: Number of results per page. @type start: int @param start: First result to retrieve. @type stop: int @param stop: Last result to retrieve. Use C{None} to keep searching forever. @type pause: float @param pause: Lapse to wait between HTTP requests. A lapse too long will make the search slow, but a lapse too short may cause Google to block your IP. Your mileage may vary! @type only_standard: bool @param only_standard: If C{True}, only returns the standard results from each page. If C{False}, it returns every possible link from each page, except for those that point back to Google itself. Defaults to C{False} for backwards compatibility with older versions of this module. @rtype: generator @return: Generator (iterator) that yields found URLs. If the C{stop} parameter is C{None} the iterator will loop forever.
[ "Search", "the", "given", "query", "string", "using", "Google", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/searchengines/google.py#L114-L234
train
238,343
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/containers.py
FieldsContainer.add_fields
def add_fields(self, fields): """Add the fields to their corresponding container. `fields` is an iterable of field objects from osrframework.thirdparties.pipl_com.lib.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)
python
def add_fields(self, fields): """Add the fields to their corresponding container. `fields` is an iterable of field objects from osrframework.thirdparties.pipl_com.lib.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)
[ "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.
[ "Add", "the", "fields", "to", "their", "corresponding", "container", ".", "fields", "is", "an", "iterable", "of", "field", "objects", "from", "osrframework", ".", "thirdparties", ".", "pipl_com", ".", "lib", ".", "fields", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/containers.py#L48-L60
train
238,344
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/containers.py
FieldsContainer.all_fields
def all_fields(self): """A list with all the fields contained in this object.""" return [field for container in FieldsContainer.class_container.values() for field in getattr(self, container)]
python
def all_fields(self): """A list with all the fields contained in this object.""" return [field for container in FieldsContainer.class_container.values() for field in getattr(self, container)]
[ "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.
[ "A", "list", "with", "all", "the", "fields", "contained", "in", "this", "object", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/containers.py#L63-L67
train
238,345
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/containers.py
FieldsContainer.fields_from_dict
def fields_from_dict(d): """Load the fields from the dict, return a list with all the fields.""" 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
python
def fields_from_dict(d): """Load the fields from the dict, return a list with all the fields.""" 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
[ "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.
[ "Load", "the", "fields", "from", "the", "dict", "return", "a", "list", "with", "all", "the", "fields", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/containers.py#L70-L76
train
238,346
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/containers.py
FieldsContainer.fields_to_dict
def fields_to_dict(self): """Transform the object to a dict and return the dict.""" 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
python
def fields_to_dict(self): """Transform the object to a dict and return the dict.""" 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
[ "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.
[ "Transform", "the", "object", "to", "a", "dict", "and", "return", "the", "dict", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/containers.py#L78-L85
train
238,347
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/containers.py
Record.from_dict
def from_dict(d): """Transform the dict to a record object and return the record.""" 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_from_dict(d) return Record(source=source, fields=fields, query_params_match=query_params_match, query_person_match=query_person_match, valid_since=valid_since)
python
def from_dict(d): """Transform the dict to a record object and return the record.""" 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_from_dict(d) return Record(source=source, fields=fields, query_params_match=query_params_match, query_person_match=query_person_match, valid_since=valid_since)
[ "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_from_dict", "(", "d", ")", "return", "Record", "(", "source", "=", "source", ",", "fields", "=", "fields", ",", "query_params_match", "=", "query_params_match", ",", "query_person_match", "=", "query_person_match", ",", "valid_since", "=", "valid_since", ")" ]
Transform the dict to a record object and return the record.
[ "Transform", "the", "dict", "to", "a", "record", "object", "and", "return", "the", "record", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/containers.py#L145-L157
train
238,348
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/containers.py
Record.to_dict
def to_dict(self): """Return a dict representation of the record.""" 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_since) if self.source is not None: d['source'] = self.source.to_dict() d.update(self.fields_to_dict()) return d
python
def to_dict(self): """Return a dict representation of the record.""" 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_since) if self.source is not None: d['source'] = self.source.to_dict() d.update(self.fields_to_dict()) return d
[ "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_since", ")", "if", "self", ".", "source", "is", "not", "None", ":", "d", "[", "'source'", "]", "=", "self", ".", "source", ".", "to_dict", "(", ")", "d", ".", "update", "(", "self", ".", "fields_to_dict", "(", ")", ")", "return", "d" ]
Return a dict representation of the record.
[ "Return", "a", "dict", "representation", "of", "the", "record", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/containers.py#L159-L171
train
238,349
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/containers.py
Person.is_searchable
def is_searchable(self): """A bool value that indicates whether the person has enough data and can be sent as a query to the API.""" 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))
python
def is_searchable(self): """A bool value that indicates whether the person has enough data and can be sent as a query to the API.""" 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))
[ "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.
[ "A", "bool", "value", "that", "indicates", "whether", "the", "person", "has", "enough", "data", "and", "can", "be", "sent", "as", "a", "query", "to", "the", "API", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/containers.py#L222-L229
train
238,350
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/containers.py
Person.from_dict
def from_dict(d): """Transform the dict to a person object and return the person.""" 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)
python
def from_dict(d): """Transform the dict to a person object and return the person.""" 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)
[ "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.
[ "Transform", "the", "dict", "to", "a", "person", "object", "and", "return", "the", "person", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/containers.py#L248-L254
train
238,351
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/containers.py
Person.to_dict
def to_dict(self): """Return a dict representation of the person.""" 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
python
def to_dict(self): """Return a dict representation of the person.""" 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
[ "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.
[ "Return", "a", "dict", "representation", "of", "the", "person", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/containers.py#L256-L264
train
238,352
i3visio/osrframework
osrframework/phonefy.py
processPhoneList
def processPhoneList(platformNames=[], numbers=[], excludePlatformNames=[]): """ Method to perform searchs on a series of numbers. Args: ----- platformNames: List of names of the platforms. numbers: List of numbers to be queried. excludePlatformNames: A list of platforms not to be searched. Return: ------- A list of verified emails. """ # Grabbing the <Platform> objects platforms = platform_selection.getPlatformsByName(platformNames, mode="phonefy", excludePlatformNames=excludePlatformNames) results = [] for num in numbers: for pla in platforms: # This returns a json.txt! entities = pla.getInfo(query=num, process=True, mode="phonefy") if entities != {}: results+=json.loads(entities) return results
python
def processPhoneList(platformNames=[], numbers=[], excludePlatformNames=[]): """ Method to perform searchs on a series of numbers. Args: ----- platformNames: List of names of the platforms. numbers: List of numbers to be queried. excludePlatformNames: A list of platforms not to be searched. Return: ------- A list of verified emails. """ # Grabbing the <Platform> objects platforms = platform_selection.getPlatformsByName(platformNames, mode="phonefy", excludePlatformNames=excludePlatformNames) results = [] for num in numbers: for pla in platforms: # This returns a json.txt! entities = pla.getInfo(query=num, process=True, mode="phonefy") if entities != {}: results+=json.loads(entities) return results
[ "def", "processPhoneList", "(", "platformNames", "=", "[", "]", ",", "numbers", "=", "[", "]", ",", "excludePlatformNames", "=", "[", "]", ")", ":", "# Grabbing the <Platform> objects", "platforms", "=", "platform_selection", ".", "getPlatformsByName", "(", "platformNames", ",", "mode", "=", "\"phonefy\"", ",", "excludePlatformNames", "=", "excludePlatformNames", ")", "results", "=", "[", "]", "for", "num", "in", "numbers", ":", "for", "pla", "in", "platforms", ":", "# This returns a json.txt!", "entities", "=", "pla", ".", "getInfo", "(", "query", "=", "num", ",", "process", "=", "True", ",", "mode", "=", "\"phonefy\"", ")", "if", "entities", "!=", "{", "}", ":", "results", "+=", "json", ".", "loads", "(", "entities", ")", "return", "results" ]
Method to perform searchs on a series of numbers. Args: ----- platformNames: List of names of the platforms. numbers: List of numbers to be queried. excludePlatformNames: A list of platforms not to be searched. Return: ------- A list of verified emails.
[ "Method", "to", "perform", "searchs", "on", "a", "series", "of", "numbers", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/phonefy.py#L37-L61
train
238,353
i3visio/osrframework
osrframework/utils/platforms.py
Platform.createURL
def createURL(self, word, mode="phonefy"): """ Method to create the URL replacing the word in the appropriate URL. Args: ----- word: Word to be searched. mode: Mode to be executed. Return: ------- The URL to be queried. """ 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[mode].replace("<"+mode+">", urllib.pathname2url(word)) except: pass return None
python
def createURL(self, word, mode="phonefy"): """ Method to create the URL replacing the word in the appropriate URL. Args: ----- word: Word to be searched. mode: Mode to be executed. Return: ------- The URL to be queried. """ 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[mode].replace("<"+mode+">", urllib.pathname2url(word)) except: pass return None
[ "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", "[", "mode", "]", ".", "replace", "(", "\"<\"", "+", "mode", "+", "\">\"", ",", "urllib", ".", "pathname2url", "(", "word", ")", ")", "except", ":", "pass", "return", "None" ]
Method to create the URL replacing the word in the appropriate URL. Args: ----- word: Word to be searched. mode: Mode to be executed. Return: ------- The URL to be queried.
[ "Method", "to", "create", "the", "URL", "replacing", "the", "word", "in", "the", "appropriate", "URL", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/platforms.py#L86-L112
train
238,354
i3visio/osrframework
osrframework/utils/platforms.py
Platform.launchQueryForMode
def launchQueryForMode(self, query=None, mode=None): """ Method that launches an i3Browser to collect data. Args: ----- query: The query to be performed mode: The mode to be used to build the query. Return: ------- A string containing the recovered data or None. """ # Creating the query URL for that mode qURL = self.createURL(word=query, mode=mode) i3Browser = browser.Browser() try: # Check if it needs creds if self.needsCredentials[mode]: self._getAuthenticated(i3Browser, qURL) data = i3Browser.recoverURL(qURL) else: # Accessing the resources data = i3Browser.recoverURL(qURL) return data except KeyError: print(general.error("[*] '{}' is not a valid mode for this wrapper ({}).".format(mode, self.__class__.__name__))) return None
python
def launchQueryForMode(self, query=None, mode=None): """ Method that launches an i3Browser to collect data. Args: ----- query: The query to be performed mode: The mode to be used to build the query. Return: ------- A string containing the recovered data or None. """ # Creating the query URL for that mode qURL = self.createURL(word=query, mode=mode) i3Browser = browser.Browser() try: # Check if it needs creds if self.needsCredentials[mode]: self._getAuthenticated(i3Browser, qURL) data = i3Browser.recoverURL(qURL) else: # Accessing the resources data = i3Browser.recoverURL(qURL) return data except KeyError: print(general.error("[*] '{}' is not a valid mode for this wrapper ({}).".format(mode, self.__class__.__name__))) return None
[ "def", "launchQueryForMode", "(", "self", ",", "query", "=", "None", ",", "mode", "=", "None", ")", ":", "# Creating the query URL for that mode", "qURL", "=", "self", ".", "createURL", "(", "word", "=", "query", ",", "mode", "=", "mode", ")", "i3Browser", "=", "browser", ".", "Browser", "(", ")", "try", ":", "# Check if it needs creds", "if", "self", ".", "needsCredentials", "[", "mode", "]", ":", "self", ".", "_getAuthenticated", "(", "i3Browser", ",", "qURL", ")", "data", "=", "i3Browser", ".", "recoverURL", "(", "qURL", ")", "else", ":", "# Accessing the resources", "data", "=", "i3Browser", ".", "recoverURL", "(", "qURL", ")", "return", "data", "except", "KeyError", ":", "print", "(", "general", ".", "error", "(", "\"[*] '{}' is not a valid mode for this wrapper ({}).\"", ".", "format", "(", "mode", ",", "self", ".", "__class__", ".", "__name__", ")", ")", ")", "return", "None" ]
Method that launches an i3Browser to collect data. Args: ----- query: The query to be performed mode: The mode to be used to build the query. Return: ------- A string containing the recovered data or None.
[ "Method", "that", "launches", "an", "i3Browser", "to", "collect", "data", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/platforms.py#L115-L144
train
238,355
i3visio/osrframework
osrframework/utils/platforms.py
Platform.getInfo
def getInfo(self, query=None, process=False, mode="phonefy", qURI=None): """ Method that checks the presence of a given query and recovers the first list of complains. Args: ----- query: Query to verify. process: Calling the processing function. mode: Mode to be executed. qURI: A query to be checked. Return: ------- Python structure for the html processed. Raises: ------- NoCredentialsException. NotImplementedModeError. BadImplementationError. """ 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))(query) except AttributeError as e: raise NotImplementedModeError(str(self), mode) return json.dumps(results)
python
def getInfo(self, query=None, process=False, mode="phonefy", qURI=None): """ Method that checks the presence of a given query and recovers the first list of complains. Args: ----- query: Query to verify. process: Calling the processing function. mode: Mode to be executed. qURI: A query to be checked. Return: ------- Python structure for the html processed. Raises: ------- NoCredentialsException. NotImplementedModeError. BadImplementationError. """ 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))(query) except AttributeError as e: raise NotImplementedModeError(str(self), mode) return json.dumps(results)
[ "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", ")", ")", "(", "query", ")", "except", "AttributeError", "as", "e", ":", "raise", "NotImplementedModeError", "(", "str", "(", "self", ")", ",", "mode", ")", "return", "json", ".", "dumps", "(", "results", ")" ]
Method that checks the presence of a given query and recovers the first list of complains. Args: ----- query: Query to verify. process: Calling the processing function. mode: Mode to be executed. qURI: A query to be checked. Return: ------- Python structure for the html processed. Raises: ------- NoCredentialsException. NotImplementedModeError. BadImplementationError.
[ "Method", "that", "checks", "the", "presence", "of", "a", "given", "query", "and", "recovers", "the", "first", "list", "of", "complains", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/platforms.py#L147-L178
train
238,356
i3visio/osrframework
osrframework/utils/platforms.py
Platform._modeIsValid
def _modeIsValid(self, mode): """ Verification of whether the mode is a correct option to be used. Args: ----- mode: Mode to be executed. Return: ------- True if the mode exists in the three main folders. """ try: # Suport for version 2 of wrappers return mode in self.modes.keys() except AttributeError as e: # Legacy for mantaining old wrappers if mode in self.isValidMode.keys(): if mode in self.isValidMode.keys(): return True return False
python
def _modeIsValid(self, mode): """ Verification of whether the mode is a correct option to be used. Args: ----- mode: Mode to be executed. Return: ------- True if the mode exists in the three main folders. """ try: # Suport for version 2 of wrappers return mode in self.modes.keys() except AttributeError as e: # Legacy for mantaining old wrappers if mode in self.isValidMode.keys(): if mode in self.isValidMode.keys(): return True return False
[ "def", "_modeIsValid", "(", "self", ",", "mode", ")", ":", "try", ":", "# Suport for version 2 of wrappers", "return", "mode", "in", "self", ".", "modes", ".", "keys", "(", ")", "except", "AttributeError", "as", "e", ":", "# Legacy for mantaining old wrappers", "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. Args: ----- mode: Mode to be executed. Return: ------- True if the mode exists in the three main folders.
[ "Verification", "of", "whether", "the", "mode", "is", "a", "correct", "option", "to", "be", "used", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/platforms.py#L181-L201
train
238,357
i3visio/osrframework
osrframework/utils/platforms.py
Platform._getAuthenticated
def _getAuthenticated(self, browser, url): """ Getting authenticated. This method may be overwritten. TODO: update to version 2 of the wrappers. Args: ----- browser: The browser in which the user will be authenticated. url: The URL to get authenticated in. Return: ------- True or False. Raises: ------ NoCredentialsException: If no valid credentials have been found. BadImplementationError: If an expected attribute is missing. """ # check if we have creds try: if len(self.creds) > 0: # TODO: in choosing a cred there is an uneeded nesting of arrays c = random.choice(self.creds)[0] # adding the credential browser.setNewPassword(url, c.user, c.password) return True else: raise NoCredentialsException(str(self)) except AttributeError as e: raise BadImplementationError(str(e))
python
def _getAuthenticated(self, browser, url): """ Getting authenticated. This method may be overwritten. TODO: update to version 2 of the wrappers. Args: ----- browser: The browser in which the user will be authenticated. url: The URL to get authenticated in. Return: ------- True or False. Raises: ------ NoCredentialsException: If no valid credentials have been found. BadImplementationError: If an expected attribute is missing. """ # check if we have creds try: if len(self.creds) > 0: # TODO: in choosing a cred there is an uneeded nesting of arrays c = random.choice(self.creds)[0] # adding the credential browser.setNewPassword(url, c.user, c.password) return True else: raise NoCredentialsException(str(self)) except AttributeError as e: raise BadImplementationError(str(e))
[ "def", "_getAuthenticated", "(", "self", ",", "browser", ",", "url", ")", ":", "# check if we have creds", "try", ":", "if", "len", "(", "self", ".", "creds", ")", ">", "0", ":", "# TODO: in choosing a cred there is an uneeded nesting of arrays", "c", "=", "random", ".", "choice", "(", "self", ".", "creds", ")", "[", "0", "]", "# adding the credential", "browser", ".", "setNewPassword", "(", "url", ",", "c", ".", "user", ",", "c", ".", "password", ")", "return", "True", "else", ":", "raise", "NoCredentialsException", "(", "str", "(", "self", ")", ")", "except", "AttributeError", "as", "e", ":", "raise", "BadImplementationError", "(", "str", "(", "e", ")", ")" ]
Getting authenticated. This method may be overwritten. TODO: update to version 2 of the wrappers. Args: ----- browser: The browser in which the user will be authenticated. url: The URL to get authenticated in. Return: ------- True or False. Raises: ------ NoCredentialsException: If no valid credentials have been found. BadImplementationError: If an expected attribute is missing.
[ "Getting", "authenticated", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/platforms.py#L234-L267
train
238,358
i3visio/osrframework
osrframework/utils/platforms.py
Platform._isValidQuery
def _isValidQuery(self, query, mode="phonefy"): """ Method to verify if a given query is processable by the platform. The system looks for the forbidden characters in self.Forbidden list. Args: ----- query: The query to be launched. mode: To be chosen amongst mailfy, phonefy, usufy, searchfy. Return: ------- True | False """ try: # Suport for version 2 of wrappers 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 AttributeError as e: # Legacy for mantaining old wrappers compiledRegexp = re.compile("^{r}$".format(r=self.validQuery[mode])) return compiledRegexp.match(query)
python
def _isValidQuery(self, query, mode="phonefy"): """ Method to verify if a given query is processable by the platform. The system looks for the forbidden characters in self.Forbidden list. Args: ----- query: The query to be launched. mode: To be chosen amongst mailfy, phonefy, usufy, searchfy. Return: ------- True | False """ try: # Suport for version 2 of wrappers 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 AttributeError as e: # Legacy for mantaining old wrappers compiledRegexp = re.compile("^{r}$".format(r=self.validQuery[mode])) return compiledRegexp.match(query)
[ "def", "_isValidQuery", "(", "self", ",", "query", ",", "mode", "=", "\"phonefy\"", ")", ":", "try", ":", "# Suport for version 2 of wrappers", "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", "AttributeError", "as", "e", ":", "# Legacy for mantaining old wrappers", "compiledRegexp", "=", "re", ".", "compile", "(", "\"^{r}$\"", ".", "format", "(", "r", "=", "self", ".", "validQuery", "[", "mode", "]", ")", ")", "return", "compiledRegexp", ".", "match", "(", "query", ")" ]
Method to verify if a given query is processable by the platform. The system looks for the forbidden characters in self.Forbidden list. Args: ----- query: The query to be launched. mode: To be chosen amongst mailfy, phonefy, usufy, searchfy. Return: ------- True | False
[ "Method", "to", "verify", "if", "a", "given", "query", "is", "processable", "by", "the", "platform", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/platforms.py#L270-L301
train
238,359
i3visio/osrframework
osrframework/utils/platforms.py
Platform._somethingFound
def _somethingFound(self, data, mode="phonefy"): """ Verifying if something was found. Args: ----- data: Data where the self.notFoundText will be searched. mode: Mode to be executed. Return: ------- True if exists. """ if data: try: for text in self.notFoundText[mode]: if text in data: return False return True except AttributeError as e: # Update to version 2 of the wrappers. verifier = self.modes.get(mode) if verifier: if verifier.get("not_found_text", "") in data: return False else: return True return False
python
def _somethingFound(self, data, mode="phonefy"): """ Verifying if something was found. Args: ----- data: Data where the self.notFoundText will be searched. mode: Mode to be executed. Return: ------- True if exists. """ if data: try: for text in self.notFoundText[mode]: if text in data: return False return True except AttributeError as e: # Update to version 2 of the wrappers. verifier = self.modes.get(mode) if verifier: if verifier.get("not_found_text", "") in data: return False else: return True return False
[ "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", ":", "# Update to version 2 of the wrappers.", "verifier", "=", "self", ".", "modes", ".", "get", "(", "mode", ")", "if", "verifier", ":", "if", "verifier", ".", "get", "(", "\"not_found_text\"", ",", "\"\"", ")", "in", "data", ":", "return", "False", "else", ":", "return", "True", "return", "False" ]
Verifying if something was found. Args: ----- data: Data where the self.notFoundText will be searched. mode: Mode to be executed. Return: ------- True if exists.
[ "Verifying", "if", "something", "was", "found", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/platforms.py#L304-L331
train
238,360
i3visio/osrframework
osrframework/utils/platforms.py
Platform.do_phonefy
def do_phonefy(self, query, **kwargs): """ Verifying a phonefy query in this platform. This might be redefined in any class inheriting from Platform. Args: ----- query: The element to be searched. Return: ------- A list of elements to be appended. """ 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"), "attributes": [] } r["attributes"].append(aux) except: pass aux = { "type": "i3visio.platform", "value": self.platformName, "attributes": [] } r["attributes"].append(aux) # V2 of the wrappers r["attributes"] += self.process_phonefy(test) results.append(r) return results
python
def do_phonefy(self, query, **kwargs): """ Verifying a phonefy query in this platform. This might be redefined in any class inheriting from Platform. Args: ----- query: The element to be searched. Return: ------- A list of elements to be appended. """ 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"), "attributes": [] } r["attributes"].append(aux) except: pass aux = { "type": "i3visio.platform", "value": self.platformName, "attributes": [] } r["attributes"].append(aux) # V2 of the wrappers r["attributes"] += self.process_phonefy(test) results.append(r) return results
[ "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\"", ")", ",", "\"attributes\"", ":", "[", "]", "}", "r", "[", "\"attributes\"", "]", ".", "append", "(", "aux", ")", "except", ":", "pass", "aux", "=", "{", "\"type\"", ":", "\"i3visio.platform\"", ",", "\"value\"", ":", "self", ".", "platformName", ",", "\"attributes\"", ":", "[", "]", "}", "r", "[", "\"attributes\"", "]", ".", "append", "(", "aux", ")", "# V2 of the wrappers", "r", "[", "\"attributes\"", "]", "+=", "self", ".", "process_phonefy", "(", "test", ")", "results", ".", "append", "(", "r", ")", "return", "results" ]
Verifying a phonefy query in this platform. This might be redefined in any class inheriting from Platform. Args: ----- query: The element to be searched. Return: ------- A list of elements to be appended.
[ "Verifying", "a", "phonefy", "query", "in", "this", "platform", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/platforms.py#L541-L587
train
238,361
i3visio/osrframework
osrframework/utils/platforms.py
Platform.process_usufy
def process_usufy(self, data): """ Method to process and extract the entities of a usufy Args: ----- data: The information from which the info will be extracted. Return: ------- A list of the entities found. """ mode = "usufy" info = [] try: # v2 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"] = val aux["attributes"] = [] if aux not in info: info.append(aux) except AttributeError as e: # Legacy for field in self.fieldsRegExp[mode].keys(): # Recovering the RegularExpression try: # Using the old approach of "Start" + "End" regexp = self.fieldsRegExp[mode][field]["start"]+"([^\)]+)"+self.fieldsRegExp[mode][field]["end"] tmp = re.findall(regexp, data) # Now we are performing an operation just in case the "end" tag is found in the results, which would mean that the tag selected matches something longer in the data. values = [] for t in tmp: if self.fieldsRegExp[mode][field]["end"] in t: values.append(t.split(self.fieldsRegExp[mode][field]["end"])[0]) else: values.append(t) except: # Using the compact approach if start and end tags do not exist. regexp = self.fieldsRegExp[mode][field] values = re.findall(regexp, data) for val in values: aux = {} aux["type"] = field aux["value"] = val aux["attributes"] = [] if aux not in info: info.append(aux) return info
python
def process_usufy(self, data): """ Method to process and extract the entities of a usufy Args: ----- data: The information from which the info will be extracted. Return: ------- A list of the entities found. """ mode = "usufy" info = [] try: # v2 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"] = val aux["attributes"] = [] if aux not in info: info.append(aux) except AttributeError as e: # Legacy for field in self.fieldsRegExp[mode].keys(): # Recovering the RegularExpression try: # Using the old approach of "Start" + "End" regexp = self.fieldsRegExp[mode][field]["start"]+"([^\)]+)"+self.fieldsRegExp[mode][field]["end"] tmp = re.findall(regexp, data) # Now we are performing an operation just in case the "end" tag is found in the results, which would mean that the tag selected matches something longer in the data. values = [] for t in tmp: if self.fieldsRegExp[mode][field]["end"] in t: values.append(t.split(self.fieldsRegExp[mode][field]["end"])[0]) else: values.append(t) except: # Using the compact approach if start and end tags do not exist. regexp = self.fieldsRegExp[mode][field] values = re.findall(regexp, data) for val in values: aux = {} aux["type"] = field aux["value"] = val aux["attributes"] = [] if aux not in info: info.append(aux) return info
[ "def", "process_usufy", "(", "self", ",", "data", ")", ":", "mode", "=", "\"usufy\"", "info", "=", "[", "]", "try", ":", "# v2", "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\"", "]", "=", "val", "aux", "[", "\"attributes\"", "]", "=", "[", "]", "if", "aux", "not", "in", "info", ":", "info", ".", "append", "(", "aux", ")", "except", "AttributeError", "as", "e", ":", "# Legacy", "for", "field", "in", "self", ".", "fieldsRegExp", "[", "mode", "]", ".", "keys", "(", ")", ":", "# Recovering the RegularExpression", "try", ":", "# Using the old approach of \"Start\" + \"End\"", "regexp", "=", "self", ".", "fieldsRegExp", "[", "mode", "]", "[", "field", "]", "[", "\"start\"", "]", "+", "\"([^\\)]+)\"", "+", "self", ".", "fieldsRegExp", "[", "mode", "]", "[", "field", "]", "[", "\"end\"", "]", "tmp", "=", "re", ".", "findall", "(", "regexp", ",", "data", ")", "# Now we are performing an operation just in case the \"end\" tag is found in the results, which would mean that the tag selected matches something longer in the data.", "values", "=", "[", "]", "for", "t", "in", "tmp", ":", "if", "self", ".", "fieldsRegExp", "[", "mode", "]", "[", "field", "]", "[", "\"end\"", "]", "in", "t", ":", "values", ".", "append", "(", "t", ".", "split", "(", "self", ".", "fieldsRegExp", "[", "mode", "]", "[", "field", "]", "[", "\"end\"", "]", ")", "[", "0", "]", ")", "else", ":", "values", ".", "append", "(", "t", ")", "except", ":", "# Using the compact approach if start and end tags do not exist.", "regexp", "=", "self", ".", "fieldsRegExp", "[", "mode", "]", "[", "field", "]", "values", "=", "re", ".", "findall", "(", "regexp", ",", "data", ")", "for", "val", "in", "values", ":", "aux", "=", "{", "}", "aux", "[", "\"type\"", "]", "=", "field", "aux", "[", "\"value\"", "]", "=", "val", "aux", "[", "\"attributes\"", "]", "=", "[", "]", "if", "aux", "not", "in", "info", ":", "info", ".", "append", "(", "aux", ")", "return", "info" ]
Method to process and extract the entities of a usufy Args: ----- data: The information from which the info will be extracted. Return: ------- A list of the entities found.
[ "Method", "to", "process", "and", "extract", "the", "entities", "of", "a", "usufy" ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/platforms.py#L723-L783
train
238,362
i3visio/osrframework
osrframework/utils/benchmark.py
doBenchmark
def doBenchmark(plats): ''' Perform the benchmark... ''' logger = logging.getLogger("osrframework.utils") # defining the results dict res = {} # args args = [] #for p in plats: # args.append( (str(p),) ) # selecting the number of tries to be performed tries = [1, 4, 8 ,16, 24, 32, 40, 48, 56, 64] #for i in range(1, len(plats)/10): # tries.append(i*10) logger.info("The test is starting recovering webpages by creating the following series of threads: " + str(tries)) for i in tries: print "Testing creating " + str(i) + " simultaneous threads..." # starting t0 = time.clock() pool = Pool(i) # We call the wrapping function with all the args previously generated poolResults = pool.map(multi_run_wrapper, args) t1 = time.clock() # storing the results res[i] = t1 - t0 print str(i) + "\t" + str(res[i]) + "\n" return res
python
def doBenchmark(plats): ''' Perform the benchmark... ''' logger = logging.getLogger("osrframework.utils") # defining the results dict res = {} # args args = [] #for p in plats: # args.append( (str(p),) ) # selecting the number of tries to be performed tries = [1, 4, 8 ,16, 24, 32, 40, 48, 56, 64] #for i in range(1, len(plats)/10): # tries.append(i*10) logger.info("The test is starting recovering webpages by creating the following series of threads: " + str(tries)) for i in tries: print "Testing creating " + str(i) + " simultaneous threads..." # starting t0 = time.clock() pool = Pool(i) # We call the wrapping function with all the args previously generated poolResults = pool.map(multi_run_wrapper, args) t1 = time.clock() # storing the results res[i] = t1 - t0 print str(i) + "\t" + str(res[i]) + "\n" return res
[ "def", "doBenchmark", "(", "plats", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"osrframework.utils\"", ")", "# defining the results dict", "res", "=", "{", "}", "# args", "args", "=", "[", "]", "#for p in plats:", "#\targs.append( (str(p),) )", "# selecting the number of tries to be performed", "tries", "=", "[", "1", ",", "4", ",", "8", ",", "16", ",", "24", ",", "32", ",", "40", ",", "48", ",", "56", ",", "64", "]", "#for i in range(1, len(plats)/10):", "#\ttries.append(i*10)", "logger", ".", "info", "(", "\"The test is starting recovering webpages by creating the following series of threads: \"", "+", "str", "(", "tries", ")", ")", "for", "i", "in", "tries", ":", "print", "\"Testing creating \"", "+", "str", "(", "i", ")", "+", "\" simultaneous threads...\"", "# starting ", "t0", "=", "time", ".", "clock", "(", ")", "pool", "=", "Pool", "(", "i", ")", "# We call the wrapping function with all the args previously generated", "poolResults", "=", "pool", ".", "map", "(", "multi_run_wrapper", ",", "args", ")", "t1", "=", "time", ".", "clock", "(", ")", "# storing the results", "res", "[", "i", "]", "=", "t1", "-", "t0", "print", "str", "(", "i", ")", "+", "\"\\t\"", "+", "str", "(", "res", "[", "i", "]", ")", "+", "\"\\n\"", "return", "res" ]
Perform the benchmark...
[ "Perform", "the", "benchmark", "..." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/benchmark.py#L55-L90
train
238,363
i3visio/osrframework
osrframework/utils/configuration.py
changePermissionsRecursively
def changePermissionsRecursively(path, uid, gid): """ Function to recursively change the user id and group id. It sets 700 permissions. """ os.chown(path, uid, gid) for item in os.listdir(path): itempath = os.path.join(path, item) if os.path.isfile(itempath): # Setting owner try: os.chown(itempath, uid, gid) except Exception as e: # If this crashes it may be because we are running the # application in Windows systems, where os.chown does NOT work. pass # Setting permissions os.chmod(itempath, 600) elif os.path.isdir(itempath): # Setting owner try: os.chown(itempath, uid, gid) except Exception as e: # If this crashes it may be because we are running the # application in Windows systems, where os.chown does NOT work. pass # Setting permissions os.chmod(itempath, 6600) # Recursive function to iterate the files changePermissionsRecursively(itempath, uid, gid)
python
def changePermissionsRecursively(path, uid, gid): """ Function to recursively change the user id and group id. It sets 700 permissions. """ os.chown(path, uid, gid) for item in os.listdir(path): itempath = os.path.join(path, item) if os.path.isfile(itempath): # Setting owner try: os.chown(itempath, uid, gid) except Exception as e: # If this crashes it may be because we are running the # application in Windows systems, where os.chown does NOT work. pass # Setting permissions os.chmod(itempath, 600) elif os.path.isdir(itempath): # Setting owner try: os.chown(itempath, uid, gid) except Exception as e: # If this crashes it may be because we are running the # application in Windows systems, where os.chown does NOT work. pass # Setting permissions os.chmod(itempath, 6600) # Recursive function to iterate the files changePermissionsRecursively(itempath, uid, gid)
[ "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", ")", ":", "# Setting owner", "try", ":", "os", ".", "chown", "(", "itempath", ",", "uid", ",", "gid", ")", "except", "Exception", "as", "e", ":", "# If this crashes it may be because we are running the", "# application in Windows systems, where os.chown does NOT work.", "pass", "# Setting permissions", "os", ".", "chmod", "(", "itempath", ",", "600", ")", "elif", "os", ".", "path", ".", "isdir", "(", "itempath", ")", ":", "# Setting owner", "try", ":", "os", ".", "chown", "(", "itempath", ",", "uid", ",", "gid", ")", "except", "Exception", "as", "e", ":", "# If this crashes it may be because we are running the", "# application in Windows systems, where os.chown does NOT work.", "pass", "# Setting permissions", "os", ".", "chmod", "(", "itempath", ",", "6600", ")", "# Recursive function to iterate the files", "changePermissionsRecursively", "(", "itempath", ",", "uid", ",", "gid", ")" ]
Function to recursively change the user id and group id. It sets 700 permissions.
[ "Function", "to", "recursively", "change", "the", "user", "id", "and", "group", "id", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/configuration.py#L33-L63
train
238,364
i3visio/osrframework
osrframework/utils/configuration.py
getConfigPath
def getConfigPath(configFileName = None): """ Auxiliar function to get the configuration paths depending on the system Args: ----- configFileName: TODO. Returns: -------- A dictionary with the following keys: appPath, appPathDefaults, appPathTransforms, appPathPlugins, appPathPatterns, appPathPatterns. """ paths = {} applicationPath = "./" # Returning the path of the configuration folder if sys.platform == 'win32': applicationPath = os.path.expanduser(os.path.join('~\\', 'OSRFramework')) else: applicationPath = os.path.expanduser(os.path.join('~/', '.config', 'OSRFramework')) # Defining additional folders paths = { "appPath": applicationPath, "appPathData": os.path.join(applicationPath, "data"), "appPathDefaults": os.path.join(applicationPath, "default"), "appPathPlugins": os.path.join(applicationPath, "plugins"), "appPathWrappers": os.path.join(applicationPath, "plugins", "wrappers"), "appPathPatterns": os.path.join(applicationPath, "plugins", "patterns"), } # Creating them if they don't exist for path in paths.keys(): if not os.path.exists(paths[path]): os.makedirs(paths[path]) return paths
python
def getConfigPath(configFileName = None): """ Auxiliar function to get the configuration paths depending on the system Args: ----- configFileName: TODO. Returns: -------- A dictionary with the following keys: appPath, appPathDefaults, appPathTransforms, appPathPlugins, appPathPatterns, appPathPatterns. """ paths = {} applicationPath = "./" # Returning the path of the configuration folder if sys.platform == 'win32': applicationPath = os.path.expanduser(os.path.join('~\\', 'OSRFramework')) else: applicationPath = os.path.expanduser(os.path.join('~/', '.config', 'OSRFramework')) # Defining additional folders paths = { "appPath": applicationPath, "appPathData": os.path.join(applicationPath, "data"), "appPathDefaults": os.path.join(applicationPath, "default"), "appPathPlugins": os.path.join(applicationPath, "plugins"), "appPathWrappers": os.path.join(applicationPath, "plugins", "wrappers"), "appPathPatterns": os.path.join(applicationPath, "plugins", "patterns"), } # Creating them if they don't exist for path in paths.keys(): if not os.path.exists(paths[path]): os.makedirs(paths[path]) return paths
[ "def", "getConfigPath", "(", "configFileName", "=", "None", ")", ":", "paths", "=", "{", "}", "applicationPath", "=", "\"./\"", "# Returning the path of the configuration folder", "if", "sys", ".", "platform", "==", "'win32'", ":", "applicationPath", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "'~\\\\'", ",", "'OSRFramework'", ")", ")", "else", ":", "applicationPath", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "join", "(", "'~/'", ",", "'.config'", ",", "'OSRFramework'", ")", ")", "# Defining additional folders", "paths", "=", "{", "\"appPath\"", ":", "applicationPath", ",", "\"appPathData\"", ":", "os", ".", "path", ".", "join", "(", "applicationPath", ",", "\"data\"", ")", ",", "\"appPathDefaults\"", ":", "os", ".", "path", ".", "join", "(", "applicationPath", ",", "\"default\"", ")", ",", "\"appPathPlugins\"", ":", "os", ".", "path", ".", "join", "(", "applicationPath", ",", "\"plugins\"", ")", ",", "\"appPathWrappers\"", ":", "os", ".", "path", ".", "join", "(", "applicationPath", ",", "\"plugins\"", ",", "\"wrappers\"", ")", ",", "\"appPathPatterns\"", ":", "os", ".", "path", ".", "join", "(", "applicationPath", ",", "\"plugins\"", ",", "\"patterns\"", ")", ",", "}", "# Creating them if they don't exist", "for", "path", "in", "paths", ".", "keys", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "paths", "[", "path", "]", ")", ":", "os", ".", "makedirs", "(", "paths", "[", "path", "]", ")", "return", "paths" ]
Auxiliar function to get the configuration paths depending on the system Args: ----- configFileName: TODO. Returns: -------- A dictionary with the following keys: appPath, appPathDefaults, appPathTransforms, appPathPlugins, appPathPatterns, appPathPatterns.
[ "Auxiliar", "function", "to", "get", "the", "configuration", "paths", "depending", "on", "the", "system" ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/configuration.py#L66-L103
train
238,365
i3visio/osrframework
osrframework/utils/configuration.py
returnListOfConfigurationValues
def returnListOfConfigurationValues(util): """ Method that recovers the configuration information about each program TODO: Grab the default file from the package data instead of storing it in the main folder. Args: ----- util: Any of the utils that are contained in the framework: domainfy, entify, mailfy, phonefy, searchfy, usufy. Returns: -------- A dictionary containing the default configuration. """ VALUES = {} # If a api_keys.cfg has not been found, creating it by copying from default configPath = os.path.join(getConfigPath()["appPath"], "general.cfg") # Checking if the configuration file exists if not os.path.exists(configPath): # Copy the data from the default folder defaultConfigPath = os.path.join(getConfigPath()["appPathDefaults"], "general.cfg") try: # Recovering default file with open(defaultConfigPath) as iF: cont = iF.read() # Moving its contents as the default values with open(configPath, "w") as oF: oF.write(cont) except Exception as e: raise errors.DefaultConfigurationFileNotFoundError(configPath, defaultConfigPath); # Reading the configuration file config = ConfigParser.ConfigParser() config.read(configPath) LISTS = ["tlds", "domains", "platforms", "extension", "exclude_platforms", "exclude_domains"] # Iterating through all the sections, which contain the platforms for section in config.sections(): incomplete = False if section.lower() == util.lower(): # Iterating through parameters for (param, value) in config.items(section): if value == '': # Manually setting an empty value if param in LISTS: value = [] else: value = "" # Splitting the parameters to create the arrays when needed elif param in LISTS: value = value.split(' ') # Converting threads to int elif param == "threads": try: value = int(value) except Exception as err: raise errors.ConfigurationParameterNotValidError(configPath, section, param, value) elif param == "debug": try: if int(value) == 0: value = False else: value = True except Exception as err: print("Something happened when processing this debug option. Resetting to default.") # Copy the data from the default folder defaultConfigPath = os.path.join(getConfigPath()["appPathDefaults"], "general.cfg") try: # Recovering default file with open(defaultConfigPath) as iF: cont = iF.read() # Moving its contents as the default values with open(configPath, "w") as oF: oF.write(cont) except Exception as e: raise errors.DefaultConfigurationFileNotFoundError(configPath, defaultConfigPath); #raise errors.ConfigurationParameterNotValidError(configPath, section, param, value) VALUES[param] = value break return VALUES
python
def returnListOfConfigurationValues(util): """ Method that recovers the configuration information about each program TODO: Grab the default file from the package data instead of storing it in the main folder. Args: ----- util: Any of the utils that are contained in the framework: domainfy, entify, mailfy, phonefy, searchfy, usufy. Returns: -------- A dictionary containing the default configuration. """ VALUES = {} # If a api_keys.cfg has not been found, creating it by copying from default configPath = os.path.join(getConfigPath()["appPath"], "general.cfg") # Checking if the configuration file exists if not os.path.exists(configPath): # Copy the data from the default folder defaultConfigPath = os.path.join(getConfigPath()["appPathDefaults"], "general.cfg") try: # Recovering default file with open(defaultConfigPath) as iF: cont = iF.read() # Moving its contents as the default values with open(configPath, "w") as oF: oF.write(cont) except Exception as e: raise errors.DefaultConfigurationFileNotFoundError(configPath, defaultConfigPath); # Reading the configuration file config = ConfigParser.ConfigParser() config.read(configPath) LISTS = ["tlds", "domains", "platforms", "extension", "exclude_platforms", "exclude_domains"] # Iterating through all the sections, which contain the platforms for section in config.sections(): incomplete = False if section.lower() == util.lower(): # Iterating through parameters for (param, value) in config.items(section): if value == '': # Manually setting an empty value if param in LISTS: value = [] else: value = "" # Splitting the parameters to create the arrays when needed elif param in LISTS: value = value.split(' ') # Converting threads to int elif param == "threads": try: value = int(value) except Exception as err: raise errors.ConfigurationParameterNotValidError(configPath, section, param, value) elif param == "debug": try: if int(value) == 0: value = False else: value = True except Exception as err: print("Something happened when processing this debug option. Resetting to default.") # Copy the data from the default folder defaultConfigPath = os.path.join(getConfigPath()["appPathDefaults"], "general.cfg") try: # Recovering default file with open(defaultConfigPath) as iF: cont = iF.read() # Moving its contents as the default values with open(configPath, "w") as oF: oF.write(cont) except Exception as e: raise errors.DefaultConfigurationFileNotFoundError(configPath, defaultConfigPath); #raise errors.ConfigurationParameterNotValidError(configPath, section, param, value) VALUES[param] = value break return VALUES
[ "def", "returnListOfConfigurationValues", "(", "util", ")", ":", "VALUES", "=", "{", "}", "# If a api_keys.cfg has not been found, creating it by copying from default", "configPath", "=", "os", ".", "path", ".", "join", "(", "getConfigPath", "(", ")", "[", "\"appPath\"", "]", ",", "\"general.cfg\"", ")", "# Checking if the configuration file exists", "if", "not", "os", ".", "path", ".", "exists", "(", "configPath", ")", ":", "# Copy the data from the default folder", "defaultConfigPath", "=", "os", ".", "path", ".", "join", "(", "getConfigPath", "(", ")", "[", "\"appPathDefaults\"", "]", ",", "\"general.cfg\"", ")", "try", ":", "# Recovering default file", "with", "open", "(", "defaultConfigPath", ")", "as", "iF", ":", "cont", "=", "iF", ".", "read", "(", ")", "# Moving its contents as the default values", "with", "open", "(", "configPath", ",", "\"w\"", ")", "as", "oF", ":", "oF", ".", "write", "(", "cont", ")", "except", "Exception", "as", "e", ":", "raise", "errors", ".", "DefaultConfigurationFileNotFoundError", "(", "configPath", ",", "defaultConfigPath", ")", "# Reading the configuration file", "config", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "configPath", ")", "LISTS", "=", "[", "\"tlds\"", ",", "\"domains\"", ",", "\"platforms\"", ",", "\"extension\"", ",", "\"exclude_platforms\"", ",", "\"exclude_domains\"", "]", "# Iterating through all the sections, which contain the platforms", "for", "section", "in", "config", ".", "sections", "(", ")", ":", "incomplete", "=", "False", "if", "section", ".", "lower", "(", ")", "==", "util", ".", "lower", "(", ")", ":", "# Iterating through parameters", "for", "(", "param", ",", "value", ")", "in", "config", ".", "items", "(", "section", ")", ":", "if", "value", "==", "''", ":", "# Manually setting an empty value", "if", "param", "in", "LISTS", ":", "value", "=", "[", "]", "else", ":", "value", "=", "\"\"", "# Splitting the parameters to create the arrays when needed", "elif", "param", "in", "LISTS", ":", "value", "=", "value", ".", "split", "(", "' '", ")", "# Converting threads to int", "elif", "param", "==", "\"threads\"", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "Exception", "as", "err", ":", "raise", "errors", ".", "ConfigurationParameterNotValidError", "(", "configPath", ",", "section", ",", "param", ",", "value", ")", "elif", "param", "==", "\"debug\"", ":", "try", ":", "if", "int", "(", "value", ")", "==", "0", ":", "value", "=", "False", "else", ":", "value", "=", "True", "except", "Exception", "as", "err", ":", "print", "(", "\"Something happened when processing this debug option. Resetting to default.\"", ")", "# Copy the data from the default folder", "defaultConfigPath", "=", "os", ".", "path", ".", "join", "(", "getConfigPath", "(", ")", "[", "\"appPathDefaults\"", "]", ",", "\"general.cfg\"", ")", "try", ":", "# Recovering default file", "with", "open", "(", "defaultConfigPath", ")", "as", "iF", ":", "cont", "=", "iF", ".", "read", "(", ")", "# Moving its contents as the default values", "with", "open", "(", "configPath", ",", "\"w\"", ")", "as", "oF", ":", "oF", ".", "write", "(", "cont", ")", "except", "Exception", "as", "e", ":", "raise", "errors", ".", "DefaultConfigurationFileNotFoundError", "(", "configPath", ",", "defaultConfigPath", ")", "#raise errors.ConfigurationParameterNotValidError(configPath, section, param, value)", "VALUES", "[", "param", "]", "=", "value", "break", "return", "VALUES" ]
Method that recovers the configuration information about each program TODO: Grab the default file from the package data instead of storing it in the main folder. Args: ----- util: Any of the utils that are contained in the framework: domainfy, entify, mailfy, phonefy, searchfy, usufy. Returns: -------- A dictionary containing the default configuration.
[ "Method", "that", "recovers", "the", "configuration", "information", "about", "each", "program" ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/configuration.py#L106-L195
train
238,366
i3visio/osrframework
osrframework/searchfy.py
performSearch
def performSearch(platformNames=[], queries=[], process=False, excludePlatformNames=[]): """ Method to perform the search itself on the different platforms. Args: ----- platforms: List of <Platform> objects. queries: List of queries to be performed. process: Whether to process all the profiles... SLOW! Returns: -------- A list with the entities collected. """ # Grabbing the <Platform> objects platforms = platform_selection.getPlatformsByName(platformNames, mode="searchfy", excludePlatformNames=excludePlatformNames) results = [] for q in queries: for pla in platforms: # This returns a json.txt! entities = pla.getInfo(query=q, process = process, mode="searchfy") if entities != "[]": results += json.loads(entities) return results
python
def performSearch(platformNames=[], queries=[], process=False, excludePlatformNames=[]): """ Method to perform the search itself on the different platforms. Args: ----- platforms: List of <Platform> objects. queries: List of queries to be performed. process: Whether to process all the profiles... SLOW! Returns: -------- A list with the entities collected. """ # Grabbing the <Platform> objects platforms = platform_selection.getPlatformsByName(platformNames, mode="searchfy", excludePlatformNames=excludePlatformNames) results = [] for q in queries: for pla in platforms: # This returns a json.txt! entities = pla.getInfo(query=q, process = process, mode="searchfy") if entities != "[]": results += json.loads(entities) return results
[ "def", "performSearch", "(", "platformNames", "=", "[", "]", ",", "queries", "=", "[", "]", ",", "process", "=", "False", ",", "excludePlatformNames", "=", "[", "]", ")", ":", "# Grabbing the <Platform> objects", "platforms", "=", "platform_selection", ".", "getPlatformsByName", "(", "platformNames", ",", "mode", "=", "\"searchfy\"", ",", "excludePlatformNames", "=", "excludePlatformNames", ")", "results", "=", "[", "]", "for", "q", "in", "queries", ":", "for", "pla", "in", "platforms", ":", "# This returns a json.txt!", "entities", "=", "pla", ".", "getInfo", "(", "query", "=", "q", ",", "process", "=", "process", ",", "mode", "=", "\"searchfy\"", ")", "if", "entities", "!=", "\"[]\"", ":", "results", "+=", "json", ".", "loads", "(", "entities", ")", "return", "results" ]
Method to perform the search itself on the different platforms. Args: ----- platforms: List of <Platform> objects. queries: List of queries to be performed. process: Whether to process all the profiles... SLOW! Returns: -------- A list with the entities collected.
[ "Method", "to", "perform", "the", "search", "itself", "on", "the", "different", "platforms", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/searchfy.py#L37-L60
train
238,367
i3visio/osrframework
osrframework/utils/platform_selection.py
getAllPlatformNames
def getAllPlatformNames(mode): """Method that defines the whole list of available parameters. :param mode: The mode of the search. The following can be chosen: ["phonefy", "usufy", "searchfy"]. Return values: Returns a list [] of strings for the platform objects. """ # Recovering all the possible platforms installed platOptions = [] if mode in ["phonefy", "usufy", "searchfy", "mailfy"]: allPlatforms = getAllPlatformObjects(mode=mode) # Defining the platOptions for p in allPlatforms: try: # E. g.: to use wikipedia instead of wikipedia_ca and so on parameter = p.parameterName except: parameter = p.platformName.lower() if parameter not in platOptions: platOptions.append(parameter) elif mode == "domainfy": platOptions = osrframework.domainfy.TLD.keys() platOptions = sorted(set(platOptions)) platOptions.insert(0, 'all') return platOptions
python
def getAllPlatformNames(mode): """Method that defines the whole list of available parameters. :param mode: The mode of the search. The following can be chosen: ["phonefy", "usufy", "searchfy"]. Return values: Returns a list [] of strings for the platform objects. """ # Recovering all the possible platforms installed platOptions = [] if mode in ["phonefy", "usufy", "searchfy", "mailfy"]: allPlatforms = getAllPlatformObjects(mode=mode) # Defining the platOptions for p in allPlatforms: try: # E. g.: to use wikipedia instead of wikipedia_ca and so on parameter = p.parameterName except: parameter = p.platformName.lower() if parameter not in platOptions: platOptions.append(parameter) elif mode == "domainfy": platOptions = osrframework.domainfy.TLD.keys() platOptions = sorted(set(platOptions)) platOptions.insert(0, 'all') return platOptions
[ "def", "getAllPlatformNames", "(", "mode", ")", ":", "# Recovering all the possible platforms installed", "platOptions", "=", "[", "]", "if", "mode", "in", "[", "\"phonefy\"", ",", "\"usufy\"", ",", "\"searchfy\"", ",", "\"mailfy\"", "]", ":", "allPlatforms", "=", "getAllPlatformObjects", "(", "mode", "=", "mode", ")", "# Defining the platOptions", "for", "p", "in", "allPlatforms", ":", "try", ":", "# E. g.: to use wikipedia instead of wikipedia_ca and so on", "parameter", "=", "p", ".", "parameterName", "except", ":", "parameter", "=", "p", ".", "platformName", ".", "lower", "(", ")", "if", "parameter", "not", "in", "platOptions", ":", "platOptions", ".", "append", "(", "parameter", ")", "elif", "mode", "==", "\"domainfy\"", ":", "platOptions", "=", "osrframework", ".", "domainfy", ".", "TLD", ".", "keys", "(", ")", "platOptions", "=", "sorted", "(", "set", "(", "platOptions", ")", ")", "platOptions", ".", "insert", "(", "0", ",", "'all'", ")", "return", "platOptions" ]
Method that defines the whole list of available parameters. :param mode: The mode of the search. The following can be chosen: ["phonefy", "usufy", "searchfy"]. Return values: Returns a list [] of strings for the platform objects.
[ "Method", "that", "defines", "the", "whole", "list", "of", "available", "parameters", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/platform_selection.py#L35-L62
train
238,368
i3visio/osrframework
osrframework/thirdparties/pipl_com/lib/utils.py
Serializable.from_json
def from_json(cls, json_str): """Deserialize the object from a JSON string.""" d = json.loads(json_str) return cls.from_dict(d)
python
def from_json(cls, json_str): """Deserialize the object from a JSON string.""" d = json.loads(json_str) return cls.from_dict(d)
[ "def", "from_json", "(", "cls", ",", "json_str", ")", ":", "d", "=", "json", ".", "loads", "(", "json_str", ")", "return", "cls", ".", "from_dict", "(", "d", ")" ]
Deserialize the object from a JSON string.
[ "Deserialize", "the", "object", "from", "a", "JSON", "string", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/pipl_com/lib/utils.py#L33-L36
train
238,369
i3visio/osrframework
osrframework/checkfy.py
createEmails
def createEmails(nicks=None, nicksFile=None): """ Method that globally permits to generate the emails to be checked. Args: ----- nicks: List of aliases. nicksFile: The filepath to the aliases file. Returns: -------- list: list of emails to be checked. """ 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 nicks: for e in email_providers.domains: candidate_emails.add("{}@{}".format(n, e)) return candidate_emails
python
def createEmails(nicks=None, nicksFile=None): """ Method that globally permits to generate the emails to be checked. Args: ----- nicks: List of aliases. nicksFile: The filepath to the aliases file. Returns: -------- list: list of emails to be checked. """ 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 nicks: for e in email_providers.domains: candidate_emails.add("{}@{}".format(n, e)) return candidate_emails
[ "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", "nicks", ":", "for", "e", "in", "email_providers", ".", "domains", ":", "candidate_emails", ".", "add", "(", "\"{}@{}\"", ".", "format", "(", "n", ",", "e", ")", ")", "return", "candidate_emails" ]
Method that globally permits to generate the emails to be checked. Args: ----- nicks: List of aliases. nicksFile: The filepath to the aliases file. Returns: -------- list: list of emails to be checked.
[ "Method", "that", "globally", "permits", "to", "generate", "the", "emails", "to", "be", "checked", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/checkfy.py#L39-L63
train
238,370
i3visio/osrframework
osrframework/thirdparties/resolvethem_com/processing.py
checkIPFromAlias
def checkIPFromAlias(alias=None): ''' Method that checks if the given alias is currently connected to Skype and returns its IP address. :param alias: Alias to be searched. :return: Python structure for the Json received. It has the following structure: { "type": "i3visio.ip", "value": "1.1.1.1", "attributes" : [] } ''' 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.resolvethem.com", "Referer": "http://www.resolvethem.com/index.php", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0", "Content-Length": "26", "Content-Type": "application/x-www-form-urlencoded", } req = requests.post("http://www.resolvethem.com/index.php",headers=headers,data={'skypeUsername': alias,'submit':''}) # Data returned data = req.content # Compilation of the regular expression p = re.compile("class='alert alert-success'>([0-9\.]*)<") allMatches = p.findall(data) if len(allMatches)> 0: jsonData = {} jsonData["type"]="i3visio.ip" jsonData["value"]=allMatches[0] jsonData["attributes"]=[] return jsonData return {}
python
def checkIPFromAlias(alias=None): ''' Method that checks if the given alias is currently connected to Skype and returns its IP address. :param alias: Alias to be searched. :return: Python structure for the Json received. It has the following structure: { "type": "i3visio.ip", "value": "1.1.1.1", "attributes" : [] } ''' 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.resolvethem.com", "Referer": "http://www.resolvethem.com/index.php", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0", "Content-Length": "26", "Content-Type": "application/x-www-form-urlencoded", } req = requests.post("http://www.resolvethem.com/index.php",headers=headers,data={'skypeUsername': alias,'submit':''}) # Data returned data = req.content # Compilation of the regular expression p = re.compile("class='alert alert-success'>([0-9\.]*)<") allMatches = p.findall(data) if len(allMatches)> 0: jsonData = {} jsonData["type"]="i3visio.ip" jsonData["value"]=allMatches[0] jsonData["attributes"]=[] return jsonData return {}
[ "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.resolvethem.com\"", ",", "\"Referer\"", ":", "\"http://www.resolvethem.com/index.php\"", ",", "\"User-Agent\"", ":", "\"Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0\"", ",", "\"Content-Length\"", ":", "\"26\"", ",", "\"Content-Type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "}", "req", "=", "requests", ".", "post", "(", "\"http://www.resolvethem.com/index.php\"", ",", "headers", "=", "headers", ",", "data", "=", "{", "'skypeUsername'", ":", "alias", ",", "'submit'", ":", "''", "}", ")", "# Data returned", "data", "=", "req", ".", "content", "# Compilation of the regular expression", "p", "=", "re", ".", "compile", "(", "\"class='alert alert-success'>([0-9\\.]*)<\"", ")", "allMatches", "=", "p", ".", "findall", "(", "data", ")", "if", "len", "(", "allMatches", ")", ">", "0", ":", "jsonData", "=", "{", "}", "jsonData", "[", "\"type\"", "]", "=", "\"i3visio.ip\"", "jsonData", "[", "\"value\"", "]", "=", "allMatches", "[", "0", "]", "jsonData", "[", "\"attributes\"", "]", "=", "[", "]", "return", "jsonData", "return", "{", "}" ]
Method that checks if the given alias is currently connected to Skype and returns its IP address. :param alias: Alias to be searched. :return: Python structure for the Json received. It has the following structure: { "type": "i3visio.ip", "value": "1.1.1.1", "attributes" : [] }
[ "Method", "that", "checks", "if", "the", "given", "alias", "is", "currently", "connected", "to", "Skype", "and", "returns", "its", "IP", "address", "." ]
83437f4c14c9c08cb80a896bd9834c77f6567871
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/thirdparties/resolvethem_com/processing.py#L26-L65
train
238,371
jrief/djangocms-cascade
cmsplugin_cascade/sharable/forms.py
SharableGlossaryMixin.get_form
def get_form(self, request, obj=None, **kwargs): """ Extend the form for the given plugin with the form SharableCascadeForm """ 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) return super(SharableGlossaryMixin, self).get_form(request, obj, **kwargs)
python
def get_form(self, request, obj=None, **kwargs): """ Extend the form for the given plugin with the form SharableCascadeForm """ 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) return super(SharableGlossaryMixin, self).get_form(request, obj, **kwargs)
[ "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", ")", "return", "super", "(", "SharableGlossaryMixin", ",", "self", ")", ".", "get_form", "(", "request", ",", "obj", ",", "*", "*", "kwargs", ")" ]
Extend the form for the given plugin with the form SharableCascadeForm
[ "Extend", "the", "form", "for", "the", "given", "plugin", "with", "the", "form", "SharableCascadeForm" ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/sharable/forms.py#L122-L129
train
238,372
jrief/djangocms-cascade
cmsplugin_cascade/bootstrap4/grid.py
Bootstrap4Column.get_min_max_bounds
def get_min_max_bounds(self): """ Return a dict of min- and max-values for the given column. This is required to estimate the bounds of images. """ bound = Bound(999999.0, 0.0) for bp in Breakpoint: bound.extend(self.get_bound(bp)) return {'min': bound.min, 'max': bound.max}
python
def get_min_max_bounds(self): """ Return a dict of min- and max-values for the given column. This is required to estimate the bounds of images. """ bound = Bound(999999.0, 0.0) for bp in Breakpoint: bound.extend(self.get_bound(bp)) return {'min': bound.min, 'max': bound.max}
[ "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.
[ "Return", "a", "dict", "of", "min", "-", "and", "max", "-", "values", "for", "the", "given", "column", ".", "This", "is", "required", "to", "estimate", "the", "bounds", "of", "images", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/bootstrap4/grid.py#L306-L314
train
238,373
jrief/djangocms-cascade
cmsplugin_cascade/plugin_base.py
create_proxy_model
def create_proxy_model(name, model_mixins, base_model, attrs=None, module=None): """ Create a Django Proxy Model on the fly, to be used by any Cascade Plugin. """ 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_mixins + (base_model,) attrs = dict(attrs or {}, Meta=Meta, __module__=module) Model = type(name, bases, attrs) fake_proxy_models[name] = bases return Model
python
def create_proxy_model(name, model_mixins, base_model, attrs=None, module=None): """ Create a Django Proxy Model on the fly, to be used by any Cascade Plugin. """ 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_mixins + (base_model,) attrs = dict(attrs or {}, Meta=Meta, __module__=module) Model = type(name, bases, attrs) fake_proxy_models[name] = bases return Model
[ "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_mixins", "+", "(", "base_model", ",", ")", "attrs", "=", "dict", "(", "attrs", "or", "{", "}", ",", "Meta", "=", "Meta", ",", "__module__", "=", "module", ")", "Model", "=", "type", "(", "name", ",", "bases", ",", "attrs", ")", "fake_proxy_models", "[", "name", "]", "=", "bases", "return", "Model" ]
Create a Django Proxy Model on the fly, to be used by any Cascade Plugin.
[ "Create", "a", "Django", "Proxy", "Model", "on", "the", "fly", "to", "be", "used", "by", "any", "Cascade", "Plugin", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/plugin_base.py#L35-L53
train
238,374
jrief/djangocms-cascade
cmsplugin_cascade/plugin_base.py
CascadePluginBase._get_parent_classes_transparent
def _get_parent_classes_transparent(cls, slot, page, instance=None): """ Return all parent classes including those marked as "transparent". """ 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 = [] # add all plugins marked as 'transparent', since they all are potential parents parent_classes = set(parent_classes) parent_classes.update(TransparentContainer.get_plugins()) return list(parent_classes)
python
def _get_parent_classes_transparent(cls, slot, page, instance=None): """ Return all parent classes including those marked as "transparent". """ 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 = [] # add all plugins marked as 'transparent', since they all are potential parents parent_classes = set(parent_classes) parent_classes.update(TransparentContainer.get_plugins()) return list(parent_classes)
[ "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", "=", "[", "]", "# add all plugins marked as 'transparent', since they all are potential parents", "parent_classes", "=", "set", "(", "parent_classes", ")", "parent_classes", ".", "update", "(", "TransparentContainer", ".", "get_plugins", "(", ")", ")", "return", "list", "(", "parent_classes", ")" ]
Return all parent classes including those marked as "transparent".
[ "Return", "all", "parent", "classes", "including", "those", "marked", "as", "transparent", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/plugin_base.py#L282-L295
train
238,375
jrief/djangocms-cascade
cmsplugin_cascade/plugin_base.py
CascadePluginBase.extend_children
def extend_children(self, parent, wanted_children, child_class, child_glossary=None): """ 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. """ 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=parent) if isinstance(child_glossary, dict): child.glossary.update(child_glossary) child.save()
python
def extend_children(self, parent, wanted_children, child_class, child_glossary=None): """ 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. """ 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=parent) if isinstance(child_glossary, dict): child.glossary.update(child_glossary) child.save()
[ "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", "=", "parent", ")", "if", "isinstance", "(", "child_glossary", ",", "dict", ")", ":", "child", ".", "glossary", ".", "update", "(", "child_glossary", ")", "child", ".", "save", "(", ")" ]
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.
[ "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", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/plugin_base.py#L360-L371
train
238,376
jrief/djangocms-cascade
cmsplugin_cascade/plugin_base.py
CascadePluginBase.get_parent_instance
def get_parent_instance(self, request=None, obj=None): """ 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. """ try: parent_id = obj.parent_id except AttributeError: try: # TODO: self.parent presumably is not used anymore in CMS-3.4, because it doesn't # make sense anyway, since the plugin instances shall know their parents, not the # plugins. 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: parent_id = CMSPlugin.objects.filter(id=request.resolver_match.args[0] ).only("parent_id").order_by('?').first().parent_id except (AttributeError, IndexError): parent_id = None else: parent_id = None for model in CascadeModelBase._get_cascade_elements(): try: return model.objects.get(id=parent_id) except model.DoesNotExist: continue
python
def get_parent_instance(self, request=None, obj=None): """ 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. """ try: parent_id = obj.parent_id except AttributeError: try: # TODO: self.parent presumably is not used anymore in CMS-3.4, because it doesn't # make sense anyway, since the plugin instances shall know their parents, not the # plugins. 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: parent_id = CMSPlugin.objects.filter(id=request.resolver_match.args[0] ).only("parent_id").order_by('?').first().parent_id except (AttributeError, IndexError): parent_id = None else: parent_id = None for model in CascadeModelBase._get_cascade_elements(): try: return model.objects.get(id=parent_id) except model.DoesNotExist: continue
[ "def", "get_parent_instance", "(", "self", ",", "request", "=", "None", ",", "obj", "=", "None", ")", ":", "try", ":", "parent_id", "=", "obj", ".", "parent_id", "except", "AttributeError", ":", "try", ":", "# TODO: self.parent presumably is not used anymore in CMS-3.4, because it doesn't", "# make sense anyway, since the plugin instances shall know their parents, not the", "# plugins.", "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", ":", "parent_id", "=", "CMSPlugin", ".", "objects", ".", "filter", "(", "id", "=", "request", ".", "resolver_match", ".", "args", "[", "0", "]", ")", ".", "only", "(", "\"parent_id\"", ")", ".", "order_by", "(", "'?'", ")", ".", "first", "(", ")", ".", "parent_id", "except", "(", "AttributeError", ",", "IndexError", ")", ":", "parent_id", "=", "None", "else", ":", "parent_id", "=", "None", "for", "model", "in", "CascadeModelBase", ".", "_get_cascade_elements", "(", ")", ":", "try", ":", "return", "model", ".", "objects", ".", "get", "(", "id", "=", "parent_id", ")", "except", "model", ".", "DoesNotExist", ":", "continue" ]
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.
[ "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", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/plugin_base.py#L403-L432
train
238,377
jrief/djangocms-cascade
cmsplugin_cascade/plugin_base.py
CascadePluginBase.in_edit_mode
def in_edit_mode(self, request, placeholder): """ Returns True, if the plugin is in "edit mode". """ 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
python
def in_edit_mode(self, request, placeholder): """ Returns True, if the plugin is in "edit mode". """ 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
[ "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".
[ "Returns", "True", "if", "the", "plugin", "is", "in", "edit", "mode", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/plugin_base.py#L480-L488
train
238,378
jrief/djangocms-cascade
cmsplugin_cascade/segmentation/cms_plugins.py
SegmentPlugin._get_previous_open_tag
def _get_previous_open_tag(self, obj): """ Return the open tag of the previous sibling """ 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')
python
def _get_previous_open_tag(self, obj): """ Return the open tag of the previous sibling """ 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')
[ "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
[ "Return", "the", "open", "tag", "of", "the", "previous", "sibling" ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/segmentation/cms_plugins.py#L170-L176
train
238,379
jrief/djangocms-cascade
cmsplugin_cascade/generic/mixins.py
SectionForm.check_unique_element_id
def check_unique_element_id(cls, instance, element_id): """ Check for uniqueness of the given element_id for the current page. Return None if instance is not yet associated with a page. """ 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(instance.pk) and element_id == value: msg = _("The element ID '{}' is not unique for this page.") raise ValidationError(msg.format(element_id))
python
def check_unique_element_id(cls, instance, element_id): """ Check for uniqueness of the given element_id for the current page. Return None if instance is not yet associated with a page. """ 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(instance.pk) and element_id == value: msg = _("The element ID '{}' is not unique for this page.") raise ValidationError(msg.format(element_id))
[ "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", "(", "instance", ".", "pk", ")", "and", "element_id", "==", "value", ":", "msg", "=", "_", "(", "\"The element ID '{}' is not unique for this page.\"", ")", "raise", "ValidationError", "(", "msg", ".", "format", "(", "element_id", ")", ")" ]
Check for uniqueness of the given element_id for the current page. Return None if instance is not yet associated with a page.
[ "Check", "for", "uniqueness", "of", "the", "given", "element_id", "for", "the", "current", "page", ".", "Return", "None", "if", "instance", "is", "not", "yet", "associated", "with", "a", "page", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/generic/mixins.py#L20-L34
train
238,380
jrief/djangocms-cascade
cmsplugin_cascade/utils.py
rectify_partial_form_field
def rectify_partial_form_field(base_field, partial_form_fields): """ 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. """ 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)
python
def rectify_partial_form_field(base_field, partial_form_fields): """ 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. """ 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)
[ "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.
[ "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", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/utils.py#L16-L28
train
238,381
jrief/djangocms-cascade
cmsplugin_cascade/utils.py
validate_link
def validate_link(link_data): """ Check if the given model exists, otherwise raise a Validation error """ 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__))
python
def validate_link(link_data): """ Check if the given model exists, otherwise raise a Validation error """ 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__))
[ "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
[ "Check", "if", "the", "given", "model", "exists", "otherwise", "raise", "a", "Validation", "error" ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/utils.py#L30-L40
train
238,382
jrief/djangocms-cascade
cmsplugin_cascade/utils.py
parse_responsive_length
def parse_responsive_length(responsive_length): """ 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. """ 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) return (None, None)
python
def parse_responsive_length(responsive_length): """ 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. """ 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) return (None, None)
[ "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", ")", "return", "(", "None", ",", "None", ")" ]
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.
[ "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", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/utils.py#L71-L83
train
238,383
jrief/djangocms-cascade
cmsplugin_cascade/mixins.py
CascadePluginMixin.get_css_classes
def get_css_classes(cls, instance): """ Returns a list of CSS classes to be added as class="..." to the current HTML tag. """ 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_classes.append(css_class) elif isinstance(css_class, list): css_classes.extend(css_class) return css_classes
python
def get_css_classes(cls, instance): """ Returns a list of CSS classes to be added as class="..." to the current HTML tag. """ 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_classes.append(css_class) elif isinstance(css_class, list): css_classes.extend(css_class) return css_classes
[ "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_classes", ".", "append", "(", "css_class", ")", "elif", "isinstance", "(", "css_class", ",", "list", ")", ":", "css_classes", ".", "extend", "(", "css_class", ")", "return", "css_classes" ]
Returns a list of CSS classes to be added as class="..." to the current HTML tag.
[ "Returns", "a", "list", "of", "CSS", "classes", "to", "be", "added", "as", "class", "=", "...", "to", "the", "current", "HTML", "tag", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/mixins.py#L27-L40
train
238,384
jrief/djangocms-cascade
cmsplugin_cascade/mixins.py
CascadePluginMixin.get_inline_styles
def get_inline_styles(cls, instance): """ Returns a dictionary of CSS attributes to be added as style="..." to the current HTML tag. """ 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
python
def get_inline_styles(cls, instance): """ Returns a dictionary of CSS attributes to be added as style="..." to the current HTML tag. """ 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
[ "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.
[ "Returns", "a", "dictionary", "of", "CSS", "attributes", "to", "be", "added", "as", "style", "=", "...", "to", "the", "current", "HTML", "tag", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/mixins.py#L43-L51
train
238,385
jrief/djangocms-cascade
cmsplugin_cascade/mixins.py
CascadePluginMixin.get_html_tag_attributes
def get_html_tag_attributes(cls, instance): """ 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" ...``. """ attributes = getattr(cls, 'html_tag_attributes', {}) return dict((attr, instance.glossary.get(key, '')) for key, attr in attributes.items())
python
def get_html_tag_attributes(cls, instance): """ 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" ...``. """ attributes = getattr(cls, 'html_tag_attributes', {}) return dict((attr, instance.glossary.get(key, '')) for key, attr in attributes.items())
[ "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" ...``.
[ "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", "...", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/mixins.py#L54-L62
train
238,386
jrief/djangocms-cascade
cmsplugin_cascade/widgets.py
CascadingSizeWidgetMixin.compile_validation_pattern
def compile_validation_pattern(self, units=None): """ 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. """ 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(units))) endings = (' %s ' % ugettext("or")).join("'%s'" % u.replace('%', '%%') for u in units) params = {'label': '%(label)s', 'value': '%(value)s', 'field': '%(field)s', 'endings': endings} return regex, self.invalid_message % params
python
def compile_validation_pattern(self, units=None): """ 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. """ 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(units))) endings = (' %s ' % ugettext("or")).join("'%s'" % u.replace('%', '%%') for u in units) params = {'label': '%(label)s', 'value': '%(value)s', 'field': '%(field)s', 'endings': endings} return regex, self.invalid_message % params
[ "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", "(", "units", ")", ")", ")", "endings", "=", "(", "' %s '", "%", "ugettext", "(", "\"or\"", ")", ")", ".", "join", "(", "\"'%s'\"", "%", "u", ".", "replace", "(", "'%'", ",", "'%%'", ")", "for", "u", "in", "units", ")", "params", "=", "{", "'label'", ":", "'%(label)s'", ",", "'value'", ":", "'%(value)s'", ",", "'field'", ":", "'%(field)s'", ",", "'endings'", ":", "endings", "}", "return", "regex", ",", "self", ".", "invalid_message", "%", "params" ]
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.
[ "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", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/widgets.py#L108-L123
train
238,387
jrief/djangocms-cascade
cmsplugin_cascade/link/forms.py
LinkForm.unset_required_for
def unset_required_for(cls, sharable_fields): """ Fields borrowed by `SharedGlossaryAdmin` to build its temporary change form, only are required if they are declared in `sharable_fields`. Otherwise just deactivate them. """ 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
python
def unset_required_for(cls, sharable_fields): """ Fields borrowed by `SharedGlossaryAdmin` to build its temporary change form, only are required if they are declared in `sharable_fields`. Otherwise just deactivate them. """ 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
[ "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.
[ "Fields", "borrowed", "by", "SharedGlossaryAdmin", "to", "build", "its", "temporary", "change", "form", "only", "are", "required", "if", "they", "are", "declared", "in", "sharable_fields", ".", "Otherwise", "just", "deactivate", "them", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/link/forms.py#L260-L268
train
238,388
jrief/djangocms-cascade
cmsplugin_cascade/models.py
CascadePage.assure_relation
def assure_relation(cls, cms_page): """ Assure that we have a foreign key relation, pointing from CascadePage onto CMSPage. """ try: cms_page.cascadepage except cls.DoesNotExist: cls.objects.create(extended_object=cms_page)
python
def assure_relation(cls, cms_page): """ Assure that we have a foreign key relation, pointing from CascadePage onto CMSPage. """ try: cms_page.cascadepage except cls.DoesNotExist: cls.objects.create(extended_object=cms_page)
[ "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.
[ "Assure", "that", "we", "have", "a", "foreign", "key", "relation", "pointing", "from", "CascadePage", "onto", "CMSPage", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/models.py#L371-L378
train
238,389
jrief/djangocms-cascade
cmsplugin_cascade/bootstrap3/utils.py
compute_media_queries
def compute_media_queries(element): """ For e given Cascade element, compute the current media queries for each breakpoint, even for nested containers, rows and columns. """ parent_glossary = element.get_parent_glossary() # compute the max width and the required media queries for each chosen breakpoint element.glossary['container_max_widths'] = max_widths = {} element.glossary['media_queries'] = media_queries = {} breakpoints = element.glossary.get('breakpoints', parent_glossary.get('breakpoints', [])) last_index = len(breakpoints) - 1 fluid = element.glossary.get('fluid') for index, bp in enumerate(breakpoints): try: key = 'container_fluid_max_widths' if fluid else 'container_max_widths' max_widths[bp] = parent_glossary[key][bp] except KeyError: max_widths[bp] = BS3_BREAKPOINTS[bp][4 if fluid else 3] if last_index > 0: if index == 0: next_bp = breakpoints[1] media_queries[bp] = ['(max-width: {0}px)'.format(BS3_BREAKPOINTS[next_bp][0])] elif index == last_index: media_queries[bp] = ['(min-width: {0}px)'.format(BS3_BREAKPOINTS[bp][0])] else: next_bp = breakpoints[index + 1] media_queries[bp] = ['(min-width: {0}px)'.format(BS3_BREAKPOINTS[bp][0]), '(max-width: {0}px)'.format(BS3_BREAKPOINTS[next_bp][0])]
python
def compute_media_queries(element): """ For e given Cascade element, compute the current media queries for each breakpoint, even for nested containers, rows and columns. """ parent_glossary = element.get_parent_glossary() # compute the max width and the required media queries for each chosen breakpoint element.glossary['container_max_widths'] = max_widths = {} element.glossary['media_queries'] = media_queries = {} breakpoints = element.glossary.get('breakpoints', parent_glossary.get('breakpoints', [])) last_index = len(breakpoints) - 1 fluid = element.glossary.get('fluid') for index, bp in enumerate(breakpoints): try: key = 'container_fluid_max_widths' if fluid else 'container_max_widths' max_widths[bp] = parent_glossary[key][bp] except KeyError: max_widths[bp] = BS3_BREAKPOINTS[bp][4 if fluid else 3] if last_index > 0: if index == 0: next_bp = breakpoints[1] media_queries[bp] = ['(max-width: {0}px)'.format(BS3_BREAKPOINTS[next_bp][0])] elif index == last_index: media_queries[bp] = ['(min-width: {0}px)'.format(BS3_BREAKPOINTS[bp][0])] else: next_bp = breakpoints[index + 1] media_queries[bp] = ['(min-width: {0}px)'.format(BS3_BREAKPOINTS[bp][0]), '(max-width: {0}px)'.format(BS3_BREAKPOINTS[next_bp][0])]
[ "def", "compute_media_queries", "(", "element", ")", ":", "parent_glossary", "=", "element", ".", "get_parent_glossary", "(", ")", "# compute the max width and the required media queries for each chosen breakpoint", "element", ".", "glossary", "[", "'container_max_widths'", "]", "=", "max_widths", "=", "{", "}", "element", ".", "glossary", "[", "'media_queries'", "]", "=", "media_queries", "=", "{", "}", "breakpoints", "=", "element", ".", "glossary", ".", "get", "(", "'breakpoints'", ",", "parent_glossary", ".", "get", "(", "'breakpoints'", ",", "[", "]", ")", ")", "last_index", "=", "len", "(", "breakpoints", ")", "-", "1", "fluid", "=", "element", ".", "glossary", ".", "get", "(", "'fluid'", ")", "for", "index", ",", "bp", "in", "enumerate", "(", "breakpoints", ")", ":", "try", ":", "key", "=", "'container_fluid_max_widths'", "if", "fluid", "else", "'container_max_widths'", "max_widths", "[", "bp", "]", "=", "parent_glossary", "[", "key", "]", "[", "bp", "]", "except", "KeyError", ":", "max_widths", "[", "bp", "]", "=", "BS3_BREAKPOINTS", "[", "bp", "]", "[", "4", "if", "fluid", "else", "3", "]", "if", "last_index", ">", "0", ":", "if", "index", "==", "0", ":", "next_bp", "=", "breakpoints", "[", "1", "]", "media_queries", "[", "bp", "]", "=", "[", "'(max-width: {0}px)'", ".", "format", "(", "BS3_BREAKPOINTS", "[", "next_bp", "]", "[", "0", "]", ")", "]", "elif", "index", "==", "last_index", ":", "media_queries", "[", "bp", "]", "=", "[", "'(min-width: {0}px)'", ".", "format", "(", "BS3_BREAKPOINTS", "[", "bp", "]", "[", "0", "]", ")", "]", "else", ":", "next_bp", "=", "breakpoints", "[", "index", "+", "1", "]", "media_queries", "[", "bp", "]", "=", "[", "'(min-width: {0}px)'", ".", "format", "(", "BS3_BREAKPOINTS", "[", "bp", "]", "[", "0", "]", ")", ",", "'(max-width: {0}px)'", ".", "format", "(", "BS3_BREAKPOINTS", "[", "next_bp", "]", "[", "0", "]", ")", "]" ]
For e given Cascade element, compute the current media queries for each breakpoint, even for nested containers, rows and columns.
[ "For", "e", "given", "Cascade", "element", "compute", "the", "current", "media", "queries", "for", "each", "breakpoint", "even", "for", "nested", "containers", "rows", "and", "columns", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/bootstrap3/utils.py#L63-L90
train
238,390
jrief/djangocms-cascade
cmsplugin_cascade/fields.py
GlossaryField.get_element_ids
def get_element_ids(self, prefix_id): """ Returns a single or a list of element ids, one for each input widget of this field """ 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}'.format(prefix_id, self.name, k) for k in range(len(self.widget.choices))] else: ids = ['{0}_{1}'.format(prefix_id, self.name)] return ids
python
def get_element_ids(self, prefix_id): """ Returns a single or a list of element ids, one for each input widget of this field """ 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}'.format(prefix_id, self.name, k) for k in range(len(self.widget.choices))] else: ids = ['{0}_{1}'.format(prefix_id, self.name)] return ids
[ "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}'", ".", "format", "(", "prefix_id", ",", "self", ".", "name", ",", "k", ")", "for", "k", "in", "range", "(", "len", "(", "self", ".", "widget", ".", "choices", ")", ")", "]", "else", ":", "ids", "=", "[", "'{0}_{1}'", ".", "format", "(", "prefix_id", ",", "self", ".", "name", ")", "]", "return", "ids" ]
Returns a single or a list of element ids, one for each input widget of this field
[ "Returns", "a", "single", "or", "a", "list", "of", "element", "ids", "one", "for", "each", "input", "widget", "of", "this", "field" ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/fields.py#L50-L60
train
238,391
jrief/djangocms-cascade
cmsplugin_cascade/segmentation/mixins.py
EmulateUserModelMixin.get_context_override
def get_context_override(self, request): """ Override the request object with an emulated user. """ 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.UserModel.DoesNotExist, KeyError): pass return context_override
python
def get_context_override(self, request): """ Override the request object with an emulated user. """ 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.UserModel.DoesNotExist, KeyError): pass return context_override
[ "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", ".", "UserModel", ".", "DoesNotExist", ",", "KeyError", ")", ":", "pass", "return", "context_override" ]
Override the request object with an emulated user.
[ "Override", "the", "request", "object", "with", "an", "emulated", "user", "." ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/segmentation/mixins.py#L48-L59
train
238,392
jrief/djangocms-cascade
cmsplugin_cascade/segmentation/mixins.py
EmulateUserAdminMixin.emulate_users
def emulate_users(self, request): """ The list view """ 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('emulate_user_id') if emulate_user_id == obj.id: return format_html('<strong>{}</strong>', identifier) fmtargs = { 'href': reverse('admin:emulate-user', kwargs={'user_id': obj.id}), 'identifier': identifier, } return format_html('<a href="{href}" class="emulate-user">{identifier}</a>', **fmtargs) opts = self.UserModel._meta app_label = opts.app_label user_model_admin = self.admin_site._registry[self.UserModel] request._lookup_model = self.UserModel list_display_links = user_model_admin.get_list_display_links(request, user_model_admin.list_display) # replace first entry in list_display_links by customized method display_as_link list_display_link = list_display_links[0] try: list_display = list(user_model_admin.segmentation_list_display) except AttributeError: list_display = list(user_model_admin.list_display) list_display.remove(list_display_link) list_display.insert(0, 'display_as_link') display_as_link.allow_tags = True # TODO: presumably not required anymore since Django-1.9 try: display_as_link.short_description = user_model_admin.identifier.short_description except AttributeError: display_as_link.short_description = admin.utils.label_for_field(list_display_link, self.UserModel) self.display_as_link = six.create_bound_method(display_as_link, self) ChangeList = self.get_changelist(request) cl = ChangeList(request, self.UserModel, list_display, (None,), # disable list_display_links in ChangeList, instead override that field user_model_admin.list_filter, user_model_admin.date_hierarchy, user_model_admin.search_fields, user_model_admin.list_select_related, user_model_admin.list_per_page, user_model_admin.list_max_show_all, (), # disable list_editable self) cl.formset = None selection_note_all = ungettext('%(total_count)s selected', 'All %(total_count)s selected', cl.result_count) context = { 'module_name': force_text(opts.verbose_name_plural), 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)}, 'selection_note_all': selection_note_all % {'total_count': cl.result_count}, 'title': _("Select %(user_model)s to emulate") % {'user_model': opts.verbose_name}, 'is_popup': cl.is_popup, 'cl': cl, 'media': self.media, 'has_add_permission': False, 'opts': cl.opts, 'app_label': app_label, 'actions_on_top': self.actions_on_top, 'actions_on_bottom': self.actions_on_bottom, 'actions_selection_counter': self.actions_selection_counter, 'preserved_filters': self.get_preserved_filters(request), } return TemplateResponse(request, self.change_list_template or [ 'admin/%s/%s/change_list.html' % (app_label, opts.model_name), 'admin/%s/change_list.html' % app_label, 'admin/change_list.html' ], context)
python
def emulate_users(self, request): """ The list view """ 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('emulate_user_id') if emulate_user_id == obj.id: return format_html('<strong>{}</strong>', identifier) fmtargs = { 'href': reverse('admin:emulate-user', kwargs={'user_id': obj.id}), 'identifier': identifier, } return format_html('<a href="{href}" class="emulate-user">{identifier}</a>', **fmtargs) opts = self.UserModel._meta app_label = opts.app_label user_model_admin = self.admin_site._registry[self.UserModel] request._lookup_model = self.UserModel list_display_links = user_model_admin.get_list_display_links(request, user_model_admin.list_display) # replace first entry in list_display_links by customized method display_as_link list_display_link = list_display_links[0] try: list_display = list(user_model_admin.segmentation_list_display) except AttributeError: list_display = list(user_model_admin.list_display) list_display.remove(list_display_link) list_display.insert(0, 'display_as_link') display_as_link.allow_tags = True # TODO: presumably not required anymore since Django-1.9 try: display_as_link.short_description = user_model_admin.identifier.short_description except AttributeError: display_as_link.short_description = admin.utils.label_for_field(list_display_link, self.UserModel) self.display_as_link = six.create_bound_method(display_as_link, self) ChangeList = self.get_changelist(request) cl = ChangeList(request, self.UserModel, list_display, (None,), # disable list_display_links in ChangeList, instead override that field user_model_admin.list_filter, user_model_admin.date_hierarchy, user_model_admin.search_fields, user_model_admin.list_select_related, user_model_admin.list_per_page, user_model_admin.list_max_show_all, (), # disable list_editable self) cl.formset = None selection_note_all = ungettext('%(total_count)s selected', 'All %(total_count)s selected', cl.result_count) context = { 'module_name': force_text(opts.verbose_name_plural), 'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)}, 'selection_note_all': selection_note_all % {'total_count': cl.result_count}, 'title': _("Select %(user_model)s to emulate") % {'user_model': opts.verbose_name}, 'is_popup': cl.is_popup, 'cl': cl, 'media': self.media, 'has_add_permission': False, 'opts': cl.opts, 'app_label': app_label, 'actions_on_top': self.actions_on_top, 'actions_on_bottom': self.actions_on_bottom, 'actions_selection_counter': self.actions_selection_counter, 'preserved_filters': self.get_preserved_filters(request), } return TemplateResponse(request, self.change_list_template or [ 'admin/%s/%s/change_list.html' % (app_label, opts.model_name), 'admin/%s/change_list.html' % app_label, 'admin/change_list.html' ], context)
[ "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", "(", "'emulate_user_id'", ")", "if", "emulate_user_id", "==", "obj", ".", "id", ":", "return", "format_html", "(", "'<strong>{}</strong>'", ",", "identifier", ")", "fmtargs", "=", "{", "'href'", ":", "reverse", "(", "'admin:emulate-user'", ",", "kwargs", "=", "{", "'user_id'", ":", "obj", ".", "id", "}", ")", ",", "'identifier'", ":", "identifier", ",", "}", "return", "format_html", "(", "'<a href=\"{href}\" class=\"emulate-user\">{identifier}</a>'", ",", "*", "*", "fmtargs", ")", "opts", "=", "self", ".", "UserModel", ".", "_meta", "app_label", "=", "opts", ".", "app_label", "user_model_admin", "=", "self", ".", "admin_site", ".", "_registry", "[", "self", ".", "UserModel", "]", "request", ".", "_lookup_model", "=", "self", ".", "UserModel", "list_display_links", "=", "user_model_admin", ".", "get_list_display_links", "(", "request", ",", "user_model_admin", ".", "list_display", ")", "# replace first entry in list_display_links by customized method display_as_link", "list_display_link", "=", "list_display_links", "[", "0", "]", "try", ":", "list_display", "=", "list", "(", "user_model_admin", ".", "segmentation_list_display", ")", "except", "AttributeError", ":", "list_display", "=", "list", "(", "user_model_admin", ".", "list_display", ")", "list_display", ".", "remove", "(", "list_display_link", ")", "list_display", ".", "insert", "(", "0", ",", "'display_as_link'", ")", "display_as_link", ".", "allow_tags", "=", "True", "# TODO: presumably not required anymore since Django-1.9", "try", ":", "display_as_link", ".", "short_description", "=", "user_model_admin", ".", "identifier", ".", "short_description", "except", "AttributeError", ":", "display_as_link", ".", "short_description", "=", "admin", ".", "utils", ".", "label_for_field", "(", "list_display_link", ",", "self", ".", "UserModel", ")", "self", ".", "display_as_link", "=", "six", ".", "create_bound_method", "(", "display_as_link", ",", "self", ")", "ChangeList", "=", "self", ".", "get_changelist", "(", "request", ")", "cl", "=", "ChangeList", "(", "request", ",", "self", ".", "UserModel", ",", "list_display", ",", "(", "None", ",", ")", ",", "# disable list_display_links in ChangeList, instead override that field", "user_model_admin", ".", "list_filter", ",", "user_model_admin", ".", "date_hierarchy", ",", "user_model_admin", ".", "search_fields", ",", "user_model_admin", ".", "list_select_related", ",", "user_model_admin", ".", "list_per_page", ",", "user_model_admin", ".", "list_max_show_all", ",", "(", ")", ",", "# disable list_editable", "self", ")", "cl", ".", "formset", "=", "None", "selection_note_all", "=", "ungettext", "(", "'%(total_count)s selected'", ",", "'All %(total_count)s selected'", ",", "cl", ".", "result_count", ")", "context", "=", "{", "'module_name'", ":", "force_text", "(", "opts", ".", "verbose_name_plural", ")", ",", "'selection_note'", ":", "_", "(", "'0 of %(cnt)s selected'", ")", "%", "{", "'cnt'", ":", "len", "(", "cl", ".", "result_list", ")", "}", ",", "'selection_note_all'", ":", "selection_note_all", "%", "{", "'total_count'", ":", "cl", ".", "result_count", "}", ",", "'title'", ":", "_", "(", "\"Select %(user_model)s to emulate\"", ")", "%", "{", "'user_model'", ":", "opts", ".", "verbose_name", "}", ",", "'is_popup'", ":", "cl", ".", "is_popup", ",", "'cl'", ":", "cl", ",", "'media'", ":", "self", ".", "media", ",", "'has_add_permission'", ":", "False", ",", "'opts'", ":", "cl", ".", "opts", ",", "'app_label'", ":", "app_label", ",", "'actions_on_top'", ":", "self", ".", "actions_on_top", ",", "'actions_on_bottom'", ":", "self", ".", "actions_on_bottom", ",", "'actions_selection_counter'", ":", "self", ".", "actions_selection_counter", ",", "'preserved_filters'", ":", "self", ".", "get_preserved_filters", "(", "request", ")", ",", "}", "return", "TemplateResponse", "(", "request", ",", "self", ".", "change_list_template", "or", "[", "'admin/%s/%s/change_list.html'", "%", "(", "app_label", ",", "opts", ".", "model_name", ")", ",", "'admin/%s/change_list.html'", "%", "app_label", ",", "'admin/change_list.html'", "]", ",", "context", ")" ]
The list view
[ "The", "list", "view" ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/segmentation/mixins.py#L88-L159
train
238,393
jrief/djangocms-cascade
cmsplugin_cascade/apps.py
CascadeConfig.pre_migrate
def pre_migrate(cls, sender=None, **kwargs): """ Iterate over contenttypes and remove those not in proxy models """ 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() if model is None: sender.revoke_permissions(ctype) ContentType.objects.get(app_label=sender.label, model=ctype).delete() except DatabaseError: return
python
def pre_migrate(cls, sender=None, **kwargs): """ Iterate over contenttypes and remove those not in proxy models """ 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() if model is None: sender.revoke_permissions(ctype) ContentType.objects.get(app_label=sender.label, model=ctype).delete() except DatabaseError: return
[ "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", "(", ")", "if", "model", "is", "None", ":", "sender", ".", "revoke_permissions", "(", "ctype", ")", "ContentType", ".", "objects", ".", "get", "(", "app_label", "=", "sender", ".", "label", ",", "model", "=", "ctype", ")", ".", "delete", "(", ")", "except", "DatabaseError", ":", "return" ]
Iterate over contenttypes and remove those not in proxy models
[ "Iterate", "over", "contenttypes", "and", "remove", "those", "not", "in", "proxy", "models" ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/apps.py#L29-L42
train
238,394
jrief/djangocms-cascade
cmsplugin_cascade/apps.py
CascadeConfig.post_migrate
def post_migrate(cls, sender=None, **kwargs): """ Iterate over fake_proxy_models and add contenttypes and permissions for missing proxy models, if this has not been done by Django yet """ 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: sender.grant_permissions(proxy_model)
python
def post_migrate(cls, sender=None, **kwargs): """ Iterate over fake_proxy_models and add contenttypes and permissions for missing proxy models, if this has not been done by Django yet """ 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: sender.grant_permissions(proxy_model)
[ "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", ":", "sender", ".", "grant_permissions", "(", "proxy_model", ")" ]
Iterate over fake_proxy_models and add contenttypes and permissions for missing proxy models, if this has not been done by Django yet
[ "Iterate", "over", "fake_proxy_models", "and", "add", "contenttypes", "and", "permissions", "for", "missing", "proxy", "models", "if", "this", "has", "not", "been", "done", "by", "Django", "yet" ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/apps.py#L45-L55
train
238,395
jrief/djangocms-cascade
cmsplugin_cascade/apps.py
CascadeConfig.grant_permissions
def grant_permissions(self, proxy_model): """ Create the default permissions for the just added proxy model """ ContentType = apps.get_model('contenttypes', 'ContentType') try: Permission = apps.get_model('auth', 'Permission') except LookupError: return # searched_perms will hold the permissions we're looking for as (content_type, (codename, name)) searched_perms = [] ctype = ContentType.objects.get_for_model(proxy_model) for perm in self.default_permissions: searched_perms.append(( '{0}_{1}'.format(perm, proxy_model._meta.model_name), "Can {0} {1}".format(perm, proxy_model._meta.verbose_name_raw) )) all_perms = set(Permission.objects.filter( content_type=ctype, ).values_list( 'content_type', 'codename' )) permissions = [ Permission(codename=codename, name=name, content_type=ctype) for codename, name in searched_perms if (ctype.pk, codename) not in all_perms ] Permission.objects.bulk_create(permissions)
python
def grant_permissions(self, proxy_model): """ Create the default permissions for the just added proxy model """ ContentType = apps.get_model('contenttypes', 'ContentType') try: Permission = apps.get_model('auth', 'Permission') except LookupError: return # searched_perms will hold the permissions we're looking for as (content_type, (codename, name)) searched_perms = [] ctype = ContentType.objects.get_for_model(proxy_model) for perm in self.default_permissions: searched_perms.append(( '{0}_{1}'.format(perm, proxy_model._meta.model_name), "Can {0} {1}".format(perm, proxy_model._meta.verbose_name_raw) )) all_perms = set(Permission.objects.filter( content_type=ctype, ).values_list( 'content_type', 'codename' )) permissions = [ Permission(codename=codename, name=name, content_type=ctype) for codename, name in searched_perms if (ctype.pk, codename) not in all_perms ] Permission.objects.bulk_create(permissions)
[ "def", "grant_permissions", "(", "self", ",", "proxy_model", ")", ":", "ContentType", "=", "apps", ".", "get_model", "(", "'contenttypes'", ",", "'ContentType'", ")", "try", ":", "Permission", "=", "apps", ".", "get_model", "(", "'auth'", ",", "'Permission'", ")", "except", "LookupError", ":", "return", "# searched_perms will hold the permissions we're looking for as (content_type, (codename, name))", "searched_perms", "=", "[", "]", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "proxy_model", ")", "for", "perm", "in", "self", ".", "default_permissions", ":", "searched_perms", ".", "append", "(", "(", "'{0}_{1}'", ".", "format", "(", "perm", ",", "proxy_model", ".", "_meta", ".", "model_name", ")", ",", "\"Can {0} {1}\"", ".", "format", "(", "perm", ",", "proxy_model", ".", "_meta", ".", "verbose_name_raw", ")", ")", ")", "all_perms", "=", "set", "(", "Permission", ".", "objects", ".", "filter", "(", "content_type", "=", "ctype", ",", ")", ".", "values_list", "(", "'content_type'", ",", "'codename'", ")", ")", "permissions", "=", "[", "Permission", "(", "codename", "=", "codename", ",", "name", "=", "name", ",", "content_type", "=", "ctype", ")", "for", "codename", ",", "name", "in", "searched_perms", "if", "(", "ctype", ".", "pk", ",", "codename", ")", "not", "in", "all_perms", "]", "Permission", ".", "objects", ".", "bulk_create", "(", "permissions", ")" ]
Create the default permissions for the just added proxy model
[ "Create", "the", "default", "permissions", "for", "the", "just", "added", "proxy", "model" ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/apps.py#L67-L95
train
238,396
jrief/djangocms-cascade
cmsplugin_cascade/apps.py
CascadeConfig.revoke_permissions
def revoke_permissions(self, ctype): """ Remove all permissions for the content type to be removed """ 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_model(self.label, 'cascadeelement') element_ctype = ContentType.objects.get_for_model(cascade_element) Permission.objects.filter(content_type=element_ctype, codename__in=codenames).delete()
python
def revoke_permissions(self, ctype): """ Remove all permissions for the content type to be removed """ 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_model(self.label, 'cascadeelement') element_ctype = ContentType.objects.get_for_model(cascade_element) Permission.objects.filter(content_type=element_ctype, codename__in=codenames).delete()
[ "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_model", "(", "self", ".", "label", ",", "'cascadeelement'", ")", "element_ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "cascade_element", ")", "Permission", ".", "objects", ".", "filter", "(", "content_type", "=", "element_ctype", ",", "codename__in", "=", "codenames", ")", ".", "delete", "(", ")" ]
Remove all permissions for the content type to be removed
[ "Remove", "all", "permissions", "for", "the", "content", "type", "to", "be", "removed" ]
58996f990c4068e5d50f0db6030a5c0e06b682e5
https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/apps.py#L97-L110
train
238,397
adamreeve/npTDMS
nptdms/writer.py
to_file
def to_file(file, array): """Wrapper around ndarray.tofile to support any file-like object""" try: array.tofile(file) except (TypeError, IOError, UnsupportedOperation): # tostring actually returns bytes file.write(array.tostring())
python
def to_file(file, array): """Wrapper around ndarray.tofile to support any file-like object""" try: array.tofile(file) except (TypeError, IOError, UnsupportedOperation): # tostring actually returns bytes file.write(array.tostring())
[ "def", "to_file", "(", "file", ",", "array", ")", ":", "try", ":", "array", ".", "tofile", "(", "file", ")", "except", "(", "TypeError", ",", "IOError", ",", "UnsupportedOperation", ")", ":", "# tostring actually returns bytes", "file", ".", "write", "(", "array", ".", "tostring", "(", ")", ")" ]
Wrapper around ndarray.tofile to support any file-like object
[ "Wrapper", "around", "ndarray", ".", "tofile", "to", "support", "any", "file", "-", "like", "object" ]
d7d6632d4ebc2e78ed941477c2f1c56bd7493d74
https://github.com/adamreeve/npTDMS/blob/d7d6632d4ebc2e78ed941477c2f1c56bd7493d74/nptdms/writer.py#L317-L324
train
238,398
adamreeve/npTDMS
nptdms/writer.py
TdmsWriter.write_segment
def write_segment(self, objects): """ Write a segment of data to a TDMS file :param objects: A list of TdmsObject instances to write """ segment = TdmsSegment(objects) segment.write(self._file)
python
def write_segment(self, objects): """ Write a segment of data to a TDMS file :param objects: A list of TdmsObject instances to write """ segment = TdmsSegment(objects) segment.write(self._file)
[ "def", "write_segment", "(", "self", ",", "objects", ")", ":", "segment", "=", "TdmsSegment", "(", "objects", ")", "segment", ".", "write", "(", "self", ".", "_file", ")" ]
Write a segment of data to a TDMS file :param objects: A list of TdmsObject instances to write
[ "Write", "a", "segment", "of", "data", "to", "a", "TDMS", "file" ]
d7d6632d4ebc2e78ed941477c2f1c56bd7493d74
https://github.com/adamreeve/npTDMS/blob/d7d6632d4ebc2e78ed941477c2f1c56bd7493d74/nptdms/writer.py#L63-L69
train
238,399