commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
c1335e241e4d39df1cd07b811f7ffd70ac923bdc | Fix broken tests | skwashd/python-acquia-cloud | acapi/resources/acquiaresource.py | acapi/resources/acquiaresource.py | """Generic Acquia Cloud API resource."""
from acapi.resources.acquiadata import AcquiaData
class AcquiaResource(AcquiaData):
"""Acquia Cloud API resource."""
#: Valid properties for this resource object
valid_keys = None
def __getitem__(self, key):
"""Get the value of an object property."""
if self.data is None:
self.get()
if self.valid_keys is not None and key in self.valid_keys:
return self.data[key]
def get(self):
"""Return the resource from the Acquia Cloud API."""
if self.data is None:
response = self.request()
self.data = response
return self.data
| """Generic Acquia Cloud API resource."""
from acapi.resources.acquiadata import AcquiaData
class AcquiaResource(AcquiaData):
"""Acquia Cloud API resource."""
#: Valid properties for this resource object
valid_keys = None
def __getitem__(self, key):
"""Get the value of an object property."""
if self.data is None:
self.get()
if self.valid_keys is None and key in self.valid_keys:
return self.data[key]
def get(self):
"""Return the resource from the Acquia Cloud API."""
if self.data is None:
response = self.request()
self.data = response
return self.data
| mit | Python |
12cf7d220408971509b57cb3a60f2d87b4a37477 | Revert "Add support for server side authentication." | jgoclawski/django-facebook-auth,pozytywnie/django-facebook-auth,pozytywnie/django-facebook-auth,jgoclawski/django-facebook-auth | facebook_auth/models.py | facebook_auth/models.py | from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
| from uuid import uuid1
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
def get_auth_address(request, redirect_to, scope=''):
state = unicode(uuid1())
request.session['state'] = state
return 'https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s&state=%s' % (
settings.FACEBOOK_APP_ID, redirect_to, scope, state
)
| mit | Python |
b88a7f03b43d8f2b1ceb34827295d37b7cd714e6 | Implement UserToken manager class. | pozytywnie/django-facebook-auth,pozytywnie/django-facebook-auth,jgoclawski/django-facebook-auth,jgoclawski/django-facebook-auth | facebook_auth/models.py | facebook_auth/models.py | import json
import logging
from django.contrib.auth import models as auth_models
from django.db import models
from django.utils import timezone
import facepy
from facebook_auth import utils
logger = logging.getLogger(__name__)
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
access_token_expiration_date = models.DateTimeField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return json.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
response = utils.get_from_graph_api(self.graph, "me/friends")
if 'data' in response:
return response['data']
logger.warning("OpenGraph error: %s" % response)
return []
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
existing_friends = self.app_friends.all().values_list('user_id', flat=True)
new_friends = FacebookUser.objects.filter(user_id__in=friends_ids).exclude(user_id__in=existing_friends)
removed_friends = self.app_friends.exclude(user_id__in=friends_ids)
self.app_friends.add(*new_friends)
self.app_friends.remove(*removed_friends)
class UserToken(models.Model):
provider_user_id = models.CharField(max_length=255)
token = models.TextField()
expiration_date = models.DateTimeField(blank=True, null=True)
deleted = models.BooleanField(default=False)
class Meta:
verbose_name = 'User token'
verbose_name_plural = 'User tokens'
class UserTokenManager(object):
@staticmethod
def insert_token(provider_user_id, token, expiration_date):
UserToken.objects.get_or_create(provider_user_id=provider_user_id,
token=token,
expiration_date=expiration_date)
@staticmethod
def get_access_token(provider_user_id):
now = timezone.now()
return (UserToken.objects
.filter(provider_user_id=provider_user_id,
expiration_date__gt=now)
.latest('expiration_date'))
@staticmethod
def invalidate_access_token(token):
UserToken.objects.filter(token=token).update(deleted=True)
| import json
import logging
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
from facebook_auth import utils
logger = logging.getLogger(__name__)
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
access_token_expiration_date = models.DateTimeField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return json.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
response = utils.get_from_graph_api(self.graph, "me/friends")
if 'data' in response:
return response['data']
logger.warning("OpenGraph error: %s" % response)
return []
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
existing_friends = self.app_friends.all().values_list('user_id', flat=True)
new_friends = FacebookUser.objects.filter(user_id__in=friends_ids).exclude(user_id__in=existing_friends)
removed_friends = self.app_friends.exclude(user_id__in=friends_ids)
self.app_friends.add(*new_friends)
self.app_friends.remove(*removed_friends)
class UserToken(models.Model):
provider_user_id = models.CharField(max_length=255)
token = models.TextField()
expiration_date = models.DateTimeField(blank=True, null=True)
deleted = models.BooleanField(default=False)
class Meta:
verbose_name = 'User token'
verbose_name_plural = 'User tokens'
| mit | Python |
30322e79409de2ea0e1747deed44720fe2b24fd1 | Fix minor issues and add a comment to the flag version | e-koch/VLA_Lband,e-koch/VLA_Lband | 16B/pipeline4.6.0_custom/EVLA_Lband_RFI_flag.py | 16B/pipeline4.6.0_custom/EVLA_Lband_RFI_flag.py |
'''
Several portions of the L-band have constant RFI that is unrecoverable.
This is meant to be run in the pipeline environment to remove these regions
before wasting time trying to find solutions.
'''
from glob import glob
import os
from tasks import flagdata, flagmanager
logprint("Starting EVLA_Lband_RFI_flag.py", logfileout='logs/known_RFI_flag.log')
try:
ms_active
except NameError:
raise NameError("Run EVLA_pipe_restore.py")
# Check if the flag version already exists. If it does, skip the flagging and
# continue
needs_flagging = True
flag_folder = "{}.flagversions".format(ms_active)
if os.path.exists(flag_folder):
flag_versions = \
glob(os.path.join(flag_folder, "flags.known_RFI*"))
if len(flag_versions) != 0:
needs_flagging = False
if needs_flagging:
# Flag SPW 0, 1 and 4. The pipeline always fails for 0 and usually for 4.
# SPW 1 is always returned by the pipeline, but by-eye investigations and
# the VLA RFI plots show there are almost no RFI free channels.
default("flagdata")
flagdata(vis=ms_active, spw="0,1,4", flagbackup=False)
# Now remove specific portions of the other SPWs
# Channel ranges are for 16B, and are the regions that were found to
# persist over multiple SBs. Other strong RFI exists (SPW 6, for instance)
# but is intermittent.
# This leaves 438 good channels, or 68% of the recoverable 5 SPWs.
# This is 43% of the total BW. We assumed 60% recovered in the proposal.
# Using the sensitivity calculator, the difference in sensitivity is
# 1.88 uJy/bm vs. 1.63 uJy/bm over 48 hours. So not much of a difference.
spw2 = "2:0~20;42~54;83~96"
spw3 = "3:0~10;30;31;69;70"
spw5 = "5:52~67;112;113"
# spw6 = "" # There are two narrow, strong, but intermittent RFI sources
spw7 = "7:44~127"
flag_str = ",".join([spw2, spw3, spw5, spw7])
flagdata(vis=ms_active, spw=flag_str, flagbackup=False)
flagmanager(vis=ms_active, mode='save', versionname="known_RFI",
comment="Removal of constant L-band RFI in 16B. See "
"EVLA_Lband_RFI_flag.py")
else:
logprint("known_RFI flag version already exists. Skipping flagging.")
logprint("Finished EVLA_Lband_RFI_flag.py", logfileout='logs/known_RFI_flag.log')
|
'''
Several portions of the L-band have constant RFI that is unrecoverable.
This is meant to be run in the pipeline environment to remove these regions
before wasting time trying to find solutions.
'''
from glob import glob
import os
from tasks import flagdata, flagmanager
logprint("Starting EVLA_Lband_RFI_flag.py", logfileout='logs/known_RFI_flag.log')
try:
ms_active
except NameError:
raise NameError("Run EVLA_pipe_restore.py")
# Check if the flag version already exists. If it does, skip the flagging and
# continue
needs_flagging = True
flag_folder = "{}.flagversions".format(ms_active)
if os.path.exists(flag_folder):
flag_versions = \
glob(os.path.join(flag_folder, "flags.known_RFI*"))
if len(flag_versions) != 0:
needs_flagging = False
if needs_flagging:
# Flag SPW 0, 1 and 4. The pipeline always fails for 0 and usually for 4.
# SPW 1 is always returned by the pipeline, but by-eye investigations and
# the VLA RFI plots show there are almost no RFI free channels.
default("flagdata")
flagdata(vis=ms_active, spw="0,1,4", flagbackup=False)
# Now remove specific portions of the other SPWs
# Channel ranges are for 16B, and are the regions that were found to
# persist over multiple SBs. Other strong RFI exists (SPW 6, for instance)
# but is intermittent.
# This leaves 438 good channels, or 68% of the recoverable 5 SPWs.
# This is 43% of the total BW. We assumed 60% recovered in the proposal.
# Using the sensitivity calculator, the difference in sensitivity is
# 1.88 uJy/bm vs. 1.63 uJy/bm over 48 hours. So not much of a difference.
spw2 = "2:0~20;42~54;83~96"
spw3 = "3:0~10;30;31;48;49;69;70"
spw5 = "5:52~67;112;113"
# spw6 = "" # There are two narrow, strong, but intermittent RFI sources
spw7 = "7:44~"
flag_str = ",".join([spw2, spw3, spw5, spw7])
flagdata(vis=ms_active, spw=flag_str, flagbackup=False)
flagmanager(vis=ms_active, mode='save', versionname="known_RFI")
else:
logprint("known_RFI flag version already exists. Skipping flagging.")
logprint("Finished EVLA_Lband_RFI_flag.py", logfileout='logs/known_RFI_flag.log')
| mit | Python |
64079b449d272fa1e06206c89ed1ba680cade50a | Fix kick message | TitanEmbeds/Titan,TitanEmbeds/Titan,TitanEmbeds/Titan | discordbot/titanembeds/commands.py | discordbot/titanembeds/commands.py | class Commands():
def __init__(self, client, database):
self.client = client
self.database = database
async def ban(self, message):
serverid = message.server.id
content = message.content.strip()
if len(content.split()) == 2:
await self.client.send_message(message.channel, message.author.mention + " Please provide a username-query (or optionally a discriminator) to ban a guest user.\nExample: `ban Titan#0001`")
return
content = content.split()
username = content[2][:content[2].find("#")] if "#" in content[2] else content[2]
discriminator = int(content[2][content[2].find("#") + 1:]) if "#" in content[2] else None
reason = await self.database.ban_unauth_user_by_query(message.server.id, message.author.id, username, discriminator)
await self.client.send_message(message.channel, message.author.mention + " " + reason)
async def kick(self, message):
serverid = message.server.id
content = message.content.strip()
if len(content.split()) == 2:
await self.client.send_message(message.channel, message.author.mention + " Please provide a username-query (or optionally a discriminator) to kick a guest user.\nExample: `kick Titan#0001`")
return
content = content.split()
username = content[2][:content[2].find("#")] if "#" in content[2] else content[2]
discriminator = int(content[2][content[2].find("#") + 1:]) if "#" in content[2] else None
reason = await self.database.revoke_unauth_user_by_query(message.server.id, username, discriminator)
await self.client.send_message(message.channel, message.author.mention + " " + reason)
| class Commands():
def __init__(self, client, database):
self.client = client
self.database = database
async def ban(self, message):
serverid = message.server.id
content = message.content.strip()
if len(content.split()) == 2:
await self.client.send_message(message.channel, message.author.mention + " Please provide a username-query (or optionally a discriminator) to ban a guest user.\nExample: `ban Titan#0001`")
return
content = content.split()
username = content[2][:content[2].find("#")] if "#" in content[2] else content[2]
discriminator = int(content[2][content[2].find("#") + 1:]) if "#" in content[2] else None
reason = await self.database.ban_unauth_user_by_query(message.server.id, message.author.id, username, discriminator)
await self.client.send_message(message.channel, message.author.mention + " " + reason)
async def kick(self, message):
serverid = message.server.id
content = message.content.strip()
if len(content.split()) == 2:
await self.client.send_message(message.channel, message.author.mention + " Please provide a username-query (or optionally a discriminator) to ban a guest user.\nExample: `ban Titan#0001`")
return
content = content.split()
username = content[2][:content[2].find("#")] if "#" in content[2] else content[2]
discriminator = int(content[2][content[2].find("#") + 1:]) if "#" in content[2] else None
reason = await self.database.revoke_unauth_user_by_query(message.server.id, username, discriminator)
await self.client.send_message(message.channel, message.author.mention + " " + reason)
| agpl-3.0 | Python |
e75bafa43908d9f66f94ffae1393f18c9262f5a1 | Add basic test for get_all_certs_keys IInstaller interface method. | letsencrypt/letsencrypt,stweil/letsencrypt,letsencrypt/letsencrypt,lmcro/letsencrypt,lmcro/letsencrypt,stweil/letsencrypt | letsencrypt-postfix/TestPostfixConfigGenerator.py | letsencrypt-postfix/TestPostfixConfigGenerator.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import logging
import unittest
import Config
import PostfixConfigGenerator as pcg
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
# Fake Postfix Configs
names_only_config = """myhostname = mail.fubard.org
mydomain = fubard.org
myorigin = fubard.org"""
certs_only_config = """
smtpd_tls_cert_file = /etc/letsencrypt/live/www.fubard.org/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/www.fubard.org/privkey.pem
"""
def GetFakeOpen(fake_file_contents):
fake_file = io.StringIO()
# cast this to unicode for py2
fake_file.write(fake_file_contents)
fake_file.seek(0)
def FakeOpen(_):
return fake_file
return FakeOpen
class TestPostfixConfigGenerator(unittest.TestCase):
def setUp(self):
self.fopen_names_only_config = GetFakeOpen(names_only_config)
self.fopen_certs_only_config = GetFakeOpen(certs_only_config)
#self.config = Config.Config()
self.config = None
self.postfix_dir = 'tests/'
def tearDown(self):
pass
def testGetAllNames(self):
sorted_names = ['fubard.org', 'mail.fubard.org']
postfix_config_gen = pcg.PostfixConfigGenerator(
self.config,
self.postfix_dir,
fixup=True,
fopen=self.fopen_names_only_config
)
self.assertEqual(sorted_names, postfix_config_gen.get_all_names())
def testGetAllCertAndKeys(self):
return_vals = ('/etc/letsencrypt/live/www.fubard.org/fullchain.pem',
'/etc/letsencrypt/live/www.fubard.org/privkey.pem',
None)
postfix_config_gen = pcg.PostfixConfigGenerator(
self.config,
self.postfix_dir,
fixup=True,
fopen=self.fopen_certs_only_config
)
self.assertEqual(return_vals, postfix_config_gen.get_all_certs_keys())
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import logging
import unittest
import Config
import PostfixConfigGenerator as pcg
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
# Fake Postfix Configs
names_only_config = """myhostname = mail.fubard.org
mydomain = fubard.org
myorigin = fubard.org"""
def GetFakeOpen(fake_file_contents):
fake_file = io.StringIO()
# cast this to unicode for py2
fake_file.write(fake_file_contents)
fake_file.seek(0)
def FakeOpen(_):
return fake_file
return FakeOpen
class TestPostfixConfigGenerator(unittest.TestCase):
def setUp(self):
self.fopen_names_only_config = GetFakeOpen(names_only_config)
#self.config = Config.Config()
self.config = None
self.postfix_dir = 'tests/'
def tearDown(self):
pass
def testGetAllNames(self):
sorted_names = ['fubard.org', 'mail.fubard.org']
postfix_config_gen = pcg.PostfixConfigGenerator(
self.config,
self.postfix_dir,
fixup=True,
fopen=self.fopen_names_only_config
)
self.assertEqual(sorted_names, postfix_config_gen.get_all_names())
if __name__ == '__main__':
unittest.main()
| apache-2.0 | Python |
c6c2febcf32d2316baf41b55d23162eb06253ea4 | Delete duplicate versioneer section | Josef-Friedrich/audiorename | audiorename/__init__.py | audiorename/__init__.py | # -*- coding: utf-8 -*-
"""Rename audio files from metadata tags."""
import os
from audiorename.args import parser
from .batch import Batch
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
def execute(args=None):
args = parser.parse_args(args)
args.path = os.path.abspath(args.path)
if os.path.isdir(args.path):
args.is_dir = True
else:
args.is_dir = False
if args.filter_album_min or args.filter_album_complete:
args.filter = True
else:
args.filter = False
batch = Batch(args)
batch.execute()
| # -*- coding: utf-8 -*-
"""Rename audio files from metadata tags."""
import os
from audiorename.args import parser
from .batch import Batch
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
def execute(args=None):
args = parser.parse_args(args)
args.path = os.path.abspath(args.path)
if os.path.isdir(args.path):
args.is_dir = True
else:
args.is_dir = False
if args.filter_album_min or args.filter_album_complete:
args.filter = True
else:
args.filter = False
batch = Batch(args)
batch.execute()
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
| mit | Python |
4805c7d7bc97ae4fc1b44e6dbd3626bfe5bd0ff9 | fix favouriting own bookmark | ev-agelos/Python-bookmarks,ev-agelos/Python-bookmarks,ev-agelos/Python-bookmarks | bookmarks/api/favourites.py | bookmarks/api/favourites.py | from flask import request, jsonify, url_for, g
from flask.views import MethodView
from flask_login import login_required
from flask_smorest import Blueprint, abort
from bookmarks import csrf
from bookmarks.models import Bookmark, Favourite
from bookmarks.logic import _save, _unsave
from .schemas import FavouriteSchema, FavouritePOSTSchema
favourites_api = Blueprint('favourites_api', 'Favourites', url_prefix='/api/v1/favourites/',
description='Operations on Favourites')
@favourites_api.route('/')
class FavouritesAPI(MethodView):
decorators = [login_required, csrf.exempt]
@favourites_api.response(FavouriteSchema(many=True))
def get(self):
"""Return all user's bookmark favourites."""
return g.user.favourites.all()
@favourites_api.arguments(FavouritePOSTSchema)
def post(self, args):
"""Add a bookmark to user's favourites."""
bookmark = Bookmark.query.get(args['bookmark_id'])
if bookmark is None:
abort(404, message='bookmark not found')
elif bookmark.user_id == g.user.id:
abort(403, message='forbidden')
elif Favourite.query.filter_by(user_id=g.user.id,
bookmark_id=bookmark.id).scalar() is not None:
abort(409, message='bookmark already saved')
_save(bookmark.id)
return {}, 201
@favourites_api.route('/<int:id>')
class FavouriteAPI(MethodView):
decorators = [csrf.exempt, login_required]
@favourites_api.response(code=204)
def delete(self, id):
"""Remove bookmark from user's favourites."""
bookmark = Bookmark.query.get(id)
if bookmark is None:
abort(404, message='Bookmark not found')
favourite = Favourite.query.filter_by(user_id=g.user.id,
bookmark_id=id).scalar()
if favourite is None:
abort(404, message='Favourite not found')
_unsave(favourite)
| from flask import request, jsonify, url_for, g
from flask.views import MethodView
from flask_login import login_required
from flask_smorest import Blueprint, abort
from bookmarks import csrf
from bookmarks.models import Bookmark, Favourite
from bookmarks.logic import _save, _unsave
from .schemas import FavouriteSchema, FavouritePOSTSchema
favourites_api = Blueprint('favourites_api', 'Favourites', url_prefix='/api/v1/favourites/',
description='Operations on Favourites')
@favourites_api.route('/')
class FavouritesAPI(MethodView):
decorators = [login_required, csrf.exempt]
@favourites_api.response(FavouriteSchema(many=True))
def get(self):
"""Return all user's bookmark favourites."""
return g.user.favourites.all()
@favourites_api.arguments(FavouritePOSTSchema)
def post(self, args):
"""Add a bookmark to user's favourites."""
bookmark = Bookmark.query.get(args['bookmark_id'])
if bookmark is None:
abort(404, message='bookmark not found')
elif bookmark.user_id != g.user.id:
abort(403, message='forbidden')
elif Favourite.query.filter_by(user_id=g.user.id,
bookmark_id=bookmark.id).scalar() is not None:
abort(409, message='bookmark already saved')
_save(bookmark.id)
return {}, 201
@favourites_api.route('/<int:id>')
class FavouriteAPI(MethodView):
decorators = [csrf.exempt, login_required]
@favourites_api.response(code=204)
def delete(self, id):
"""Remove bookmark from user's favourites."""
bookmark = Bookmark.query.get(id)
if bookmark is None:
abort(404, message='Bookmark not found')
favourite = Favourite.query.filter_by(user_id=g.user.id,
bookmark_id=id).scalar()
if favourite is None:
abort(404, message='Favourite not found')
_unsave(favourite)
| mit | Python |
af2bd3600fd4984886fb52aedf55eeb95a700bfc | sort events list | vhanla/CudaText,vhanla/CudaText,Alexey-T/CudaText,vhanla/CudaText,Alexey-T/CudaText,vhanla/CudaText,Alexey-T/CudaText,Alexey-T/CudaText,Alexey-T/CudaText,Alexey-T/CudaText,vhanla/CudaText,vhanla/CudaText,vhanla/CudaText,vhanla/CudaText,Alexey-T/CudaText,vhanla/CudaText,vhanla/CudaText,Alexey-T/CudaText | app/py/cuda_make_plugin/events.py | app/py/cuda_make_plugin/events.py | EVENTS = [
'on_caret',
'on_change',
'on_change_slow',
'on_click',
'on_click_dbl',
'on_click_gap',
'on_close',
'on_complete',
'on_console',
'on_console_nav',
'on_focus',
'on_func_hint',
'on_goto_caret',
'on_goto_change',
'on_goto_def',
'on_goto_enter',
'on_goto_key',
'on_goto_key_up',
'on_insert',
'on_key',
'on_key_up',
'on_lexer',
'on_macro',
'on_open',
'on_open_pre',
'on_output_nav',
'on_paste',
'on_save',
'on_save_pre',
'on_scroll',
'on_snippet',
'on_start',
'on_state',
'on_tab_move',
]
EVENTS_ADD_PARAMS = {
'on_key': 'key, state',
'on_key_up': 'key, state',
'on_insert': 'text',
'on_click': 'state',
'on_click_dbl': 'state',
'on_click_gap': 'state, nline, ntag, size_x, size_y, pos_x, pos_y',
'on_console': 'text',
'on_console_nav': 'text',
'on_goto_enter': 'text',
'on_goto_key': 'key, state',
'on_goto_key_up': 'key, state',
'on_output_nav': 'text, tag',
'on_macro': 'text',
'on_open_pre': 'filename',
'on_paste': 'keep_caret, select_then',
'on_snippet': 'snippet_id, snippet_text',
'on_state': 'state',
}
| EVENTS = [
'on_caret',
'on_change',
'on_change_slow',
'on_click',
'on_click_dbl',
'on_click_gap',
'on_close',
'on_complete',
'on_console',
'on_console_nav',
'on_focus',
'on_func_hint',
'on_goto_enter',
'on_goto_caret',
'on_goto_change',
'on_goto_key',
'on_goto_key_up',
'on_goto_def',
'on_insert',
'on_key',
'on_key_up',
'on_lexer',
'on_macro',
'on_open',
'on_open_pre',
'on_output_nav',
'on_paste',
'on_save',
'on_save_pre',
'on_scroll',
'on_snippet',
'on_start',
'on_state',
'on_tab_move',
]
EVENTS_ADD_PARAMS = {
'on_key': 'key, state',
'on_key_up': 'key, state',
'on_insert': 'text',
'on_click': 'state',
'on_click_dbl': 'state',
'on_click_gap': 'state, nline, ntag, size_x, size_y, pos_x, pos_y',
'on_console': 'text',
'on_console_nav': 'text',
'on_goto_enter': 'text',
'on_goto_key': 'key, state',
'on_goto_key_up': 'key, state',
'on_output_nav': 'text, tag',
'on_macro': 'text',
'on_open_pre': 'filename',
'on_paste': 'keep_caret, select_then',
'on_snippet': 'snippet_id, snippet_text',
'on_state': 'state',
}
| mpl-2.0 | Python |
e4b679afd6c7a43450faa668ba6454389935a668 | remove sensor | kervi/can-bot | app/sensors/__init__.py | app/sensors/__init__.py | """
Include the sensor modules that you have created here.
Kervi will load the sensors that are imported here.
"""
#from . import my_sensor
from . import system_sensors
| """
Include the sensor modules that you have created here.
Kervi will load the sensors that are imported here.
"""
from . import my_sensor
from . import system_sensors
| mit | Python |
4378aef47a7e2b80a4a22af2bbe69ce4b780ab6d | Fix due to Flask-Login version up | teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr | pokr/views/login.py | pokr/views/login.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from flask import g, render_template, redirect, request, url_for
from flask.ext.login import current_user, login_required, logout_user
from social.apps.flask_app.template_filters import backends
def register(app):
@login_required
@app.route('/done/')
def done():
return redirect(request.referrer or url_for('main'))
@app.route('/logout')
def logout():
logout_user()
return redirect(request.referrer or url_for('main'))
@app.before_request
def global_user():
g.user = current_user
@app.context_processor
def inject_user():
user = getattr(g, 'user')
return {
'user': user,
'is_logged': user and user.is_authenticated
}
app.context_processor(backends)
| #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from flask import g, render_template, redirect, request, url_for
from flask.ext.login import current_user, login_required, logout_user
from social.apps.flask_app.template_filters import backends
def register(app):
@login_required
@app.route('/done/')
def done():
return redirect(request.referrer or url_for('main'))
@app.route('/logout')
def logout():
logout_user()
return redirect(request.referrer or url_for('main'))
@app.before_request
def global_user():
g.user = current_user
@app.context_processor
def inject_user():
user = getattr(g, 'user')
return {
'user': user,
'is_logged': user and not user.is_anonymous()
}
app.context_processor(backends)
| apache-2.0 | Python |
8560139ce4380226a72c776023045faf801a2cc0 | Add missing user id constant | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | app/soc/mapreduce/convert_user.py | app/soc/mapreduce/convert_user.py | #!/usr/bin/python2.5
#
# Copyright 2012 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""User updating MapReduce.
This MapReduce updates user accounts to have complete email
addresses (including @gmail.com for gmail users) and sets the
user_id attribute of User objects if it is missing.
"""
import logging
from google.appengine.ext import db
from mapreduce import operation
from soc.models.user import User
from soc.logic import accounts
MISSING_USER = 'missing_user'
MISSING_USER_SECOND = 'missing_user_second'
MISSING_USER_ID = 'missing_user_id'
IGNORED_USER = 'ignored_user'
CONVERTED_USER = 'converted_user'
def convert_user_txn(user_key):
user = db.get(user_key)
if not user:
logging.error("Missing user for key '%r'." % user_key)
return MISSING_USER
normalized = accounts.denormalizeAccount(user.account)
if (user.account.email() == normalized.email() and
user.user_id == user.account.user_id()):
return IGNORED_USER
user.account = normalized
user.put()
user = db.get(user_key)
if not user:
logging.error("Missing user second time around for key '%s'." % user_key)
return MISSING_USER_SECOND
if not user.account.user_id():
logging.error("Missing user_id around for key '%s'." % user_key)
return MISSING_USER_ID
user.user_id = user.account.user_id()
user.put()
if not user.user_id:
return MISSING_USER_ID
return CONVERTED_USER
def process(user_key):
result = db.run_in_transaction(convert_user_txn, user_key)
yield operation.counters.Increment(result)
| #!/usr/bin/python2.5
#
# Copyright 2012 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""User updating MapReduce.
This MapReduce updates user accounts to have complete email
addresses (including @gmail.com for gmail users) and sets the
user_id attribute of User objects if it is missing.
"""
import logging
from google.appengine.ext import db
from mapreduce import operation
from soc.models.user import User
from soc.logic import accounts
MISSING_USER = 'missing_user'
MISSING_USER_SECOND = 'missing_user_second'
IGNORED_USER = 'ignored_user'
CONVERTED_USER = 'converted_user'
def convert_user_txn(user_key):
user = db.get(user_key)
if not user:
logging.error("Missing user for key '%r'." % user_key)
return MISSING_USER
normalized = accounts.denormalizeAccount(user.account)
if (user.account.email() == normalized.email() and
user.user_id == user.account.user_id()):
return IGNORED_USER
user.account = normalized
user.put()
user = db.get(user_key)
if not user:
logging.error("Missing user second time around for key '%s'." % user_key)
return MISSING_USER_SECOND
if not user.account.user_id():
logging.error("Missing user_id around for key '%s'." % user_key)
return MISSING_USER_ID
user.user_id = user.account.user_id()
user.put()
if not user.user_id:
return MISSING_USER_ID
return CONVERTED_USER
def process(user_key):
result = db.run_in_transaction(convert_user_txn, user_key)
yield operation.counters.Increment(result)
| apache-2.0 | Python |
1c8de2450313843bba360b98814def4555608917 | Update stuffaboutcode_bridge.py | jargonautical/mcpi,jargonautical/mcpi | mcpipy/stuffaboutcode_bridge.py | mcpipy/stuffaboutcode_bridge.py | #!/usr/bin/env python
#www.stuffaboutcode.com
#Raspberry Pi, Minecraft - auto bridge
# mcpipy.com retrieved from URL below, written by stuffaboutcode
# http://www.stuffaboutcode.com/2013/02/raspberry-pi-minecraft-auto-bridge.html
#import the minecraft.py module from the minecraft directory
import mcpi.minecraft as minecraft
import mcpi.block as block
#import time, so delays can be used
import time
import server
#function to round players float position to integer position
def roundVec3(vec3):
return minecraft.Vec3(int(vec3.x), int(vec3.y), int(vec3.z))
if __name__ == "__main__":
time.sleep(2)
#Connect to minecraft by creating the minecraft object
# - minecraft needs to be running and in a game
mc = minecraft.Minecraft.create(server.address)
#Post a message to the minecraft chat window
mc.postToChat("Hi, Minecraft - Auto Bridge Active")
mc.postToChat("www.stuffaboutcode.com")
#Get the players position
lastPlayerPos = mc.player.getPos()
while (True):
#Get the players position
playerPos = mc.player.getPos()
#Find the difference between the player's position and the last position
movementX = lastPlayerPos.x - playerPos.x
movementZ = lastPlayerPos.z - playerPos.z
#Has the player moved more than 0.2 in any horizontal (x,z) direction
if ((movementX < -0.2) or (movementX > 0.2) or (movementZ < -0.2) or (movementZ > 0.2)):
#Project players direction forward to the next square
nextPlayerPos = playerPos
# keep adding the movement to the players location till the next block is found
while ((int(playerPos.x) == int(nextPlayerPos.x)) and (int(playerPos.z) == int(nextPlayerPos.z))):
nextPlayerPos = minecraft.Vec3(nextPlayerPos.x - movementX, nextPlayerPos.y, nextPlayerPos.z - movementZ)
#Is the block below the next player pos air, if so fill it in with DIAMOND
blockBelowPos = roundVec3(nextPlayerPos)
blockBelowPos.z = blockBelowPos.z - 1
blockBelowPos.y = blockBelowPos.y - 1
if mc.getBlock(blockBelowPos) == block.AIR:
mc.setBlock(blockBelowPos.x, blockBelowPos.y, blockBelowPos.z, block.DIAMOND_BLOCK)
#Store players last position
lastPlayerPos = playerPos
#Delay
time.sleep(0.01)
| #!/usr/bin/env python
#www.stuffaboutcode.com
#Raspberry Pi, Minecraft - auto bridge
# mcpipy.com retrieved from URL below, written by stuffaboutcode
# http://www.stuffaboutcode.com/2013/02/raspberry-pi-minecraft-auto-bridge.html
#import the minecraft.py module from the minecraft directory
from .. import minecraft
from .. import block
#import time, so delays can be used
import time
import server
#function to round players float position to integer position
def roundVec3(vec3):
return minecraft.Vec3(int(vec3.x), int(vec3.y), int(vec3.z))
if __name__ == "__main__":
time.sleep(2)
#Connect to minecraft by creating the minecraft object
# - minecraft needs to be running and in a game
mc = minecraft.Minecraft.create(server.address)
#Post a message to the minecraft chat window
mc.postToChat("Hi, Minecraft - Auto Bridge Active")
mc.postToChat("www.stuffaboutcode.com")
#Get the players position
lastPlayerPos = mc.player.getPos()
while (True):
#Get the players position
playerPos = mc.player.getPos()
#Find the difference between the player's position and the last position
movementX = lastPlayerPos.x - playerPos.x
movementZ = lastPlayerPos.z - playerPos.z
#Has the player moved more than 0.2 in any horizontal (x,z) direction
if ((movementX < -0.2) or (movementX > 0.2) or (movementZ < -0.2) or (movementZ > 0.2)):
#Project players direction forward to the next square
nextPlayerPos = playerPos
# keep adding the movement to the players location till the next block is found
while ((int(playerPos.x) == int(nextPlayerPos.x)) and (int(playerPos.z) == int(nextPlayerPos.z))):
nextPlayerPos = minecraft.Vec3(nextPlayerPos.x - movementX, nextPlayerPos.y, nextPlayerPos.z - movementZ)
#Is the block below the next player pos air, if so fill it in with DIAMOND
blockBelowPos = roundVec3(nextPlayerPos)
blockBelowPos.z = blockBelowPos.z - 1
blockBelowPos.y = blockBelowPos.y - 1
if mc.getBlock(blockBelowPos) == block.AIR:
mc.setBlock(blockBelowPos.x, blockBelowPos.y, blockBelowPos.z, block.DIAMOND_BLOCK)
#Store players last position
lastPlayerPos = playerPos
#Delay
time.sleep(0.01) | cc0-1.0 | Python |
71089e9cf1fd991fbcd2cccd906448c3d9bde13e | Update win_batch_md2ipynb.py | d2l-ai/d2l-zh,d2l-ai/d2l-zh,d2l-ai/d2l-zh,mli/gluon-tutorials-zh,mli/gluon-tutorials-zh,mli/gluon-tutorials-zh,mli/gluon-tutorials-zh | build/win_batch_md2ipynb.py | build/win_batch_md2ipynb.py | import glob
import nbformat
import notedown
import os
from subprocess import check_output
import sys
import time
def mkdir_if_not_exist(path):
if not os.path.exists(os.path.join(*path)):
os.makedirs(os.path.join(*path))
# timeout for each notebook, in sec
timeout = 20 * 60
# the files will be ingored for execution
ignore_execution = []
reader = notedown.MarkdownReader(match='strict')
do_eval = int(os.environ.get('EVAL', True))
for chap in glob.glob('chapter_*'):
mkdir_if_not_exist(['build', 'win_ipynb', chap])
mds = filter(lambda x: x.endswith('md'), os.listdir(chap))
for md in mds:
if md != 'index.md':
in_md = os.path.join(chap, md)
out_nb = os.path.join('build', 'win_ipynb', in_md[:-2] + '.ipynb')
print('---', in_md)
# read
with open(in_md, 'r', encoding="utf8") as f:
notebook = reader.read(f)
if do_eval and not any([i in input_fn for i in ignore_execution]):
tic = time.time()
notedown.run(notebook, timeout)
print('=== Finished evaluation in %f sec'%(time.time()-tic))
# write
# need to add language info to for syntax highlight
notebook['metadata'].update({'language_info':{'name':'python'}})
with open(out_nb, 'w', encoding="utf8") as f:
f.write(nbformat.writes(notebook))
| import glob
import nbformat
import notedown
import os
from subprocess import check_output
import sys
import time
def mkdir_if_not_exist(path):
if not os.path.exists(os.path.join(*path)):
os.makedirs(os.path.join(*path))
# timeout for each notebook, in sec
timeout = 20 * 60
# the files will be ingored for execution
ignore_execution = []
reader = notedown.MarkdownReader(match='strict')
do_eval = int(os.environ.get('EVAL', True))
for chap in glob.glob('chapter_*'):
mkdir_if_not_exist(['build', 'win_ipynb', chap])
mds = filter(lambda x: x.endswith('md'), os.listdir(chap))
for md in mds:
if md != 'index.md':
in_md = os.path.join(chap, md)
out_nb = os.path.join('build', in_md[:-2] + '.ipynb')
print('---', in_md)
# read
with open(in_md, 'r', encoding="utf8") as f:
notebook = reader.read(f)
if do_eval and not any([i in input_fn for i in ignore_execution]):
tic = time.time()
notedown.run(notebook, timeout)
print('=== Finished evaluation in %f sec'%(time.time()-tic))
# write
# need to add language info to for syntax highlight
notebook['metadata'].update({'language_info':{'name':'python'}})
with open(out_nb, 'w', encoding="utf8") as f:
f.write(nbformat.writes(notebook))
| apache-2.0 | Python |
d015c90f06b3b8413955ebaac3ec828d4517c2d1 | upgrade java to 1.9.64 (#78) | bazelbuild/rules_appengine,bazelbuild/rules_appengine | appengine/variables.bzl | appengine/variables.bzl | """This file is a central location for configuring new SDK versions.
"""
# Not all languages are released for every SDK version. Whenever possible, set
# ${LANG}_SDK_VERSION = APPENGINE_VERSION.
APPENGINE_VERSION = "1.9.64"
SDK_URL_PREFIX = "https://storage.googleapis.com/appengine-sdks/featured"
JAVA_SDK_SHA256 = "8eb229a6f2a1d6dbe4345ba854b7388c77abfd64af1f9fc8bdd1316811b2f8fc"
JAVA_SDK_VERSION = APPENGINE_VERSION
PY_SDK_SHA256 = "76b90b3a780c6dfd2e5dcd9d79ec8be2ab7c1146fd445e472f18e3aeb90fabc5"
# Note: Python ahead of Java
PY_SDK_VERSION = "1.9.69"
| """This file is a central location for configuring new SDK versions.
"""
# Not all languages are released for every SDK version. Whenever possible, set
# ${LANG}_SDK_VERSION = APPENGINE_VERSION.
APPENGINE_VERSION = "1.9.63"
SDK_URL_PREFIX = "https://storage.googleapis.com/appengine-sdks/featured"
JAVA_SDK_SHA256 = "477eb0bdec2c98fa68e4d0d9cbd1329c140e907fa64be2c3c9c065373369e93b"
JAVA_SDK_VERSION = APPENGINE_VERSION
PY_SDK_SHA256 = "76b90b3a780c6dfd2e5dcd9d79ec8be2ab7c1146fd445e472f18e3aeb90fabc5"
# Note: Python ahead of Java
PY_SDK_VERSION = "1.9.69"
| apache-2.0 | Python |
b84ce75ab4c88e69ba6978761e5cfcae9f872b10 | add basic auth to config | crossgovernmentservices/prototypes,crossgovernmentservices/prototypes,crossgovernmentservices/prototypes,crossgovernmentservices/prototypes,crossgovernmentservices/prototypes | application/settings.py | application/settings.py | # -*- coding: utf-8 -*-
import os
class Config(object):
SECRET_KEY = os.environ.get('APPLICATION_SECRET', 'secret-key') # TODO: Change me
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
BCRYPT_LOG_ROUNDS = 13
ASSETS_DEBUG = False
CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc.
BASIC_AUTH_FORCE = os.environ.get('BASIC_AUTH_FORCE')
BASIC_AUTH_USERNAME = os.environ.get('BASIC_AUTH_USERNAME')
BASIC_AUTH_PASSWORD = os.environ.get('BASIC_AUTH_PASSWORD')
class ProdConfig(Config):
"""Production configuration."""
ENV = 'prod'
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/example' # TODO: Change me
class DevConfig(Config):
"""Development configuration."""
ENV = 'dev'
DEBUG = True
DB_NAME = 'dev.db'
# Put the db file in project root
DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH)
ASSETS_DEBUG = True # Don't bundle/minify static assets
CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc.
class TestConfig(Config):
TESTING = True
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite://'
BCRYPT_LOG_ROUNDS = 1 # For faster tests
WTF_CSRF_ENABLED = False # Allows form testing
| # -*- coding: utf-8 -*-
import os
os_env = os.environ
class Config(object):
SECRET_KEY = os_env.get('APPLICATION_SECRET', 'secret-key') # TODO: Change me
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
BCRYPT_LOG_ROUNDS = 13
ASSETS_DEBUG = False
CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc.
class ProdConfig(Config):
"""Production configuration."""
ENV = 'prod'
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/example' # TODO: Change me
class DevConfig(Config):
"""Development configuration."""
ENV = 'dev'
DEBUG = True
DB_NAME = 'dev.db'
# Put the db file in project root
DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(DB_PATH)
ASSETS_DEBUG = True # Don't bundle/minify static assets
CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc.
class TestConfig(Config):
TESTING = True
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite://'
BCRYPT_LOG_ROUNDS = 1 # For faster tests
WTF_CSRF_ENABLED = False # Allows form testing
| mit | Python |
6f0a28810acd28a0a680d82761216f7fe5518076 | Remove the log transform stub. Will add it back in later if needed. | jakirkham/bokeh,Karel-van-de-Plassche/bokeh,dennisobrien/bokeh,percyfal/bokeh,philippjfr/bokeh,azjps/bokeh,philippjfr/bokeh,DuCorey/bokeh,ericmjl/bokeh,phobson/bokeh,dennisobrien/bokeh,ericmjl/bokeh,bokeh/bokeh,ericmjl/bokeh,clairetang6/bokeh,aavanian/bokeh,dennisobrien/bokeh,jakirkham/bokeh,aiguofer/bokeh,rs2/bokeh,bokeh/bokeh,azjps/bokeh,stonebig/bokeh,bokeh/bokeh,mindriot101/bokeh,stonebig/bokeh,aavanian/bokeh,schoolie/bokeh,rs2/bokeh,jakirkham/bokeh,azjps/bokeh,ptitjano/bokeh,quasiben/bokeh,DuCorey/bokeh,jakirkham/bokeh,timsnyder/bokeh,dennisobrien/bokeh,rs2/bokeh,phobson/bokeh,stonebig/bokeh,aavanian/bokeh,mindriot101/bokeh,clairetang6/bokeh,percyfal/bokeh,phobson/bokeh,justacec/bokeh,clairetang6/bokeh,Karel-van-de-Plassche/bokeh,ptitjano/bokeh,quasiben/bokeh,timsnyder/bokeh,phobson/bokeh,DuCorey/bokeh,philippjfr/bokeh,aiguofer/bokeh,ptitjano/bokeh,dennisobrien/bokeh,ericmjl/bokeh,Karel-van-de-Plassche/bokeh,aiguofer/bokeh,rs2/bokeh,schoolie/bokeh,aavanian/bokeh,azjps/bokeh,aiguofer/bokeh,rs2/bokeh,timsnyder/bokeh,philippjfr/bokeh,stonebig/bokeh,justacec/bokeh,ptitjano/bokeh,schoolie/bokeh,quasiben/bokeh,Karel-van-de-Plassche/bokeh,aiguofer/bokeh,draperjames/bokeh,timsnyder/bokeh,ericmjl/bokeh,ptitjano/bokeh,draperjames/bokeh,Karel-van-de-Plassche/bokeh,bokeh/bokeh,aavanian/bokeh,schoolie/bokeh,justacec/bokeh,jakirkham/bokeh,phobson/bokeh,timsnyder/bokeh,DuCorey/bokeh,azjps/bokeh,bokeh/bokeh,percyfal/bokeh,philippjfr/bokeh,justacec/bokeh,mindriot101/bokeh,schoolie/bokeh,draperjames/bokeh,DuCorey/bokeh,percyfal/bokeh,draperjames/bokeh,percyfal/bokeh,clairetang6/bokeh,mindriot101/bokeh,draperjames/bokeh | bokeh/models/transforms.py | bokeh/models/transforms.py | '''
'''
from __future__ import absolute_import
from ..core.enums import StepMode, JitterRandomDistribution
from ..core.properties import abstract
from ..core.properties import Either, Enum, Float, Instance, Seq, String, Tuple
from ..model import Model
from .sources import ColumnDataSource
@abstract
class Transform(Model):
''' Base class for ``Transform`` models that represent a computation
to be carried out on the client-side.
JavaScript implementations should implement the following methods:
.. code-block: coffeescript
compute: (x) ->
# compute the transform of a single value
v_compute: (xs) ->
# compute the transform of an array of values
'''
pass
class Jitter(Transform):
''' Apply uniformly sampled random jitter to data.
'''
mean = Float(default=0, help="""
The central value for the random sample
""")
width = Float(default=1, help="""
The width (absolute for uniform distribution and sigma for the normal distribution) of the random sample.
""")
distribution = Enum(JitterRandomDistribution, default='uniform', help="""
The random distribution upon which to pull the random scatter
""")
@abstract
class Interpolator(Transform):
''' Base class for interpolator transforms.
Interpolators are configured with ``values`` which can either be:
* A literal sequence of values:
.. code-block: python
interp = Interpolator(y=[2, 5, 10, 12, 16])
.. code-block: python
interp = Interpolator(x="year", y="earnings", data=jewlery_prices))
'''
x = Either(String, Seq(Float), help="""
Independant coordiante denoting the location of a point.
""")
y = Either(String, Seq(Float), help="""
Dependant coordinate denoting the value of a point at a location.
""")
data = Instance(ColumnDataSource, help="""
Data which defines the source for the named columns if a string is passed to either the `x` or `y` parameters.
""")
# Define an initialization routine to do some cross checking of input values
def __init__(self, palette=None, **kwargs):
super(Interpolator, self).__init__(**kwargs)
class LinearInterpolator(Interpolator):
''' Compute a linear interpolation between the points given by ``values``.
'''
pass
class StepInterpolator(Interpolator):
''' Compute a step-wise interpolation between the points given
by ``values``.
'''
mode = Enum(StepMode, default="after", help="""
""")
| '''
'''
from __future__ import absolute_import
from ..core.enums import StepMode, JitterRandomDistribution
from ..core.properties import abstract
from ..core.properties import Either, Enum, Float, Instance, Seq, String, Tuple
from ..model import Model
from .sources import ColumnDataSource
@abstract
class Transform(Model):
''' Base class for ``Transform`` models that represent a computation
to be carried out on the client-side.
JavaScript implementations should implement the following methods:
.. code-block: coffeescript
compute: (x) ->
# compute the transform of a single value
v_compute: (xs) ->
# compute the transform of an array of values
'''
pass
class Jitter(Transform):
''' Apply uniformly sampled random jitter to data.
'''
mean = Float(default=0, help="""
The central value for the random sample
""")
width = Float(default=1, help="""
The width (absolute for uniform distribution and sigma for the normal distribution) of the random sample.
""")
distribution = Enum(JitterRandomDistribution, default='uniform', help="""
The random distribution upon which to pull the random scatter
""")
@abstract
class Interpolator(Transform):
''' Base class for interpolator transforms.
Interpolators are configured with ``values`` which can either be:
* A literal sequence of values:
.. code-block: python
interp = Interpolator(y=[2, 5, 10, 12, 16])
.. code-block: python
interp = Interpolator(x="year", y="earnings", data=jewlery_prices))
'''
x = Either(String, Seq(Float), help="""
Independant coordiante denoting the location of a point.
""")
y = Either(String, Seq(Float), help="""
Dependant coordinate denoting the value of a point at a location.
""")
data = Instance(ColumnDataSource, help="""
Data which defines the source for the named columns if a string is passed to either the `x` or `y` parameters.
""")
# Define an initialization routine to do some cross checking of input values
def __init__(self, palette=None, **kwargs):
super(Interpolator, self).__init__(**kwargs)
class LinearInterpolator(Interpolator):
''' Compute a linear interpolation between the points given by ``values``.
'''
pass
class LogInterpolator(Interpolator):
''' Compute a log interpolation between the points given by ``values``.
'''
base = Float(default=10, help="""
Base value for the logorithm. For example, if base = 10, then that would imply log_10.
""")
pass
class StepInterpolator(Interpolator):
''' Compute a step-wise interpolation between the points given
by ``values``.
'''
mode = Enum(StepMode, default="after", help="""
""")
| bsd-3-clause | Python |
90067f5543ec883d849cefef30f079d4e127ad59 | Improve filter_news.py and fix some small issues. | geektoni/Influenza-Like-Illness-Predictor,geektoni/Influenza-Like-Illness-Predictor | data_analysis/filter_news.py | data_analysis/filter_news.py | """Generate year files with news counts
Usage:
filter_news.py <directory> <output>
Options:
-h, --help
"""
from docopt import docopt
from os import listdir
from os.path import isfile, join
import datetime
from tqdm import *
import pandas as pd
def find_index(id, lis):
for i in range(0, len(lis)):
if id == lis[i]:
return i
return -1
if __name__ == "__main__":
# Parse the command line
args = docopt(__doc__)
# Array with the week we are considering
weeks = [42,43,44,45,46,47,48,49,50,51,52,1,23,4,5,6,7,8,9,10,11,12,13,14,15]
# Final count dictionary
news_count = {}
# Get only the files in the directory
onlyfiles = [f for f in listdir(args["<directory>"]) if isfile(join(args["<directory>"], f))]
# Loop over all the files and parse them
for file in tqdm(onlyfiles):
# Split the filename and get the day/month/year
file_name = file.split("_")
day = file_name[2]
month = file_name[1]
year = file_name[3]
# Compute the week number
week_number = datetime.date(int(year), int(month), int(day)).isocalendar()[1]
# Read and parse the file only if it is in the week range we are considering
if week_number in weeks:
# Read the file
file = pd.read_csv(join(args["<directory>"], file))
# Count how many news we have, considering only the italian ones
total_news = file[file.lang_detected == "it"].count()
# If that year column is still empty, create it and set it to zero
if news_count.get(year, []) == []:
news_count[year] = [0 for x in range(0, len(weeks))]
# Increment the week count
news_count[year][find_index(week_number, weeks)] += int(total_news["lang_detected"])
# Generate the index for the future dataframe
df_index = []
# Add a zero in front of number less than 10
for i in weeks:
if i < 10:
number = "0" + str(i)
else:
number = str(i)
df_index.append(number)
# Generate the dataframe
final_df = pd.DataFrame(news_count)
final_df.set_index(df_index)
# Print the dataframe to show the result
print(final_df)
# Save it to file
final_df.to_csv(args["<output>"], index_label="Week")
| """Generate year files with news counts
Usage:
filter_news.py <directory> <output>
Options:
-h, --help
"""
from docopt import docopt
from os import listdir
from os.path import isfile, join
import datetime
import pandas as pd
if __name__ == "__main__":
# Parse the command line
args = docopt(__doc__)
# Array with the week we are considering
weeks = [42,43,44,45,46,47,48,49,50,51,52,1,23,4,5,6,7,8,9,10,11,12,13,14,15]
# Final count dictionary
news_count = {}
# Get only the files in the directory
onlyfiles = [f for f in listdir(args["<directory>"]) if isfile(join(args["<directory>"], f))]
# Loop over all the files and parse them
for file in onlyfiles:
# Split the filename and get the day/month/year
file_name = file.split("_")
day = file_name[2]
month = file_name[1]
year = file_name[3]
# Compute the week number
week_number = datetime.date(int(year), int(month), int(day)).isocalendar()[1]
# Read and parse the file only if it is in the week range we are considering
if week_number in weeks:
# Read the file
file = pd.read_csv(join(args["<directory>"], file))
# Count how many news we have, considering only the italian ones
total_news = file[file.lang_detected == "it"].count()
# If that year column is still empty, create it and set it to zero
if news_count.get(year, []) == []:
news_count[year] = [0 for x in range(53)]
# Increment the week count
news_count[year][week_number] += int(total_news)
# Generate the index for the future dataframe
df_index = []
# Add a zero in front of number less than 10
for i in weeks:
if i < 10:
number = "0" + str(i)
else:
number = str(i)
df_index.append(number)
# Generate the dataframe
final_df = pd.DataFrame(news_count)
final_df.set_index(df_index)
# Print the dataframe to show the result
print(final_df)
# Save it to file
final_df.to_csv(args["<output>"], index_label="Week")
| mit | Python |
a79596be92323391ef79e3502b02e90904ec9f4e | Add PMT coordinates | CosmicLaserShow/CosmicLaserShow,CosmicLaserShow/CosmicLaserShow,CosmicLaserShow/CosmicLaserShow | globals.py | globals.py | MM = 1.
M = 1000 * MM
NS = 1.
S = 10**9 * NS
SPEED_OF_LIGHT = 299792458. * M / S
SPEED = (2./3.) * SPEED_OF_LIGHT
LENGTH = 500. * MM
PMT_COORDS = [(0., 0.), (LENGTH, 0.), (0., LENGTH), (LENGTH, LENGTH)]
| MM = 1.
M = 1000 * MM
NS = 1.
S = 10**9 * NS
SPEED_OF_LIGHT = 299792458. * M / S
SPEED = (2./3.) * SPEED_OF_LIGHT
LENGTH = 500. * MM
| mit | Python |
49026db21c3f200e68f6048ddac165ff5f5d8d17 | Update based on code review | gtagency/buzzmobile,gtagency/buzzmobile,gtagency/buzzmobile,jgkamat/buzzmobile,jgkamat/buzzmobile,jgkamat/buzzmobile | buzzmobile/sense/inputer/inputer.py | buzzmobile/sense/inputer/inputer.py | #!/usr/bin/env python
import rospy
from std_msgs.msg import String
def input_node():
pub = rospy.Publisher('input_value', String, queue_size=0)
rospy.init_node('inputer', anonymous=True)
# Publish a nonsense initial value to make sure subscribers don't explode
pub.publish("")
while not rospy.is_shutdown():
new_dst = raw_input("Dest> ")
pub.publish(new_dst)
if __name__ == '__main__':
input_node()
| #!/usr/bin/env python
import rospy
from std_msgs.msg import String
def input_node():
pub = rospy.Publisher('dst', String, queue_size=0)
rospy.init_node('inputer', anonymous=True)
pub.publish("")
while not rospy.is_shutdown():
new_dst = raw_input("Dest> ")
pub.publish(new_dst)
if __name__ == '__main__':
input_node()
| mit | Python |
05e651b0e606f216a78c61ccfb441ce7ed41d852 | Exclude from coverage the code pathways that are specific to Python 2. | morepath/reg,taschini/reg | reg/compat.py | reg/compat.py | import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else: # pragma: no cover
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
| import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else:
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
| bsd-3-clause | Python |
d00f510f69bacd6a9888f4cea77da110fa7165d7 | add install list generator | ReanGD/ansible-personal,ReanGD/ansible-personal,ReanGD/py-pacman-manager,ReanGD/py-pacman-manager | mngpacman.py | mngpacman.py | #!/usr/bin/env python
import os
import platform
import subprocess
class PackageManager(object):
def all_packages(self):
raise NotImplementedError()
def explicit_packages(self):
raise NotImplementedError()
def depend_packages(self, package):
raise NotImplementedError()
def group_depend_packages(self, group):
raise NotImplementedError()
class PacmanManager(PackageManager):
def __parse(self, cmd):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, err = p.communicate()
return set(out.decode("UTF-8").split())
def all_packages(self):
return self.__parse(["pacman", "-Qq"])
def explicit_packages(self):
return self.__parse(["pacman", "-Qeq"])
def depend_packages(self, package):
l = self.__parse(["pactree", "-u", package])
l.discard(package)
return l
def groups_depend_packages(self, groups):
pkgs = set()
for it in groups:
pkgs.update(self.__parse(["pacman", "-Qgq", it]))
return pkgs
def get_package_manager():
platform_name = platform.linux_distribution()[0]
if platform_name == "arch":
return PacmanManager()
else:
raise NotImplementedError()
class Config(object):
def __init__(self, path):
if not os.path.isfile(path):
path = os.path.join(os.getcwd(), path)
config_data = {}
exec(open(path).read(), config_data)
self.packages = set(config_data["packages"])
self.ignore_groups = set(config_data["ignore_groups"])
def gen_install_list(pkgs, gen_list=None, parent=None):
if gen_list is None:
gen_list = []
if parent not in gen_list:
for it in pkgs if parent is None else pkgs[parent]:
if it not in gen_list:
gen_install_list(pkgs, gen_list, it)
if parent is not None:
gen_list.append(parent)
return gen_list
mng = get_package_manager()
cfg = Config("config.py")
pkgs = {}
for pkg in cfg.packages:
pkgs[pkg] = mng.depend_packages(pkg).intersection(cfg.packages)
print(gen_install_list(pkgs))
# ignore_pkgs = mng.groups_depend_packages(cfg.ignore_groups)
# explicit_pkgs = mng.explicit_packages()
# new_pkgs = explicit_pkgs.difference(ignore_pkgs, cfg.packages)
# print(len(new_pkgs))
# print(new_pkgs)
# print(len(cfg.packages.intersection(ignore_pkgs)))
| #!/usr/bin/env python
import os
import platform
import subprocess
class PackageManager(object):
def all_packages(self):
raise NotImplementedError()
def explicit_packages(self):
raise NotImplementedError()
def depend_packages(self, package):
raise NotImplementedError()
def group_depend_packages(self, group):
raise NotImplementedError()
class PacmanManager(PackageManager):
def __parse(self, cmd):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
out, err = p.communicate()
return set(out.decode("UTF-8").split())
def all_packages(self):
return self.__parse(["pacman", "-Qq"])
def explicit_packages(self):
return self.__parse(["pacman", "-Qeq"])
def depend_packages(self, package):
l = self.__parse(["pactree", "-u", package])
l.discard(package)
return l
def groups_depend_packages(self, groups):
pkgs = set()
for it in groups:
pkgs.update(self.__parse(["pacman", "-Qgq", it]))
return pkgs
def get_package_manager():
platform_name = platform.linux_distribution()[0]
if platform_name == "arch":
return PacmanManager()
else:
raise NotImplementedError()
class Config(object):
def __init__(self, path):
if not os.path.isfile(path):
path = os.path.join(os.getcwd(), path)
config_data = {}
exec(open(path).read(), config_data)
self.packages = set(config_data["packages"])
self.ignore_groups = set(config_data["ignore_groups"])
mng = get_package_manager()
cfg = Config("config.py")
ignore_pkgs = mng.groups_depend_packages(cfg.ignore_groups)
explicit_pkgs = mng.explicit_packages()
new_pkgs = explicit_pkgs.difference(ignore_pkgs, cfg.packages)
print(len(new_pkgs))
print(new_pkgs)
print(len(cfg.packages.intersection(ignore_pkgs)))
| apache-2.0 | Python |
f450af8eb2b64e2f1eaccd6098a4004b6d0c766e | Add url validation. move imports to top of method. | anthonyw12123/4chanwebscraper | 4ChanWebScraper.py | 4ChanWebScraper.py | #downloads an IMAGE to the provided path.
#this fails on .WEBM or other media
def downloadImage(url,path):
import requests
from PIL import Image
img = requests.get(url)
i = Image.open(StringIO(img.content))
i.save(path)
#Checks if input folder exists in the current directory. If not, create it.
def checkFolderExists(folder, verbose):
import os
if not os.path.exists('./' + folder):
os.makedirs('./'+folder)
if verbose:
print('created folder '+ folder)
else:
if verbose:
print('folder already exists')
#uses re to normalize spaces for generating a folder name.
def normalize_whitespace(str):
import re
str = str.strip()
str = re.sub(r'\s+', ' ', str)
return str
#given an ugly full name, create a trimmed and formatted shortened folder name.
def createFolderName(webpageTitle):
splitString = webpageTitle.split('-')
outputString = splitString[0].strip().upper() + ' - ' + normalize_whitespace(splitString[1]).lower().title()
return outputString
def validateUrl(url):
pattern = r'^(https?://)?(www\.)?4chan'
if( re.match(pattern, url, re.I)):
return url
else:
msg = "URLs must be for a 4chan domain!"
raise argparse.ArgumentTypeError(msg)
if __name__ == '__main__':
import argparse
import re
parser = argparse.ArgumentParser(description='Process a 4chan thread to scrape all images from.')
parser.add_argument('url',nargs='+', type=validateUrl, help='a list, separated by spaces, of web addresses to be parsed')
parser.add_argument('-v', help='verbose. Turn on debug output.', action='store_true', dest='verbose')
args = parser.parse_args()
exit(0)
from BeautifulSoup import BeautifulSoup
import requests
from StringIO import StringIO
for link in args.url:
if args.verbose:
print('Processing ' + link)
response = requests.get(link)
html = response.content
soup = BeautifulSoup(html)
folderName = createFolderName(soup.title.string.replace('/',''))
checkFolderExists(folderName, args.verbose)
if args.verbose:
print('Capturing ' + folderName)
for link in soup.findAll('a', 'fileThumb'):
imageName = link.get('href')
if args.verbose:
print('Getting ' + imageName)
fileName = re.search('\d+\.\w+$',imageName)
savePath = './'+ folderName +'/' + fileName.group(0)
if args.verbose:
print('saving:' + savePath)
downloadImage('http:'+imageName,savePath)
| #downloads an IMAGE to the provided path.
#this fails on .WEBM or other media
def downloadImage(url,path):
import requests
from PIL import Image
img = requests.get(url)
i = Image.open(StringIO(img.content))
i.save(path)
#Checks if input folder exists in the current directory. If not, create it.
def checkFolderExists(folder, verbose):
import os
if not os.path.exists('./' + folder):
os.makedirs('./'+folder)
if verbose:
print('created folder '+ folder)
else:
if verbose:
print('folder already exists')
#uses re to normalize spaces for generating a folder name.
def normalize_whitespace(str):
import re
str = str.strip()
str = re.sub(r'\s+', ' ', str)
return str
#given an ugly full name, create a trimmed and formatted shortened folder name.
def createFolderName(webpageTitle):
splitString = webpageTitle.split('-')
outputString = splitString[0].strip().upper() + ' - ' + normalize_whitespace(splitString[1]).lower().title()
return outputString
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Process a 4chan thread to scrape all images from.')
parser.add_argument('url',nargs='+', help='a list, separated by spaces, of web addresses to be parsed')
parser.add_argument('-v', help='verbose. Turn on debug output.', action='store_true', dest='verbose')
args = parser.parse_args()
import re
from BeautifulSoup import BeautifulSoup
import requests
from StringIO import StringIO
for link in args.url:
if args.verbose:
print('Processing ' + link)
response = requests.get(link)
html = response.content
soup = BeautifulSoup(html)
folderName = createFolderName(soup.title.string.replace('/',''))
checkFolderExists(folderName, args.verbose)
if args.verbose:
print('Capturing ' + folderName)
for link in soup.findAll('a', 'fileThumb'):
imageName = link.get('href')
if args.verbose:
print('Getting ' + imageName)
fileName = re.search('\d+\.\w+$',imageName)
savePath = './'+ folderName +'/' + fileName.group(0)
if args.verbose:
print('saving:' + savePath)
downloadImage('http:'+imageName,savePath) | mit | Python |
b8b60bf646126ed3b2a4eb15b6ed51d7eba687a6 | add world bank example | Impactstory/oadoi,Impactstory/oadoi,Impactstory/sherlockoa,Impactstory/oadoi,Impactstory/sherlockoa | oa_manual.py | oa_manual.py | from collections import defaultdict
from time import time
from util import elapsed
# things to set here:
# license, free_metadata_url, free_pdf_url
# free_fulltext_url is set automatically from free_metadata_url and free_pdf_url
def get_overrides_dict():
override_dict = defaultdict(dict)
# cindy wu example
override_dict["10.1038/nature21360"]["free_pdf_url"] = "https://arxiv.org/pdf/1703.01424.pdf"
# example from twitter
override_dict["10.1021/acs.jproteome.5b00852"]["free_pdf_url"] = "http://pubs.acs.org/doi/pdfplus/10.1021/acs.jproteome.5b00852"
# have the unpaywall example go straight to the PDF, not the metadata page
override_dict["10.1098/rspa.1998.0160"]["free_pdf_url"] = "https://arxiv.org/pdf/quant-ph/9706064.pdf"
# missed, not in BASE, from Maha Bali in email
override_dict["10.1080/13562517.2014.867620"]["free_pdf_url"] = "http://dar.aucegypt.edu/bitstream/handle/10526/4363/Final%20Maha%20Bali%20TiHE-PoD-Empowering_Sept30-13.pdf"
# otherwise links to figshare match that only has data, not the article
override_dict["10.1126/science.aaf3777"]["free_pdf_url"] = None
override_dict["10.1126/science.aaf3777"]["free_metadata_url"] = None
#otherwise links to a metadata page that doesn't have the PDF because have to request a copy: https://openresearch-repository.anu.edu.au/handle/1885/103608
override_dict["10.1126/science.aad2622"]["free_pdf_url"] = "https://lra.le.ac.uk/bitstream/2381/38048/6/Waters%20et%20al%20draft_post%20review_v2_clean%20copy.pdf"
# otherwise led to http://www.researchonline.mq.edu.au/vital/access/services/Download/mq:39727/DS01 and authorization error
override_dict["10.1111/j.1461-0248.2008.01185.x"]["free_pdf_url"] = None
# override old-style webpage
override_dict["10.1210/jc.2016-2141"]["free_pdf_url"] = "https://academic.oup.com/jcem/article-lookup/doi/10.1210/jc.2016-2141"
override_dict["10.1210/jc.2016-2141"]["evidence"] = "hybrid manual"
# not indexing this location yet, from @rickypo
override_dict["10.1207/s15327957pspr0203_4"]["free_pdf_url"] = "http://www2.psych.ubc.ca/~schaller/528Readings/Kerr1998.pdf"
# also, work around broken url extraction from sage
override_dict["10.1207_s15327957pspr0203_4"]["free_pdf_url"] = "http://www2.psych.ubc.ca/~schaller/528Readings/Kerr1998.pdf"
# mentioned in world bank as good unpaywall example
override_dict["10.3386/w23298"]["free_pdf_url"] = "https://economics.mit.edu/files/12774"
return override_dict
| from collections import defaultdict
from time import time
from util import elapsed
# things to set here:
# license, free_metadata_url, free_pdf_url
# free_fulltext_url is set automatically from free_metadata_url and free_pdf_url
def get_overrides_dict():
override_dict = defaultdict(dict)
# cindy wu example
override_dict["10.1038/nature21360"]["free_pdf_url"] = "https://arxiv.org/pdf/1703.01424.pdf"
# example from twitter
override_dict["10.1021/acs.jproteome.5b00852"]["free_pdf_url"] = "http://pubs.acs.org/doi/pdfplus/10.1021/acs.jproteome.5b00852"
# have the unpaywall example go straight to the PDF, not the metadata page
override_dict["10.1098/rspa.1998.0160"]["free_pdf_url"] = "https://arxiv.org/pdf/quant-ph/9706064.pdf"
# missed, not in BASE, from Maha Bali in email
override_dict["10.1080/13562517.2014.867620"]["free_pdf_url"] = "http://dar.aucegypt.edu/bitstream/handle/10526/4363/Final%20Maha%20Bali%20TiHE-PoD-Empowering_Sept30-13.pdf"
# otherwise links to figshare match that only has data, not the article
override_dict["10.1126/science.aaf3777"]["free_pdf_url"] = None
override_dict["10.1126/science.aaf3777"]["free_metadata_url"] = None
#otherwise links to a metadata page that doesn't have the PDF because have to request a copy: https://openresearch-repository.anu.edu.au/handle/1885/103608
override_dict["10.1126/science.aad2622"]["free_pdf_url"] = "https://lra.le.ac.uk/bitstream/2381/38048/6/Waters%20et%20al%20draft_post%20review_v2_clean%20copy.pdf"
# otherwise led to http://www.researchonline.mq.edu.au/vital/access/services/Download/mq:39727/DS01 and authorization error
override_dict["10.1111/j.1461-0248.2008.01185.x"]["free_pdf_url"] = None
# override old-style webpage
override_dict["10.1210/jc.2016-2141"]["free_pdf_url"] = "https://academic.oup.com/jcem/article-lookup/doi/10.1210/jc.2016-2141"
override_dict["10.1210/jc.2016-2141"]["evidence"] = "hybrid manual"
# not indexing this location yet, from @rickypo
override_dict["10.1207/s15327957pspr0203_4"]["free_pdf_url"] = "http://www2.psych.ubc.ca/~schaller/528Readings/Kerr1998.pdf"
# also, work around broken url extraction from sage
override_dict["10.1207_s15327957pspr0203_4"]["free_pdf_url"] = "http://www2.psych.ubc.ca/~schaller/528Readings/Kerr1998.pdf"
return override_dict
| mit | Python |
56186c985b87fbbf0a7ea0f04c8b089a13b29fe3 | Test execution: Remove unneeded variable | Tanmay28/coala,Tanmay28/coala,meetmangukiya/coala,arush0311/coala,NalinG/coala,Tanmay28/coala,incorrectusername/coala,yashtrivedi96/coala,shreyans800755/coala,sagark123/coala,jayvdb/coala,MariosPanag/coala,Nosferatul/coala,vinc456/coala,damngamerz/coala,MattAllmendinger/coala,ManjiriBirajdar/coala,andreimacavei/coala,rresol/coala,AdeshAtole/coala,kartikeys98/coala,NalinG/coala,karansingh1559/coala,coala/coala,SambitAcharya/coala,Uran198/coala,Tanmay28/coala,nemaniarjun/coala,coala/coala,jayvdb/coala,netman92/coala,lonewolf07/coala,andreimacavei/coala,SanketDG/coala,d6e/coala,NiklasMM/coala,tltuan/coala,SanketDG/coala,refeed/coala,rimacone/testing2,SambitAcharya/coala,abhiroyg/coala,arush0311/coala,svsn2117/coala,shreyans800755/coala,sils1297/coala,arjunsinghy96/coala,rresol/coala,AbdealiJK/coala,tushar-rishav/coala,AdeshAtole/coala,NiklasMM/coala,arafsheikh/coala,scriptnull/coala,aptrishu/coala,scriptnull/coala,MattAllmendinger/coala,yland/coala,AbdealiJK/coala,SambitAcharya/coala,ayushin78/coala,arjunsinghy96/coala,yashtrivedi96/coala,FeodorFitsner/coala,SanketDG/coala,andreimacavei/coala,sils1297/coala,JohnS-01/coala,nemaniarjun/coala,mr-karan/coala,rimacone/testing2,karansingh1559/coala,incorrectusername/coala,yashLadha/coala,coala-analyzer/coala,NalinG/coala,NiklasMM/coala,saurabhiiit/coala,saurabhiiit/coala,MattAllmendinger/coala,NalinG/coala,karansingh1559/coala,Nosferatul/coala,Nosferatul/coala,ayushin78/coala,CruiseDevice/coala,d6e/coala,djkonro/coala,ManjiriBirajdar/coala,rimacone/testing2,sagark123/coala,SambitAcharya/coala,RJ722/coala,stevemontana1980/coala,kartikeys98/coala,NalinG/coala,Asnelchristian/coala,Tanmay28/coala,Uran198/coala,Shade5/coala,stevemontana1980/coala,incorrectusername/coala,Balaji2198/coala,RJ722/coala,swatilodha/coala,ManjiriBirajdar/coala,Tanmay28/coala,MariosPanag/coala,aptrishu/coala,sophiavanvalkenburg/coala,sils1297/coala,coala-analyzer/coala,RJ722/coala,arush0311/coala,saurabhiiit/coala,svsn2117/coala,vinc456/coala,refeed/coala,sophiavanvalkenburg/coala,impmihai/coala,meetmangukiya/coala,yashLadha/coala,djkonro/coala,svsn2117/coala,Shade5/coala,netman92/coala,scriptnull/coala,abhiroyg/coala,JohnS-01/coala,damngamerz/coala,tushar-rishav/coala,arafsheikh/coala,abhiroyg/coala,CruiseDevice/coala,lonewolf07/coala,ayushin78/coala,SambitAcharya/coala,sagark123/coala,tushar-rishav/coala,yland/coala,jayvdb/coala,shreyans800755/coala,JohnS-01/coala,Balaji2198/coala,impmihai/coala,swatilodha/coala,sophiavanvalkenburg/coala,stevemontana1980/coala,dagdaggo/coala,CruiseDevice/coala,coala/coala,netman92/coala,scriptnull/coala,scottbelden/coala,tltuan/coala,Asalle/coala,sudheesh001/coala,Uran198/coala,MariosPanag/coala,djkonro/coala,mr-karan/coala,SambitAcharya/coala,coala-analyzer/coala,meetmangukiya/coala,scriptnull/coala,swatilodha/coala,dagdaggo/coala,Tanmay28/coala,scottbelden/coala,impmihai/coala,dagdaggo/coala,FeodorFitsner/coala,vinc456/coala,AbdealiJK/coala,rresol/coala,NalinG/coala,d6e/coala,Shade5/coala,Asalle/coala,Tanmay28/coala,nemaniarjun/coala,Balaji2198/coala,lonewolf07/coala,arjunsinghy96/coala,yashtrivedi96/coala,aptrishu/coala,Asnelchristian/coala,yashLadha/coala,NalinG/coala,scriptnull/coala,arafsheikh/coala,scottbelden/coala,scriptnull/coala,kartikeys98/coala,yland/coala,AdeshAtole/coala,tltuan/coala,refeed/coala,Asnelchristian/coala,damngamerz/coala,mr-karan/coala,FeodorFitsner/coala,sudheesh001/coala,Asalle/coala,sudheesh001/coala,SambitAcharya/coala | execute_all_tests.py | execute_all_tests.py | #! /bin/python3
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
from coalib.tests.TestHelper import TestHelper
def show_help():
print("Usage: {name} [OPTIONS]".format(name=sys.argv[0]))
print()
print("--help : Show this help text")
print("--cover : Use coverage to get statement and branch coverage of tests")
if __name__ == '__main__':
use_coverage = False
for arg in sys.argv[1:]:
arg = str(arg).strip().lower()
if arg == "--cover" and not use_coverage:
use_coverage = True
else:
show_help()
exit()
files = TestHelper.get_test_files(os.path.abspath("coalib/tests"))
exit(TestHelper.execute_python3_files(files, use_coverage))
| #! /bin/python3
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import sys
from coalib.tests.TestHelper import TestHelper
def show_help():
print("Usage: {name} [OPTIONS]".format(name=sys.argv[0]))
print()
print("--help : Show this help text")
print("--cover : Use coverage to get statement and branch coverage of tests")
if __name__ == '__main__':
use_coverage = False
for arg in sys.argv[1:]:
arg = str(arg).strip().lower()
if arg == "--cover" and not use_coverage:
use_coverage = True
else:
show_help()
exit()
test_dir = os.path.abspath("coalib/tests")
files = TestHelper.get_test_files(test_dir)
exit(TestHelper.execute_python3_files(files, use_coverage))
| agpl-3.0 | Python |
ace9947582aec32d8e03b214bbf6e270c8978a50 | Add stack-docs clean command | lsst-sqre/documenteer,lsst-sqre/sphinxkit,lsst-sqre/documenteer | documenteer/stackdocs/stackcli.py | documenteer/stackdocs/stackcli.py | """Implements the ``stack-docs`` CLI for stack documentation builds.
"""
__all__ = ('main',)
import logging
import os
import shutil
import sys
import click
from .build import build_stack_docs
# Add -h as a help shortcut option
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(context_settings=CONTEXT_SETTINGS)
@click.option(
'-d', '--dir', 'root_project_dir',
type=click.Path(exists=True, file_okay=False, dir_okay=True,
resolve_path=True),
default='.',
help='Root Sphinx project directory'
)
@click.option(
'-v', '--verbose',
is_flag=True,
help='Enable verbose output (debug-level logging)'
)
@click.version_option()
@click.pass_context
def main(ctx, root_project_dir, verbose):
"""stack-docs is a CLI for building LSST Stack documentation, such as
pipelines.lsst.io.
"""
# Subcommands should use the click.pass_obj decorator to get this
# ctx.obj object as the first argument.
ctx.obj = {'root_project_dir': root_project_dir,
'verbose': verbose}
# Set up application logging. This ensures that only documenteer's
# logger is activated. If necessary, we can add other app's loggers too.
if verbose:
log_level = logging.DEBUG
else:
log_level = logging.INFO
logger = logging.getLogger('documenteer')
logger.addHandler(logging.StreamHandler())
logger.setLevel(log_level)
@main.command()
@click.argument('topic', default=None, required=False, nargs=1)
@click.pass_context
def help(ctx, topic, **kw):
"""Show help for any command.
"""
# The help command implementation is taken from
# https://www.burgundywall.com/post/having-click-help-subcommand
if topic is None:
click.echo(ctx.parent.get_help())
else:
click.echo(main.commands[topic].get_help(ctx))
@main.command()
@click.pass_context
def build(ctx):
"""Build documentation as HTML.
"""
return_code = build_stack_docs(ctx.obj['root_project_dir'])
if return_code > 0:
sys.exit(return_code)
@main.command()
@click.pass_context
def clean(ctx):
"""Clean Sphinx build products.
"""
logger = logging.getLogger(__name__)
dirnames = ['py-api', '_build', 'modules', 'packages']
dirnames = [os.path.join(ctx.obj['root_project_dir'], dirname)
for dirname in dirnames]
for dirname in dirnames:
if os.path.isdir(dirname):
shutil.rmtree(dirname)
logger.debug('Cleaned up %r', dirname)
else:
logger.debug('Did not clean up %r (missing)', dirname)
| """Implements the ``stack-docs`` CLI for stack documentation builds.
"""
__all__ = ('main',)
import logging
import sys
import click
from .build import build_stack_docs
# Add -h as a help shortcut option
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(context_settings=CONTEXT_SETTINGS)
@click.option(
'-d', '--dir', 'root_project_dir',
type=click.Path(exists=True, file_okay=False, dir_okay=True,
resolve_path=True),
default='.',
help='Root Sphinx project directory'
)
@click.option(
'-v', '--verbose',
is_flag=True,
help='Enable verbose output (debug-level logging)'
)
@click.version_option()
@click.pass_context
def main(ctx, root_project_dir, verbose):
"""stack-docs is a CLI for building LSST Stack documentation, such as
pipelines.lsst.io.
"""
# Subcommands should use the click.pass_obj decorator to get this
# ctx.obj object as the first argument.
ctx.obj = {'root_project_dir': root_project_dir,
'verbose': verbose}
# Set up application logging. This ensures that only documenteer's
# logger is activated. If necessary, we can add other app's loggers too.
if verbose:
log_level = logging.DEBUG
else:
log_level = logging.INFO
logger = logging.getLogger('documenteer')
logger.addHandler(logging.StreamHandler())
logger.setLevel(log_level)
@main.command()
@click.argument('topic', default=None, required=False, nargs=1)
@click.pass_context
def help(ctx, topic, **kw):
"""Show help for any command.
"""
# The help command implementation is taken from
# https://www.burgundywall.com/post/having-click-help-subcommand
if topic is None:
click.echo(ctx.parent.get_help())
else:
click.echo(main.commands[topic].get_help(ctx))
@main.command()
@click.pass_context
def build(ctx):
"""Build documentation as HTML.
"""
return_code = build_stack_docs(ctx.obj['root_project_dir'])
if return_code > 0:
sys.exit(return_code)
| mit | Python |
94e0dc267e159014675556687f52157371c5a813 | order standings by position | wefner/w2pfooty,wefner/w2pfooty,wefner/w2pfooty | controllers/matches.py | controllers/matches.py | import tempfile
from datetime import datetime
@auth.requires_login()
def next_match():
where_next_match = (((db.matches.visiting_team == auth.user.team_name) |
(db.matches.home_team == auth.user.team_name)) &
(db.matches.datetime > datetime.today()))
match = db(where_next_match).select(db.matches.ALL,
orderby=db.matches.datetime,
cache=(cache.ram, 60),
cacheable=True).first()
where_attendance = (db.attendance.match_id == match.id)
attendance = db(where_attendance).select(db.attendance.ALL)
return dict(match=match, attendance=attendance)
def divisions():
where = ((db.matches.division_id == request.args(0)))
matches = db(where).select(db.matches.ALL,
distinct=True,
orderby=db.matches.division_id|db.matches.datetime)
where_standing = (db.standings.division_id == request.args(0))
standings = db(where_standing).select(db.standings.ALL,
orderby=db.standings.pos)
return dict(matches=matches, standings=standings)
def locations():
where = ((db.matches.location_id == request.args(0)) &
(db.divisions.id == db.matches.division_id) &
(db.matches.location_id == db.locations.id))
divisions = db(where).select(db.divisions.ALL, db.locations.name,
distinct=True,
orderby=db.divisions.name)
location = divisions[0]['locations']['name']
return dict(divisions=divisions, location=location)
@auth.requires_login()
def team_calendar():
where = (db.standings.team_id == auth.user.team_name)
standings = db(where).select(db.standings.ALL)
tmp = tempfile.NamedTemporaryFile(prefix='calendar', suffix='.ics')
for standing in standings.render():
tmp.write(standing.calendar)
tmp.flush()
return response.stream(tmp.name, 512)
| import tempfile
from datetime import datetime
@auth.requires_login()
def next_match():
where_next_match = (((db.matches.visiting_team == auth.user.team_name) |
(db.matches.home_team == auth.user.team_name)) &
(db.matches.datetime > datetime.today()))
match = db(where_next_match).select(db.matches.ALL,
orderby=db.matches.datetime,
cache=(cache.ram, 60),
cacheable=True).first()
where_attendance = (db.attendance.match_id == match.id)
attendance = db(where_attendance).select(db.attendance.ALL)
return dict(match=match, attendance=attendance)
def divisions():
where = ((db.matches.division_id == request.args(0)))
# (db.standings.team_id == db.teams.id) &
# (db.standings.division_id == db.divisions.id))
matches = db(where).select(db.matches.ALL,
distinct=True,
orderby=db.matches.division_id|db.matches.datetime)
where_standing = (db.standings.division_id == request.args(0))
standings = db(where_standing).select(db.standings.ALL)
return dict(matches=matches, standings=standings)
def locations():
where = ((db.matches.location_id == request.args(0)) &
(db.divisions.id == db.matches.division_id) &
(db.matches.location_id == db.locations.id))
divisions = db(where).select(db.divisions.ALL, db.locations.name,
distinct=True,
orderby=db.divisions.name)
location = divisions[0]['locations']['name']
return dict(divisions=divisions, location=location)
@auth.requires_login()
def team_calendar():
where = (db.standings.team_id == auth.user.team_name)
standings = db(where).select(db.standings.ALL)
tmp = tempfile.NamedTemporaryFile(prefix='calendar', suffix='.ics')
for standing in standings.render():
tmp.write(standing.calendar)
tmp.flush()
return response.stream(tmp.name, 512)
| apache-2.0 | Python |
07a7a24d231a6807c1512632b903bb439d46f4e8 | remove default=uuid.uuid4, which does not work | vmprof/vmprof-server,vmprof/vmprof-server,vmprof/vmprof-server,vmprof/vmprof-server | vmlog/models.py | vmlog/models.py | import uuid
from jitlog.parser import _parse_jitlog
from django.db import models
from django.contrib import admin
from vmprofile.models import RuntimeData
from vmcache.cache import get_reader
def get_profile_storage_directory(profile, filename):
return "log/%d/%s" % (profile.pk, filename)
class BinaryJitLog(models.Model):
jitlog_id = models.CharField(max_length=64, primary_key=True)
checksum = models.CharField(max_length=128)
created = models.DateTimeField(auto_now_add=True)
file = models.FileField(upload_to=get_profile_storage_directory)
# relations
profile = models.ForeignKey(RuntimeData, related_name='jitlog',
null=True, blank=False)
def decode_forest(self):
# ultra slow, especially when run on cpython 3.5
# see vmcache.cache for a faster impl. using pypy.
# it caches the results as well (not using pickle)
with get_reader(self.file.name) as fd:
forest = _parse_jitlog(fd)
return forest
@admin.register(BinaryJitLog)
class BinaryJitLogAdmin(admin.ModelAdmin):
list_display = ('checksum', 'created', 'file', 'profile')
| import uuid
from jitlog.parser import _parse_jitlog
from django.db import models
from django.contrib import admin
from vmprofile.models import RuntimeData
from vmcache.cache import get_reader
def get_profile_storage_directory(profile, filename):
return "log/%d/%s" % (profile.pk, filename)
class BinaryJitLog(models.Model):
jitlog_id = models.CharField(max_length=64, default=uuid.uuid4, primary_key=True)
checksum = models.CharField(max_length=128)
created = models.DateTimeField(auto_now_add=True)
file = models.FileField(upload_to=get_profile_storage_directory)
# relations
profile = models.ForeignKey(RuntimeData, related_name='jitlog',
null=True, blank=False)
def decode_forest(self):
# ultra slow, especially when run on cpython 3.5
# see vmcache.cache for a faster impl. using pypy.
# it caches the results as well (not using pickle)
with get_reader(self.file.name) as fd:
forest = _parse_jitlog(fd)
return forest
@admin.register(BinaryJitLog)
class BinaryJitLogAdmin(admin.ModelAdmin):
list_display = ('checksum', 'created', 'file', 'profile')
| mit | Python |
097aa0bc21f8eea28edff148fb36146bbced92c4 | Exclude duecredit from the documentation. | arokem/sklearn-forest-ci,scikit-learn-contrib/forest-confidence-interval,arokem/sklearn-forest-ci,uwescience/sklearn-forest-ci,kpolimis/sklearn-forest-ci,scikit-learn-contrib/forest-confidence-interval,kpolimis/sklearn-forest-ci,uwescience/sklearn-forest-ci | doc/tools/buildmodref.py | doc/tools/buildmodref.py | #!/usr/bin/env python
"""Script to auto-generate API docs.
"""
from __future__ import print_function, division
# stdlib imports
import sys
import re
# local imports
from apigen import ApiDocWriter
# version comparison
from distutils.version import LooseVersion as V
#*****************************************************************************
def abort(error):
print('*WARNING* API documentation not generated: %s' % error)
exit()
def writeapi(package, outdir, source_version, other_defines=True):
# Check that the package is available. If not, the API documentation is not
# (re)generated and existing API documentation sources will be used.
try:
__import__(package)
except ImportError:
abort("Can not import " + package)
module = sys.modules[package]
# Check that the source version is equal to the installed
# version. If the versions mismatch the API documentation sources
# are not (re)generated. This avoids automatic generation of documentation
# for older or newer versions if such versions are installed on the system.
installed_version = V(module.__version__)
if source_version != installed_version:
abort("Installed version does not match source version")
docwriter = ApiDocWriter(package, rst_extension='.rst',
other_defines=other_defines)
docwriter.package_skip_patterns += [r'\.%s$' % package,
r'.*test.*$',
r'.*duecredit.*$',
r'.*due.*$',
r'\.version.*$']
docwriter.write_api_docs(outdir)
docwriter.write_index(outdir, 'index', relative_to=outdir)
print('%d files written' % len(docwriter.written_modules))
if __name__ == '__main__':
package = sys.argv[1]
outdir = sys.argv[2]
try:
other_defines = sys.argv[3]
except IndexError:
other_defines = True
else:
other_defines = other_defines in ('True', 'true', '1')
writeapi(package, outdir, other_defines=other_defines)
| #!/usr/bin/env python
"""Script to auto-generate API docs.
"""
from __future__ import print_function, division
# stdlib imports
import sys
import re
# local imports
from apigen import ApiDocWriter
# version comparison
from distutils.version import LooseVersion as V
#*****************************************************************************
def abort(error):
print('*WARNING* API documentation not generated: %s' % error)
exit()
def writeapi(package, outdir, source_version, other_defines=True):
# Check that the package is available. If not, the API documentation is not
# (re)generated and existing API documentation sources will be used.
try:
__import__(package)
except ImportError:
abort("Can not import " + package)
module = sys.modules[package]
# Check that the source version is equal to the installed
# version. If the versions mismatch the API documentation sources
# are not (re)generated. This avoids automatic generation of documentation
# for older or newer versions if such versions are installed on the system.
installed_version = V(module.__version__)
if source_version != installed_version:
abort("Installed version does not match source version")
docwriter = ApiDocWriter(package, rst_extension='.rst',
other_defines=other_defines)
docwriter.package_skip_patterns += [r'\.%s$' % package,
r'.*test.*$',
r'.*duecredit.*$',
r'\.version.*$']
docwriter.write_api_docs(outdir)
docwriter.write_index(outdir, 'index', relative_to=outdir)
print('%d files written' % len(docwriter.written_modules))
if __name__ == '__main__':
package = sys.argv[1]
outdir = sys.argv[2]
try:
other_defines = sys.argv[3]
except IndexError:
other_defines = True
else:
other_defines = other_defines in ('True', 'true', '1')
writeapi(package, outdir, other_defines=other_defines)
| mit | Python |
be29e195bbdfd9acad4841d0e241554e735baf3a | add -dev suffix to version for code in master | ASP1234/voc,pombredanne/voc,gEt-rIgHt-jR/voc,ASP1234/voc,cflee/voc,cflee/voc,gEt-rIgHt-jR/voc,freakboy3742/voc,pombredanne/voc,freakboy3742/voc | voc/__init__.py | voc/__init__.py | # Examples of valid version strings
# __version__ = '1.2.3.dev1' # Development release 1
# __version__ = '1.2.3a1' # Alpha Release 1
# __version__ = '1.2.3b1' # Beta Release 1
# __version__ = '1.2.3rc1' # RC Release 1
# __version__ = '1.2.3' # Final Release
# __version__ = '1.2.3.post1' # Post Release 1
__version__ = '0.1.2-dev'
| # Examples of valid version strings
# __version__ = '1.2.3.dev1' # Development release 1
# __version__ = '1.2.3a1' # Alpha Release 1
# __version__ = '1.2.3b1' # Beta Release 1
# __version__ = '1.2.3rc1' # RC Release 1
# __version__ = '1.2.3' # Final Release
# __version__ = '1.2.3.post1' # Post Release 1
__version__ = '0.1.2'
| bsd-3-clause | Python |
39f327bb9e37d6d290eb3f3179f7e79d60b5ab6d | Switch from ORM to Core | labhack/whiskeynovember,labhack/whiskeynovember,labhack/whiskeynovember | model.py | model.py | from sqlalchemy import create_engine
engine = create_engine('postgresql://wn:wn@localhost:5432/wndb')
from sqlalchemy import Column, Integer, Float, DateTime, Boolean, String, MetaData
metadata = MetaData()
table = Table('obs', metadata, Column(Integer, primary_key=True),
Column('station_name',String),
Column('x',Float),
Column('y',Float),
Column('z',Float),
Column('jam_indicator',Boolean),
Column('jam_intensity',Float),
Column('date_time',DateTime)
)
| from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
engine = create_engine('postgresql://wn:wn@localhost:5432/wndb')
Base = declarative_base()
from sqlalchemy import Column, Integer, Float, DateTime, Boolean, String
class Observation(Base):
__tablename__ = 'obs'
id = Column(Integer, primary_key=True)
station_name = Column(String)
x = Column(Float)
y = Column(Float)
z = Column(Float)
jam_indicator = Column(Boolean)
jam_intensity = Column(Float)
date_time = Column(DateTime)
def __repr__(self):
return "<Observation(station_name='%r', x='%f', y='%f', z='%f', jam_indicator='%r', jam_intensity='%f', date_time='%r')>" % (
self.station_name, self.x, self.y, self.z, self.jam_indicator, self.jam_intensity, self.date_time)
Base.metadata.create_all(engine)
| mit | Python |
3ccb2f688a568ff2193bf1f1e19cecc112c2054f | add losetup context manager | lamyj/tmbackup | mount.py | mount.py | import os
import subprocess
import tempfile
class mount(object):
""" Context manager mounting and un-mounting a filesystem on a temporary directory.
>>> with mount("/dev/sdc1") as directory:
... print os.listdir(directory)
"""
def __init__(self, source, command="mount", *args):
self.source = source
self.command = command
self.args = args
def __enter__(self):
""" Create a temporary directory and mount the filesystem there. Return the name
of the directory.
"""
self._directory = tempfile.mkdtemp()
subprocess.check_output(
[self.command, self.source]+list(self.args)+[self._directory])
return self._directory
def __exit__(self, exc_type, exc_val, exc_tb):
""" Unmount the filesystem and remove the temporary directory.
"""
subprocess.check_output(["umount", self._directory])
os.rmdir(self._directory)
class losetup(object):
""" Context manager mounting an un-mounting an image on a loop device. The size and
offset of the partition in the image are automatically computed using parted.
"""
def __init__(self, image):
self.image = image
def __enter__(self):
offset, size = self._get_offset_and_size()
loop = subprocess.check_output(["losetup", "-f", self.image,
"--offset", offset, "--sizelimit", size,
"--show"])
self.loop = loop.strip()
return self.loop
def __exit__(self, exc_type, exc_val, exc_tb):
subprocess.check_output(["losetup", "-d", self.loop])
def _get_offset_and_size(self):
offset, size = None, None
data = subprocess.check_output(["parted", self.image, "unit", "B", "print"])
for line in data.splitlines():
match = re.search(r"(?P<start>\d+)B\s+\d+B\s+(?P<size>\d+)B\s+hfs\+", data)
if match:
offset, size = match.groups()
break
return offset, size | import os
import subprocess
import tempfile
class mount(object):
""" Context manager mounting and un-mounting a filesystem on a temporary directory.
>>> with mount("/dev/sdc1") as directory:
... print os.listdir(directory)
"""
def __init__(self, source, command="mount", *args):
self.source = source
self.command = command
self.args = args
def __enter__(self):
""" Create a temporary directory and mount the filesystem there. Return the name
of the directory.
"""
self._directory = tempfile.mkdtemp()
subprocess.check_output(
[self.command, self.source]+list(self.args)+[self._directory])
return self._directory
def __exit__(self, exc_type, exc_val, exc_tb):
""" Unmount the filesystem and remove the temporary directory.
"""
subprocess.check_output(["umount", self._directory])
os.rmdir(self._directory)
| agpl-3.0 | Python |
a5b89ed7aa9e2fe4305f6431a3bdd675a7eda03f | Fix newline at the end of file. | honzajavorek/python.cz,honzajavorek/python.cz,honzajavorek/python.cz,honzajavorek/python.cz | web/__init__.py | web/__init__.py | # -*- coding: utf-8 -*-
from os import path
from flask import Flask
PACKAGE_DIR = path.dirname(path.realpath(__file__))
ROOT_DIR = path.realpath(path.join(PACKAGE_DIR, '..'))
ROOT_URL = 'http://pythoncz.herokuapp.com'
GITHUB_URL = (
'https://github.com/honzajavorek/python.cz/'
'blob/master/{template_folder}/{filename}'
)
app = Flask('web',
static_folder=path.join(ROOT_DIR, 'files'),
static_url_path='',
template_folder=path.join(ROOT_DIR, 'pages'))
app.config.from_object(__name__)
from . import views # NOQA
| # -*- coding: utf-8 -*-
from os import path
from flask import Flask
PACKAGE_DIR = path.dirname(path.realpath(__file__))
ROOT_DIR = path.realpath(path.join(PACKAGE_DIR, '..'))
ROOT_URL = 'http://pythoncz.herokuapp.com'
GITHUB_URL = (
'https://github.com/honzajavorek/python.cz/'
'blob/master/{template_folder}/{filename}'
)
app = Flask('web',
static_folder=path.join(ROOT_DIR, 'files'),
static_url_path='',
template_folder=path.join(ROOT_DIR, 'pages'))
app.config.from_object(__name__)
from . import views # NOQA | mit | Python |
76c09dfe2e151a59d5017b661a6f751245c35270 | Update version info | suminb/tldr-web,suminb/tldr-web,suminb/tldr-web | web/__init__.py | web/__init__.py | import os
from flask import Flask
__version__ = '0.1.2'
def create_app(name=__name__):
app = Flask(name)
from web.main import main_module
app.register_blueprint(main_module, url_prefix='/')
return app
app = create_app()
if __name__ == '__main__':
host = os.environ.get('HOST', '0.0.0.0')
port = int(os.environ.get('PORT', 8005))
debug = bool(os.environ.get('DEBUG', False))
app.run(host=host, port=port, debug=debug)
| import os
from flask import Flask
__version__ = '0.1.1'
def create_app(name=__name__):
app = Flask(name)
from web.main import main_module
app.register_blueprint(main_module, url_prefix='/')
return app
app = create_app()
if __name__ == '__main__':
host = os.environ.get('HOST', '0.0.0.0')
port = int(os.environ.get('PORT', 8005))
debug = bool(os.environ.get('DEBUG', False))
app.run(host=host, port=port, debug=debug)
| bsd-3-clause | Python |
c4f7cc009e94f50562a985d0bc377cd696580c15 | fix output utf8 | StalkR/misc,StalkR/misc,StalkR/misc,StalkR/misc,StalkR/misc,StalkR/misc,StalkR/misc,StalkR/misc | web/imdb_cli.py | web/imdb_cli.py | #!/usr/bin/python
# Search a title on IMDb and display a nice line.
import imdb
import sys
def main(argv):
if len(argv) < 2:
print 'Usage: %s <search query>' % argv[0]
raise SystemExit(0)
result = imdb.SearchTitle(' '.join(argv[1:]))
if not result:
print 'Not found.'
raise SystemExit(1)
t = result[0]
infos = [t.name + (' (%i)' % t.year if t.year else '')]
if t.genres:
infos.append(', '.join(t.genres[:3]))
if t.directors:
infos.append(', '.join(d.name for d in t.directors[:2]))
if t.actors:
infos.append(', '.join(a.name for a in t.actors[:3]))
if t.duration:
infos.append(t.duration)
if t.rating:
infos.append('%.1f/10' % t.rating)
infos.extend([t.url, 'tg'])
print ' - '.join(i.encode('utf-8') for i in infos)
if __name__ == '__main__':
main(sys.argv)
| #!/usr/bin/python
# Search a title on IMDb and display a nice line.
import imdb
import sys
def main(argv):
if len(argv) < 2:
print 'Usage: %s <search query>' % argv[0]
raise SystemExit(0)
result = imdb.SearchTitle(' '.join(argv[1:]))
if not result:
print 'Not found.'
raise SystemExit(1)
t = result[0]
infos = [t.name + (' (%i)' % t.year if t.year else '')]
if t.genres:
infos.append(', '.join(t.genres[:3]))
if t.directors:
infos.append(', '.join(d.name for d in t.directors[:2]))
if t.actors:
infos.append(', '.join(a.name for a in t.actors[:3]))
if t.duration:
infos.append(t.duration)
if t.rating:
infos.append('%.1f/10' % t.rating)
infos.extend([t.url, 'tg'])
print ' - '.join(infos)
if __name__ == '__main__':
main(sys.argv)
| apache-2.0 | Python |
6598b684892c061e1e17174e1435b5770d3f2933 | use CmsRepoException instead of KeyError | universalcore/unicore-cms,universalcore/unicore-cms,universalcore/unicore-cms | cms/__init__.py | cms/__init__.py | from cms.utils import CmsRepo, CmsRepoException
from pyramid_beaker import set_cache_regions_from_settings
from pyramid.config import Configurator
import logging
log = logging.getLogger(__name__)
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
set_cache_regions_from_settings(settings)
config = Configurator(settings=settings)
config.include('cms')
return config.make_wsgi_app()
def init_repository(config):
settings = config.registry.settings
if 'git.path' not in settings:
raise KeyError(
'Please specify the git repo path '
'e.g [app:main] git.path = %(here)s/repo/')
repo_path = settings['git.path'].strip()
if 'git.content_repo_url' in settings \
and settings['git.content_repo_url'] \
and not CmsRepo.exists(repo_path):
content_repo_url = settings['git.content_repo_url'].strip()
log.info('Cloning repository: %s' % (content_repo_url,))
repo = CmsRepo.clone(content_repo_url, repo_path)
log.info('Cloned repository into: %s' % (repo_path,))
try:
repo = CmsRepo.read(repo_path)
log.info('Using repository found in: %s' % (repo_path,))
except CmsRepoException:
repo = CmsRepo.init(
repo_path, 'Unicore CMS', 'support@unicore.io')
log.info('Initialising repository in: %s' % (repo_path,))
repo.checkout_all_upstream()
def includeme(config):
config.include('pyramid_chameleon')
config.include('pyramid_beaker')
config.include("cornice")
config.include("pyramid_celery")
config.add_static_view('static', 'cms:static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('categories', '/content/list/')
config.add_route('category', '/content/list/{category}/')
config.add_route('content', '/content/detail/{uuid}/')
config.add_route('admin_home', '/admin/')
config.add_route('configure', '/admin/configure/')
config.add_route('configure_switch', '/admin/configure/switch/')
config.add_route('check_updates', '/admin/configure/update/')
config.add_route('configure_fast_forward', '/admin/configure/fastforward/')
config.add_route('commit_log', '/admin/configure/log.json')
config.add_route('get_updates', '/admin/configure/updates.json')
config.add_route('locale', '/locale/')
config.add_route('flatpage', '/{slug}/')
config.scan()
init_repository(config)
| from cms.utils import CmsRepo
from pyramid_beaker import set_cache_regions_from_settings
from pyramid.config import Configurator
import logging
log = logging.getLogger(__name__)
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
set_cache_regions_from_settings(settings)
config = Configurator(settings=settings)
config.include('cms')
return config.make_wsgi_app()
def init_repository(config):
settings = config.registry.settings
if 'git.path' not in settings:
raise KeyError(
'Please specify the git repo path '
'e.g [app:main] git.path = %(here)s/repo/')
repo_path = settings['git.path'].strip()
if 'git.content_repo_url' in settings \
and settings['git.content_repo_url'] \
and not CmsRepo.exists(repo_path):
content_repo_url = settings['git.content_repo_url'].strip()
log.info('Cloning repository: %s' % (content_repo_url,))
repo = CmsRepo.clone(content_repo_url, repo_path)
log.info('Cloned repository into: %s' % (repo_path,))
try:
repo = CmsRepo.read(repo_path)
log.info('Using repository found in: %s' % (repo_path,))
except KeyError:
repo = CmsRepo.init(
repo_path, 'Unicore CMS', 'support@unicore.io')
log.info('Initialising repository in: %s' % (repo_path,))
repo.checkout_all_upstream()
def includeme(config):
config.include('pyramid_chameleon')
config.include('pyramid_beaker')
config.include("cornice")
config.include("pyramid_celery")
config.add_static_view('static', 'cms:static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('categories', '/content/list/')
config.add_route('category', '/content/list/{category}/')
config.add_route('content', '/content/detail/{uuid}/')
config.add_route('admin_home', '/admin/')
config.add_route('configure', '/admin/configure/')
config.add_route('configure_switch', '/admin/configure/switch/')
config.add_route('check_updates', '/admin/configure/update/')
config.add_route('configure_fast_forward', '/admin/configure/fastforward/')
config.add_route('commit_log', '/admin/configure/log.json')
config.add_route('get_updates', '/admin/configure/updates.json')
config.add_route('locale', '/locale/')
config.add_route('flatpage', '/{slug}/')
config.scan()
init_repository(config)
| bsd-2-clause | Python |
70adbbb8b575adef43ef7907e21c1e13616fd73c | Update LogisticRegr.py | konemshad/ML,mahesh-9/ML | ml/GLM/LogisticRegr.py | ml/GLM/LogisticRegr.py | from math import log,e
from ..numc import *
from .lr import LR
class LogisticRegression():
def fit(self,X,Y):
LR.fit(self,X,Y)
return self
def hypo(self,it):
res=1/(1+e**(-LR.hyp(self,it)))
return res
def cost(self):
s=0
for _ in range(self.m):
s+=self.target[_]*log(self.hypo(_))+(1-self.target[_])*log(1-self.hypo(_))
r=(-1/self.m)*s
return r
def gd(self,rate=0.001,loops=100):
for k in range(loops):
for i in range(len(self.theta)):
ts=0
for j in range(self.m):
res=(self.hypo(it=j)-self.target[j])*self.feat[j][i]
ts+=res
self.theta[i]-=rate*(1/(self.m))*(ts)
#self.theta[i]-=rate*(ts)
t=self.cost()
def predict(self,x):
self.gd()
x=np.array(x)
return x.dot(self.theta[1:])+self.theta[0]
| from math import log,e
from ..numc import *
from .lr import LR
class LogisticRegression():
def fit(self,X,Y):
LR.fit(self,X,Y)
#self.ran=0
return self
def hypo(self,it):
res=1/(1+e**(-LR.hyp(self,it)))
return res
def cost(self):
s=0
for _ in range(self.m):
s+=self.target[_]*log(self.hypo(_))+(1-self.target[_])*log(1-self.hypo(_))
r=(-1/self.m)*s
return r
def gd(self,rate=0.001,loops=100):
for k in range(loops):
for i in range(len(self.theta)):
ts=0
for j in range(self.m):
res=(self.hypo(it=j)-self.target[j])*self.feat[j][i]
ts+=res
self.theta[i]-=rate*(1/(self.m))*(ts)
#self.theta[i]-=rate*(ts)
t=self.cost()
def predict(self,x):
self.gd()
#if not self.ran:self.gd()
#else:LogisticRegression.ran+=1
x=np.array(x)
#return self._labify(x.dot(self.theta[1:]))
return x.dot(self.theta[1:])+self.theta[0]
| mit | Python |
c2ee17b335d686b44d6cd05adadc17b69797993b | fix bugs | Charleo85/SIS-Rebuild,Charleo85/SIS-Rebuild,Charleo85/SIS-Rebuild,Charleo85/SIS-Rebuild | web/web/urls.py | web/web/urls.py | """web URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from . import views
statics = static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
misc = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.home_page, name='home'),
url(r'^about/$', views.about, name='about'),
]
course = [
url(r'^course/$', views.list_item, { 'modelname' : 'course' }),
url(
r'^course/(?P<itemid>[0-9]{5})/$',
views.item_detail, { 'modelname' : 'course' },
),
]
ins = [
url(r'^instructor/$', views.list_item, { 'modelname' : 'instructor' }),
url(
r'^instructor/(?P<itemid>[a-zA-Z0-9]+)/$',
views.item_detail, { 'modelname' : 'instructor' },
),
]
stud = [
url(r'^student/$', views.list_item, { 'modelname' : 'student' }),
url(
r'^student/(?P<itemid>[a-zA-Z0-9]+)/$',
views.item_detail, { 'modelname' : 'student' },
),
]
enr = [
url(r'^enrollment/$', views.list_item, { 'modelname' : 'enrollment' }),
url(
r'^enrollment/(?P<itemid>[0-9]+)/$',
views.item_detail, { 'modelname' : 'enrollment' },
),
]
urlpatterns = statics + misc + course + ins + stud + enr
| """web URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from . import views
statics = static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
misc = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.home_page, name='home'),
url(r'^about/$', views.about, name='about'),
]
course = [
url(r'^course/$', views.list_item, { 'modelname' : 'course' }),
url(
r'^course/(?P<itemid>[0-9]{5})/$',
views.item_detail, { 'modelname' : 'course' },
),
]
ins = [
url(r'^instructor/$', views.list_item, { 'modelname' : 'instructor' }),
url(
r'^instructor/(?P<itemid>[a-zA-Z0-9]+)/$',
views.item_detail, { 'modelname' : 'instructor' },
),
]
ins = [
url(r'^student/$', views.list_item, { 'modelname' : 'student' }),
url(
r'^student/(?P<itemid>[a-zA-Z0-9]+)/$',
views.item_detail, { 'modelname' : 'student' },
),
]
enr = [
url(r'^enrollment/$', views.list_item, { 'modelname' : 'enrollment' }),
url(
r'^enrollment/(?P<itemid>[0-9]+)/$',
views.item_detail, { 'modelname' : 'enrollment' },
),
]
urlpatterns = statics + misc + course + ins + stud + enr
| bsd-3-clause | Python |
a321d58730d491417dc08c7b8370149d07b460eb | Update count python script for 2.10 | zapbot/zap-mgmt-scripts,zapbot/zap-mgmt-scripts,zapbot/zap-mgmt-scripts | count-zap-downloads.py | count-zap-downloads.py | #!/usr/bin/env python
# This script generates the dynamic data for http://zapbot.github.io/zap-mgmt-scripts/downloads.html
import glob,json,os,sys
# The file names
REL = 'v2.10.0'
CORE = 'ZAP_2.10.0_Core.zip'
CROSS = 'ZAP_2.10.0_Crossplatform.zip'
LINUX = 'ZAP_2.10.0_Linux.tar.gz'
UNIX = 'ZAP_2_10_0_unix.sh'
MAC = 'ZAP_2.10.0.dmg'
WIN32 = 'ZAP_2_10_0_windows-x32.exe'
WIN64 = 'ZAP_2_10_0_windows.exe'
counts = {}
files = sorted(glob.glob('./stats/releases-*'))
# Option to just show the last 180 days to prevent the chart getting too big
files = files[-180:]
for file in files:
with open(file) as stats_file:
stats = json.load(stats_file)
if (stats['name'] == REL):
assets = {}
for asset in stats['assets']:
name = asset['name']
count = asset['download_count']
if (name in counts):
# Ignore negative numbers - can happen when files are replaced
assets[name] = max((count - counts[name]), 0)
else:
assets[name] = count
counts[name] = count
if (files.index(file) == 0):
# Ignore the first as its just for getting a baseline
continue
else:
print(" ['%s', %d, %d, %d, %d, %d, %d, %d, '']," % (file[-15:-5],
assets[WIN64], assets[WIN32], assets[UNIX], assets[LINUX], assets[MAC], assets[CROSS], assets[CORE])) | #!/usr/bin/env python
# This script generates the dynamic data for http://zapbot.github.io/zap-mgmt-scripts/downloads.html
import glob,json,os,sys
# The file names
REL = 'v2.9.0'
CORE = 'ZAP_2.9.0_Core.zip'
CROSS = 'ZAP_2.9.0_Crossplatform.zip'
LINUX = 'ZAP_2.9.0_Linux.tar.gz'
UNIX = 'ZAP_2_9_0_unix.sh'
MAC = 'ZAP_2.9.0.dmg'
WIN32 = 'ZAP_2_9_0_windows-x32.exe'
WIN64 = 'ZAP_2_9_0_windows.exe'
counts = {}
files = sorted(glob.glob('./stats/releases-*'))
# Option to just show the last 180 days to prevent the chart getting too big
files = files[-180:]
for file in files:
with open(file) as stats_file:
stats = json.load(stats_file)
if (stats['name'] == REL):
assets = {}
for asset in stats['assets']:
name = asset['name']
count = asset['download_count']
if (name in counts):
# Ignore negative numbers - can happen when files are replaced
assets[name] = max((count - counts[name]), 0)
else:
assets[name] = count
counts[name] = count
if (files.index(file) == 0):
# Ignore the first as its just for getting a baseline
continue
else:
print(" ['%s', %d, %d, %d, %d, %d, %d, %d, '']," % (file[-15:-5],
assets[WIN64], assets[WIN32], assets[UNIX], assets[LINUX], assets[MAC], assets[CROSS], assets[CORE])) | apache-2.0 | Python |
d5deb7149c633fffe34f2a264bdba01e4d920942 | 添加 poll 函数 | encorehu/webqq | webqq/client.py | webqq/client.py | class WebQQClient(object):
def login(self, username=None, password=None):
return True
def logout(self):
pass
def heartbeat(self):
print 'Bom..bong!'
def poll(self):
return 'poll'
def run_forever(self):
i=0
while True:
i=i+1
if i>100:
break
print i
| class WebQQClient(object):
def login(self, username=None, password=None):
return True
def logout(self):
pass
def heartbeat(self):
print 'Bom..bong!'
def run_forever(self):
i=0
while True:
i=i+1
if i>100:
break
print i
| mit | Python |
54e0c6cb69f0d1cd659d4ed6f0ce3592daaf73c5 | raise error if status code not 200 in timegetter | m0re4u/SmartLight,m0re4u/SmartLight,m0re4u/SmartLight | modules/time_getter.py | modules/time_getter.py | import json
import yaml
import requests
from datetime import datetime
def light_on(yml_path="../config.yml"):
with open(yml_path) as f:
config = yaml.load(f)
r = requests.get(
"http://api.sunrise-sunset.org/json?lat={}&lng={}&date=today".format(
config['longitude'], config['latitude'])
)
if r.status_code == 200:
now = datetime.now()
data = json.loads(r.text)
sunrise = datetime.strptime(
data['results']['sunrise'], '%I:%M:%S %p').time()
sunset = datetime.strptime(
data['results']['sunset'], '%I:%M:%S %p').time()
if sunrise < now.time() < sunset:
print("It's {}, and the sun is shining!".format(now.time()))
return False, False, False
else:
print("It's {}, and the light is on!".format(now.time()))
return True, True, True
else:
raise requests.HTTPError('Could not connect to server, HTTP status code: {}'.format(r.status_code))
if __name__ == '__main__':
print(light_on())
| import json
import yaml
import requests
from datetime import datetime
def light_on(yml_path="../config.yml"):
with open(yml_path) as f:
config = yaml.load(f)
r = requests.get(
"http://api.sunrise-sunset.org/json?lat={}&lng={}&date=today".format(
config['longitude'], config['latitude'])
)
if r.status_code == 200:
now = datetime.now()
data = json.loads(r.text)
sunrise = datetime.strptime(
data['results']['sunrise'], '%I:%M:%S %p').time()
sunset = datetime.strptime(
data['results']['sunset'], '%I:%M:%S %p').time()
if sunrise < now.time() < sunset:
print("It's {}, and the sun is shining!".format(now.time()))
return False, False, False
else:
print("It's {}, and the light is on!".format(now.time()))
return True, True, True
if __name__ == '__main__':
print(light_on())
| mit | Python |
d505f346eb1efc01b1f75ea91c2e52616430645f | tweak route being tested | mozilla/make.mozilla.org,mozilla/make.mozilla.org,mozilla/make.mozilla.org,mozilla/make.mozilla.org | make_mozilla/users/tests/test_views.py | make_mozilla/users/tests/test_views.py | from django.conf import settings
from django.utils import unittest
from mock import patch, Mock
from nose.tools import eq_, ok_
from make_mozilla.base.tests.assertions import assert_routing
from make_mozilla.users import views
class LoginJumpPageTest(unittest.TestCase):
def test_that_it_routes(self):
assert_routing('/users/login/', views.login, name = 'login')
| from django.conf import settings
from django.utils import unittest
from mock import patch, Mock
from nose.tools import eq_, ok_
from make_mozilla.base.tests.assertions import assert_routing
from make_mozilla.users import views
rf = RequestFactory()
class LoginJumpPageTest(unittest.TestCase):
def test_that_it_routes(self):
assert_routing('/users/login', views.login, name = 'login')
| bsd-3-clause | Python |
5f716da231aa3f338300295695b1513aa404ae7d | Use http instead of https | lino-framework/xl,lino-framework/xl,lino-framework/xl,lino-framework/xl | lino_xl/lib/appypod/__init__.py | lino_xl/lib/appypod/__init__.py | # Copyright 2014-2019 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
"""
Adds functionality for generating printable documents using
LibreOffice and the `appy.pod <http://appyframework.org/pod.html>`__
package.
See also :ref:`lino.admin.appypod` and :doc:`/specs/appypod`.
"""
import six
from lino.api import ad, _
class Plugin(ad.Plugin):
verbose_name = _("Appy POD")
def get_requirements(self, site):
try:
import appy
# leave unchanged if it is already installed
except ImportError:
if six.PY3:
# yield "-e svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy"
yield "svn+http://svn.forge.pallavi.be/appy-dev/dev1#egg=appy"
else:
yield "appy"
def get_used_libs(self, html=None):
try:
# ~ import appy
from appy import version
version = version.verbose
except ImportError:
version = self.site.not_found_msg
yield ("Appy", version, "http://appyframework.org/pod.html")
| # Copyright 2014-2019 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
"""
Adds functionality for generating printable documents using
LibreOffice and the `appy.pod <http://appyframework.org/pod.html>`__
package.
See also :ref:`lino.admin.appypod` and :doc:`/specs/appypod`.
"""
import six
from lino.api import ad, _
class Plugin(ad.Plugin):
verbose_name = _("Appy POD")
def get_requirements(self, site):
try:
import appy
# leave unchanged if it is already installed
except ImportError:
if six.PY3:
# yield "-e svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy"
yield "svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy"
else:
yield "appy"
def get_used_libs(self, html=None):
try:
# ~ import appy
from appy import version
version = version.verbose
except ImportError:
version = self.site.not_found_msg
yield ("Appy", version, "http://appyframework.org/pod.html")
| bsd-2-clause | Python |
6f6bf45582ad06977e890d295b85290b1d169a01 | update doc | pfnet/chainercv,yuyu2172/chainercv,chainer/chainercv,chainer/chainercv,yuyu2172/chainercv | chainercv/transforms/image/pca_lighting.py | chainercv/transforms/image/pca_lighting.py | import numpy
def pca_lighting(img, sigma, eigen_value=None, eigen_vector=None):
"""AlexNet style color augmentation
This method adds a noise vector drawn from a Gaussian. The direction of
the Gaussian is same as that of the principal components of the dataset.
This method is used in training of AlexNet [1].
.. [1] Alex Krizhevsky, Ilya Sutskever, Geoffrey E. Hinton. \
ImageNet Classification with Deep Convolutional Neural Networks. \
NIPS 2012.
Args:
image (numpy.ndarray): An image array to be augmented. This is in
CHW format.
sigma (float): Standard deviation of the Gaussian. In the original
paper, this value is 10% of the range of intensity
(25.5 if the range is [0, 255]).
eigen_value: (numpy.ndarray): An array of eigen values. The shape
have to be (3,). If it is not specified, the values computed from
ImageNet are used.
eigen_vector: (numpy.ndarray): An array of eigen vectors. The shape
have to be (3, 3). If it is not specified, the vectors computed
from ImageNet are used.
Returns:
An image in CHW format.
"""
if sigma <= 0:
return img
# these values are copied from facebook/fb.resnet.torch
if eigen_value is None:
eigen_value = numpy.array((0.2175, 0.0188, 0.0045))
if eigen_vector is None:
eigen_vector = numpy.array((
(0.4009, -0.814, 0.4203),
(0.7192, -0.0045, -0.6948),
(-0.5675, -0.5808, -0.5836)))
alpha = numpy.random.normal(0, sigma, size=3)
img = img.copy()
img += eigen_vector.dot(eigen_value * alpha).reshape(-1, 1, 1)
return img
| import numpy
def pca_lighting(img, sigma, eigen_value=None, eigen_vector=None):
"""Alter the intensities of input image using PCA.
This is used in training of AlexNet [1].
.. [1] Alex Krizhevsky, Ilya Sutskever, Geoffrey E. Hinton. \
ImageNet Classification with Deep Convolutional Neural Networks. \
NIPS 2012.
Args:
image (numpy.ndarray): An image array to be augmented. This is in
CHW format.
sigma (float): Standard deviation of the Gaussian. In the original
paper, this value is 10% of the range of intensity
(25.5 if the range is [0, 255]).
eigen_value: (numpy.ndarray): An array of eigen values. The shape
have to be (3,). If it is not specified, the values computed from
ImageNet are used.
eigen_vector: (numpy.ndarray): An array of eigen vectors. The shape
have to be (3, 3). If it is not specified, the vectors computed
from ImageNet are used.
Returns:
An image in CHW format.
"""
if sigma <= 0:
return img
# these values are copied from facebook/fb.resnet.torch
if eigen_value is None:
eigen_value = numpy.array((0.2175, 0.0188, 0.0045))
if eigen_vector is None:
eigen_vector = numpy.array((
(0.4009, -0.814, 0.4203),
(0.7192, -0.0045, -0.6948),
(-0.5675, -0.5808, -0.5836)))
alpha = numpy.random.normal(0, sigma, size=3)
img = img.copy()
img += eigen_vector.dot(eigen_value * alpha).reshape(-1, 1, 1)
return img
| mit | Python |
b49f733d675d537779bed931d0a079888a83a735 | Revert "Bump dev version to 0.3.0-dev.1" | missionpinball/mpf-monitor | mpfmonitor/_version.py | mpfmonitor/_version.py | # mpf-monitor
__version__ = '0.2.0-dev.3'
__short_version__ = '0.2'
__bcp_version__ = '1.1'
__config_version__ = '4'
__mpf_version_required__ = '0.33.0.dev15'
version = "MPF Monitor v{} (config_version={}, BCP v{}, Requires MPF v{})".format(
__version__, __config_version__, __bcp_version__, __mpf_version_required__)
| # mpf-monitor
__version__ = '0.3.0-dev.1'
__short_version__ = '0.3'
__bcp_version__ = '1.1'
__config_version__ = '4'
__mpf_version_required__ = '0.33.0'
version = "MPF Monitor v{} (config_version={}, BCP v{}, Requires MPF v{})".format(
__version__, __config_version__, __bcp_version__, __mpf_version_required__)
| mit | Python |
e353ec6950edc4137cd8fa937e40cb0f6c76ca86 | Add support for lists to assert_equal_ignore | CybOXProject/python-cybox | cybox/test/__init__.py | cybox/test/__init__.py | import json
def assert_equal_ignore(item1, item2, ignore_keys=None):
"""Recursively compare two dictionaries, ignoring differences in some keys.
"""
if not ignore_keys:
ignore_keys = []
if isinstance(item1, dict) and isinstance(item2, dict):
item1keys = set(item1.keys())
item2keys = set(item2.keys())
ignore = set(ignore_keys)
compare_keys = (item1keys | item2keys) - ignore
for k in compare_keys:
assert k in item1, "Item 1 is missing %s" % k
assert k in item2, "Item 2 is missing %s" % k
assert_equal_ignore(item1.get(k), item2.get(k), ignore_keys)
elif isinstance(item1, list) and isinstance(item2, list):
assert len(item1) == len(item2), "Lists are of different lengths"
for (x, y) in zip(item1, item2):
assert_equal_ignore(x, y, ignore_keys)
else:
assert item1 == item2, "%s != %s" % (item1, item2)
def round_trip(o, output=False, list_=False):
""" Performs all four conversions to verify import/export functionality.
1. Object->JSON
2. JSON->Object
3. Object->XML
4. XML->Object
It returns the object from the last test, so tests which call this function
can check to ensure it was not modified during any of the transforms.
"""
klass = o.__class__
# object to dict
if list_:
d = o.to_list()
else:
d = o.to_dict()
# dict to JSON-string
s = json.dumps(d)
if output:
print(s)
# JSON-string to dict
d2 = json.loads(s)
# dict to object
if list_:
o2 = klass.from_list(d2)
else:
o2 = klass.from_dict(d2)
# object to XML-object
xobj = o2.to_obj()
# object to XML string
if output:
print(o2.to_xml())
# TODO: XML-string to XML-object.
# XML-object to object
o3 = klass.from_obj(xobj)
return o3
def round_trip_dict(cls, dict_):
obj = cls.object_from_dict(dict_)
dict2 = cls.dict_from_object(obj)
return dict2
def round_trip_list(cls, list_):
obj = cls.object_from_list(list_)
list2 = cls.list_from_object(obj)
return list2
| import json
def assert_equal_ignore(item1, item2, ignore_keys=None):
"""Recursively compare two dictionaries, ignoring differences in some keys.
"""
if not ignore_keys:
ignore_keys = []
if not (isinstance(item1, dict) and isinstance(item2, dict)):
assert item1 == item2, "%s != %s" % (item1, item2)
else:
item1keys = set(item1.keys())
item2keys = set(item2.keys())
ignore = set(ignore_keys)
compare_keys = (item1keys | item2keys) - ignore
for k in compare_keys:
assert k in item1, "Item 1 is missing %s" % k
assert k in item2, "Item 2 is missing %s" % k
assert_equal_ignore(item1.get(k), item2.get(k), ignore_keys)
def round_trip(o, output=False, list_=False):
""" Performs all four conversions to verify import/export functionality.
1. Object->JSON
2. JSON->Object
3. Object->XML
4. XML->Object
It returns the object from the last test, so tests which call this function
can check to ensure it was not modified during any of the transforms.
"""
klass = o.__class__
# object to dict
if list_:
d = o.to_list()
else:
d = o.to_dict()
# dict to JSON-string
s = json.dumps(d)
if output:
print(s)
# JSON-string to dict
d2 = json.loads(s)
# dict to object
if list_:
o2 = klass.from_list(d2)
else:
o2 = klass.from_dict(d2)
# object to XML-object
xobj = o2.to_obj()
# object to XML string
if output:
print(o2.to_xml())
# TODO: XML-string to XML-object.
# XML-object to object
o3 = klass.from_obj(xobj)
return o3
def round_trip_dict(cls, dict_):
obj = cls.object_from_dict(dict_)
dict2 = cls.dict_from_object(obj)
return dict2
def round_trip_list(cls, list_):
obj = cls.object_from_list(list_)
list2 = cls.list_from_object(obj)
return list2
| bsd-3-clause | Python |
0c29ee8be7ba2ccb9dd16c98065b56f1c6e4c92e | fix lint | plotly/dash,plotly/dash,plotly/dash,plotly/dash,plotly/dash | dash/testing/plugin.py | dash/testing/plugin.py | # pylint: disable=missing-docstring,redefined-outer-name
import pytest
from selenium import webdriver
from dash.testing.application_runners import ThreadedRunner, ProcessRunner
from dash.testing.browser import Browser
from dash.testing.composite import DashComposite
WEBDRIVERS = {
"Chrome": webdriver.Chrome,
"Firefox": webdriver.Firefox,
"Remote": webdriver.Remote,
}
def pytest_addoption(parser):
# Add options to the pytest parser, either on the commandline or ini
# TODO add more options for the selenium driver.
dash = parser.getgroup("Dash", "Dash Integration Tests")
dash.addoption(
"--webdriver",
choices=tuple(WEBDRIVERS.keys()),
default="Chrome",
help="Name of the selenium driver to use",
)
###############################################################################
# Fixtures
###############################################################################
@pytest.fixture
def dash_thread_server():
"""Start a local dash server in a new thread"""
with ThreadedRunner() as starter:
yield starter
@pytest.fixture
def dash_process_server():
"""Start a Dash server with subprocess.Popen and waitress-serve"""
with ProcessRunner() as starter:
yield starter
@pytest.fixture
def dash_br(request):
with Browser(request.config.getoption("webdriver")) as browser:
yield browser
@pytest.fixture
def dash_duo(request, dash_thread_server):
with DashComposite(
dash_thread_server, request.config.getoption("webdriver")
) as dc:
yield dc
| # pylint: disable=missing-docstring
import pytest
from selenium import webdriver
from dash.testing.application_runners import ThreadedRunner, ProcessRunner
from dash.testing.browser import Browser
from dash.testing.composite import DashComposite
WEBDRIVERS = {
"Chrome": webdriver.Chrome,
"Firefox": webdriver.Firefox,
"Remote": webdriver.Remote,
}
def pytest_addoption(parser):
# Add options to the pytest parser, either on the commandline or ini
# TODO add more options for the selenium driver.
dash = parser.getgroup("Dash", "Dash Integration Tests")
dash.addoption(
"--webdriver",
choices=tuple(WEBDRIVERS.keys()),
default="Chrome",
help="Name of the selenium driver to use",
)
###############################################################################
# Fixtures
###############################################################################
@pytest.fixture
def dash_thread_server():
"""Start a local dash server in a new thread"""
with ThreadedRunner() as starter:
yield starter
@pytest.fixture
def dash_process_server():
"""Start a Dash server with subprocess.Popen and waitress-serve"""
with ProcessRunner() as starter:
yield starter
@pytest.fixture
def dash_br(request):
with Browser(request.config.getoption("webdriver")) as browser:
yield browser
@pytest.fixture
def dash_duo(request, dash_thread_server):
with DashComposite(
dash_thread_server, request.config.getoption("webdriver")
) as dc:
yield dc
| mit | Python |
b8c82af3b98e30ca9447d610a6a6b5859c1c90de | Bump version to 0.21.11 | b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril | mythril/__version__.py | mythril/__version__.py | """This file contains the current Mythril version.
This file is suitable for sourcing inside POSIX shell, e.g. bash as well
as for importing into Python.
"""
__version__ = "v0.21.11"
| """This file contains the current Mythril version.
This file is suitable for sourcing inside POSIX shell, e.g. bash as well
as for importing into Python.
"""
__version__ = "v0.21.10"
| mit | Python |
07726b187b6dc6a6c49a3ea701cd1f1be11cb6d0 | Use mocks to test the decorators. | jaapverloop/knot | test_knot.py | test_knot.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from mock import MagicMock
from knot import Container, factory, service, provider
class TestContainer(unittest.TestCase):
def test_returns_return_value_provider(self):
c = Container()
def foo(container):
return 'bar'
c.add_provider(foo, False)
self.assertEqual(c.provide('foo'), 'bar')
def test_returns_value(self):
c = Container({'value': 'foobar'})
self.assertEqual(c.provide('value'), 'foobar')
def test_returns_default(self):
c = Container()
self.assertEqual(c.provide('foo', 'bar'), 'bar')
def test_caches_return_value_provider(self):
c = Container()
def foobar(container):
return {}
c.add_provider(foobar, True)
self.assertFalse(c.is_cached('foobar'))
dict1 = c.provide('foobar')
dict2 = c.provide('foobar')
self.assertTrue(c.is_cached('foobar'))
assert isinstance(dict1, dict)
assert isinstance(dict2, dict)
assert dict1 is dict2
def test_uses_alternative_name(self):
c = Container()
def foobar(container):
return 'foobar'
c.add_provider(foobar, False, 'foobaz')
self.assertEqual(c.provide('foobaz'), 'foobar')
def test_registers_factory_with_decorator(self):
c = Container()
c.add_factory = MagicMock()
@factory(c)
def foo(container):
return 'bar'
c.add_factory.assert_called_once_with(foo, None)
def test_registers_service_with_decorator(self):
c = Container()
c.add_service = MagicMock()
@service(c)
def foo(container):
return 'bar'
c.add_service.assert_called_once_with(foo, None)
def test_registers_provider_with_decorator(self):
c = Container()
c.add_provider = MagicMock()
@provider(c, False)
def foo(container):
return 'bar'
c.add_provider.assert_called_once_with(foo, False, None)
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from knot import Container, factory, service, provider
class TestContainer(unittest.TestCase):
def test_returns_return_value_provider(self):
c = Container()
def foo(container):
return 'bar'
c.add_provider(foo, False)
self.assertEqual(c.provide('foo'), 'bar')
def test_returns_value(self):
c = Container({'value': 'foobar'})
self.assertEqual(c.provide('value'), 'foobar')
def test_returns_default(self):
c = Container()
self.assertEqual(c.provide('foo', 'bar'), 'bar')
def test_caches_return_value_provider(self):
c = Container()
def foobar(container):
return {}
c.add_provider(foobar, True)
self.assertFalse(c.is_cached('foobar'))
dict1 = c.provide('foobar')
dict2 = c.provide('foobar')
self.assertTrue(c.is_cached('foobar'))
assert isinstance(dict1, dict)
assert isinstance(dict2, dict)
assert dict1 is dict2
def test_uses_alternative_name(self):
c = Container()
def foobar(container):
return 'foobar'
c.add_provider(foobar, False, 'foobaz')
self.assertEqual(c.provide('foobaz'), 'foobar')
def test_registers_factory_with_decorator(self):
c = Container()
@factory(c)
def foo(container):
return 'bar'
self.assertEqual(c.provide('foo'), 'bar')
def test_registers_service_with_decorator(self):
c = Container()
@service(c)
def foo(container):
return 'bar'
self.assertEqual(c.provide('foo'), 'bar')
def test_registers_provider_with_decorator(self):
c = Container()
@provider(c, False)
def foo(container):
return 'bar'
self.assertEqual(c.provide('foo'), 'bar')
if __name__ == '__main__':
unittest.main()
| mit | Python |
a36d128a1af653760a7ea20f803e3f39d4e514e5 | Use the new optional argument to endRequest in the middleware | SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange | app/soc/middleware/value_store.py | app/soc/middleware/value_store.py | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Middleware to set up and empty the value store.
"""
__authors__ = [
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class ValueStoreMiddleware(object):
"""Middleware class to set up and empty the value store.
"""
def start(self, request):
"""Sets up the value store.
Args:
request: a Django HttpRequest object
"""
core = callback.getCore()
core.startNewRequest(request)
def end(self, request, optional):
"""Empties the value store.
Args:
request: a Django HttpRequest object
"""
core = callback.getCore()
core.endRequest(request, optional)
def process_request(self, request):
"""Called when a request is made.
See the Django middleware documentation for an explanation of
the method signature.
"""
self.start(request)
def process_response(self, request, response):
"""Called when a response is returned.
See the Django middleware documentation for an explanation of
the method signature.
"""
self.end(request, True)
return response
def process_exception(self, request, exception):
"""Called when an uncaught exception is raised.
See the Django middleware documentation for an explanation of
the method signature.
"""
self.end(request, False)
| #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Middleware to set up and empty the value store.
"""
__authors__ = [
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
from soc.modules import callback
class ValueStoreMiddleware(object):
"""Middleware class to set up and empty the value store.
"""
def start(self, request):
"""Sets up the value store.
Args:
request: a Django HttpRequest object
"""
core = callback.getCore()
core.startNewRequest(request)
def end(self, request):
"""Empties the value store.
Args:
request: a Django HttpRequest object
"""
core = callback.getCore()
core.endRequest(request)
def process_request(self, request):
"""Called when a request is made.
See the Django middleware documentation for an explanation of
the method signature.
"""
self.start(request)
def process_response(self, request, response):
"""Called when a response is returned.
See the Django middleware documentation for an explanation of
the method signature.
"""
self.end(request)
return response
def process_exception(self, request, exception):
"""Called when an uncaught exception is raised.
See the Django middleware documentation for an explanation of
the method signature.
"""
self.end(request)
| apache-2.0 | Python |
60a4010e25404e0211e938a2a2109e9244273d78 | fix for filer_gui_file_thumb templatetag | rouxcode/django-filer-addons,rouxcode/django-filer-addons,rouxcode/django-filer-addons,rouxcode/django-filer-addons | filer_addons/filer_gui/templatetags/filer_gui_tags.py | filer_addons/filer_gui/templatetags/filer_gui_tags.py | from django import template
from easy_thumbnails.exceptions import InvalidImageFormatError
from easy_thumbnails.files import get_thumbnailer
# support very big images
# https://stackoverflow.com/questions/51152059/pillow-in-python-wont-let-me-open-image-exceeds-limit
import PIL.Image
PIL.Image.MAX_IMAGE_PIXELS = 933120000
from filer.models import Image
from .. import conf
register = template.Library()
@register.simple_tag(takes_context=False)
def filer_gui_file_thumb(obj, context='change_list'):
if isinstance(obj, Image):
thumbnailer = get_thumbnailer(obj.file)
thumbnail_options = {'size': conf.CHANGE_LIST_THUMB_SIZE}
if context == 'field':
thumbnail_options = {'size': conf.FIELD_THUMB_SIZE}
try:
return thumbnailer.get_thumbnail(thumbnail_options).url
except (InvalidImageFormatError, FileNotFoundError) as e:
pass
if obj.file and obj.file.path.endswith('.pdf'):
return '/static/filer/icons/file-pdf.svg'
return '/static/filer/icons/file-unknown.svg'
| from django import template
from easy_thumbnails.exceptions import InvalidImageFormatError
from easy_thumbnails.files import get_thumbnailer
# support very big images
# https://stackoverflow.com/questions/51152059/pillow-in-python-wont-let-me-open-image-exceeds-limit
import PIL.Image
PIL.Image.MAX_IMAGE_PIXELS = 933120000
from filer.models import Image
from .. import conf
register = template.Library()
@register.simple_tag(takes_context=False)
def filer_gui_file_thumb(obj, context='change_list'):
if isinstance(obj, Image):
thumbnailer = get_thumbnailer(obj.file)
thumbnail_options = {'size': conf.CHANGE_LIST_THUMB_SIZE}
try:
return thumbnailer.get_thumbnail(thumbnail_options).url
except (InvalidImageFormatError, FileNotFoundError) as e:
pass
if obj.file and obj.file.path.endswith('.pdf'):
return '/static/filer/icons/file-pdf.svg'
return '/static/filer/icons/file-unknown.svg'
| mit | Python |
aa077a89ac66787a90fcf066c5466a8152d8dc31 | Set final_link field of Work model as optional | fernandolobato/balarco,fernandolobato/balarco,fernandolobato/balarco | works/models.py | works/models.py | from django.db import models
from django.contrib.auth.models import User
from clients.models import Client, Contact
from balarco import utils
class WorkType(models.Model):
name = models.CharField(max_length=100)
class ArtType(models.Model):
work_type = models.ForeignKey(WorkType, related_name='art_types', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
class Iguala(models.Model):
client = models.ForeignKey(Client, related_name='igualas', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
start_date = models.DateField()
end_date = models.DateField()
class ArtIguala(models.Model):
iguala = models.ForeignKey(Iguala, related_name='art_iguala', on_delete=models.CASCADE)
art_type = models.ForeignKey(ArtType, related_name='art_iguala', on_delete=models.CASCADE)
quantity = models.IntegerField()
class Status(models.Model):
status_id = models.IntegerField(choices=utils.STATUS)
def __str__(self):
return utils.STATUS[self.status_id][1]
class Work(models.Model):
executive = models.ForeignKey(User, related_name='managed_works', on_delete=models.CASCADE)
contact = models.ForeignKey(Contact, related_name='works', on_delete=models.CASCADE)
current_status = models.ForeignKey(Status, related_name='works', on_delete=models.CASCADE)
work_type = models.ForeignKey(WorkType, related_name='works', on_delete=models.CASCADE)
iguala = models.ForeignKey(Iguala, related_name='works', on_delete=models.CASCADE, blank=True)
creation_date = models.DateField()
name = models.CharField(max_length=100)
expected_delivery_date = models.DateField()
brief = models.TextField()
final_link = models.CharField(max_length=1000, blank=True)
class ArtWork(models.Model):
work = models.ForeignKey(Work, related_name='art_works', on_delete=models.CASCADE)
art_type = models.ForeignKey(ArtType, related_name='art_works', on_delete=models.CASCADE)
quantity = models.IntegerField()
class File(models.Model):
work = models.ForeignKey(Work, related_name='files', on_delete=models.CASCADE)
upload = models.FileField(upload_to='work_files/')
class WorkDesigner(models.Model):
designer = models.ForeignKey(User, related_name='asigned_works', on_delete=models.CASCADE)
work = models.ForeignKey(Work, related_name='work_designers', on_delete=models.CASCADE)
start_date = models.DateField()
end_date = models.DateField()
class StatusChange(models.Model):
work = models.ForeignKey(Work, related_name='status_changes', on_delete=models.CASCADE)
status = models.ForeignKey(Status, related_name='status_changes', on_delete=models.CASCADE)
date = models.DateField()
| from django.db import models
from django.contrib.auth.models import User
from clients.models import Client, Contact
from balarco import utils
class WorkType(models.Model):
name = models.CharField(max_length=100)
class ArtType(models.Model):
work_type = models.ForeignKey(WorkType, related_name='art_types', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
class Iguala(models.Model):
client = models.ForeignKey(Client, related_name='igualas', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
start_date = models.DateField()
end_date = models.DateField()
class ArtIguala(models.Model):
iguala = models.ForeignKey(Iguala, related_name='art_iguala', on_delete=models.CASCADE)
art_type = models.ForeignKey(ArtType, related_name='art_iguala', on_delete=models.CASCADE)
quantity = models.IntegerField()
class Status(models.Model):
status_id = models.IntegerField(choices=utils.STATUS)
def __str__(self):
return utils.STATUS[self.status_id][1]
class Work(models.Model):
executive = models.ForeignKey(User, related_name='managed_works', on_delete=models.CASCADE)
contact = models.ForeignKey(Contact, related_name='works', on_delete=models.CASCADE)
current_status = models.ForeignKey(Status, related_name='works', on_delete=models.CASCADE)
work_type = models.ForeignKey(WorkType, related_name='works', on_delete=models.CASCADE)
iguala = models.ForeignKey(Iguala, related_name='works', on_delete=models.CASCADE, blank=True)
creation_date = models.DateField()
name = models.CharField(max_length=100)
expected_delivery_date = models.DateField()
brief = models.TextField()
final_link = models.CharField(max_length=1000)
class ArtWork(models.Model):
work = models.ForeignKey(Work, related_name='art_works', on_delete=models.CASCADE)
art_type = models.ForeignKey(ArtType, related_name='art_works', on_delete=models.CASCADE)
quantity = models.IntegerField()
class File(models.Model):
work = models.ForeignKey(Work, related_name='files', on_delete=models.CASCADE)
upload = models.FileField(upload_to='work_files/')
class WorkDesigner(models.Model):
designer = models.ForeignKey(User, related_name='asigned_works', on_delete=models.CASCADE)
work = models.ForeignKey(Work, related_name='work_designers', on_delete=models.CASCADE)
start_date = models.DateField()
end_date = models.DateField()
class StatusChange(models.Model):
work = models.ForeignKey(Work, related_name='status_changes', on_delete=models.CASCADE)
status = models.ForeignKey(Status, related_name='status_changes', on_delete=models.CASCADE)
date = models.DateField()
| mit | Python |
eb6b21ed3cbb1607910f10c21a93d120591d1190 | move to wasabi for printing messages | datascopeanalytics/scrubadub,deanmalmgren/scrubadub,deanmalmgren/scrubadub,datascopeanalytics/scrubadub | tests/run.py | tests/run.py | #!/usr/bin/env python
"""Run the test suite that is specified in the .travis.yml file
"""
import os
import sys
import subprocess
import yaml
from wasabi import msg
def run_test(command, directory):
"""Execute a command that runs a test"""
wrapped_command = "cd %s && %s" % (directory, command)
pipe = subprocess.Popen(
wrapped_command, shell=True,
)
pipe.wait()
if pipe.returncode == 0:
msg.good("TEST PASSED")
else:
msg.fail("TEST FAILED")
return pipe.returncode
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# load the script tests from the .travis.yml file
with open(os.path.join(root_dir, '.travis.yml')) as stream:
travis_yml = yaml.safe_load(stream.read())
tests = travis_yml['script']
# run the tests
if isinstance(tests, str):
returncode = run_test(tests, root_dir)
elif isinstance(tests, (list, tuple)):
returncode = 0
for test in tests:
returncode += run_test(test, root_dir)
if returncode == 0:
msg.good("ALL TESTS PASSED")
else:
msg.fail("SOME TESTS FAILED, SEE ABOVE")
sys.exit(returncode)
| #!/usr/bin/env python
"""Run the test suite that is specified in the .travis.yml file
"""
import os
import sys
import subprocess
import yaml
from colors import green, red
def run_test(command, directory):
"""Execute a command that runs a test"""
wrapped_command = "cd %s && %s" % (directory, command)
pipe = subprocess.Popen(
wrapped_command, shell=True,
)
pipe.wait()
if pipe.returncode == 0:
print(green("TEST PASSED"))
else:
print(red("TEST FAILED"))
return pipe.returncode
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# load the script tests from the .travis.yml file
with open(os.path.join(root_dir, '.travis.yml')) as stream:
travis_yml = yaml.safe_load(stream.read())
tests = travis_yml['script']
# run the tests
if isinstance(tests, str):
returncode = run_test(tests, root_dir)
elif isinstance(tests, (list, tuple)):
returncode = 0
for test in tests:
returncode += run_test(test, root_dir)
if returncode == 0:
print(green("ALL TESTS PASSED"))
else:
print(red("SOME TESTS FAILED, SEE ABOVE"))
sys.exit(returncode)
| mit | Python |
ad1131a3382963a4a17f78ed12194aeb67a2a240 | Clean up lint and long lines in local.py | yougov/pmxbot,yougov/pmxbot,yougov/pmxbot | local.py | local.py | """
Local pmxbot extensions, incude the path to this file in your config.yaml.
"""
import random
import urllib
from pmxbot import command, execdelay
@command("yahoolunch", doc="Find a random neary restaurant for lunch using "
"Yahoo Local. Defaults to 1 mile radius, but append Xmi to the end to "
"change the radius.")
def lunch(client, event, channel, nick, rest):
yahooid = "eeGETYOUROWN.yu"
from yahoo.search.local import LocalSearch
location = rest.strip()
if location.endswith('mi'):
radius, location = ''.join(reversed(location)).split(' ', 1)
location = ''.join(reversed(location))
radius = ''.join(reversed(radius))
radius = float(radius.replace('mi', ''))
else:
radius = 1
srch = LocalSearch(app_id=yahooid, category=96926236, results=20,
query="lunch", location=location, radius=radius)
res = srch.parse_results()
limit = min(250, res.totalResultsAvailable)
num = random.randint(1, limit) - 1
if num < 19:
selection = res.results[num]
else:
srch = LocalSearch(app_id=yahooid, category=96926236, results=20,
query="lunch", location=location, start=num)
res = srch.parse_results()
selection = res.results[0]
return '{Title} @ {Address} - {Url}'.format(**selection)
@command("paste", aliases=(), doc="Drop a link to your latest paste on "
"http://libpa.st")
def paste(client, event, channel, nick, rest):
request = urllib.urlopen("http://libpa.st/last/%s" % nick)
post_url = request.geturl()
if post_url and request.getcode() == 200:
return post_url
else:
return ("hmm.. I didn't find a recent paste of yours, %s. Checkout "
"http://libpa.st" % nick)
@execdelay("hi", channel="#botone", howlong=10)
def howdy(client, event):
return "Howdy everybody!"
| """
Local pmxbot extensions, incude the path to this file in your config.yaml.
"""
@command("yahoolunch", doc="Find a random neary restaurant for lunch using Yahoo Local. Defaults to 1 mile radius, but append Xmi to the end to change the radius.")
def lunch(client, event, channel, nick, rest):
yahooid = "eeGETYOUROWN.yu"
from yahoo.search.local import LocalSearch
location = rest.strip()
if location.endswith('mi'):
radius, location = ''.join(reversed(location)).split(' ', 1)
location = ''.join(reversed(location))
radius = ''.join(reversed(radius))
radius = float(radius.replace('mi', ''))
else:
radius = 1
srch = LocalSearch(app_id=yahooid, category=96926236, results=20, query="lunch", location=location, radius=radius)
res = srch.parse_results()
max = res.totalResultsAvailable if res.totalResultsAvailable < 250 else 250
num = random.randint(1, max) - 1
if num < 19:
choice = res.results[num]
else:
srch = LocalSearch(app_id=yahooid, category=96926236, results=20, query="lunch", location=location, start=num)
res = srch.parse_results()
choice = res.results[0]
return '%s @ %s - %s' % (choice['Title'], choice['Address'], choice['Url'])
@command("paste", aliases=(), doc="Drop a link to your latest paste on http://libpa.st")
def paste(client, event, channel, nick, rest):
request = urllib.urlopen("http://libpa.st/last/%s" % nick)
post_url = request.geturl()
if post_url and request.getcode() == 200:
return post_url
else:
return "hmm.. I didn't find a recent paste of yours, %s. Checkout http://libpa.st" % nick
@execdelay("hi", channel="#botone", howlong=10)
def howdy(client, event):
return "Howdy everybody!"
| mit | Python |
11a144016b66361d79e1fdcc5e6b15085051929b | add websites to admin | Fresnoy/kart,Fresnoy/kart | common/admin.py | common/admin.py | from django.contrib import admin
from .models import Website
admin.site.register(Website)
| from django.contrib import admin
# Register your models here.
| agpl-3.0 | Python |
55d95118d3d694bef0656a4403d7a24e321cf332 | Update to set functions. | iShoto/testpy | codes/20200107_arcface_pytorch/src/temp.py | codes/20200107_arcface_pytorch/src/temp.py | from __future__ import print_function
import os
import numpy as np
import random
import time
import torch
from torch.utils import data
import torch.nn.functional as F
from torch.nn import DataParallel
from torch.optim.lr_scheduler import StepLR
import torchvision
from config import config
from utils import visualizer, view_model
from data import dataset
from models import resnet, metrics
#from test import *
import test
def main():
device = torch.device("cuda")
model = resnet.resnet18()
print(model)
num_classes = 13938
easy_margin = False
metric_fc = metrics.ArcMarginProduct(512, num_classes, s=30, m=0.5, easy_margin=easy_margin)
model.to(device)
model = DataParallel(model)
metric_fc.to(device)
metric_fc = DataParallel(metric_fc)
lr = 1e-1 # initial learning rate
lr_step = 10
weight_decay = 5e-4
optimizer = torch.optim.SGD([{'params': model.parameters()},
{'params': metric_fc.parameters()}],
lr=lr, weight_decay=weight_decay)
scheduler = StepLR(optimizer, step_size=lr_step, gamma=0.1)
if __name__ == '__main__':
main() | from __future__ import print_function
import os
import numpy as np
import random
import time
import torch
from torch.utils import data
import torch.nn.functional as F
from torch.nn import DataParallel
from torch.optim.lr_scheduler import StepLR
import torchvision
from config import config
from utils import visualizer, view_model
from data import dataset
from models import resnet
#from test import *
import test
def main():
model = resnet.resnet18()
print(model)
if __name__ == '__main__':
main() | mit | Python |
329305b3da831bff3b883e368396f7c74b0bea90 | print slug of new docs | hoover/search,hoover/search,hoover/search | collector/management/commands/configure.py | collector/management/commands/configure.py | import yaml
from django.core.management.base import BaseCommand
from django.utils.module_loading import import_string
from ...models import Document
class Command(BaseCommand):
help = "Imprt configuration file"
def add_arguments(self, parser):
parser.add_argument('config_path')
def handle(self, verbosity, config_path, **options):
with open(config_path) as f:
config = yaml.load(f)
for collection in config['collections']:
loader_cls = import_string(collection['loader'])
loader = loader_cls(**collection)
for data in loader.documents():
(doc, created) = Document.objects.get_or_create(
slug=data.pop('slug'),
defaults=data,
)
if created:
print doc.slug
| import yaml
from django.core.management.base import BaseCommand
from django.utils.module_loading import import_string
from ...models import Document
class Command(BaseCommand):
help = "Imprt configuration file"
def add_arguments(self, parser):
parser.add_argument('config_path')
def handle(self, verbosity, config_path, **options):
with open(config_path) as f:
config = yaml.load(f)
for collection in config['collections']:
loader_cls = import_string(collection['loader'])
loader = loader_cls(**collection)
for data in loader.documents():
(_, created) = Document.objects.get_or_create(
slug=data.pop('slug'),
defaults=data,
)
if created:
print data
| mit | Python |
d99011bc623f0c02c3fa35050c282f273f153d87 | Update RestartProgram.py | VitorHugoAguiar/ProBot,VitorHugoAguiar/ProBot,VitorHugoAguiar/ProBot,VitorHugoAguiar/ProBot | ProBot_BeagleBone/RestartProgram.py | ProBot_BeagleBone/RestartProgram.py | #!/usr/bin/python
import sys
import os
import zmq
import SocketCommunication
# Initialization of classes from local files
Pub_Sub = SocketCommunication.publisher_and_subscriber()
class Restart():
def RestartProgram (self):
while True:
# Checking if the program needs to restart
restartVar = Pub_Sub.subscriber2()
if restartVar is None:
restartVar = 0
userChoice = '0'
userChoice1 = '0'
else:
userChoice, userChoice1 = restartVar.split()
# Sending the previous value of the user's choices to the ProBot.py file
if userChoice=='0':
python = sys.executable
os.execl(python, python, * sys.argv)
publisher2=Pub_Sub.publisher2(userChoice, userChoice1)
if __name__ == '__main__':
Restart=Restart()
Restart.RestartProgram()
| #!/usr/bin/python
import sys
import os
import zmq
import SocketCommunication
Pub_Sub = SocketCommunication.publisher_and_subscriber()
class Restart():
def RestartProgram (self):
while True:
# Checking if the program needs to restart
restartVar = Pub_Sub.subscriber2()
if restartVar is None:
restartVar = 0
userChoice = '0'
userChoice1 = '0'
else:
userChoice, userChoice1 = restartVar.split()
# Sending the previous value of the user's choices to the ProBot.py file
if userChoice=='0':
python = sys.executable
os.execl(python, python, * sys.argv)
publisher2=Pub_Sub.publisher2(userChoice, userChoice1)
if __name__ == '__main__':
Restart=Restart()
Restart.RestartProgram()
| agpl-3.0 | Python |
36ebb3e124335fc99d14b8721164e4ea14a889b4 | Add --force option to backfill_course_outlines. | eduNEXT/edx-platform,arbrandes/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,eduNEXT/edunext-platform,angelapper/edx-platform,edx/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,EDUlib/edx-platform,EDUlib/edx-platform,EDUlib/edx-platform,eduNEXT/edunext-platform,angelapper/edx-platform,arbrandes/edx-platform,angelapper/edx-platform,angelapper/edx-platform,edx/edx-platform,eduNEXT/edx-platform,eduNEXT/edx-platform,edx/edx-platform,eduNEXT/edunext-platform,edx/edx-platform | cms/djangoapps/contentstore/management/commands/backfill_course_outlines.py | cms/djangoapps/contentstore/management/commands/backfill_course_outlines.py | """
Management command to create the course outline for all courses that are missing
an outline. Outlines are built automatically on course publish and manually
using the `update_course_outline` command, but they can be backfilled using this
command. People updating to Lilac release should run this command as part of the
upgrade process.
This should be invoked from the Studio process.
"""
import logging
from django.core.management.base import BaseCommand
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.content.learning_sequences.api import (
get_course_keys_with_outlines,
key_supports_outlines,
)
from ...tasks import update_outline_from_modulestore_task
log = logging.getLogger('backfill_course_outlines')
class Command(BaseCommand):
"""
Invoke with:
python manage.py cms backfill_course_outlines
"""
help = (
"Backfill missing course outlines. This will queue a celery task for "
"each course with a missing outline, meaning that the outlines may be "
"generated minutes or hours after this script has finished running."
)
def add_arguments(self, parser):
parser.add_argument(
'--dry',
action='store_true',
help="Show course outlines that will be backfilled, but do not make any changes."
)
parser.add_argument(
'--force',
action='store_true',
help="Force Outline re-generation for all Courses, not just missing ones."
)
def handle(self, *args, **options):
dry_run = options.get('dry', False)
force_all = options.get('force', False)
log.info("Starting backfill_course_outlines: dry=%s, force=%s", dry_run, force_all)
all_course_keys_qs = CourseOverview.objects.values_list('id', flat=True)
if force_all:
target_courses_qs = all_course_keys_qs
log.info("Forcing re-generation for all %d course runs.", len(target_courses_qs))
else:
# .difference() is not supported in MySQL, but this at least does the
# SELECT NOT IN... subquery in the database rather than Python.
target_courses_qs = all_course_keys_qs.exclude(
id__in=get_course_keys_with_outlines()
)
log.info("Found %d courses without outlines.", len(target_courses_qs))
for course_key in target_courses_qs:
if key_supports_outlines(course_key):
log.info("Queuing outline creation for %s", course_key)
if not dry_run:
update_outline_from_modulestore_task.delay(str(course_key))
else:
log.info("Outlines not supported for %s - skipping", course_key)
| """
Management command to create the course outline for all courses that are missing
an outline. Outlines are built automatically on course publish and manually
using the `update_course_outline` command, but they can be backfilled using this
command. People updating to Lilac release should run this command as part of the
upgrade process.
This should be invoked from the Studio process.
"""
import logging
from django.core.management.base import BaseCommand
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.content.learning_sequences.api import (
get_course_keys_with_outlines,
key_supports_outlines,
)
from ...tasks import update_outline_from_modulestore_task
log = logging.getLogger('backfill_course_outlines')
class Command(BaseCommand):
"""
Invoke with:
python manage.py cms backfill_course_outlines
"""
help = (
"Backfill missing course outlines. This will queue a celery task for "
"each course with a missing outline, meaning that the outlines may be "
"generated minutes or hours after this script has finished running."
)
def add_arguments(self, parser):
parser.add_argument(
'--dry',
action='store_true',
help="Show course outlines that will be backfilled, but do not make any changes."
)
def handle(self, *args, **options):
dry_run = options.get('dry', False)
log.info("Starting backfill_course_outlines{}".format(" (dry run)" if dry_run else ""))
all_course_keys_qs = CourseOverview.objects.values_list('id', flat=True)
# .difference() is not supported in MySQL, but this at least does the
# SELECT NOT IN... subquery in the database rather than Python.
missing_outlines_qs = all_course_keys_qs.exclude(
id__in=get_course_keys_with_outlines()
)
num_courses_needing_outlines = len(missing_outlines_qs)
log.info(
"Found %d courses without outlines. Queuing tasks...",
num_courses_needing_outlines
)
for course_key in missing_outlines_qs:
if key_supports_outlines(course_key):
log.info("Queuing outline creation for %s", course_key)
if not dry_run:
update_outline_from_modulestore_task.delay(str(course_key))
else:
log.info("Outlines not supported for %s - skipping", course_key)
| agpl-3.0 | Python |
37956a6f0fae8506abd026d4f9eb70fdfb496c84 | handle errors in AsyncRequest | oconnor663/fbmessenger,oconnor663/fbmessenger,oconnor663/fbmessenger | network.py | network.py | import threading
try:
# python3
from urllib.request import urlopen
from urllib.parse import urlsplit, parse_qs, urlencode, urlunsplit
except ImportError:
#python2
from urllib import urlopen, urlencode
from urlparse import urlsplit, parse_qs, urlunsplit
import settings
import event
class AsyncRequest(threading.Thread):
def __init__(self, url, callback=None, poststr=None):
threading.Thread.__init__(self)
self._callback = callback
self._url = url
self._postbytes = poststr.encode("utf-8") if poststr else None
self.start()
def run(self):
token_url = add_access_token(self._url)
response_text = ""
try:
response = urlopen(token_url, self._postbytes)
response_text = response.read().decode("utf-8")
except Exception as e:
print("async request failed:", e)
# avoid a self reference in the callback, so this object can get gc'd
cached_callback = self._callback
event.run_on_ui_thread(lambda: cached_callback(response_text))
def add_access_token(url):
uid, token = settings.get_user_info()
if not token:
return url
scheme, netloc, path, query_string, fragment = urlsplit(url)
query_params = parse_qs(query_string)
query_params["access_token"] = token
new_query_string = urlencode(query_params, doseq=True)
return urlunsplit((scheme, netloc, path, new_query_string, fragment))
| import threading
try:
# python3
from urllib.request import urlopen
from urllib.parse import urlsplit, parse_qs, urlencode, urlunsplit
except ImportError:
#python2
from urllib import urlopen, urlencode
from urlparse import urlsplit, parse_qs, urlunsplit
import settings
import event
class AsyncRequest(threading.Thread):
def __init__(self, url, callback=None, poststr=None):
threading.Thread.__init__(self)
self._callback = callback
self._url = url
self._postbytes = poststr.encode("utf-8") if poststr else None
self.start()
def run(self):
token_url = add_access_token(self._url)
response = urlopen(token_url, self._postbytes)
response_text = response.read().decode("utf-8")
# avoid a self reference in the callback, so this object can get gc'd
cached_callback = self._callback
event.run_on_ui_thread(lambda: cached_callback(response_text))
def add_access_token(url):
uid, token = settings.get_user_info()
if not token:
return url
scheme, netloc, path, query_string, fragment = urlsplit(url)
query_params = parse_qs(query_string)
query_params["access_token"] = token
new_query_string = urlencode(query_params, doseq=True)
return urlunsplit((scheme, netloc, path, new_query_string, fragment))
| bsd-3-clause | Python |
047a8fb22717fcee8a4725827c85cb1013d07e15 | Change send-alert script | ivantsov/lens_alert_proto,ShpuntiK/lens_alert_proto,ivantsov/lens_alert_proto,ShpuntiK/lens_alert_proto | app/management/commands/send_alert.py | app/management/commands/send_alert.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import send_mass_mail
from django.contrib.auth.models import User
from app.models import Alert
from datetime import datetime
class Command(BaseCommand):
args = ''
help = 'Run alerts for users'
def handle(self, *args, **options):
cur_time = datetime.now().strftime('%H:%M')
alerts = Alert.objects.filter(alert_server_time=cur_time)
#alerts = Alert.objects.all()
if alerts.count() != 0:
msges = []
for alert in alerts:
subject = u'LinsAlert - оповещение о смене линз.'
msg = u'Здравствуйте, ' + alert.user.first_name + u'. Сервис LinsAlert напоминает вам об необходимости смены линз.'
from_email = u'shpuntik74@gmail.com'
msges.append((subject, msg, from_email, [alert.email]))
try:
send_mass_mail(msges, fail_silently=False)
except Exception as error:
print CommandError(error)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import send_mass_mail
from django.contrib.auth.models import User
from app.models import Alert
from datetime import datetime
class Command(BaseCommand):
args = ''
help = 'Run alerts for users'
def handle(self, *args, **options):
cur_time = datetime.now().strftime('%H:%M')
#alerts = Alert.objects.filter(alert_server_time=cur_time)
alerts = Alert.objects.all()
if alerts.count() != 0:
msges = []
for alert in alerts:
subject = u'LinsAlert - оповещение о смене линз.'
msg = alert.user.first_name + u'Сервис LinsAlert напоминает вам об необходимости смены линз.'
from_email = u'shpuntik74@gmail.com'
msges.append((subject, msg, from_email, [alert.email]))
try:
send_mass_mail(msges, fail_silently=False)
except Exception as error:
print CommandError(error) | mit | Python |
e606d44c7fcaf28adbae8c68e23fa33366a57dd7 | Change script for email alerts | ivantsov/lens_alert_proto,ShpuntiK/lens_alert_proto,ivantsov/lens_alert_proto,ShpuntiK/lens_alert_proto | app/management/commands/send_alert.py | app/management/commands/send_alert.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import send_mass_mail
from django.contrib.auth.models import User
from app.models import Alert
from datetime import datetime, date, timedelta
class Command(BaseCommand):
args = ''
help = 'Send alerts for users'
def handle(self, *args, **options):
cur_time = datetime.now().strftime('%H:%M')
cur_date = date.today()
pre_alerts = Alert.objects.filter(alert_server_time=cur_time, start__lte=cur_date, finish__gte=cur_date)
alerts = []
for alert in pre_alerts:
real_period = {'1': 1, '2': 7, '3': 14, '4': 28}
t_date = alert.start
while t_date <= cur_date:
if t_date == cur_date:
alerts.append(alert)
break
else:
t_date += timedelta(days=real_period[alert.period])
if len(alerts) != 0:
msges = []
for alert in alerts:
subject = u'LinsAlert - оповещение о смене линз.'
msg = u'Здравствуйте, ' + alert.user.first_name + u'.\n\n Сервис LinsAlert напоминает вам об необходимости смены линз.'
from_email = u'shpuntik74@gmail.com'
msges.append((subject, msg, from_email, [alert.email]))
try:
send_mass_mail(msges, fail_silently=False)
except Exception as error:
print CommandError(error)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import send_mass_mail
from django.contrib.auth.models import User
from app.models import Alert
from datetime import datetime
class Command(BaseCommand):
args = ''
help = 'Run alerts for users'
def handle(self, *args, **options):
cur_time = datetime.now().strftime('%H:%M')
alerts = Alert.objects.filter(alert_server_time=cur_time)
#alerts = Alert.objects.all()
if alerts.count() != 0:
msges = []
for alert in alerts:
subject = u'LinsAlert - оповещение о смене линз.'
msg = u'Здравствуйте, ' + alert.user.first_name + u'. Сервис LinsAlert напоминает вам об необходимости смены линз.'
from_email = u'shpuntik74@gmail.com'
msges.append((subject, msg, from_email, [alert.email]))
try:
send_mass_mail(msges, fail_silently=False)
except Exception as error:
print CommandError(error)
| mit | Python |
1c59bae012249d5e1624d1b9445590b499546d80 | change save interval | iizukak/nupic-nlp-experiment | src/pos_prediction.py | src/pos_prediction.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import unicodecsv as csv
from nupic.data.inference_shifter import InferenceShifter
from nupic.frameworks.opf.modelfactory import ModelFactory
import pprint
import os
import model_params.model_params as model_params
import pos_tags
DATA_DIR = "data/"
INPUT_FILE = "firefox-pos-list.csv"
MODEL_DIR = os.getcwd() + "/model"
def addCategoryEncoder(params):
params["modelParams"]["sensorParams"]["encoders"].update({
"token": {
"fieldname": u"token",
"name": u"token",
"type": "CategoryEncoder",
"categoryList": pos_tags.TAG_IDS,
"w": 23
}
})
return params
def createModel(verbosity=False):
model = ModelFactory.create(addCategoryEncoder(model_params.MODEL_PARAMS))
model.enableInference({"predictedField": "token"})
if verbosity:
print(model)
return model
def main():
model = createModel(verbosity = True)
shifter = InferenceShifter()
input_file_name = DATA_DIR + INPUT_FILE
output_file_name = DATA_DIR + "out.csv"
countor = 1
with open(input_file_name, 'r') as f1, open(output_file_name, 'w') as f2:
reader = csv.reader(f1)
writer = csv.writer(f2)
for row in reader:
model_input = {"token": row[1]}
result = shifter.shift(model.run(model_input))
if countor % 100 == 0:
print("input line:", countor)
if countor % 1000 == 0:
print("result:", result)
if countor % 5000 == 0:
print("save model")
model.save(MODEL_DIR)
writer.writerow(row + [result.inferences["anomalyScore"]])
countor += 1
print("saving model to", MODEL_DIR)
model.save(MODEL_DIR)
if __name__ == "__main__":
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import unicodecsv as csv
from nupic.data.inference_shifter import InferenceShifter
from nupic.frameworks.opf.modelfactory import ModelFactory
import pprint
import os
import model_params.model_params as model_params
import pos_tags
DATA_DIR = "data/"
INPUT_FILE = "firefox-pos-list.csv"
MODEL_DIR = os.getcwd() + "/model"
def addCategoryEncoder(params):
params["modelParams"]["sensorParams"]["encoders"].update({
"token": {
"fieldname": u"token",
"name": u"token",
"type": "CategoryEncoder",
"categoryList": pos_tags.TAG_IDS,
"w": 23
}
})
return params
def createModel(verbosity=False):
model = ModelFactory.create(addCategoryEncoder(model_params.MODEL_PARAMS))
model.enableInference({"predictedField": "token"})
if verbosity:
print(model)
return model
def main():
model = createModel(verbosity = True)
shifter = InferenceShifter()
input_file_name = DATA_DIR + INPUT_FILE
output_file_name = DATA_DIR + "out.csv"
countor = 1
with open(input_file_name, 'r') as f1, open(output_file_name, 'w') as f2:
reader = csv.reader(f1)
writer = csv.writer(f2)
for row in reader:
if countor % 100 == 0:
print("input line:", countor)
model_input = {"token": row[1]}
result = shifter.shift(model.run(model_input))
# print("DEBUG:", row[1], result.inferences["anomalyScore"])
if countor % 1000 == 0:
print("result:", result)
model.save(MODEL_DIR)
writer.writerow(row + [result.inferences["anomalyScore"]])
countor += 1
print("saving model to", MODEL_DIR)
model.save(MODEL_DIR)
if __name__ == "__main__":
main()
| agpl-3.0 | Python |
48587d0c7a5906bd95c2c26db92365bf0843ddee | add Music | zhengze/zblog,zhengze/zblog,zhengze/zblog,zhengze/zblog | zblog/models.py | zblog/models.py | from django.db import models
class Classify(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
class Tag(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
class Article(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
created_time = models.DateTimeField(auto_now=True)
classify = models.ForeignKey(Classify)
tag = models.ForeignKey(Tag)
hits = models.IntegerField(max_length=1, default=0)
class Meta:
ordering = ['-created_time']
def __unicode__(self):
return self.title
class Album(models.Model):
name = models.CharField(max_length=50)
cover = models.ImageField(upload_to='images/covers/%Y/%m/%d', null=True, blank=True)
def __unicode__(self):
return self.name
class Photo(models.Model):
photo = models.ImageField(upload_to='images/%Y/%m/%d')
description = models.CharField(max_length=255, null=True)
created_time = models.DateTimeField(auto_now=True, null=True)
album = models.ForeignKey(Album)
class Meta:
ordering = ['-created_time']
def __unicode__(self):
return self.description
class Music(models.Model):
title = models.CharField(max_length=50)
mp3 = models.FileField(upload_to='music/%Y/%m/%d')
created_time = models.DateTimeField(auto_now=True, null=True)
class Meta:
ordering = ['-created_time']
def __unicode__(self):
return self.title
| from django.db import models
class Classify(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
class Tag(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
class Article(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
created_time = models.DateTimeField()
classify = models.ForeignKey(Classify)
tag = models.ForeignKey(Tag)
hits = models.IntegerField(max_length=1, default=0)
class Meta:
ordering = ['-created_time']
def __unicode__(self):
return self.title
class Album(models.Model):
name = models.CharField(max_length=50)
cover = models.ImageField(upload_to='images/covers/%Y/%m/%d', null=True, blank=True)
def __unicode__(self):
return self.name
class Photo(models.Model):
photo = models.ImageField(upload_to='images/%Y/%m/%d')
description = models.CharField(max_length=255, null=True)
album = models.ForeignKey(Album)
def __unicode__(self):
return self.description
| mit | Python |
a677e25a75291091a23e309afd30c2542f8a61f1 | Bump version (0.3.10) | cgwire/zou | zou/__init__.py | zou/__init__.py | __version__ = "0.3.10"
| __version__ = "0.3.9"
| agpl-3.0 | Python |
2ff50deea8f8b605af7e21fa8a448bc68d2844b4 | Fix is_locked() | stuartarchibald/numba,sklam/numba,IntelLabs/numba,cpcloud/numba,stonebig/numba,cpcloud/numba,seibert/numba,gmarkall/numba,numba/numba,IntelLabs/numba,numba/numba,jriehl/numba,seibert/numba,seibert/numba,sklam/numba,numba/numba,cpcloud/numba,cpcloud/numba,sklam/numba,sklam/numba,gmarkall/numba,gmarkall/numba,jriehl/numba,gmarkall/numba,IntelLabs/numba,jriehl/numba,stuartarchibald/numba,stuartarchibald/numba,IntelLabs/numba,jriehl/numba,jriehl/numba,IntelLabs/numba,seibert/numba,stonebig/numba,stonebig/numba,seibert/numba,stuartarchibald/numba,sklam/numba,numba/numba,numba/numba,stuartarchibald/numba,gmarkall/numba,stonebig/numba,cpcloud/numba,stonebig/numba | numba/compiler_lock.py | numba/compiler_lock.py | import threading
import functools
# Lock for the preventing multiple compiler execution
class _CompilerLock(object):
def __init__(self):
self._lock = threading.RLock()
self._locked = 0
def acquire(self):
self._lock.acquire()
self._locked += 1
def release(self):
self._locked -= 1
self._lock.release()
def __enter__(self):
self.acquire()
def __exit__(self, exc_val, exc_type, traceback):
self.release()
def is_locked(self):
return self._locked > 0
def __call__(self, func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
with self:
return func(*args, **kwargs)
return wrapped
global_compiler_lock = _CompilerLock()
def require_global_compiler_lock():
"""Sentry that checks the global_compiler_lock is acquired.
"""
# Use assert to allow turning off this checks
assert global_compiler_lock.is_locked()
| import threading
import functools
# Lock for the preventing multiple compiler execution
class _CompilerLock(object):
def __init__(self):
self._lock = threading.RLock()
self._locked = False
def acquire(self):
self._lock.acquire()
self._locked = True
def release(self):
self._locked = False
self._lock.release()
def __enter__(self):
self.acquire()
def __exit__(self, exc_val, exc_type, traceback):
self.release()
def is_locked(self):
return self._locked
def __call__(self, func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
with self:
return func(*args, **kwargs)
return wrapped
global_compiler_lock = _CompilerLock()
def require_global_compiler_lock():
"""Sentry that checks the global_compiler_lock is acquired.
"""
# Use assert to allow turning off this checks
assert global_compiler_lock.is_locked()
| bsd-2-clause | Python |
8f37c13394143f90421ffcea45dbdf4282ecbdce | Add function to scan the network for IPs | dimriou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dionyziz/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,dimkarakostas/rupture,esarafianou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture | backend/breach/helpers/network.py | backend/breach/helpers/network.py | import netifaces
import ipaddress
import subprocess
import os
from bs4 import BeautifulSoup
def get_interface():
return netifaces.gateways()['default'][netifaces.AF_INET][1]
def get_local_IP():
def_gw_device = get_interface()
return netifaces.ifaddresses(def_gw_device)[netifaces.AF_INET][0]['addr']
def get_netmask():
def_gw_device = get_interface()
return netifaces.ifaddresses(def_gw_device)[netifaces.AF_INET][0]['netmask']
def scan_network():
possible_victims = []
local_ip = get_local_IP()
netmask = get_netmask()
network = str(ipaddress.IPv4Network((local_ip.decode('utf-8'), netmask.decode('utf-8')), strict=False))
proc = subprocess.Popen(['sudo', 'nmap', '-oX', '-', '-sP', network], stdout=subprocess.PIPE, preexec_fn=os.setpgrp)
nmap_output = proc.communicate()[0]
soup = BeautifulSoup(nmap_output)
for address in soup.findAll('address'):
addr_attrs = dict(address.attrs)
if addr_attrs[u'addrtype'] == 'ipv4':
possible_victims.append(addr_attrs[u'addr'])
return possible_victims
if __name__ == '__main__':
print scan_network()
| import netifaces
def get_interface():
return netifaces.gateways()['default'][netifaces.AF_INET][1]
def get_local_IP():
def_gw_device = get_interface()
return netifaces.ifaddresses(def_gw_device)[netifaces.AF_INET][0]['addr']
def get_netmask():
def_gw_device = get_interface()
return netifaces.ifaddresses(def_gw_device)[netifaces.AF_INET][0]['netmask']
| mit | Python |
f8df32c28905cd97b6bfd562d16ed2394a67d297 | Fix Dick Blick scraper | iandees/all-the-places,iandees/all-the-places,iandees/all-the-places | locations/spiders/dick_blick.py | locations/spiders/dick_blick.py | # -*- coding: utf-8 -*-
import scrapy
import re
from locations.items import GeojsonPointItem
class DickBlickSpider(scrapy.Spider):
name = "dick_blick"
allowed_domains = ["www.dickblick.com"]
start_urls = (
'https://www.dickblick.com/stores/',
)
def parse_store(self, response):
contacts = response.xpath('//ul[@class="contact"]/li/span/text()').extract()
properties = {
'addr:full': contacts[0],
'addr:city': contacts[1],
'addr:state': contacts[2],
'addr:postcode': contacts[3],
'phone': contacts[4],
'ref': response.url,
'website': response.url,
}
day_groups = response.xpath('//ul[@class="hours"]/li[@class="storehours"]/text()').extract()
opening_hours = []
for day_group in day_groups:
match = re.match(r'(.*): (\d+)-(\d+)', day_group)
days, f_hr, t_hr = match.groups()
f_hr = int(f_hr)
t_hr = int(t_hr) + 12
opening_hours.append('{} {:02d}:00-{:02d}:00'.format(days, f_hr, t_hr))
if opening_hours:
properties['opening_hours'] = '; '.join(opening_hours)
yield GeojsonPointItem(
properties=properties,
)
def parse_state(self, response):
urls = response.xpath('//div/ul[@class="storelist"]/li/a/@href').extract()
for path in urls:
yield scrapy.Request(response.urljoin(path), callback=self.parse_store)
def parse(self, response):
urls = response.xpath('//div[@class="statechooser"]/select/option/@value').extract()
for path in urls:
yield scrapy.Request(response.urljoin(path), callback=self.parse_state)
| # -*- coding: utf-8 -*-
import scrapy
import re
from scrapy.utils.url import urljoin_rfc
from scrapy.utils.response import get_base_url
from locations.items import GeojsonPointItem
class DickBlickSpider(scrapy.Spider):
name = "dick_blick"
allowed_domains = ["www.dickblick.com"]
start_urls = (
'https://www.dickblick.com/stores/',
)
def parse_store(self, response):
contacts = response.xpath('//ul[@class="contact"]/li/span/text()').extract()
properties = {
'addr:full': contacts[0],
'addr:city': contacts[1],
'addr:state': contacts[2],
'addr:postcode': contacts[3],
'phone': contacts[4],
'ref': response.url,
'website': response.url,
}
day_groups = response.xpath('//ul[@class="hours"]/li[@class="storehours"]/text()').extract()
opening_hours = []
for day_group in day_groups:
match = re.match(r'(.*): (\d+)-(\d+)', day_group)
days, f_hr, t_hr = match.groups()
f_hr = int(f_hr)
t_hr = int(t_hr) + 12
opening_hours.append('{} {:02d}:00-{:02d}:00'.format(days, f_hr, t_hr))
if opening_hours:
properties['opening_hours'] = '; '.join(opening_hours)
yield GeojsonPointItem(
properties=properties,
)
def parse_state(self, response):
base_url = get_base_url(response)
urls = response.xpath('//div/ul[@class="storelist"]/li/a/@href').extract()
for path in urls:
yield scrapy.Request(urljoin_rfc(base_url, path), callback=self.parse_store)
def parse(self, response):
base_url = get_base_url(response)
urls = response.xpath('//div[@class="statechooser"]/select/option/@value').extract()
for path in urls:
yield scrapy.Request(urljoin_rfc(base_url, path), callback=self.parse_state)
| mit | Python |
3af2a5b6eda4af972e3a208e727483384f313cb9 | Remove index and check filename | jason-neal/equanimous-octo-tribble,jason-neal/equanimous-octo-tribble,jason-neal/equanimous-octo-tribble | octotribble/csv2tex.py | octotribble/csv2tex.py | #!/usr/bin/env python
"""Convert a CSV table into a latex tabular using pandas."""
import argparse
import pandas as pd
def convert(filename, transpose=False):
"""convert csv to tex table."""
df = pd.read_csv(filename)
if transpose:
df = df.transpose()
tex_name = filename.replace(".csv", "_transpose.tex")
index = True
else:
tex_name = filename.replace(".csv", ".tex")
index=False
assert tex_name != filename, "This will overwrite the file, did you pass in a csv?"
latex = df.to_latex(na_rep="-", index=index)
with open(tex_name, "w") as f:
f.write(r"\begin{table}")
f.write("\n")
f.write(r"\label{}")
f.write("\n")
f.write(r"\caption{}")
f.write("\n")
f.write(latex)
f.write(r"\end{table}")
f.write("\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert csv to latex tabular")
parser.add_argument("filename", help="Name of csv file", type=str)
parser.add_argument(
"-t", "--transpose", help="Transpose table", action="store_true"
)
args = parser.parse_args()
convert(args.filename, args.transpose)
| #!/usr/bin/env python
"""Convert a CSV table into a latex tabular using pandas."""
import argparse
import pandas as pd
def convert(filename, transpose=False):
"""convert csv to tex table."""
df = pd.read_csv(filename)
if transpose:
df = df.transpose()
tex_name = filename.replace(".csv", "_transpose.tex")
else:
tex_name = filename.replace(".csv", ".tex")
with open(tex_name, "w") as f:
f.write(r"\begin{table}")
f.write("\n")
f.write(r"\label{}")
f.write("\n")
f.write(r"\caption{}")
f.write("\n")
f.write(df.to_latex(na_rep="-"))
f.write(r"\end{table}")
f.write("\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert csv to latex tabular")
parser.add_argument("filename", help="Name of csv file", type=str)
parser.add_argument(
"-t", "--transpose", help="Transpose table", action="store_true"
)
args = parser.parse_args()
convert(args.filename, args.transpose)
| mit | Python |
bae92f91baa43e44582d78a4183868b8b32016e9 | Put new values from supervisor | atooma/makerfaire-2014,atooma/makerfaire-2014 | GreenThumb/supervisor.py | GreenThumb/supervisor.py | # -*- coding: utf-8 -*-
import dht11
import time
import os
import requests
import json
measurements_buffer = {}
def ouput_val(pin):
pin_hash = str(pin)
try:
(humidity, temperature) = dht11.read(pin)
measurements_buffer[pin_hash] = (humidity, temperature)
except:
if pin_hash in measurements_buffer:
(humidity, temperature) = measurements_buffer[pin_hash]
else:
(humidity, temperature) = (-1, -1)
return
print '--------PIN {}----------'.format(pin)
print 'Humidity: {}%'.format(humidity)
print 'Temperature: {}°C'.format(temperature)
print '------------------------'
data = {'id':pin, 'temperature': temperature, 'humidity': humidity}
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
requests.put('http://localhost:9092/api/sensors/dht/{}/'.format(pin),
data=json.dumps(data), headers=headers, auth=('andrea', 'andrea'))
while True:
ouput_val(25)
ouput_val(24)
ouput_val(18)
time.sleep(4)
os.system('clear') | # -*- coding: utf-8 -*-
import dht11
import time
import os
measurements_buffer = {}
def ouput_val(pin):
pin_hash = str(pin)
try:
(humidity, temperature) = dht11.read(pin)
measurements_buffer[pin_hash] = (humidity, temperature)
except:
if pin_hash in measurements_buffer:
(humidity, temperature) = measurements_buffer[pin_hash]
else:
(humidity, temperature) = ('-', '-')
print '--------PIN {}----------'.format(pin)
print 'Humidity: {}%'.format(humidity)
print 'Temperature: {}°C'.format(temperature)
print '------------------------'
while True:
ouput_val(25)
ouput_val(24)
ouput_val(18)
time.sleep(4)
os.system('clear') | mit | Python |
75b50ffcb6575e38e6792356dd58612089ee4f55 | Return 400 for inexistant accounts | asermax/django-mercadopago | django_mercadopago/views.py | django_mercadopago/views.py | import logging
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Notification, Account
logger = logging.getLogger(__name__)
# Maybe use a form for this? :D
@csrf_exempt
def create_notification(request, slug):
topic = request.GET.get('topic', None)
resource_id = request.GET.get('id', None)
if topic is None:
return HttpResponse(
'<h1>400 Bad Request.</h1>'
'Missing parameter topic',
status=400
)
if resource_id is None:
return HttpResponse(
'<h1>400 Bad Request.</h1>'
'Missing parameter id',
status=400
)
if topic == 'merchant_order':
topic = Notification.TOPIC_ORDER
elif topic == 'payment':
topic = Notification.TOPIC_PAYMENT
else:
return HttpResponse('invalid topic', status=400)
try:
owner = Account.objects.get(slug=slug)
except Account.DoesNotExist:
return HttpResponse('Unknown account/slug', status=400)
notification, created = Notification.objects.get_or_create(
topic=topic,
resource_id=resource_id,
owner=owner,
)
if not created:
notification.processed = False
notification.save()
if not settings.MERCADOPAGO_ASYNC:
notification.process()
# TODO: Else add to some queue?
return HttpResponse("<h1>200 OK</h1>", status=201)
| import logging
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Notification, Account
logger = logging.getLogger(__name__)
# Maybe use a form for this? :D
@csrf_exempt
def create_notification(request, slug):
topic = request.GET.get('topic', None)
resource_id = request.GET.get('id', None)
if topic is None:
return HttpResponse(
'<h1>400 Bad Request.</h1>'
'Missing parameter topic',
status=400
)
if resource_id is None:
return HttpResponse(
'<h1>400 Bad Request.</h1>'
'Missing parameter id',
status=400
)
if topic == 'merchant_order':
topic = Notification.TOPIC_ORDER
elif topic == 'payment':
topic = Notification.TOPIC_PAYMENT
else:
return HttpResponse('invalid topic', status=400)
owner = Account.objects.get(slug=slug)
notification, created = Notification.objects.get_or_create(
topic=topic,
resource_id=resource_id,
owner=owner,
)
if not created:
notification.processed = False
notification.save()
if not settings.MERCADOPAGO_ASYNC:
notification.process()
# TODO: Else add to some queue?
return HttpResponse("<h1>200 OK</h1>", status=201)
| isc | Python |
08be96e39db786b1187ab7acc8beafe5c186ae54 | Bump Version | mishbahr/djangocms-forms,mishbahr/djangocms-forms,mishbahr/djangocms-forms | djangocms_forms/__init__.py | djangocms_forms/__init__.py | __version__ = '0.2.4'
default_app_config = 'djangocms_forms.apps.DjangoCMSFormsConfig'
| __version__ = '0.2.3'
default_app_config = 'djangocms_forms.apps.DjangoCMSFormsConfig'
| bsd-3-clause | Python |
e2d5fcf9997ff7cdac1ba55b6fe47e4e6ad2b182 | simplify options | claman/apollo,claman/percival | percy.py | percy.py | #!/usr/bin/python
import argparse
file = open('your filename here', 'r') # change this to correspond to your list
def getYear(date):
slashDate = date.split('/')
year = slashDate[2]
return year
def info(title, author, owned, start, end, format, date):
print title + ' by ' + author
print 'Owned: ' + owned
print 'Started: ' + start
print 'Finished: ' + end
print 'Format: ' + format
print 'First Published: ' + date
print
def search(option, search):
for line in file:
line = line.strip('|\n')
entry = line.split('|')
title, author, owned, start, end, format, date = entry[0], entry[1], entry[2], entry[3], entry[4], entry[5], entry[6]
if option == 't':
if search in title:
info(title, author, owned, start, end, format, date)
elif option == 'y':
if title != 'Title' and title != ':----':
if start and end != '-':
if search == getYear(start) or search == getYear(end):
info(title, author, owned, start, end, format, date)
elif option == 'a':
search = search.title()
if search in author:
info(title, author, owned, start, end, format, date)
elif option == 'p':
if search == date:
info(title, author, owned, start, end, format, date)
def stats():
totalBooks = 0
totalPhysical = 0
totalEbooks = 0
for line in file:
line = line.strip('|\n')
entry = line.split('|')
title, author, owned, start, end, format, date = entry[0], entry[1], entry[2], entry[3], entry[4], entry[5], entry[6]
if title != 'Title' and title != ':----':
totalBooks += 1
if format == 'Paperback' or format == 'Hardcover':
totalPhysical += 1
elif format == 'Ebook':
totalEbooks += 1
print 'You have ' + str(totalBooks) + ' books on your list.'
print str(totalPhysical) + ' of them are physical (paperback or hardcover).'
print str(totalEbooks) + ' of them are ebooks.'
parser = argparse.ArgumentParser()
parser.add_argument('-a', help='Search by author')
parser.add_argument('-p', help='Search by publication date')
parser.add_argument('-t', help='Search by title')
parser.add_argument('-y', help='Search by reading year')
parser.add_argument('--stats', action='store_true')
args = parser.parse_args()
if args.title:
search('t', args.title)
elif args.year:
search('y', args.year)
elif args.author:
search('a', args.author)
elif args.published:
search('p', args.published)
elif args.stats:
stats()
else:
print 'Try running again with \'-h\''
file.close()
| #!/usr/bin/python
import argparse
file = open('your filename here', 'r') # change this to correspond to your list
def getYear(date):
slashDate = date.split('/')
year = slashDate[2]
return year
def info(title, author, owned, start, end, format, date):
print title + ' by ' + author
print 'Owned: ' + owned
print 'Started: ' + start
print 'Finished: ' + end
print 'Format: ' + format
print 'First Published: ' + date
print
def search(option, search):
for line in file:
line = line.strip('|\n')
entry = line.split('|')
title, author, owned, start, end, format, date = entry[0], entry[1], entry[2], entry[3], entry[4], entry[5], entry[6]
if option == 't':
if search in title:
info(title, author, owned, start, end, format, date)
elif option == 'y':
if title != 'Title' and title != ':----':
if start and end != '-':
if search == getYear(start) or search == getYear(end):
info(title, author, owned, start, end, format, date)
elif option == 'a':
search = search.title()
if search in author:
info(title, author, owned, start, end, format, date)
elif option == 'p':
if search == date:
info(title, author, owned, start, end, format, date)
def stats():
totalBooks = 0
totalPhysical = 0
totalEbooks = 0
for line in file:
line = line.strip('|\n')
entry = line.split('|')
title, author, owned, start, end, format, date = entry[0], entry[1], entry[2], entry[3], entry[4], entry[5], entry[6]
if title != 'Title' and title != ':----':
totalBooks += 1
if format == 'Paperback' or format == 'Hardcover':
totalPhysical += 1
elif format == 'Ebook':
totalEbooks += 1
print 'You have ' + str(totalBooks) + ' books on your list.'
print str(totalPhysical) + ' of them are physical (paperback or hardcover).'
print str(totalEbooks) + ' of them are ebooks.'
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--author', help='Search by author')
parser.add_argument('-p', '--published', help='Search by publication date')
parser.add_argument('-t', '--title', help='Search by title')
parser.add_argument('-y', '--year', help='Search by reading year')
parser.add_argument('--stats', action='store_true')
args = parser.parse_args()
if args.title:
search('t', args.title)
elif args.year:
search('y', args.year)
elif args.author:
search('a', args.author)
elif args.published:
search('p', args.published)
elif args.stats:
stats()
else:
print 'Try running again with \'-h\' or \'--help\''
file.close()
| mit | Python |
d52c9460411fee14a66eaf8f4793ea25e349d6f7 | Make sure the _texture is always defined. | onitake/Uranium,onitake/Uranium | UM/Scene/Platform.py | UM/Scene/Platform.py | from . import SceneNode
from UM.Application import Application
from UM.View.Renderer import Renderer
from UM.Resources import Resources
class Platform(SceneNode.SceneNode):
def __init__(self, parent):
super().__init__(parent)
self._settings = None
self._material = None
self._texture = None
Application.getInstance().activeMachineChanged.connect(self._onActiveMachineChanged)
self._onActiveMachineChanged()
def render(self, renderer):
if not self._material:
self._material = renderer.createMaterial(
Resources.getPath(Resources.ShadersLocation, 'default.vert'),
Resources.getPath(Resources.ShadersLocation, 'platform.frag')
)
self._material.setUniformValue("u_ambientColor", [0.3, 0.3, 0.3, 1.0])
self._material.setUniformValue("u_diffuseColor", [1.0, 1.0, 1.0, 1.0])
self._material.setUniformValue('u_opacity', 0.5)
if self._texture:
self._material.setUniformTexture('u_texture', Resources.getPath(Resources.ImagesLocation, self._texture))
if self.getMeshData():
renderer.queueNode(self, material = self._material, transparent = True)
return True
def _onActiveMachineChanged(self):
if self._settings:
self.setMeshData(None)
app = Application.getInstance()
self._settings = app.getActiveMachine()
if self._settings:
mesh = self._settings.getPlatformMesh()
self.setMeshData(app.getMeshFileHandler().read(Resources.getPath(Resources.MeshesLocation, mesh), app.getStorageDevice('LocalFileStorage')))
self._texture = self._settings.getPlatformTexture()
if self._material and self._texture:
self._material.setUniformTexture('u_texture', Resources.getPath(Resources.ImagesLocation, self._texture))
| from . import SceneNode
from UM.Application import Application
from UM.View.Renderer import Renderer
from UM.Resources import Resources
class Platform(SceneNode.SceneNode):
def __init__(self, parent):
super().__init__(parent)
self._settings = None
self._material = None
Application.getInstance().activeMachineChanged.connect(self._onActiveMachineChanged)
self._onActiveMachineChanged()
def render(self, renderer):
if not self._material:
self._material = renderer.createMaterial(
Resources.getPath(Resources.ShadersLocation, 'default.vert'),
Resources.getPath(Resources.ShadersLocation, 'platform.frag')
)
self._material.setUniformValue("u_ambientColor", [0.3, 0.3, 0.3, 1.0])
self._material.setUniformValue("u_diffuseColor", [1.0, 1.0, 1.0, 1.0])
self._material.setUniformValue('u_opacity', 0.5)
if self._texture:
self._material.setUniformTexture('u_texture', Resources.getPath(Resources.ImagesLocation, self._texture))
if self.getMeshData():
renderer.queueNode(self, material = self._material, transparent = True)
return True
def _onActiveMachineChanged(self):
if self._settings:
self.setMeshData(None)
app = Application.getInstance()
self._settings = app.getActiveMachine()
if self._settings:
mesh = self._settings.getPlatformMesh()
self.setMeshData(app.getMeshFileHandler().read(Resources.getPath(Resources.MeshesLocation, mesh), app.getStorageDevice('LocalFileStorage')))
self._texture = self._settings.getPlatformTexture()
if self._material and self._texture:
self._material.setUniformTexture('u_texture', Resources.getPath(Resources.ImagesLocation, self._texture))
| agpl-3.0 | Python |
d7dacfc6bdb80a9ad09bd58c20e97516a62da58f | Update zipslip_good.py | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | python/ql/src/experimental/Security/CWE-022/zipslip_good.py | python/ql/src/experimental/Security/CWE-022/zipslip_good.py | import zipfile
def unzip(filename, dir):
zf = zipfile.ZipFile(filename)
zf.extractall(dir)
def unzip1(filename, dir):
zf = zipfile.ZipFile(filename)
zf.extract(dir)
| import zipfile
zf = zipfile.ZipFile(filename)
with zipfile.open() as zipf:
for entry in zipf:
zipf.extract(entry, "/tmp/unpack/")
| mit | Python |
109a6aec8b8b4a888462129bb9f5cac01ddc97f9 | Update jupyter_notebook_config.py (#3664) | davidzchen/tensorflow,xzturn/tensorflow,thjashin/tensorflow,haeusser/tensorflow,with-git/tensorflow,handroissuazo/tensorflow,vrv/tensorflow,alisidd/tensorflow,aam-at/tensorflow,ZhangXinNan/tensorflow,anand-c-goog/tensorflow,allenlavoie/tensorflow,yufengg/tensorflow,apark263/tensorflow,snnn/tensorflow,rabipanda/tensorflow,tongwang01/tensorflow,annarev/tensorflow,jostep/tensorflow,laosiaudi/tensorflow,lukeiwanski/tensorflow-opencl,hehongliang/tensorflow,handroissuazo/tensorflow,alivecor/tensorflow,jhseu/tensorflow,taknevski/tensorflow-xsmm,karllessard/tensorflow,kobejean/tensorflow,mrry/tensorflow,aselle/tensorflow,mdrumond/tensorflow,tornadozou/tensorflow,sjperkins/tensorflow,ageron/tensorflow,kchodorow/tensorflow,RapidApplicationDevelopment/tensorflow,XueqingLin/tensorflow,admcrae/tensorflow,Kongsea/tensorflow,mortada/tensorflow,chemelnucfin/tensorflow,sarvex/tensorflow,av8ramit/tensorflow,gautam1858/tensorflow,haeusser/tensorflow,adamtiger/tensorflow,martinwicke/tensorflow,frreiss/tensorflow-fred,mavenlin/tensorflow,pierreg/tensorflow,a-doumoulakis/tensorflow,mdrumond/tensorflow,alshedivat/tensorflow,eadgarchen/tensorflow,alheinecke/tensorflow-xsmm,girving/tensorflow,annarev/tensorflow,tensorflow/tensorflow,chemelnucfin/tensorflow,dongjoon-hyun/tensorflow,scenarios/tensorflow,taknevski/tensorflow-xsmm,DCSaunders/tensorflow,jendap/tensorflow,Intel-Corporation/tensorflow,memo/tensorflow,annarev/tensorflow,asimshankar/tensorflow,anilmuthineni/tensorflow,mdrumond/tensorflow,alivecor/tensorflow,aam-at/tensorflow,apark263/tensorflow,jendap/tensorflow,jbedorf/tensorflow,jwlawson/tensorflow,llhe/tensorflow,handroissuazo/tensorflow,jbedorf/tensorflow,yanchen036/tensorflow,alsrgv/tensorflow,Mistobaan/tensorflow,zycdragonball/tensorflow,jeffzheng1/tensorflow,av8ramit/tensorflow,gautam1858/tensorflow,meteorcloudy/tensorflow,andrewcmyers/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ishay2b/tensorflow,ageron/tensorflow,sjperkins/tensorflow,hfp/tensorflow-xsmm,paolodedios/tensorflow,alshedivat/tensorflow,hfp/tensorflow-xsmm,admcrae/tensorflow,freedomtan/tensorflow,neilhan/tensorflow,tornadozou/tensorflow,alshedivat/tensorflow,mrry/tensorflow,haeusser/tensorflow,RapidApplicationDevelopment/tensorflow,eaplatanios/tensorflow,laosiaudi/tensorflow,dancingdan/tensorflow,arborh/tensorflow,tongwang01/tensorflow,benoitsteiner/tensorflow-opencl,Xeralux/tensorflow,ishay2b/tensorflow,arborh/tensorflow,nikste/tensorflow,MoamerEncsConcordiaCa/tensorflow,gnieboer/tensorflow,chenjun0210/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,dancingdan/tensorflow,ppwwyyxx/tensorflow,tntnatbry/tensorflow,LUTAN/tensorflow,nikste/tensorflow,Carmezim/tensorflow,yaroslavvb/tensorflow,sjperkins/tensorflow,markslwong/tensorflow,ravindrapanda/tensorflow,Bulochkin/tensorflow_pack,chris-chris/tensorflow,mixturemodel-flow/tensorflow,ppries/tensorflow,aam-at/tensorflow,DavidNorman/tensorflow,nolanliou/tensorflow,benoitsteiner/tensorflow-xsmm,tensorflow/tensorflow-pywrap_saved_model,tntnatbry/tensorflow,Bismarrck/tensorflow,thesuperzapper/tensorflow,girving/tensorflow,ravindrapanda/tensorflow,freedomtan/tensorflow,aldian/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,benoitsteiner/tensorflow-opencl,zasdfgbnm/tensorflow,tongwang01/tensorflow,ville-k/tensorflow,tongwang01/tensorflow,petewarden/tensorflow,juharris/tensorflow,whn09/tensorflow,Intel-tensorflow/tensorflow,dendisuhubdy/tensorflow,rdipietro/tensorflow,nburn42/tensorflow,asimshankar/tensorflow,jostep/tensorflow,aam-at/tensorflow,haeusser/tensorflow,petewarden/tensorflow,gnieboer/tensorflow,pcm17/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_saved_model,benoitsteiner/tensorflow-xsmm,lukeiwanski/tensorflow,rdipietro/tensorflow,markslwong/tensorflow,sjperkins/tensorflow,dancingdan/tensorflow,sandeepdsouza93/TensorFlow-15712,ychfan/tensorflow,benoitsteiner/tensorflow,seaotterman/tensorflow,ravindrapanda/tensorflow,LUTAN/tensorflow,laszlocsomor/tensorflow,abhitopia/tensorflow,scenarios/tensorflow,scenarios/tensorflow,lakshayg/tensorflow,benoitsteiner/tensorflow-xsmm,laszlocsomor/tensorflow,eaplatanios/tensorflow,jendap/tensorflow,jhaux/tensorflow,nburn42/tensorflow,lukeiwanski/tensorflow,jwlawson/tensorflow,apark263/tensorflow,sandeepdsouza93/TensorFlow-15712,seaotterman/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,AnishShah/tensorflow,JVillella/tensorflow,thjashin/tensorflow,jhseu/tensorflow,xodus7/tensorflow,xzturn/tensorflow,mengxn/tensorflow,benoitsteiner/tensorflow-opencl,nikste/tensorflow,manjunaths/tensorflow,aselle/tensorflow,drpngx/tensorflow,ageron/tensorflow,paolodedios/tensorflow,anand-c-goog/tensorflow,tongwang01/tensorflow,lukeiwanski/tensorflow-opencl,jalexvig/tensorflow,yufengg/tensorflow,meteorcloudy/tensorflow,alsrgv/tensorflow,MostafaGazar/tensorflow,a-doumoulakis/tensorflow,Bismarrck/tensorflow,arborh/tensorflow,dongjoon-hyun/tensorflow,suiyuan2009/tensorflow,nolanliou/tensorflow,gautam1858/tensorflow,DavidNorman/tensorflow,andrewcmyers/tensorflow,drpngx/tensorflow,chenjun0210/tensorflow,RapidApplicationDevelopment/tensorflow,jart/tensorflow,pavelchristof/gomoku-ai,Moriadry/tensorflow,ppries/tensorflow,cxxgtxy/tensorflow,whn09/tensorflow,sandeepdsouza93/TensorFlow-15712,AndreasMadsen/tensorflow,freedomtan/tensorflow,ageron/tensorflow,gojira/tensorflow,manazhao/tf_recsys,alheinecke/tensorflow-xsmm,wangyum/tensorflow,Mazecreator/tensorflow,kobejean/tensorflow,snnn/tensorflow,davidzchen/tensorflow,jwlawson/tensorflow,laszlocsomor/tensorflow,johndpope/tensorflow,manazhao/tf_recsys,taknevski/tensorflow-xsmm,admcrae/tensorflow,ppries/tensorflow,jeffzheng1/tensorflow,sandeepdsouza93/TensorFlow-15712,jostep/tensorflow,jwlawson/tensorflow,strint/tensorflow,SnakeJenny/TensorFlow,DCSaunders/tensorflow,gnieboer/tensorflow,gunan/tensorflow,johndpope/tensorflow,alheinecke/tensorflow-xsmm,DCSaunders/tensorflow,anilmuthineni/tensorflow,lukeiwanski/tensorflow,benoitsteiner/tensorflow-xsmm,with-git/tensorflow,tornadozou/tensorflow,codrut3/tensorflow,raymondxyang/tensorflow,pierreg/tensorflow,cg31/tensorflow,eadgarchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,alsrgv/tensorflow,xodus7/tensorflow,martinwicke/tensorflow,llhe/tensorflow,chris-chris/tensorflow,xodus7/tensorflow,rdipietro/tensorflow,yanchen036/tensorflow,xzturn/tensorflow,laosiaudi/tensorflow,drpngx/tensorflow,pcm17/tensorflow,haeusser/tensorflow,asadziach/tensorflow,rabipanda/tensorflow,brchiu/tensorflow,MostafaGazar/tensorflow,rabipanda/tensorflow,ppries/tensorflow,arborh/tensorflow,rabipanda/tensorflow,MycChiu/tensorflow,maciekcc/tensorflow,renyi533/tensorflow,sjperkins/tensorflow,kobejean/tensorflow,manjunaths/tensorflow,unsiloai/syntaxnet-ops-hack,MycChiu/tensorflow,zasdfgbnm/tensorflow,martinwicke/tensorflow,nanditav/15712-TensorFlow,zasdfgbnm/tensorflow,renyi533/tensorflow,XueqingLin/tensorflow,petewarden/tensorflow,anilmuthineni/tensorflow,arborh/tensorflow,lakshayg/tensorflow,jhaux/tensorflow,sarvex/tensorflow,krikru/tensorflow-opencl,with-git/tensorflow,dongjoon-hyun/tensorflow,yongtang/tensorflow,rdipietro/tensorflow,horance-liu/tensorflow,petewarden/tensorflow,jwlawson/tensorflow,ghchinoy/tensorflow,jwlawson/tensorflow,krikru/tensorflow-opencl,thesuperzapper/tensorflow,alheinecke/tensorflow-xsmm,ibmsoe/tensorflow,tongwang01/tensorflow,guschmue/tensorflow,HKUST-SING/tensorflow,meteorcloudy/tensorflow,Kongsea/tensorflow,rabipanda/tensorflow,bowang/tensorflow,alistairlow/tensorflow,HKUST-SING/tensorflow,mavenlin/tensorflow,yanchen036/tensorflow,tensorflow/tensorflow-pywrap_saved_model,mengxn/tensorflow,alistairlow/tensorflow,calebfoss/tensorflow,wangyum/tensorflow,alisidd/tensorflow,caisq/tensorflow,ArtsiomCh/tensorflow,mdrumond/tensorflow,memo/tensorflow,Intel-Corporation/tensorflow,ychfan/tensorflow,MostafaGazar/tensorflow,aselle/tensorflow,renyi533/tensorflow,eadgarchen/tensorflow,eadgarchen/tensorflow,AnishShah/tensorflow,odejesush/tensorflow,mavenlin/tensorflow,ppwwyyxx/tensorflow,seaotterman/tensorflow,alivecor/tensorflow,adit-chandra/tensorflow,markslwong/tensorflow,tensorflow/tensorflow-pywrap_saved_model,lakshayg/tensorflow,pierreg/tensorflow,bowang/tensorflow,MycChiu/tensorflow,pierreg/tensorflow,zasdfgbnm/tensorflow,ychfan/tensorflow,eaplatanios/tensorflow,karllessard/tensorflow,tillahoffmann/tensorflow,DCSaunders/tensorflow,nikste/tensorflow,arborh/tensorflow,elingg/tensorflow,adit-chandra/tensorflow,jalexvig/tensorflow,jhaux/tensorflow,drpngx/tensorflow,Xeralux/tensorflow,alisidd/tensorflow,suiyuan2009/tensorflow,tillahoffmann/tensorflow,elingg/tensorflow,arborh/tensorflow,strint/tensorflow,xodus7/tensorflow,eerwitt/tensorflow,MycChiu/tensorflow,anand-c-goog/tensorflow,Xeralux/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ageron/tensorflow,Xeralux/tensorflow,LUTAN/tensorflow,DCSaunders/tensorflow,vrv/tensorflow,girving/tensorflow,admcrae/tensorflow,chenjun0210/tensorflow,kamcpp/tensorflow,mixturemodel-flow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,dyoung418/tensorflow,seanli9jan/tensorflow,pcm17/tensorflow,gojira/tensorflow,karllessard/tensorflow,yufengg/tensorflow,sandeepgupta2k4/tensorflow,xzturn/tensorflow,snnn/tensorflow,XueqingLin/tensorflow,yongtang/tensorflow,markslwong/tensorflow,handroissuazo/tensorflow,alistairlow/tensorflow,av8ramit/tensorflow,lukeiwanski/tensorflow,sjperkins/tensorflow,allenlavoie/tensorflow,gibiansky/tensorflow,abhitopia/tensorflow,ibmsoe/tensorflow,wangyum/tensorflow,Intel-Corporation/tensorflow,andrewcmyers/tensorflow,sandeepgupta2k4/tensorflow,annarev/tensorflow,JingJunYin/tensorflow,kevin-coder/tensorflow-fork,jeffzheng1/tensorflow,yaroslavvb/tensorflow,dyoung418/tensorflow,kevin-coder/tensorflow-fork,yaroslavvb/tensorflow,krikru/tensorflow-opencl,memo/tensorflow,JingJunYin/tensorflow,chenjun0210/tensorflow,aam-at/tensorflow,horance-liu/tensorflow,apark263/tensorflow,tomasreimers/tensorflow-emscripten,karllessard/tensorflow,chemelnucfin/tensorflow,XueqingLin/tensorflow,gunan/tensorflow,jhaux/tensorflow,yongtang/tensorflow,dancingdan/tensorflow,cg31/tensorflow,taknevski/tensorflow-xsmm,ageron/tensorflow,with-git/tensorflow,guschmue/tensorflow,johndpope/tensorflow,andrewcmyers/tensorflow,alistairlow/tensorflow,Mazecreator/tensorflow,laszlocsomor/tensorflow,davidzchen/tensorflow,ZhangXinNan/tensorflow,ychfan/tensorflow,alivecor/tensorflow,dendisuhubdy/tensorflow,MycChiu/tensorflow,adit-chandra/tensorflow,AnishShah/tensorflow,jart/tensorflow,guschmue/tensorflow,unsiloai/syntaxnet-ops-hack,ran5515/DeepDecision,nightjean/Deep-Learning,ville-k/tensorflow,tntnatbry/tensorflow,hfp/tensorflow-xsmm,bowang/tensorflow,ravindrapanda/tensorflow,jbedorf/tensorflow,elingg/tensorflow,adamtiger/tensorflow,Kongsea/tensorflow,aldian/tensorflow,anand-c-goog/tensorflow,brchiu/tensorflow,maciekcc/tensorflow,drpngx/tensorflow,tongwang01/tensorflow,tntnatbry/tensorflow,theflofly/tensorflow,codrut3/tensorflow,aam-at/tensorflow,lakshayg/tensorflow,Bismarrck/tensorflow,anilmuthineni/tensorflow,nightjean/Deep-Learning,davidzchen/tensorflow,Bismarrck/tensorflow,lukeiwanski/tensorflow,gnieboer/tensorflow,ppries/tensorflow,laszlocsomor/tensorflow,paolodedios/tensorflow,unsiloai/syntaxnet-ops-hack,anand-c-goog/tensorflow,naturali/tensorflow,kamcpp/tensorflow,yufengg/tensorflow,sandeepgupta2k4/tensorflow,eaplatanios/tensorflow,ran5515/DeepDecision,mengxn/tensorflow,Mistobaan/tensorflow,davidzchen/tensorflow,wangyum/tensorflow,alsrgv/tensorflow,gojira/tensorflow,wangyum/tensorflow,sandeepdsouza93/TensorFlow-15712,bowang/tensorflow,DCSaunders/tensorflow,codrut3/tensorflow,cg31/tensorflow,lukeiwanski/tensorflow,abhitopia/tensorflow,mrry/tensorflow,ibmsoe/tensorflow,ran5515/DeepDecision,paolodedios/tensorflow,JingJunYin/tensorflow,manazhao/tf_recsys,cancan101/tensorflow,meteorcloudy/tensorflow,eaplatanios/tensorflow,sandeepgupta2k4/tensorflow,kamcpp/tensorflow,SnakeJenny/TensorFlow,gautam1858/tensorflow,a-doumoulakis/tensorflow,martinwicke/tensorflow,freedomtan/tensorflow,brchiu/tensorflow,chemelnucfin/tensorflow,LUTAN/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,codrut3/tensorflow,benoitsteiner/tensorflow-xsmm,horance-liu/tensorflow,arborh/tensorflow,taknevski/tensorflow-xsmm,chris-chris/tensorflow,thesuperzapper/tensorflow,ychfan/tensorflow,ageron/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ArtsiomCh/tensorflow,benoitsteiner/tensorflow-opencl,tomasreimers/tensorflow-emscripten,dancingdan/tensorflow,calebfoss/tensorflow,krikru/tensorflow-opencl,krikru/tensorflow-opencl,JVillella/tensorflow,hfp/tensorflow-xsmm,alshedivat/tensorflow,tornadozou/tensorflow,maciekcc/tensorflow,ageron/tensorflow,benoitsteiner/tensorflow,Bulochkin/tensorflow_pack,xodus7/tensorflow,ishay2b/tensorflow,hfp/tensorflow-xsmm,raymondxyang/tensorflow,yongtang/tensorflow,tornadozou/tensorflow,laosiaudi/tensorflow,manjunaths/tensorflow,cancan101/tensorflow,llhe/tensorflow,tntnatbry/tensorflow,rdipietro/tensorflow,juharris/tensorflow,allenlavoie/tensorflow,llhe/tensorflow,Xeralux/tensorflow,mortada/tensorflow,ghchinoy/tensorflow,gunan/tensorflow,strint/tensorflow,mdrumond/tensorflow,MostafaGazar/tensorflow,taknevski/tensorflow-xsmm,benoitsteiner/tensorflow-xsmm,ishay2b/tensorflow,ppries/tensorflow,tomasreimers/tensorflow-emscripten,kamcpp/tensorflow,snnn/tensorflow,aam-at/tensorflow,Moriadry/tensorflow,petewarden/tensorflow,asimshankar/tensorflow,dancingdan/tensorflow,gautam1858/tensorflow,scenarios/tensorflow,sarvex/tensorflow,seanli9jan/tensorflow,jbedorf/tensorflow,freedomtan/tensorflow,thesuperzapper/tensorflow,code-sauce/tensorflow,caisq/tensorflow,scenarios/tensorflow,thjashin/tensorflow,asadziach/tensorflow,hehongliang/tensorflow,dendisuhubdy/tensorflow,thjashin/tensorflow,a-doumoulakis/tensorflow,theflofly/tensorflow,ville-k/tensorflow,yufengg/tensorflow,DavidNorman/tensorflow,neilhan/tensorflow,LUTAN/tensorflow,sjperkins/tensorflow,yaroslavvb/tensorflow,ZhangXinNan/tensorflow,unsiloai/syntaxnet-ops-hack,zycdragonball/tensorflow,aam-at/tensorflow,strint/tensorflow,benoitsteiner/tensorflow-xsmm,mrry/tensorflow,Mistobaan/tensorflow,cg31/tensorflow,arborh/tensorflow,MycChiu/tensorflow,JingJunYin/tensorflow,haeusser/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,calebfoss/tensorflow,ychfan/tensorflow,tillahoffmann/tensorflow,jostep/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,adamtiger/tensorflow,alheinecke/tensorflow-xsmm,yaroslavvb/tensorflow,ZhangXinNan/tensorflow,annarev/tensorflow,MycChiu/tensorflow,nburn42/tensorflow,Kongsea/tensorflow,aselle/tensorflow,Xeralux/tensorflow,unsiloai/syntaxnet-ops-hack,DavidNorman/tensorflow,paolodedios/tensorflow,ppwwyyxx/tensorflow,taknevski/tensorflow-xsmm,drpngx/tensorflow,av8ramit/tensorflow,pierreg/tensorflow,nolanliou/tensorflow,SnakeJenny/TensorFlow,seanli9jan/tensorflow,tomasreimers/tensorflow-emscripten,yanchen036/tensorflow,freedomtan/tensorflow,karllessard/tensorflow,ravindrapanda/tensorflow,JingJunYin/tensorflow,jbedorf/tensorflow,yongtang/tensorflow,maciekcc/tensorflow,zasdfgbnm/tensorflow,asadziach/tensorflow,sarvex/tensorflow,sandeepgupta2k4/tensorflow,jeffzheng1/tensorflow,ibmsoe/tensorflow,HKUST-SING/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,nolanliou/tensorflow,calebfoss/tensorflow,rabipanda/tensorflow,anilmuthineni/tensorflow,kamcpp/tensorflow,apark263/tensorflow,kchodorow/tensorflow,drpngx/tensorflow,haeusser/tensorflow,juharris/tensorflow,memo/tensorflow,frreiss/tensorflow-fred,hsaputra/tensorflow,benoitsteiner/tensorflow-xsmm,tensorflow/tensorflow-pywrap_tf_optimizer,aselle/tensorflow,jostep/tensorflow,jhaux/tensorflow,mengxn/tensorflow,asadziach/tensorflow,aldian/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,vrv/tensorflow,lukeiwanski/tensorflow,ZhangXinNan/tensorflow,chris-chris/tensorflow,tomasreimers/tensorflow-emscripten,elingg/tensorflow,anilmuthineni/tensorflow,bowang/tensorflow,ppwwyyxx/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,dancingdan/tensorflow,tntnatbry/tensorflow,mortada/tensorflow,neilhan/tensorflow,annarev/tensorflow,dendisuhubdy/tensorflow,suiyuan2009/tensorflow,dongjoon-hyun/tensorflow,DCSaunders/tensorflow,llhe/tensorflow,benoitsteiner/tensorflow,mixturemodel-flow/tensorflow,nolanliou/tensorflow,a-doumoulakis/tensorflow,tiagofrepereira2012/tensorflow,kevin-coder/tensorflow-fork,ageron/tensorflow,laszlocsomor/tensorflow,Moriadry/tensorflow,llhe/tensorflow,jalexvig/tensorflow,wangyum/tensorflow,dongjoon-hyun/tensorflow,rdipietro/tensorflow,johndpope/tensorflow,chris-chris/tensorflow,ville-k/tensorflow,mixturemodel-flow/tensorflow,HKUST-SING/tensorflow,raymondxyang/tensorflow,dongjoon-hyun/tensorflow,ppwwyyxx/tensorflow,jart/tensorflow,yaroslavvb/tensorflow,Intel-tensorflow/tensorflow,xzturn/tensorflow,naturali/tensorflow,yongtang/tensorflow,martinwicke/tensorflow,kobejean/tensorflow,nolanliou/tensorflow,benoitsteiner/tensorflow,renyi533/tensorflow,alheinecke/tensorflow-xsmm,ravindrapanda/tensorflow,ibmsoe/tensorflow,kchodorow/tensorflow,juharris/tensorflow,tiagofrepereira2012/tensorflow,adamtiger/tensorflow,aldian/tensorflow,guschmue/tensorflow,benoitsteiner/tensorflow-opencl,jart/tensorflow,yanchen036/tensorflow,kamcpp/tensorflow,apark263/tensorflow,alivecor/tensorflow,DavidNorman/tensorflow,tomasreimers/tensorflow-emscripten,theflofly/tensorflow,theflofly/tensorflow,benoitsteiner/tensorflow-opencl,gojira/tensorflow,alheinecke/tensorflow-xsmm,jhaux/tensorflow,tillahoffmann/tensorflow,ishay2b/tensorflow,adit-chandra/tensorflow,hfp/tensorflow-xsmm,guschmue/tensorflow,yongtang/tensorflow,elingg/tensorflow,JVillella/tensorflow,brchiu/tensorflow,lukeiwanski/tensorflow-opencl,yufengg/tensorflow,alsrgv/tensorflow,tiagofrepereira2012/tensorflow,apark263/tensorflow,hehongliang/tensorflow,manipopopo/tensorflow,dyoung418/tensorflow,arborh/tensorflow,Mazecreator/tensorflow,jhaux/tensorflow,caisq/tensorflow,yanchen036/tensorflow,pierreg/tensorflow,tomasreimers/tensorflow-emscripten,ville-k/tensorflow,xodus7/tensorflow,guschmue/tensorflow,snnn/tensorflow,eadgarchen/tensorflow,jbedorf/tensorflow,horance-liu/tensorflow,cxxgtxy/tensorflow,sandeepgupta2k4/tensorflow,tensorflow/tensorflow,xzturn/tensorflow,jalexvig/tensorflow,johndpope/tensorflow,Bismarrck/tensorflow,theflofly/tensorflow,annarev/tensorflow,dongjoon-hyun/tensorflow,jalexvig/tensorflow,rabipanda/tensorflow,zycdragonball/tensorflow,taknevski/tensorflow-xsmm,markslwong/tensorflow,kobejean/tensorflow,gnieboer/tensorflow,seaotterman/tensorflow,gunan/tensorflow,cxxgtxy/tensorflow,Intel-Corporation/tensorflow,anand-c-goog/tensorflow,whn09/tensorflow,Bismarrck/tensorflow,Intel-tensorflow/tensorflow,alistairlow/tensorflow,manjunaths/tensorflow,alsrgv/tensorflow,JingJunYin/tensorflow,mavenlin/tensorflow,yanchen036/tensorflow,manjunaths/tensorflow,meteorcloudy/tensorflow,alistairlow/tensorflow,girving/tensorflow,horance-liu/tensorflow,davidzchen/tensorflow,eadgarchen/tensorflow,gojira/tensorflow,Bismarrck/tensorflow,haeusser/tensorflow,frreiss/tensorflow-fred,dongjoon-hyun/tensorflow,eadgarchen/tensorflow,DavidNorman/tensorflow,anilmuthineni/tensorflow,kchodorow/tensorflow,vrv/tensorflow,thesuperzapper/tensorflow,nolanliou/tensorflow,MoamerEncsConcordiaCa/tensorflow,nanditav/15712-TensorFlow,nolanliou/tensorflow,AnishShah/tensorflow,tensorflow/tensorflow,ppwwyyxx/tensorflow,Bismarrck/tensorflow,Xeralux/tensorflow,jalexvig/tensorflow,thjashin/tensorflow,jeffzheng1/tensorflow,ZhangXinNan/tensorflow,theflofly/tensorflow,caisq/tensorflow,a-doumoulakis/tensorflow,whn09/tensorflow,JVillella/tensorflow,cxxgtxy/tensorflow,nanditav/15712-TensorFlow,Mazecreator/tensorflow,SnakeJenny/TensorFlow,nightjean/Deep-Learning,HKUST-SING/tensorflow,maciekcc/tensorflow,kamcpp/tensorflow,pcm17/tensorflow,pavelchristof/gomoku-ai,tongwang01/tensorflow,hfp/tensorflow-xsmm,jeffzheng1/tensorflow,mrry/tensorflow,jeffzheng1/tensorflow,lakshayg/tensorflow,jalexvig/tensorflow,Mistobaan/tensorflow,Carmezim/tensorflow,pavelchristof/gomoku-ai,freedomtan/tensorflow,hfp/tensorflow-xsmm,seanli9jan/tensorflow,mixturemodel-flow/tensorflow,theflofly/tensorflow,ZhangXinNan/tensorflow,manipopopo/tensorflow,sandeepdsouza93/TensorFlow-15712,drpngx/tensorflow,chemelnucfin/tensorflow,hsaputra/tensorflow,cg31/tensorflow,dyoung418/tensorflow,vrv/tensorflow,cxxgtxy/tensorflow,alsrgv/tensorflow,dongjoon-hyun/tensorflow,tornadozou/tensorflow,petewarden/tensorflow,brchiu/tensorflow,gibiansky/tensorflow,thesuperzapper/tensorflow,mengxn/tensorflow,zasdfgbnm/tensorflow,RapidApplicationDevelopment/tensorflow,hfp/tensorflow-xsmm,benoitsteiner/tensorflow-xsmm,juharris/tensorflow,frreiss/tensorflow-fred,chemelnucfin/tensorflow,eadgarchen/tensorflow,dancingdan/tensorflow,Mazecreator/tensorflow,caisq/tensorflow,davidzchen/tensorflow,JingJunYin/tensorflow,jart/tensorflow,benoitsteiner/tensorflow,tensorflow/tensorflow-pywrap_saved_model,laosiaudi/tensorflow,caisq/tensorflow,johndpope/tensorflow,hehongliang/tensorflow,ppwwyyxx/tensorflow,aldian/tensorflow,tiagofrepereira2012/tensorflow,ZhangXinNan/tensorflow,odejesush/tensorflow,ghchinoy/tensorflow,code-sauce/tensorflow,naturali/tensorflow,alsrgv/tensorflow,eadgarchen/tensorflow,johndpope/tensorflow,DCSaunders/tensorflow,suiyuan2009/tensorflow,codrut3/tensorflow,allenlavoie/tensorflow,rabipanda/tensorflow,DavidNorman/tensorflow,ran5515/DeepDecision,nightjean/Deep-Learning,alheinecke/tensorflow-xsmm,manipopopo/tensorflow,gojira/tensorflow,brchiu/tensorflow,meteorcloudy/tensorflow,cancan101/tensorflow,abhitopia/tensorflow,jart/tensorflow,tensorflow/tensorflow,manipopopo/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,jostep/tensorflow,apark263/tensorflow,karllessard/tensorflow,XueqingLin/tensorflow,chris-chris/tensorflow,Bulochkin/tensorflow_pack,Carmezim/tensorflow,rdipietro/tensorflow,ghchinoy/tensorflow,alshedivat/tensorflow,Moriadry/tensorflow,manipopopo/tensorflow,admcrae/tensorflow,nightjean/Deep-Learning,mdrumond/tensorflow,lukeiwanski/tensorflow-opencl,Carmezim/tensorflow,cxxgtxy/tensorflow,Carmezim/tensorflow,chemelnucfin/tensorflow,brchiu/tensorflow,SnakeJenny/TensorFlow,snnn/tensorflow,adit-chandra/tensorflow,tillahoffmann/tensorflow,handroissuazo/tensorflow,ZhangXinNan/tensorflow,nanditav/15712-TensorFlow,ppwwyyxx/tensorflow,ghchinoy/tensorflow,adamtiger/tensorflow,calebfoss/tensorflow,juharris/tensorflow,AnishShah/tensorflow,brchiu/tensorflow,nightjean/Deep-Learning,ychfan/tensorflow,Moriadry/tensorflow,jhaux/tensorflow,tntnatbry/tensorflow,scenarios/tensorflow,tensorflow/tensorflow,AndreasMadsen/tensorflow,rdipietro/tensorflow,ArtsiomCh/tensorflow,memo/tensorflow,unsiloai/syntaxnet-ops-hack,paolodedios/tensorflow,martinwicke/tensorflow,eaplatanios/tensorflow,ageron/tensorflow,odejesush/tensorflow,davidzchen/tensorflow,nburn42/tensorflow,LUTAN/tensorflow,AndreasMadsen/tensorflow,aselle/tensorflow,JingJunYin/tensorflow,sjperkins/tensorflow,Intel-tensorflow/tensorflow,AndreasMadsen/tensorflow,Mistobaan/tensorflow,vrv/tensorflow,lukeiwanski/tensorflow-opencl,kevin-coder/tensorflow-fork,code-sauce/tensorflow,alsrgv/tensorflow,wangyum/tensorflow,nburn42/tensorflow,AnishShah/tensorflow,chenjun0210/tensorflow,seanli9jan/tensorflow,ghchinoy/tensorflow,horance-liu/tensorflow,seaotterman/tensorflow,jendap/tensorflow,xzturn/tensorflow,nightjean/Deep-Learning,thesuperzapper/tensorflow,theflofly/tensorflow,ArtsiomCh/tensorflow,markslwong/tensorflow,Mistobaan/tensorflow,nburn42/tensorflow,mrry/tensorflow,andrewcmyers/tensorflow,frreiss/tensorflow-fred,kchodorow/tensorflow,adit-chandra/tensorflow,annarev/tensorflow,AndreasMadsen/tensorflow,handroissuazo/tensorflow,snnn/tensorflow,jwlawson/tensorflow,petewarden/tensorflow,tillahoffmann/tensorflow,cxxgtxy/tensorflow,kobejean/tensorflow,gautam1858/tensorflow,kamcpp/tensorflow,sarvex/tensorflow,anand-c-goog/tensorflow,brchiu/tensorflow,jbedorf/tensorflow,hfp/tensorflow-xsmm,brchiu/tensorflow,andrewcmyers/tensorflow,snnn/tensorflow,laosiaudi/tensorflow,ishay2b/tensorflow,alshedivat/tensorflow,bowang/tensorflow,asimshankar/tensorflow,kchodorow/tensorflow,andrewcmyers/tensorflow,MostafaGazar/tensorflow,lukeiwanski/tensorflow-opencl,kobejean/tensorflow,renyi533/tensorflow,suiyuan2009/tensorflow,odejesush/tensorflow,Intel-tensorflow/tensorflow,renyi533/tensorflow,aam-at/tensorflow,yongtang/tensorflow,jwlawson/tensorflow,alivecor/tensorflow,jeffzheng1/tensorflow,tensorflow/tensorflow,guschmue/tensorflow,neilhan/tensorflow,adit-chandra/tensorflow,dendisuhubdy/tensorflow,tomasreimers/tensorflow-emscripten,mortada/tensorflow,martinwicke/tensorflow,handroissuazo/tensorflow,manipopopo/tensorflow,thjashin/tensorflow,JVillella/tensorflow,horance-liu/tensorflow,jart/tensorflow,gunan/tensorflow,XueqingLin/tensorflow,xodus7/tensorflow,renyi533/tensorflow,asimshankar/tensorflow,chemelnucfin/tensorflow,ibmsoe/tensorflow,frreiss/tensorflow-fred,zasdfgbnm/tensorflow,scenarios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,krikru/tensorflow-opencl,martinwicke/tensorflow,wangyum/tensorflow,neilhan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ppwwyyxx/tensorflow,naturali/tensorflow,tensorflow/tensorflow-pywrap_saved_model,pcm17/tensorflow,eerwitt/tensorflow,with-git/tensorflow,asimshankar/tensorflow,jwlawson/tensorflow,tensorflow/tensorflow-pywrap_saved_model,manazhao/tf_recsys,guschmue/tensorflow,av8ramit/tensorflow,chris-chris/tensorflow,benoitsteiner/tensorflow,hsaputra/tensorflow,frreiss/tensorflow-fred,odejesush/tensorflow,dyoung418/tensorflow,jbedorf/tensorflow,aam-at/tensorflow,lukeiwanski/tensorflow,pcm17/tensorflow,eerwitt/tensorflow,nikste/tensorflow,gnieboer/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,thjashin/tensorflow,nanditav/15712-TensorFlow,AndreasMadsen/tensorflow,pierreg/tensorflow,adit-chandra/tensorflow,mortada/tensorflow,whn09/tensorflow,jart/tensorflow,Mazecreator/tensorflow,lukeiwanski/tensorflow,Intel-Corporation/tensorflow,aselle/tensorflow,alisidd/tensorflow,dyoung418/tensorflow,ville-k/tensorflow,seanli9jan/tensorflow,DCSaunders/tensorflow,Kongsea/tensorflow,dongjoon-hyun/tensorflow,allenlavoie/tensorflow,alshedivat/tensorflow,cancan101/tensorflow,vrv/tensorflow,naturali/tensorflow,chris-chris/tensorflow,nikste/tensorflow,elingg/tensorflow,frreiss/tensorflow-fred,code-sauce/tensorflow,MoamerEncsConcordiaCa/tensorflow,jendap/tensorflow,ibmsoe/tensorflow,alisidd/tensorflow,jendap/tensorflow,MoamerEncsConcordiaCa/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,strint/tensorflow,asimshankar/tensorflow,maciekcc/tensorflow,cg31/tensorflow,meteorcloudy/tensorflow,vrv/tensorflow,eerwitt/tensorflow,martinwicke/tensorflow,ghchinoy/tensorflow,odejesush/tensorflow,aam-at/tensorflow,MycChiu/tensorflow,AnishShah/tensorflow,kevin-coder/tensorflow-fork,laszlocsomor/tensorflow,arborh/tensorflow,Moriadry/tensorflow,AnishShah/tensorflow,Carmezim/tensorflow,AnishShah/tensorflow,allenlavoie/tensorflow,hfp/tensorflow-xsmm,maciekcc/tensorflow,HKUST-SING/tensorflow,jwlawson/tensorflow,Carmezim/tensorflow,gnieboer/tensorflow,tensorflow/tensorflow,hehongliang/tensorflow,SnakeJenny/TensorFlow,anand-c-goog/tensorflow,hsaputra/tensorflow,AndreasMadsen/tensorflow,Bulochkin/tensorflow_pack,abhitopia/tensorflow,jhseu/tensorflow,eaplatanios/tensorflow,snnn/tensorflow,adit-chandra/tensorflow,renyi533/tensorflow,mdrumond/tensorflow,pavelchristof/gomoku-ai,nightjean/Deep-Learning,gibiansky/tensorflow,tillahoffmann/tensorflow,with-git/tensorflow,asadziach/tensorflow,chemelnucfin/tensorflow,dancingdan/tensorflow,juharris/tensorflow,ZhangXinNan/tensorflow,nanditav/15712-TensorFlow,ravindrapanda/tensorflow,sarvex/tensorflow,guschmue/tensorflow,allenlavoie/tensorflow,MostafaGazar/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,mavenlin/tensorflow,whn09/tensorflow,tornadozou/tensorflow,zasdfgbnm/tensorflow,juharris/tensorflow,with-git/tensorflow,adamtiger/tensorflow,mortada/tensorflow,HKUST-SING/tensorflow,seanli9jan/tensorflow,petewarden/tensorflow,yanchen036/tensorflow,laszlocsomor/tensorflow,AndreasMadsen/tensorflow,tensorflow/tensorflow,suiyuan2009/tensorflow,jendap/tensorflow,xzturn/tensorflow,with-git/tensorflow,girving/tensorflow,naturali/tensorflow,jbedorf/tensorflow,naturali/tensorflow,girving/tensorflow,ppries/tensorflow,anand-c-goog/tensorflow,gojira/tensorflow,jhseu/tensorflow,strint/tensorflow,HKUST-SING/tensorflow,jart/tensorflow,sjperkins/tensorflow,meteorcloudy/tensorflow,Mazecreator/tensorflow,codrut3/tensorflow,asimshankar/tensorflow,strint/tensorflow,cxxgtxy/tensorflow,petewarden/tensorflow,manipopopo/tensorflow,gnieboer/tensorflow,MoamerEncsConcordiaCa/tensorflow,eerwitt/tensorflow,gunan/tensorflow,asadziach/tensorflow,gibiansky/tensorflow,ville-k/tensorflow,RapidApplicationDevelopment/tensorflow,Mazecreator/tensorflow,cancan101/tensorflow,jostep/tensorflow,dyoung418/tensorflow,zasdfgbnm/tensorflow,ZhangXinNan/tensorflow,dongjoon-hyun/tensorflow,benoitsteiner/tensorflow-opencl,mixturemodel-flow/tensorflow,tornadozou/tensorflow,nburn42/tensorflow,abhitopia/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,neilhan/tensorflow,ville-k/tensorflow,asimshankar/tensorflow,tillahoffmann/tensorflow,alistairlow/tensorflow,snnn/tensorflow,tiagofrepereira2012/tensorflow,pcm17/tensorflow,memo/tensorflow,pierreg/tensorflow,aselle/tensorflow,mixturemodel-flow/tensorflow,mengxn/tensorflow,chenjun0210/tensorflow,handroissuazo/tensorflow,codrut3/tensorflow,mengxn/tensorflow,Bulochkin/tensorflow_pack,lakshayg/tensorflow,alshedivat/tensorflow,memo/tensorflow,pavelchristof/gomoku-ai,drpngx/tensorflow,freedomtan/tensorflow,laszlocsomor/tensorflow,ArtsiomCh/tensorflow,adamtiger/tensorflow,gibiansky/tensorflow,manazhao/tf_recsys,codrut3/tensorflow,allenlavoie/tensorflow,code-sauce/tensorflow,unsiloai/syntaxnet-ops-hack,gibiansky/tensorflow,aselle/tensorflow,gibiansky/tensorflow,raymondxyang/tensorflow,ghchinoy/tensorflow,hsaputra/tensorflow,freedomtan/tensorflow,mortada/tensorflow,caisq/tensorflow,eerwitt/tensorflow,pavelchristof/gomoku-ai,gunan/tensorflow,renyi533/tensorflow,caisq/tensorflow,XueqingLin/tensorflow,elingg/tensorflow,eerwitt/tensorflow,RapidApplicationDevelopment/tensorflow,xodus7/tensorflow,caisq/tensorflow,ibmsoe/tensorflow,nanditav/15712-TensorFlow,calebfoss/tensorflow,gautam1858/tensorflow,jendap/tensorflow,yaroslavvb/tensorflow,RapidApplicationDevelopment/tensorflow,zycdragonball/tensorflow,JingJunYin/tensorflow,nolanliou/tensorflow,benoitsteiner/tensorflow-opencl,kchodorow/tensorflow,hsaputra/tensorflow,alsrgv/tensorflow,benoitsteiner/tensorflow-xsmm,gunan/tensorflow,eaplatanios/tensorflow,jhseu/tensorflow,ArtsiomCh/tensorflow,girving/tensorflow,gunan/tensorflow,MostafaGazar/tensorflow,Intel-Corporation/tensorflow,sandeepdsouza93/TensorFlow-15712,seanli9jan/tensorflow,eaplatanios/tensorflow,XueqingLin/tensorflow,seanli9jan/tensorflow,yaroslavvb/tensorflow,thesuperzapper/tensorflow,gautam1858/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,chenjun0210/tensorflow,dancingdan/tensorflow,asimshankar/tensorflow,gibiansky/tensorflow,ville-k/tensorflow,mengxn/tensorflow,SnakeJenny/TensorFlow,anilmuthineni/tensorflow,yongtang/tensorflow,annarev/tensorflow,nikste/tensorflow,ran5515/DeepDecision,kobejean/tensorflow,laosiaudi/tensorflow,nanditav/15712-TensorFlow,MoamerEncsConcordiaCa/tensorflow,sandeepgupta2k4/tensorflow,annarev/tensorflow,odejesush/tensorflow,jalexvig/tensorflow,jhseu/tensorflow,tensorflow/tensorflow,benoitsteiner/tensorflow,admcrae/tensorflow,llhe/tensorflow,sandeepdsouza93/TensorFlow-15712,alistairlow/tensorflow,rdipietro/tensorflow,jeffzheng1/tensorflow,paolodedios/tensorflow,alisidd/tensorflow,jendap/tensorflow,av8ramit/tensorflow,dendisuhubdy/tensorflow,adit-chandra/tensorflow,Xeralux/tensorflow,laosiaudi/tensorflow,nburn42/tensorflow,jbedorf/tensorflow,zasdfgbnm/tensorflow,raymondxyang/tensorflow,lakshayg/tensorflow,whn09/tensorflow,manjunaths/tensorflow,cancan101/tensorflow,eaplatanios/tensorflow,eaplatanios/tensorflow,ghchinoy/tensorflow,calebfoss/tensorflow,meteorcloudy/tensorflow,aldian/tensorflow,asadziach/tensorflow,Kongsea/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,alisidd/tensorflow,Intel-Corporation/tensorflow,Mazecreator/tensorflow,zycdragonball/tensorflow,ghchinoy/tensorflow,manipopopo/tensorflow,davidzchen/tensorflow,krikru/tensorflow-opencl,xzturn/tensorflow,elingg/tensorflow,jhseu/tensorflow,mengxn/tensorflow,yongtang/tensorflow,brchiu/tensorflow,sandeepgupta2k4/tensorflow,av8ramit/tensorflow,tensorflow/tensorflow-pywrap_saved_model,mavenlin/tensorflow,tntnatbry/tensorflow,av8ramit/tensorflow,jhseu/tensorflow,markslwong/tensorflow,nburn42/tensorflow,sandeepdsouza93/TensorFlow-15712,alsrgv/tensorflow,ville-k/tensorflow,ran5515/DeepDecision,code-sauce/tensorflow,mdrumond/tensorflow,ravindrapanda/tensorflow,Carmezim/tensorflow,cancan101/tensorflow,Xeralux/tensorflow,a-doumoulakis/tensorflow,Bulochkin/tensorflow_pack,chemelnucfin/tensorflow,gojira/tensorflow,Mistobaan/tensorflow,chris-chris/tensorflow,sjperkins/tensorflow,ppries/tensorflow,thesuperzapper/tensorflow,aselle/tensorflow,davidzchen/tensorflow,gojira/tensorflow,ppwwyyxx/tensorflow,alisidd/tensorflow,ychfan/tensorflow,tomasreimers/tensorflow-emscripten,abhitopia/tensorflow,nburn42/tensorflow,mrry/tensorflow,raymondxyang/tensorflow,mavenlin/tensorflow,krikru/tensorflow-opencl,strint/tensorflow,renyi533/tensorflow,caisq/tensorflow,manazhao/tf_recsys,apark263/tensorflow,Bulochkin/tensorflow_pack,horance-liu/tensorflow,LUTAN/tensorflow,manipopopo/tensorflow,thjashin/tensorflow,horance-liu/tensorflow,tiagofrepereira2012/tensorflow,laszlocsomor/tensorflow,llhe/tensorflow,zycdragonball/tensorflow,ghchinoy/tensorflow,bowang/tensorflow,theflofly/tensorflow,LUTAN/tensorflow,benoitsteiner/tensorflow,kchodorow/tensorflow,asadziach/tensorflow,xodus7/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,jhseu/tensorflow,DavidNorman/tensorflow,MoamerEncsConcordiaCa/tensorflow,yaroslavvb/tensorflow,dendisuhubdy/tensorflow,Mistobaan/tensorflow,neilhan/tensorflow,freedomtan/tensorflow,nolanliou/tensorflow,dendisuhubdy/tensorflow,yufengg/tensorflow,kevin-coder/tensorflow-fork,Bismarrck/tensorflow,kevin-coder/tensorflow-fork,XueqingLin/tensorflow,alisidd/tensorflow,sandeepgupta2k4/tensorflow,andrewcmyers/tensorflow,benoitsteiner/tensorflow,whn09/tensorflow,calebfoss/tensorflow,freedomtan/tensorflow,alivecor/tensorflow,neilhan/tensorflow,alshedivat/tensorflow,llhe/tensorflow,gautam1858/tensorflow,tiagofrepereira2012/tensorflow,Intel-tensorflow/tensorflow,ravindrapanda/tensorflow,girving/tensorflow,jendap/tensorflow,suiyuan2009/tensorflow,jendap/tensorflow,RapidApplicationDevelopment/tensorflow,seaotterman/tensorflow,alshedivat/tensorflow,jostep/tensorflow,haeusser/tensorflow,asimshankar/tensorflow,AndreasMadsen/tensorflow,jbedorf/tensorflow,scenarios/tensorflow,lukeiwanski/tensorflow-opencl,gunan/tensorflow,karllessard/tensorflow,hehongliang/tensorflow,DCSaunders/tensorflow,manazhao/tf_recsys,kevin-coder/tensorflow-fork,Bulochkin/tensorflow_pack,annarev/tensorflow,benoitsteiner/tensorflow,handroissuazo/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,hsaputra/tensorflow,Intel-tensorflow/tensorflow,odejesush/tensorflow,code-sauce/tensorflow,kevin-coder/tensorflow-fork,thjashin/tensorflow,Intel-tensorflow/tensorflow,hsaputra/tensorflow,jhseu/tensorflow,mrry/tensorflow,HKUST-SING/tensorflow,lukeiwanski/tensorflow-opencl,allenlavoie/tensorflow,dyoung418/tensorflow,theflofly/tensorflow,petewarden/tensorflow,xodus7/tensorflow,pavelchristof/gomoku-ai,aldian/tensorflow,johndpope/tensorflow,jhaux/tensorflow,manipopopo/tensorflow,admcrae/tensorflow,manjunaths/tensorflow,paolodedios/tensorflow,theflofly/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,anilmuthineni/tensorflow,av8ramit/tensorflow,allenlavoie/tensorflow,Bulochkin/tensorflow_pack,seaotterman/tensorflow,raymondxyang/tensorflow,seanli9jan/tensorflow,naturali/tensorflow,nanditav/15712-TensorFlow,abhitopia/tensorflow,ArtsiomCh/tensorflow,hsaputra/tensorflow,johndpope/tensorflow,jhaux/tensorflow,kchodorow/tensorflow,admcrae/tensorflow,seaotterman/tensorflow,aldian/tensorflow,aam-at/tensorflow,benoitsteiner/tensorflow-opencl,adit-chandra/tensorflow,theflofly/tensorflow,kobejean/tensorflow,zycdragonball/tensorflow,cancan101/tensorflow,gibiansky/tensorflow,dendisuhubdy/tensorflow,girving/tensorflow,rabipanda/tensorflow,codrut3/tensorflow,hsaputra/tensorflow,Moriadry/tensorflow,llhe/tensorflow,alistairlow/tensorflow,codrut3/tensorflow,Bulochkin/tensorflow_pack,meteorcloudy/tensorflow,hehongliang/tensorflow,MoamerEncsConcordiaCa/tensorflow,Mistobaan/tensorflow,karllessard/tensorflow,dancingdan/tensorflow,apark263/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,mrry/tensorflow,Mistobaan/tensorflow,mortada/tensorflow,raymondxyang/tensorflow,rabipanda/tensorflow,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,arborh/tensorflow,av8ramit/tensorflow,eerwitt/tensorflow,tntnatbry/tensorflow,pcm17/tensorflow,Bulochkin/tensorflow_pack,MoamerEncsConcordiaCa/tensorflow,drpngx/tensorflow,neilhan/tensorflow,adit-chandra/tensorflow,RapidApplicationDevelopment/tensorflow,ran5515/DeepDecision,xzturn/tensorflow,davidzchen/tensorflow,ppwwyyxx/tensorflow,bowang/tensorflow,ppwwyyxx/tensorflow,guschmue/tensorflow,sarvex/tensorflow,manipopopo/tensorflow,renyi533/tensorflow,xzturn/tensorflow,mavenlin/tensorflow,MostafaGazar/tensorflow,DavidNorman/tensorflow,tiagofrepereira2012/tensorflow,renyi533/tensorflow,seanli9jan/tensorflow,lukeiwanski/tensorflow-opencl,tensorflow/tensorflow-pywrap_saved_model,DavidNorman/tensorflow,xodus7/tensorflow,apark263/tensorflow,paolodedios/tensorflow,snnn/tensorflow,girving/tensorflow,jalexvig/tensorflow,frreiss/tensorflow-fred,jwlawson/tensorflow,manjunaths/tensorflow,whn09/tensorflow,petewarden/tensorflow,elingg/tensorflow,memo/tensorflow,alistairlow/tensorflow,gunan/tensorflow,gautam1858/tensorflow,Carmezim/tensorflow,taknevski/tensorflow-xsmm,kamcpp/tensorflow,Moriadry/tensorflow,jbedorf/tensorflow,maciekcc/tensorflow,jart/tensorflow,scenarios/tensorflow,allenlavoie/tensorflow,markslwong/tensorflow,kevin-coder/tensorflow-fork,mixturemodel-flow/tensorflow,wangyum/tensorflow,ychfan/tensorflow,jalexvig/tensorflow,pcm17/tensorflow,ppries/tensorflow,markslwong/tensorflow,kobejean/tensorflow,chemelnucfin/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,jalexvig/tensorflow,gunan/tensorflow,horance-liu/tensorflow,gojira/tensorflow,admcrae/tensorflow,kobejean/tensorflow,strint/tensorflow,AnishShah/tensorflow,SnakeJenny/TensorFlow,calebfoss/tensorflow,memo/tensorflow,nikste/tensorflow,JVillella/tensorflow,ageron/tensorflow,JVillella/tensorflow,vrv/tensorflow,Bulochkin/tensorflow_pack,Bismarrck/tensorflow,cg31/tensorflow,mortada/tensorflow,gnieboer/tensorflow,Kongsea/tensorflow,lukeiwanski/tensorflow,dendisuhubdy/tensorflow,laosiaudi/tensorflow,LUTAN/tensorflow,Mistobaan/tensorflow,seaotterman/tensorflow,jhseu/tensorflow,ArtsiomCh/tensorflow,odejesush/tensorflow,av8ramit/tensorflow,asadziach/tensorflow,ghchinoy/tensorflow,eadgarchen/tensorflow,eerwitt/tensorflow,benoitsteiner/tensorflow-xsmm,kevin-coder/tensorflow-fork,Xeralux/tensorflow,unsiloai/syntaxnet-ops-hack,ageron/tensorflow,pavelchristof/gomoku-ai,lakshayg/tensorflow,chenjun0210/tensorflow,aselle/tensorflow,johndpope/tensorflow,nburn42/tensorflow,AnishShah/tensorflow,cg31/tensorflow,alshedivat/tensorflow,sarvex/tensorflow,alivecor/tensorflow,JingJunYin/tensorflow,cancan101/tensorflow,rabipanda/tensorflow,zasdfgbnm/tensorflow,a-doumoulakis/tensorflow,Kongsea/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,abhitopia/tensorflow,nikste/tensorflow,ishay2b/tensorflow,alheinecke/tensorflow-xsmm,manjunaths/tensorflow,Xeralux/tensorflow,alsrgv/tensorflow,cg31/tensorflow,girving/tensorflow,code-sauce/tensorflow,code-sauce/tensorflow,Bismarrck/tensorflow,gojira/tensorflow,MycChiu/tensorflow,chenjun0210/tensorflow,krikru/tensorflow-opencl,jhseu/tensorflow,DavidNorman/tensorflow,xzturn/tensorflow,ibmsoe/tensorflow,MostafaGazar/tensorflow,mdrumond/tensorflow | tensorflow/tools/docker/jupyter_notebook_config.py | tensorflow/tools/docker/jupyter_notebook_config.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import os
from IPython.lib import passwd
c.NotebookApp.ip = '*'
c.NotebookApp.port = int(os.getenv('PORT', 8888))
c.NotebookApp.open_browser = False
c.MultiKernelManager.default_kernel_name = 'python2'
# sets a password if PASSWORD is set in the environment
if 'PASSWORD' in os.environ:
c.NotebookApp.password = passwd(os.environ['PASSWORD'])
del os.environ['PASSWORD']
| # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import os
from IPython.lib import passwd
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.MultiKernelManager.default_kernel_name = 'python2'
# sets a password if PASSWORD is set in the environment
if 'PASSWORD' in os.environ:
c.NotebookApp.password = passwd(os.environ['PASSWORD'])
del os.environ['PASSWORD']
| apache-2.0 | Python |
05e671a41641746802f6ae6155f79fdcb13a3c6a | Fix Authorization header that is not a Bearer to not return a token | oauthlib/oauthlib | oauthlib/openid/connect/core/tokens.py | oauthlib/openid/connect/core/tokens.py | """
authlib.openid.connect.core.tokens
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains methods for adding JWT tokens to requests.
"""
from oauthlib.oauth2.rfc6749.tokens import TokenBase, random_token_generator
class JWTToken(TokenBase):
__slots__ = (
'request_validator', 'token_generator',
'refresh_token_generator', 'expires_in'
)
def __init__(self, request_validator=None, token_generator=None,
expires_in=None, refresh_token_generator=None):
self.request_validator = request_validator
self.token_generator = token_generator or random_token_generator
self.refresh_token_generator = (
refresh_token_generator or self.token_generator
)
self.expires_in = expires_in or 3600
def create_token(self, request, refresh_token=False):
"""Create a JWT Token, using requestvalidator method."""
if callable(self.expires_in):
expires_in = self.expires_in(request)
else:
expires_in = self.expires_in
request.expires_in = expires_in
return self.request_validator.get_jwt_bearer_token(None, None, request)
def validate_request(self, request):
token = None
if 'Authorization' in request.headers:
split_header = request.headers.get('Authorization').split()
if len(split_header) == 2 and split_header[0].lower() == 'bearer':
token = split_header[1]
else:
token = request.access_token
return self.request_validator.validate_jwt_bearer_token(
token, request.scopes, request)
def estimate_type(self, request):
token = request.headers.get('Authorization', '')[7:]
if token.startswith('ey') and token.count('.') in (2, 4):
return 10
else:
return 0
| """
authlib.openid.connect.core.tokens
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains methods for adding JWT tokens to requests.
"""
from oauthlib.oauth2.rfc6749.tokens import TokenBase, random_token_generator
class JWTToken(TokenBase):
__slots__ = (
'request_validator', 'token_generator',
'refresh_token_generator', 'expires_in'
)
def __init__(self, request_validator=None, token_generator=None,
expires_in=None, refresh_token_generator=None):
self.request_validator = request_validator
self.token_generator = token_generator or random_token_generator
self.refresh_token_generator = (
refresh_token_generator or self.token_generator
)
self.expires_in = expires_in or 3600
def create_token(self, request, refresh_token=False):
"""Create a JWT Token, using requestvalidator method."""
if callable(self.expires_in):
expires_in = self.expires_in(request)
else:
expires_in = self.expires_in
request.expires_in = expires_in
return self.request_validator.get_jwt_bearer_token(None, None, request)
def validate_request(self, request):
token = None
if 'Authorization' in request.headers:
token = request.headers.get('Authorization')[7:]
else:
token = request.access_token
return self.request_validator.validate_jwt_bearer_token(
token, request.scopes, request)
def estimate_type(self, request):
token = request.headers.get('Authorization', '')[7:]
if token.startswith('ey') and token.count('.') in (2, 4):
return 10
else:
return 0
| bsd-3-clause | Python |
8063970bd063d53cf2a05734643f6326f69bcd97 | move to release 0.0.7 | Eric89GXL/sphinx-gallery,sphinx-gallery/sphinx-gallery,Titan-C/sphinx-gallery,Titan-C/sphinx-gallery,lesteve/sphinx-gallery,Eric89GXL/sphinx-gallery,sphinx-gallery/sphinx-gallery,lesteve/sphinx-gallery | sphinxgallery/__init__.py | sphinxgallery/__init__.py | """Sphinx Gallery
"""
import os
__version__ = '0.0.7'
def path_static():
"""Returns path to packaged static files"""
return os.path.abspath(os.path.dirname(__file__))+'/_static'
| """Sphinx Gallery
"""
import os
__version__ = '0.0.6'
def _path_static():
"""Returns path to packaged static files"""
return os.path.abspath(os.path.dirname(__file__))+'/_static'
| bsd-3-clause | Python |
7777bb182906e7808f407d0d0c9eb25adaae5417 | Define debug. | soasme/riotpy | riot/utils.py | riot/utils.py | # -*- coding: utf-8 -*-
import sys
def debug(*args):
for arg in args:
print >> sys.stderr, arg,
print >> sys.stderr, ''
def walk(root, function, path=None):
if not root:
return
path = path or []
if not function(root, path):
return
for index, child in enumerate(root.children().items()):
walk(child, function, path + [index])
def get_ui_by_path(root, path):
import urwid
ui = root
for level in path[1:]:
if level == 0:
if isinstance(ui, urwid.Filler):
ui = ui.body
elif isinstance(ui, urwid.Pile):
ui = ui.contents[0][0]
elif isinstance(ui, urwid.ListBox):
ui = ui.body.contents[0]
elif isinstance(ui, urwid.AttrMap):
ui = ui.base_widget
elif isinstance(ui, urwid.Text):
continue
else:
raise NotImplementedError(ui)
else:
if callable(ui.contents):
ui = ui.contents()[level][0]
else:
ui = ui.contents[level][0]
if isinstance(ui, urwid.AttrMap):
return ui.original_widget
return ui
| # -*- coding: utf-8 -*-
import sys
def walk(root, function, path=None):
if not root:
return
path = path or []
if not function(root, path):
return
for index, child in enumerate(root.children().items()):
walk(child, function, path + [index])
def get_ui_by_path(root, path):
import urwid
ui = root
for level in path[1:]:
if level == 0:
if isinstance(ui, urwid.Filler):
ui = ui.body
elif isinstance(ui, urwid.Pile):
ui = ui.contents[0][0]
elif isinstance(ui, urwid.AttrMap):
ui = ui.base_widget
else:
raise NotImplementedError(ui)
else:
ui = ui.contents[level][0]
if isinstance(ui, urwid.AttrMap):
return ui.base_widget
return ui
| mit | Python |
2ab0083a2b143130d19552a37ae4366b2a681720 | Add a comment explaining what these tests are for, and where to look for tests of complex(). | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | Lib/test/test_complex.py | Lib/test/test_complex.py | from test_support import TestFailed
from random import random
# These tests ensure that complex math does the right thing; tests of
# the complex() function/constructor are in test_b1.py.
# XXX need many, many more tests here.
nerrors = 0
def check_close_real(x, y, eps=1e-9):
"""Return true iff floats x and y "are close\""""
# put the one with larger magnitude second
if abs(x) > abs(y):
x, y = y, x
if y == 0:
return abs(x) < eps
if x == 0:
return abs(y) < eps
# check that relative difference < eps
return abs((x-y)/y) < eps
def check_close(x, y, eps=1e-9):
"""Return true iff complexes x and y "are close\""""
return check_close_real(x.real, y.real, eps) and \
check_close_real(x.imag, y.imag, eps)
def test_div(x, y):
"""Compute complex z=x*y, and check that z/x==y and z/y==x."""
global nerrors
z = x * y
if x != 0:
q = z / x
if not check_close(q, y):
nerrors += 1
print "%r / %r == %r but expected %r" % (z, x, q, y)
if y != 0:
q = z / y
if not check_close(q, x):
nerrors += 1
print "%r / %r == %r but expected %r" % (z, y, q, x)
simple_real = [float(i) for i in range(-5, 6)]
simple_complex = [complex(x, y) for x in simple_real for y in simple_real]
for x in simple_complex:
for y in simple_complex:
test_div(x, y)
# A naive complex division algorithm (such as in 2.0) is very prone to
# nonsense errors for these (overflows and underflows).
test_div(complex(1e200, 1e200), 1+0j)
test_div(complex(1e-200, 1e-200), 1+0j)
# Just for fun.
for i in range(100):
test_div(complex(random(), random()),
complex(random(), random()))
try:
z = 1.0 / (0+0j)
except ZeroDivisionError:
pass
else:
nerrors += 1
raise TestFailed("Division by complex 0 didn't raise ZeroDivisionError")
if nerrors:
raise TestFailed("%d tests failed" % nerrors)
| from test_support import TestFailed
from random import random
# XXX need many, many more tests here.
nerrors = 0
def check_close_real(x, y, eps=1e-9):
"""Return true iff floats x and y "are close\""""
# put the one with larger magnitude second
if abs(x) > abs(y):
x, y = y, x
if y == 0:
return abs(x) < eps
if x == 0:
return abs(y) < eps
# check that relative difference < eps
return abs((x-y)/y) < eps
def check_close(x, y, eps=1e-9):
"""Return true iff complexes x and y "are close\""""
return check_close_real(x.real, y.real, eps) and \
check_close_real(x.imag, y.imag, eps)
def test_div(x, y):
"""Compute complex z=x*y, and check that z/x==y and z/y==x."""
global nerrors
z = x * y
if x != 0:
q = z / x
if not check_close(q, y):
nerrors += 1
print "%r / %r == %r but expected %r" % (z, x, q, y)
if y != 0:
q = z / y
if not check_close(q, x):
nerrors += 1
print "%r / %r == %r but expected %r" % (z, y, q, x)
simple_real = [float(i) for i in range(-5, 6)]
simple_complex = [complex(x, y) for x in simple_real for y in simple_real]
for x in simple_complex:
for y in simple_complex:
test_div(x, y)
# A naive complex division algorithm (such as in 2.0) is very prone to
# nonsense errors for these (overflows and underflows).
test_div(complex(1e200, 1e200), 1+0j)
test_div(complex(1e-200, 1e-200), 1+0j)
# Just for fun.
for i in range(100):
test_div(complex(random(), random()),
complex(random(), random()))
try:
z = 1.0 / (0+0j)
except ZeroDivisionError:
pass
else:
nerrors += 1
raise TestFailed("Division by complex 0 didn't raise ZeroDivisionError")
if nerrors:
raise TestFailed("%d tests failed" % nerrors)
| mit | Python |
a2810fb4154685456e8ad4381234e109cf657d6e | modify assert in distance.py | k2kobayashi/sprocket | sprocket/util/distance.py | sprocket/util/distance.py | # -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import numpy as np
def melcd(array1, array2):
"""Calculate mel-cepstrum distortion
Calculate mel-cepstrum distortion between the arrays.
This function assumes the shapes of arrays are same.
Parameters
----------
array1, array2 : array, shape (`T`, `dim`) or shape (`dim`)
Arrays of original and target.
Returns
-------
mcd : scala, number > 0
Scala of mel-cepstrum distortion
"""
if array1.shape != array2.shape:
raise ValueError(
"The shapes of both arrays are different \
: {} / {}".format(array1.shape, array2.shape))
if array1.ndim == 2:
# array based melcd calculation
diff = array1 - array2
mcd = 10.0 / np.log(10) \
* np.mean(np.sqrt(2.0 * np.sum(diff ** 2, axis=1)))
elif array1.ndim == 1:
diff = array1 - array2
mcd = 10.0 / np.log(10) * np.sqrt(2.0 * np.sum(diff ** 2))
else:
raise ValueError("Dimension mismatch")
return mcd
| # -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import numpy as np
def melcd(array1, array2):
"""Calculate mel-cepstrum distortion
Calculate mel-cepstrum distortion between the arrays
or vectors. This function assumes the shapes of arrays
or vectors are same.
Parameters
----------
array1, array2 : array, shape (`T`, `dim`)
Arrays of original and target.
Returns
-------
mcd : scala, number > 0
Scala of mel-cepstrum distortion
"""
assert array1.shape == array2.shape
if array1.ndim == 2:
# array based melcd calculation
diff = array1 - array2
mcd = 10.0 / np.log(10) \
* np.mean(np.sqrt(2.0 * np.sum(diff ** 2, axis=1)))
elif array1.ndim == 1:
diff = array1 - array2
mcd = 10.0 / np.log(10) * np.sqrt(2.0 * np.sum(diff ** 2))
else:
raise ValueError("Dimension mismatch")
return mcd
| mit | Python |
870915b4ff62911a4d19295b45ff9e95a92532d3 | Simplify runner for installer | SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview,SasView/sasview | installers/sasview.py | installers/sasview.py | # -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
Run sasview from an installed bundle
"""
import sys
sys.dont_write_bytecode = True
from sas.qtgui.MainWindow.MainWindow import run_sasview
run_sasview()
| # -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
Run sasview in place. This allows sasview to use the python
files in the source tree without having to call setup.py install
first. A rebuild is still necessary when working on sas models
or c modules.
Usage:
./run.py [(module|script) args...]
Without arguments run.py runs sasview. With arguments, run.py will run
the given module or script.
"""
import imp
import os
import sys
from contextlib import contextmanager
from os.path import join as joinpath
from os.path import abspath, dirname, realpath
def addpath(path):
"""
Add a directory to the python path environment, and to the PYTHONPATH
environment variable for subprocesses.
"""
path = abspath(path)
if 'PYTHONPATH' in os.environ:
PYTHONPATH = path + os.pathsep + os.environ['PYTHONPATH']
else:
PYTHONPATH = path
os.environ['PYTHONPATH'] = PYTHONPATH
sys.path.insert(0, path)
@contextmanager
def cd(path):
"""
Change directory for duration of "with" context.
"""
old_dir = os.getcwd()
os.chdir(path)
yield
os.chdir(old_dir)
def import_package(modname, path):
"""Import a package into a particular point in the python namespace"""
#logger.debug("Dynamicly importing: %s", path)
mod = imp.load_source(modname, abspath(joinpath(path, '__init__.py')))
sys.modules[modname] = mod
mod.__path__ = [abspath(path)]
return mod
def import_dll(modname, build_path):
"""Import a DLL from the build directory"""
import sysconfig
ext = sysconfig.get_config_var('SO')
# build_path comes from context
path = joinpath(build_path, *modname.split('.')) + ext
return imp.load_dynamic(modname, path)
def prepare():
# Don't create *.pyc files
sys.dont_write_bytecode = True
# find the directories for the source and build
from distutils.util import get_platform
root = joinpath(abspath(dirname(sys.argv[0])), '..')
platform = '%s-%s' % (get_platform(), sys.version[:3])
build_path = joinpath(root, 'build', 'lib.' + platform)
# Notify the help menu that the Sphinx documentation is in a different
# place than it otherwise would be.
os.environ['SASVIEW_DOC_PATH'] = joinpath(build_path, "doc")
# add periodictable to the path
try:
import periodictable
except:
addpath(joinpath(root, '..', 'periodictable'))
try:
import bumps
except:
addpath(joinpath(root, '..', 'bumps'))
# Put the source trees on the path
addpath(joinpath(root, 'src'))
# sasmodels on the path
addpath(joinpath(root, '../sasmodels/'))
from sas.sascalc.dataloader.readers import (
abs_reader, anton_paar_saxs_reader, ascii_reader, cansas_reader_HDF5,
cansas_reader, danse_reader, red2d_reader, sesans_reader, tiff_reader,
xml_reader,
)
sys.path.append(build_path)
if __name__ == "__main__":
# Need to add absolute path before actual prepare call,
# so logging can be done during initialization process too
root = abspath(dirname(realpath(sys.argv[0])))
addpath(joinpath(root, '..', 'src','sas'))
prepare()
from sas.qtgui.MainWindow.MainWindow import run_sasview
run_sasview()
| bsd-3-clause | Python |
d4a1282e7e7c3a6cc804d2f583d37d484961adad | handle the case where a package has no downloads | crateio/crate.io | crate_project/apps/packages/stats/views.py | crate_project/apps/packages/stats/views.py | import collections
import json
import time
import isoweek
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from packages.models import Package, Release, DownloadDelta, DownloadStatsCache
def fetch_stats(package):
releases = Release.objects.filter(package=package)
releases = sorted(releases, key=lambda x: x.downloads)
specific_releases = set([x.version for x in releases[-8:]])
deltas = list(DownloadDelta.objects.filter(file__release__in=releases).order_by("date"))
# @@@ Sanity Checks
if not deltas:
return []
data = [{"name": "Other", "data": []}] + [{"name": release.version, "data": []} for release in releases if release.version in specific_releases]
# Get First Week
start_week = isoweek.Week.withdate(deltas[0].date)
end_week = isoweek.Week.thisweek()
current = isoweek.Week(start_week.year, start_week.week)
while current.year <= end_week.year and current.week < end_week.week:
for x in data:
x["data"].append({"x": int(time.mktime(current.day(0).timetuple()))})
current = isoweek.Week(current.year, current.week + 1)
_data = collections.defaultdict(dict)
for d in deltas:
target = int(time.mktime(isoweek.Week.withdate(d.date).day(0).timetuple()))
_data[d.file.release.version if d.file.release.version in specific_releases else "Other"][target] = d.delta
for i in xrange(0, len(data)):
for j in xrange(0, len(data[i]["data"])):
data[i]["data"][j]["y"] = _data[data[i]["name"] if data[i]["name"] in specific_releases else "Other"].get(data[i]["data"][j]["x"], 0)
return data
def stats_delta(request, slug):
package = get_object_or_404(Package, name=slug)
try:
cached = DownloadStatsCache.objects.get(package=package)
except DownloadStatsCache.DoesNotExist:
pass
else:
return HttpResponse(json.dumps(cached.data), mimetype="application/json")
data = fetch_stats(package)
DownloadStatsCache.objects.create(package=package, data=data)
return HttpResponse(json.dumps(data), mimetype="application/json")
| import collections
import json
import time
import isoweek
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from packages.models import Package, Release, DownloadDelta, DownloadStatsCache
def fetch_stats(package):
releases = Release.objects.filter(package=package)
releases = sorted(releases, key=lambda x: x.downloads)
specific_releases = set([x.version for x in releases[-8:]])
deltas = list(DownloadDelta.objects.filter(file__release__in=releases).order_by("date"))
# @@@ Sanity Checks
data = [{"name": "Other", "data": []}] + [{"name": release.version, "data": []} for release in releases if release.version in specific_releases]
# Get First Week
start_week = isoweek.Week.withdate(deltas[0].date)
end_week = isoweek.Week.thisweek()
current = isoweek.Week(start_week.year, start_week.week)
while current.year <= end_week.year and current.week < end_week.week:
for x in data:
x["data"].append({"x": int(time.mktime(current.day(0).timetuple()))})
current = isoweek.Week(current.year, current.week + 1)
_data = collections.defaultdict(dict)
for d in deltas:
target = int(time.mktime(isoweek.Week.withdate(d.date).day(0).timetuple()))
_data[d.file.release.version if d.file.release.version in specific_releases else "Other"][target] = d.delta
for i in xrange(0, len(data)):
for j in xrange(0, len(data[i]["data"])):
data[i]["data"][j]["y"] = _data[data[i]["name"] if data[i]["name"] in specific_releases else "Other"].get(data[i]["data"][j]["x"], 0)
return data
def stats_delta(request, slug):
package = get_object_or_404(Package, name=slug)
try:
cached = DownloadStatsCache.objects.get(package=package)
except DownloadStatsCache.DoesNotExist:
pass
else:
return HttpResponse(json.dumps(cached.data), mimetype="application/json")
data = fetch_stats(package)
DownloadStatsCache.objects.create(package=package, data=data)
return HttpResponse(json.dumps(data), mimetype="application/json")
| bsd-2-clause | Python |
2d6ea66a5ef078ec000dee05ba855ee5e22fbd6c | Address review comments, fix signatures that the docs lied about | sholsapp/cryptography,skeuomorf/cryptography,kimvais/cryptography,Hasimir/cryptography,dstufft/cryptography,dstufft/cryptography,sholsapp/cryptography,dstufft/cryptography,sholsapp/cryptography,skeuomorf/cryptography,dstufft/cryptography,bwhmather/cryptography,skeuomorf/cryptography,Ayrx/cryptography,Ayrx/cryptography,Ayrx/cryptography,kimvais/cryptography,bwhmather/cryptography,bwhmather/cryptography,kimvais/cryptography,kimvais/cryptography,dstufft/cryptography,Hasimir/cryptography,Ayrx/cryptography,Hasimir/cryptography,Hasimir/cryptography,skeuomorf/cryptography,sholsapp/cryptography,bwhmather/cryptography | cryptography/hazmat/bindings/openssl/dh.py | cryptography/hazmat/bindings/openssl/dh.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
INCLUDES = """
#include <openssl/dh.h>
"""
TYPES = """
typedef struct dh_st {
// prime number (shared)
BIGNUM *p;
// generator of Z_p (shared)
BIGNUM *g;
// private DH value x
BIGNUM *priv_key;
// public DH value g^x
BIGNUM *pub_key;
...;
} DH;
"""
FUNCTIONS = """
DH *DH_new(void);
void DH_free(DH *);
int DH_size(const DH *);
DH *DH_generate_parameters(int, int, void (*)(int, int, void *), void *);
int DH_check(const DH *, int *);
int DH_generate_key(DH *);
int DH_compute_key(unsigned char *, const BIGNUM *, DH *);
int DH_set_ex_data(DH *, int, void *);
void *DH_get_ex_data(DH *, int);
DH *d2iDHparams(DH **, unsigned char **, long);
int i2d_DHparams(const DH *, unsigned char **);
int DHparams_print_fp(FILE *, const DH *);
int DHparams_print(BIO *, const DH *);
"""
MACROS = """
int DH_generate_parameters_ex(DH *, int, int, BN_GENCB *);
"""
CUSTOMIZATIONS = """
"""
CONDITIONAL_NAMES = {}
| # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
INCLUDES = """
#include <openssl/dh.h>
"""
TYPES = """
typedef struct dh_st {
// prime number (shared)
BIGNUM *p;
// generator of Z_p (shared)
BIGNUM *g;
// private DH value x
BIGNUM *priv_key;
// public DH value g^x
BIGNUM *pub_key;
...;
} DH;
"""
FUNCTIONS = """
DH *DH_new(void);
void DH_free(DH *);
int DH_size(const DH *);
DH *DH_generate_parameters(int, int, void (*)(int, int, void *), void *);
int DH_check(const DH *, int *);
int DH_generate_key(DH *);
int DH_compute_key(unsigned char *, BIGNUM *, DH *);
int DH_set_ex_data(DH *, int, char *);
char *DH_get_ex_data(DH *, int);
DH *d2iDHparams(DH **, unsigned char **, long);
int i2d_DHparams(const DH *, unsigned char **);
int DHparams_print_fp(FILE *, const DH *);
int DHparams_print(BIO *, const DH *);
"""
MACROS = """
int DH_generate_parameters_ex(DH *, int, int, BN_GENCB *);
"""
CUSTOMIZATIONS = """
"""
CONDITIONAL_NAMES = {}
| bsd-3-clause | Python |
c2699d9769aff771985bac7fbb6dd60a943307f9 | add the tests results to pull | redhat-cip/dci-control-server,redhat-cip/dci-control-server | dci/analytics/access_data_layer.py | dci/analytics/access_data_layer.py | # -*- coding: utf-8 -*-
#
# Copyright (C) Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from datetime import datetime as dt, timedelta as td
import sqlalchemy.orm as sa_orm
from dci.db import models2
def get_jobs(session, offset, limit, unit, amount):
delta = {unit: amount}
query = session.query(models2.Job)
query = query.filter(models2.Job.state != "archived")
query = query.filter(models2.Job.created_at >= (dt.now() - td(**delta)))
query = query.order_by(models2.Job.created_at.asc())
query = query.from_self()
query = (
query.options(sa_orm.selectinload("components"))
.options(sa_orm.selectinload("jobstates"))
.options(sa_orm.selectinload("jobstates.files"))
.options(sa_orm.selectinload("files"))
.options(sa_orm.selectinload("results"))
.options(sa_orm.joinedload("pipeline", innerjoin=True))
)
query = query.offset(offset)
query = query.limit(limit)
jobs = [j.serialize(ignore_columns=["data"]) for j in query.all()]
return jobs
def get_components(session, offset, limit, unit, amount):
delta = {unit: amount}
query = session.query(models2.Component)
query = query.filter(models2.Component.state != "archived")
query = query.filter(models2.Component.created_at >= (dt.now() - td(**delta)))
query = query.order_by(models2.Component.created_at.asc())
query = query.options(sa_orm.selectinload("jobs"))
query = query.offset(offset)
query = query.limit(limit)
jobs = [c.serialize() for c in query.all()]
return jobs
| # -*- coding: utf-8 -*-
#
# Copyright (C) Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from datetime import datetime as dt, timedelta as td
import sqlalchemy.orm as sa_orm
from dci.db import models2
def get_jobs(session, offset, limit, unit, amount):
delta = {unit: amount}
query = session.query(models2.Job)
query = query.filter(models2.Job.state != "archived")
query = query.filter(models2.Job.created_at >= (dt.now() - td(**delta)))
query = query.order_by(models2.Job.created_at.asc())
query = query.from_self()
query = (
query.options(sa_orm.selectinload("components"))
.options(sa_orm.selectinload("jobstates"))
.options(sa_orm.selectinload("jobstates.files"))
.options(sa_orm.selectinload("files"))
.options(sa_orm.joinedload("pipeline", innerjoin=True))
)
query = query.offset(offset)
query = query.limit(limit)
jobs = [j.serialize(ignore_columns=["data"]) for j in query.all()]
return jobs
def get_components(session, offset, limit, unit, amount):
delta = {unit: amount}
query = session.query(models2.Component)
query = query.filter(models2.Component.state != "archived")
query = query.filter(models2.Component.created_at >= (dt.now() - td(**delta)))
query = query.order_by(models2.Component.created_at.asc())
query = query.options(sa_orm.selectinload("jobs"))
query = query.offset(offset)
query = query.limit(limit)
jobs = [c.serialize() for c in query.all()]
return jobs
| apache-2.0 | Python |
cf7b1be0c416142c6f0b991f715b9c9df88a0c05 | handle event priority in the DI extension | rande/python-simple-ioc,rande/python-simple-ioc | ioc/extra/event/di.py | ioc/extra/event/di.py | import ioc.loader, ioc.component, ioc.exceptions
import os, datetime
class Extension(ioc.component.Extension):
def load(self, config, container_builder):
container_builder.add('ioc.extra.event_dispatcher', ioc.component.Definition('ioc.event.Dispatcher'))
def post_build(self, container_builder, container):
dispatcher = container.get('ioc.extra.event_dispatcher')
for id in container_builder.get_ids_by_tag('event.listener'):
definition = container_builder.get(id)
for option in definition.get_tag('event.listener'):
if 'name' not in option:
break
if 'method' not in option:
break
if 'priority' not in option:
option['priority'] = 0
dispatcher.add_listener(option['name'], getattr(container.get(id), option['method']), option['priority']) | import ioc.loader, ioc.component, ioc.exceptions
import os, datetime
class Extension(ioc.component.Extension):
def load(self, config, container_builder):
container_builder.add('ioc.extra.event_dispatcher', ioc.component.Definition('ioc.event.Dispatcher'))
def post_build(self, container_builder, container):
dispatcher = container.get('ioc.extra.event_dispatcher')
for id in container_builder.get_ids_by_tag('event.listener'):
definition = container_builder.get(id)
for option in definition.get_tag('event.listener'):
if 'name' not in option:
break
if 'method' not in option:
break
dispatcher.add_listener(option['name'], getattr(container.get(id), option['method'])) | apache-2.0 | Python |
277222434b184cab036445aee95aac4e7dec8e31 | Revert "Let's ignore utf8 issues for now." | kbussell/django-docusign,kbussell/django-docusign,novafloss/django-docusign | demo/django_docusign_demo/tests.py | demo/django_docusign_demo/tests.py | # coding=utf8
import os
from django.core.urlresolvers import reverse
import django.test
from django_docusign_demo import models
here = os.path.abspath(os.path.dirname(__file__))
fixtures_dir = os.path.join(here, 'fixtures')
class SignatureFunctionalTestCase(django.test.TestCase):
"""Functional test suite for 'create_signature' URL."""
#: Class-level signature instance, in order to reduce API calls.
_signature = None
@property
def signature(self):
"""Get or create signature instance."""
if self._signature is None:
self.assertEqual(models.Signature.objects.all().count(), 0)
url = reverse('create_signature')
with open(os.path.join(fixtures_dir, 'test.pdf')) as document_file:
data = {
'signer_name': u'John Accentué',
'signer_email': u'john@example.com',
'document': document_file,
}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, reverse('home'))
self.assertEqual(models.Signature.objects.all().count(), 1)
self._signature = models.Signature.objects.get()
return self._signature
def test_form_valid(self):
"""Can create a signature using 'create_signature' URL."""
self.assertTrue(self.signature.signature_backend_id)
def test_signer_view(self):
"""Signer view redirects to DocuSign."""
url = reverse('anysign:signer',
args=[self.signature.signers.all()[0].pk])
response = self.client.get(url)
self.assertEqual(response.status_code, 301)
self.assertTrue(
response['Location'].startswith('https://demo.docusign.net'))
| # coding=utf8
import os
from django.core.urlresolvers import reverse
import django.test
from django_docusign_demo import models
here = os.path.abspath(os.path.dirname(__file__))
fixtures_dir = os.path.join(here, 'fixtures')
class SignatureFunctionalTestCase(django.test.TestCase):
"""Functional test suite for 'create_signature' URL."""
#: Class-level signature instance, in order to reduce API calls.
_signature = None
@property
def signature(self):
"""Get or create signature instance."""
if self._signature is None:
self.assertEqual(models.Signature.objects.all().count(), 0)
url = reverse('create_signature')
with open(os.path.join(fixtures_dir, 'test.pdf')) as document_file:
data = {
'signer_name': u'John Accentue',
'signer_email': u'john@example.com',
'document': document_file,
}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, reverse('home'))
self.assertEqual(models.Signature.objects.all().count(), 1)
self._signature = models.Signature.objects.get()
return self._signature
def test_form_valid(self):
"""Can create a signature using 'create_signature' URL."""
self.assertTrue(self.signature.signature_backend_id)
def test_signer_view(self):
"""Signer view redirects to DocuSign."""
url = reverse('anysign:signer',
args=[self.signature.signers.all()[0].pk])
response = self.client.get(url)
self.assertEqual(response.status_code, 301)
self.assertTrue(
response['Location'].startswith('https://demo.docusign.net'))
| bsd-3-clause | Python |
d3c753a145b173cd5cad9e053c691d8460dad8f0 | add _add_child to ForeignFutureOperation | genome/flow-workflow,genome/flow-workflow,genome/flow-workflow | flow_workflow/future_operation.py | flow_workflow/future_operation.py | from flow_workflow.factory import operation_variable_name
class FutureOperation(object):
def __init__(self, operation_class, operation_id, name, parent, **kwargs):
self.operation_class = operation_class
self.operation_id = int(operation_id)
self.name = name
self.parent = parent
self.kwargs = kwargs
self._children = {}
parent._add_child(self)
def _add_child(self, child):
self._children[child.name] = child
def _child_data(self, default_net_key):
return {name: (c.net_key(default_net_key), c.operation_id)
for name, c in self._children.iteritems()}
@property
def _operation_variable_name(self):
return operation_variable_name(self.operation_id)
def net_key(self, default_net_key):
return default_net_key
def save(self, net):
net.variables[self._operation_variable_name] = self.as_dict(
default_net_key=net.key)
def as_dict(self, default_net_key):
result = {
'_class': self.operation_class,
'children': self._child_data(default_net_key),
'name': self.name,
'operation_id': self.operation_id,
'parent_operation_id': self.parent.operation_id,
'parent_net_key': self.parent.net_key(default_net_key),
}
result.update(self.kwargs)
return result
class NullFutureOperation(FutureOperation):
def __init__(self, *args, **kwargs):
pass
def _add_child(self, child):
pass
@property
def operation_id(self):
return None
class ForeignFutureOperation(object):
def __init__(self, operation_data):
self.operation_id = operation_data.operation_id
self._net_key = operation_data.net_key
def _add_child(self, child):
pass
def net_key(self, default_net_key):
return self._net_key
| from flow_workflow.factory import operation_variable_name
class FutureOperation(object):
def __init__(self, operation_class, operation_id, name, parent, **kwargs):
self.operation_class = operation_class
self.operation_id = int(operation_id)
self.name = name
self.parent = parent
self.kwargs = kwargs
self._children = {}
parent._add_child(self)
def _add_child(self, child):
self._children[child.name] = child
def _child_data(self, default_net_key):
return {name: (c.net_key(default_net_key), c.operation_id)
for name, c in self._children.iteritems()}
@property
def _operation_variable_name(self):
return operation_variable_name(self.operation_id)
def net_key(self, default_net_key):
return default_net_key
def save(self, net):
net.variables[self._operation_variable_name] = self.as_dict(
default_net_key=net.key)
def as_dict(self, default_net_key):
result = {
'_class': self.operation_class,
'children': self._child_data(default_net_key),
'name': self.name,
'operation_id': self.operation_id,
'parent_operation_id': self.parent.operation_id,
'parent_net_key': self.parent.net_key(default_net_key),
}
result.update(self.kwargs)
return result
class NullFutureOperation(FutureOperation):
def __init__(self, *args, **kwargs):
pass
def _add_child(self, child):
pass
@property
def operation_id(self):
return None
class ForeignFutureOperation(object):
def __init__(self, operation_data):
self.operation_id = operation_data.operation_id
self._net_key = operation_data.net_key
def net_key(self, default_net_key):
return self._net_key
| agpl-3.0 | Python |
afce0f198e47b1fd1d8ba70ac748eda5e3943d25 | Remove get_normalized_sentiment. Sentiment score need not to be normalized. | studiawan/pygraphc | pygraphc/anomaly/SentimentAnalysis.py | pygraphc/anomaly/SentimentAnalysis.py | from textblob import TextBlob
from operator import itemgetter
class SentimentAnalysis(object):
"""Get sentiment analysis with only positive and negative considered.
Positive means normal logs and negative sentiment refers to possible attacks.
This class uses sentiment analysis feature from the TextBlob library [Loria2016]_.
References
----------
.. [Loria2016] Steven Loria and the contributors, TextBlob: Simple, Pythonic, text processing--Sentiment analysis,
part-of-speech tagging, noun phrase extraction, translation, and more.
https://github.com/sloria/TextBlob/
"""
def __init__(self, graph, clusters):
self.graph = graph
self.clusters = clusters
self.cluster_message = {}
def get_cluster_message(self):
"""Get most frequent message in a cluster.
"""
for cluster_id, cluster in self.clusters.iteritems():
event_frequency = {}
for node in cluster:
event = self.graph.node[node]['preprocessed_event']
event_frequency[event] = event_frequency.get(event, 0) + 1
sorted_event_frequency = sorted(event_frequency.items(), key=itemgetter(1), reverse=True)[0][0]
self.cluster_message[cluster_id] = sorted_event_frequency
def get_sentiment(self):
"""Get negative or positive sentiment.
Default score for sentiment score is -1 to 1. The value that close to 1 means more positive and vice versa.
Returns
-------
sentiment_score : dict
A dictionary containing key: cluster id and value: sentiment score.
"""
sentiment_score = {}
for cluster_id, message in self.cluster_message.iteritems():
possible_sentiment = TextBlob(message)
if possible_sentiment.sentiment.polarity >= 0.:
sentiment_score[cluster_id] = possible_sentiment.sentiment.polarity
elif possible_sentiment.sentiment.polarity < 0.:
sentiment_score[cluster_id] = possible_sentiment.sentiment.polarity
return sentiment_score
| from textblob import TextBlob
from operator import itemgetter
class SentimentAnalysis(object):
"""Get sentiment analysis with only positive and negative considered.
Positive means normal logs and negative sentiment refers to possible attacks.
This class uses sentiment analysis feature from the TextBlob library [Loria2016]_.
References
----------
.. [Loria2016] Steven Loria and the contributors, TextBlob: Simple, Pythonic, text processing--Sentiment analysis,
part-of-speech tagging, noun phrase extraction, translation, and more.
https://github.com/sloria/TextBlob/
"""
def __init__(self, graph, clusters):
self.graph = graph
self.clusters = clusters
self.cluster_message = {}
def get_cluster_message(self):
"""Get most frequent message in a cluster.
"""
for cluster_id, cluster in self.clusters.iteritems():
event_frequency = {}
for node in cluster:
event = self.graph.node[node]['preprocessed_event']
event_frequency[event] = event_frequency.get(event, 0) + 1
sorted_event_frequency = sorted(event_frequency.items(), key=itemgetter(1), reverse=True)[0][0]
self.cluster_message[cluster_id] = sorted_event_frequency
def get_sentiment(self):
"""Get negative or positive sentiment.
Default score for sentiment score is -1 to 1. The value that close to 1 means more positive and vice versa.
Returns
-------
sentiment_score : dict
A dictionary containing key: cluster id and value: sentiment score.
"""
sentiment_score = {}
for cluster_id, message in self.cluster_message.iteritems():
possible_sentiment = TextBlob(message)
if possible_sentiment.sentiment.polarity >= 0.:
sentiment_score[cluster_id] = possible_sentiment.sentiment.polarity
elif possible_sentiment.sentiment.polarity < 0.:
sentiment_score[cluster_id] = possible_sentiment.sentiment.polarity
return sentiment_score
def get_normalized_sentiment(self):
"""Get normalized sentiment score.
Returns
-------
normalized_score : dict
A dictionary containing key: cluster id and value: normalized sentiment score.
"""
sentiment_score = self.get_sentiment()
normalized_score = {}
min_score = min(sentiment_score.values())
max_score = max(sentiment_score.values())
for cluster_id, score in sentiment_score.iteritems():
normalized_score[cluster_id] = (score - min_score) / (max_score - min_score)
return normalized_score
| mit | Python |
2a63e93dc2ecb8f3d195411a140c6fc3c0c50bf7 | Remove missed `website.models` import | brianjgeiger/osf.io,icereval/osf.io,binoculars/osf.io,caneruguz/osf.io,adlius/osf.io,cslzchen/osf.io,baylee-d/osf.io,cslzchen/osf.io,chennan47/osf.io,cslzchen/osf.io,crcresearch/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,crcresearch/osf.io,cwisecarver/osf.io,mattclark/osf.io,caseyrollins/osf.io,caneruguz/osf.io,aaxelb/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,adlius/osf.io,HalcyonChimera/osf.io,chennan47/osf.io,adlius/osf.io,caseyrollins/osf.io,leb2dg/osf.io,chrisseto/osf.io,laurenrevere/osf.io,caneruguz/osf.io,saradbowman/osf.io,caneruguz/osf.io,sloria/osf.io,erinspace/osf.io,TomBaxter/osf.io,TomBaxter/osf.io,chrisseto/osf.io,icereval/osf.io,caseyrollins/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,TomBaxter/osf.io,felliott/osf.io,laurenrevere/osf.io,adlius/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,sloria/osf.io,mattclark/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,leb2dg/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,cwisecarver/osf.io,brianjgeiger/osf.io,erinspace/osf.io,saradbowman/osf.io,felliott/osf.io,chrisseto/osf.io,sloria/osf.io,mfraezz/osf.io,leb2dg/osf.io,mfraezz/osf.io,pattisdr/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,aaxelb/osf.io,baylee-d/osf.io,pattisdr/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,binoculars/osf.io,icereval/osf.io,felliott/osf.io,Johnetordoff/osf.io,cwisecarver/osf.io,HalcyonChimera/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,erinspace/osf.io,leb2dg/osf.io,binoculars/osf.io,felliott/osf.io | framework/celery_tasks/signals.py | framework/celery_tasks/signals.py | # -*- coding: utf-8 -*-
"""Attach callbacks to signals emitted by Celery. This module should only be
imported by Celery and is not used elsewhere in the application.
"""
import logging
from celery import signals
from framework.mongo import StoredObject
from website import settings
logger = logging.getLogger(__name__)
@signals.task_prerun.connect
@signals.task_postrun.connect
def clear_caches(*args, **kwargs):
"""Clear database cache before and after each task.
"""
StoredObject._clear_caches()
@signals.worker_process_init.connect
def attach_models(*args, **kwargs):
"""Attach models to database collections on worker initialization.
"""
if settings.USE_POSTGRES:
return
logger.error('USE_POSTGRES must be set to True')
| # -*- coding: utf-8 -*-
"""Attach callbacks to signals emitted by Celery. This module should only be
imported by Celery and is not used elsewhere in the application.
"""
import logging
from celery import signals
from framework.mongo import storage, set_up_storage, StoredObject
from website import models, settings
logger = logging.getLogger(__name__)
@signals.task_prerun.connect
@signals.task_postrun.connect
def clear_caches(*args, **kwargs):
"""Clear database cache before and after each task.
"""
StoredObject._clear_caches()
@signals.worker_process_init.connect
def attach_models(*args, **kwargs):
"""Attach models to database collections on worker initialization.
"""
if settings.USE_POSTGRES:
logger.debug('Not setting storage backends because USE_POSTGRES = True')
return
set_up_storage(models.MODELS, storage.MongoStorage)
| apache-2.0 | Python |
b639e094f0ac9feb008c0d13deb26c55bbb50793 | Make jumping between changes loop back around | michaelhogg/GitGutter,biodamasceno/GitGutter,biodamasceno/GitGutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,biodamasceno/GitGutter,natecavanaugh/GitGutter,tushortz/GitGutter,michaelhogg/GitGutter,akpersad/GitGutter,akpersad/GitGutter,natecavanaugh/GitGutter,akpersad/GitGutter,tushortz/GitGutter,akpersad/GitGutter,michaelhogg/GitGutter,tushortz/GitGutter,jisaacks/GitGutter,biodamasceno/GitGutter,natecavanaugh/GitGutter,michaelhogg/GitGutter,tushortz/GitGutter,natecavanaugh/GitGutter | git_gutter_change.py | git_gutter_change.py | import sublime
import sublime_plugin
try:
from GitGutter.view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand):
def lines_to_blocks(self, lines):
blocks = []
last_line = -2
for line in lines:
if line > last_line+1:
blocks.append(line)
last_line = line
return blocks
def run(self):
view = self.window.active_view()
inserted, modified, deleted = ViewCollection.diff(view)
inserted = self.lines_to_blocks(inserted)
modified = self.lines_to_blocks(modified)
all_changes = sorted(inserted + modified + deleted)
row, col = view.rowcol(view.sel()[0].begin())
current_row = row + 1
line = self.jump(all_changes, current_row)
self.window.active_view().run_command("goto_line", {"line": line})
class GitGutterNextChangeCommand(GitGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in all_changes
if change > current_row), all_changes[0])
class GitGutterPrevChangeCommand(GitGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in reversed(all_changes)
if change < current_row), all_changes[-1]) | import sublime
import sublime_plugin
try:
from GitGutter.view_collection import ViewCollection
except ImportError:
from view_collection import ViewCollection
class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand):
def lines_to_blocks(self, lines):
blocks = []
last_line = -2
for line in lines:
if line > last_line+1:
blocks.append(line)
last_line = line
return blocks
def run(self):
view = self.window.active_view()
inserted, modified, deleted = ViewCollection.diff(view)
inserted = self.lines_to_blocks(inserted)
modified = self.lines_to_blocks(modified)
all_changes = sorted(inserted + modified + deleted)
row, col = view.rowcol(view.sel()[0].begin())
current_row = row + 1
line = self.jump(all_changes, current_row)
self.window.active_view().run_command("goto_line", {"line": line})
class GitGutterNextChangeCommand(GitGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in all_changes
if change > current_row), current_row)
class GitGutterPrevChangeCommand(GitGutterBaseChangeCommand):
def jump(self, all_changes, current_row):
return next((change for change in reversed(all_changes)
if change < current_row), current_row) | mit | Python |
71e1369eab7a389cb8d89e62eaa24724a249524e | FIX constrains sale.order.type | ingadhoc/sale,ingadhoc/sale,ingadhoc/sale,ingadhoc/sale | sale_order_type_automation/sale_order_type.py | sale_order_type_automation/sale_order_type.py | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api, _
from openerp.exceptions import Warning
class SaleOrderTypology(models.Model):
_inherit = 'sale.order.type'
validate_automatically_picking = fields.Boolean(
'Validate automatically picking',
help="It will force availability")
validate_automatically_invoice = fields.Boolean(
'Validate automatically invoice',)
payment_journal_id = fields.Many2one(
'account.journal',
'Payment Journal',
domain="[('type','in', ['cash', 'bank'])]"
)
validate_automatically_voucher = fields.Boolean(
'Validate automatically voucher')
@api.onchange('payment_journal_id')
def onchange_payment_journal_id(self):
if self.payment_journal_id:
self.validate_automatically_invoice = True
@api.onchange('order_policy')
def onchange_order_policy(self):
if self.order_policy != 'manual':
self.validate_automatically_invoice = False
self.validate_automatically_picking = False
self.validate_automatically_voucher = False
self.payment_journal_id = False
self.journal_id = False
@api.one
@api.constrains(
'journal_id',
'payment_journal_id',
'refund_journal_id',
'sequence_id')
def validate_company_id(self):
text = _(
'The Journal "%s" company must be the same than sale order type')
if self.journal_id and self.journal_id.company_id != self.company_id:
raise Warning(text % self.journal_id.name)
if self.payment_journal_id and self.payment_journal_id.company_id != self.company_id:
raise Warning(text % self.payment_journal_id.name)
if self.refund_journal_id and self.refund_journal_id.company_id != self.company_id:
raise Warning(text % self.refund_journal_id.name)
if self.sequence_id.company_id and self.sequence_id.company_id != self.company_id:
raise Warning(_(
'The Sequence "%s" company must be the same than'
' sale order type') % self.sequence_id.name)
| # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api, _
from openerp.exceptions import Warning
class SaleOrderTypology(models.Model):
_inherit = 'sale.order.type'
validate_automatically_picking = fields.Boolean(
'Validate automatically picking',
help="It will force availability")
validate_automatically_invoice = fields.Boolean(
'Validate automatically invoice',)
payment_journal_id = fields.Many2one(
'account.journal',
'Payment Journal',
domain="[('type','in', ['cash', 'bank'])]"
)
validate_automatically_voucher = fields.Boolean(
'Validate automatically voucher')
@api.onchange('payment_journal_id')
def onchange_payment_journal_id(self):
if self.payment_journal_id:
self.validate_automatically_invoice = True
@api.onchange('order_policy')
def onchange_order_policy(self):
if self.order_policy != 'manual':
self.validate_automatically_invoice = False
self.validate_automatically_picking = False
self.validate_automatically_voucher = False
self.payment_journal_id = False
self.journal_id = False
@api.model
@api.constrains(
'journal_id',
'payment_journal_id',
'refund_journal_id',
'sequence_id')
def validate_company_id(self):
text = _(
'The Journal "%s" company must be the same than sale order type')
if self.journal_id.company_id != self.company_id:
raise Warning(text % self.journal_id.name)
if self.payment_journal_id.company_id != self.company_id:
raise Warning(text % self.payment_journal_id.name)
if self.refund_journal_id.company_id != self.company_id:
raise Warning(text % self.refund_journal_id.name)
if self.sequence_id.company_id != self.company_id:
raise Warning(_(
'The Sequence "%s" company must be the same than'
' sale order type') % self.sequence_id.name)
| agpl-3.0 | Python |
926dc5a10fd9d54a6b183266f21834013ad05abb | Fix debugging issue in VSCode | nixxa/SecretShopper,nixxa/SecretShopper,nixxa/SecretShopper | frontui/app.py | frontui/app.py | """ Creat and init application """
import logging
from logging.handlers import TimedRotatingFileHandler
import os
from flask import Flask
from frontui import BASE_DIR
from frontui.views.public import public_ui
from frontui.views.member import member_ui
from frontui.views.customer import customer_ui
def create_app(app_mode='DEBUG'):
""" Create application, register blueprints, etc """
if app_mode == '':
app_mode = os.environ.get('APP_MODE', 'DEBUG')
# create an application
app = Flask(__name__)
app.config['SECRET_KEY'] = b'\x88~\x17h\xdc;,\x9f\x1do\x98\xcd\xaf|\x1c\x19\xec\xcf\xb1\x12\xd4\x8b\xcdQ'
# set logging
configure_logging(app_mode, app)
if app_mode == 'DEBUG':
# debugging in VSCode works only if following 2 lines are commented out
#app.debug = True
#app.config['DEBUG'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
# register blueprints
app.register_blueprint(public_ui)
app.register_blueprint(member_ui)
app.register_blueprint(customer_ui)
# register jinja exts
app.add_template_filter(f=points, name='points')
# configure uploads
app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'uploads')
# app started
logging.info('Application started in %s mode', app_mode)
return app
def configure_logging(app_mode, app):
logHandler = None
if app_mode == 'DEBUG':
# create console handler
logHandler = logging.StreamHandler()
elif app_mode == 'PROD':
# create file time rotating handler
logHandler = TimedRotatingFileHandler(
filename=os.environ.get('APP_LOG_FILENAME', 'app.log'),
when='D',
backupCount=5,
encoding='UTF-8'
)
if logHandler is None:
return
logHandler.setLevel(logging.DEBUG)
logHandler.setFormatter(logging.Formatter(
fmt='%(asctime)s %(name)-10s %(levelname)-7s %(message)s',
datefmt='%H:%M:%S'))
# get root logger
logger = logging.getLogger()
logger.addHandler(logHandler)
logger.setLevel(logging.DEBUG)
app.logger.addHandler(logHandler)
app.logger.setLevel(logging.DEBUG)
return
def points(answer, question):
return str(question.cost) if answer == 'yes' else '0' if answer == 'no' else ''
| """ Creat and init application """
import logging
from logging.handlers import TimedRotatingFileHandler
import os
from flask import Flask
from frontui import BASE_DIR
from frontui.views.public import public_ui
from frontui.views.member import member_ui
from frontui.views.customer import customer_ui
def create_app(app_mode='DEBUG'):
""" Create application, register blueprints, etc """
if app_mode == '':
app_mode = os.environ.get('APP_MODE', 'DEBUG')
# create an application
app = Flask(__name__)
app.config['SECRET_KEY'] = b'\x88~\x17h\xdc;,\x9f\x1do\x98\xcd\xaf|\x1c\x19\xec\xcf\xb1\x12\xd4\x8b\xcdQ'
# set logging
configure_logging(app_mode, app)
if app_mode == 'DEBUG':
app.debug = True
app.config['DEBUG'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
# register blueprints
app.register_blueprint(public_ui)
app.register_blueprint(member_ui)
app.register_blueprint(customer_ui)
# register jinja exts
app.add_template_filter(f=points, name='points')
# configure uploads
app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'uploads')
# app started
logging.info('Application started in %s mode', app_mode)
return app
def configure_logging(app_mode, app):
logHandler = None
if app_mode == 'DEBUG':
# create console handler
logHandler = logging.StreamHandler()
elif app_mode == 'PROD':
# create file time rotating handler
logHandler = TimedRotatingFileHandler(
filename=os.environ.get('APP_LOG_FILENAME', 'app.log'),
when='D',
backupCount=5,
encoding='UTF-8'
)
if logHandler is None:
return
logHandler.setLevel(logging.DEBUG)
logHandler.setFormatter(logging.Formatter(
fmt='%(asctime)s %(name)-10s %(levelname)-7s %(message)s',
datefmt='%H:%M:%S'))
# get root logger
logger = logging.getLogger()
logger.addHandler(logHandler)
logger.setLevel(logging.DEBUG)
app.logger.addHandler(logHandler)
app.logger.setLevel(logging.DEBUG)
return
def points(answer, question):
return str(question.cost) if answer == 'yes' else '0' if answer == 'no' else ''
| mit | Python |
2ad6cdefabec041ace5afcdcffce7f6e6c2352fa | Add priors import to __init__.py | jrg365/gpytorch,jrg365/gpytorch,jrg365/gpytorch | gpytorch/__init__.py | gpytorch/__init__.py | from . import models
from . import means
from . import mlls
from . import kernels
from . import priors
from .module import Module
from .mlls import ExactMarginalLogLikelihood, VariationalMarginalLogLikelihood
from .functions import add_diag, add_jitter, dsmm, log_normal_cdf, normal_cdf
from .functions import inv_matmul, inv_quad, inv_quad_log_det, log_det, matmul
from .functions import root_decomposition, root_inv_decomposition
from .functions import exact_predictive_mean, exact_predictive_covar
from . import beta_features
from . import settings
from .beta_features import fast_pred_var
__all__ = [
# Submodules
models,
mlls,
means,
kernels,
priors,
# Classes
Module,
ExactMarginalLogLikelihood,
VariationalMarginalLogLikelihood,
# Functions
add_diag,
add_jitter,
dsmm,
exact_predictive_mean,
exact_predictive_covar,
inv_matmul,
inv_quad,
inv_quad_log_det,
matmul,
log_det,
log_normal_cdf,
normal_cdf,
root_decomposition,
root_inv_decomposition,
# Context managers
beta_features,
fast_pred_var,
settings,
]
| from . import models
from . import means
from . import mlls
from . import kernels
from .module import Module
from .mlls import ExactMarginalLogLikelihood, VariationalMarginalLogLikelihood
from .functions import add_diag, add_jitter, dsmm, log_normal_cdf, normal_cdf
from .functions import inv_matmul, inv_quad, inv_quad_log_det, log_det, matmul
from .functions import root_decomposition, root_inv_decomposition
from .functions import exact_predictive_mean, exact_predictive_covar
from . import beta_features
from . import settings
from .beta_features import fast_pred_var
__all__ = [
# Submodules
models,
mlls,
means,
kernels,
# Classes
Module,
ExactMarginalLogLikelihood,
VariationalMarginalLogLikelihood,
# Functions
add_diag,
add_jitter,
dsmm,
exact_predictive_mean,
exact_predictive_covar,
inv_matmul,
inv_quad,
inv_quad_log_det,
matmul,
log_det,
log_normal_cdf,
normal_cdf,
root_decomposition,
root_inv_decomposition,
# Context managers
beta_features,
fast_pred_var,
settings,
]
| mit | Python |
66920331012c49b84f2d4d4f8d0ffbf058adc073 | tweak internet explorer so to avoid popups | cuckoobox/cuckoo,cuckoobox/cuckoo,cuckoobox/cuckoo,cuckoobox/cuckoo,cuckoobox/cuckoo | analyzer/windows/modules/packages/ie.py | analyzer/windows/modules/packages/ie.py | # Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from _winreg import OpenKey, SetValueEx, CloseKey
from _winreg import HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER
from _winreg import KEY_SET_VALUE, REG_DWORD, REG_SZ
from lib.common.abstracts import Package
from lib.common.exceptions import CuckooPackageError
class IE(Package):
"""Internet Explorer analysis package."""
PATHS = [
("ProgramFiles", "Internet Explorer", "iexplore.exe"),
]
REGKEYS = [
{
"key": HKEY_CURRENT_USER,
"subkey": "Software\\Microsoft\\Internet Explorer\\Main",
"values": {
# "Would you like Internet Explorer as default browser?"
"Check_Associations": "no",
},
},
{
"key": HKEY_CURRENT_USER,
"subkey": "Software\\Microsoft\\Internet Explorer\\Security",
"values": {
"Safety Warning Level": "Low",
"Sending_Security": "Low",
"Viewing_Security": "Low",
},
},
{
"key": HKEY_LOCAL_MACHINE,
"subkey": "Software\\Microsoft\\Internet Explorer\\Main",
"values": {
# Disable Security Settings Check.
"DisableSecuritySettingsCheck": 1,
},
},
{
"key": HKEY_CURRENT_USER,
"subkey": "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
"values": {
# "You are about to be redirected to a connection that is not secure."
"WarnOnHTTPSToHTTPRedirect": 0,
# "You are about to view pages over a secure connection."
"WarnOnZoneCrossing": 0,
},
},
]
def init_iexplore(self):
"""Sets various Internet Explorer related registry settings in case
the user has not taken care of it already."""
for row in self.REGKEYS:
key_handle = OpenKey(row["key"], row["subkey"], 0, KEY_SET_VALUE)
for key, value in row["values"].items():
if isinstance(value, str):
SetValueEx(key_handle, key, 0, REG_SZ, value)
elif isinstance(value, int):
SetValueEx(key_handle, key, 0, REG_DWORD, value)
else:
raise CuckooPackageError("Invalid value type: %r" % value)
CloseKey(key_handle)
def start(self, url):
self.init_iexplore()
iexplore = self.get_path("Internet Explorer")
return self.execute(iexplore, args=[url])
| # Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.common.abstracts import Package
class IE(Package):
"""Internet Explorer analysis package."""
PATHS = [
("ProgramFiles", "Internet Explorer", "iexplore.exe"),
]
def start(self, url):
iexplore = self.get_path("Internet Explorer")
return self.execute(iexplore, args=[url])
| mit | Python |
a6fa6fd8595510748d4d4fb06a1383dcea3288c2 | fix deoplete mark | lvht/phpcd.vim,przepompownia/phpcd.vim,lvht/phpcd.vim,przepompownia/phpcd.vim,przepompownia/phpcd.vim,lvht/phpcd.vim | rplugin/python3/deoplete/sources/phpcd.py | rplugin/python3/deoplete/sources/phpcd.py | from .base import Base
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'phpcd'
self.mark = '[phpcd]'
self.filetypes = ['php']
self.is_bytepos = True
self.input_pattern = '\w+|[^. \t]->\w*|\w+::\w*'
self.rank = 500
self.max_pattern_length = -1
self.matchers = ['matcher_full_fuzzy']
def get_complete_position(self, context):
return self.vim.call('phpcd#CompletePHP', 1, '')
def gather_candidates(self, context):
return self.vim.call('phpcd#CompletePHP', 0, context['complete_str'])
| from .base import Base
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'phpcd'
self.mark = '[php]'
self.filetypes = ['php']
self.is_bytepos = True
self.input_pattern = '\w+|[^. \t]->\w*|\w+::\w*'
self.rank = 500
self.max_pattern_length = -1
self.matchers = ['matcher_full_fuzzy']
def get_complete_position(self, context):
return self.vim.call('phpcd#CompletePHP', 1, '')
def gather_candidates(self, context):
return self.vim.call('phpcd#CompletePHP', 0, context['complete_str'])
| apache-2.0 | Python |
ba943a9c46f20b6f1b061ca1fff62df36a5d9562 | fix deoplete error | lvht/phpcd.vim,lvht/phpcd.vim,lvht/phpcd.vim | rplugin/python3/deoplete/sources/phpcd.py | rplugin/python3/deoplete/sources/phpcd.py | from .base import Base
from neovim.api.nvim import NvimError
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'phpcd'
self.mark = '[phpcd]'
self.filetypes = ['php']
self.is_bytepos = True
self.input_pattern = '\w+|[^. \t]->\w*|\w+::\w*'
self.rank = 500
self.max_pattern_length = -1
self.matchers = ['matcher_full_fuzzy']
def get_complete_position(self, context):
return self.vim.call('phpcd#CompletePHP', 1, '')
def gather_candidates(self, context):
try:
return self.vim.call('phpcd#CompletePHP', 0, context['complete_str'])
except NvimError:
return []
| from .base import Base
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'phpcd'
self.mark = '[phpcd]'
self.filetypes = ['php']
self.is_bytepos = True
self.input_pattern = '\w+|[^. \t]->\w*|\w+::\w*'
self.rank = 500
self.max_pattern_length = -1
self.matchers = ['matcher_full_fuzzy']
def get_complete_position(self, context):
return self.vim.call('phpcd#CompletePHP', 1, '')
def gather_candidates(self, context):
return self.vim.call('phpcd#CompletePHP', 0, context['complete_str'])
| apache-2.0 | Python |
21dd97cec5003f1e53f02b079da3130a606feb3a | Fix marker script support for '-c' flag (#18418) | DonJayamanne/pythonVSCode,DonJayamanne/pythonVSCode,DonJayamanne/pythonVSCode,DonJayamanne/pythonVSCode,DonJayamanne/pythonVSCode | pythonFiles/get_output_via_markers.py | pythonFiles/get_output_via_markers.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import runpy
import sys
# Sometimes executing scripts can print out stuff before the actual output is
# printed. For eg. when activating conda. Hence, printing out markers to make
# it more resilient to pull the output.
print(">>>PYTHON-EXEC-OUTPUT")
module = sys.argv[1]
try:
if module == "-c":
ns = {}
code = sys.argv[2]
del sys.argv[2]
del sys.argv[0]
exec(code, ns, ns)
elif module.startswith("-m"):
moduleName = sys.argv[2]
sys.argv = sys.argv[2:] # It should begin with the module name.
runpy.run_module(moduleName, run_name="__main__", alter_sys=True)
elif module.endswith(".py"):
sys.argv = sys.argv[1:]
runpy.run_path(module, run_name="__main__")
elif module.startswith("-"):
raise NotImplementedError(sys.argv)
else:
runpy.run_module(module, run_name="__main__", alter_sys=True)
finally:
print("<<<PYTHON-EXEC-OUTPUT")
| # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import runpy
import sys
# Sometimes executing scripts can print out stuff before the actual output is
# printed. For eg. when activating conda. Hence, printing out markers to make
# it more resilient to pull the output.
print(">>>PYTHON-EXEC-OUTPUT")
module = sys.argv[1]
try:
if module == "-c":
ns = {}
for code in sys.argv[2:]:
exec(code, ns, ns)
elif module.startswith("-m"):
moduleName = sys.argv[2]
sys.argv = sys.argv[2:] # It should begin with the module name.
runpy.run_module(moduleName, run_name="__main__", alter_sys=True)
elif module.endswith(".py"):
sys.argv = sys.argv[1:]
runpy.run_path(module, run_name="__main__")
elif module.startswith("-"):
raise NotImplementedError(sys.argv)
else:
runpy.run_module(module, run_name="__main__", alter_sys=True)
finally:
print("<<<PYTHON-EXEC-OUTPUT")
| mit | Python |
572c2f4a0a3a0ffedaa45184848e2d5a37fd2078 | Update helpers.py with new problems | samanehsan/spark_github,samanehsan/spark_github,samanehsan/learn-git,samanehsan/learn-git | helpers.py | helpers.py | """ A bunch of helper functions that, when fixed up, will return the things we
need to make this website work!
"""
## Import python libraries we need up here.
import requests
import random
###############################################
### Problem One! ###
###############################################
def get_city_coordinates():
"""Find the GPS coordinates for Charlottesville,
and fill in the information below
"""
lattitude = 38.0293
longitude = -78.4767
return lattitude, longitude
###############################################
### Problem Two! ###
###############################################
def get_icon_size():
""" Modify this function to return a number of instagram photos
you want to appear on the site at a time! Because of how the instagram API works,
it won't return more than 20 photos at once.
"""
size = 100
return size
###############################################
### Problem Three! ###
###############################################
def choose_number_of_tweets():
""" Modify this function to return a number of tweets
you want to appear on the site at a time!
"""
number = 10
return number
###############################################
### Problem Four! ###
###############################################
def get_api_content(api_url):
""" Modify this function to use a commmon python library to go to an api_url (get it!) and give you
back what it finds. Request the site, and get its contents. Hint Hint.
"""
return requests.get(api_url)
| """ A bunch of helper functions that, when fixed up, will return the things we
need to make this website work!
"""
## Import python libraries we need up here.
import requests
import random
###############################################
### Problem One! ###
###############################################
def choose_random_unique_items(my_list, number_of_images):
""" Given a list of items, return a *random* element of that list.
Only return the item if we haven't seen it before! Get a sample. A random sample.
"""
if number_of_images <= len(my_list):
# This is the case if our hashtag has enough images to meet our number request
# figure out the one line that we can return that will give us a random member of the
# list, with no repeats.
return random.sample(my_list, 1)
else:
## If we ask for more images that we have, then just return everything there is
return my_list
###############################################
### Problem Two! ###
###############################################
def choose_number_of_images():
""" Modify this function to return a number of instagram photos
you want to appear on the site at a time! Because of how the instagram API works,
it won't return more than 20 photos at once.
"""
number = 20
return number
###############################################
### Problem Three! ###
###############################################
def choose_number_of_tweets():
""" Modify this function to return a number of tweets
you want to appear on the site at a time!
"""
number = 5
return number
###############################################
### Problem Four! ###
###############################################
def get_api_content(api_url):
""" Modify this function to use a commmon python library to go to an api_url (get it!) and give you
back what it finds. Request the site, and get its contents. Hint Hint.
"""
return requests.get(api_url)
| apache-2.0 | Python |
4286953271952bfcfce0b122d1338b75e1daed70 | Remove unused parameter (#3306) | kubeflow/pipelines,kubeflow/pipelines,kubeflow/pipelines,kubeflow/pipelines,kubeflow/pipelines,kubeflow/pipelines | samples/core/exit_handler/exit_handler.py | samples/core/exit_handler/exit_handler.py | #!/usr/bin/env python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import kfp
from kfp import dsl
def gcs_download_op(url):
return dsl.ContainerOp(
name='GCS - Download',
image='google/cloud-sdk:279.0.0',
command=['sh', '-c'],
arguments=['gsutil cat $0 | tee $1', url, '/tmp/results.txt'],
file_outputs={
'data': '/tmp/results.txt',
}
)
def echo_op(text):
return dsl.ContainerOp(
name='echo',
image='library/bash:4.4.23',
command=['sh', '-c'],
arguments=['echo "$0"', text],
)
@dsl.pipeline(
name='Exit Handler',
description='Downloads a message and prints it. The exit handler will run after the pipeline finishes (successfully or not).'
)
def download_and_print(url='gs://ml-pipeline-playground/shakespeare1.txt'):
"""A sample pipeline showing exit handler."""
exit_task = echo_op('exit!')
with dsl.ExitHandler(exit_task):
download_task = gcs_download_op(url)
echo_task = echo_op(download_task.output)
if __name__ == '__main__':
kfp.compiler.Compiler().compile(download_and_print, __file__ + '.yaml')
| #!/usr/bin/env python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import kfp
from kfp import dsl
def gcs_download_op(url):
return dsl.ContainerOp(
name='GCS - Download',
image='google/cloud-sdk:279.0.0',
command=['sh', '-c'],
arguments=['gsutil cat $0 | tee $1', url, '/tmp/results.txt'],
file_outputs={
'data': '/tmp/results.txt',
}
)
def echo_op(text, is_exit_handler=False):
return dsl.ContainerOp(
name='echo',
image='library/bash:4.4.23',
command=['sh', '-c'],
arguments=['echo "$0"', text],
)
@dsl.pipeline(
name='Exit Handler',
description='Downloads a message and prints it. The exit handler will run after the pipeline finishes (successfully or not).'
)
def download_and_print(url='gs://ml-pipeline-playground/shakespeare1.txt'):
"""A sample pipeline showing exit handler."""
exit_task = echo_op('exit!')
with dsl.ExitHandler(exit_task):
download_task = gcs_download_op(url)
echo_task = echo_op(download_task.output)
if __name__ == '__main__':
kfp.compiler.Compiler().compile(download_and_print, __file__ + '.yaml')
| apache-2.0 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.