code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
A = {}
r = numpy.arange(N, dtype=int)
key = numpy.zeros(dim, dtype=int)
for i in range(N):
key[-1] = i
A[tuple(key)] = 1*(r==i)
return Poly(A, dim, (N,), int) | def prange(N=1, dim=1) | Constructor to create a range of polynomials where the exponent vary.
Args:
N (int):
Number of polynomials in the array.
dim (int):
The dimension the polynomial should span.
Returns:
(Poly):
A polynomial array of length N containing simple polynomial... | 5.556293 | 6.818474 | 0.814888 |
dim = P.dim
shape = P.shape
dtype = P.dtype
A = dict(((key[n:]+key[:n],P.A[key]) for key in P.keys))
return Poly(A, dim, shape, dtype) | def rolldim(P, n=1) | Roll the axes.
Args:
P (Poly) : Input polynomial.
n (int) : The axis that after rolling becomes the 0th axis.
Returns:
(Poly) : Polynomial with new axis configuration.
Examples:
>>> x,y,z = variable(3)
>>> P = x*x*x + y*y + z
>>> print(P)
q0^3+q1^2+... | 6.262584 | 7.09972 | 0.882089 |
if not isinstance(P, Poly):
return numpy.swapaxes(P, dim1, dim2)
dim = P.dim
shape = P.shape
dtype = P.dtype
if dim1==dim2:
return P
m = max(dim1, dim2)
if P.dim <= m:
P = chaospy.poly.dimension.setdim(P, m+1)
dim = m+1
A = {}
for key in P.ke... | def swapdim(P, dim1=1, dim2=0) | Swap the dim between two variables.
Args:
P (Poly):
Input polynomial.
dim1 (int):
First dim
dim2 (int):
Second dim.
Returns:
(Poly):
Polynomial with swapped dimensions.
Examples:
>>> x,y = variable(2)
>>> P = ... | 3.180354 | 3.557174 | 0.894068 |
A = P.A.copy()
for key in P.keys:
A[key] = numpy.tril(P.A[key])
return Poly(A, dim=P.dim, shape=P.shape) | def tril(P, k=0) | Lower triangle of coefficients. | 4.153788 | 3.958809 | 1.049252 |
tri = numpy.sum(numpy.mgrid[[slice(0,_,1) for _ in P.shape]], 0)
tri = tri<len(tri) + k
if isinstance(P, Poly):
A = P.A.copy()
B = {}
for key in P.keys:
B[key] = A[key]*tri
return Poly(B, shape=P.shape, dim=P.dim, dtype=P.dtype)
out = P*tri
return o... | def tricu(P, k=0) | Cross-diagonal upper triangle. | 5.256135 | 5.165418 | 1.017562 |
if dims == 1:
return Poly({(1,): 1}, dim=1, shape=())
return Poly({
tuple(indices): indices for indices in numpy.eye(dims, dtype=int)
}, dim=dims, shape=(dims,)) | def variable(dims=1) | Simple constructor to create single variables to create polynomials.
Args:
dims (int):
Number of dimensions in the array.
Returns:
(Poly):
Polynomial array with unit components in each dimension.
Examples:
>>> print(variable())
q0
>>> print(... | 6.38221 | 6.780922 | 0.941201 |
if isinstance(A, Poly):
out = numpy.zeros(A.shape, dtype=bool)
B = A.A
for key in A.keys:
out += all(B[key], ax)
return out
return numpy.all(A, ax) | def all(A, ax=None) | Test if all values in A evaluate to True | 4.23702 | 4.346238 | 0.974871 |
if isinstance(A, Poly):
B = A.A.copy()
for key in A.keys:
B[key] = around(B[key], decimals)
return Poly(B, A.dim, A.shape, A.dtype)
return numpy.around(A, decimals) | def around(A, decimals=0) | Evenly round to the given number of decimals.
Args:
A (Poly, numpy.ndarray):
Input data.
decimals (int):
Number of decimal places to round to (default: 0). If decimals is
negative, it specifies the number of positions to the left of the
decimal point... | 3.810848 | 4.874524 | 0.781789 |
if isinstance(A, Poly):
core, core_new = A.A, {}
for key in A.keys:
core_new[key] = numpy.diag(core[key], k)
return Poly(core_new, A.dim, None, A.dtype)
return numpy.diag(A, k) | def diag(A, k=0) | Extract or construct a diagonal polynomial array. | 4.873888 | 4.43746 | 1.098351 |
if isinstance(A, Poly):
B = A.A.copy()
for key in A.keys:
values = B[key].copy()
values[numpy.abs(values) < threshold] = 0.
B[key] = values
return Poly(B, A.dim, A.shape, A.dtype)
A = A.copy()
A[numpy.abs(A) < threshold] = 0.
return A | def prune(A, threshold) | Remove coefficients that is not larger than a given threshold.
Args:
A (Poly):
Input data.
threshold (float):
Threshold for which values to cut.
Returns:
(Poly):
Same type as A.
Examples:
>>> P = chaospy.sum(chaospy.prange(3)*2**-numpy.a... | 3.113568 | 3.285584 | 0.947645 |
uloc = numpy.zeros((2, len(self)))
for dist in evaluation.sorted_dependencies(self, reverse=True):
if dist not in self.inverse_map:
continue
idx = self.inverse_map[dist]
xloc_ = xloc[idx].reshape(1, -1)
uloc[:, idx] = evaluation.ev... | def _range(self, xloc, cache) | Special handle for finding bounds on constrained dists.
Example:
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(dist.range())
[[0. 0.]
[1. 2.]] | 5.67879 | 5.787698 | 0.981183 |
uloc = numpy.zeros((2,)+xloc.shape)
for dist in evaluation.sorted_dependencies(self, reverse=True):
if dist not in self.inverse_map:
continue
idx = self.inverse_map[dist]
xloc_ = xloc[idx].reshape(1, -1)
uloc[:, idx] = evaluation.e... | def _bnd(self, xloc, cache, **kwargs) | Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal())
>>> print(dist.range([[-0.5, 0.5, 1.5], [-1, 0, 1]]))
[[[ 0. 0. 0. ]
[-7.5 -7.5 -7.5]]
<BLANKLINE>
[[ 1. 1. 1. ]
[ 7.5 7.5 7.5]]]
>>> d0 = cha... | 5.006418 | 5.171045 | 0.968164 |
floc = numpy.zeros(xloc.shape)
for dist in evaluation.sorted_dependencies(self, reverse=True):
if dist not in self.inverse_map:
continue
idx = self.inverse_map[dist]
xloc_ = xloc[idx].reshape(1, -1)
floc[idx] = evaluation.evaluate_... | def _pdf(self, xloc, cache, **kwargs) | Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal())
>>> print(numpy.around(dist.pdf([[-0.5, 0.5, 1.5], [-1, 0, 1]]), 4))
[0. 0.3989 0. ]
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(dist.... | 4.623881 | 5.272498 | 0.876981 |
xloc = numpy.zeros(qloc.shape)
for dist in evaluation.sorted_dependencies(self, reverse=True):
if dist not in self.inverse_map:
continue
idx = self.inverse_map[dist]
qloc_ = qloc[idx].reshape(1, -1)
xloc[idx] = evaluation.evaluate_... | def _ppf(self, qloc, cache, **kwargs) | Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal())
>>> print(numpy.around(dist.inv([[0.1, 0.2, 0.3], [0.3, 0.3, 0.4]]), 4))
[[ 0.1 0.2 0.3 ]
[-0.5244 -0.5244 -0.2533]]
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d... | 4.431209 | 4.787617 | 0.925556 |
if evaluation.get_dependencies(*list(self.inverse_map)):
raise StochasticallyDependentError(
"Joint distribution with dependencies not supported.")
output = 1.
for dist in evaluation.sorted_dependencies(self):
if dist not in self.inverse_map:
... | def _mom(self, kloc, cache, **kwargs) | Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal())
>>> print(numpy.around(dist.mom([[0, 0, 1], [0, 1, 1]]), 4))
[1. 0. 0.]
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(numpy.around(dist.mom([1,... | 6.635479 | 6.790993 | 0.9771 |
if evaluation.get_dependencies(*list(self.inverse_map)):
raise StochasticallyDependentError(
"Joint distribution with dependencies not supported.")
output = numpy.zeros((2,)+kloc.shape)
for dist in evaluation.sorted_dependencies(self):
if dist not... | def _ttr(self, kloc, cache, **kwargs) | Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal(), chaospy.Exponential())
>>> print(numpy.around(dist.ttr([[1, 2, 3], [1, 2, 3], [1, 2, 3]]), 4))
[[[0.5 0.5 0.5 ]
[0.0833 0.0667 0.0643]
[0. 0. 0. ]]
<BLANKLINE... | 6.362346 | 5.536646 | 1.149134 |
samples = dist.sample(sample, **kws)
poly = polynomials.flatten(poly)
Y = poly(*samples)
if retall:
return spearmanr(Y.T)
return spearmanr(Y.T)[0] | def Spearman(poly, dist, sample=10000, retall=False, **kws) | Calculate Spearman's rank-order correlation coefficient.
Args:
poly (Poly):
Polynomial of interest.
dist (Dist):
Defines the space where correlation is taken.
sample (int):
Number of samples used in estimation.
retall (bool):
If true, ... | 3.612152 | 5.304086 | 0.681013 |
foo = lambda y: self.igen(numpy.sum(self.gen(y, th), 0), th)
out1 = out2 = 0.
sign = 1 - 2*(x > .5).T
for I in numpy.ndindex(*((2,)*(len(x)-1)+(1,))):
eps_ = numpy.array(I)*eps
x_ = (x.T + sign*eps_).T
out1 += (-1)**sum(I)*foo(x_)
... | def _diff(self, x, th, eps) | Differentiation function.
Numerical approximation of a Rosenblatt transformation created from
copula formulation. | 6.292215 | 6.304562 | 0.998042 |
all_datas = ()
data = ()
for class_path in settings.TH_SERVICES:
class_name = class_path.rsplit('.', 1)[1]
# 2nd array position contains the name of the service
data = (class_name, class_name.rsplit('Service', 1)[1])
all_datas = (data,) + all_datas
return all_datas | def available_services() | get the available services to be activated
read the models dir to find the services installed
to be added to the system by the administrator | 5.691189 | 5.690553 | 1.000112 |
from django.db import connection
connection.close()
failed_tries = settings.DJANGO_TH.get('failed_tries', 10)
trigger = TriggerService.objects.filter(
Q(provider_failed__lte=failed_tries) |
Q(consumer_failed__lte=failed_tries),
status=True,
... | def handle(self, *args, **options) | get all the triggers that need to be handled | 4.381649 | 4.160385 | 1.053183 |
status = False
# set the title and content of the data
title, content = super(ServiceTwitter, self).save_data(trigger_id, **data)
if data.get('link') and len(data.get('link')) > 0:
# remove html tag if any
content = html.strip_tags(content)
... | def save_data(self, trigger_id, **data) | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | 4.781082 | 4.86587 | 0.982575 |
callback_url = self.callback_url(request)
twitter = Twython(self.consumer_key, self.consumer_secret)
req_token = twitter.get_authentication_tokens(
callback_url=callback_url)
request.session['oauth_token'] = req_token['oauth_token']
request.session['oauth_t... | def auth(self, request) | build the request to access to the Twitter
website with all its required parms
:param request: makes the url to call Twitter + the callback url
:return: go to the Twitter website to ask to the user
to allow the access of TriggerHappy | 2.33345 | 2.504767 | 0.931603 |
return super(ServiceTwitter, self).callback(request, **kwargs) | def callback(self, request, **kwargs) | Called from the Service when the user accept to activate it | 10.508088 | 7.326889 | 1.434182 |
twitter = Twython(self.consumer_key,
self.consumer_secret,
oauth_token,
oauth_token_secret)
access_token = twitter.get_authorized_tokens(oauth_verifier)
return access_token | def get_access_token(
self, oauth_token, oauth_token_secret, oauth_verifier
) | :param oauth_token: oauth_token retrieve by the API Twython
get_authentication_tokens()
:param oauth_token_secret: oauth_token_secret retrieve by the
API Twython get_authentication_tokens()
:param oauth_verifier: oauth_verifier retrieve from Twitter
:type oauth_token: string
... | 2.601749 | 2.430012 | 1.070673 |
status = False
service = TriggerService.objects.get(id=trigger_id)
desc = service.description
slack = Slack.objects.get(trigger_id=trigger_id)
title = self.set_title(data)
if title is None:
title = data.get('subject')
type_action = data.get(... | def save_data(self, trigger_id, **data) | get the data from the service
:param trigger_id: id of the trigger
:params data, dict
:rtype: dict | 4.201778 | 4.233017 | 0.99262 |
trigger_id = options.get('trigger_id')
trigger = TriggerService.objects.filter(
id=int(trigger_id),
status=True,
user__is_active=True,
provider_failed__lt=settings.DJANGO_TH.get('failed_tries', 10),
consumer_failed__lt=settings.DJANGO_... | def handle(self, *args, **options) | get the trigger to fire | 4.277108 | 4.022536 | 1.063286 |
trigger_id = kwargs.get('trigger_id')
trigger = Pushbullet.objects.get(trigger_id=trigger_id)
date_triggered = kwargs.get('date_triggered')
data = list()
pushes = self.pushb.get_pushes()
for p in pushes:
title = 'From Pushbullet'
created =... | def read_data(self, **kwargs) | get the data from the service
as the pushbullet service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id a... | 5.520071 | 5.170135 | 1.067684 |
title, content = super(ServicePushbullet, self).save_data(trigger_id, **data)
if self.token:
trigger = Pushbullet.objects.get(trigger_id=trigger_id)
if trigger.type == 'note':
status = self.pushb.push_note(title=title, body=content)
elif trigg... | def save_data(self, trigger_id, **data) | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | 3.425989 | 3.455238 | 0.991535 |
try:
char = defs[m.group(1)]
return "&{char};".format(char=char)
except ValueError:
return m.group(0)
except KeyError:
return m.group(0) | def html_entity_decode_char(self, m, defs=htmlentities.entitydefs) | decode html entity into one of the html char | 2.535952 | 2.417854 | 1.048844 |
try:
char = defs[m.group(1)]
return "&{char};".format(char=char)
except ValueError:
return m.group(0)
except KeyError:
return m.group(0) | def html_entity_decode_codepoint(self, m,
defs=htmlentities.codepoint2name) | decode html entity into one of the codepoint2name | 2.576806 | 2.716896 | 0.948438 |
pattern = re.compile(r"&#(\w+?);")
string = pattern.sub(self.html_entity_decode_char, self.my_string)
return pattern.sub(self.html_entity_decode_codepoint, string) | def html_entity_decode(self) | entry point of this set of tools
to decode html entities | 3.882437 | 4.299663 | 0.902963 |
taiga_obj = Taiga.objects.get(trigger_id=trigger_id)
action = data.get('action')
domain = data.get('type')
data = data.get('data')
t = TaigaDomain.factory(domain)
if action == 'create':
t.create(taiga_obj, data)
elif action == 'change':
t.change(taiga_obj, data)
el... | def data_filter(trigger_id, **data) | check if we want to track event for a given action
:param trigger_id:
:param data:
:return: | 2.925797 | 3.039068 | 0.962728 |
status = True
# consumer - the service which uses the data
default_provider.load_services()
service = TriggerService.objects.get(id=trigger_id)
service_consumer = default_provider.get_service(str(service.consumer.name.name))
kwargs = {'user': service.user}
if len(data) > 0:
ge... | def save_data(trigger_id, data) | call the consumer and handle the data
:param trigger_id:
:param data:
:return: | 6.520451 | 6.369473 | 1.023703 |
try:
self.pocket.add(url=url, title=title, tags=tags)
sentence = str('pocket {} created').format(url)
logger.debug(sentence)
status = True
except Exception as e:
logger.critical(e)
update_result(self.trigger_id, msg=e, stat... | def _create_entry(self, url, title, tags) | Create an entry
:param url: url to save
:param title: title to set
:param tags: tags to set
:return: status | 5.251323 | 5.399206 | 0.97261 |
trigger_id = kwargs.get('trigger_id')
date_triggered = kwargs.get('date_triggered')
data = list()
# pocket uses a timestamp date format
since = arrow.get(date_triggered).timestamp
if self.token is not None:
# get the data from the last time the trig... | def read_data(self, **kwargs) | get the data from the service
As the pocket service does not have any date in its API linked to the note,
add the triggered date to the dict data thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at least
:type kw... | 4.046824 | 3.747219 | 1.079954 |
if data.get('link'):
if len(data.get('link')) > 0:
# get the pocket data of this trigger
from th_pocket.models import Pocket as PocketModel
trigger = PocketModel.objects.get(trigger_id=trigger_id)
title = self.set_title(data)
... | def save_data(self, trigger_id, **data) | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | 4.468825 | 4.365974 | 1.023557 |
callback_url = self.callback_url(request)
request_token = Pocket.get_request_token(consumer_key=self.consumer_key, redirect_uri=callback_url)
# Save the request token information for later
request.session['request_token'] = request_token
# URL to redirect user to, to au... | def auth(self, request) | let's auth the user to the Service
:param request: request object
:return: callback url
:rtype: string that contains the url to redirect after auth | 3.545237 | 3.619849 | 0.979388 |
access_token = Pocket.get_access_token(consumer_key=self.consumer_key, code=request.session['request_token'])
kwargs = {'access_token': access_token}
return super(ServicePocket, self).callback(request, **kwargs) | def callback(self, request, **kwargs) | Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template | 4.670106 | 4.778286 | 0.97736 |
elements = document_element.getElementsByTagName(tag_name)
for element in elements:
p = element.parentNode
p.removeChild(element) | def remove_prohibited_element(tag_name, document_element) | To fit the Evernote DTD need, drop this tag name | 2.893664 | 2.742339 | 1.055181 |
title, content = super(ServiceMastodon, self).save_data(trigger_id, **data)
# check if we have a 'good' title
if self.title_or_content(title):
content = str("{title} {link}").format(title=title, link=data.get('link'))
content += get_tags(Mastodon, trigger_id)
... | def save_data(self, trigger_id, **data) | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | 3.900378 | 3.988494 | 0.977908 |
local_file = ''
if 'https://t.co' in content:
content = re.sub(r'https://t.co/(\w+)', '', content)
if 'https://pbs.twimg.com/media/' in content:
m = re.search('https://pbs.twimg.com/media/([\w\-_]+).jpg', content) # NOQA
url = 'https://pbs.twimg.com/... | def media_in_content(self, content) | check if the content contains and url of an image
for the moment, check twitter media url
could be elaborate with other service when needed
:param content:
:return: | 2.43187 | 2.305503 | 1.054811 |
# create app
redirect_uris = '%s://%s%s' % (request.scheme, request.get_host(),
reverse('mastodon_callback'))
us = UserService.objects.get(user=request.user,
name='ServiceMastodon')
client_id, client_sec... | def auth(self, request) | get the auth of the services
:param request: contains the current session
:type request: dict
:rtype: dict | 3.032158 | 3.010433 | 1.007217 |
redirect_uris = '%s://%s%s' % (request.scheme, request.get_host(), reverse('mastodon_callback'))
us = UserService.objects.get(user=user,
name='ServiceMastodon')
client_id, client_secret = MastodonAPI.create_app(
client_name="TriggerHappy"... | def check(self, request, user) | check if the service is well configured
:return: Boolean | 3.919655 | 3.827969 | 1.023951 |
if service.startswith('th_'):
cache = caches['django_th']
limit = settings.DJANGO_TH.get('publishing_limit', 0)
# publishing of all the data
if limit == 0:
return cache_data
# or just a set of them
if cache_data i... | def get_data(service, cache_data, trigger_id) | get the data from the cache
:param service: the service name
:param cache_data: the data from the cache
:type trigger_id: integer
:return: Return the data from the cache
:rtype: object | 5.773417 | 5.946646 | 0.97087 |
content = ''
if data.get(which_content):
if isinstance(data.get(which_content), feedparser.FeedParserDict):
content = data.get(which_content)['value']
elif not isinstance(data.get(which_content), str):
if 'value' in data.get(which_content)... | def _get_content(data, which_content) | get the content that could be hidden
in the middle of "content" or "summary detail"
from the data of the provider | 2.256484 | 2.206141 | 1.02282 |
content = self._get_content(data, 'content')
if content == '':
content = self._get_content(data, 'summary_detail')
if content == '':
if data.get('description'):
content = data.get('description')
return content | def set_content(self, data) | handle the content from the data
:param data: contains the data from the provider
:type data: dict
:rtype: string | 3.686217 | 3.840349 | 0.959865 |
model = get_model(kwargs['app_label'], kwargs['model_name'])
return model.objects.get(trigger_id=kwargs['trigger_id']) | def read_data(self, **kwargs) | get the data from the service
:param kwargs: contain keyword args : trigger_id and model name
:type kwargs: dict
:rtype: model | 6.084301 | 4.271781 | 1.424301 |
cache = caches['django_th']
cache_data = cache.get(kwargs.get('cache_stack') + '_' + kwargs.get('trigger_id'))
return PublishingLimit.get_data(kwargs.get('cache_stack'), cache_data, int(kwargs.get('trigger_id'))) | def process_data(self, **kwargs) | get the data from the cache
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict | 9.535865 | 7.940144 | 1.200969 |
title = self.set_title(data)
title = HtmlEntities(title).html_entity_decode
content = self.set_content(data)
content = HtmlEntities(content).html_entity_decode
if data.get('output_format'):
# pandoc to convert tools
import pypandoc
con... | def save_data(self, trigger_id, **data) | used to save data to the service
but first of all
make some work about the data to find
and the data to convert
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
... | 4.725685 | 5.283847 | 0.894364 |
service = self.service.split('Service')[1].lower()
return_to = '{service}_callback'.format(service=service)
return '%s://%s%s' % (request.scheme, request.get_host(), reverse(return_to)) | def callback_url(self, request) | the url to go back after the external service call
:param request: contains the current session
:type request: dict
:rtype: string | 4.104013 | 4.64079 | 0.884335 |
if self.oauth == 'oauth1':
token = self.callback_oauth1(request, **kwargs)
else:
token = self.callback_oauth2(request)
service_name = ServicesActivated.objects.get(name=self.service)
UserService.objects.filter(user=request.user, name=service_name).updat... | def callback(self, request, **kwargs) | Called from the Service when the user accept to activate it
the url to go back after the external service call
:param request: contains the current session
:param kwargs: keyword args
:type request: dict
:type kwargs: dict
:rtype: string | 4.869054 | 4.966393 | 0.9804 |
if kwargs.get('access_token') == '' or kwargs.get('access_token') is None:
access_token = self.get_access_token(request.session['oauth_token'],
request.session.get('oauth_token_secret', ''),
re... | def callback_oauth1(self, request, **kwargs) | Process for oAuth 1
:param request: contains the current session
:param kwargs: keyword args
:type request: dict
:type kwargs: dict
:rtype: string | 2.632844 | 2.718054 | 0.968651 |
callback_url = self.callback_url(request)
oauth = OAuth2Session(client_id=self.consumer_key, redirect_uri=callback_url, scope=self.scope)
request_token = oauth.fetch_token(self.REQ_TOKEN,
code=request.GET.get('code', ''),
... | def callback_oauth2(self, request) | Process for oAuth 2
:param request: contains the current session
:return: | 2.823236 | 3.028152 | 0.932329 |
if self.oauth == 'oauth1':
oauth = OAuth1Session(self.consumer_key, client_secret=self.consumer_secret)
request_token = oauth.fetch_request_token(self.REQ_TOKEN)
# Save the request token information for later
request.session['oauth_token'] = request_token... | def get_request_token(self, request) | request the token to the external service | 2.019736 | 1.983088 | 1.018481 |
# Using OAuth1Session
oauth = OAuth1Session(self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=oauth_token,
resource_owner_secret=oauth_token_secret,
ve... | def get_access_token(self, oauth_token, oauth_token_secret, oauth_verifier) | get the access token
the url to go back after the external service call
:param oauth_token: oauth token
:param oauth_token_secret: oauth secret token
:param oauth_verifier: oauth verifier
:type oauth_token: string
:type oauth_token_secret: string
... | 2.346754 | 2.458639 | 0.954493 |
TriggerService.objects.filter(consumer__name__id=pk).update(consumer_failed=0, provider_failed=0)
TriggerService.objects.filter(provider__name__id=pk).update(consumer_failed=0, provider_failed=0) | def reset_failed(self, pk) | reset failed counter
:param pk:
:return: | 3.900018 | 4.187616 | 0.931322 |
if settings.DJANGO_TH.get('digest_event'):
t = TriggerService.objects.get(id=trigger_id)
if t.provider.duration != 'n':
kwargs = {'user': t.user, 'title': title, 'link': link, 'duration': t.provider.duration}
signals.digest_event.send(sender=t.p... | def send_digest_event(self, trigger_id, title, link='') | handling of the signal of digest
:param trigger_id:
:param title:
:param link:
:return: | 5.83155 | 5.769356 | 1.01078 |
date_triggered = kwargs.get('date_triggered')
trigger_id = kwargs.get('trigger_id')
kwargs['model_name'] = 'Evernote'
kwargs['app_label'] = 'th_evernote'
trigger = super(ServiceEvernote, self).read_data(**kwargs)
filter_string = self.set_evernote_filter(date_t... | def read_data(self, **kwargs) | get the data from the service
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list | 4.372887 | 4.266701 | 1.024887 |
new_date_triggered = arrow.get(str(date_triggered)[:-6],
'YYYY-MM-DD HH:mm:ss')
new_date_triggered = str(new_date_triggered).replace(
':', '').replace('-', '').replace(' ', '')
date_filter = "created:{} ".format(new_date_triggered[:-6]... | def set_evernote_filter(self, date_triggered, trigger) | build the filter that will be used by evernote
:param date_triggered:
:param trigger:
:return: filter | 3.193781 | 3.227277 | 0.989621 |
data = []
note_store = self.client.get_note_store()
our_note_list = note_store.findNotesMetadata(self.token, evernote_filter, 0, 100,
EvernoteMgr.set_evernote_spec())
for note in our_note_list.notes:
whole_note =... | def get_evernote_notes(self, evernote_filter) | get the notes related to the filter
:param evernote_filter: filtering
:return: notes | 3.963334 | 4.040585 | 0.980881 |
# set the title and content of the data
title, content = super(ServiceEvernote, self).save_data(trigger_id, **data)
# get the evernote data of this trigger
trigger = Evernote.objects.get(trigger_id=trigger_id)
# initialize notestore process
note_store = self._not... | def save_data(self, trigger_id, **data) | let's save the data
don't want to handle empty title nor content
otherwise this will produce an Exception by
the Evernote's API
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_... | 5.622969 | 5.551009 | 1.012963 |
note = Types.Note()
if trigger.notebook:
# get the notebookGUID ...
notebook_id = EvernoteMgr.get_notebook(note_store, trigger.notebook)
# create notebookGUID if it does not exist then return its id
note.notebookGuid = EvernoteMgr.set_notebook(not... | def _notebook(trigger, note_store) | :param trigger: trigger object
:param note_store: note_store object
:return: note object | 4.132634 | 4.004283 | 1.032053 |
# attribute of the note: the link to the website
note_attribute = EvernoteMgr.set_note_attribute(data)
if note_attribute:
note.attributes = note_attribute
return note | def _attributes(note, data) | attribute of the note
:param note: note object
:param data:
:return: | 11.710556 | 11.556524 | 1.013329 |
# footer of the note
footer = EvernoteMgr.set_note_footer(data, trigger)
content += footer
return content | def _footer(trigger, data, content) | footer of the note
:param trigger: trigger object
:param data: data to be used
:param content: add the footer of the note to the content
:return: content string | 16.010098 | 14.430592 | 1.109455 |
note.content = EvernoteMgr.set_header()
note.content += sanitize(content)
return note | def _content(note, content) | content of the note
:param note: note object
:param content: content string to make the main body of the note
:return: | 24.496571 | 27.031563 | 0.906221 |
if token:
return EvernoteClient(token=token, sandbox=self.sandbox)
else:
return EvernoteClient(consumer_key=self.consumer_key, consumer_secret=self.consumer_secret,
sandbox=self.sandbox) | def get_evernote_client(self, token=None) | get the token from evernote | 1.836857 | 1.747972 | 1.05085 |
client = self.get_evernote_client()
request_token = client.get_request_token(self.callback_url(request))
# Save the request token information for later
request.session['oauth_token'] = request_token['oauth_token']
request.session['oauth_token_secret'] = request_token['oa... | def auth(self, request) | let's auth the user to the Service | 3.554729 | 3.526888 | 1.007894 |
try:
client = self.get_evernote_client()
# finally we save the user auth token
# As we already stored the object ServicesActivated
# from the UserServiceCreateView now we update the same
# object to the database so :
# 1) we get th... | def callback(self, request, **kwargs) | Called from the Service when the user accept to activate it | 8.456641 | 8.344983 | 1.01338 |
data['output_format'] = 'md'
title, content = super(ServiceTrello, self).save_data(trigger_id, **data)
if len(title):
# get the data of this trigger
t = Trello.objects.get(trigger_id=trigger_id)
# footer of the card
footer = self.set_card_... | def save_data(self, trigger_id, **data) | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | 4.335387 | 4.388964 | 0.987793 |
footer = ''
if data.get('link'):
provided_by = _('Provided by')
provided_from = _('from')
footer_from = "<br/><br/>{} <em>{}</em> {} <a href='{}'>{}</a>"
description = trigger.trigger.description
footer = footer_from.format(provided_by... | def set_card_footer(data, trigger) | handle the footer of the note | 4.060888 | 4.021085 | 1.009899 |
request_token = super(ServiceTrello, self).auth(request)
callback_url = self.callback_url(request)
# URL to redirect user to, to authorize your app
auth_url_str = '{auth_url}?oauth_token={token}'
auth_url_str += '&scope={scope}&name={name}'
auth_url_str += '&exp... | def auth(self, request) | let's auth the user to the Service
:param request: request object
:return: callback url
:rtype: string that contains the url to redirect after auth | 2.754805 | 2.809074 | 0.980681 |
return super(ServiceTrello, self).callback(request, **kwargs) | def callback(self, request, **kwargs) | Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template | 10.179757 | 11.989493 | 0.849056 |
trigger_id = kwargs.get('trigger_id')
date_triggered = str(kwargs.get('date_triggered')).replace(' ', 'T')
data = list()
if self.token:
# check if it remains more than 1 access
# then we can create an issue
if self.gh.ratelimit_remaining > 1:
... | def read_data(self, **kwargs) | get the data from the service
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list | 5.136499 | 5.014332 | 1.024364 |
if self.token:
title = self.set_title(data)
body = self.set_content(data)
# get the details of this trigger
trigger = Github.objects.get(trigger_id=trigger_id)
# check if it remains more than 1 access
# then we can create an issue... | def save_data(self, trigger_id, **data) | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | 6.019549 | 6.060327 | 0.993271 |
try:
auth = self.gh.authorize(self.username,
self.password,
self.scope,
'',
'',
self.consumer_key,
... | def auth(self, request) | let's auth the user to the Service
:param request: request object
:return: callback url
:rtype: string that contains the url to redirect after auth | 5.128627 | 4.902983 | 1.046022 |
access_token = request.session['oauth_token'] + "#TH#"
access_token += str(request.session['oauth_id'])
kwargs = {'access_token': access_token}
return super(ServiceGithub, self).callback(request, **kwargs) | def callback(self, request, **kwargs) | Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template | 8.048542 | 8.080762 | 0.996013 |
trigger_id = kwargs.get('trigger_id')
trigger = Reddit.objects.get(trigger_id=trigger_id)
date_triggered = arrow.get(kwargs.get('date_triggered'))
data = list()
submissions = self.reddit.subreddit(trigger.subreddit).top('day')
for submission in submissions:
... | def read_data(self, **kwargs) | get the data from the service
as the pocket service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at le... | 3.995079 | 3.928513 | 1.016944 |
# convert the format to be released in Markdown
status = False
data['output_format'] = 'md'
title, content = super(ServiceReddit, self).save_data(trigger_id, **data)
if self.token:
trigger = Reddit.objects.get(trigger_id=trigger_id)
if trigger.sha... | def save_data(self, trigger_id, **data) | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | 4.741076 | 4.784158 | 0.990995 |
code = request.GET.get('code', '')
redirect_uri = '%s://%s%s' % (request.scheme, request.get_host(), reverse("reddit_callback"))
reddit = RedditApi(client_id=self.consumer_key,
client_secret=self.consumer_secret,
redirect_uri=redirec... | def callback(self, request, **kwargs) | Called from the Service when the user accept to activate it
the url to go back after the external service call
:param request: contains the current session
:param kwargs: keyword args
:type request: dict
:type kwargs: dict
:rtype: string | 3.088687 | 3.028711 | 1.019802 |
trigger_id = kwargs.get('trigger_id')
data = list()
kwargs['model_name'] = 'Tumblr'
kwargs['app_label'] = 'th_tumblr'
super(ServiceTumblr, self).read_data(**kwargs)
cache.set('th_tumblr_' + str(trigger_id), data)
return data | def read_data(self, **kwargs) | get the data from the service
as the pocket service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at le... | 5.477273 | 5.190349 | 1.05528 |
from th_tumblr.models import Tumblr
title, content = super(ServiceTumblr, self).save_data(trigger_id, **data)
# get the data of this trigger
trigger = Tumblr.objects.get(trigger_id=trigger_id)
# we suppose we use a tag property for this service
status = self.tu... | def save_data(self, trigger_id, **data) | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | 6.30406 | 6.107118 | 1.032248 |
request_token = super(ServiceTumblr, self).auth(request)
callback_url = self.callback_url(request)
# URL to redirect user to, to authorize your app
auth_url_str = '{auth_url}?oauth_token={token}'
auth_url_str += '&oauth_callback={callback_url}'
auth_url = auth_u... | def auth(self, request) | let's auth the user to the Service
:param request: request object
:return: callback url
:rtype: string that contains the url to redirect after auth | 3.159702 | 3.177927 | 0.994265 |
obj = User.objects.get(id=self.request.user.id)
return obj | def get_object(self, queryset=None) | get only the data of the current user
:param queryset:
:return: | 4.172309 | 4.002919 | 1.042317 |
triggers_enabled = triggers_disabled = services_activated = ()
context = super(TriggerListView, self).get_context_data(**kwargs)
if self.kwargs.get('trigger_filtered_by'):
page_link = reverse('trigger_filter_by',
kwargs={'trigger_filtered_by... | def get_context_data(self, **kwargs) | get the data of the view
data are :
1) number of triggers enabled
2) number of triggers disabled
3) number of activated services
4) list of activated services by the connected user | 2.739172 | 2.469673 | 1.109123 |
data = feedparser.parse(self.URL_TO_PARSE, agent=self.USER_AGENT)
# when chardet says
# >>> chardet.detect(data)
# {'confidence': 0.99, 'encoding': 'utf-8'}
# bozo says sometimes
# >>> data.bozo_exception
# CharacterEncodingOverride('document declared as... | def datas(self) | read the data from a given URL or path to a local file | 14.195175 | 13.879486 | 1.022745 |
default_provider.load_services()
service_name = kwargs.get('service_name')
service_object = default_provider.get_service(service_name)
lets_callback = getattr(service_object, 'callback')
# call the auth func from this class
# and redirect to the external service page
# to auth the appli... | def finalcallback(request, **kwargs) | let's do the callback of the related service after
the auth request from UserServiceCreateView | 11.511854 | 10.995001 | 1.047008 |
from django.db import connection
connection.close()
failed_tries = settings.DJANGO_TH.get('failed_tries', 10)
trigger = TriggerService.objects.filter(
Q(provider_failed__lte=failed_tries) |
Q(consumer_failed__lte=failed_tries),
status=True,
... | def handle(self, *args, **options) | get all the triggers that need to be handled | 4.608788 | 4.327753 | 1.064938 |
'''
this method permits to reduce the quantity of information to read
by applying some filtering
here '*filers' can receive a list of properties to be filtered
'''
# special case : no filter : want to read all the feed
if self.match == "" and self.does... | def check(self, datas, *filers) | this method permits to reduce the quantity of information to read
by applying some filtering
here '*filers' can receive a list of properties to be filtered | 7.458925 | 4.883305 | 1.527434 |
'''
this method just use the module 're' to check if the data contain
the string to find
'''
import re
prog = re.compile(criteria)
return True if prog.match(data) else False | def filter_that(self, criteria, data) | this method just use the module 're' to check if the data contain
the string to find | 11.495568 | 3.3818 | 3.399246 |
self.date_triggered = arrow.get(kwargs.get('date_triggered'))
self.trigger_id = kwargs.get('trigger_id')
self.user = kwargs.get('user', '')
responses = self._get_wall_data()
data = []
try:
json_data = responses.json()
for d in json_data... | def read_data(self, **kwargs) | get the data from the service
as the pocket service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at le... | 3.923006 | 3.717062 | 1.055405 |
us = UserService.objects.get(user=self.user, name='ServiceWallabag')
params = {
'client_id': us.client_id,
'client_secret': us.client_secret,
'username': us.username,
'password': us.password,
}
try:
token = Wall.get_tok... | def wall(self) | refresh the token from the API
then call a Wallabag instance
then store the token
:return: wall instance | 3.855155 | 3.417674 | 1.128005 |
status = False
if data.get('link') and len(data.get('link')) > 0:
wall = self.wall()
if wall is not False:
try:
wall.post_entries(url=data.get('link').encode(), title=title, tags=(tags.lower()))
logger.debug('wallab... | def _create_entry(self, title, data, tags) | create an entry
:param title: string
:param data: dict
:param tags: list
:return: boolean | 6.901663 | 6.804991 | 1.014206 |
self.trigger_id = trigger_id
trigger = Wallabag.objects.get(trigger_id=trigger_id)
title = self.set_title(data)
if title is not None:
# convert htmlentities
title = HtmlEntities(title).html_entity_decode
return self._create_entry(title, dat... | def save_data(self, trigger_id, **data) | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | 8.394208 | 8.806642 | 0.953168 |
service = UserService.objects.get(user=request.user, name='ServiceWallabag')
callback_url = '%s://%s%s' % (request.scheme, request.get_host(), reverse('wallabag_callback'))
params = {'username': service.username,
'password': service.password,
'client_... | def auth(self, request) | let's auth the user to the Service
:param request: request object
:return: callback url
:rtype: string that contains the url to redirect after auth | 3.637119 | 3.684282 | 0.987199 |
try:
UserService.objects.filter(
user=request.user,
name=ServicesActivated.objects.get(name='ServiceWallabag')
)
except KeyError:
return '/'
return 'wallabag/callback.html' | def callback(self, request, **kwargs) | Called from the Service when the user accept to activate it
:param request: request object
:return: callback url
:rtype: string , path to the template | 13.232958 | 11.402845 | 1.160496 |
us = UserService.objects.get(user=user, name='ServiceWallabag')
params = {'username': us.username,
'password': us.password,
'client_id': us.client_id,
'client_secret': us.client_secret}
try:
Wall.get_token(host=us.host, ... | def check(self, request, user) | check if the service is well configured
:return: Boolean | 5.527236 | 5.148848 | 1.07349 |
default_provider.load_services()
service = get_object_or_404(ServicesActivated, pk=pk)
service_name = str(service.name)
service_object = default_provider.get_service(service_name)
lets_auth = getattr(service_object, 'auth')
getattr(service_object, 'reset_failed')(pk=pk)
return redirect(... | def renew_service(request, pk) | renew an existing service
:param request object
:param pk: the primary key of the service to renew
:type pk: int | 5.942857 | 6.933805 | 0.857085 |
context = super(UserServiceUpdateView, self).get_context_data(**kwargs)
context['service_name_alone'] = self.object.name.name.rsplit('Service')[1]
context['service_name'] = self.object.name.name
context['SERVICES_AUTH'] = settings.SERVICES_AUTH
context['SERVICES_HOSTED_W... | def get_context_data(self, **kwargs) | push data from settings and from the current object, in the current
context
:param kwargs:
:return: | 3.864817 | 3.949616 | 0.97853 |
kwargs = super(UserServiceUpdateView, self).get_form_kwargs()
kwargs['initial']['user'] = self.request.user
kwargs['initial']['name'] = self.object.name
return kwargs | def get_form_kwargs(self) | initialize default value that won't be displayed
:return: | 3.210964 | 3.40481 | 0.943067 |
valid = True
# 'name' is injected in the clean() of the form line 56
name = form.cleaned_data.get('name').name
user = self.request.user
form.save(user=user, service_name=name)
sa = ServicesActivated.objects.get(name=name)
if sa.auth_required and sa.self_... | def form_valid(self, form) | save the data
:param form:
:return: | 5.885531 | 5.996773 | 0.98145 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.