Search is not available for this dataset
text stringlengths 75 104k |
|---|
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...
"""
... |
def display(self):
"""A unicode value with the object's data, to be used for displaying
the object in your application."""
if self.title and self.organization:
disp = self.title + u' at ' + self.organization
else:
disp = self.title or self.organization or N... |
def display(self):
"""A unicode value with the object's data, to be used for displaying
the object in your application."""
if self.degree and self.school:
disp = self.degree + u' from ' + self.school
else:
disp = self.degree or self.school or None
... |
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 se... |
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)
... |
def from_birth_year(birth_year):
"""Take a person's birth year (int) and return a new DOB object
suitable for him."""
if birth_year <= 0:
raise ValueError('birth_year must be positive')
date_range = DateRange.from_years_range(birth_year, birth_year)
return DOB(... |
def from_birth_date(birth_date):
"""Take a person's birth date (datetime.date) and return a new DOB
object suitable for him."""
if birth_date > datetime.date.today():
raise ValueError('birth_date can\'t be in the future')
date_range = DateRange(birth_date, birth_date)
... |
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:
... |
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_years_range(start_year, end_year):
"""Transform a range of years (two ints) to a DateRange object."""
start = datetime.date(start_year, 1 , 1)
end = datetime.date(end_year, 12 , 31)
return DateRange(start, end) |
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)
ret... |
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 getAttributes(self, foundExp):
'''
Method to extract additional attributes from a given expression (i. e.: domains and ports from URL and so on). This method may be overwritten in certain child classes.
:param found_exp: expression to be processed.
:return: The outpu... |
def getAttributes(self, found = None):
'''
Method to extract additional attributes from a given expression (i. e.: domains and ports from URL and so on). This method may be overwritten in certain child classes.
:param found: expression to be processed.
:return: The outpu... |
def getEntityType(self, found = None):
'''
Method to recover the value of the entity in case it may vary.
:param found: The expression to be analysed.
:return: The entity type returned will be an s'i3visio.email' for foo@bar.com and an 'i3visio.text' for foo[at]bar[dot]... |
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
... |
def main(params=None):
"""
Main loop for the enumeration
Args:
-----
params: A list with the parameters as grabbed by the terminal. It is
None when this is called by an entry_point.
"""
# Grabbing the parser
parser = getParser()
if params != None:
... |
def do_usufy(self, query, **kwargs):
"""
Verifying a usufy 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 app... |
def do_searchfy(self, query, **kwargs):
"""
Verifying a usufy 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 ... |
def returnListOfCreds():
'''
:return:
A list of tuples containing in the first the name of the platform,
as read from the accounts.cfg file in the application folder. E. g.:
listCreds.append(("<platform>", "<username>", "<password>"))
'''
listCreds = []
# If ... |
def extractFieldsFromResult(data):
'''
Method that parses Infobel textual information to return a series of attributes.
:return: a list of i3visio-like objects.
'''
entities = []
# Defining the objects to extract
fieldsRegExp = {}
fieldsRegExp["i3visio.full... |
def getResults(uri):
'''
Method that recovers the text for each result in infobel.com
:param uri: Infobel uri
:return: A list of textual information to be processed
'''
# Using i3visio browser to avoid certain issues...
i3Browser = browser.Browser()
data... |
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... |
def checkInfo(email=None, username=None, api_key=None):
'''
Method that checks if the given hash is stored in the pipl.com website.
:param email: queries to be launched.
:param api_key: api_key to be used in pipl.com. If not provided, the API key will be searched in the config_api_keys.py... |
def launchRequest(request):
'''
Method to launch a given request.
:param request: The request object.
:return: A dictionary containinf the results of the person and a list of dicts containing the references for the record.
'''
person = {}
records = []
... |
def setupLogger(loggerName="osrframework", logFolder="./logs", verbosity=0):
"""
Returns the logger to be used for the whole app. This method may be invoked if required by the launcher to update the verbosity syntax.
:param loggerName: Name of the package or app that is going to use this lo... |
def do_mailfy(self, query):
"""
Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return an equivalent array.
Args:
-----
query: The element to be searched.... |
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... |
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.
@... |
def processSearch(query, tld='com', lang='en', num=10, start=0, stop=50, pause=2.0, only_standard=False):
'''
Method that recovers the URI for a search returning an i3visio-compliant json object.
:return: A json-like object.
'''
uriList = search(query, tld=tld, lang=lang... |
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:
con... |
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 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... |
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]
... |
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(v... |
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
... |
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
... |
def unsearchable_fields(self):
"""A list of all the fields that can't be searched by.
For example: names/usernames that are too short, emails that are
invalid etc.
"""
filter_func = lambda field: not field.is_searchable
return filter(filter_func, self.n... |
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=... |
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(se... |
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 ... |
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.
"""
... |
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... |
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:... |
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:
# Su... |
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 authen... |
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 am... |
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.
"""
... |
def check_mailfy(self, query, kwargs={}):
"""
Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return a dictionary as defined.
Args:
-----
query: The eleme... |
def do_mailfy(self, query, **kwargs):
"""
Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return an equivalent array.
Args:
-----
query: The element to be... |
def check_searchfy(self, query, kwargs={}):
"""
Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return a dictionary as defined.
Args:
-----
query: The ele... |
def do_searchfy(self, query, **kwargs):
"""
Verifying a searchfy query in this platform.
This might be redefined in any class inheriting from Platform.
Performing additional procesing may be possible by iterating the requested profiles
to extract more entities from the URI woul... |
def check_phonefy(self, query, kwargs={}):
"""
Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return a dictionary as defined.
Args:
-----
query: The elem... |
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... |
def check_usufy(self, query, **kwargs):
"""
Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return a dictionary as defined.
Args:
-----
query: The element to ... |
def do_usufy(self, query, **kwargs):
"""
Verifying a usufy 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 app... |
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 ... |
def getAllRegexp():
'''
Method that recovers ALL the list of <RegexpObject> classes to be processed....
:return: Returns a list [] of <RegexpObject> classes.
'''
listAll = []
############################################################################
##########################... |
def checkIfHashIsCracked(hash=None, api_key=None):
'''
Method that checks if the given hash is stored in the md5crack.com website.
:param hash: hash to verify.
:param api_key: api_key to be used in md5crack.com. If not provided, the API key will be searched in the config_api_keys.py file.
:return: Python s... |
def somethingFound(self,data,mode="phonefy"):
'''
Verifying if something was found. Note that this method needed to be rewritten as in Spoj we need to look for a text which APPEARS instead of looking for a text that does NOT appear.
:param data: Data where the self.notFo... |
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]
... |
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):
# Setti... |
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, appPathPlugi... |
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: domai... |
def getBitcoinAddressDetails(address=None):
'''
Method that checks the presence of a Bitcoin Address in blockchain.info:
{
"total_sent": 41301084,
"total_received": 52195147,
"final_balance": 10894063,
"address": "1APKyS2TEdFMjXjJfMCgavFtoWuv2QNXTw",
"hash160": "66f21efc754af07e87913db46bf24d... |
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 a... |
def main(params=None):
"""
Main function to launch usufy.
The function is created in this way so as to let other applications make
use of the full configuration capabilities of the application. The
parameters received are used as parsed by this modules `getParser()`.
Args:
-----
pa... |
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.
"""
# Recov... |
def getPlatformsByName(platformNames=['all'], mode=None, tags=[], excludePlatformNames=[]):
"""Method that recovers the names of the <Platforms> in a given list.
:param platformNames: List of strings containing the possible platforms.
:param mode: The mode of the search. The following can be ... |
def getAllPlatformNamesByTag (mode = None):
"""Returns the platforms in the framework grouped by tags.
:param mode: The mode of the search. The following can be chosen: ["phonefy", "usufy", "searchfy"].
"""
tags = {}
allPlatformsList = getAllPlatformObjects(mode)
# Iterating the list of... |
def getAllPlatformObjects(mode = None):
"""Method that recovers ALL the list of <Platform> classes to be processed....
:param mode: The mode of the search. The following can be chosen: ["phonefy", "usufy", "searchfy"].
:return: Returns a list [] of <Platform> objects.
"""
listAll = ... |
def from_json(cls, json_str):
"""Deserialize the object from a JSON string."""
d = json.loads(json_str)
return cls.from_dict(d) |
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.
"""
candid... |
def verifyEmails(emails=[], regExpPattern="^.+$"):
"""
Method to perform the mail verification process.
Arguments
---------
emails: List of emails to verify.
regExpPattern: Pattern that should match.
Returns
-------
list: A list containing the results that match.
""... |
def main(params=None):
"""
Main function to launch phonefy.
The function is created in this way so as to let other applications make
use of the full configuration capabilities of the application. The
parameters received are used as parsed by this modules `getParser()`.
Args:
-----
... |
def generate_thumbnail_url(image_url, height, width, favicon_domain=None,
zoom_face=True, api_key=None):
"""Take an image URL and generate a thumbnail URL for that image.
Args:
image_url -- unicode (or utf8 encoded str), URL of the image you want to
th... |
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",
... |
def getCredentials():
'''
Recovering the credentials from a file with the following structure:
:return: A dictionary with the following struture:
{ "platform1": [C1<Credential>, C2<Credential>], "platform2": [C3<Credential>]}
'''
logger = logging.getLogger("osrframework... |
def check_mailfy(self, query, kwargs={}):
"""
Verifying a mailfy query in this platform.
This might be redefined in any class inheriting from Platform. The only
condition is that any of this should return a dictionary as defined.
Args:
-----
query: The eleme... |
def _enrich_link(self, glossary):
"""
Enrich the dict glossary['link'] with an identifier onto the model
"""
try:
Model = apps.get_model(*glossary['link']['model'].split('.'))
obj = Model.objects.get(pk=glossary['link']['pk'])
glossary['link'].update(i... |
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 = dic... |
def get_picture_elements(instance):
"""
Create a context, used to render a <picture> together with all its ``<source>`` elements:
It returns a list of HTML elements, each containing the information to render a ``<source>``
element.
The purpose of this HTML entity is to display images with art direct... |
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... |
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')
... |
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.ge... |
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... |
def get_form(self, request, obj=None, **kwargs):
"""
Build the form used for changing the model.
"""
widgets = kwargs.pop('widgets', {})
labels = kwargs.pop('labels', {})
glossary_fields = kwargs.pop('glossary_fields', self.glossary_fields)
widgets.update(glossary... |
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
... |
def get_previous_instance(self, obj):
"""
Return the previous plugin instance for the given object.
This differs from `obj.get_prev_sibling()` which returns an unsorted sibling.
"""
ordered_siblings = obj.get_siblings().filter(placeholder=obj.placeholder).order_by('position')
... |
def get_next_instance(self, obj):
"""
Return the next plugin instance for the given object.
This differs from `obj.get_next_sibling()` which returns an unsorted sibling.
"""
ordered_siblings = obj.get_siblings().filter(placeholder=obj.placeholder).order_by('position')
pos... |
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_m... |
def get_image_tags(instance):
"""
Create a context returning the tags to render an <img ...> element with
``sizes``, ``srcset``, a fallback ``src`` and if required inline styles.
"""
if hasattr(instance, 'image') and hasattr(instance.image, 'exif'):
aspect_ratio = compute_aspect_ratio(instan... |
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 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... |
def remove_duplicates(lst):
"""
Emulate what a Python ``set()`` does, but keeping the element's order.
"""
dset = set()
return [l for l in lst if l not in dset and not dset.add(l)] |
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.
... |
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 Valid... |
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.
No... |
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... |
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:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.