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 polynomials with
increasing exponent.
Examples:
>>> print(prange(4))
[1, q0, q0^2, q0^3]
>>> print(prange(4, dim=3))
[1, q2, q2^2, q2^3] | 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+q2
>>> print(rolldim(P))
q0^2+q2^3+q1 | 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.keys:
val = P.A[key]
key = list(key)
key[dim1], key[dim2] = key[dim2], key[dim1]
A[tuple(key)] = val
return Poly(A, dim, shape, dtype) | 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 = x**4-y
>>> print(P)
q0^4-q1
>>> print(swapdim(P))
q1^4-q0 | 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 out | 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(variable(3))
[q0, q1, q2] | 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.
Returns:
(Poly, numpy.ndarray):
Same type as A.
Examples:
>>> P = chaospy.prange(3)*2**-numpy.arange(0, 6, 2, float)
>>> print(P)
[1.0, 0.25q0, 0.0625q0^2]
>>> print(chaospy.around(P))
[1.0, 0.0, 0.0]
>>> print(chaospy.around(P, 2))
[1.0, 0.25q0, 0.06q0^2] | 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.arange(0, 6, 2, float))
>>> print(P)
0.0625q0^2+0.25q0+1.0
>>> print(chaospy.prune(P, 0.1))
0.25q0+1.0
>>> print(chaospy.prune(P, 0.5))
1.0
>>> print(chaospy.prune(P, 1.5))
0.0 | 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.evaluate_bound(
dist, xloc_, cache=cache).flatten()
return uloc | 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.evaluate_bound(
dist, xloc_, cache=cache)[:, 0]
cache[dist] = xloc_
return uloc | 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 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(dist.range([[-0.5, 0.5, 1.5], [0, 1, 2]]))
[[[ 0. 0. 0. ]
[-0.5 0.5 1.5]]
<BLANKLINE>
[[ 1. 1. 1. ]
[ 0.5 1.5 2.5]]] | 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_density(
dist, xloc_, cache=cache)[0]
return floc | 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.pdf([[-0.5, 0.5, 1.5], [0, 1, 2]]))
[0. 1. 0.] | 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_inverse(
dist, qloc_, cache=cache)[0]
return xloc | 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, d0+chaospy.Uniform())
>>> 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.4 0.5 0.7]] | 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:
continue
idx = self.inverse_map[dist]
kloc_ = kloc[idx].reshape(1)
output *= evaluation.evaluate_moment(dist, kloc_, cache=cache)
return output | 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, 1]), 4))
0.5833 | 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 in self.inverse_map:
continue
idx = self.inverse_map[dist]
kloc_ = kloc[idx].reshape(1)
values = evaluation.evaluate_recurrence_coefficients(
dist, kloc_, cache=cache)
output.T[idx] = values.T
return output | 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>
[[1. 2. 3. ]
[3. 5. 7. ]
[1. 4. 9. ]]]
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(numpy.around(dist.ttr([1, 1]), 4)) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
chaospy.distributions.baseclass.StochasticallyDependentError: Joint ... | 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, return p-value as well.
Returns:
(float, numpy.ndarray):
Correlation output ``rho``. Of type float if two-dimensional problem.
Correleation matrix if larger.
(float, numpy.ndarray):
The two-sided p-value for a hypothesis test whose null hypothesis
is that two sets of data are uncorrelated, has same dimension as
``rho``. | 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_)
x_[-1] = 1
out2 += (-1)**sum(I)*foo(x_)
out = out1/out2
return out | 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,
user__is_active=True,
provider__name__status=True,
consumer__name__status=True,
).select_related('consumer__name', 'provider__name')
try:
with Pool(processes=settings.DJANGO_TH.get('processes')) as pool:
p = Pub()
result = pool.map_async(p.publishing, trigger)
result.get(timeout=60)
except TimeoutError as e:
logger.warning(e) | 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)
if self.title_or_content(title):
content = str("{title} {link}").format(title=title, link=data.get('link'))
content += get_tags(Twitter, trigger_id)
else:
content = self.set_twitter_content(content)
try:
self.twitter_api.update_status(status=content)
status = True
except Exception as inst:
logger.critical("Twitter ERR {}".format(inst))
update_result(trigger_id, msg=inst, status=False)
status = False
return status | 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_token_secret'] = req_token['oauth_token_secret']
return req_token['auth_url'] | 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
:type oauth_token_secret: string
:type oauth_verifier: string
:return: access_token
:rtype: dict | 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('type_action', '')
# set the bot username of Slack to the name of the
# provider service
username = service.provider.name.name.split('Service')[1]
# 'build' a link
title_link = ''
if data.get('permalink'):
title_link = ': <' + data.get('permalink') + '|' + title + '>'
else:
title_link = ': <' + data.get('link') + '|' + title + '>'
data = '*' + desc + '*: ' + type_action + title_link
payload = {'username': username,
'text': data}
r = requests.post(slack.webhook_url, json=payload)
if r.status_code == requests.codes.ok:
status = True
# return the data
return status | 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_TH.get('failed_tries', 10)
).select_related('consumer__name', 'provider__name')
try:
with Pool(processes=1) as pool:
r = Read()
result = pool.map_async(r.reading, trigger)
result.get(timeout=360)
p = Pub()
result = pool.map_async(p.publishing, trigger)
result.get(timeout=360)
cache.delete('django_th' + '_fire_trigger_' + str(trigger_id))
except TimeoutError as e:
logger.warning(e) | 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 = arrow.get(p.get('created'))
if created > date_triggered and p.get('type') == trigger.type and\
(p.get('sender_email') == p.get('receiver_email') or p.get('sender_email') is None):
title = title + ' Channel' if p.get('channel_iden') and p.get('title') is None else title
# if sender_email and receiver_email are the same ;
# that means that "I" made a note or something
# if sender_email is None, then "an API" does the post
body = p.get('body')
data.append({'title': title, 'content': body})
# digester
self.send_digest_event(trigger_id, title, '')
cache.set('th_pushbullet_' + str(trigger_id), data)
return data | 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 at least
:type kwargs: dict
:rtype: list | 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 trigger.type == 'link':
status = self.pushb.push_link(title=title, body=content, url=data.get('link'))
sentence = str('pushbullet {} created').format(title)
logger.debug(sentence)
else:
# no valid type of pushbullet specified
msg = "no valid type of pushbullet specified"
logger.critical(msg)
update_result(trigger_id, msg=msg, status=False)
status = False
else:
msg = "no token or link provided for trigger ID {} ".format(trigger_id)
logger.critical(msg)
update_result(trigger_id, msg=msg, status=False)
status = False
return status | 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)
elif action == 'delete':
t.delete(taiga_obj, data)
return data | 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:
getattr(service_consumer, '__init__')(service.consumer.token, **kwargs)
status = getattr(service_consumer, 'save_data')(service.id, **data)
return status | 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, status=False)
status = False
return status | 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 trigger have been started
# timestamp form
pockets = self.pocket.get(since=since, state="unread")
content = ''
if pockets is not None and len(pockets[0]['list']) > 0:
for my_pocket in pockets[0]['list'].values():
if my_pocket.get('excerpt'):
content = my_pocket['excerpt']
elif my_pocket.get('given_title'):
content = my_pocket['given_title']
my_date = arrow.get(str(date_triggered), 'YYYY-MM-DD HH:mm:ss').to(settings.TIME_ZONE)
data.append({'my_date': str(my_date),
'tag': '',
'link': my_pocket['given_url'],
'title': my_pocket['given_title'],
'content': content,
'tweet_id': 0})
# digester
self.send_digest_event(trigger_id, my_pocket['given_title'], my_pocket['given_url'])
cache.set('th_pocket_' + 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 least
:type kwargs: dict
:rtype: list | 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)
# convert htmlentities
title = HtmlEntities(title).html_entity_decode
status = self._create_entry(url=data.get('link'),
title=title,
tags=(trigger.tag.lower()))
else:
msg = "no link provided for trigger ID {}, so we ignore it".format(trigger_id)
logger.warning(msg)
update_result(trigger_id, msg=msg, status=True)
status = True
else:
msg = "no token provided for trigger ID {}".format(trigger_id)
logger.critical(msg)
update_result(trigger_id, msg=msg, status=False)
status = False
return status | 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 authorize your app
auth_url = Pocket.get_auth_url(code=request_token, redirect_uri=callback_url)
return auth_url | 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)
# if not then use the content
else:
content += " " + data.get('link') + " " + get_tags(Mastodon, trigger_id)
content = self.set_mastodon_content(content)
us = UserService.objects.get(user=self.user, token=self.token, name='ServiceMastodon')
try:
toot_api = MastodonAPI(client_id=us.client_id, client_secret=us.client_secret, access_token=self.token,
api_base_url=us.host)
except ValueError as e:
logger.error(e)
status = False
update_result(trigger_id, msg=e, status=status)
media_ids = None
try:
if settings.DJANGO_TH['sharing_media']:
# do we have a media in the content ?
content, media = self.media_in_content(content)
if media:
# upload the media first
media_ids = toot_api.media_post(media_file=media)
media_ids = [media_ids]
toot_api.status_post(content, media_ids=media_ids)
status = True
except Exception as inst:
logger.critical("Mastodon ERR {}".format(inst))
status = False
update_result(trigger_id, msg=inst, status=status)
return status | 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/media/{}.jpg'.format(m.group(1))
local_file = download_image(url)
content = re.sub(r'https://pbs.twimg.com/media/([\w\-_]+).jpg', '', # NOQA
content)
return content, local_file
return content, local_file | 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_secret = MastodonAPI.create_app(
client_name="TriggerHappy", api_base_url=us.host,
redirect_uris=redirect_uris)
us.client_id = client_id
us.client_secret = client_secret
us.save()
us = UserService.objects.get(user=request.user,
name='ServiceMastodon')
# get the token by logging in
mastodon = MastodonAPI(
client_id=client_id,
client_secret=client_secret,
api_base_url=us.host
)
token = mastodon.log_in(username=us.username, password=us.password)
us.token = token
us.save()
return self.callback_url(request) | 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", api_base_url=us.host,
redirect_uris=redirect_uris)
# get the token by logging in
mastodon = MastodonAPI(
client_id=client_id,
client_secret=client_secret,
api_base_url=us.host
)
try:
mastodon.log_in(username=us.username, password=us.password)
return True
except MastodonIllegalArgumentError as e:
return e | 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 is not None and len(cache_data) > limit:
for data in cache_data[limit:]:
service_str = ''.join((service, '_', str(trigger_id)))
# put that data in a version 2 of the cache
cache.set(service_str, data, version=2)
# delete data from cache version=1
# https://niwinz.github.io/django-redis/latest/#_scan_delete_keys_in_bulk
cache.delete_pattern(service_str)
# put in cache unpublished data
cache_data = cache_data[:limit]
return cache_data | 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)[0]:
content = data.get(which_content)[0].value
else:
content = data.get(which_content)
return 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
content = pypandoc.convert(content, str(data.get('output_format')), format='html')
return title, content | 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
:type data: dict
:return: the status of the save statement
:rtype: boolean | 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).update(token=token)
back = self.service.split('Service')[1].lower()
back_to = '{back_to}/callback.html'.format(back_to=back)
return back_to | 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', ''),
request.GET.get('oauth_verifier', ''))
else:
access_token = kwargs.get('access_token')
if type(access_token) == str:
token = access_token
else:
token = '#TH#'.join((access_token.get('oauth_token'), access_token.get('oauth_token_secret')))
return token | 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', ''),
authorization_response=callback_url,
client_secret=self.consumer_secret,
scope=self.scope,
verify=False)
return request_token.get('access_token') | 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['oauth_token']
request.session['oauth_token_secret'] = request_token['oauth_token_secret']
return request_token
else:
callback_url = self.callback_url(request)
oauth = OAuth2Session(client_id=self.consumer_key, redirect_uri=callback_url, scope=self.scope)
authorization_url, state = oauth.authorization_url(self.AUTH_URL)
return authorization_url | 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,
verifier=oauth_verifier)
oauth_tokens = oauth.fetch_access_token(self.ACC_TOKEN)
return oauth_tokens | 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
:type oauth_verifier: string
:rtype: dict | 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.provider.name, **kwargs) | 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_triggered, trigger)
evernote_filter = self.set_note_filter(filter_string)
data = self.get_evernote_notes(evernote_filter)
cache.set('th_evernote_' + str(trigger_id), data)
return data | 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])
notebook_filter = ''
if trigger.notebook:
notebook_filter = "notebook:{} ".format(trigger.notebook)
tag_filter = "tag:{} ".format(trigger.tag) if trigger.tag != '' else ''
complet_filter = ''.join((notebook_filter, tag_filter, date_filter))
return complet_filter | 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 = note_store.getNote(self.token, note.guid, True, True, False, False)
content = self._cleaning_content(whole_note.content)
data.append({'title': note.title, 'my_date': arrow.get(note.created),
'link': whole_note.attributes.sourceURL, 'content': content})
return data | 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._notestore(trigger_id, data)
if isinstance(note_store, evernote.api.client.Store):
# note object
note = self._notebook(trigger, note_store)
# its attributes
note = self._attributes(note, data)
# its footer
content = self._footer(trigger, data, content)
# its title
note.title = limit_content(title, 255)
# its content
note = self._content(note, content)
# create a note
return EvernoteMgr.create_note(note_store, note, trigger_id, data)
else:
# so its note an evernote object, so something wrong happens
return note_store | 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_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | 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(note_store, trigger.notebook, notebook_id)
if trigger.tag:
# ... and get the tagGUID if a tag has been provided
tag_id = EvernoteMgr.get_tag(note_store, trigger.tag)
if tag_id is False:
tag_id = EvernoteMgr.set_tag(note_store, trigger.tag, tag_id)
# set the tag to the note if a tag has been provided
if tag_id:
note.tagGuids = tag_id
logger.debug("notebook that will be used %s", trigger.notebook)
return note | 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['oauth_token_secret']
# Redirect the user to the Evernote authorization URL
# return the URL string which will be used by redirect()
# from the calling func
return client.get_authorize_url(request_token) | 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 the previous object
us = UserService.objects.get(user=request.user, name=ServicesActivated.objects.get(name='ServiceEvernote'))
# 2) then get the token
us.token = client.get_access_token(request.session['oauth_token'], request.session['oauth_token_secret'],
request.GET.get('oauth_verifier', ''))
# 3) and save everything
us.save()
except KeyError:
return '/'
return 'evernote/callback.html' | 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_footer(data, t)
content += footer
# 1 - we need to search the list and board where we will
# store the card so ...
# 1.a search the board_id by its name
# by retrieving all the boards
boards = self.trello_instance.list_boards()
board_id = ''
my_list = ''
for board in boards:
if t.board_name == board.name:
board_id = board.id
break
if board_id:
# 1.b search the list_id by its name
my_board = self.trello_instance.get_board(board_id)
lists = my_board.open_lists()
# just get the open list ; not all the archive ones
for list_in_board in lists:
# search the name of the list we set in the form
if t.list_name == list_in_board.name:
# return the (trello) list object to be able to add card at step 3
my_list = my_board.get_list(list_in_board.id)
break
# we didnt find the list in that board -> create it
if my_list == '':
my_list = my_board.add_list(t.list_name)
else:
# 2 if board_id and/or list_id does not exist, create it/them
my_board = self.trello_instance.add_board(t.board_name)
# add the list that didn't exists and return a (trello) list object
my_list = my_board.add_list(t.list_name)
# 3 create the card
my_list.add_card(title, content)
logger.debug(str('trello {} created').format(data['link']))
status = True
else:
sentence = "no token or link provided for trigger ID {}".format(trigger_id)
update_result(trigger_id, msg=sentence, status=False)
status = False
return status | 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, description, provided_from, data.get('link'), data.get('link'))
import pypandoc
footer = pypandoc.convert(footer, 'md', format='html')
return footer | 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 += '&expiration={expiry}&oauth_callback={callback_url}'
auth_url = auth_url_str.format(auth_url=self.AUTH_URL,
token=request_token['oauth_token'],
scope=self.scope,
name=self.app_name,
expiry=self.expiry,
callback_url=callback_url)
return auth_url | 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:
trigger = Github.objects.get(trigger_id=trigger_id)
issues = self.gh.issues_on(trigger.repo, trigger.project, since=date_triggered)
for issue in issues:
content = pypandoc.convert(issue.body, 'md', format='html')
content += self.gh_footer(trigger, issue)
data.append({'title': issue.title, 'content': content})
# digester
self.send_digest_event(trigger_id, issue.title, '')
cache.set('th_github_' + str(trigger_id), data)
else:
# rate limit reach, do nothing right now
logger.warning("Rate limit reached")
update_result(trigger_id, msg="Rate limit reached", status=True)
else:
logger.critical("no token provided")
update_result(trigger_id, msg="No token provided", status=True)
return data | 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
limit = self.gh.ratelimit_remaining
if limit > 1:
# repo goes to "owner"
# project goes to "repository"
r = self.gh.create_issue(trigger.repo, trigger.project, title, body)
else:
# rate limit reach
logger.warning("Rate limit reached")
update_result(trigger_id, msg="Rate limit reached", status=True)
# put again in cache the data that could not be
# published in Github yet
cache.set('th_github_' + str(trigger_id), data, version=2)
return True
sentence = str('github {} created').format(r)
logger.debug(sentence)
status = True
else:
sentence = "no token or link provided for trigger ID {} ".format(trigger_id)
logger.critical(sentence)
update_result(trigger_id, msg=sentence, status=False)
status = False
return status | 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,
self.consumer_secret)
request.session['oauth_token'] = auth.token
request.session['oauth_id'] = auth.id
except AuthenticationFailed as e:
messages.add_message(request, messages.ERROR, message="GITHUB RENEW FAILED : Reason {}".format(e))
return reverse('user_services')
return self.callback_url(request) | 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:
title = 'From Reddit ' + submission.title
created = arrow.get(submission.created).to(settings.TIME_ZONE)
if date_triggered is not None and created is not None \
and created >= date_triggered and not submission.is_self and trigger.share_link:
body = submission.selftext if submission.selftext else submission.url
data.append({'title': title, 'content': body})
self.send_digest_event(trigger_id, title, '')
cache.set('th_reddit_' + 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 least
:type kwargs: dict
:rtype: list | 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.share_link:
status = self.reddit.subreddit(trigger.subreddit).submit(title=title, url=content)
else:
status = self.reddit.subreddit(trigger.subreddit).submit(title=title, selftext=content)
sentence = str('reddit submission {} created').format(title)
logger.debug(sentence)
else:
msg = "no token or link provided for trigger ID {} ".format(trigger_id)
logger.critical(msg)
update_result(trigger_id, msg=msg, status=False)
return status | 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=redirect_uri,
user_agent=self.user_agent)
token = reddit.auth.authorize(code)
UserService.objects.filter(user=request.user, name='ServiceReddit').update(token=token)
return 'reddit/callback.html' | 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 least
:type kwargs: dict
:rtype: list | 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.tumblr.create_text(blogname=trigger.blogname,
title=title,
body=content,
state='published',
tags=trigger.tag)
return status | 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_url_str.format(auth_url=self.AUTH_URL,
token=request_token['oauth_token'],
callback_url=callback_url)
return auth_url | 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':
self.kwargs.get('trigger_filtered_by')})
elif self.kwargs.get('trigger_ordered_by'):
page_link = reverse('trigger_order_by',
kwargs={'trigger_ordered_by':
self.kwargs.get('trigger_ordered_by')})
else:
page_link = reverse('home')
if self.request.user.is_authenticated:
# get the enabled triggers
triggers_enabled = TriggerService.objects.filter(
user=self.request.user, status=1).count()
# get the disabled triggers
triggers_disabled = TriggerService.objects.filter(
user=self.request.user, status=0).count()
# get the activated services
user_service = UserService.objects.filter(user=self.request.user)
context['trigger_filter_by'] = user_service
services_activated = user_service.count()
context['nb_triggers'] = {'enabled': triggers_enabled,
'disabled': triggers_disabled}
context['nb_services'] = services_activated
context['page_link'] = page_link
context['fire'] = settings.DJANGO_TH.get('fire', False)
return context | 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 us-ascii, but parsed as utf-8', ) # invalid Feed
# so I remove this detection :(
# the issue come from the server that return a charset different from the feeds
# it is not related to Feedparser but from the HTTP server itself
if data.bozo == 1:
data.entries = ''
return data | 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 application django-th to access to the user
# account details
return render_to_response(lets_callback(request)) | 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,
user__is_active=True,
provider__name__status=True,
consumer__name__status=True,
).select_related('consumer__name', 'provider__name')
with ThreadPoolExecutor(max_workers=settings.DJANGO_TH.get('processes')) as executor:
r = Read()
for t in trigger:
executor.submit(r.reading, t) | 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_not_match == '':
yield datas
# let's filtering :
else:
condition1 = False
condition2 = False
# arg contain the property from which we want to check the 'data'
for prop in filers:
# check if my datas contains my property
if prop in datas:
# filter to find only this data
if self.match != '' and condition1 is False:
condition1 = self.filter_that(self.match,
datas[prop])
# filter to exclude this data,
# when found, continue to the next entry
if self.does_not_match != '' and condition2 is False:
condition2 = self.filter_that(self.does_not_match,
datas[prop])
if condition2:
continue
if condition1 and condition2 is False:
yield datas | 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['_embedded']['items']:
created_at = arrow.get(d.get('created_at'))
date_triggered = arrow.get(self.date_triggered)
if created_at > date_triggered:
data.append({'title': d.get('title'),
'content': d.get('content')})
# digester
self.send_digest_event(self.trigger_id,
d.get('title'),
link='')
if len(data) > 0:
cache.set('th_wallabag_' + str(self.trigger_id), data)
except Exception as e:
logger.critical(e)
update_result(self.trigger_id, msg=e, status=False)
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 least
:type kwargs: dict
:rtype: list | 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_token(host=us.host, **params)
except Exception as e:
update_result(self.trigger_id, msg=e, status=False)
logger.critical('{} {}'.format(self.user, e))
return False
wall = Wall(host=us.host, client_secret=us.client_secret,
client_id=us.client_id, token=token)
UserService.objects.filter(user=self.user,
name='ServiceWallabag').update(token=token)
return wall | 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('wallabag {} created'.format(data.get('link')))
status = True
except Exception as e:
logger.critical('issue with something else that a token link ? : {}'.format(data.get('link')))
logger.critical(e)
update_result(self.trigger_id, msg=e, status=False)
status = False
else:
status = True # we ignore empty link
return status | 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, data, trigger.tag)
else:
# we ignore data without title so return True to let
# the process continue without
# raising exception
return True | 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_id': service.client_id,
'client_secret': service.client_secret}
access_token = Wall.get_token(host=service.host, **params)
request.session['oauth_token'] = access_token
return callback_url | 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, **params)
return True
except requests.exceptions.HTTPError as e:
return e | 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(lets_auth(request)) | 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_WITH_AUTH'] = settings.SERVICES_HOSTED_WITH_AUTH
context['SERVICES_NEUTRAL'] = settings.SERVICES_NEUTRAL
context['action'] = 'edit'
return context | 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_hosted:
# trigger the checking of the service
from django_th.services import default_provider
default_provider.load_services()
service_provider = default_provider.get_service(name)
result = service_provider.check(self.request, user)
if result is not True:
# the call of the API failed due to an error which is in the result string
# return by the call of the API
form.add_error('host', result)
messages.error(self.request, result)
return redirect('edit_service', pk=self.kwargs.get(self.pk_url_kwarg))
if valid:
messages.success(self.request, _('Service %s modified successfully') % name.split('Service')[1])
return HttpResponseRedirect(reverse('user_services')) | 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.