repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.or_where | python | def or_where(self, key, operator, value):
if len(self._queries) > 0:
self._current_query_index += 1
self.__store_query({"key": key, "operator": operator, "value": value})
return self | Make or_where clause
:@param key
:@param operator
:@param value
:@type key, operator, value: string
:@return self | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L190-L203 | [
"def __store_query(self, query_items):\n \"\"\"Make where clause\n\n :@param query_items\n :@type query_items: dict\n \"\"\"\n temp_index = self._current_query_index\n if len(self._queries) - 1 < temp_index:\n self._queries.append([])\n\n self._queries[temp_index].append(query_items)\n"
... | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.nth | python | def nth(self, index):
self.__prepare()
return None if self.count() < math.fabs(index) else self._json_data[index] | Getting the nth element of the collection
:@param index
:@type index: int
:@return object | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L321-L330 | [
"def __prepare(self):\n \"\"\"Prepare query result\"\"\"\n\n if len(self._queries) > 0:\n self.__execute_queries()\n self.__reset_queries()\n",
"def count(self):\n \"\"\"Getting the size of the collection\n\n :@return int\n \"\"\"\n self.__prepare()\n return len(self._json_data)... | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.sum | python | def sum(self, property):
self.__prepare()
total = 0
for i in self._json_data:
total += i.get(property)
return total | Getting the sum according to the given property
:@param property
:@type property: string
:@return int/float | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L332-L345 | [
"def __prepare(self):\n \"\"\"Prepare query result\"\"\"\n\n if len(self._queries) > 0:\n self.__execute_queries()\n self.__reset_queries()\n"
] | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.max | python | def max(self, property):
self.__prepare()
try:
return max(self._json_data, key=lambda x: x[property]).get(property)
except KeyError:
raise KeyError("Key is not exists") | Getting the maximum value from the prepared data
:@param property
:@type property: string
:@return object
:@throws KeyError | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L347-L360 | [
"def __prepare(self):\n \"\"\"Prepare query result\"\"\"\n\n if len(self._queries) > 0:\n self.__execute_queries()\n self.__reset_queries()\n"
] | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.avg | python | def avg(self, property):
self.__prepare()
return self.sum(property) / self.count() | Getting average according to given property
:@param property
:@type property: string
:@return average: int/float | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L377-L386 | [
"def __prepare(self):\n \"\"\"Prepare query result\"\"\"\n\n if len(self._queries) > 0:\n self.__execute_queries()\n self.__reset_queries()\n",
"def count(self):\n \"\"\"Getting the size of the collection\n\n :@return int\n \"\"\"\n self.__prepare()\n return len(self._json_data)... | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.chunk | python | def chunk(self, size=0):
if size == 0:
raise ValueError('Invalid chunk size')
self.__prepare()
_new_content = []
while(len(self._json_data) > 0):
_new_content.append(self._json_data[0:size])
self._json_data = self._json_data[size:]
self._js... | Group the resulted collection to multiple chunk
:@param size: 0
:@type size: integer
:@return Chunked List | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L388-L409 | [
"def __prepare(self):\n \"\"\"Prepare query result\"\"\"\n\n if len(self._queries) > 0:\n self.__execute_queries()\n self.__reset_queries()\n"
] | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.group_by | python | def group_by(self, property):
self.__prepare()
group_data = {}
for data in self._json_data:
if data[property] not in group_data:
group_data[data[property]] = []
group_data[data[property]].append(data)
self._json_data = group_data
return se... | Getting the grouped result by the given property
:@param property
:@type property: string
:@return self | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L411-L427 | [
"def __prepare(self):\n \"\"\"Prepare query result\"\"\"\n\n if len(self._queries) > 0:\n self.__execute_queries()\n self.__reset_queries()\n"
] | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.sort | python | def sort(self, order="asc"):
self.__prepare()
if isinstance(self._json_data, list):
if order == "asc":
self._json_data = sorted(self._json_data)
else:
self._json_data = sorted(self._json_data, reverse=True)
return self | Getting the sorted result of the given list
:@param order: "asc"
:@type order: string
:@return self | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L429-L444 | [
"def __prepare(self):\n \"\"\"Prepare query result\"\"\"\n\n if len(self._queries) > 0:\n self.__execute_queries()\n self.__reset_queries()\n"
] | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/query.py | JsonQ.sort_by | python | def sort_by(self, property, order="asc"):
self.__prepare()
if isinstance(self._json_data, list):
if order == "asc":
self._json_data = sorted(
self._json_data,
key=lambda x: x.get(property)
)
else:
... | Getting the sorted result by the given property
:@param property, order: "asc"
:@type property, order: string
:@return self | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/query.py#L446-L468 | [
"def __prepare(self):\n \"\"\"Prepare query result\"\"\"\n\n if len(self._queries) > 0:\n self.__execute_queries()\n self.__reset_queries()\n"
] | class JsonQ(object):
"""Query over Json file"""
def __init__(self, file_path="", data={}):
"""
:@param file_path: Set main json file path
:@type file_path: string
"""
if file_path != "":
self.from_file(file_path)
if data:
self.__parse_jso... |
s1s1ty/py-jsonq | pyjsonq/matcher.py | Matcher._match | python | def _match(self, x, op, y):
if (op not in self.condition_mapper):
raise ValueError('Invalid where condition given')
func = getattr(self, self.condition_mapper.get(op))
return func(x, y) | Compare the given `x` and `y` based on `op`
:@param x, y, op
:@type x, y: mixed
:@type op: string
:@return bool
:@throws ValueError | train | https://github.com/s1s1ty/py-jsonq/blob/9625597a2578bddcbed4e540174d5253b1fc3b75/pyjsonq/matcher.py#L162-L176 | null | class Matcher(object):
"""docstring for Helper."""
def __init__(self):
self.condition_mapper = {
'=': '_is_equal',
'eq': '_is_equal',
'!=': '_is_not_equal',
'neq': '_is_not_equal',
'>': '_is_greater',
'gt': '_is_greater',
... |
jgorset/fandjango | fandjango/decorators.py | facebook_authorization_required | python | def facebook_authorization_required(redirect_uri=FACEBOOK_AUTHORIZATION_REDIRECT_URL, permissions=None):
def decorator(function):
@wraps(function)
def wrapper(request, *args, **kwargs):
# We know the user has been authenticated via a canvas page if a signed request is set.
... | Require the user to authorize the application.
:param redirect_uri: A string describing an URL to redirect to after authorization is complete.
If ``None``, redirects to the current URL in the Facebook canvas
(e.g. ``http://apps.facebook.com/myapp/current/path``). D... | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/decorators.py#L14-L65 | [
"def decorator(function):\n @wraps(function)\n def wrapper(request, *args, **kwargs):\n\n # We know the user has been authenticated via a canvas page if a signed request is set.\n canvas = request.facebook is not False and hasattr(request.facebook, \"signed_request\")\n\n # The user has a... | from functools import wraps
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.core.handlers.wsgi import WSGIRequest
from fandjango.utils import get_post_authorization_redirect_url
from fandjango.views import authorize_application
from fandjango.settings import FACEBOOK_APPL... |
jgorset/fandjango | fandjango/models.py | User.full_name | python | def full_name(self):
if self.first_name and self.middle_name and self.last_name:
return "%s %s %s" % (self.first_name, self.middle_name, self.last_name)
if self.first_name and self.last_name:
return "%s %s" % (self.first_name, self.last_name) | Return the user's first name. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L86-L91 | null | class User(models.Model):
"""
Instances of the User class represent Facebook users who
have authorized the application.
"""
facebook_id = models.BigIntegerField(_('facebook id'), unique=True)
"""An integer describing the user's Facebook ID."""
facebook_username = models.CharField(_('facebo... |
jgorset/fandjango | fandjango/models.py | User.permissions | python | def permissions(self):
records = self.graph.get('me/permissions')['data']
permissions = []
for record in records:
if record['status'] == 'granted':
permissions.append(record['permission'])
return permissions | A list of strings describing `permissions`_ the user has granted your application.
.. _permissions: http://developers.facebook.com/docs/reference/api/permissions/ | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L102-L115 | null | class User(models.Model):
"""
Instances of the User class represent Facebook users who
have authorized the application.
"""
facebook_id = models.BigIntegerField(_('facebook id'), unique=True)
"""An integer describing the user's Facebook ID."""
facebook_username = models.CharField(_('facebo... |
jgorset/fandjango | fandjango/models.py | User.synchronize | python | def synchronize(self, graph_data=None):
profile = graph_data or self.graph.get('me')
self.facebook_username = profile.get('username')
self.first_name = profile.get('first_name')
self.middle_name = profile.get('middle_name')
self.last_name = profile.get('last_name')
self.... | Synchronize ``facebook_username``, ``first_name``, ``middle_name``,
``last_name`` and ``birthday`` with Facebook.
:param graph_data: Optional pre-fetched graph data | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L126-L144 | null | class User(models.Model):
"""
Instances of the User class represent Facebook users who
have authorized the application.
"""
facebook_id = models.BigIntegerField(_('facebook id'), unique=True)
"""An integer describing the user's Facebook ID."""
facebook_username = models.CharField(_('facebo... |
jgorset/fandjango | fandjango/models.py | OAuthToken.extended | python | def extended(self):
if self.expires_at:
return self.expires_at - self.issued_at > timedelta(days=30)
else:
return False | Determine whether the OAuth token has been extended. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L179-L184 | null | class OAuthToken(models.Model):
"""
Instances of the OAuthToken class are credentials used to query
the Facebook API on behalf of a user.
"""
token = models.TextField(_('token'))
"""A string describing the OAuth token itself."""
issued_at = models.DateTimeField(_('issued at'))
"""A ``d... |
jgorset/fandjango | fandjango/models.py | OAuthToken.extend | python | def extend(self):
graph = GraphAPI()
response = graph.get('oauth/access_token',
client_id = FACEBOOK_APPLICATION_ID,
client_secret = FACEBOOK_APPLICATION_SECRET_KEY,
grant_type = 'fb_exchange_token',
fb_exchange_token = self.token
)
compo... | Extend the OAuth token. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/models.py#L186-L202 | [
"def now():\n return datetime.now()\n"
] | class OAuthToken(models.Model):
"""
Instances of the OAuthToken class are credentials used to query
the Facebook API on behalf of a user.
"""
token = models.TextField(_('token'))
"""A string describing the OAuth token itself."""
issued_at = models.DateTimeField(_('issued at'))
"""A ``d... |
jgorset/fandjango | fandjango/middleware.py | FacebookMiddleware.process_request | python | def process_request(self, request):
# User has already been authed by alternate middleware
if hasattr(request, "facebook") and request.facebook:
return
request.facebook = False
if not self.is_valid_path(request):
return
if self.is_access_denied(request... | Process the signed request. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L53-L141 | [
"def is_valid_path(self, request):\n if ENABLED_PATHS and DISABLED_PATHS:\n raise ImproperlyConfigured(\n 'You may configure either FANDJANGO_ENABLED_PATHS '\n 'or FANDJANGO_DISABLED_PATHS, but not both.'\n )\n\n if DISABLED_PATHS and is_disabled_path(request.path):\n ... | class FacebookMiddleware(BaseMiddleware):
"""Middleware for Facebook canvas applications."""
def process_response(self, request, response):
"""
Set compact P3P policies and save signed request to cookie.
P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignor... |
jgorset/fandjango | fandjango/middleware.py | FacebookMiddleware.process_response | python | def process_response(self, request, response):
response['P3P'] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"'
if FANDJANGO_CACHE_SIGNED_REQUEST:
if hasattr(request, "facebook") and request.facebook and request.facebook.signed_request:
response.set_cookie('signed_request', re... | Set compact P3P policies and save signed request to cookie.
P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most
browsers it is considered by IE before accepting third-party cookies (ie. cookies set by
documents in iframes). If they are not set correctly, ... | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L143-L159 | null | class FacebookMiddleware(BaseMiddleware):
"""Middleware for Facebook canvas applications."""
def process_request(self, request):
"""Process the signed request."""
# User has already been authed by alternate middleware
if hasattr(request, "facebook") and request.facebook:
re... |
jgorset/fandjango | fandjango/middleware.py | FacebookWebMiddleware.process_request | python | def process_request(self, request):
# User has already been authed by alternate middleware
if hasattr(request, "facebook") and request.facebook:
return
request.facebook = False
if not self.is_valid_path(request):
return
if self.is_access_denied(request... | Process the web-based auth request. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L164-L274 | [
"def is_valid_path(self, request):\n if ENABLED_PATHS and DISABLED_PATHS:\n raise ImproperlyConfigured(\n 'You may configure either FANDJANGO_ENABLED_PATHS '\n 'or FANDJANGO_DISABLED_PATHS, but not both.'\n )\n\n if DISABLED_PATHS and is_disabled_path(request.path):\n ... | class FacebookWebMiddleware(BaseMiddleware):
"""Middleware for Facebook auth on websites."""
def process_request(self, request):
"""Process the web-based auth request."""
# User has already been authed by alternate middleware
if hasattr(request, "facebook") and request.facebook:
... |
jgorset/fandjango | fandjango/middleware.py | FacebookWebMiddleware.process_response | python | def process_response(self, request, response):
if hasattr(request, "facebook") and request.facebook and request.facebook.oauth_token:
if "code" in request.REQUEST:
""" Remove auth related query params """
path = get_full_path(request, remove_querystrings=['code', 'web... | Set compact P3P policies and save auth token to cookie.
P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most
browsers it is considered by IE before accepting third-party cookies (ie. cookies set by
documents in iframes). If they are not set correctly, IE w... | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/middleware.py#L277-L297 | [
"def get_full_path(request, remove_querystrings=[]):\n \"\"\"Gets the current path, removing specified querstrings\"\"\"\n\n path = request.get_full_path()\n for qs in remove_querystrings:\n path = re.sub(r'&?' + qs + '=?(.+)?&?', '', path)\n return path\n"
] | class FacebookWebMiddleware(BaseMiddleware):
"""Middleware for Facebook auth on websites."""
def process_request(self, request):
"""Process the web-based auth request."""
# User has already been authed by alternate middleware
if hasattr(request, "facebook") and request.facebook:
... |
jgorset/fandjango | fandjango/utils.py | is_disabled_path | python | def is_disabled_path(path):
for disabled_path in DISABLED_PATHS:
match = re.search(disabled_path, path[1:])
if match:
return True
return False | Determine whether or not the path matches one or more paths
in the DISABLED_PATHS setting.
:param path: A string describing the path to be matched. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L17-L28 | null | import re
from datetime import timedelta
from urlparse import urlparse
from functools import wraps
from django.core.cache import cache
from django.utils.importlib import import_module
from fandjango.settings import FACEBOOK_APPLICATION_CANVAS_URL
from fandjango.settings import FACEBOOK_APPLICATION_DOMAIN
from fandjan... |
jgorset/fandjango | fandjango/utils.py | is_enabled_path | python | def is_enabled_path(path):
for enabled_path in ENABLED_PATHS:
match = re.search(enabled_path, path[1:])
if match:
return True
return False | Determine whether or not the path matches one or more paths
in the ENABLED_PATHS setting.
:param path: A string describing the path to be matched. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L30-L41 | null | import re
from datetime import timedelta
from urlparse import urlparse
from functools import wraps
from django.core.cache import cache
from django.utils.importlib import import_module
from fandjango.settings import FACEBOOK_APPLICATION_CANVAS_URL
from fandjango.settings import FACEBOOK_APPLICATION_DOMAIN
from fandjan... |
jgorset/fandjango | fandjango/utils.py | cached_property | python | def cached_property(**kwargs):
def decorator(function):
@wraps(function)
def wrapper(self):
key = 'fandjango.%(model)s.%(property)s_%(pk)s' % {
'model': self.__class__.__name__,
'pk': self.pk,
'property': function.__name__
}
... | Cache the return value of a property. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L43-L66 | null | import re
from datetime import timedelta
from urlparse import urlparse
from functools import wraps
from django.core.cache import cache
from django.utils.importlib import import_module
from fandjango.settings import FACEBOOK_APPLICATION_CANVAS_URL
from fandjango.settings import FACEBOOK_APPLICATION_DOMAIN
from fandjan... |
jgorset/fandjango | fandjango/utils.py | authorization_denied_view | python | def authorization_denied_view(request):
authorization_denied_module_name = AUTHORIZATION_DENIED_VIEW.rsplit('.', 1)[0]
authorization_denied_view_name = AUTHORIZATION_DENIED_VIEW.split('.')[-1]
authorization_denied_module = import_module(authorization_denied_module_name)
authorization_denied_view = geta... | Proxy for the view referenced in ``FANDJANGO_AUTHORIZATION_DENIED_VIEW``. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L68-L76 | null | import re
from datetime import timedelta
from urlparse import urlparse
from functools import wraps
from django.core.cache import cache
from django.utils.importlib import import_module
from fandjango.settings import FACEBOOK_APPLICATION_CANVAS_URL
from fandjango.settings import FACEBOOK_APPLICATION_DOMAIN
from fandjan... |
jgorset/fandjango | fandjango/utils.py | get_post_authorization_redirect_url | python | def get_post_authorization_redirect_url(request, canvas=True):
path = request.get_full_path()
if canvas:
if FACEBOOK_APPLICATION_CANVAS_URL:
path = path.replace(urlparse(FACEBOOK_APPLICATION_CANVAS_URL).path, '')
redirect_uri = 'https://%(domain)s/%(namespace)s%(path)s' % {
... | Determine the URL users should be redirected to upon authorization the application.
If request is non-canvas use user defined site url if set, else the site hostname. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L78-L105 | null | import re
from datetime import timedelta
from urlparse import urlparse
from functools import wraps
from django.core.cache import cache
from django.utils.importlib import import_module
from fandjango.settings import FACEBOOK_APPLICATION_CANVAS_URL
from fandjango.settings import FACEBOOK_APPLICATION_DOMAIN
from fandjan... |
jgorset/fandjango | fandjango/utils.py | get_full_path | python | def get_full_path(request, remove_querystrings=[]):
path = request.get_full_path()
for qs in remove_querystrings:
path = re.sub(r'&?' + qs + '=?(.+)?&?', '', path)
return path | Gets the current path, removing specified querstrings | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/utils.py#L107-L113 | null | import re
from datetime import timedelta
from urlparse import urlparse
from functools import wraps
from django.core.cache import cache
from django.utils.importlib import import_module
from fandjango.settings import FACEBOOK_APPLICATION_CANVAS_URL
from fandjango.settings import FACEBOOK_APPLICATION_DOMAIN
from fandjan... |
jgorset/fandjango | fandjango/views.py | authorize_application | python | def authorize_application(
request,
redirect_uri = 'https://%s/%s' % (FACEBOOK_APPLICATION_DOMAIN, FACEBOOK_APPLICATION_NAMESPACE),
permissions = FACEBOOK_APPLICATION_INITIAL_PERMISSIONS
):
query = {
'client_id': FACEBOOK_APPLICATION_ID,
'redirect_uri': redirect_uri
}
if per... | Redirect the user to authorize the application.
Redirection is done by rendering a JavaScript snippet that redirects the parent
window to the authorization URI, since Facebook will not allow this inside an iframe. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/views.py#L15-L41 | null | from urllib import urlencode
from django.http import HttpResponse
from django.shortcuts import render
from facepy import SignedRequest
from fandjango.models import User
from fandjango.settings import (
FACEBOOK_APPLICATION_ID, FACEBOOK_APPLICATION_DOMAIN,
FACEBOOK_APPLICATION_NAMESPACE, FACEBOOK_APPLICATION_... |
jgorset/fandjango | fandjango/views.py | deauthorize_application | python | def deauthorize_application(request):
if request.facebook:
user = User.objects.get(
facebook_id = request.facebook.signed_request.user.id
)
user.authorized = False
user.save()
return HttpResponse()
else:
return HttpResponse(status=400) | When a user deauthorizes an application, Facebook sends a HTTP POST request to the application's
"deauthorization callback" URL. This view picks up on requests of this sort and marks the corresponding
users as unauthorized. | train | https://github.com/jgorset/fandjango/blob/01334a76c1d9f0629842aa6830678ae097756551/fandjango/views.py#L53-L69 | null | from urllib import urlencode
from django.http import HttpResponse
from django.shortcuts import render
from facepy import SignedRequest
from fandjango.models import User
from fandjango.settings import (
FACEBOOK_APPLICATION_ID, FACEBOOK_APPLICATION_DOMAIN,
FACEBOOK_APPLICATION_NAMESPACE, FACEBOOK_APPLICATION_... |
walkr/oi | oi/core.py | BaseProgram.new_parser | python | def new_parser(self):
parser = argparse.ArgumentParser(description=self.description)
parser.add_argument(
'--version', help='show version and exit',
default=False, action='store_true')
parser.add_argument(
'--debug', help='enable debugging',
defau... | Create a command line argument parser
Add a few default flags, such as --version
for displaying the program version when invoked | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L48-L61 | null | class BaseProgram(object):
""" Subclass this """
def __init__(self, description, address=None, state=None, workers=None):
self.description = description
self.address = address
self.parser = self.new_parser()
self.state = state or State()
self.workers = workers or []
... |
walkr/oi | oi/core.py | BaseProgram.add_command | python | def add_command(self, command, function, description=None):
self.registered[command] = {
'function': function, 'description': description
} | Register a new function with a the name `command` and
`description` (which will be shown then help is invoked). | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L63-L69 | null | class BaseProgram(object):
""" Subclass this """
def __init__(self, description, address=None, state=None, workers=None):
self.description = description
self.address = address
self.parser = self.new_parser()
self.state = state or State()
self.workers = workers or []
... |
walkr/oi | oi/core.py | BaseProgram.run | python | def run(self, args=None):
args = args or self.parser.parse_args()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
if args.version:
print(version.VERSION)
sys.exit(0) | Parse command line arguments if necessary then run program.
By default this method will just take of the --version flag.
The logic for other flags should be handled by your subclass | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L71-L84 | null | class BaseProgram(object):
""" Subclass this """
def __init__(self, description, address=None, state=None, workers=None):
self.description = description
self.address = address
self.parser = self.new_parser()
self.state = state or State()
self.workers = workers or []
... |
walkr/oi | oi/core.py | Program.help_function | python | def help_function(self, command=None):
if command:
return self.registered[command].get(
'description', 'No help available'
)
return ', '.join(sorted(self.registered)) | Show help for all available commands or just a single one | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L115-L121 | null | class Program(BaseProgram):
""" Long running program with a nanoservice endpoint.
`service` - nanoservice Service object
`config` - the configuration parsed from --config <filepath> """
def __init__(self, description, address):
super(Program, self).__init__(description, address)
self.... |
walkr/oi | oi/core.py | Program.add_command | python | def add_command(self, command, function, description=None):
super(Program, self).add_command(command, function, description)
self.service.register(command, function) | Register a new function for command | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L123-L126 | [
"def add_command(self, command, function, description=None):\n \"\"\" Register a new function with a the name `command` and\n `description` (which will be shown then help is invoked). \"\"\"\n\n self.registered[command] = {\n 'function': function, 'description': description\n }\n"
] | class Program(BaseProgram):
""" Long running program with a nanoservice endpoint.
`service` - nanoservice Service object
`config` - the configuration parsed from --config <filepath> """
def __init__(self, description, address):
super(Program, self).__init__(description, address)
self.... |
walkr/oi | oi/core.py | Program.run | python | def run(self, args=None):
args = args or self.parser.parse_args()
super(Program, self).run(args)
# Read configuration file if any
if args.config is not None:
filepath = args.config
self.config.read(filepath)
# Start workers then wait until they finish w... | Parse comand line arguments/flags and run program | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L128-L141 | [
"def run(self, args=None):\n \"\"\" Parse command line arguments if necessary then run program.\n By default this method will just take of the --version flag.\n\n The logic for other flags should be handled by your subclass \"\"\"\n\n args = args or self.parser.parse_args()\n\n if args.debug:\n ... | class Program(BaseProgram):
""" Long running program with a nanoservice endpoint.
`service` - nanoservice Service object
`config` - the configuration parsed from --config <filepath> """
def __init__(self, description, address):
super(Program, self).__init__(description, address)
self.... |
walkr/oi | oi/core.py | ClientWrapper.create_client | python | def create_client(self, addr, timeout):
def make(addr):
c = Client(addr)
c.socket._set_recv_timeout(timeout)
return c
if ',' in addr:
addrs = addr.split(',')
addrs = [a.strip() for a in addrs]
return {a: make(a) for a in addrs}
... | Create client(s) based on addr | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L151-L163 | [
"def make(addr):\n c = Client(addr)\n c.socket._set_recv_timeout(timeout)\n return c\n"
] | class ClientWrapper(object):
""" An wrapper over nanoservice.Client to deal with one or multiple
clients in a similar fasion """
def __init__(self, address, timeout):
self.c = self.create_client(address, timeout)
def _call_single(self, client, command, *args):
""" Call single """
... |
walkr/oi | oi/core.py | ClientWrapper._call_single | python | def _call_single(self, client, command, *args):
try:
return client.call(command, *args)
except Exception as e:
return None, str(e) | Call single | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L165-L170 | null | class ClientWrapper(object):
""" An wrapper over nanoservice.Client to deal with one or multiple
clients in a similar fasion """
def __init__(self, address, timeout):
self.c = self.create_client(address, timeout)
def create_client(self, addr, timeout):
""" Create client(s) based on add... |
walkr/oi | oi/core.py | ClientWrapper._call_multi | python | def _call_multi(self, clients, command, *args):
responses, errors = {}, {}
for addr, client in clients.items():
res, err = self._call_single(client, command, *args)
responses[addr] = res
errors[addr] = err
return responses, errors | Call multi | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L172-L179 | [
"def _call_single(self, client, command, *args):\n \"\"\" Call single \"\"\"\n try:\n return client.call(command, *args)\n except Exception as e:\n return None, str(e)\n"
] | class ClientWrapper(object):
""" An wrapper over nanoservice.Client to deal with one or multiple
clients in a similar fasion """
def __init__(self, address, timeout):
self.c = self.create_client(address, timeout)
def create_client(self, addr, timeout):
""" Create client(s) based on add... |
walkr/oi | oi/core.py | ClientWrapper.call | python | def call(self, command, *args):
if isinstance(self.c, dict):
return self._call_multi(self.c, command, *args)
return self._call_single(self.c, command, *args) | Call remote service(s) | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L181-L185 | [
"def _call_single(self, client, command, *args):\n \"\"\" Call single \"\"\"\n try:\n return client.call(command, *args)\n except Exception as e:\n return None, str(e)\n",
"def _call_multi(self, clients, command, *args):\n \"\"\" Call multi \"\"\"\n responses, errors = {}, {}\n for... | class ClientWrapper(object):
""" An wrapper over nanoservice.Client to deal with one or multiple
clients in a similar fasion """
def __init__(self, address, timeout):
self.c = self.create_client(address, timeout)
def create_client(self, addr, timeout):
""" Create client(s) based on add... |
walkr/oi | oi/core.py | ClientWrapper.close | python | def close(self):
if isinstance(self.c, dict):
for client in self.c.values():
client.sock.close()
return
self.c.socket.close() | Close socket(s) | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L191-L197 | null | class ClientWrapper(object):
""" An wrapper over nanoservice.Client to deal with one or multiple
clients in a similar fasion """
def __init__(self, address, timeout):
self.c = self.create_client(address, timeout)
def create_client(self, addr, timeout):
""" Create client(s) based on add... |
walkr/oi | oi/core.py | Response._show | python | def _show(self, res, err, prefix='', colored=False):
if self.kind is 'local':
what = res if not err else err
print(what)
return
if self.kind is 'remote':
if colored:
red, green, reset = Fore.RED, Fore.GREEN, Fore.RESET
else:
... | Show result or error | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L210-L227 | null | class Response(object):
""" A local or remote response for a command """
def __init__(self, kind, res, err, multi=False):
super(Response, self).__init__()
self.kind = kind
self.res = res
self.err = err
self.multi = multi
def show(self):
if self.multi:
... |
walkr/oi | oi/core.py | CtlProgram.call | python | def call(self, command, *args):
if not command:
return
# Look for local methods first
try:
res = self.registered[command]['function'](self, *args)
return Response('local', res, None)
# Method not found, try remote
except KeyError:
... | Execute local OR remote command and show response | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L267-L287 | null | class CtlProgram(BaseProgram):
""" The Ctl program
Note:
When a CtlProgram accepts a command it will make a request
to the remote service with that command and any args extracted.
When we add commands via `add_command` method, then those
commands will be executed by our regist... |
walkr/oi | oi/core.py | CtlProgram.parse_input | python | def parse_input(self, text):
parts = util.split(text)
command = parts[0] if text and parts else None
command = command.lower() if command else None
args = parts[1:] if len(parts) > 1 else []
return (command, args) | Parse ctl user input. Double quotes are used
to group together multi words arguments. | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L289-L298 | null | class CtlProgram(BaseProgram):
""" The Ctl program
Note:
When a CtlProgram accepts a command it will make a request
to the remote service with that command and any args extracted.
When we add commands via `add_command` method, then those
commands will be executed by our regist... |
walkr/oi | oi/core.py | CtlProgram.loop | python | def loop(self):
while True:
text = compat.input('ctl > ')
command, args = self.parse_input(text)
if not command:
continue
response = self.call(command, *args)
response.show() | Enter loop, read user input then run command. Repeat | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/core.py#L300-L309 | [
"def show(self):\n if self.multi:\n for addr in self.res:\n self._show(\n self.res[addr], self.err[addr],\n prefix='- {}: '.format(addr), colored=True\n )\n return\n self._show(self.res, self.err)\n",
"def call(self, command, *args):\n \"\... | class CtlProgram(BaseProgram):
""" The Ctl program
Note:
When a CtlProgram accepts a command it will make a request
to the remote service with that command and any args extracted.
When we add commands via `add_command` method, then those
commands will be executed by our regist... |
walkr/oi | oi/util.py | split | python | def split(text):
# Cleanup text
text = text.strip()
text = re.sub('\s+', ' ', text) # collpse multiple spaces
space, quote, parts = ' ', '"', []
part, quoted = '', False
for char in text:
# Encoutered beginning double quote
if char is quote and quoted is False:
q... | Split text into arguments accounting for muti-word arguments
which are double quoted | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/oi/util.py#L6-L51 | null | # Utility functions that didn't fit anywhere else
import re
|
walkr/oi | setup.py | read_long_description | python | def read_long_description(readme_file):
try:
import pypandoc
except (ImportError, OSError) as e:
print('No pypandoc or pandoc: %s' % (e,))
if is_py3:
fh = open(readme_file, encoding='utf-8')
else:
fh = open(readme_file)
long_description = fh.read()... | Read package long description from README file | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/setup.py#L17-L31 | null | #!/usr/bin/env python
import sys
try:
import setuptools
from setuptools import setup
except ImportError:
setuptools = None
from distutils.core import setup
is_py3 = sys.version_info.major == 3
readme_file = 'README.md'
def read_version():
""" Read package version """
with open('./oi/versi... |
walkr/oi | setup.py | read_version | python | def read_version():
with open('./oi/version.py') as fh:
for line in fh:
if line.startswith('VERSION'):
return line.split('=')[1].strip().strip("'") | Read package version | train | https://github.com/walkr/oi/blob/d9d8491d0bc920e493d8f716d6078762b8b2c6d3/setup.py#L34-L39 | null | #!/usr/bin/env python
import sys
try:
import setuptools
from setuptools import setup
except ImportError:
setuptools = None
from distutils.core import setup
is_py3 = sys.version_info.major == 3
readme_file = 'README.md'
def read_long_description(readme_file):
""" Read package long description f... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | Engine.repositories | python | def repositories(self):
return RepositoriesDataFrame(self.__engine.getRepositories(),
self.session, self.__implicits) | Returns a DataFrame with the data about the repositories found at
the specified repositories path in the form of siva files.
>>> repos_df = engine.repositories
:rtype: RepositoriesDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L57-L67 | null | class Engine(object):
"""
This is the entry point to any functionality exposed by the source{d}
Engine. It contains methods to initialize the analysis on top of source
code repositories.
>>> from sourced.engine import Engine
>>> repos_df = Engine(sparkSession, "/path/to/my/repositories").reposi... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | Engine.blobs | python | def blobs(self, repository_ids=[], reference_names=[], commit_hashes=[]):
if not isinstance(repository_ids, list):
raise Exception("repository_ids must be a list")
if not isinstance(reference_names, list):
raise Exception("reference_names must be a list")
if not isinsta... | Retrieves the blobs of a list of repositories, reference names and commit hashes.
So the result will be a DataFrame of all the blobs in the given commits that are
in the given references that belong to the given repositories.
>>> blobs_df = engine.blobs(repo_ids, ref_names, hashes)
Cal... | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L70-L103 | null | class Engine(object):
"""
This is the entry point to any functionality exposed by the source{d}
Engine. It contains methods to initialize the analysis on top of source
code repositories.
>>> from sourced.engine import Engine
>>> repos_df = Engine(sparkSession, "/path/to/my/repositories").reposi... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | Engine.from_metadata | python | def from_metadata(self, db_path, db_name='engine_metadata.db'):
self.__engine.fromMetadata(db_path, db_name)
return self | Registers in the current session the views of the MetadataSource so the
data is obtained from the metadata database instead of reading the
repositories with the DefaultSource.
:param db_path: path to the folder that contains the database.
:type db_path: str
:param db_name: name ... | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L106-L121 | null | class Engine(object):
"""
This is the entry point to any functionality exposed by the source{d}
Engine. It contains methods to initialize the analysis on top of source
code repositories.
>>> from sourced.engine import Engine
>>> repos_df = Engine(sparkSession, "/path/to/my/repositories").reposi... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | SourcedDataFrame.__generate_method | python | def __generate_method(name):
try:
func = getattr(DataFrame, name)
except AttributeError as e:
# PySpark version is too old
def func(self, *args, **kwargs):
raise e
return func
wraps = getattr(functools, "wraps", lambda _: lambda f: ... | Wraps the DataFrame's original method by name to return the derived class instance. | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L176-L198 | null | class SourcedDataFrame(DataFrame):
"""
Custom source{d} Engine DataFrame that contains some DataFrame overriden methods and
utilities. This class should not be used directly, please get your SourcedDataFrames
using the provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.Ja... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | RepositoriesDataFrame.references | python | def references(self):
return ReferencesDataFrame(self._engine_dataframe.getReferences(),
self._session, self._implicits) | Returns the joined DataFrame of references and repositories.
>>> refs_df = repos_df.references
:rtype: ReferencesDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L261-L270 | null | class RepositoriesDataFrame(SourcedDataFrame):
"""
DataFrame containing repositories.
This class should not be instantiated directly, please get your RepositoriesDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Se... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | RepositoriesDataFrame.remote_references | python | def remote_references(self):
return ReferencesDataFrame(self._engine_dataframe.getRemoteReferences(),
self._session, self._implicits) | Returns a new DataFrame with only the remote references of the
current repositories.
>>> remote_refs_df = repos_df.remote_references
:rtype: ReferencesDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L274-L284 | null | class RepositoriesDataFrame(SourcedDataFrame):
"""
DataFrame containing repositories.
This class should not be instantiated directly, please get your RepositoriesDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Se... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | RepositoriesDataFrame.master_ref | python | def master_ref(self):
return ReferencesDataFrame(self._engine_dataframe.getReferences().getHEAD(),
self._session, self._implicits) | Filters the current DataFrame references to only contain those rows whose reference is master.
>>> master_df = repos_df.master_ref
:rtype: ReferencesDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L301-L310 | null | class RepositoriesDataFrame(SourcedDataFrame):
"""
DataFrame containing repositories.
This class should not be instantiated directly, please get your RepositoriesDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Se... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | ReferencesDataFrame.head_ref | python | def head_ref(self):
return ReferencesDataFrame(self._engine_dataframe.getHEAD(),
self._session, self._implicits) | Filters the current DataFrame to only contain those rows whose reference is HEAD.
>>> heads_df = refs_df.head_ref
:rtype: ReferencesDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L346-L355 | null | class ReferencesDataFrame(SourcedDataFrame):
"""
DataFrame with references.
This class should not be instantiated directly, please get your ReferencesDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | ReferencesDataFrame.master_ref | python | def master_ref(self):
return ReferencesDataFrame(self._engine_dataframe.getMaster(),
self._session, self._implicits)
return self.ref('refs/heads/master') | Filters the current DataFrame to only contain those rows whose reference is master.
>>> master_df = refs_df.master_ref
:rtype: ReferencesDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L359-L369 | null | class ReferencesDataFrame(SourcedDataFrame):
"""
DataFrame with references.
This class should not be instantiated directly, please get your ReferencesDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | ReferencesDataFrame.ref | python | def ref(self, ref):
return ReferencesDataFrame(self.filter(self.name == ref)._jdf,
self._session, self._implicits) | Filters the current DataFrame to only contain those rows whose reference is the given
reference name.
>>> heads_df = refs_df.ref('refs/heads/HEAD')
:param ref: Reference to get
:type ref: str
:rtype: ReferencesDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L372-L384 | null | class ReferencesDataFrame(SourcedDataFrame):
"""
DataFrame with references.
This class should not be instantiated directly, please get your ReferencesDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | ReferencesDataFrame.all_reference_commits | python | def all_reference_commits(self):
return CommitsDataFrame(self._engine_dataframe.getAllReferenceCommits(), self._session, self._implicits) | Returns the current DataFrame joined with the commits DataFrame, with all of the commits
in all references.
>>> commits_df = refs_df.all_reference_commits
Take into account that getting all the commits will lead to a lot of repeated tree
entries and blobs, thus making your query very s... | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L388-L404 | null | class ReferencesDataFrame(SourcedDataFrame):
"""
DataFrame with references.
This class should not be instantiated directly, please get your ReferencesDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | ReferencesDataFrame.commits | python | def commits(self):
return CommitsDataFrame(self._engine_dataframe.getCommits(), self._session, self._implicits) | Returns the current DataFrame joined with the commits DataFrame. It just returns
the last commit in a reference (aka the current state).
>>> commits_df = refs_df.commits
If you want all commits from the references, use the `all_reference_commits` method,
but take into account that gett... | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L408-L423 | null | class ReferencesDataFrame(SourcedDataFrame):
"""
DataFrame with references.
This class should not be instantiated directly, please get your ReferencesDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | ReferencesDataFrame.blobs | python | def blobs(self):
return BlobsDataFrame(self._engine_dataframe.getBlobs(), self._session, self._implicits) | Returns this DataFrame joined with the blobs DataSource.
>>> blobs_df = refs_df.blobs
:rtype: BlobsDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L427-L435 | null | class ReferencesDataFrame(SourcedDataFrame):
"""
DataFrame with references.
This class should not be instantiated directly, please get your ReferencesDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | CommitsDataFrame.tree_entries | python | def tree_entries(self):
return TreeEntriesDataFrame(self._engine_dataframe.getTreeEntries(), self._session, self._implicits) | Returns this DataFrame joined with the tree entries DataSource.
>>> entries_df = commits_df.tree_entries
:rtype: TreeEntriesDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L476-L484 | null | class CommitsDataFrame(SourcedDataFrame):
"""
DataFrame with commits data.
This class should not be instantiated directly, please get your CommitsDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use
... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | BlobsDataFrame.classify_languages | python | def classify_languages(self):
return BlobsWithLanguageDataFrame(self._engine_dataframe.classifyLanguages(),
self._session, self._implicits) | Returns a new DataFrame with the language data of any blob added to
its row.
>>> blobs_lang_df = blobs_df.classify_languages
:rtype: BlobsWithLanguageDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L549-L559 | null | class BlobsDataFrame(SourcedDataFrame):
"""
DataFrame containing blobs data.
This class should not be instantiated directly, please get your BlobsDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use
... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | BlobsDataFrame.extract_uasts | python | def extract_uasts(self):
return UASTsDataFrame(self._engine_dataframe.extractUASTs(),
self._session, self._implicits) | Returns a new DataFrame with the parsed UAST data of any blob added to
its row.
>>> blobs_df.extract_uasts
:rtype: UASTsDataFrame | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L562-L572 | null | class BlobsDataFrame(SourcedDataFrame):
"""
DataFrame containing blobs data.
This class should not be instantiated directly, please get your BlobsDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use
... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | UASTsDataFrame.query_uast | python | def query_uast(self, query, query_col='uast', output_col='result'):
return UASTsDataFrame(self._engine_dataframe.queryUAST(query,
query_col,
output_col),
self._session, self._implicits) | Queries the UAST of a file with the given query to get specific nodes.
>>> rows = uasts_df.query_uast('//*[@roleIdentifier]').collect()
>>> rows = uasts_df.query_uast('//*[@roleIdentifier]', 'foo', 'bar')
:param query: xpath query
:type query: str
:param query_col: column conta... | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L624-L642 | null | class UASTsDataFrame(SourcedDataFrame):
"""
DataFrame containing UAST data.
This class should not be instantiated directly, please get your UASTsDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use
... |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | UASTsDataFrame.extract_tokens | python | def extract_tokens(self, input_col='result', output_col='tokens'):
return UASTsDataFrame(self._engine_dataframe.extractTokens(input_col, output_col),
self._session, self._implicits) | Extracts the tokens from UAST nodes.
>>> rows = uasts_df.query_uast('//*[@roleIdentifier]').extract_tokens().collect()
>>> rows = uasts_df.query_uast('//*[@roleIdentifier]', output_col='foo').extract_tokens('foo', 'bar')
:param input_col: column containing the list of nodes to extract tokens f... | train | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L645-L659 | null | class UASTsDataFrame(SourcedDataFrame):
"""
DataFrame containing UAST data.
This class should not be instantiated directly, please get your UASTsDataFrame using the
provided methods.
:param jdf: Java DataFrame
:type jdf: py4j.java_gateway.JavaObject
:param session: Spark Session to use
... |
acsone/git-aggregator | git_aggregator/repo.py | Repo.init_git_version | python | def init_git_version(cls, v_str):
r"""Parse git version string and store the resulting tuple on self.
:returns: the parsed version tuple
Only the first 3 digits are kept. This is good enough for the few
version dependent cases we need, and coarse enough to avoid
more complicated ... | r"""Parse git version string and store the resulting tuple on self.
:returns: the parsed version tuple
Only the first 3 digits are kept. This is good enough for the few
version dependent cases we need, and coarse enough to avoid
more complicated parsing.
Some real-life examples::... | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L85-L132 | null | class Repo(object):
_git_version = None
def __init__(self, cwd, remotes, merges, target,
shell_command_after=None, fetch_all=False, defaults=None,
force=False):
"""Initialize a git repository aggregator
:param cwd: path to the directory where to initialize th... |
acsone/git-aggregator | git_aggregator/repo.py | Repo.query_remote_ref | python | def query_remote_ref(self, remote, ref):
out = self.log_call(['git', 'ls-remote', remote, ref],
cwd=self.cwd,
callwith=subprocess.check_output).strip()
for sha, fullref in (l.split() for l in out.splitlines()):
if fullref == 'refs/heads... | Query remote repo about given ref.
:return: ``('tag', sha)`` if ref is a tag in remote
``('branch', sha)`` if ref is branch (aka "head") in remote
``(None, ref)`` if ref does not exist in remote. This happens
notably if ref if a commit sha (they can't be querie... | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L134-L151 | [
"def log_call(self, cmd, callwith=subprocess.check_call,\n log_level=logging.DEBUG, **kw):\n \"\"\"Wrap a subprocess call with logging\n :param meth: the calling method to use.\n \"\"\"\n logger.log(log_level, \"%s> call %r\", self.cwd, cmd)\n ret = callwith(cmd, **kw)\n if callwith ==... | class Repo(object):
_git_version = None
def __init__(self, cwd, remotes, merges, target,
shell_command_after=None, fetch_all=False, defaults=None,
force=False):
"""Initialize a git repository aggregator
:param cwd: path to the directory where to initialize th... |
acsone/git-aggregator | git_aggregator/repo.py | Repo.log_call | python | def log_call(self, cmd, callwith=subprocess.check_call,
log_level=logging.DEBUG, **kw):
logger.log(log_level, "%s> call %r", self.cwd, cmd)
ret = callwith(cmd, **kw)
if callwith == subprocess.check_output:
ret = console_to_str(ret)
return ret | Wrap a subprocess call with logging
:param meth: the calling method to use. | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L153-L162 | [
"def console_to_str(s):\n \"\"\" From pypa/pip project, pip.backwardwardcompat. License MIT. \"\"\"\n try:\n return s.decode(console_encoding)\n except UnicodeDecodeError:\n return s.decode('utf_8')\n except AttributeError: # for tests, #13\n return s\n"
] | class Repo(object):
_git_version = None
def __init__(self, cwd, remotes, merges, target,
shell_command_after=None, fetch_all=False, defaults=None,
force=False):
"""Initialize a git repository aggregator
:param cwd: path to the directory where to initialize th... |
acsone/git-aggregator | git_aggregator/repo.py | Repo.aggregate | python | def aggregate(self):
logger.info('Start aggregation of %s', self.cwd)
target_dir = self.cwd
is_new = not os.path.exists(target_dir)
if is_new:
self.init_repository(target_dir)
self._switch_to_branch(self.target['branch'])
for r in self.remotes:
s... | Aggregate all merges into the target branch
If the target_dir doesn't exist, create an empty git repo otherwise
clean it, add all remotes , and merge all merges. | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L164-L189 | [
"def init_repository(self, target_dir):\n logger.info('Init empty git repository in %s', target_dir)\n self.log_call(['git', 'init', target_dir])\n",
"def fetch(self):\n basecmd = (\"git\", \"fetch\")\n logger.info(\"Fetching required remotes\")\n for merge in self.merges:\n cmd = basecmd + ... | class Repo(object):
_git_version = None
def __init__(self, cwd, remotes, merges, target,
shell_command_after=None, fetch_all=False, defaults=None,
force=False):
"""Initialize a git repository aggregator
:param cwd: path to the directory where to initialize th... |
acsone/git-aggregator | git_aggregator/repo.py | Repo._check_status | python | def _check_status(self):
logger.info('Checking repo status')
status = self.log_call(
['git', 'status', '--porcelain'],
callwith=subprocess.check_output,
cwd=self.cwd,
)
if status:
raise DirtyException(status) | Check repo status and except if dirty. | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L210-L219 | null | class Repo(object):
_git_version = None
def __init__(self, cwd, remotes, merges, target,
shell_command_after=None, fetch_all=False, defaults=None,
force=False):
"""Initialize a git repository aggregator
:param cwd: path to the directory where to initialize th... |
acsone/git-aggregator | git_aggregator/repo.py | Repo._fetch_options | python | def _fetch_options(self, merge):
cmd = tuple()
for option in FETCH_DEFAULTS:
value = merge.get(option, self.defaults.get(option))
if value:
cmd += ("--%s" % option, str(value))
return cmd | Get the fetch options from the given merge dict. | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L221-L228 | null | class Repo(object):
_git_version = None
def __init__(self, cwd, remotes, merges, target,
shell_command_after=None, fetch_all=False, defaults=None,
force=False):
"""Initialize a git repository aggregator
:param cwd: path to the directory where to initialize th... |
acsone/git-aggregator | git_aggregator/repo.py | Repo._set_remote | python | def _set_remote(self, name, url):
remotes = self._get_remotes()
exising_url = remotes.get(name)
if exising_url == url:
logger.info('Remote already exists %s <%s>', name, url)
return
if not exising_url:
logger.info('Adding remote %s <%s>', name, url)
... | Add remote to the repository. It's equivalent to the command
git remote add <name> <url>
If the remote already exists with an other url, it's removed
and added aggain | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L285-L304 | [
"def log_call(self, cmd, callwith=subprocess.check_call,\n log_level=logging.DEBUG, **kw):\n \"\"\"Wrap a subprocess call with logging\n :param meth: the calling method to use.\n \"\"\"\n logger.log(log_level, \"%s> call %r\", self.cwd, cmd)\n ret = callwith(cmd, **kw)\n if callwith ==... | class Repo(object):
_git_version = None
def __init__(self, cwd, remotes, merges, target,
shell_command_after=None, fetch_all=False, defaults=None,
force=False):
"""Initialize a git repository aggregator
:param cwd: path to the directory where to initialize th... |
acsone/git-aggregator | git_aggregator/repo.py | Repo.collect_prs_info | python | def collect_prs_info(self):
REPO_RE = re.compile(
'^(https://github.com/|git@github.com:)'
'(?P<owner>.*?)/(?P<repo>.*?)(.git)?$')
PULL_RE = re.compile(
'^(refs/)?pull/(?P<pr>[0-9]+)/head$')
remotes = {r['name']: r['url'] for r in self.remotes}
all_prs... | Collect all pending merge PRs info.
:returns: mapping of PRs by state | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L313-L357 | [
"def _github_api_get(self, path):\n url = 'https://api.github.com' + path\n token = os.environ.get('GITHUB_TOKEN')\n if token:\n url += '?access_token=' + token\n return requests.get(url)\n"
] | class Repo(object):
_git_version = None
def __init__(self, cwd, remotes, merges, target,
shell_command_after=None, fetch_all=False, defaults=None,
force=False):
"""Initialize a git repository aggregator
:param cwd: path to the directory where to initialize th... |
acsone/git-aggregator | git_aggregator/repo.py | Repo.show_closed_prs | python | def show_closed_prs(self):
all_prs = self.collect_prs_info()
for pr_info in all_prs.get('closed', []):
logger.info(
'{url} in state {state} ({merged})'.format(**pr_info)
) | Log only closed PRs. | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L359-L365 | [
"def collect_prs_info(self):\n \"\"\"Collect all pending merge PRs info.\n\n :returns: mapping of PRs by state\n \"\"\"\n REPO_RE = re.compile(\n '^(https://github.com/|git@github.com:)'\n '(?P<owner>.*?)/(?P<repo>.*?)(.git)?$')\n PULL_RE = re.compile(\n '^(refs/)?pull/(?P<pr>[0-... | class Repo(object):
_git_version = None
def __init__(self, cwd, remotes, merges, target,
shell_command_after=None, fetch_all=False, defaults=None,
force=False):
"""Initialize a git repository aggregator
:param cwd: path to the directory where to initialize th... |
acsone/git-aggregator | git_aggregator/repo.py | Repo.show_all_prs | python | def show_all_prs(self):
for __, prs in self.collect_prs_info().items():
for pr_info in prs:
logger.info(
'{url} in state {state} ({merged})'.format(**pr_info)
) | Log all PRs grouped by state. | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/repo.py#L367-L373 | [
"def collect_prs_info(self):\n \"\"\"Collect all pending merge PRs info.\n\n :returns: mapping of PRs by state\n \"\"\"\n REPO_RE = re.compile(\n '^(https://github.com/|git@github.com:)'\n '(?P<owner>.*?)/(?P<repo>.*?)(.git)?$')\n PULL_RE = re.compile(\n '^(refs/)?pull/(?P<pr>[0-... | class Repo(object):
_git_version = None
def __init__(self, cwd, remotes, merges, target,
shell_command_after=None, fetch_all=False, defaults=None,
force=False):
"""Initialize a git repository aggregator
:param cwd: path to the directory where to initialize th... |
acsone/git-aggregator | git_aggregator/config.py | get_repos | python | def get_repos(config, force=False):
repo_list = []
for directory, repo_data in config.items():
if not os.path.isabs(directory):
directory = os.path.abspath(directory)
repo_dict = {
'cwd': directory,
'defaults': repo_data.get('defaults', dict()),
'f... | Return a :py:obj:`list` list of repos from config file.
:param config: the repos config in :py:class:`dict` format.
:param bool force: Force aggregate dirty repos or not.
:type config: dict
:rtype: list | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/config.py#L17-L123 | null | # -*- coding: utf-8 -*-
# © 2015 ACSONE SA/NV
# License AGPLv3 (http://www.gnu.org/licenses/agpl-3.0-standalone.html)
import logging
import os
from string import Template
import kaptan
from .exception import ConfigException
from ._compat import string_types
log = logging.getLogger(__name__)
def load_config(confi... |
acsone/git-aggregator | git_aggregator/config.py | load_config | python | def load_config(config, expand_env=False, force=False):
if not os.path.exists(config):
raise ConfigException('Unable to find configuration file: %s' % config)
file_extension = os.path.splitext(config)[1][1:]
conf = kaptan.Kaptan(handler=kaptan.HANDLER_EXT.get(file_extension))
if expand_env:
... | Return repos from a directory and fnmatch. Not recursive.
:param config: paths to config file
:type config: str
:param expand_env: True to expand environment varialbes in the config.
:type expand_env: bool
:param bool force: True to aggregate even if repo is dirty.
:returns: expanded config dic... | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/config.py#L126-L149 | [
"def get_repos(config, force=False):\n \"\"\"Return a :py:obj:`list` list of repos from config file.\n :param config: the repos config in :py:class:`dict` format.\n :param bool force: Force aggregate dirty repos or not.\n :type config: dict\n :rtype: list\n \"\"\"\n repo_list = []\n for dire... | # -*- coding: utf-8 -*-
# © 2015 ACSONE SA/NV
# License AGPLv3 (http://www.gnu.org/licenses/agpl-3.0-standalone.html)
import logging
import os
from string import Template
import kaptan
from .exception import ConfigException
from ._compat import string_types
log = logging.getLogger(__name__)
def get_repos(config, ... |
acsone/git-aggregator | git_aggregator/main.py | setup_logger | python | def setup_logger(log=None, level=logging.INFO):
if not log:
log = logging.getLogger()
if not log.handlers:
channel = logging.StreamHandler()
if level == logging.DEBUG:
channel.setFormatter(DebugLogFormatter())
else:
channel.setFormatter(LogFormatter())
... | Setup logging for CLI use.
:param log: instance of logger
:type log: :py:class:`Logger` | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L45-L60 | null | # -*- coding: utf-8 -*-
# © 2015 ACSONE SA/NV
# License AGPLv3 (http://www.gnu.org/licenses/agpl-3.0-standalone.html)
import logging
import os
import sys
import threading
import traceback
try:
from Queue import Queue, Empty as EmptyQueue
except ImportError:
from queue import Queue, Empty as EmptyQueue
import ... |
acsone/git-aggregator | git_aggregator/main.py | get_parser | python | def get_parser():
main_parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter)
main_parser.add_argument(
'-c', '--config',
dest='config',
type=str,
nargs='?',
help='Pull the latest repositories from config(s)'
).completer = argcomple... | Return :py:class:`argparse.ArgumentParser` instance for CLI. | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L63-L139 | null | # -*- coding: utf-8 -*-
# © 2015 ACSONE SA/NV
# License AGPLv3 (http://www.gnu.org/licenses/agpl-3.0-standalone.html)
import logging
import os
import sys
import threading
import traceback
try:
from Queue import Queue, Empty as EmptyQueue
except ImportError:
from queue import Queue, Empty as EmptyQueue
import ... |
acsone/git-aggregator | git_aggregator/main.py | main | python | def main():
parser = get_parser()
argcomplete.autocomplete(parser, always_complete_options=False)
args = parser.parse_args()
setup_logger(
level=args.log_level
)
try:
if args.config and \
args.command in \
('aggregate', 'show-closed-prs', 'sho... | Main CLI application. | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L142-L163 | [
"def run(args):\n \"\"\"Load YAML and JSON configs and run the command specified\n in args.command\"\"\"\n\n repos = load_config(args.config, args.expand_env, args.force)\n\n jobs = max(args.jobs, 1)\n threads = []\n sem = threading.Semaphore(jobs)\n err_queue = Queue()\n\n for repo_dict in ... | # -*- coding: utf-8 -*-
# © 2015 ACSONE SA/NV
# License AGPLv3 (http://www.gnu.org/licenses/agpl-3.0-standalone.html)
import logging
import os
import sys
import threading
import traceback
try:
from Queue import Queue, Empty as EmptyQueue
except ImportError:
from queue import Queue, Empty as EmptyQueue
import ... |
acsone/git-aggregator | git_aggregator/main.py | load_aggregate | python | def load_aggregate(args):
repos = load_config(args.config, args.expand_env)
dirmatch = args.dirmatch
for repo_dict in repos:
r = Repo(**repo_dict)
logger.debug('%s' % r)
if not match_dir(r.cwd, dirmatch):
logger.info("Skip %s", r.cwd)
continue
r.aggreg... | Load YAML and JSON configs and begin creating / updating , aggregating
and pushing the repos (deprecated in favor or run()) | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L174-L187 | [
"def load_config(config, expand_env=False, force=False):\n \"\"\"Return repos from a directory and fnmatch. Not recursive.\n\n :param config: paths to config file\n :type config: str\n :param expand_env: True to expand environment varialbes in the config.\n :type expand_env: bool\n :param bool for... | # -*- coding: utf-8 -*-
# © 2015 ACSONE SA/NV
# License AGPLv3 (http://www.gnu.org/licenses/agpl-3.0-standalone.html)
import logging
import os
import sys
import threading
import traceback
try:
from Queue import Queue, Empty as EmptyQueue
except ImportError:
from queue import Queue, Empty as EmptyQueue
import ... |
acsone/git-aggregator | git_aggregator/main.py | aggregate_repo | python | def aggregate_repo(repo, args, sem, err_queue):
try:
logger.debug('%s' % repo)
dirmatch = args.dirmatch
if not match_dir(repo.cwd, dirmatch):
logger.info("Skip %s", repo.cwd)
return
if args.command == 'aggregate':
repo.aggregate()
if ar... | Aggregate one repo according to the args.
Args:
repo (Repo): The repository to aggregate.
args (argparse.Namespace): CLI arguments. | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L190-L214 | [
"def match_dir(cwd, dirmatch=None):\n if not dirmatch:\n return True\n return (fnmatch.fnmatch(cwd, dirmatch) or\n fnmatch.fnmatch(os.path.relpath(cwd), dirmatch) or\n os.path.relpath(cwd) == os.path.relpath(dirmatch))\n"
] | # -*- coding: utf-8 -*-
# © 2015 ACSONE SA/NV
# License AGPLv3 (http://www.gnu.org/licenses/agpl-3.0-standalone.html)
import logging
import os
import sys
import threading
import traceback
try:
from Queue import Queue, Empty as EmptyQueue
except ImportError:
from queue import Queue, Empty as EmptyQueue
import ... |
acsone/git-aggregator | git_aggregator/main.py | run | python | def run(args):
repos = load_config(args.config, args.expand_env, args.force)
jobs = max(args.jobs, 1)
threads = []
sem = threading.Semaphore(jobs)
err_queue = Queue()
for repo_dict in repos:
if not err_queue.empty():
break
sem.acquire()
r = Repo(**repo_dic... | Load YAML and JSON configs and run the command specified
in args.command | train | https://github.com/acsone/git-aggregator/blob/8631b0e64f9e8ce1857b21adeddb890ebd8469a6/git_aggregator/main.py#L217-L258 | [
"def load_config(config, expand_env=False, force=False):\n \"\"\"Return repos from a directory and fnmatch. Not recursive.\n\n :param config: paths to config file\n :type config: str\n :param expand_env: True to expand environment varialbes in the config.\n :type expand_env: bool\n :param bool for... | # -*- coding: utf-8 -*-
# © 2015 ACSONE SA/NV
# License AGPLv3 (http://www.gnu.org/licenses/agpl-3.0-standalone.html)
import logging
import os
import sys
import threading
import traceback
try:
from Queue import Queue, Empty as EmptyQueue
except ImportError:
from queue import Queue, Empty as EmptyQueue
import ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.figure | python | def figure(bgcolor=(1,1,1), size=(1000,1000)):
Visualizer3D._scene = Scene(background_color=np.array(bgcolor))
Visualizer3D._scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], strength=1.0)
Visualizer3D._init_size = np.array(size) | Create a blank figure.
Parameters
----------
bgcolor : (3,) float
Color of the background with values in [0,1].
size : (2,) int
Width and height of the figure in pixels. | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L32-L44 | null | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.show | python | def show(animate=False, axis=np.array([0.,0.,1.]), clf=True, **kwargs):
x = SceneViewer(Visualizer3D._scene,
size=Visualizer3D._init_size,
animate=animate,
animate_axis=axis,
save_directory=Visualizer3D._save_directo... | Display the current figure and enable interaction.
Parameters
----------
animate : bool
Whether or not to animate the scene.
axis : (3,) float or None
If present, the animation will rotate about the given axis in world coordinates.
Otherwise, the anim... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L48-L72 | [
"def clf():\n \"\"\"Clear the current figure\n \"\"\"\n Visualizer3D._scene = Scene(background_color=Visualizer3D._scene.background_color)\n Visualizer3D._scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], strength=1.0)\n"
] | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.render | python | def render(n_frames=1, axis=np.array([0.,0.,1.]), clf=True, **kwargs):
v = SceneViewer(Visualizer3D._scene,
size=Visualizer3D._init_size,
animate=(n_frames > 1),
animate_axis=axis,
max_frames=n_frames,
... | Render frames from the viewer.
Parameters
----------
n_frames : int
Number of frames to render. If more than one, the scene will animate.
axis : (3,) float or None
If present, the animation will rotate about the given axis in world coordinates.
Otherw... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L76-L106 | [
"def clf():\n \"\"\"Clear the current figure\n \"\"\"\n Visualizer3D._scene = Scene(background_color=Visualizer3D._scene.background_color)\n Visualizer3D._scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], strength=1.0)\n"
] | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.save | python | def save(filename, n_frames=1, axis=np.array([0.,0.,1.]), clf=True, **kwargs):
if n_frames >1 and os.path.splitext(filename)[1] != '.gif':
raise ValueError('Expected .gif file for multiple-frame save.')
v = SceneViewer(Visualizer3D._scene,
size=Visualizer3D._init_size... | Save frames from the viewer out to a file.
Parameters
----------
filename : str
The filename in which to save the output image. If more than one frame,
should have extension .gif.
n_frames : int
Number of frames to render. If more than one, the scene ... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L110-L143 | [
"def clf():\n \"\"\"Clear the current figure\n \"\"\"\n Visualizer3D._scene = Scene(background_color=Visualizer3D._scene.background_color)\n Visualizer3D._scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], strength=1.0)\n"
] | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.save_loop | python | def save_loop(filename, framerate=30, time=3.0, axis=np.array([0.,0.,1.]), clf=True, **kwargs):
n_frames = framerate * time
az = 2.0 * np.pi / n_frames
Visualizer3D.save(filename, n_frames=n_frames, axis=axis, clf=clf,
animate_rate=framerate, animate_az=az)
if c... | Off-screen save a GIF of one rotation about the scene.
Parameters
----------
filename : str
The filename in which to save the output image (should have extension .gif)
framerate : int
The frame rate at which to animate motion.
time : float
The... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L146-L170 | [
"def save(filename, n_frames=1, axis=np.array([0.,0.,1.]), clf=True, **kwargs):\n \"\"\"Save frames from the viewer out to a file.\n\n Parameters\n ----------\n filename : str\n The filename in which to save the output image. If more than one frame,\n should have extension .gif.\n n_fra... | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.clf | python | def clf():
Visualizer3D._scene = Scene(background_color=Visualizer3D._scene.background_color)
Visualizer3D._scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], strength=1.0) | Clear the current figure | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L173-L177 | null | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.points | python | def points(points, T_points_world=None, color=np.array([0,1,0]), scale=0.01, n_cuts=20, subsample=None, random=False, name=None):
if isinstance(points, BagOfPoints):
if points.dim != 3:
raise ValueError('BagOfPoints must have dimension 3xN!')
else:
if type(points)... | Scatter a point cloud in pose T_points_world.
Parameters
----------
points : autolab_core.BagOfPoints or (n,3) float
The point set to visualize.
T_points_world : autolab_core.RigidTransform
Pose of points, specified as a transformation from point frame to world f... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L209-L287 | null | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.mesh | python | def mesh(mesh, T_mesh_world=RigidTransform(from_frame='obj', to_frame='world'),
style='surface', smooth=False, color=(0.5,0.5,0.5), name=None):
if not isinstance(mesh, trimesh.Trimesh):
raise ValueError('Must provide a trimesh.Trimesh object')
mp = MaterialProperties(
... | Visualize a 3D triangular mesh.
Parameters
----------
mesh : trimesh.Trimesh
The mesh to visualize.
T_mesh_world : autolab_core.RigidTransform
The pose of the mesh, specified as a transformation from mesh frame to world frame.
style : str
Tria... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L290-L325 | null | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.mesh_stable_pose | python | def mesh_stable_pose(mesh, T_obj_table,
T_table_world=RigidTransform(from_frame='table', to_frame='world'),
style='wireframe', smooth=False, color=(0.5,0.5,0.5),
dim=0.15, plot_table=True, plot_com=False, name=None):
T_obj_table = T_obj_... | Visualize a mesh in a stable pose.
Parameters
----------
mesh : trimesh.Trimesh
The mesh to visualize.
T_obj_table : autolab_core.RigidTransform
Pose of object relative to table.
T_table_world : autolab_core.RigidTransform
Pose of table relati... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L329-L371 | [
"def points(points, T_points_world=None, color=np.array([0,1,0]), scale=0.01, n_cuts=20, subsample=None, random=False, name=None):\n \"\"\"Scatter a point cloud in pose T_points_world.\n\n Parameters\n ----------\n points : autolab_core.BagOfPoints or (n,3) float\n The point set to visualize.\n ... | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.pose | python | def pose(T_frame_world, alpha=0.1, tube_radius=0.005, center_scale=0.01):
R = T_frame_world.rotation
t = T_frame_world.translation
x_axis_tf = np.array([t, t + alpha * R[:,0]])
y_axis_tf = np.array([t, t + alpha * R[:,1]])
z_axis_tf = np.array([t, t + alpha * R[:,2]])
V... | Plot a 3D pose as a set of axes (x red, y green, z blue).
Parameters
----------
T_frame_world : autolab_core.RigidTransform
The pose relative to world coordinates.
alpha : float
Length of plotted x,y,z axes.
tube_radius : float
Radius of plott... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L374-L398 | [
"def points(points, T_points_world=None, color=np.array([0,1,0]), scale=0.01, n_cuts=20, subsample=None, random=False, name=None):\n \"\"\"Scatter a point cloud in pose T_points_world.\n\n Parameters\n ----------\n points : autolab_core.BagOfPoints or (n,3) float\n The point set to visualize.\n ... | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.table | python | def table(T_table_world=RigidTransform(from_frame='table', to_frame='world'), dim=0.16, color=(0,0,0)):
table_vertices = np.array([[ dim, dim, 0],
[ dim, -dim, 0],
[-dim, dim, 0],
[-dim, -dim, 0]]).astype... | Plot a table mesh in 3D.
Parameters
----------
T_table_world : autolab_core.RigidTransform
Pose of table relative to world.
dim : float
The side-length for the table.
color : 3-tuple
Color tuple. | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L401-L421 | [
"def mesh(mesh, T_mesh_world=RigidTransform(from_frame='obj', to_frame='world'),\n style='surface', smooth=False, color=(0.5,0.5,0.5), name=None):\n \"\"\"Visualize a 3D triangular mesh.\n\n Parameters\n ----------\n mesh : trimesh.Trimesh\n The mesh to visualize.\n T_mesh_world : auto... | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer3d.py | Visualizer3D.plot3d | python | def plot3d(points, color=(0.5, 0.5, 0.5), tube_radius=0.005, n_components=30, name=None):
points = np.asanyarray(points)
mp = MaterialProperties(
color = np.array(color),
k_a = 0.5,
k_d = 0.3,
k_s = 0.0,
alpha = 10.0,
smooth=True
... | Plot a 3d curve through a set of points using tubes.
Parameters
----------
points : (n,3) float
A series of 3D points that define a curve in space.
color : (3,) float
The color of the tube.
tube_radius : float
Radius of tube representing curve... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer3d.py#L424-L468 | null | class Visualizer3D:
"""
Class containing static methods for visualization.
The interface is styled after pyplot.
Should be thought of as a namespace rather than a class.
"""
_scene = Scene(background_color=np.array([1.0, 1.0, 1.0]))
_scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], ... |
BerkeleyAutomation/visualization | visualization/visualizer2d.py | Visualizer2D.figure | python | def figure(size=(8,8), *args, **kwargs):
return plt.figure(figsize=size, *args, **kwargs) | Creates a figure.
Parameters
----------
size : 2-tuple
size of the view window in inches
args : list
args of mayavi figure
kwargs : list
keyword args of mayavi figure
Returns
-------
pyplot figure
the current ... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L14-L31 | null | class Visualizer2D:
@staticmethod
@staticmethod
def show(filename=None, *args, **kwargs):
""" Show the current figure.
Parameters
----------
filename : :obj:`str`
filename to save the image to, for auto-saving
"""
if filename is None:
... |
BerkeleyAutomation/visualization | visualization/visualizer2d.py | Visualizer2D.show | python | def show(filename=None, *args, **kwargs):
if filename is None:
plt.show(*args, **kwargs)
else:
plt.savefig(filename, *args, **kwargs) | Show the current figure.
Parameters
----------
filename : :obj:`str`
filename to save the image to, for auto-saving | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L34-L45 | null | class Visualizer2D:
@staticmethod
def figure(size=(8,8), *args, **kwargs):
""" Creates a figure.
Parameters
----------
size : 2-tuple
size of the view window in inches
args : list
args of mayavi figure
kwargs : list
keyword args o... |
BerkeleyAutomation/visualization | visualization/visualizer2d.py | Visualizer2D.imshow | python | def imshow(image, auto_subplot=False, **kwargs):
if isinstance(image, BinaryImage) or isinstance(image, GrayscaleImage):
plt.imshow(image.data, cmap=plt.cm.gray, **kwargs)
elif isinstance(image, ColorImage) or isinstance(image, SegmentationImage):
plt.imshow(image.data, **kwargs)... | Displays an image.
Parameters
----------
image : :obj:`perception.Image`
image to display
auto_subplot : bool
whether or not to automatically subplot for multi-channel images e.g. rgbd | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L118-L151 | null | class Visualizer2D:
@staticmethod
def figure(size=(8,8), *args, **kwargs):
""" Creates a figure.
Parameters
----------
size : 2-tuple
size of the view window in inches
args : list
args of mayavi figure
kwargs : list
keyword args o... |
BerkeleyAutomation/visualization | visualization/visualizer2d.py | Visualizer2D.box | python | def box(b, line_width=2, color='g', style='-'):
if not isinstance(b, Box):
raise ValueError('Input must be of type Box')
# get min pixels
min_i = b.min_pt[1]
min_j = b.min_pt[0]
max_i = b.max_pt[1]
max_j = b.max_pt[0]
top_left = np.array([... | Draws a box on the current plot.
Parameters
----------
b : :obj:`autolab_core.Box`
box to draw
line_width : int
width of lines on side of box
color : :obj:`str`
color of box
style : :obj:`str`
style of lines to draw | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L154-L191 | null | class Visualizer2D:
@staticmethod
def figure(size=(8,8), *args, **kwargs):
""" Creates a figure.
Parameters
----------
size : 2-tuple
size of the view window in inches
args : list
args of mayavi figure
kwargs : list
keyword args o... |
BerkeleyAutomation/visualization | visualization/visualizer2d.py | Visualizer2D.contour | python | def contour(c, subsample=1, size=10, color='g'):
if not isinstance(c, Contour):
raise ValueError('Input must be of type Contour')
for i in range(c.num_pixels)[0::subsample]:
plt.scatter(c.boundary_pixels[i,1], c.boundary_pixels[i,0], s=size, c=color) | Draws a contour on the current plot by scattering points.
Parameters
----------
c : :obj:`autolab_core.Contour`
contour to draw
subsample : int
subsample rate for boundary pixels
size : int
size of scattered points
color : :obj:`str`
... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L194-L212 | null | class Visualizer2D:
@staticmethod
def figure(size=(8,8), *args, **kwargs):
""" Creates a figure.
Parameters
----------
size : 2-tuple
size of the view window in inches
args : list
args of mayavi figure
kwargs : list
keyword args o... |
BerkeleyAutomation/visualization | visualization/visualizer2d.py | Visualizer2D.grasp | python | def grasp(grasp, width=None, color='r', arrow_len=4, arrow_head_len = 2, arrow_head_width = 3,
arrow_width = 1, jaw_len=3, jaw_width = 1.0,
grasp_center_size=1, grasp_center_thickness=2.5,
grasp_center_style='+', grasp_axis_width=1,
grasp_axis_style='--', line_wid... | Plots a 2D grasp with arrow and jaw style using matplotlib
Parameters
----------
grasp : :obj:`Grasp2D`
2D grasp to plot
width : float
width, in pixels, of the grasp (overrides Grasp2D.width_px)
color : :obj:`str`
color of plotted gras... | train | https://github.com/BerkeleyAutomation/visualization/blob/f8d038cc65c78f841ef27f99fb2a638f44fa72b6/visualization/visualizer2d.py#L215-L308 | null | class Visualizer2D:
@staticmethod
def figure(size=(8,8), *args, **kwargs):
""" Creates a figure.
Parameters
----------
size : 2-tuple
size of the view window in inches
args : list
args of mayavi figure
kwargs : list
keyword args o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.