commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
8b84b2ae83977e091ee33ce86e30bcc7cc5c08a2
Allow apostrophe and forbid colon in thread names
chandl/util.py
chandl/util.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import sys import hashlib import unidecode import six import requests import chandl def bytes_fmt(num, suffix='B'): """ Turn a number of bytes into a more friendly representation, e.g. 2.5MiB. :param num: The number of bytes to convert. :param suffix: The unit suffix (defaults to 'B'). :return: The human-readable equivalent of the input size. :raises ValueError: If num is not an integer. """ if not isinstance(num, six.integer_types): raise ValueError('Byte count must be an integral type') num = abs(num) for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if num < 1024.0: return '{0:.1f} {1}{2}'.format(num, unit, suffix) num /= 1024.0 return '{0:.1f} {1}{2}'.format(num, 'Yi', suffix) def decode_cli_arg(arg): """ Turn a bytestring provided by `argparse` into unicode. :param arg: The bytestring to decode. :return: The argument as a unicode object. :raises ValueError: If arg is None. """ if arg is None: raise ValueError('Argument cannot be None') if sys.version_info.major == 3: # already decoded return arg return arg.decode(sys.getfilesystemencoding()) def expand_cli_args(args): """ Expand a list of possibly comma separated arguments, removing duplicates. :param args: The list of arguments to expand. :return: The set of unique arguments. """ items = set() for arg in args: # "a.jpg,b.png" for arg_ in [n.strip() for n in arg.split(',')]: # "a.jpg"|"b.jpg" items.add(arg_) return items def make_filename(string): """ Turn a string into something that can be safely used as a file or directory name. :param string: The string to convert. :return: The sanitised string. :raises ValueError: If string is None. """ if string is None: raise ValueError('String cannot be None') safe = [' ', '.', '_', ':'] joined = ''.join([c for c in unidecode.unidecode(string) if c.isalnum() or c in safe]).strip() if not joined: raise ValueError('Filename would be empty') return joined def md5_file(path): """ Get the MD5 hash of a file. :param path: The path of the file. :return: The 32-character long lowercase hex representation of the checksum. :raises ValueError: If path is invalid. """ if not path: raise ValueError('Path cannot be empty or None') hash_ = hashlib.md5() with open(path, 'rb') as fd: for chunk in iter(lambda: fd.read(4096), b''): hash_.update(chunk) return hash_.hexdigest() def log_level_from_vebosity(verbosity): """ Get the `logging` module log level from a verbosity. :param verbosity: The number of times the `-v` option was specified. :return: The corresponding log level. """ if verbosity == 0: return logging.WARNING if verbosity == 1: return logging.INFO return logging.DEBUG def create_session(): """ Create a requests session for issuing HTTP requests to 4chan. :return: The created session. """ headers = requests.utils.default_headers() headers.update({ 'User-Agent': 'chandl/' + chandl.__version__ }) session = requests.Session() session.headers = headers return session
Python
0.000006
@@ -2047,17 +2047,18 @@ , '_', ' -: +%5C' '%5D%0A j
a82d419d17c67cfd7842cf104994b9ecbda96e94
Delete existing libnccl before installing NCCL
perfkitbenchmarker/linux_packages/nccl.py
perfkitbenchmarker/linux_packages/nccl.py
# Copyright 2018 PerfKitBenchmarker 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. """Module containing NCCL installation function.""" import posixpath from perfkitbenchmarker import flags from perfkitbenchmarker import vm_util flags.DEFINE_string('nccl_version', '2.5.6-2', 'NCCL version to install') FLAGS = flags.FLAGS GIT_REPO = 'https://github.com/NVIDIA/nccl.git' def _Build(vm): """Installs the OpenMPI package on the VM.""" vm.RemoteCommand('[ -d "nccl" ] || git clone {git_repo} --branch v{version}' .format(git_repo=GIT_REPO, version=FLAGS.nccl_version)) cuda_home = '/usr/local/cuda' vm.InstallPackages('build-essential devscripts debhelper fakeroot') env_vars = {} env_vars['PATH'] = (r'{cuda_bin_path}:$PATH' .format(cuda_bin_path=posixpath.join(cuda_home, 'bin'))) env_vars['CUDA_HOME'] = (r'{cuda_home}'.format(cuda_home=cuda_home)) env_vars['LD_LIBRARY_PATH'] = (r'{lib_path}:$LD_LIBRARY_PATH' .format(lib_path=posixpath.join( cuda_home, 'lib64'))) vm.RemoteCommand('cd nccl && {env} make -j 20 pkg.debian.build' .format(env=vm_util.DictonaryToEnvString(env_vars))) def AptInstall(vm): """Installs the NCCL package on the VM.""" _Build(vm) vm.InstallPackages('{build}libnccl2_{nccl}+cuda{cuda}_amd64.deb ' '{build}libnccl-dev_{nccl}+cuda{cuda}_amd64.deb' .format( build='./nccl/build/pkg/deb/', nccl=FLAGS.nccl_version, cuda=FLAGS.cuda_toolkit_version))
Python
0.000001
@@ -1859,16 +1859,94 @@ ild(vm)%0A + vm.RemoteCommand('sudo rm -rf /usr/local/nccl2') # Preexisting NCCL in DLVM %0A vm.In
13ae8cf8eddba1cf40d89307ba1c52480cbac472
Bump version
async2rewrite/__init__.py
async2rewrite/__init__.py
""" Convert discord.py code using abstract syntax trees. """ __title__ = 'async2rewrite' __author__ = 'Tyler Gibbs' __version__ = '0.0.2' __copyright__ = 'Copyright 2017 TheTrain2000' __license__ = 'MIT' from .main import *
Python
0
@@ -131,17 +131,17 @@ = '0.0. -2 +3 '%0A__copy
0639158e539f0f1c1a6d4dac1753179429257017
add django_pluralize template filter
source/base/helpers.py
source/base/helpers.py
import datetime import logging import os from django.conf import settings from django.template.defaultfilters import linebreaks as django_linebreaks,\ escapejs as django_escapejs from jingo import register from sorl.thumbnail import get_thumbnail logger = logging.getLogger('base.helpers') @register.filter def linebreaks(string): return django_linebreaks(string) @register.filter def escapejs(string): return django_escapejs(string) @register.function def get_timestamp(): return datetime.datetime.now() @register.function def thumbnail(source, *args, **kwargs): """ Wraps sorl thumbnail with an additional 'default' keyword https://github.com/mozilla/mozillians/blob/master/apps/common/helpers.py """ # Templates should never return an exception try: if not source.path: source = kwargs.get('default') # Handle PNG images a little more gracefully # Make sure thumbnail call doesn't specifically set format if not 'format' in kwargs: filetype = source.path.split('.')[-1] # If we have a PNG, don't default convert to JPG if filetype.lower() == 'png': kwargs['format'] = 'PNG' return get_thumbnail(source, *args, **kwargs) except Exception as e: logger.error('Thumbnail had Exception: %s' % (e,)) source = getattr(settings, 'DEFAULT_IMAGE_SRC') return get_thumbnail(source, *args, **kwargs)
Python
0.000001
@@ -176,16 +176,47 @@ escapejs +, pluralize as django_pluralize %0A%0Afrom j @@ -550,16 +550,114 @@ me.now() +%0A %0A@register.filter%0Adef dj_pluralize(string, arg='s'):%0A return django_pluralize(string, arg) %0A%0A@regis @@ -1583,28 +1583,29 @@ il(source, *args, **kwargs)%0A +%0A
982f2c8777c43cff2d69cc6adac02a6d5397c043
Update warning message for PMID search
indra/literature/pubmed_client.py
indra/literature/pubmed_client.py
import urllib, urllib2 from functools32 import lru_cache import xml.etree.ElementTree as ET from indra.databases import hgnc_client pubmed_search = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi' pubmed_fetch = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi' pmid_convert = 'http://www.ncbi.nlm.nih.gov/pmc/utils/idconv/v1.0/' @lru_cache(maxsize=100) def send_request(url, data): try: req = urllib2.Request(url, data) res = urllib2.urlopen(req) xml_str = res.read() tree = ET.fromstring(xml_str) except: return None return tree def get_ids(search_term, **kwargs): """Search Pubmed for paper IDs given a search term. The options are passed as named arguments. For details on parameters that can be used, see http://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch Some useful parameters to pass are db='pmc' to search PMC instead of pubmed reldate=2 to search for papers within the last 2 days mindate='2016/03/01', maxdate='2016/03/31' to search for papers in March 2016. """ params = {'term': search_term, 'retmax': 1000, 'retstart': 0, 'db': 'pubmed', 'sort': 'pub+date'} for k, v in kwargs.iteritems(): params[k] = v tree = send_request(pubmed_search, urllib.urlencode(params)) if tree is None: return [] if tree.find('ERROR') is not None: print tree.find('ERROR').text return [] count = int(tree.find('Count').text) id_terms = tree.findall('IdList/Id') if id_terms is None: return [] ids = [idt.text for idt in id_terms] if count != len(ids): print 'Not all ids were retrieved, limited at %d.' % params['retmax'] return ids def get_ids_for_gene(hgnc_name, **kwargs): """Get the curated set of articles for a gene in the Entrez database.""" # Get the HGNC ID for the HGNC name hgnc_id = hgnc_client.get_hgnc_id(hgnc_name) if hgnc_id is None: raise ValueError('Invalid HGNC name.') # Get the Entrez ID entrez_id = hgnc_client.get_entrez_id(hgnc_id) if entrez_id is None: raise ValueError('Entrez ID not found in HGNC table.') # Query the Entrez Gene database params = {'db': 'gene', 'retmode': 'xml', 'id': entrez_id, } for k, v in kwargs.iteritems(): params[k] = v tree = send_request(pubmed_fetch, urllib.urlencode(params)) if tree is None: return [] if tree.find('ERROR') is not None: print tree.find('ERROR').text return [] # Get all PMIDs from the XML tree id_terms = tree.findall('.//PubMedId') if id_terms is None: return [] # Use a set to remove duplicate IDs ids = list(set([idt.text for idt in id_terms])) return ids def get_article_xml(pubmed_id): if pubmed_id.upper().startswith('PMID'): pubmed_id = pubmed_id[4:] params = {'db': 'pubmed', 'retmode': 'xml', 'id': pubmed_id} tree = send_request(pubmed_fetch, urllib.urlencode(params)) if tree is None: return None article = tree.find('PubmedArticle/MedlineCitation/Article') return article # May be none def get_title(pubmed_id): article = get_article_xml(pubmed_id) if article is None: return None title = article.find('ArticleTitle').text return title def get_abstract(pubmed_id): article = get_article_xml(pubmed_id) if article is None: return None abstract = article.findall('Abstract/AbstractText') if abstract is None: return None else: abstract_text = ' '.join([' ' if abst.text is None else abst.text for abst in abstract]) return abstract_text
Python
0
@@ -1706,17 +1706,17 @@ print - +( 'Not all @@ -1734,18 +1734,50 @@ etrieved -, +for search %25s;%5Cn'%0A ' limited @@ -1785,16 +1785,30 @@ t %25d.' %25 + (search_term, params%5B @@ -1816,16 +1816,18 @@ retmax'%5D +)) %0A ret
62694c2072e3499b843372166daeead8a6335a5e
Format with Black
comics/accounts/views.py
comics/accounts/views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from invitations.utils import get_invitation_model from comics.accounts.models import Subscription from comics.core.models import Comic @login_required def account_details(request): return render( request, "accounts/details.html", {"active": {"account": True, "account_details": True}}, ) @login_required def secret_key(request): """Show and generate a new secret key for the current user""" if request.method == "POST": comics_profile = request.user.comics_profile comics_profile.generate_new_secret_key() comics_profile.save() messages.info(request, "A new secret key was generated.") return HttpResponseRedirect(reverse("secret_key")) return render( request, "accounts/secret_key.html", {"active": {"account": True, "secret_key": True}}, ) @login_required def mycomics_toggle_comic(request): """Change a single comic in My comics""" if request.method != "POST": response = HttpResponse(status=405) response["Allowed"] = "POST" return response comic = get_object_or_404(Comic, slug=request.POST["comic"]) if "add_comic" in request.POST: subscription = Subscription( userprofile=request.user.comics_profile, comic=comic ) subscription.save() if not request.is_ajax(): messages.info(request, 'Added "%s" to my comics' % comic.name) elif "remove_comic" in request.POST: subscriptions = Subscription.objects.filter( userprofile=request.user.comics_profile, comic=comic ) subscriptions.delete() if not request.is_ajax(): messages.info(request, 'Removed "%s" from my comics' % comic.name) if request.is_ajax(): return HttpResponse(status=204) else: return HttpResponseRedirect(reverse("mycomics_latest")) @login_required def mycomics_edit_comics(request): """Change multiple comics in My comics""" if request.method != "POST": response = HttpResponse(status=405) response["Allowed"] = "POST" return response my_comics = request.user.comics_profile.comics.all() for comic in my_comics: if comic.slug not in request.POST: subscriptions = Subscription.objects.filter( userprofile=request.user.comics_profile, comic=comic ) subscriptions.delete() if not request.is_ajax(): messages.info( request, 'Removed "%s" from my comics' % comic.name ) for comic in Comic.objects.all(): if comic.slug in request.POST and comic not in my_comics: subscription = Subscription( userprofile=request.user.comics_profile, comic=comic ) subscription.save() if not request.is_ajax(): messages.info(request, 'Added "%s" to my comics' % comic.name) if request.is_ajax(): return HttpResponse(status=204) elif "HTTP_REFERER" in request.META: return HttpResponseRedirect(request.META["HTTP_REFERER"]) else: return HttpResponseRedirect(reverse("mycomics_latest")) @login_required def invite(request): if request.method == "POST": invitation_model = get_invitation_model() invitation = invitation_model.create( request.POST["email"], inviter=request.user ) invitation.send_invitation(request) messages.success( 'An invitation has been sent to "%s".' % invitation.email ) invitations = request.user.invitation_set.all().order_by('-created') return render( request, "accounts/invite.html", { "active": {"invite": True}, "invitations": invitations, }, )
Python
0
@@ -3917,17 +3917,17 @@ _by( -' +%22 -created ')%0A%0A @@ -3922,17 +3922,17 @@ -created -' +%22 )%0A%0A r
d305e953d028b935333b86b4cffc58649b8a4652
Twitter uses OAuth1 not OAuth2, dummy
hiptweet/tasks.py
hiptweet/tasks.py
import logging import requests from flask import Blueprint, jsonify from requests_oauthlib import OAuth2Session from hiptweet import celery from hiptweet.models import HipChatGroup, HipChatRoom from celery.utils.log import get_task_logger # set up logging logger = get_task_logger(__name__) logger.setLevel(logging.INFO) # create a Flask blueprint for getting task status info tasks = Blueprint('tasks', __name__) @tasks.route('/status/<task_id>') def status(task_id): result = celery.AsyncResult(task_id) return jsonify({ "state": result.state, "info": result.info, }) def paginated_get(url, session=None, callback=None, **kwargs): """ Return a generator of results for this API call, based on the structure of HipChat's API return values. """ session = session or requests.Session() payload = { "start-index": 0, "max-results": 1000, } payload.update(kwargs) while url: resp = session.get(url, params=payload) if callable(callback): callback(resp) resp.raise_for_status() result = resp.json() for item in result["items"]: yield item url = result.get("links", {}).get("next", "") @celery.task(bind=True) def fetch_room_names(self, group_id): group = HipChatGroup.query.get(group_id) capabilities_url = group.install_info[0].capabilities_url capabilities_resp = requests.get(capabilities_url) capabilities_resp.raise_for_status() base_api_url = ( capabilities_resp.json()["capabilities"]["hipchatApiProvider"]["url"] ) rooms_info_url = base_api_url + "room" session = OAuth2Session(token=group.twitter_oauth.token) def update_state(resp): if not resp.ok: return start_index = resp.json()["startIndex"] self.update_state(state="STARTED", meta={"startIndex": start_index}) rooms_info = paginated_get(rooms_info_url, session=session, callback=update_state) for room_info in rooms_info: room_id = room_info['id'] room = HipChatRoom.query.get(room_id) if not room: room = HipChatRoom(id=room_id, group=group) room.name = room_info["name"] db.session.add(room) db.session.commit()
Python
0.99914
@@ -92,25 +92,25 @@ import OAuth -2 +1 Session%0Afrom @@ -1344,32 +1344,28 @@ id)%0A -capabilities_url +install_info = group @@ -1384,25 +1384,8 @@ o%5B0%5D -.capabilities_url %0A @@ -1418,16 +1418,29 @@ sts.get( +install_info. capabili @@ -1638,16 +1638,62 @@ %22room%22%0A + twitter_token = group.twitter_oauth.token%0A sess @@ -1707,17 +1707,17 @@ Auth -2 +1 Session( toke @@ -1716,28 +1716,195 @@ ion( -token=group. +%0A client_key=install_info.oauth_id,%0A client_secret=install_info.oauth_secret,%0A resource_owner_key=twitter_token%5B'oauth_token'%5D,%0A resource_owner_secret= twitter_ oaut @@ -1899,27 +1899,49 @@ twitter_ +token%5B' oauth -. +_ token +_secret'%5D,%0A )%0A%0A d
7b42e7e84adb091f100ed13a52e1c1f9a65dbd5b
set ordering by block number in database
sunfinder/sunfinder.py
sunfinder/sunfinder.py
#!/usr/bin/env python """sunfinder.py: Queries the Chainz SolarCoin Explorer API, pulls solar production data and loads to database""" __author__ = "Steven Campbell AKA Scalextrix" __copyright__ = "Copyright 2017, Steven Campbell" __license__ = "The Unlicense" __version__ = "1.0" import json import os.path import sqlite3 import sys import time import requests def apikeystore(): if os.path.isfile('APIkey.conf'): print 'Found stored API key in APIkey.conf' f = open('APIkey.conf', 'r') api_key = f.readline() f.close return api_key else: api_key = raw_input('What is your Chainz API Key?: ') f = open('APIkey.conf', 'wb') f.write(api_key) f.close() return api_key def databasecreate(): conn = sqlite3.connect('solardetails.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS SOLARDETAILS (id INTEGER PRIMARY KEY AUTOINCREMENT, txhash TEXT UNIQUE, block TEXT, time TEXT, dataloggerid BLOB, panelid TEXT, inverterid TEXT, pkwatt TEXT, lat TEXT, lon TEXT, msg TEXT, pi TEXT, period TEXT, totalmwh TEXT)''') conn.commit() conn.close() def databaseupdate(): conn = sqlite3.connect('solardetails.db') c = conn.cursor() c.execute("INSERT OR IGNORE INTO SOLARDETAILS VALUES (NULL,?,?,?,?,?,?,?,?,?,?,?,?,?);", (tx_hash, block, block_time, datalogger_id, solar_panel, solar_inverter, peak_watt, latitude, longitude, message, rpi, period, total_mwh,)) conn.commit() conn.close() last_block = "" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0'} api_key = apikeystore() while True: try: print "Attempting Chainz API call and JSON data load" last_block = str(last_block) url = ("https://chainz.cryptoid.info/slr/api.dws?q=txbymessage&key="+api_key+"&m=UserID&before="+last_block) json_data = str((requests.get(url, headers=headers)).content.decode()) json_decoded = json.loads(json_data) before_block = json_decoded['before'] more_blocks = json_decoded['more'] for a in json_decoded: hashes = [a['hash'] for a in json_decoded['txs']] blocks = [a['height'] for a in json_decoded['txs']] block_t = [a['time'] for a in json_decoded['txs']] messages = [a['message'] for a in json_decoded['txs']] first_block = blocks[0] counter_max = len(blocks) if last_block <= 1900000: print 'Minimum safe blockheight of 1900000 reached: Exiting in 10 seconds' time.sleep(10) sys.exit() else: databasecreate() conn = sqlite3.connect('solardetails.db') c = conn.cursor() row_count_start = c.execute('select count(*) FROM SOLARDETAILS').fetchone()[0] dbase_blocks = c.execute('select block FROM SOLARDETAILS').fetchall() conn.close() dbase_blocks = [int(a[0]) for a in dbase_blocks] if first_block in dbase_blocks: print 'First block returned from API already in database, nothing new: Please try again later, stopping in 10 seconds' time.sleep(10) sys.exit() else: counter = 0 while True: try: tx_hash = hashes [counter] block = blocks [counter] block_time = block_t [counter] first_message = str(messages [counter]) first_message = first_message[first_message.find('{'):first_message.find('}')+1] first_message_decoded = json.loads(first_message) datalogger_id = first_message_decoded['UserID'] solar_panel = first_message_decoded['module'] solar_inverter = first_message_decoded['inverter'] datalogger = first_message_decoded['data-logger'] pyranometer = first_message_decoded['pyranometer'] windsensor = first_message_decoded['windsensor'] rainsensor = first_message_decoded['rainsensor'] waterflow = first_message_decoded['waterflow'] web_layer_api = first_message_decoded['Web_layer_API'] total_mwh = first_message_decoded['Total MWh'] peak_watt = first_message_decoded['Size_kW'] latitude = first_message_decoded['lat'] longitude = first_message_decoded['long'] message = first_message_decoded['Comment'] rpi = first_message_decoded['IoT'] period = first_message_decoded['period'] databaseupdate() print ('In block: {}').format(block) print ('UserID: {}').format(datalogger_id) print ('made TX hash: {}').format(tx_hash) print ('and recorded a total of: {} MWh of energy').format(total_mwh) print'' except: print ('Skipping load: Message in block {} does not conform').format(block) print'' if block <= 1900000: break print 'Minimum safe blockheight of 1900000 reached: Exiting in 10 seconds' time.sleep(10) sys.exit() counter = counter+1 if counter == counter_max: break conn = sqlite3.connect('solardetails.db') c = conn.cursor() row_count_end = c.execute('select count(*) FROM SOLARDETAILS').fetchone()[0] conn.close() rows_added = row_count_end - row_count_start print ('{} new results added to database').format(rows_added) if block <= 1900000: print 'Minimum safe blockheight of 1900000 reached: Exiting in 10 seconds' time.sleep(10) sys.exit() print ('Any more blocks to load?: {}').format(more_blocks) if more_blocks != True: print 'Found all blocks, exiting in 10 seconds' time.sleep(10) sys.exit() else: print 'Waiting 10 seconds so as not to spam API, hit CTRL + c to stop search' time.sleep(10) except KeyboardInterrupt: print 'Stopping Sunfinder in 10 seconds' time.sleep(10) sys.exit()
Python
0.000001
@@ -4798,16 +4798,79 @@ ursor()%0A +%09%09%09c.execute('select * FROM SOLARDETAILS ORDER BY block DESC')%0A %09%09%09row_c
aa4be6a435222003bf5e87df5c1f8d34394592fe
add celery conf
hiren/__init__.py
hiren/__init__.py
Python
0.999777
@@ -0,0 +1,43 @@ +from github.celery import app as celery_app
a871f05ba94c34b1444468c46ed7895469059653
Create member allow_origin
glarkconnector.py
glarkconnector.py
#!/usr/bin/python """Connector for the glark.io editor. """ __version__ = "0.1" import BaseHTTPServer import json import os import re import sys class ConnectorRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Request handler exposing a REST api to the underlying filesystem""" server_version = "glarkconnector/" + __version__ def do_GET(self): """Serve a GET request.""" # Route request. print('Request path: ' + self.path) if (self.path == '/files'): self.route_get_list_files() elif (re.match(r'/files/(.+)$', self.path)): requested_file = re.match(r'/files/(.+)$', self.path).group(1) self.route_get_file(requested_file) else: self.route_400() def do_OPTIONS(self): """Serve a OPTIONS request.""" self.send_response(200) self.send_header("Access-Control-Allow-Origin", "http://dev.galipette.org") self.send_header("Access-Control-Allow-Headers", "accept, origin, x-requested-with") self.end_headers() def do_HEAD(self): """Serve a HEAD request.""" raise NotImplemented # ---------- # Routes: def route_get_list_files(self): try: files = os.listdir(os.getcwd()) except os.error: self.route_403() return self.jsend(files) def route_get_file(self, requested_file): if not self.is_in_directory(requested_file, os.getcwd()): self.route_403() else: try: # Always read in binary mode. Opening files in text mode may cause # newline translations, making the actual size of the content # transmitted *less* than the content-length! with open(os.path.realpath(requested_file), 'rb') as fp: file_content = fp.read() file_stat = os.fstat(fp.fileno()) file_size = str(file_stat[6]) file_mtime = str(file_stat.st_mtime) except IOError: self.route_404() return data = {'content': file_content, 'size': file_size, 'mtime': file_mtime} self.jsend(data) def route_400(self): self.send_error(404, "Not a valid api route") def route_403(self): self.send_error(403, "Forbidden path") def route_404(self): self.send_error(404, "Not found") # ---------- # Helpers def jsend(self, data): """Send data in jsend format.""" formatted = {'status': 'success', 'data': data} jsend = json.dumps(formatted) self.send_response(200) self.send_header("Access-Control-Allow-Origin", "http://dev.galipette.org") encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/json; charset=%s" % encoding) self.send_header("Content-Length", str(len(jsend))) self.end_headers() self.wfile.write(jsend) def is_in_directory(self, file_path, directory_path): """Check that file_path is inside directory_path or any of its subdirectories, following symlinks.""" real_dir = os.path.realpath(directory_path) real_file = os.path.realpath(file_path) return os.path.commonprefix([real_file, real_dir]) == real_dir def startConnector(): port = 3001 httpd = BaseHTTPServer.HTTPServer(("", port), ConnectorRequestHandler) print("Serving at port " + str(port)) httpd.serve_forever() if __name__ == '__main__': startConnector()
Python
0
@@ -358,16 +358,63 @@ rsion__%0D +%0A allow_origin = %22http://dev.galipette.org%22%0D %0A%0D%0A d @@ -1010,34 +1010,20 @@ n%22, -%22http://dev.galipette.org%22 +allow_origin )%0D%0A @@ -2896,34 +2896,20 @@ n%22, -%22http://dev.galipette.org%22 +allow_origin )%0D%0A
f343c9782ac0ae02ca056385aa4c6098399d0076
Fix loop through jaydebeapi cursor because not iterable
atp_classes/TeradataDB.py
atp_classes/TeradataDB.py
import atp_classes, re, platform, os class TeradataDB: def __init__(self, host=None, port=None, username=None, password=None, database=None, auth_mech=None): config = atp_classes.Config() self.host = host or config.get_config()['database']['dataWarehouse']['host'] self.username = username or config.get_config()['database']['dataWarehouse']['username'] self.password = password or config.get_config()['database']['dataWarehouse']['password'] def execute_query(self, query_string): result_rows = [] if platform.mac_ver()[0] != '': import teradata udaExec = teradata.UdaExec(appName="DataFetcher", version="1.0", logConsole=False) with udaExec.connect(method="odbc", system=self.host, username=self.username, password=self.password)as conn: with conn.cursor() as cur: try: print "executing query" # Execute query cur.execute(query_string) print "done executing query" # Get column names columns = cur.description # Fetch table results for row in cur: result_obj = {} for index, val in enumerate(columns): # Remove characters and dot which precedes column name for key values result_obj[re.sub(r'.*[.]', '', val[0])] = str(row[index]).strip() result_rows.append(result_obj) except Exception, e: return e conn.close() else: import jaydebeapi import jpype try: if not jpype.isJVMStarted(): current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) jar = r'{lib_path_gss}{java_sep}{lib_path_jdbc}'.format(lib_path_gss=os.path.join(current_dir,"lib",'tdgssconfig.jar'), java_sep=os.pathsep, lib_path_jdbc=os.path.join(current_dir,'lib','terajdbc4.jar')) args='-Djava.class.path=%s' % jar if 'JVM_PATH' in os.environ: jvm_path = os.environ['JVM_PATH'] else: jvm_path = jpype.getDefaultJVMPath() jpype.startJVM(jvm_path, args) conn = jaydebeapi.connect('com.teradata.jdbc.TeraDriver','jdbc:teradata://{url}/USER={user},PASSWORD={password}' .format(url=self.host, user=self.username, password=self.password)) cur = conn.cursor() print "executing query" # Execute query cur.execute(query_string) print "done executing query" # Get column names columns = cur.description # Fetch table results for row in cur: result_obj = {} for index, val in enumerate(columns): # Remove characters and dot which precedes column name for key values result_obj[re.sub(r'.*[.]', '', val[0])] = str(row[index]).strip() result_rows.append(result_obj) conn.close() except Exception, e: return e return result_rows
Python
0.000022
@@ -3223,32 +3223,43 @@ for row in cur +.fetchall() :%0A
e8583e6ad8c0a3d89fe4bcb063a776f1ad139447
Update spoonerism.py
pythainlp/transliterate/spoonerism.py
pythainlp/transliterate/spoonerism.py
# -*- coding: utf-8 -*- from pythainlp.transliterate import pronunciate from pythainlp import thai_consonants _list_consonants = list(thai_consonants.replace("ห", "")) def puan(word: str, show_pronunciation: bool = True) -> str: """ Thai Spoonerism This function converts Thai word to spoonerized. It only supports words with 2 to 3 syllables. :param str word: Thai word to be spoonerism :param bool show_pronunciation: True (default) or False :return: A string of Thai spoonerism word. :rtype: str :Example: :: from pythainlp.transliterate import puan puan("นาริน") # output: 'นิน-รา' puan("นาริน", False) # output: 'นินรา' """ word = pronunciate(word, engine="w2p") _list_char = [] _list_pron = word.split('-') _mix_list = "" if len(_list_pron) == 1: return word[0] if show_pronunciation: _mix_list = "-" for i in _list_pron: for j in i: if j in _list_consonants: _list_char.append(j) break elif "ห" in j and "หฺ" not in i: _list_char.append(j) break list_w_char = list(zip(_list_pron, _list_char)) _list_w = [] if len(list_w_char) == 2: _list_w.append( list_w_char[1][0].replace(list_w_char[1][1], list_w_char[0][1], 1) ) _list_w.append( list_w_char[0][0].replace(list_w_char[0][1], list_w_char[1][1], 1) ) elif len(list_w_char) == 3: _list_w.append(_list_pron[0]) _list_w.append( list_w_char[2][0].replace(list_w_char[2][1], list_w_char[1][1], 1) ) _list_w.append(list_w_char[1][0].replace( list_w_char[1][1], list_w_char[2][1], 1) ) else: # > 3 syllables raise ValueError( """{0} is more than 3 syllables.\n It only supports words with 2 to 3 syllables.""".format(word) ) if not show_pronunciation: _list_w = [i.replace("หฺ", "") for i in _list_w] return _mix_list.join(_list_w)
Python
0
@@ -879,19 +879,16 @@ urn word -%5B0%5D %0A if
9abe7a776c4b0a4995a1c3a3d16f02bcba93f12e
add sin flute
audio/fourier_an_audio.py
audio/fourier_an_audio.py
#Milton Orlando Sarria #analisis espectral de sinusoides import matplotlib.pyplot as plt import numpy as np from fourierFunc import fourierAn import wav_rw as wp filename1='sound/flute-A4.wav' filename2='sound/violin-B3.wav' #leer los archivos de audio fs,x1=wp.wavread(filename1) fs,x2=wp.wavread(filename2) t=(np.arange(1,5*fs))/float(fs) #calcular el espectro de las ondas absY1,mY1,pY1=fourierAn(x1) absY2,mY2,pY2=fourierAn(x2) #vector de frecuencias, desde -fs/2 a fs/2 (-pi<w<pi) f=np.linspace(-fs/2,fs/2,absY1.size) #visualizar las dos ondas plt.subplot(321) plt.plot(x1) plt.title('onda sin ruido') plt.subplot(323) plt.plot(absY1) plt.title('Espectro onda 1') plt.subplot(325) plt.plot(pY1) plt.title('fase onda 1') plt.subplot(322) plt.plot(x2) plt.title('onda 2 ') plt.subplot(324) plt.plot(absY2) plt.title('Espectro 2') plt.subplot(326) plt.plot(pY2) plt.title('fase onda 2') #indx1=np.array([48355 49307 50260]) #indx1=np.array([48073 48606 49138] f1=np.array([443.7, 886.63, 1329.94]) f2=np.array([312.6, 560.54, 808.01] ) A2=np.array([0.02638, 0.13159, 0.03147]) A1=np.array([0.0270,0.02018,0.00362]) y1=np.zeros(t.size) y2=np.zeros(t.size) for i in range(3): fii=A1[i]*np.cos(2*np.pi*f1[i]*t) y1=y1+fii fii=A2[i]*np.cos(2*np.pi*f2[i]*t) y2=y2+fii plt.figure(2) plt.subplot(211) plt.plot(y1) plt.title('onda 1') plt.subplot(212) plt.plot(y2) plt.title('onda 2') plt.show()
Python
0.999997
@@ -156,16 +156,51 @@ w as wp%0A +from scipy.signal import get_window %0A%0Afilena @@ -374,16 +374,161 @@ oat(fs)%0A +#crear dos ventanas%0Aw1 = get_window('hamming', x1.size); w1 = w1 / sum(w1) %0Aw2 = get_window('hamming', x2.size); w2 = w2 / sum(w2) %0A#calcul @@ -582,16 +582,19 @@ ierAn(x1 +*w1 )%0AabsY2, @@ -613,16 +613,19 @@ ierAn(x2 +*w2 )%0A#vecto @@ -1085,17 +1085,16 @@ a 2')%0A%0A%0A -# indx1=np @@ -1110,31 +1110,41 @@ 8355 - +, 49307 - +, 5026 -0 +5, 51222,52167 %5D)%0A -# indx -1 +2 =np. @@ -1159,28 +1159,43 @@ 8073 - +, 48606 - +, 49138 -%5D%0A%0Af1= +, 50203%5D)%0A%0Af1=f%5Bindx1%5D# np.a @@ -1228,16 +1228,25 @@ 94%5D)%0Af2= +f%5Bindx2%5D# np.array @@ -1275,16 +1275,29 @@ 1%5D )%0AA2= +absY1%5Bindx1%5D# np.array @@ -1329,16 +1329,29 @@ 47%5D)%0AA1= +absY2%5Bindx2%5D# np.array @@ -1377,16 +1377,154 @@ 00362%5D)%0A +p1=pY1%5Bindx1%5D#np.array(%5B-14.42432594, -70.36247253, -68.44787598%5D)%0Ap2=pY2%5Bindx2%5D#np.array(%5B-131.58657837, -428.93927002, -783.9352417 %5D)%0A%0A %0Ay1=np.z @@ -1612,24 +1612,30 @@ p.pi*f1%5Bi%5D*t ++p1%5Bi%5D )%0A y1=y1+ @@ -1684,16 +1684,22 @@ *f2%5Bi%5D*t ++p2%5Bi%5D )%0A y2
0b7f25c92a2d0798a535487aa5305a793e998214
Fix line replacement logic
homely/general.py
homely/general.py
import os from homely.engine import add from homely.utils import filereplacer def lineinfile(filename, contents, prefix=None, regex=None): filename = os.path.expanduser(filename) obj = LineInFile(filename=filename, contents=contents) if prefix is not None: obj.findprefix(prefix) elif regex is not None: obj.findregex(regex) add(obj) class UpdateHelper(object): _kwargs = None uniqueid = None def __init__(self, **kwargs): self._kwargs = kwargs items = [self.__class__.__name__] for key in sorted(self._kwargs): items.extend([key, self._kwargs[key]]) self.uniqueid = repr(items) def asdict(self): return {"class": self.__class__.__name__, "kwargs": self._kwargs} class LineInFile(UpdateHelper): _filename = None _contents = None _findprefix = None _findregex = None def __init__(self, **kwargs): super(LineInFile, self).__init__(**kwargs) self._filename = kwargs["filename"] self._contents = kwargs["contents"] def findprefix(self, prefix): self._findprefix = prefix def findregex(self, regex): self._findregex = regex def isdone(self): try: with open(self._filename) as f: for line in f.readlines(): if line.rstrip() == self._contents: return True except FileNotFoundError: pass return False def descchanges(self): return "Adding line to %s: %s" % (self._filename, self._contents) def makechanges(self, prevchanges): changes = { "old_line": None, } if self._findprefix: matchline = lambda line: line.startswith(self._findprefix) elif self._findregex: # FIXME: implement regex matching raise Exception("FIXME: implement regex") # noqa else: matchline = lambda line: line.rstrip() == self._contents with filereplacer(self._filename) as (tmp, orig): modified = False if orig is not None: # read through the original file and look for a line to replace for line in orig.readlines(): if modified: tmp.write(line) elif matchline(line): modified = True tmp.write(self._contents) # FIXME: respect the existing lines' line endings! tmp.write("\n") if "old_line" not in changes: changes["old_line"] = line.rstrip() # if we didn't write out the new line by replacing parts of the original, then we'll # just have to pop the new line on the end if not modified: tmp.write(self._contents) # FIXME: respect the existing lines' line endings! tmp.write("\n") changes["old_line"] = None return changes
Python
0.000004
@@ -2281,24 +2281,28 @@ if +not modified :%0A @@ -2297,74 +2297,12 @@ fied -:%0A tmp.write(line)%0A elif + and mat @@ -2638,16 +2638,82 @@ strip()%0A + else:%0A tmp.write(line)%0A
53b43e51c4d073dae4f3ccad896ba1744ca1284b
Update version
auth_backends/_version.py
auth_backends/_version.py
__version__ = '0.1.1' # pragma: no cover
Python
0
@@ -12,17 +12,17 @@ = '0.1. -1 +2 ' # pra
f57a2c9124da513734a8e4934b8a02903109077e
Remove hardcoded backgrount from molecule svg
girder/molecules/server/openbabel.py
girder/molecules/server/openbabel.py
from girder.api.rest import RestException from openbabel import OBMol, OBConversion import pybel import re inchi_validator = re.compile('InChI=[0-9]S?\/') # This function only validates the first part. It does not guarantee # that the entire InChI is valid. def validate_start_of_inchi(inchi): if not inchi_validator.match(inchi): raise RestException('Invalid InChI: "' + inchi +'"', 400) # gen3d should be true for 2D input formats such as inchi or smiles def convert_str(str_data, in_format, out_format, gen3d=False, out_options=None): # Make sure that the start of InChI is valid before passing it to # Open Babel, or Open Babel will crash the server. if in_format.lower() == 'inchi': validate_start_of_inchi(str_data) if out_options is None: out_options = {} obMol = OBMol() conv = OBConversion() conv.SetInFormat(in_format) conv.SetOutFormat(out_format) conv.ReadString(obMol, str_data) if gen3d: # Generate 3D coordinates for the input mol = pybel.Molecule(obMol) mol.make3D() for option, value in out_options.items(): conv.AddOption(option, conv.OUTOPTIONS, value) return (conv.WriteString(obMol), conv.GetOutFormat().GetMIMEType()) def to_inchi(str_data, in_format): mol = OBMol() conv = OBConversion() conv.SetInFormat(in_format) # Hackish for now, convert to xyz first... conv.SetOutFormat('xyz') conv.ReadString(mol, str_data) xyz = conv.WriteString(mol) # Now convert to inchi and inchikey. mol = OBMol() conv.SetInFormat('xyz') conv.ReadString(mol, xyz) conv.SetOutFormat('inchi') inchi = conv.WriteString(mol).rstrip() conv.SetOptions("K", conv.OUTOPTIONS) inchikey = conv.WriteString(mol).rstrip() return (inchi, inchikey) def from_inchi(str_data, out_format): return convert_str(str_data, 'inchi', out_format, True) def to_smiles(str_data, in_format): # This returns ["<smiles>", "chemical/x-daylight-smiles"] # Keep only the first part. # The smiles has returns at the end of it, and may contain # a return in the middle with a common name. Get rid of # all of these. # Use canonical smiles smiles = convert_str(str_data, in_format, 'can')[0].strip() return smiles.split()[0] def from_smiles(str_data, out_format): return convert_str(str_data, 'smi', out_format, True) def atom_count(str_data, in_format): mol = OBMol() conv = OBConversion() conv.SetInFormat(in_format) conv.ReadString(mol, str_data) return mol.NumAtoms() def get_formula(str_data, in_format): # Inchi must start with 'InChI=' if in_format == 'inchi' and not str_data.startswith('InChI='): str_data = 'InChI=' + str_data validate_start_of_inchi(str_data) # Get the molecule using the "Hill Order" - i. e., C first, then H, # and then alphabetical. mol = OBMol() conv = OBConversion() conv.SetInFormat(in_format) conv.ReadString(mol, str_data) return mol.GetFormula() def to_svg(str_data, in_format): return convert_str(str_data, in_format, 'svg')[0]
Python
0.00027
@@ -3078,32 +3078,151 @@ ta, in_format):%0A + out_options = %7B%0A 'b': 'none', # transparent background color%0A 'B': 'black' # black bonds color%0A %7D%0A return conve @@ -3254,13 +3254,38 @@ t, 'svg' +, out_options=out_options )%5B0%5D%0A
2321ddb5f6d7731597f4f122a87041933348f064
Enable Unicode tests
gmn/src/d1_gmn/tests/test_unicode.py
gmn/src/d1_gmn/tests/test_unicode.py
# -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # 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. """Test handling of Unicode in D1 REST URLs and type elements """ from __future__ import absolute_import import logging import pytest import responses import d1_gmn.tests.gmn_test_case import d1_common import d1_common.system_metadata @pytest.mark.skip('TODO') class TestUnicode(d1_gmn.tests.gmn_test_case.GMNTestCase): @responses.activate def test_1000(self): """Unicode: GMN and libraries handle Unicode correctly""" def test(client): tricky_unicode_str = self.load_sample_utf8_to_unicode( 'tricky_identifiers_unicode.utf8.txt' ) for line in tricky_unicode_str.splitlines(): pid_unescaped, pid_escaped = line.split('\t') logging.debug(u'Testing PID: {}'.format(pid_unescaped)) pid, sid, send_sciobj_str, send_sysmeta_pyxb = self.create_obj( client, pid=pid_unescaped, sid=True ) recv_sciobj_str, recv_sysmeta_pyxb = self.get_obj(client, pid) # self.assertEquals(send_sciobj_str, recv_sciobj_str) assert d1_common.system_metadata.is_equivalent_pyxb( send_sysmeta_pyxb, recv_sysmeta_pyxb, ignore_timestamps=True ) client.delete(pid) with d1_gmn.tests.gmn_mock.disable_auth(): test(self.client_v1) test(self.client_v2)
Python
0.000001
@@ -933,22 +933,8 @@ ng%0A%0A -import pytest%0A impo @@ -1038,34 +1038,8 @@ a%0A%0A%0A -@pytest.mark.skip('TODO')%0A clas @@ -1135,16 +1135,33 @@ 000(self +, mn_client_v1_v2 ):%0A %22 @@ -1221,28 +1221,52 @@ %22%22%22%0A -%0A -def test(client +with d1_gmn.tests.gmn_mock.disable_auth( ):%0A @@ -1630,22 +1630,31 @@ +mn_ client +_v1_v2 , pid=pi @@ -1747,81 +1747,28 @@ obj( +mn_ client -, pid)%0A # self.assertEquals(send_sciobj_str, recv_sciobj_str +_v1_v2, pid )%0A @@ -1919,125 +1919,137 @@ -client.delete(pid)%0A%0A with d1_gmn.tests.gmn_mock.disable_auth():%0A test(self.client_v1)%0A test(self.client_v2 +assert pid == pid_unescaped%0A assert recv_sysmeta_pyxb.identifier.value() == pid_unescaped%0A mn_client_v1_v2.delete(pid )%0A
3868a4ef30835ed1904a37318013e20f2295a8a9
Remove fantastic from COB theme
ckanext/cob/plugin.py
ckanext/cob/plugin.py
import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit def groups(): # Return a list of groups return toolkit.get_action('group_list')(data_dict={'all_fields': True}) def dataset_count(): # Return a count of all datasets result = toolkit.get_action('package_search')(data_dict={'rows': 1}) return result['count'] class CobPlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) plugins.implements(plugins.ITemplateHelpers) # IConfigurer def update_config(self, config_): toolkit.add_template_directory(config_, 'templates') toolkit.add_public_directory(config_, 'public') toolkit.add_resource('fanstatic', 'cob') def get_helpers(self): # Register cob_theme_* helper functions return {'cob_theme_groups': groups, 'cob_theme_dataset_count': dataset_count}
Python
0
@@ -657,57 +657,8 @@ ic') -%0A toolkit.add_resource('fanstatic', 'cob') %0A%0A
46c1c21c0190aa95f4fede8fa1d98bbae7cf38c5
test mode defaults to true - fix for #21
ckanext/doi/config.py
ckanext/doi/config.py
#!/usr/bin/env python # encoding: utf-8 """ Created by 'bens3' on 2013-06-21. Copyright (c) 2013 'bens3'. All rights reserved. """ from pylons import config from paste.deploy.converters import asbool TEST_PREFIX = '10.5072' ENDPOINT = 'https://mds.datacite.org' TEST_ENDPOINT = 'https://test.datacite.org/mds' def get_test_mode(): """ Get test mode as boolean @return: """ return asbool(config.get("ckanext.doi.test_mode")) def get_prefix(): """ Get the prefix to use for DOIs @return: test prefix if we're in test mode, otherwise config prefix setting """ return TEST_PREFIX if get_test_mode() else config.get("ckanext.doi.prefix") def get_endpoint(): """ Get the DataCite endpoint @return: test endpoint if we're in test mode """ return TEST_ENDPOINT if get_test_mode() else ENDPOINT def get_site_url(): """ Get the site URL Try and use ckanext.doi.site_url but if that's not set use ckan.site_url @return: """ site_url = config.get("ckanext.doi.site_url") if not site_url: site_url = config.get('ckan.site_url') return site_url.rstrip('/')
Python
0.000001
@@ -379,33 +379,32 @@ return:%0A %22%22%22%0A -%0A return asboo @@ -439,16 +439,22 @@ st_mode%22 +, True ))%0A%0A%0Adef
3c1b5c425109d24eca552e60e859d7d747607492
Fix UP in TRRUST
indra/sources/trrust/processor.py
indra/sources/trrust/processor.py
from copy import deepcopy from indra.databases import hgnc_client from indra.statements import Agent, IncreaseAmount, DecreaseAmount, Evidence class TrrustProcessor(object): """Processor to extract INDRA Statements from Trrust data frame. Attributes ---------- df : pandas.DataFrame The Trrust table to process. statements : list[indra.statements.Statement] The list of INDRA Statements extracted from the table. """ def __init__(self, df): self.df = df self.statements = [] def extract_statements(self): """Process the table to extract Statements.""" for _, (tf, target, effect, refs) in self.df.iterrows(): tf_agent = get_grounded_agent(tf) target_agent = get_grounded_agent(target) if effect == 'Activation': stmt_cls = IncreaseAmount elif effect == 'Repression': stmt_cls = DecreaseAmount else: continue pmids = refs.split(';') for pmid in pmids: stmt = make_stmt(stmt_cls, tf_agent, target_agent, pmid) self.statements.append(stmt) def make_stmt(stmt_cls, tf_agent, target_agent, pmid): """Return a Statement based on its type, agents, and PMID.""" ev = Evidence(source_api='trrust', pmid=pmid) return stmt_cls(deepcopy(tf_agent), deepcopy(target_agent), evidence=[ev]) def get_grounded_agent(gene_name): """Return a grounded Agent based on an HGNC symbol.""" db_refs = {'TEXT': gene_name} if gene_name in hgnc_map: gene_name = hgnc_map[gene_name] hgnc_id = hgnc_client.get_hgnc_id(gene_name) if not hgnc_id: hgnc_id = hgnc_client.get_current_hgnc_id(gene_name) if hgnc_id: db_refs['HGNC'] = hgnc_id up_id = hgnc_client.get_uniprot_id(hgnc_id) if up_id: db_refs['UP'] = up_id agent = Agent(gene_name, db_refs=db_refs) return agent hgnc_map = { 'CTGF': 'CCN2', 'CYR61': 'CCN1', 'MKL1': 'MRTFA', 'NOV': 'CCN3', 'RFWD2': 'COP1', 'SALL4A': 'SALL4', 'STAT5': 'STAT5A', 'TRAP': 'ACP5', 'AES': 'TLE5', 'SEPT7': 'SEPTIN7' }
Python
0.000001
@@ -1893,16 +1893,37 @@ if +up_id and ',' not in up_id:%0A
bf8ab86d536570790d135f0f46c97ffb30a83535
update background_substraction.py
background_subtraction.py
background_subtraction.py
# Reference: http://docs.opencv.org/master/db/d5c/tutorial_py_bg_subtraction.html import numpy as np import cv2 # TODO: remove hard coded file name cap = cv2.VideoCapture('videos/sample_video_2.mp4') # Here are the 3 ways of background subtraction # createBackgroundSubtractorMOG2 seems to give the best result. Need more testing. fgbg = cv2.createBackgroundSubtractorMOG2() #fgbg = cv2.bgsegm.createBackgroundSubtractorMOG() #fgbg = cv2.bgsegm.createBackgroundSubtractorGMG() while(1): ret, frame = cap.read() fgmask = fgbg.apply(frame) cv2.imshow('frame',fgmask) k = cv2.waitKey(30) & 0xff if k == 27: break cap.release() cv2.destroyAllWindows()
Python
0.000001
@@ -74,16 +74,41 @@ ion.html +%0A# requires opencv v3.1.0 %0A%0Aimport
4bf71f03166fc0097668c3cf18dcbea52b000a49
comment updated
gui/form/itemdialog.py
gui/form/itemdialog.py
# -*- coding: utf-8 -*- from PyQt4 import QtGui, QtCore from core import map from core.localisation import _ class itemDialog(QtGui.QDialog): """ Window to fill some informations to create an item label npc gender npc gender field create button cancel button """ _app = None _parent = None _coordinates = None _messageLabel = None _saveButton = None _cancelButton = None itemAdded = QtCore.pyqtSignal(str, int, int) itemUpdated = QtCore.pyqtSignal(str, int, int) def __init__(self, parent, app, coordinates=None, row=None): """ Creates the window GUI and displays the window """ QtGui.QDialog.__init__(self, parent) self._app = app self._parent = parent self._editedRow = None if coordinates is None and row is None: raise BaseException("At least a row or a tuple of coordinates is needed") elif coordinates is None: self._editedRow = row['internalName'] self._coordinates = (row['x'], row['y']) else: self._coordinates = coordinates self._parent.selectCell(self._coordinates[0], self._coordinates[1]) self._row = row self.setFixedWidth(250) self.initUI() self.setWindowTitle(self._title) self.setModal(True) self.connectSignals() self.show() def initUI(self): """ Creates the UI """ layout = QtGui.QGridLayout() self._messageLabel = QtGui.QLabel() self._messageLabel.setWordWrap(True) if self._editedRow is not None: itemXLabel = QtGui.QLabel(_('ITEM_X_LABEL')) self._itemXField = QtGui.QSpinBox() self._itemXField.setMinimum(0) self._itemXField.setMaximum(self._app.map.width) self._itemXField.setValue(self._row['x']) itemYLabel = QtGui.QLabel(_('ITEM_Y_LABEL')) self._itemYField = QtGui.QSpinBox() self._itemYField.setMinimum(0) self._itemYField.setMaximum(self._app.map.height) self._itemYField.setValue(self._row['y']) fieldsLayout = self.getFields(self._row) if self._editedRow is not None: self._saveButton = QtGui.QPushButton(_('EDIT_BUTTON')) else: self._saveButton = QtGui.QPushButton(_('CREATE_BUTTON')) self._saveButton.clicked.connect(self.createItem) self._cancelButton = QtGui.QPushButton(_('CANCEL_BUTTON')) self._cancelButton.clicked.connect(self.close) layout.addWidget(self._messageLabel, 0, 0, 1, 2) gridRow = 0 if self._editedRow is not None: layout.addWidget(itemXLabel, 1, 0) layout.addWidget(self._itemXField, 1, 1) layout.addWidget(itemYLabel, 2, 0) layout.addWidget(self._itemYField, 2, 1) gridRow = 2 layout.addLayout(fieldsLayout, 1 + gridRow, 0, 1, 2) layout.addWidget(self._saveButton, 2 + gridRow, 0) layout.addWidget(self._cancelButton, 2 + gridRow, 1) self.setLayout(layout) def connectSignals(self): """ Connect a signal to unselect the cell if the window is rejected """ self.rejected.connect(self._parent.unselectCell) def displayMessage(self, message): """ Method to display a message in the window. """ self._messageLabel.setText(message) self.adjustSize() def createItem(self): """ Method called when the "Create" button is pressed. The filled values are checked and if they are correct, an entity is created or updated """ x = self._coordinates[0] y = self._coordinates[1] if self._editedRow is not None: x = int(self._itemXField.value()) y = int(self._itemYField.value()) if not self._app.map.isCellOnLand((x, y)): self.displayMessage(_('ERROR_ITEM_IN_WATER')) data = False else: data = self.validateFormData() if data is not False: if self._editedRow is not None: self._app.deleteEntity(self.entityType, self._editedRow) data['x'] = x data['y'] = y self._app.addEntity(self.entityType, data['internalName'], data) if self._editedRow is not None: self._editedRow = None self.itemUpdated.emit(self.entityType, x, y) else: self.itemAdded.emit(self.entityType, x, y) self.accept() self.close()
Python
0
@@ -200,71 +200,81 @@ em%0A%09 -label npc gender%09npc gender field%0A%09create button%09%09cancel button +All items contains two fields for their coordinates if the item is edited %0A%09%22%22
1f815ad5cb7535132a60297808abfa959709ba65
Fix redirect_to_login
daiquiri/files/views.py
daiquiri/files/views.py
import logging from django.core.exceptions import PermissionDenied from django.http import Http404 from django.shortcuts import redirect from django.views.generic import View from .utils import file_exists, check_file, send_file logger = logging.getLogger(__name__) class FileView(View): def get(self, request, file_path): # append 'index.html' when the file_path is a directory if not file_path or file_path.endswith('/'): file_path += 'index.html' if not file_exists(file_path): logger.debug('%s not found', file_path) raise Http404 if check_file(request.user, file_path): return send_file(request, file_path) else: logger.debug('%s if forbidden', file_path) if request.user.is_authenticated: raise PermissionDenied else: return redirect('account_login') # if nothing worked, return 404 raise Http404
Python
0.000011
@@ -9,16 +9,72 @@ ogging%0A%0A +from django.contrib.auth.views import redirect_to_login%0A from dja @@ -153,46 +153,8 @@ 404%0A -from django.shortcuts import redirect%0A from @@ -922,24 +922,35 @@ rect -('account_login' +_to_login(request.path_info )%0A%0A
3ce5f60102d5de7367a06e7412e9e31597e40a58
revert to original hello world
click_tutorial/cli.py
click_tutorial/cli.py
import click @click.argument('name') @click.command() def cli(name): click.echo("Hello, {0}!".format(name)) if __name__ == '__main__': cli()
Python
0.999999
@@ -11,32 +11,8 @@ ck%0A%0A -@click.argument('name')%0A @cli @@ -32,20 +32,16 @@ def cli( -name ):%0A c @@ -62,26 +62,15 @@ lo, -%7B0%7D!%22.format(name) +World!%22 )%0A%0Ai
d44250f60e9676618170bd61f8f6bc438078ef87
Add celery settings.
base/config/production.py
base/config/production.py
" Production settings must be here. " from .core import * from os import path as op SECRET_KEY = 'SecretKeyForSessionSigning' ADMINS = frozenset([MAIL_USERNAME]) # flask.ext.collect # ----------------- COLLECT_STATIC_ROOT = op.join(op.dirname(ROOTDIR), 'static') # dealer DEALER_PARAMS = dict( backends=('git', 'mercurial', 'simple', 'null') ) # FQUEST settings # --------------- AUTH_LOGIN_VIEW = 'fquest.index' AUTH_PROFILE_VIEW = 'fquest.profile' OAUTH_FACEBOOK = dict( consumer_key='365449256868307', consumer_secret='899b2ea26ca77122eef981f4712aeb04', params=dict( scope="user_status,user_likes,user_activities,user_questions,user_events,user_videos,user_groups,user_relationships,user_notes,user_photos,offline_access,publish_actions" ) ) # Cache CACHE_TYPE = 'redis' CACHE_REDIS_HOST = 'localhost' CACHE_KEY_PREFIX = 'poliglot' # Database settings SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://fquest:fquest@localhost:5432/fquest_master' # pymode:lint_ignore=W0614,W404
Python
0
@@ -975,16 +975,74 @@ master'%0A +# Celery settings%0ABROKER_URL = 'redis://localhost:6379/0'%0A %0A%0A# pymo
4c977a313942074cccdd6756762c5545e650cdc7
Switch to NumPy's `ndindex` in `_cdist_apply`
dask_distance/_utils.py
dask_distance/_utils.py
import functools import itertools import numpy import dask import dask.array from . import _compat from . import _pycompat def _broadcast_uv(u, v): u = _compat._asarray(u) v = _compat._asarray(v) U = u if U.ndim == 1: U = U[None] V = v if V.ndim == 1: V = V[None] if U.ndim != 2: raise ValueError("u must be a 1-D or 2-D array.") if V.ndim != 2: raise ValueError("v must be a 1-D or 2-D array.") U = dask.array.repeat(U[:, None], len(V), axis=1) V = dask.array.repeat(V[None, :], len(U), axis=0) return U, V def _unbroadcast_uv(u, v, result): u = _compat._asarray(u) v = _compat._asarray(v) if v.ndim == 1: result = result[:, 0] if u.ndim == 1: result = result[0] return result def _broadcast_uv_wrapper(func): @functools.wraps(func) def _wrapped_broadcast_uv(u, v): U, V = _broadcast_uv(u, v) result = func(U, V) result = _unbroadcast_uv(u, v, result) return result return _wrapped_broadcast_uv def _cdist_apply(U, V, metric): result = numpy.empty(U.shape[:-1], dtype=float) for i in itertools.product(*[_pycompat.irange(e) for e in result.shape]): result[i] = metric(U[i], V[i]) return result def _bool_cmp_cnts(U, V): U = _compat._asarray(U) V = _compat._asarray(V) U = U.astype(bool) V = V.astype(bool) U_01 = [~U, U] V_01 = [~V, V] UV_cmp_cnts = numpy.empty((2, 2), dtype=object) UV_ranges = [_pycompat.irange(e) for e in UV_cmp_cnts.shape] for i, j in itertools.product(*UV_ranges): UV_cmp_cnts[i, j] = (U_01[i] & V_01[j]).sum(axis=-1, dtype=float) for i in _pycompat.irange(UV_cmp_cnts.ndim - 1, -1, -1): UV_cmp_cnts2 = UV_cmp_cnts[..., 0] for j in itertools.product(*(UV_ranges[:i])): UV_cmp_cnts2[j] = dask.array.stack(UV_cmp_cnts[j].tolist(), axis=0) UV_cmp_cnts = UV_cmp_cnts2 UV_cmp_cnts = UV_cmp_cnts[()] return UV_cmp_cnts
Python
0
@@ -1167,57 +1167,22 @@ in -itertools.product(*%5B_pycompat.irange(e) for e in +numpy.ndindex( resu @@ -1189,17 +1189,16 @@ lt.shape -%5D ):%0A
bd712dad2709ba31be89f48f283084d5894cb378
Replace dot in archive thumbnail name by underscore
ipol_demo/modules/core/archive.py
ipol_demo/modules/core/archive.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ Helper functions for core, related to the archive module. """ import gzip import json import os import traceback from collections import OrderedDict import requests from ipolutils.utils import thumbnail def create_thumbnail(src_file): """ Create thumbnail when possible from file to archive in run folder, returns the filepath of thumbnail when created. """ thumb_height = 128 if not os.path.exists(src_file): return False thumb_name, _ = os.path.splitext(os.path.basename(src_file)) thumb_name = thumb_name.lower() + '_thumbnail.jpeg' thumb_file = os.path.join(os.path.dirname(src_file), thumb_name) try: thumbnail(src_file, thumb_height, thumb_file) except Exception: return False return thumb_file def send_to_archive(demo_id, work_dir, request, ddl_archive, res_data, host_name): """ Prepare an execution folder for archiving an experiment (thumbnails). Collect information and parameters. Send data to the archive module. """ # let's add all the parameters parameters = OrderedDict() blobs = [] for key, values in ddl_archive.items(): if key == 'params': for p in values: if p in res_data['params']: parameters[p] = res_data['params'][p] elif key == 'info': for i in values: if i in res_data['algo_info']: parameters[values[i]] = res_data['algo_info'][i] elif key == 'files' or key == 'hidden_files': for file_name, file_label in values.items(): src_file = os.path.join(work_dir, file_name) if not os.path.exists(src_file): continue # declared file in ddl is not there if not file_label: # if no label given, use filename file_label = file_name value = {file_label: src_file} try: # to get a thumbnail thumb_file = create_thumbnail(src_file) except Exception: print(traceback.format_exc()) if thumb_file: value[os.path.basename(thumb_file)] = thumb_file blobs.append(value) elif key == 'compressed_files': for file_name, file_label in values.items(): src_file = os.path.join(work_dir, file_name) if not os.path.exists(src_file): continue # normal? src_handle = open(src_file, 'rb') gz_file = src_file + '.gz' gz_handle = gzip.open(gz_file, 'wb') gz_handle.writelines(src_handle) src_handle.close() gz_handle.close() if not file_label: # if no label given, use filename file_label = file_name blobs.append({file_label: gz_file}) if 'enable_reconstruct' in ddl_archive and ddl_archive['enable_reconstruct'] and request is not None: clientData = json.loads(request['clientData']) if clientData.get("origin", "") == "upload": # Count how many file entries and remove them file_keys = [key for key in request if key.startswith("file_")] files = request.copy() list(map(files.pop, file_keys)) clientData["files"] = len(file_keys) execution = {} execution['demo_id'] = demo_id execution['request'] = clientData execution['response'] = res_data execution_json = json.dumps(execution) else: execution_json = None url = 'http://{}/api/archive/add_experiment'.format(host_name) data = { "demo_id": demo_id, "blobs": json.dumps(blobs), "parameters": json.dumps(parameters), "execution": execution_json } resp = requests.post(url, data=data) return resp.json()
Python
0
@@ -521,31 +521,11 @@ name -, _ = os.path.splitext( + = os.p @@ -546,16 +546,33 @@ rc_file) +.replace(%22.%22, %22_%22 )%0A th @@ -2016,16 +2016,52 @@ umbnail%0A + print(src_file)%0A
871f49eea1197af8224c601833e6e96f59697eb3
Update phishing_database.py
plugins/feeds/public/phishing_database.py
plugins/feeds/public/phishing_database.py
from datetime import timedelta import logging from core.observables import Url from core.feed import Feed from core.errors import ObservableValidationError class PhishingDatabase(Feed): """ This class will pull the PhishingDatabase feed from github on a 12 hour interval. """ default_values = { 'frequency': timedelta(hours=12), 'name': 'PhishingDatabase', 'source': 'https://raw.githubusercontent.com/mitchellkrogza/Phishing.Database/master/phishing-links-NEW-today.txt', 'description': 'Phishing Domains, urls websites and threats database.' } def update(self): for url in self.update_lines(): self.analyze(url) def analyze(self, url): context = {'source': self.name} try: url = Url.get_or_create(value=url) url.add_context(context) url.add_source(self.name) url.tag(['phishing']) except ObservableValidationError as e: logging.error(e)
Python
0.000002
@@ -1,12 +1,106 @@ +#!/usr/bin/env python%0A%22%22%22This class will incorporate the PhishingDatabase feed into yeti.%22%22%22%0A%0A from datetim @@ -282,17 +282,16 @@ %0A %22%22%22 - This cla @@ -363,17 +363,16 @@ nterval. - %22%22%22%0A%0A
63be69b5a977d4ae5b65bf849e0de6809dc6cc3f
Remove unused function
systemd/server_main.py
systemd/server_main.py
# -*- coding: utf-8 -*- import fcntl import json import os import socket import select import struct import sys import termios import threading import time import subprocess import atexit import re import candy_board_amt import logging import logging.handlers # sys.argv[0] ... Serial Port # sys.argv[1] ... The path to socket file, e.g. /var/run/candy-board-service.sock # sys.argv[2] ... The network interface name to be monitored logger = logging.getLogger('ltepi2') logger.setLevel(logging.INFO) handler = logging.handlers.SysLogHandler(address = '/dev/log') logger.addHandler(handler) formatter = logging.Formatter('%(module)s.%(funcName)s: %(message)s') handler.setFormatter(formatter) led = 0 class Monitor(threading.Thread): FNULL = open(os.devnull, 'w') def __init__(self, nic): super(Monitor, self).__init__() self.nic = nic def run(self): while True: err = subprocess.call("ip route | grep %s" % self.nic, shell=True, stdout=Monitor.FNULL, stderr=subprocess.STDOUT) if err != 0: logger.error("LTEPi-II modem is terminated. Shutting down.") sys.exit(1) err = subprocess.call("ip route | grep default | grep -v %s" % self.nic, shell=True, stdout=Monitor.FNULL, stderr=subprocess.STDOUT) if err == 0: ls_nic_cmd = "ip route | grep default | grep -v %s | tr -s ' ' | cut -d ' ' -f 5" % self.nic ls_nic = subprocess.Popen(ls_nic_cmd, shell=True, stdout=subprocess.PIPE).stdout.read() logger.debug("modem_init() : ls_nic => %s" % ls_nic) for nic in ls_nic.split("\n"): if nic: ip_cmd = "ip route | grep %s | awk '/default/ { print $3 }'" % nic ip = subprocess.Popen(ip_cmd, shell=True, stdout=subprocess.PIPE).stdout.read() subprocess.call("ip route del default via %s" % ip, shell=True) time.sleep(5) def delete_sock_path(sock_path): # turn LED off led = 1 blinky() # remove sock_path try: os.unlink(sock_path) except OSError: if os.path.exists(sock_path): raise def resolve_version(): if 'VERSION' in os.environ: return os.environ['VERSION'] return 'N/A' def resolve_boot_apn(): dir = os.path.dirname(os.path.abspath(__file__)) apn_json = dir + '/boot-apn.json' if not os.path.isfile(apn_json): return None with open(apn_json) as apn_creds: apn = json.load(apn_creds) os.remove(apn_json) return apn def modem_init(serial_port, sock_path): delete_sock_path(sock_path) atexit.register(delete_sock_path, sock_path) serial = candy_board_amt.SerialPort(serial_port, 115200) server = candy_board_amt.SockServer(resolve_version(), resolve_boot_apn(), sock_path, serial) ret = server.perform({'category':'modem', 'action':'enable_ecm'}) logger.debug("modem_init() : modem, enable_ecm => %s" % ret) sys.exit(json.loads(ret)['status'] != 'OK') def blinky(): global led led = 0 if led != 0 else 1 subprocess.call("echo %d > /sys/class/gpio/gpio4/value" % led, shell=True, stdout=Monitor.FNULL, stderr=subprocess.STDOUT) threading.Timer(1, blinky, ()).start() def server_main(serial_port, nic, sock_path='/var/run/candy-board-service.sock'): delete_sock_path(sock_path) atexit.register(delete_sock_path, sock_path) logger.debug("server_main() : Setting up Monitor...") monitor = Monitor(nic) monitor.start() logger.debug("server_main() : Setting up SerialPort...") serial = candy_board_amt.SerialPort(serial_port, 115200) logger.debug("server_main() : Setting up SockServer...") server = candy_board_amt.SockServer(resolve_version(), resolve_boot_apn(), sock_path, serial) if 'DEBUG' in os.environ and os.environ['DEBUG'] == "1": server.debug = True if 'BLINKY' in os.environ and os.environ['BLINKY'] == "1": logger.debug("server_main() : Starting blinky timer...") blinky() logger.debug("server_main() : Starting SockServer...") server.start() logger.debug("server_main() : Joining Monitor thread into main...") monitor.join() logger.debug("server_main() : Joining SockServer thread into main...") server.join() if __name__ == '__main__': if len(sys.argv) < 3: logger.error("USB Ethernet Network Interface isn't ready. Shutting down.") elif len(sys.argv) > 3: if sys.argv[3] == 'init': modem_init(sys.argv[1], sys.argv[2]) else: modem_reset(sys.argv[1], sys.argv[2]) else: logger.info("serial_port:%s, nic:%s" % (sys.argv[1], sys.argv[2])) server_main(sys.argv[1], sys.argv[2])
Python
0.000004
@@ -4624,20 +4624,34 @@ -modem_reset( +logger.error(%22Do nothing: sys. @@ -4647,35 +4647,40 @@ thing: sys.argv%5B -1%5D, +3%5D=%25s%22 %25 sys.argv%5B2%5D)%0A @@ -4669,25 +4669,25 @@ %25 sys.argv%5B -2 +3 %5D)%0A else:
89c32db7496ae261d24ef87cd94c92f936c7894a
Fix typo
flexget/components/trakt/trakt_calendar.py
flexget/components/trakt/trakt_calendar.py
import datetime import math from loguru import logger from requests import RequestException from flexget import plugin from flexget.entry import Entry from flexget.event import event from flexget.utils.cached_input import cached from . import db logger = logger.bind(name='trakt_calendar') max_number_of_days = 31 class TraktCalendar: schema = { 'type': 'object', 'properties': { 'start_day': {'type': 'integer', 'default': 0}, 'days': {'type': 'integer', 'default': 7}, 'account': {'type': 'string'}, 'strip_dates': {'type': 'boolean', 'default': False}, 'type': {'type': 'string', 'enum': ['shows', 'episodes']}, }, 'required': ['type'], 'additionalProperties': False, } # Series info series_map = { 'trakt_series_name': 'title', 'trakt_series_year': 'year', 'imdb_id': 'ids.imdb', 'tvdb_id': 'ids.tvdb', 'tmdb_id': 'ids.tmdb', 'trakt_show_id': 'ids.trakt', 'trakt_slug': 'ids.slug', 'tvrage_id': 'ids.tvrage', 'trakt_trailer': 'trailer', 'trakt_homepage': 'homepage', 'trakt_series_runtime': 'runtime', 'trakt_series_first_aired': 'first_aired', 'trakt_series_air_time': 'airs.time', 'trakt_series_air_day': 'airs.day', 'trakt_series_air_timezone': 'airs.timezone', 'trakt_series_content_rating': 'certification', 'trakt_genres': 'genres', 'trakt_series_network': 'network', 'imdb_url': lambda s: s['ids']['imdb'] and 'http://www.imdb.com/title/%s' % s['ids']['imdb'], 'trakt_series_url': lambda s: s['ids']['slug'] and 'https://trakt.tv/shows/%s' % s['ids']['slug'], 'trakt_series_country': 'country', 'trakt_series_status': 'status', 'trakt_series_overview': 'overview', 'trakt_series_rating': 'rating', 'trakt_series_votes': 'votes', 'trakt_series_language': 'language', 'trakt_series_aired_episodes': 'aired_episodes', 'trakt_languages': 'available_translations', 'trakt_series_updated_at': 'updated_at', } # Episode info episode_map = { 'trakt_ep_name': 'title', 'trakt_ep_imdb_id': 'ids.imdb', 'trakt_ep_tvdb_id': 'ids.tvdb', 'trakt_ep_tmdb_id': 'ids.tmdb', 'trakt_ep_tvrage': 'ids.tvrage', 'trakt_episode_id': 'ids.trakt', 'trakt_ep_first_aired': 'first_aired', 'trakt_ep_overview': 'overview', 'trakt_ep_abs_number': 'number_abs', 'trakt_season': 'season', 'trakt_episode': 'number', 'trakt_ep_id': lambda ep: 'S%02dE%02d' % (ep['season'], ep['number']), 'trakt_ep_languages': 'available_translations', 'trakt_ep_runtime': 'runtime', 'trakt_ep_updated_at': 'updated_at', 'trakt_ep_rating': 'rating', 'trakt_ep_votes': 'votes', } @cached('trakt_calendar', persist='2 hours') def on_task_input(self, task, config): start_date = datetime.datetime.now().date() + datetime.timedelta(days=config['start_day']) # The API limit is max_number_of_days days for a single all. Find the number of calls. number_of_calls = math.ceil(config['days'] / max_number_of_days) days = config['days'] entries = set() for _ in range(number_of_calls): current_number_of_days = start_date + datetime.timedelta(days=min(days, max_number_of_days)) logger.debug( 'Start date for calendar: {}, end date: {}', start_date, current_number_of_days, ) url = db.get_api_url( 'calendars', 'my' if config.get('account') else 'all', 'shows', start_date, current_number_of_days, ) try: results = ( db.get_session(config.get('account')).get(url, params={'extended': 'full'}).json() ) logger.debug('Found {} calendar entries', len(results)) except RequestException as e: raise plugin.PluginError('Error while fetching calendar: {0}'.format(e)) for result in results: e = Entry() e.update_using_map(self.series_map, result['show']) if config['type'] == 'episodes': e.update_using_map(self.episode_map, result['episode']) title = e['trakt_series_name'] if not config['strip_dates']: title = '{0} ({1})'.format(title, e['trakt_series_year']) url = e['trakt_series_url'] if config['type'] == 'episodes': title = '{0} S{1:02d}E{2:02d}'.format( title, e['trakt_season'], e['trakt_episode'] ) url = '{0}/seasons/{1}/episodes/{2}'.format( url, e['trakt_season'], e['trakt_episode'] ) e['title'] = title e['url'] = url entries.add(e) # Increment for next run days = days - max_number_of_days start_date = start_date + datetime.timedelta(days=max_number_of_days + 1) return list(entries) @event('plugin.register') def register_plugin(): plugin.register(TraktCalendar, 'trakt_calendar', api_ver=2, interfaces=['task'])
Python
0.999999
@@ -3215,16 +3215,17 @@ single +c all. Fin
730489e4f6a7f3067ad67c16512c2cbcb97f3272
stop gap on astronmical solar zenith
bin/astronomical.py
bin/astronomical.py
""" astronomical.py, Sam Murphy (2017-04-27) Astronomical calculations (e.g. solar angles) for processing satellite imagery through Google Earth Engine. """ import ee class Astronomical: pi = 3.141592653589793 degToRad = pi / 180 # degress to radians radToDeg = 180 / pi # radians to degress def sin(x):return ee.Number(x).sin() def cos(x):return ee.Number(x).cos() def radians(x):return ee.Number(x).multiply(Astronomical.degToRad) def degrees(x):return ee.Number(x).multiply(Astronomical.radToDeg) def dayOfYear(date): jan01 = ee.Date.fromYMD(date.get('year'),1,1) doy = date.difference(jan01,'day').toInt().add(1) return doy def solarDeclination(date): """ Calculates the solar declination angle (radians) https://en.wikipedia.org/wiki/Position_of_the_Sun simple version.. d = ee.Number(.doy).add(10).multiply(0.017214206).cos().multiply(-23.44) a more accurate version used here.. """ doy = Astronomical.dayOfYear(date) N = ee.Number(doy).subtract(1) solstice = N.add(10).multiply(0.985653269) eccentricity = N.subtract(2).multiply(0.985653269).multiply(Astronomical.degToRad).sin().multiply(1.913679036) axial_tilt = ee.Number(-23.44).multiply(Astronomical.degToRad).sin() return solstice.add(eccentricity).multiply(Astronomical.degToRad).cos().multiply(axial_tilt).asin() def solarZenith(geom,date): """ Calculates solar zenith angle (degrees) https://en.wikipedia.org/wiki/Solar_zenith_angle """ latitude = Astronomical.radians(geom.centroid().coordinates().get(1)) d = Astronomical.solarDeclination(date) hourAngle = Astronomical.radians(date.get('hour').subtract(12).multiply(15)) sines = Astronomical.sin(latitude).multiply(Astronomical.sin(d)) cosines = Astronomical.cos(latitude).multiply(Astronomical.cos(d)).multiply(Astronomical.cos(hourAngle)) solar_z = sines.add(cosines).acos() return solar_z.multiply(Astronomical.radToDeg)
Python
0.000001
@@ -1934,16 +1934,41 @@ return +'need to check this out'# solar_z.
9e3becba368e5cc916c9af99a89e62e502d0a506
Fix syntax error in urls
greenland/urls.py
greenland/urls.py
"""greenland URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/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. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin import maps.views urlpatterns = [ url(r'^$', maps.views.index, name='index'), url(r'^admin/', admin.site.urls), url(r'^start/(?P<question_set_id>\d+)/', maps.views.start, name='start'), url(r'^choice/', maps.views.get_choice, name='choice'), url(r'^run/(?P<answer_set_id>\d+)/(?P<index>\d+)', maps.views.run, name='task'), url(r'^results/(?P<answer_set_id>\d+)', maps.views.results, name='results') url(r'^api/', include('maps.api.urls')) ]
Python
0.000254
@@ -1133,16 +1133,17 @@ esults') +, %0A url
4be61b5013f1a9d1400abbf64d37eb2290cb8e7e
Update soc/logic/site/sidebar.py to use parts of the "site map" in soc/logic/site/map.py to generate portions of the sidebar menu.
app/soc/logic/site/sidebar.py
app/soc/logic/site/sidebar.py
#!/usr/bin/python2.5 # # Copyright 2008 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. """Site-wide sidebar menu creation. """ __authors__ = [ '"Todd Larsen" <tlarsen@google.com>', ] from google.appengine.api import users from django.utils import datastructures from soc.logic import menu from soc.logic.site import id_user def buildUserSidebar(id=None, **ignored): """Returns a list of menu items for the User portion of the sidebar. Args: is_admin: Boolean indicating that current user is a "Developer" (site super-user); default is None, in which case id_user.isIdDeveloper() is called **ignored: other keyword arguments supplied to other sidebar builder functions, but ignored by this one """ if id is None: id = users.get_current_user() if not id: return [ # user is logged out, so User top-level menu doubles as a sign-in link menu.MenuItem( 'User (sign in)', value=users.create_login_url('/')), ] return [ # user is logged in, so User top-level menu doubles as a sign-out link menu.MenuItem( 'User (sign out)', value=users.create_logout_url('/'), sub_menu=menu.Menu(items=[ # edit existing (or create new) site-wide User profile menu.MenuItem( 'Site-wide Profile', value='/user/profile'), ] ) ), ] def buildSiteSidebar(is_admin=None, **ignored): """Returns a list of menu items for the Developer portion of the sidebar. Args: is_admin: Boolean indicating that current user is a "Developer" (site super-user); default is None, in which case id_user.isIdDeveloper() is called **ignored: other keyword arguments supplied to other sidebar builder functions, but ignored by this one """ if is_admin is None: is_admin = id_user.isIdDeveloper() if not is_admin: # user is either not logged in or not a "Developer", so return no menu return None return [ menu.MenuItem( # Site top-level menu doubles as link for editing site-wide settings 'Site', value='/site/home/edit', sub_menu=menu.Menu(items=[ menu.MenuItem( 'Search Site for a User', value='/site/user/lookup'), menu.MenuItem( 'List Users of Site', value='/site/user/list'), menu.MenuItem( 'Create a new Site User', value='/site/user/profile'), menu.MenuItem( 'List Documents on Site', value='/site/docs/list'), menu.MenuItem( 'Create a new Site Document', value='/site/docs/edit'), menu.MenuItem( 'List Sponsors', value='/site/sponsor/list'), menu.MenuItem( 'Create a new Sponsor', value='/site/sponsor/profile'), ] ) ), ] def buildProgramsSidebar(**unused): """Mock-up for Programs section of sidebar menu. Args: **unused: all keyword arguments are currently unused in this mock-up TODO: actually implement this once Program entities are present in the Datastore. """ return [ menu.MenuItem( 'Google Summer of Code', value='/program/gsoc2009/home', sub_menu=menu.Menu(items=[ menu.MenuItem( 'Community', value='/program/gsoc2009/community'), menu.MenuItem( 'FAQs', value='/program/gsoc2009/docs/faqs'), menu.MenuItem( 'Terms of Service', value='/program/gsoc2009/docs/tos'), ] ) ), menu.MenuItem( 'Google Highly Open Participation', value='/program/ghop2008/home', sub_menu=menu.Menu(items=[ menu.MenuItem( 'Community', value='/program/ghop2008/community'), menu.MenuItem( 'FAQs', value='/program/ghop2008/docs/faqs'), menu.MenuItem( 'Contest Rules', value='/program/ghop2008/docs/rules'), ] ) ), ] DEF_SIDEBAR_BUILDERS = [ buildUserSidebar, buildSiteSidebar, buildProgramsSidebar, ] def buildSidebar(path=None, builders=DEF_SIDEBAR_BUILDERS, **builder_args): """Calls all sidebar builders to construct the sidebar menu. Args: builders: list of functions that take context as a single argument; default is the list of sidebar builder functions present in soc.logic.site.sidebar **builder_args: keyword arguments passed to each sidebar builder function Returns: an soc.logic.menu.Menu object containing the sidebar menu items """ menu_items = [] # call each of the sidebar builders and append any menu items they create for builder in builders: built_items = builder(**builder_args) if built_items: menu_items.extend(built_items) # try to determine which of the menu items is the current path, to indicate # that it is "selected" if not path: # path argument not supplied, so see if an HTTP request object was # supplied in the builder_args request = builder_args.get('request') if request: # there is an HTTP request object, so use the path stored in it path = request.path if path: # TODO(tlarsen): scan through list and mark current request.path as "selected" pass return menu.Menu(items=menu_items)
Python
0.000001
@@ -846,16 +846,47 @@ id_user%0A +from soc.logic.site import map%0A %0A%0Adef bu @@ -1012,94 +1012,47 @@ i -s_admin: B +d: a G oo +g le -an indicating that curre + Accou nt +( user - is a %22Developer%22%0A (site super-user) +s.User) object ; de @@ -1078,39 +1078,40 @@ hich - case %0A -id_user.isIdDevelop +case users.get_current_us er() @@ -1323,571 +1323,82 @@ rn %5B -%0A # user is logged out, so User top-level menu doubles as a +map.user_ sign -- in - link%0A menu.MenuItem(%0A 'User (sign in)',%0A value=users.create_login_url('/')),%0A %5D%0A %0A return %5B%0A # user is logged in, so User top-level menu doubles as a sign-out link%0A menu.MenuItem(%0A 'User ( +.makeMenuItem()%5D%0A%0A return %5Bmap.user_ sign - out -)',%0A value=users.create_logout_url('/'),%0A sub_menu=menu.Menu(items=%5B%0A # edit existing (or create new) site-wide User profile%0A menu.MenuItem(%0A 'Site-wide Profile',%0A value='/user/profile'),%0A %5D%0A )%0A ),%0A +.makeMenuItem() %5D%0A%0A%0A @@ -2005,876 +2005,41 @@ rn %5B -%0A menu.MenuItem(%0A # Site top-level menu doubles as link for editing site-wide settings%0A 'Site',%0A value='/site/ +map.site_ home -/ +_ edit -',%0A sub_menu=menu.Menu(items=%5B%0A menu.MenuItem(%0A 'Search Site for a User',%0A value='/site/user/lookup'),%0A menu.MenuItem(%0A 'List Users of Site',%0A value='/site/user/list'),%0A menu.MenuItem(%0A 'Create a new Site User',%0A value='/site/user/profile'),%0A menu.MenuItem(%0A 'List Documents on Site',%0A value='/site/docs/list'),%0A menu.MenuItem(%0A 'Create a new Site Document',%0A value='/site/docs/edit'),%0A menu.MenuItem(%0A 'List Sponsors',%0A value='/site/sponsor/list'),%0A menu.MenuItem(%0A 'Create a new Sponsor',%0A value='/site/sponsor/profile'),%0A %5D%0A )%0A ),%0A +.makeMenuItem() %5D%0A%0A%0A
0a08c933375197bd630442e4c1f27c68fb2c8d0b
Reorder some things
groupvpn-webui.py
groupvpn-webui.py
import json import math import random import re import string from flask import Flask, redirect, render_template, request, url_for import ipaddress import wtforms as w PASSWORD_CHARS = string.ascii_lowercase + string.digits PASSWORD_LENGTH = 30 class IPNetworkField(w.Field): widget = w.widgets.TextInput() def __init__(self, label=None, validators=None, **kwargs): super(IPNetworkField, self).__init__(label, validators, **kwargs) def _value(self): if self.raw_data: return self.raw_data[0] elif self.data is not None: return str(self.data) else: return '' def process_formdata(self, valuelist): if valuelist: try: self.data = ipaddress.ip_network(valuelist[0]) except ValueError as e: self.data = None raise ValueError(e) class ConfigurationForm(w.Form): group_name = w.TextField("Group name", [w.validators.DataRequired()]) xmpp_host = w.TextField("XMPP host", [w.validators.DataRequired()]) machine_count = w.IntegerField( "Number of machines", [w.validators.NumberRange(min=2)]) ip_network = IPNetworkField( "IP network", default=ipaddress.ip_network(u"192.168.0.0/24"), description="Enter the network base address followed by either a " "netmask or a prefix length.") end_to_end_security = w.BooleanField("End-to-end security") def validate(self): return (super(ConfigurationForm, self).validate() and self.validate_enough_addresses()) def validate_enough_addresses(self): available_addresses = len(list(self.ip_network.data.hosts())) if available_addresses >= self.machine_count.data: return True else: self.ip_network.errors.append("Network only contains {} addresses" "".format(available_addresses)) return False app = Flask(__name__) app.jinja_env.trim_blocks = True app.jinja_env.keep_trailing_newline = True @app.route('/', methods=['GET']) def home(): return redirect(url_for('configurate')) @app.route('/configurate', methods=['GET', 'POST']) def configurate(): form = ConfigurationForm(request.form) if request.method == 'POST' and form.validate(): configs = make_configs(form.group_name.data, form.xmpp_host.data, form.ip_network.data, form.machine_count.data, form.end_to_end_security.data) return render_template('success.html', form=form, configs=configs) return render_template('configuration.html', form=form, post_url=url_for('configurate')) def make_configs(group_name, xmpp_host, ip_network, machine_count, end_to_end_security): max_digits = int(math.log10(machine_count - 1)) + 1 username_template = "{}{{:0{}}}".format(group_name, max_digits) ips = iter(ip_network.hosts()) configs = [] for n in range(1, machine_count + 1): username = re.sub(r'\W+', '_', username_template.format(n).lower()) password = ''.join(random.choice(PASSWORD_CHARS) for _ in range(PASSWORD_LENGTH)) data = { 'xmpp_username': username, 'xmpp_password': password, 'xmpp_host': xmpp_host, 'ip': str(next(ips)), } configs.append({'filename': "{}.json".format(username), 'data': json.dumps(data, indent=4)}) return configs if __name__ == '__main__': app.run(debug=True)
Python
0.000335
@@ -1991,805 +1991,8 @@ se%0A%0A -app = Flask(__name__)%0Aapp.jinja_env.trim_blocks = True%0Aapp.jinja_env.keep_trailing_newline = True%0A%0A@app.route('/', methods=%5B'GET'%5D)%0Adef home():%0A return redirect(url_for('configurate'))%0A%0A@app.route('/configurate', methods=%5B'GET', 'POST'%5D)%0Adef configurate():%0A form = ConfigurationForm(request.form)%0A if request.method == 'POST' and form.validate():%0A configs = make_configs(form.group_name.data, form.xmpp_host.data,%0A form.ip_network.data,%0A form.machine_count.data,%0A form.end_to_end_security.data)%0A return render_template('success.html', form=form, configs=configs)%0A return render_template('configuration.html', form=form,%0A post_url=url_for('configurate'))%0A%0A def @@ -2824,16 +2824,813 @@ onfigs%0A%0A +app = Flask(__name__)%0Aapp.jinja_env.trim_blocks = True%0Aapp.jinja_env.keep_trailing_newline = True%0A%0A@app.route('/', methods=%5B'GET'%5D)%0Adef home():%0A return redirect(url_for('configurate'))%0A%0A@app.route('/configurate', methods=%5B'GET', 'POST'%5D)%0Adef configurate():%0A form = ConfigurationForm(request.form)%0A if request.method == 'POST' and form.validate():%0A configs = make_configs(form.group_name.data, form.xmpp_host.data,%0A form.ip_network.data,%0A form.machine_count.data,%0A form.end_to_end_security.data)%0A return render_template('success.html', form=form, configs=configs)%0A return render_template('configuration.html', form=form,%0A post_url=url_for('configurate'))%0A%0A if __nam
8c59053b4fc367246c79a967fc8764d92742ed53
add ability to feed in guess to s21 inverse
kid_readout/analysis/resonator.py
kid_readout/analysis/resonator.py
from __future__ import division import numpy as np import matplotlib.pyplot as plt import lmfit import scipy.stats import scipy.optimize minimize = lmfit.minimize # To use different defaults, change these three import statements. from kid_readout.analysis.khalil import delayed_generic_s21 as default_model from kid_readout.analysis.khalil import delayed_generic_guess as default_guess from kid_readout.analysis.khalil import generic_functions as default_functions from kid_readout.analysis.khalil import bifurcation_s21, bifurcation_guess def fit_resonator(freq, s21, mask= None, errors=None, weight_by_errors=True, min_a = 0.08, fstat_thresh = 0.999): rr = Resonator(freq, s21, mask=mask, errors=errors, weight_by_errors=weight_by_errors) bif = Resonator(freq, s21, mask=mask, errors=errors, weight_by_errors=weight_by_errors, guess = bifurcation_guess, model = bifurcation_s21) fval = scipy.stats.f_value(np.sum(np.abs(rr.residual())**2), np.sum(np.abs(bif.residual())**2), rr.result.nfree, bif.result.nfree) fstat = scipy.stats.distributions.f.cdf(fval,rr.result.nfree,bif.result.nfree) aval = bif.result.params['a'].value aerr = bif.result.params['a'].stderr reasons = [] if aval <= aerr: prefer_bif = False reasons.append("Error on bifurcation parameter exceeds fitted value") else: if aval < min_a: prefer_bif = False reasons.append("Bifurcation parameter %f is less than minimum required %f" % (aval,min_a)) else: #not sure this is working right, so leave it out for now. if False:#fstat < fstat_thresh: prefer_bif = False reasons.append("F-statistic %f is less than threshold %f" % (fstat,fstat_thresh)) else: prefer_bif = True if not prefer_bif: print "Not using bifurcation model because:",(','.join(reasons)) return rr,bif,prefer_bif def fit_best_resonator(*args,**kwargs): rr,bif,prefer_bif = fit_resonator(*args,**kwargs) return (rr,bif)[prefer_bif] class Resonator(object): """ This class represents a single resonator. All of the model-dependent behavior is contained in functions that are supplied to the class. There is a little bit of Python magic that allows for easy access to the fit parameters and functions of only the fit parameters. The idea is that, given sweep data f and s21, r = Resonator(f, s21) should just work. Modify the import statements to change the defaults. """ def __init__(self, f, data, model=default_model, guess=default_guess, functions=default_functions, mask=None, errors=None, weight_by_errors=True): """ Instantiate a resonator using our current best model. Parameter model is a function S_21(params, f) that returns the modeled values of S_21. Parameter guess is a function guess(f, data) that returns a good-enough initial guess at all of the fit parameters. Parameter functions is a dictionary that maps keys that are valid Python variables to functions that take a Parameters object as their only argument. Parameter mask is a boolean array of the same length as f and data; only points f[mask] and data[mask] are used to fit the data. The default is to use all data. Use this to exclude glitches or resonances other than the desired one. """ self.f = f self.data = data self._model = model self._functions = functions if mask is None: if errors is None: self.mask = np.ones_like(data).astype(np.bool) else: self.mask = abs(errors) < np.median(abs(errors))*3 else: self.mask = mask self.errors = errors self.weight_by_errors = weight_by_errors self.fit(guess(f[self.mask], data[self.mask])) def __getattr__(self, attr): """ Return a fit parameter or value derived from the fit parameters. This allows syntax like r.Q_i after a fit has been performed. """ try: return self.result.params[attr].value except KeyError: pass try: return self._functions[attr](self.result.params) except KeyError: raise AttributeError("'{0}' object has no attribute '{1}'".format(self.__class__.__name__, attr)) def __dir__(self): return (dir(super(Resonator, self)) + self.__dict__.keys() + self.result.params.keys() + self._functions.keys()) def fit(self, initial): """ Fit S_21 using the data and model given at instantiation. Parameter initial is a Parameters object containing initial values. It is modified by lmfit. """ self.result = minimize(self.residual, initial,ftol=1e-6) def residual(self, params=None): """ This is the residual function used by lmfit. Only data where mask is True is used for the fit. Note that the residual needs to be purely real, and should *not* include abs. The minimizer needs the signs of the residuals to properly evaluate the gradients. """ # in the following, .view('float') will take a length N complex array # and turn it into a length 2*N float array. if params is None: params = self.result.params if self.errors is None or not self.weight_by_errors: return ((self.data[self.mask] - self.model(params)[self.mask]).view('float')) else: errors = self.errors[self.mask] if not np.iscomplexobj(errors): errors = errors.astype('complex') errors = errors + 1j*errors return ((self.data[self.mask] - self.model(params)[self.mask]).view('float'))/errors.view('float') def model(self, params=None, f=None): """ Return the model evaluated with the given parameters at the given frequencies. Defaults are the fit-derived params and the frequencies corresponding to the data. """ if params is None: params = self.result.params if f is None: f = self.f return self._model(params, f) def inverse(self, s21, params=None): """ Find the frequencies that correspond to points in the complex plane as given by the model """ if params is None: params = self.result.params def resid(f,s21): return np.abs(s21 - self._model(params, f)) isscalar = np.isscalar(s21) if isscalar: s21 = np.array([s21]) def _find_inverse(s21): x0 = self.f[np.argmin(np.abs(s21-self.data))] return scipy.optimize.fsolve(resid,x0,args=(s21,)) result = np.vectorize(_find_inverse)(s21) if isscalar: result = result[0] return result
Python
0
@@ -6578,32 +6578,43 @@ s21, params=None +,guess=None ):%0A %22%22%22%0A @@ -6990,24 +6990,58 @@ verse(s21):%0A + if guess is None:%0A @@ -7086,16 +7086,61 @@ data))%5D%0A + else:%0A x0 = guess%0A
4c6c41872b9a547917d81996f5f93d628c90216d
proper print
temperature-sparkpy.py
temperature-sparkpy.py
from __future__ import print_function import sys import math from operator import add from pyspark import SparkContext def is_number(s): try: float(s) return True except ValueError: return False def mapper(line): # positive or negative sign = line[87:88] # before the decimal point, remove leading zeros before_decimal = line[88:92].lstrip("0") # combine into string that can be cast to decimal degrees = sign + before_decimal + "." + line[92:93] if (is_number(degrees)): return float(degrees) else: return 0 def reducer(a, b): if a > b: return a else: return b if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: wordcount <file>", file=sys.stderr) exit(-1) sc = SparkContext(appName="PySparkTemperature") lines = sc.textFile(sys.argv[1], 1) counts = lines.map(mapper) \ .reduce(reducer) output = counts.collect() print ("Max " + output) sc.stop()
Python
0.997763
@@ -930,22 +930,22 @@ 1)%0A -c ou -nts +tput = lines @@ -1002,33 +1002,8 @@ -output = counts.collect() %0A
548edcb10ef949d394388282d052da36135982d7
Add coveralls support[5].
build.py
build.py
#!/usr/bin/python import os import shutil from subprocess import call import sys import platform cur_path = os.getcwd() build_path = os.getcwd() + "/build" if platform.system() == 'Windows': build_path = os.getcwd() + "/win_build" if 'test' in sys.argv: os.chdir(build_path) r = call(["make tests"], shell=True) exit(r) if 'docs' in sys.argv: call(["doxygen Doxyfile"], shell=True) call( ["xsltproc doc/xml/combine.xslt doc/xml/index.xml > doc/xml/all.xml"], shell=True) call(["python doxml2md.py doc/xml/all.xml"], shell=True) sys.exit(0) if 'all' in sys.argv or not os.path.exists(build_path): if os.path.exists(build_path): shutil.rmtree(build_path, ignore_errors=True) if not os.path.exists(build_path): os.mkdir(build_path) os.chdir(build_path) if platform.system() == 'Windows': call(["cmake"] + ['-G'] + ['Visual Studio 15 2017 Win64'] + sys.argv[2:] + [cur_path]) else: call(["cmake"] + sys.argv[2:] + [cur_path]) os.chdir(build_path) if platform.system() == 'Windows': make_result =\ call([r"MSBuild.exe"] + [r"/p:Configuration=Release"] + [r"/p:Machine=X64"] + ["PONOS.sln"], shell=True) else: make_result = call(["make -j8"], shell=True) call(["make install"], shell=True) if make_result != 0: sys.exit(1)
Python
0
@@ -1295,32 +1295,73 @@ %22%5D, shell=True)%0A + if %22-DTRAVIS=1%22 not in sys.argv:%0A call(%5B%22make
2a3ba559d3aaa191a58de6868ad019ab7f8b8189
Fix for building with under Windows
build.py
build.py
#!/usr/bin/python """ /* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ """ import sys import os from os.path import join, expanduser, exists import shutil import getopt import subprocess makecommand = "make" makefilename = "Makefile" def build(components,interpreter): for (name, dir, fatal) in components: print "***Building %s***"%name try: p = subprocess.Popen([makecommand, "-f", makefilename,"BH_PYTHON=%s"%interpreter], cwd=join(install_dir, dir)) err = p.wait() except KeyboardInterrupt: p.terminate() if fatal: if err != 0: print "A build error in %s is fatal. Exiting."%name sys.exit(-1) else: if err != 0: print "A build error in %s is not fatal. Continuing."%name def clean(components): for (name, dir, fatal) in components: print "***Cleaning %s***"%name try: p = subprocess.Popen([makecommand, "-f", makefilename, "clean"], cwd=join(install_dir, dir)) err = p.wait() except KeyboardInterrupt: p.terminate() def install(components,prefix,interpreter): for (name, dir, fatal) in components: print "***Installing %s***"%name try: p = subprocess.Popen([makecommand, "-f", makefilename,"install","BH_PYTHON=%s"%interpreter,"INSTALLDIR=%s"%prefix], cwd=join(install_dir, dir)) err = p.wait() except KeyboardInterrupt: p.terminate() if fatal: if err != 0: print "A build error in %s is fatal. Exiting."%name sys.exit(-1) else: if err != 0: print "A build error in %s is not fatal. Continuing."%name def install_config(prefix): if os.geteuid() == 0:#Root user HOME_CONFIG = "/etc/bohrium" else: HOME_CONFIG = join(join(expanduser("~"),".bohrium")) if not exists(HOME_CONFIG): os.mkdir(HOME_CONFIG) dst = join(HOME_CONFIG, "config.ini") src = join(install_dir,"config.ini.example") if not exists(dst): src_file = open(src, "r") src_str = src_file.read() src_file.close() dst_str = src_str.replace("/opt/bohrium",prefix) if sys.platform.startswith('darwin'): dst_str = dst_str.replace(".so",".dylib") dst_file = open(dst,"w") dst_file.write(dst_str) dst_file.close() print "Write default config file to %s"%(dst) if __name__ == "__main__": debug = False interactive = False if os.geteuid() == 0:#Root user prefix = "/opt/bohrium" else: prefix = join(join(expanduser("~"),".local")) interpreter = sys.executable try: install_dir = os.path.abspath(os.path.dirname(__file__)) except NameError: print "The build script cannot run interactively." sys.exit(-1) try: opts, args = getopt.gnu_getopt(sys.argv[1:],"d",["debug","prefix=","interactive","interpreter="]) except getopt.GetoptError, err: print str(err) sys.exit(2) for o, a in opts: if o in ("-d","--debug"): debug = True elif o in ("--prefix"): prefix = a elif o in ("--interactive"): interactive = True elif o in ("--interpreter"): interpreter = a else: assert False, "unhandled option" if sys.platform.startswith('win32'): makecommand="nmake" makefilename="Makefile.win" elif sys.platform.startswith('darwin'): makefilename="Makefile.osx" if interactive: import readline, glob def complete(text, state):#For autocomplete return (glob.glob(text+'*')+[None])[state] readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete) print "Please specify the installation directory:" answer = raw_input("[%s] "%prefix) if answer != "": prefix = expanduser(answer) try: cmd = args[0] except IndexError: print "No command given" print "" print "Known commands: build, clean, install, rebuild" sys.exit(-1) components = [\ ("OPCODES","core/codegen",True),\ ("INIPARSER","iniparser",True),\ ("CORE-BUNDLER", "core/bundler", True),\ ("CORE-COMPUTE", "core/compute", True),\ ("CORE", "core", True),\ ("VE-PRINT", "ve/print", False),\ ("VE-GPU", "ve/gpu", False),\ ("VE-SIMPLE", "ve/simple", True),\ ("VE-TILE", "ve/tile", False),\ ("VE-NAIVE", "ve/naive", False),\ ("VE-SCORE", "ve/score", False),\ ("VE-MCORE", "ve/mcore", False),\ ("VEM-NODE", "vem/node", True),\ ("VEM-CLUSTER", "vem/cluster", False),\ ("NumCIL", "bridge/NumCIL", False),\ ("BRIDGE-NUMPY", "bridge/numpy", True),\ ("USERFUNCS-ATLAS", "userfuncs/ATLAS", False),\ ("BHNUMPY", "bohrium", True) ] if cmd == "rebuild": clean(components) if cmd == "build" or cmd == "rebuild": build(components,interpreter) elif cmd == "clean": clean(components) elif cmd == "install": prefix = os.path.abspath(prefix) if exists(prefix): assert os.path.isdir(prefix),"The prefix points to an existing file" else: os.makedirs(prefix) install(components,prefix,interpreter) install_config(prefix); else: print "Unknown command: '%s'."%cmd print "" print "Known commands: build, clean, install"
Python
0
@@ -3249,32 +3249,73 @@ = False%0A if +not sys.platform.startswith('win32') and os.geteuid() ==
df41dcb3c8538e482bcc61f9817ce26569652b6b
build script set user data for git
build.py
build.py
# -*- coding: utf-8 -*- import os import sh from logging_service import __version__ as version def open_file(path): return open(path, 'r+') def get_git(repo_path): return sh.git.bake(_cwd=repo_path) def main(): file_build = open_file('build_version') lines = file_build.readlines() build_version_old = lines[0] build_version_new = str(int(build_version_old) + 1) lines = [line.replace(build_version_old, build_version_new) for line in lines] file_build.seek(0) file_build.writelines(lines) file_build.close() repo_path = os.path.abspath(os.path.dirname(__file__)) git = get_git(repo_path) git('add', '-u') new_tag_version = version + '-' + build_version_old feature_message = 'feat: auto tag ' + new_tag_version git('commit', '-m', feature_message) git('push', 'origin', 'master') git('tag', new_tag_version) git('push', 'origin', '--tags') if __name__ == '__main__': main()
Python
0.000001
@@ -91,16 +91,74 @@ ersion%0A%0A +GIT_USER = 'circle-ci'%0AGIT_EMAIL = 'vitomarti@gmail.com'%0A%0A %0Adef ope @@ -262,24 +262,162 @@ epo_path)%0A%0A%0A +def set_user_data_git(git):%0A git('config', '--global', 'user.email', GIT_EMAIL)%0A git('config', '--global', 'user.name', GIT_USER)%0A%0A%0A def main():%0A @@ -836,16 +836,44 @@ _path)%0A%0A + set_user_data_git(git)%0A%0A git(
54b8e07ac412e757fb32ebfa19b75ef8a72f6688
Print build path
build.py
build.py
#!/usr/bin/env python import sys import os from argparse import ArgumentParser from subprocess import check_call, check_output def ensure_tool(name): check_call(['which', name]) def build_and_publish(path, args): login_command = get_login_command(args) print >>sys.stderr, "Test anaconda.org login:" check_call(login_command) binfile = check_output(['conda', 'build', '--output', path]) binfile = binfile.strip() print >>sys.stderr, "conda build {}".format(path) check_call(['conda', 'build', path]) upload_command = "binstar upload --force {}".format(binfile) login_and_upload_command = "{} && {}".format(login_command, upload_command) print >>sys.stderr, "Login to binstar and upload" check_call(login_and_upload_command) def get_login_command(args): return ("binstar login --hostname {hostname} " " --username {username} --password {password}")\ .format( hostname='https://api.anaconda.org', username=args.username, password=args.password, ) def get_conda_recipes_dir(project): # make sure the project has a conda recipes folder conda_recipes_dir = os.path.join(project, 'conda') if not os.path.isdir(conda_recipes_dir): sys.exit('no such dir: {}'.format(conda_recipes_dir)) return conda_recipes_dir def conda_paths(conda_recipes_dir): for name in sorted(os.listdir(conda_recipes_dir)): yield os.path.join(conda_recipes_dir, name) def main(): parser = ArgumentParser() parser.add_argument('-u', '--username', required=True) parser.add_argument('-P', '--password', required=True) parser.add_argument('-p', '--project', required=True) parser.add_argument('-s', '--site', required=False, default=None) args = parser.parse_args() # make sure we have a conda environment ensure_tool('conda') ensure_tool('binstar') conda_recipes_dir = get_conda_recipes_dir(args.project) for conda_path in conda_paths(conda_recipes_dir): build_and_publish(conda_path, args) return 0 if __name__ == '__main__': sys.exit(main())
Python
0.000001
@@ -436,16 +436,72 @@ .strip() +%0A print %3E%3Esys.stderr, %22build path %7B%7D%22.format(binfile) %0A%0A pr
d0315abc9ace94d767a1533cd7f2b669381c2e50
tag bug fixed
kwueBackend/kwue/models/models.py
kwueBackend/kwue/models/models.py
from django.db import models from unixtimestampfield.fields import UnixTimeStampField from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from mptt.models import MPTTModel, TreeForeignKey from kwue.helper_functions.time_helpers import show_date import time class IngredientModel(models.Model): ingredient_name = models.CharField(max_length=100, primary_key=True) def __str__(self): return self.ingredient_name+" " class UserModel(models.Model): user_id = models.AutoField(primary_key=True) user_name = models.TextField() user_nick = models.TextField(blank=True) user_email_address = models.EmailField() user_password = models.CharField(max_length=25) user_image = models.URLField(default='',blank=True) user_type = models.BooleanField(default=False) ###### False is normal user. unwanted_ingredients = models.ManyToManyField(IngredientModel, related_name='wantedIngs', blank=True) wanted_ingredients = models.ManyToManyField(IngredientModel, related_name='unwantedIngs', blank=True) ####################### protein_lower_bound = models.FloatField(default=0) fat_lower_bound = models.FloatField(default=0) carbohydrate_lower_bound = models.FloatField(default=0) calorie_lower_bound = models.FloatField(default=0) sugar_lower_bound = models.FloatField(default=0) ######################### protein_upper_bound = models.FloatField(default=1000) fat_upper_bound = models.FloatField(default=100000) carbohydrate_upper_bound = models.FloatField(default=100000) calorie_upper_bound = models.FloatField(default=10000) sugar_upper_bound = models.FloatField(default=10000) def __str__(self): return self.user_name class FoodModel(models.Model): food_id = models.AutoField(primary_key=True) food_description = models.CharField(max_length=300) food_name = models.TextField() food_image = models.URLField(blank=True) food_owner = models.ForeignKey(UserModel, on_delete=models.CASCADE) food_rate = models.FloatField(default=0) food_rate_count = models.IntegerField(default=0) food_recipe = models.TextField(default=0) ingredient_list = models.ManyToManyField(IngredientModel) protein_value = models.FloatField(default=0) fat_value = models.FloatField(default=0) carbohydrate_value = models.FloatField(default=0) fiber_value = models.FloatField(default=0) calorie_value = models.FloatField(default=0) sugar_value = models.FloatField(default=0) serving_weight_grams = models.FloatField(default=0) vitamin_A = models.FloatField(default=0) vitamin_C = models.FloatField(default=0) vitamin_D = models.FloatField(default=0) vitamin_E = models.FloatField(default=0) vitamin_K = models.FloatField(default=0) thiamin = models.FloatField(default=0) riboflavin = models.FloatField(default=0) niacin = models.FloatField(default=0) vitamin_B6 = models.FloatField(default=0) folatem = models.FloatField(default=0) vitamin_B12 = models.FloatField(default=0) pantothenic_acid = models.FloatField(default=0) choline = models.FloatField(default=0) calcium = models.FloatField(default=0) copper = models.FloatField(default=0) flouride = models.FloatField(default=0) iron_Fe = models.FloatField(default=0) magnesium = models.FloatField(default=0) manganese = models.FloatField(default=0) sodium_Na = models.FloatField(default=0) phosphorus = models.FloatField(default=0) selenium = models.FloatField(default=0) zinc = models.FloatField(default=0) def __str__(self): return self.food_name class TagModel(models.Model): tag_id = models.AutoField(primary_key=True) tag_label = models.TextField(blank=True) semantic_tag_item = models.TextField(blank=True) semantic_tag_item_label = models.TextField(blank=True) semantic_tag_item_description = models.TextField(blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, default=None, blank=True) tagged_object_id = models.PositiveIntegerField() tagged_object = GenericForeignKey('content_type', "tagged_object_id") def __str__(self): if self.content_type.model=="usermodel": return str(self.tagged_object.user_name) + ' <<<===== ' + self.semantic_tag_item_label elif self.content_type.model=="food_model": return str(self.tagged_object.food_name) + ' <<<===== ' + self.semantic_tag_item_label else: return "Tagged Object is deleted" class CommentModel(MPTTModel): comment_id = models.AutoField(primary_key=True) comment_text = models.TextField(null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, default=None, blank=True) commented_object_id = models.PositiveIntegerField() commented_object = GenericForeignKey('content_type', 'commented_object_id') comment_date = UnixTimeStampField(auto_now_add=True) comment_image = models.URLField(blank=True) comment_vote = models.IntegerField(default=0) comment_owner = models.ForeignKey(UserModel, on_delete=models.CASCADE) parent = TreeForeignKey('self', null=True, blank=True, related_name='children') def save(self): if self.parent is not None: self.commented_object = self.parent super().save(self) def __str__(self): return self.comment_text class MPTTMeta: level_attr = 'mptt_level' order_insertion_by = ['comment_text'] class ListModel(models.Model): list_id = models.AutoField(primary_key=True) list_menu = models.BooleanField() list_owner = models.ForeignKey(UserModel, on_delete=models.CASCADE) list_name = models.TextField() list_description = models.TextField() list_follower = models.ManyToManyField(UserModel, related_name="followers", blank=True) list_content = models.ManyToManyField(FoodModel, related_name="foods", blank=True) def __str__(self): return self.list_name class ConsumptionHistory(models.Model): history_id = models.AutoField(primary_key=True) user = models.ForeignKey(UserModel, on_delete=models.CASCADE) food = models.ForeignKey(FoodModel) date = models.IntegerField(default=time.time(), editable=True) def __str__(self): return show_date(self.date)
Python
0.000001
@@ -4453,17 +4453,16 @@ l==%22food -_ model%22:%0A
00e68cff5e7d370e137383b4e0c3c774ddb4c929
update metadata
l10n_br_sale_stock/__openerp__.py
l10n_br_sale_stock/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################### # # # Copyright (C) 2013 Raphaël Valyi - Akretion # # Copyright (C) 2013 Renato Lima - Akretion # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # # # You should have received a copy of the GNU Affero General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### { 'name': 'Brazilian Localization Sales and Warehouse', 'category': 'Localisation', 'license': 'AGPL-3', 'author': 'Akretion, ,Odoo Community Association (OCA)', 'website': 'http://odoo-brasil.org', 'version': '8.0.1.0.0', 'depends': [ 'sale_stock', 'l10n_br_sale_product', 'l10n_br_stock_account', ], 'data': [ 'data/l10n_br_sale_stock_data.xml', 'views/sale_stock_view.xml', ], 'demo': [ 'l10n_br_sale_stock_demo.xml', <<<<<<< HEAD ======= #'test/sale_order_demo.yml' >>>>>>> comment data file ], 'test': [ 'test/sale_order_demo.yml' ], 'installable': True, 'auto_install': True, }
Python
0.000001
@@ -1975,91 +1975,8 @@ l',%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0A=======%0A #'test/sale_order_demo.yml'%0A%3E%3E%3E%3E%3E%3E%3E comment data file%0A
3d52e82a295c7c7d6b77d81a1d2c6ac0929bb120
make sqlitecache bundable.
sqlite_cache/__init__.py
sqlite_cache/__init__.py
from sqlite_cache.core import SQLiteCache # pragma: no cover
Python
0
@@ -2,20 +2,48 @@ rom -sqlite_cache +__future__ import absolute_import%0A%0Afrom .cor
05d7bf2dd9a92ade3ca0cf909cdb49be0c67cb23
use python3 in safe_exec
codejail/safe_exec.py
codejail/safe_exec.py
"""Safe execution of untrusted Python code.""" import six import logging import os.path import shutil import sys import textwrap try: import simplejson as json except ImportError: import json from codejail import jail_code from codejail.util import temp_directory, change_directory log = logging.getLogger(__name__) # Flags to let developers temporarily change some behavior in this file. # Set this to True to log all the code and globals being executed. LOG_ALL_CODE = False # Set this to True to use the unsafe code, so that you can debug it. ALWAYS_BE_UNSAFE = False class SafeExecException(Exception): """ Python code running in the sandbox has failed. The message will be the stdout of the sandboxed process, which will usually contain the original exception message. """ pass def safe_exec(code, globals_dict, files=None, python_path=None, slug=None): """ Execute code as "exec" does, but safely. `code` is a string of Python code. `globals_dict` is used as the globals during execution. Modifications the code makes to `globals_dict` are reflected in the dictionary on return. `files` is a list of file paths, either files or directories. They will be copied into the temp directory used for execution. No attempt is made to determine whether the file is appropriate or safe to copy. The caller must determine which files to provide to the code. `python_path` is a list of directory paths. They will be copied just as `files` are, but will also be added to `sys.path` so that modules there can be imported. `slug` is an arbitrary string, a description that's meaningful to the caller, that will be used in log messages. Returns None. Changes made by `code` are visible in `globals_dict`. If the code raises an exception, this function will raise `SafeExecException` with the stderr of the sandbox process, which usually includes the original exception message and traceback. """ the_code = [] files = list(files or ()) the_code.append(textwrap.dedent( """ import sys try: import simplejson as json except ImportError: import json """ # We need to prevent the sandboxed code from printing to stdout, # or it will pollute the json we print there. This isn't a # security concern (they can put any values in the json output # anyway, either by writing to sys.__stdout__, or just by defining # global values), but keeps accidents from happening. """ class DevNull(object): def write(self, *args, **kwargs): pass sys.stdout = DevNull() """ # Read the code and the globals from the stdin. """ code, g_dict = json.load(sys.stdin) """)) for pydir in python_path or (): pybase = os.path.basename(pydir) the_code.append("sys.path.append(%r)\n" % pybase) files.append(pydir) the_code.append(textwrap.dedent( # Execute the sandboxed code. """ exec code in g_dict """ # Clean the globals for sending back as JSON over stdout. """ ok_types = ( type(None), int, long, float, str, unicode, list, tuple, dict ) bad_keys = ("__builtins__",) def jsonable(v): if not isinstance(v, ok_types): return False try: json.dumps(v) except Exception: return False return True g_dict = { k:v for k,v in g_dict.iteritems() if jsonable(v) and k not in bad_keys } """ # Write the globals back to the calling process. """ json.dump(g_dict, sys.__stdout__) """)) stdin = json.dumps([code, json_safe(globals_dict)]) jailed_code = "".join(the_code) # Turn this on to see what's being executed. if LOG_ALL_CODE: # pragma: no cover log.debug("Jailed code: %s", jailed_code) log.debug("Exec: %s", code) log.debug("Stdin: %s", stdin) res = jail_code.jail_code( "python", code=jailed_code, stdin=stdin, files=files, slug=slug, ) if res.status != 0: raise SafeExecException( "Couldn't execute jailed code: %s" % res.stderr ) globals_dict.update(json.loads(res.stdout)) def json_safe(d): """ Return only the JSON-safe part of d. Used to emulate reading data through a serialization straw. """ ok_types = (type(None), int, float, str, list, tuple, dict) if not six.PY3: ok_types += (long, unicode) bad_keys = ("__builtins__",) jd = {} for k, v in d.items(): if not isinstance(v, ok_types): continue if k in bad_keys: continue try: # Python's JSON encoder will produce output that # the JSON decoder cannot parse if the input string # contains unicode "unpaired surrogates" (only on Linux) # To test for this, we try decoding the output and check # for a ValueError json.loads(json.dumps(v)) # Also ensure that the keys encode/decode correctly json.loads(json.dumps(k)) except (TypeError, ValueError): continue else: jd[k] = v return json.loads(json.dumps(jd)) def not_safe_exec(code, globals_dict, files=None, python_path=None, slug=None): """ Another implementation of `safe_exec`, but not safe. This can be swapped in for debugging problems in sandboxed Python code. This is not thread-safe, due to temporarily changing the current directory and modifying sys.path. """ g_dict = json_safe(globals_dict) with temp_directory() as tmpdir: with change_directory(tmpdir): # Copy the files here. for filename in files or (): dest = os.path.join(tmpdir, os.path.basename(filename)) shutil.copyfile(filename, dest) original_path = sys.path if python_path: sys.path.extend(python_path) try: six.exec_(code, g_dict) except Exception as e: # Wrap the exception in a SafeExecException, but we don't # try here to include the traceback, since this is just a # substitute implementation. msg = "{0.__class__.__name__}: {0!s}".format(e) raise SafeExecException(msg) finally: sys.path = original_path globals_dict.update(json_safe(g_dict)) # If the developer wants us to be unsafe (ALWAYS_BE_UNSAFE), or if there isn't # a configured jail for Python, then we'll be UNSAFE. UNSAFE = ALWAYS_BE_UNSAFE or not jail_code.is_configured("python") if UNSAFE: # pragma: no cover # Make safe_exec actually call not_safe_exec, but log that we're doing so. def safe_exec(*args, **kwargs): # pylint: disable=E0102 """An actually-unsafe safe_exec, that warns it's being used.""" # Because it would be bad if this function were used in production, # let's log a warning when it is used. Developers can can live with # one more log line. slug = kwargs.get('slug', None) log.warning("Using codejail/safe_exec.py:not_safe_exec for %s", slug) return not_safe_exec(*args, **kwargs)
Python
0.000083
@@ -3144,23 +3144,22 @@ exec - +( code - in +, g_dict +) %0A @@ -3298,14 +3298,8 @@ int, - long, flo @@ -3310,17 +3310,8 @@ str, - unicode, lis @@ -3669,12 +3669,8 @@ ict. -iter item
962322fd385bcfcc670ead757190d37955ccda14
improve logging and add ros params
lg_earth/src/lg_earth/kmlalive.py
lg_earth/src/lg_earth/kmlalive.py
import subprocess import rospy import rosservice import traceback import sys class KmlAlive: def __init__(self, earth_proc): self.earth_proc = earth_proc rospy.loginfo("XXX starting KMLALIVE process") rospy.Timer(rospy.Duration(10), self.keep_alive, oneshot=True) # only restart when worked is true, otherwise # it may have never worked self.worked = False def keep_alive(self, *args, **kwargs): try: self._keep_alive(args, kwargs) except Exception as e: rospy.logerr("exception was {} {} {}".format(e, traceback.format_exc(), sys.exc_info()[0])) rospy.sleep(1) self.keep_alive(args, kwargs) def _keep_alive(self, *args, **kwargs): rospy.logerr("XXX in first keep_alive") loop_timeout = 1 counter = 0 with open('/dev/null', 'w') as dev_null: while not rospy.is_shutdown(): try: pid = self.earth_proc.proc.watcher.proc.pid except AttributeError as e: counter = 0 rospy.logwarn("Earth proc doesn't exist {}".format(e)) rospy.sleep(loop_timeout) continue if '/kmlsync/state' in rosservice.get_service_list(): cmd = "lsof -Pn -p {} -a -i @127.0.0.1:8765".format(pid).split(' ') ret_value = subprocess.call( cmd, stdout=dev_null, stderr=dev_null, close_fds=True ) if ret_value == 0: self.worked = True counter = 0 else: counter += 1 rospy.logerr("XXX found non zero value for {} counter at {}".format(pid, counter)) if (counter > 5 and self.worked) or counter > 60: rospy.logerr("XXX RELAUNCHING") self.earth_proc.handle_soft_relaunch() counter = 0 self.worked = False else: rospy.logerr("no kml sync state found") rospy.sleep(loop_timeout)
Python
0
@@ -216,16 +216,151 @@ ocess%22)%0A + self.timeout_period = rospy.get_param(~timeout_period, 5)%0A self.initial_timeout = rospy.get_param(~initial_timeout, 60)%0A @@ -2089,17 +2089,35 @@ unter %3E -5 +self.timeout_period and sel @@ -2139,18 +2139,36 @@ unter %3E -60 +self.initial_timeout :%0A @@ -2218,17 +2218,70 @@ AUNCHING -%22 + worked: %7B%7D counter: %7B%7D%22.format(self.worked, counter) )%0A
f672da20640b761d47d5c15d791e06fc5e25fd35
Fix Deprecation warning in Django 1.9
bootstrap3/utils.py
bootstrap3/utils.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re from django.forms.widgets import flatatt from django.template import Variable, VariableDoesNotExist, Template, Context from django.template.base import FilterExpression, kwarg_re, TemplateSyntaxError from django.template.loader import get_template from django.utils.safestring import mark_safe try: from django.utils.html import format_html except ImportError: from .legacy import format_html_pre_18 as format_html from .text import text_value # RegEx for quoted string QUOTED_STRING = re.compile(r'^["\'](?P<noquotes>.+)["\']$') def handle_var(value, context): """ Handle template tag variable """ # Resolve FilterExpression and Variable immediately if isinstance(value, FilterExpression) or isinstance(value, Variable): return value.resolve(context) # Return quoted strings unquoted # http://djangosnippets.org/snippets/886 stringval = QUOTED_STRING.search(value) if stringval: return stringval.group('noquotes') # Resolve variable or return string value try: return Variable(value).resolve(context) except VariableDoesNotExist: return value def parse_token_contents(parser, token): """ Parse template tag contents """ bits = token.split_contents() tag = bits.pop(0) args = [] kwargs = {} asvar = None if len(bits) >= 2 and bits[-2] == 'as': asvar = bits[-1] bits = bits[:-2] if len(bits): for bit in bits: match = kwarg_re.match(bit) if not match: raise TemplateSyntaxError( 'Malformed arguments to tag "{}"'.format(tag)) name, value = match.groups() if name: kwargs[name] = parser.compile_filter(value) else: args.append(parser.compile_filter(value)) return { 'tag': tag, 'args': args, 'kwargs': kwargs, 'asvar': asvar, } def split_css_classes(css_classes): """ Turn string into a list of CSS classes """ classes_list = text_value(css_classes).split(' ') return [c for c in classes_list if c] def add_css_class(css_classes, css_class, prepend=False): """ Add a CSS class to a string of CSS classes """ classes_list = split_css_classes(css_classes) classes_to_add = [c for c in split_css_classes(css_class) if c not in classes_list] if prepend: classes_list = classes_to_add + classes_list else: classes_list += classes_to_add return ' '.join(classes_list) def remove_css_class(css_classes, css_class): """ Remove a CSS class from a string of CSS classes """ remove = set(split_css_classes(css_class)) classes_list = [c for c in split_css_classes(css_classes) if c not in remove] return ' '.join(classes_list) def render_link_tag(url, rel='stylesheet', media=None): """ Build a link tag """ attrs = { 'href': url, 'rel': rel, } if media: attrs['media'] = media return render_tag('link', attrs=attrs, close=False) def render_tag(tag, attrs=None, content=None, close=True): """ Render a HTML tag """ builder = '<{tag}{attrs}>{content}' if content or close: builder += '</{tag}>' return format_html( builder, tag=tag, attrs=mark_safe(flatatt(attrs)) if attrs else '', content=text_value(content), ) def render_template_to_unicode(template, context=None): """ Render a Template to unicode """ if not isinstance(template, Template): template = get_template(template) if context is None: context = {} return template.render(Context(context))
Python
0.000067
@@ -69,16 +69,43 @@ ort re%0A%0A +from django import VERSION%0A from dja @@ -169,17 +169,82 @@ ort -Variable, +(Context, RequestContext, Template, Variable,%0A Var @@ -264,27 +264,9 @@ xist -, Template, Context +) %0Afro @@ -295,16 +295,17 @@ import +( FilterEx @@ -317,18 +317,8 @@ ion, - kwarg_re, Tem @@ -333,16 +333,61 @@ taxError +,%0A kwarg_re) %0Afrom dj @@ -474,16 +474,46 @@ k_safe%0A%0A +from .text import text_value%0A%0A try:%0A @@ -638,37 +638,8 @@ ml%0A%0A -from .text import text_value%0A %0A%0A# @@ -3774,24 +3774,70 @@ ode%0A %22%22%22%0A + if context is None:%0A context = %7B%7D%0A%0A if not i @@ -3917,48 +3917,77 @@ -if context is None:%0A + if VERSION %3E (1, 8):%0A return template.render( context - = %7B%7D +)%0A %0A @@ -4027,8 +4027,9 @@ ontext)) +%0A
67d421a5c0e59554f0e4b8a94250668194789205
Fix source in pool instrumentation.
inbox/ignition.py
inbox/ignition.py
import time import weakref import gevent from socket import gethostname from urllib import quote_plus as urlquote from sqlalchemy import create_engine, event from inbox.sqlalchemy_ext.util import ForceStrictMode from inbox.config import config from inbox.util.stats import statsd_client from nylas.logging import get_logger, find_first_app_frame_and_name from warnings import filterwarnings filterwarnings('ignore', message='Invalid utf8mb4 character string') log = get_logger() DB_POOL_SIZE = config.get_required('DB_POOL_SIZE') # Sane default of max overflow=5 if value missing in config. DB_POOL_MAX_OVERFLOW = config.get('DB_POOL_MAX_OVERFLOW') or 5 DB_POOL_TIMEOUT = config.get('DB_POOL_TIMEOUT') or 60 pool_tracker = weakref.WeakKeyDictionary() # See # https://github.com/PyMySQL/mysqlclient-python/blob/master/samples/waiter_gevent.py def gevent_waiter(fd, hub=gevent.hub.get_hub()): hub.wait(hub.loop.io(fd, 1)) def build_uri(username, password, hostname, port, database_name): uri_template = 'mysql+mysqldb://{username}:{password}@{hostname}' \ ':{port}/{database_name}?charset=utf8mb4' return uri_template.format(username=urlquote(username), password=urlquote(password), hostname=urlquote(hostname), port=port, database_name=urlquote(database_name)) def engine(database_name, database_uri, pool_size=DB_POOL_SIZE, max_overflow=DB_POOL_MAX_OVERFLOW, pool_timeout=DB_POOL_TIMEOUT, echo=False): engine = create_engine(database_uri, listeners=[ForceStrictMode()], isolation_level='READ COMMITTED', echo=False, pool_size=pool_size, pool_timeout=pool_timeout, pool_recycle=3600, max_overflow=max_overflow, connect_args={'charset': 'utf8mb4', 'waiter': gevent_waiter}) @event.listens_for(engine, 'checkout') def receive_checkout(dbapi_connection, connection_record, connection_proxy): '''Log checkedout and overflow when a connection is checked out''' hostname = gethostname().replace(".", "-") process_name = str(config.get("PROCESS_NAME", "unknown")) statsd_client.gauge(".".join( ["dbconn", database_name, hostname, process_name, "checkedout"]), connection_proxy._pool.checkedout()) statsd_client.gauge(".".join( ["dbconn", database_name, hostname, process_name, "overflow"]), connection_proxy._pool.overflow()) # Keep track of where and why this connection was checked out. log = get_logger() context = log._context._dict.copy() f, name = find_first_app_frame_and_name(ignores=['sqlalchemy', 'inbox.ignition']) source = '{}:{}'.format(name, f.f_lineno) pool_tracker[dbapi_connection] = { 'source': source, 'context': context, 'checkedout_at': time.time() } @event.listens_for(engine, 'checkin') def receive_checkin(dbapi_connection, connection_record): if dbapi_connection in pool_tracker: del pool_tracker[dbapi_connection] return engine class EngineManager(object): def __init__(self, databases, users, include_disabled=False): self.engines = {} keys = set() schema_names = set() for database in databases: hostname = database['HOSTNAME'] port = database['PORT'] username = users[hostname]['USER'] password = users[hostname]['PASSWORD'] for shard in database['SHARDS']: schema_name = shard['SCHEMA_NAME'] key = shard['ID'] # Perform some sanity checks on the configuration. assert isinstance(key, int) assert key not in keys, \ 'Shard key collision: key {} is repeated'.format(key) assert schema_name not in schema_names, \ 'Shard name collision: {} is repeated'.format(schema_name) keys.add(key) schema_names.add(schema_name) if shard.get('DISABLED') and not include_disabled: log.info('Not creating engine for disabled shard', schema_name=schema_name, hostname=hostname, key=key) continue uri = build_uri(username=username, password=password, database_name=schema_name, hostname=hostname, port=port) self.engines[key] = engine(schema_name, uri) def shard_key_for_id(self, id_): return id_ >> 48 def get_for_id(self, id_): return self.engines[self.shard_key_for_id(id_)] engine_manager = EngineManager(config.get_required('DATABASE_HOSTS'), config.get_required('DATABASE_USERS')) def init_db(engine, key=0): """ Make the tables. This is called only from bin/create-db, which is run during setup. Previously we allowed this to run everytime on startup, which broke some alembic revisions by creating new tables before a migration was run. From now on, we should ony be creating tables+columns via SQLalchemy *once* and all subsequent changes done via migration scripts. """ from inbox.models.base import MailSyncBase from sqlalchemy import event, DDL # Hopefully setting auto_increment via an event listener will make it safe # to execute this function multiple times. # STOPSHIP(emfree): verify increment = (key << 48) + 1 for table in MailSyncBase.metadata.tables.values(): event.listen(table, 'after_create', DDL('ALTER TABLE {tablename} AUTO_INCREMENT={increment}'. format(tablename=table, increment=increment))) MailSyncBase.metadata.create_all(engine) def verify_db(engine, schema, key): from inbox.models.base import MailSyncBase query = """SELECT AUTO_INCREMENT from information_schema.TABLES where table_schema='{}' AND table_name='{}';""" verified = set() for table in MailSyncBase.metadata.sorted_tables: increment = engine.execute(query.format(schema, table)).scalar() if increment is not None: assert (increment >> 48) == key, \ 'table: {}, increment: {}, key: {}'.format( table, increment, key) else: # We leverage the following invariants about the sync # schema to make the assertion below: one, in the sync # schema, a table's id column is assigned the # auto_increment since we use this column as the # primary_key. Two, the only tables that have a None # auto_increment are inherited tables (like '*account', # '*thread' '*actionlog', 'recurringevent*'), because # their id column is instead a foreign_key on their # parent's id column. parent = list(table.columns['id'].foreign_keys)[0].column.table assert parent in verified verified.add(table)
Python
0
@@ -3097,16 +3097,90 @@ gnition' +,%0A 'nylas.logging' %5D)%0A
cd19d61dcc3290f323e449a42ada0e351e1b4819
Fix bug preventing EAS accounts from being authed.
inbox/util/url.py
inbox/util/url.py
from dns.resolver import Resolver, NoNameservers from urllib import urlencode import logging as log import re # http://www.regular-expressions.info/email.html EMAIL_REGEX = re.compile(r'[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}', re.IGNORECASE) # Use Google's Public DNS server (8.8.8.8) dns_resolver = Resolver() dns_resolver.nameservers = ['8.8.8.8'] # YAHOO: # https://en.wikipedia.org/wiki/Yahoo!_Mail#Email_domains yahoo_mail_domains = [ 'yahoo.com.ar', # Argentina 'yahoo.com.au', # Australia 'yahoo.at', # Austria 'yahoo.be', # Belgium (French) 'yahoo.fr', 'yahoo.be', # Belgium (Dutch) 'yahoo.nl', 'yahoo.com.br', # Brazil 'yahoo.ca', # Canada (English) 'yahoo.en', 'yahoo.ca', # Canada (French) 'yahoo.fr', 'yahoo.com.cn', # China 'yahoo.cn', 'yahoo.com.co', # Colombia 'yahoo.cz', # Czech Republic 'yahoo.dk', # Denmark 'yahoo.fi', # Finland 'yahoo.fr', # France 'yahoo.de', # Germany 'yahoo.gr', # Greece 'yahoo.com.hk', # Hong Kong 'yahoo.hu', # Hungary 'yahoo.co.in', # India 'yahoo.in', # Indonesia 'yahoo.ie', # Ireland 'yahoo.co.il', # Israel 'yahoo.it', # Italy 'yahoo.co.jp', # Japan 'yahoo.com.my', # Malaysia 'yahoo.com.mx', # Mexico 'yahoo.ae', # Middle East 'yahoo.nl', # Netherlands 'yahoo.co.nz', # New Zealand 'yahoo.no', # Norway 'yahoo.com.ph', # Philippines 'yahoo.pl', # Poland 'yahoo.pt', # Portugal 'yahoo.ro', # Romania 'yahoo.ru', # Russia 'yahoo.com.sg', # Singapore 'yahoo.co.za', # South Africa 'yahoo.es', # Spain 'yahoo.se', # Sweden 'yahoo.ch', # Switzerland (French) 'yahoo.fr', 'yahoo.ch', # Switzerland (German) 'yahoo.de', 'yahoo.com.tw', # Taiwan 'yahoo.co.th', # Thailand 'yahoo.com.tr', # Turkey 'yahoo.co.uk', # United Kingdom 'yahoo.com', # United States 'yahoo.com.vn', # Vietnam 'ymail.com', # Newly added! 'rocketmail.com', ] # http://www.ysmallbizstatus.com/status/archives/13024 yahoo_smallbiz_mx_servers = [ 'mx-biz.mail.am0.yahoodns.net', 'mx1.biz.mail.yahoo.com.', 'mx5.biz.mail.yahoo.com.', 'mxvm2.mail.yahoo.com.', 'mx-van.mail.am0.yahoodns.net' ] # GOOGLE gmail_mx_servers = [ # Google apps for your domain 'aspmx.l.google.com.', 'aspmx2.googlemail.com.', 'aspmx3.googlemail.com.', 'aspmx4.googlemail.com.', 'aspmx5.googlemail.com.', 'alt1.aspmx.l.google.com.', 'alt2.aspmx.l.google.com.', 'alt3.aspmx.l.google.com.', 'alt4.aspmx.l.google.com.', 'aspmx1.aspmx.l.google.com.', 'aspmx2.aspmx.l.google.com.', 'aspmx3.aspmx.l.google.com.', 'aspmx4.aspmx.l.google.com.', # Gmail 'gmail-smtp-in.l.google.com.', 'alt1.gmail-smtp-in.l.google.com.', 'alt2.gmail-smtp-in.l.google.com.', 'alt3.gmail-smtp-in.l.google.com.', 'alt4.gmail-smtp-in.l.google.com.' ] class InvalidEmailAddressError(Exception): pass class NotSupportedError(Exception): pass def email_supports_gmail(domain): # Must have Gmail or Google Apps MX records is_valid = True try: answers = dns_resolver.query(domain, 'MX') # All relay servers must be gmail for rdata in answers: if not str(rdata.exchange).lower() in gmail_mx_servers: is_valid = False except NoNameservers: log.error("NoNameservers error") is_valid = False return is_valid def email_supports_yahoo(domain): # Must be a Yahoo mail domain if domain in yahoo_mail_domains: return True # Or have a Yahoo small business MX record is_valid = True try: answers = dns_resolver.query(domain, 'MX') for rdata in answers: if not str(rdata.exchange).lower() in yahoo_smallbiz_mx_servers: is_valid = False except NoNameservers: log.error("NoNameservers error") is_valid = False return is_valid def provider_from_address(email_address): if not EMAIL_REGEX.match(email_address): raise InvalidEmailAddressError('Invalid email address') domain = email_address.split('@')[1].lower() if email_supports_gmail(domain): return 'gmail' if email_supports_yahoo(domain): return 'yahoo' return None # From tornado.httputil def url_concat(url, args, fragments=None): """Concatenate url and argument dictionary regardless of whether url has existing query parameters. >>> url_concat("http://example.com/foo?a=b", dict(c="d")) 'http://example.com/foo?a=b&c=d' """ if not args and not fragments: return url # Strip off hashes while url[-1] == '#': url = url[:-1] fragment_tail = '' if fragments: fragment_tail = '#' + urlencode(fragments) args_tail = '' if args: if url[-1] not in ('?', '&'): args_tail += '&' if ('?' in url) else '?' args_tail += urlencode(args) return url + args_tail + fragment_tail
Python
0.000001
@@ -4497,16 +4497,30 @@ yahoo'%0A%0A + else:%0A retu @@ -4522,20 +4522,21 @@ return -None +'eas' %0A%0A%0A# Fro
60690c178f3adb5a2e05e4960e3b142dbf6c1aad
update cache
cache.py
cache.py
import json as json def cache_json(func, key_prefix='', expire=0, expire_at='', redis_client=None): """key_prefix should be unique at module level within the redis db, func name & all arguments would also be part of the key. redis_client: it's thread safe. to avoid giving `redis_client` param every time, you could do this: from functools import partial from somewhere import my_redis_client cache_json = partial(cache_json, redis_client=my_redis_client) """ def wrapped(_use_cache=True, *args, **kwargs): if _use_cache: return else: ret = func(*args, **kwargs) return ret return wrapped
Python
0.000001
@@ -1,12 +1,27 @@ +import inspect%0A import json @@ -28,16 +28,68 @@ as json%0A +from functools import wraps%0Afrom hashlib import md5%0A %0A%0Adef ca @@ -180,16 +180,47 @@ _prefix +is optional.%0A if use, it should b @@ -272,14 +272,30 @@ %0A + __module__ & func - +_ name @@ -615,16 +615,33 @@ %22%22%22%0A + @wraps(func)%0A def @@ -695,134 +695,754 @@ -if _use_cache:%0A return%0A else:%0A ret = func(*args, **kwargs)%0A return ret%0A return wrapped +%22%22%22set _use_cache to False if you do not want to use cache on this call.%0A %22%22%22%0A if _use_cache:%0A call_args = inspect.getcallargs(func, *args, **kwargs)%0A func_code = inspect.getsource(func)%0A args_hash = md5(json.dumps(call_args, sort_keys=True).encode()).hexdigest()%0A key = key_prefix + func.__module__ + func.__name__ + args_hash%0A cached = redis_client.get(key)%0A if cached is None:%0A ret = func(*args, **kwargs)%0A redis_client%5Bkey%5D = json.dumps(ret)%0A else:%0A ret = json.loads(cached)%0A return ret%0A else:%0A return func(*args, **kwargs)%0A return wrapped%0A%0A%0Adef release_cache(func):%0A return %0A
c40376c36312e582704b4fafbc36f4b17171394f
switch to using selectors
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by roadhump # Copyright (c) 2014 roadhump # # License: MIT # """This module exports the ESLint plugin class.""" import logging import re from SublimeLinter.lint import NodeLinter logger = logging.getLogger('SublimeLinter.plugin.eslint') class ESLint(NodeLinter): """Provides an interface to the eslint executable.""" syntax = ('javascript', 'html') npm_name = 'eslint' cmd = ('eslint', '--format', 'compact', '--stdin', '--stdin-filename', '@') regex = ( r'^.+?: line (?P<line>\d+), col (?P<col>\d+), ' r'(?:(?P<error>Error)|(?P<warning>Warning)) - ' r'(?P<message>.+)' ) crash_regex = re.compile( r'^(.*?)\r?\n\w*(Oops! Something went wrong!)', re.DOTALL ) line_col_base = (1, 1) selectors = { 'html': 'source.js.embedded.html' } def find_errors(self, output): """Parse errors from linter's output. Log errors when eslint crashes or can't find its configuration. """ match = self.crash_regex.match(output) if match: logger.error(output) return [] return super().find_errors(output) def split_match(self, match): """Extract and return values from match. Return 'no match' for ignored files """ match, line, col, error, warning, message, near = super().split_match(match) if message and message.startswith('File ignored'): return match, None, None, None, None, '', None return match, line, col, error, warning, message, near
Python
0.000002
@@ -425,44 +425,8 @@ %22%22%0A%0A - syntax = ('javascript', 'html')%0A @@ -830,16 +830,15 @@ -selector +default s = @@ -848,20 +848,24 @@ ' -html +selector ': 'sour @@ -873,22 +873,53 @@ e.js -.embedded.html + - meta.attribute-with-value, text.html.basic '%0A
d927e5dbf7820ad0e48006d9b2042b62c04bd310
Update regex
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Clifton Kaznocha # Copyright (c) 2014 Clifton Kaznocha # # License: MIT # """This module exports the Flow plugin class.""" import os from SublimeLinter.lint import Linter class Flow(Linter): """Provides an interface to flow.""" syntax = ('javascript', 'html') executable = 'flow' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.1.0' regex = r'''(?xi) # Find the line number and col ^/.+/(?P<file_name>.+):(?P<line>\d+):(?P<col>\d+),\d+:\s*(?P<message1>.+)$\r?\n # The second part of the message ^(?P<message2>.+)$\r?\n # The third part of the message ^\s*.*:\d+:\d+,\d+:\s*(?P<message3>.+)\s*$ ''' multiline = True defaults = { # Allows the user to lint *all* files, regardless of whether they have the `/* @flow */` declaration at the top. 'all': False, # Allow to bypass the 50 errors cap 'show-all-errors': True, # Options for flow '--lib:,': '' } word_re = r'^((\'|")?[^"\']+(\'|")?)(?=[\s\,\)\]])' tempfile_suffix = '-' selectors = { 'html': 'source.js.embedded.html' } config_file = ('.flowconfig') def cmd(self): """Return the command line to execute.""" command = [self.executable_path, 'check'] if self.get_merged_settings()['show-all-errors']: command.append('--show-all-errors') if self.get_merged_settings()['all']: command.append('--all') return command def split_match(self, match): """ Return the components of the match. We override this to catch linter error messages and return better error messages. """ if match: open_file_name = os.path.basename(self.view.file_name()) linted_file_name = match.group('file_name') if linted_file_name == open_file_name: message = '"{0}"" {1} {2}'.format( match.group('message1'), match.group('message2'), match.group('message3') ) line = max(int(match.group('line')) - 1, 0) col = int(match.group('col')) - 1 # match, line, col, error, warning, message, near return match, line, col, True, False, message, None return match, None, None, None, None, '', None
Python
0.000002
@@ -545,36 +545,59 @@ # -Find the line number and col +Warning location and optional title for the message %0A @@ -601,17 +601,16 @@ -%5E /.+/(?P%3C @@ -652,25 +652,25 @@ %3E%5Cd+),%5Cd+:%5Cs -* +? (?P%3Cmessage1 @@ -672,14 +672,18 @@ sage -1%3E.+)$ +_title%3E.*) %5Cr?%5C @@ -699,30 +699,17 @@ # -The second part of the +Main lint mes @@ -721,17 +721,16 @@ -%5E (?P%3Cmess @@ -736,19 +736,12 @@ sage -2 %3E.+) -$%5Cr?%5Cn %0A%0A @@ -752,68 +752,88 @@ # -The third part of the message%0A %5E%5Cs*.*:%5Cd+:%5Cd+,%5Cd +Optional message, only extract the text, leave the path%0A (%5Cr?%5Cn%5Cs%5Cs/. +:%5Cs -* (?P%3C @@ -843,17 +843,21 @@ sage -3%3E.+)%5Cs*$ +_footer%3E.+))? %0A @@ -2117,35 +2117,45 @@ sage - = '%22%7B0%7D%22%22 %7B1%7D %7B2%7D'.format( +_title = match.group('message_title') %0A @@ -2159,35 +2159,41 @@ - +message = match.group('me @@ -2201,12 +2201,10 @@ sage -1 ') -, %0A @@ -2208,35 +2208,48 @@ - +message_footer = match.group('me @@ -2257,57 +2257,229 @@ sage -2'),%0A match.group('message3')%0A +_footer') or %22%22%0A%0A if message_title:%0A message = '%22%7B0%7D%22%22 %7B1%7D %7B2%7D'.format(%0A message_title,%0A message,%0A message_footer%0A
6a9d6d30dc7ea207e2f4d8179a5ef99a95fce4e5
Fix bug in ListingGenerator with limit=None.
praw/models/listinggenerator.py
praw/models/listinggenerator.py
from .prawmodel import PRAWModel class ListingGenerator(PRAWModel): """Instances of this class generate ``RedditModels``""" def __init__(self, reddit, url, limit=100, params=None): """Initialize a ListingGenerator instance. :param reddit: An instance of :class:`.Reddit`. :param url: A URL returning a reddit listing. :param limit: The number of content entries to fetch. If ``limit`` is None, then fetch as many entries as possible. Most of reddit's listings contain a maximum of 1000 items, and are returned 100 at a time. This class will automatically issue all necessary requests. (Default: 100) :param params: A dictionary containing additional query string parameters to send with the request. """ self._exhausted = False self._list = None self._list_index = None self._reddit = reddit self.after_field = 'after' self.extract_list_index = None self.limit = limit self.params = params or {} self.root_field = 'data' self.thing_list_field = 'children' self.url = url self.yielded = 0 self.params['limit'] = self.limit or 1024 def __iter__(self): return self def __next__(self): if self.yielded >= self.limit: raise StopIteration() if self._list is None or self._list_index >= len(self._list): self._next_batch() self._list_index += 1 self.yielded += 1 return self._list[self._list_index - 1] def _next_batch(self): if self._exhausted: raise StopIteration() page_data = self._reddit.request(self.url, params=self.params) if self.extract_list_index is not None: page_data = page_data[self.extract_list_index] root = page_data[self.root_field] self._list = root[self.thing_list_field] self._list_index = 0 if len(self._list) == 0: raise StopIteration() if root.get(self.after_field): self.params['after'] = root[self.after_field] else: self._exhausted = True
Python
0
@@ -1326,24 +1326,51 @@ %0A if +self.limit is not None and self.yielded
bf7562d9f45a777163f2ac775dc9cf4afe99a930
Change 'language' to 'syntax', that is more precise terminology.
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jshint # License: MIT # """This module exports the JSHint plugin linter class.""" from SublimeLinter.lint import Linter class JSHint(Linter): """Provides an interface to the jshint executable.""" language = ('javascript', 'html') cmd = 'jshint --verbose -' regex = r'^.+?: line (?P<line>\d+), col (?P<col>\d+), (?P<message>.+) \((?:(?P<error>E)|(?P<warning>W))\d+\)$' selectors = { 'html': 'source.js.embedded.html' }
Python
0.002004
@@ -435,16 +435,14 @@ -language +syntax = (
cea40608a1efe16310c7b978fba40abcde26ced4
make flake8 happy
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Dan Flettre # Copyright (c) 2015 Dan Flettre # # License: MIT # """This module exports the Semistandard plugin class.""" from SublimeLinter.lint import NodeLinter, util class Semistandard(NodeLinter): """Provides an interface to semistandard.""" syntax = ('javascript', 'html', 'javascriptnext', 'javascript 6to5') cmd = 'semistandard' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 2.3.1' regex = r'^\s.+:(?P<line>\d+):(?P<col>\d+):(?P<message>.+)' selectors = { 'html': 'source.js.embedded.html' }
Python
0
@@ -264,14 +264,8 @@ nter -, util %0A%0A%0Ac
9bfe8cd21931c69d79657aa275be02af21ec78f1
Simplify `cmd` property
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Bartosz Kruszczynski # Copyright (c) 2015 Bartosz Kruszczynski # # License: MIT # """This module exports the Reek plugin class.""" from SublimeLinter.lint import RubyLinter import re class Reek(RubyLinter): """Provides an interface to reek.""" syntax = ( 'better rspec', 'betterruby', 'cucumber steps', 'rspec', 'ruby experimental', 'ruby on rails', 'ruby' ) cmd = 'ruby -S reek' regex = r'^.+?\[(?P<line>\d+).*\]:(?P<message>.+) \[.*\]' tempfile_suffix = 'rb' version_args = '-S reek -v' version_re = r'reek\s(?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 3.5.0' config_file = ('-c', 'config.reek') def split_match(self, match): """Extract named capture groups from the regex and return them as a tuple.""" match, line, col, error, warning, message, _ = super().split_match(match) near = self.search_token(message) return match, line, col, error, warning, message, near def search_token(self, message): """Search text token to be highlighted.""" # First search for variable name enclosed in single quotes m = re.search("'.*'", message) # If there's no variable name search for nil-check message if m is None: m = re.search('nil(?=-check)', message) # If there's no nil-check search for method name that comes after a `#` if m is None: m = re.search('(?<=#)\S+', message) return m.group(0) if m else None
Python
0
@@ -543,16 +543,8 @@ = ' -ruby -S reek @@ -638,40 +638,8 @@ rb'%0A - version_args = '-S reek -v'%0A
d20d035516f279b00deeae9ad55d3540f02eaf33
Fix deprecation warnings
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Fred Callaway # Copyright (c) 2015 Fred Callaway # Copyright (c) 2017 FichteFoll <fichtefoll2@googlemail.com> # # License: MIT # """This module exports the Mypy plugin class.""" import logging import os import shutil import tempfile import getpass from SublimeLinter.lint import const from SublimeLinter.lint import PythonLinter USER = getpass.getuser() TMPDIR_PREFIX = "SublimeLinter-contrib-mypy-%s" % USER logger = logging.getLogger("SublimeLinter.plugin.mypy") # Mapping for our created temporary directories. # For smarter caching purposes, # we index different cache folders based on the working dir. tmpdirs = {} class Mypy(PythonLinter): """Provides an interface to mypy.""" regex = r'^(\w:)?[^:]+:(?P<line>\d+):((?P<col>\d+):)?\s*(?P<error_type>[^:]+):\s*(?P<message>.+)' line_col_base = (1, 1) tempfile_suffix = 'py' default_type = const.WARNING # Pretty much all interesting options don't expect a value, # so you'll have to specify those in "args" anyway. # This dict only contains settings for which we have special handling. defaults = { 'selector': "source.python", # Will default to tempfile.TemporaryDirectory if empty. "--cache-dir:": "", # Allow users to disable this "--incremental": True, # Need this to silent lints for other files. Alternatively: 'skip' "--follow-imports:": "silent", } def cmd(self): """Return a list with the command line to execute.""" cmd = [ 'mypy', '${args}', '--show-column-numbers', '--hide-error-context', # '--incremental', ] if self.filename: cmd.extend([ # --shadow-file SOURCE_FILE SHADOW_FILE # # '@' needs to be the (temporary) shadow file, # while we request the normal filename # to be checked in its normal environment. '--shadow-file', '${file}', '${temp_file}', # The file we want to lint on the surface '${file}', ]) else: cmd.append('${temp_file}') # Add a temporary cache dir to the command if none was specified. # Helps keep the environment clean # by not littering everything with `.mypy_cache` folders. settings = self.get_view_settings() if not settings.get('cache-dir'): cwd = self.get_working_dir(settings) if cwd in tmpdirs: cache_dir = tmpdirs[cwd].name else: tmp_dir = tempfile.TemporaryDirectory(prefix=TMPDIR_PREFIX) tmpdirs[cwd] = tmp_dir cache_dir = tmp_dir.name logger.info("Created temporary cache dir at: %s", cache_dir) cmd[1:1] = ["--cache-dir", cache_dir] return cmd def _cleanup_tmpdirs(): def _onerror(function, path, exc_info): logger.exception("Unable to delete '%s' while cleaning up temporary directory", path, exc_info=exc_info) tmpdir = tempfile.gettempdir() for dirname in os.listdir(tmpdir): if dirname.startswith(TMPDIR_PREFIX): shutil.rmtree(os.path.join(tmpdir, dirname), onerror=_onerror) def plugin_loaded(): """Attempt to clean up temporary directories from previous runs.""" _cleanup_tmpdirs() def plugin_unloaded(): """Clear references to TemporaryDirectory instances. They should then be removed automatically. """ # (Actually, do we even need to do this?) tmpdirs.clear()
Python
0.00011
@@ -2478,59 +2478,20 @@ -settings = self.get_view_settings()%0A if not +self. sett @@ -2552,24 +2552,16 @@ ing_dir( -settings )%0A
153a4dfaa5ecdd2a257a7e8d4e079bf7b6264956
fix serializer
project/apps/api/serializers.py
project/apps/api/serializers.py
from rest_framework import serializers from .models import ( Convention, Contest, Contestant, Group, Performance, Note, ) from django.contrib.auth import get_user_model User = get_user_model() class PerformanceSerializer(serializers.ModelSerializer): round = serializers.CharField( source='get_round_display', ) kind = serializers.CharField( source='contestant.contest.get_kind_display', ) prelim = serializers.FloatField( source='contestant.prelim', ) group = serializers.SlugRelatedField( read_only=True, slug_field='slug', source='contestant.group', ) class Meta: model = Performance lookup_field = 'slug' fields = ( 'id', 'slug', 'round', 'kind', 'prelim', 'group', 'queue', 'session', 'stagetime', 'place', 'song1', 'mus1', 'prs1', 'sng1', 'song2', 'mus2', 'prs2', 'sng2', 'men', 'mus1_rata', 'prs1_rata', 'sng1_rata', 'song1_raw', 'song1_rata', 'mus2_rata', 'prs2_rata', 'sng2_rata', 'song2_raw', 'song2_rata', 'total_raw', 'score', ) class GroupSerializer(serializers.ModelSerializer): # contestants = serializers.SlugRelatedField( # many=True, # read_only=True, # slug_field='slug', # ) district_fk = serializers.StringRelatedField() kind = serializers.CharField( source='get_kind_display', ) chapterName = serializers.CharField( source='chapter_name', ) lead = serializers.StringRelatedField() tenor = serializers.StringRelatedField() baritone = serializers.StringRelatedField() bass = serializers.StringRelatedField() class Meta: model = Group lookup_field = 'slug' fields = ( 'id', 'url', 'slug', 'name', 'kind', 'district_fk', 'location', 'website', 'facebook', 'twitter', 'email', 'phone', 'picture', 'description', 'director', 'chapterName', 'lead', 'tenor', 'baritone', 'bass', 'bsmdb', # 'contestants', ) class ContestantSerializer(serializers.ModelSerializer): contest = serializers.SlugRelatedField( read_only=True, slug_field='slug', ) performances = serializers.SlugRelatedField( many=True, read_only=True, slug_field='slug', ) group = serializers.SlugRelatedField( read_only=True, slug_field='slug', ) # group = GroupSerializer( # read_only=True, # ) # performances = PerformanceSerializer( # read_only=True, # many=True, # ) class Meta: model = Contestant lookup_field = 'slug' fields = ( 'id', 'slug', 'contest', 'group', 'seed', 'prelim', 'place', 'score', 'queue', 'stagetime', 'quarters_place', 'quarters_score', 'semis_place', 'semis_score', 'finals_place', 'finals_score', 'performances', ) class ContestSerializer(serializers.ModelSerializer): contestants = serializers.SlugRelatedField( many=True, read_only=True, slug_field='slug', ) # contestants = ContestantSerializer( # many=True, # read_only=True, # ) level = serializers.CharField( source='get_level_display', ) kind = serializers.CharField( source='get_kind_display', ) year = serializers.CharField( source='get_year_display', ) district = serializers.CharField( source='get_district_display', ) class Meta: model = Contest lookup_field = 'slug' fields = ( 'id', 'slug', 'level', 'kind', 'year', 'district', 'panel', 'scoresheet_pdf', 'contestants', ) class ConventionSerializer(serializers.ModelSerializer): contests = serializers.SlugRelatedField( many=True, read_only=True, slug_field='slug', ) # contests = ContestSerializer( # read_only=True, # many=True, # ) class Meta: model = Convention lookup_field = 'slug' fields = ( 'id', 'url', 'slug', 'name', 'dates', 'timezone', 'contests', ) class NoteSerializer(serializers.ModelSerializer): performance = serializers.SlugRelatedField( # read_only=True, queryset=Performance.objects.all(), slug_field='slug', ) user = serializers.PrimaryKeyRelatedField( queryset=User.objects.all(), # read_only=True, ) class Meta: model = Note fields = ( 'id', 'text', 'performance', 'user', ) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'id', 'email', 'username', )
Python
0.000003
@@ -4215,16 +4215,19 @@ district +_fk = seria @@ -4237,62 +4237,27 @@ ers. -CharField(%0A source='get_district_display',%0A +StringRelatedField( )%0A%0A @@ -4464,16 +4464,19 @@ district +_fk ',%0A
68293b6075ead70651924761e4e3187286ad6765
Add the proper tests user/pass.
integration_tests/test_basic_page_loads.py
integration_tests/test_basic_page_loads.py
from django.contrib.auth.models import User from django.test import testcases from django.test.client import Client class Fail(testcases.TestCase): def setUp(self): super(Fail, self).setUp() u = User(username='john_doe') u.set_password('password') u.is_superuser = True u.save() self.client = Client() def test_require_login(self): response = self.client.get('/') self.assertEqual(response.status_code, 302) self.assertEqual(response.url, 'http://testserver/user/login?next=/') def test_login(self): response = self.client.post('/user/login?next=/', {'username': 'ivailo', 'password': 'Heman3f5'}) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, 'http://testserver/') response = self.client.get('/') self.assertEqual(response.status_code, 200) def test_login_redirect_correct(self): response = self.client.post('/user/login?next=/dummy_url', {'username': 'ivailo', 'password': 'Heman3f5'}) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, 'http://testserver/dummy_url') def test_profile(self): self.client.post('/user/login', {'username': 'ivailo', 'password': 'Heman3f5'}) response = self.client.get('/profile/') self.assertEqual(response.status_code, 200)
Python
0
@@ -683,38 +683,40 @@ %7B'username': ' -ivailo +john_doe ', 'password': ' @@ -711,32 +711,32 @@ password': ' -Heman3f5 +password '%7D)%0A @@ -1085,38 +1085,40 @@ %7B'username': ' -ivailo +john_doe ', 'password': ' @@ -1113,32 +1113,32 @@ password': ' -Heman3f5 +password '%7D)%0A @@ -1363,14 +1363,16 @@ ': ' -ivailo +john_doe ', ' @@ -1387,16 +1387,16 @@ ': ' -Heman3f5 +password '%7D)%0A
1b048e5c4504d31fe001651468b95b31a3ce5255
update cron job
clock.py
clock.py
import os import sys from argparse import ArgumentParser from datetime import date from apscheduler.schedulers.blocking import BlockingScheduler from flask import Flask, request, abort from linebot import ( LineBotApi, WebhookParser ) from linebot.exceptions import ( InvalidSignatureError, LineBotApiError ) from linebot.models import ( MessageEvent, TextMessage, TextSendMessage, ImageSendMessage, VideoSendMessage ) app = Flask(__name__) # get channel_secret and channel_access_token from your environment variable channel_secret = os.getenv('LINE_CHANNEL_SECRET', None) channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None) if channel_secret is None: print('Specify LINE_CHANNEL_SECRET as environment variable.') sys.exit(1) if channel_access_token is None: print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.') sys.exit(1) my_group_id = os.getenv('GROUP_ID', None) if my_group_id is None: print('GROUP_ID as environment variable.') sys.exit(1) image1 = os.getenv('IMAGE1', None) if image1 is None: print('IMAGE1 as environment variable.') sys.exit(1) image2 = os.getenv('IMAGE2', None) if image2 is None: print('IMAGE2 as environment variable.') sys.exit(1) image3 = os.getenv('IMAGE3', None) if image3 is None: print('IMAGE3 as environment variable.') sys.exit(1) image4 = os.getenv('IMAGE4', None) if image4 is None: print('IMAGE4 as environment variable.') sys.exit(1) image5 = os.getenv('IMAGE5', None) if image5 is None: print('IMAGE5 as environment variable.') sys.exit(1) image6 = os.getenv('IMAGE6', None) if image6 is None: print('IMAGE6 as environment variable.') sys.exit(1) image7 = os.getenv('IMAGE7', None) if image7 is None: print('IMAGE7 as environment variable.') sys.exit(1) image8 = os.getenv('IMAGE8', None) if image8 is None: print('IMAGE8 as environment variable.') sys.exit(1) image9 = os.getenv('IMAGE9', None) if image9 is None: print('IMAGE9 as environment variable.') sys.exit(1) line_bot_api = LineBotApi(channel_access_token) parser = WebhookParser(channel_secret) ## simulate day #my_date = date.today() # ## Start the scheduler #sched = BlockingScheduler() #@sched.scheduled_job('interval', seconds=1) #def timed_job(): # print('This job is run every 1 seconds.') # ##@sched.scheduled_job('cron', day_of_week='mon-fri', hour=10) ##def scheduled_job(): ## print('This job is run every weekday at 10am.') # ##sched.configure(options_from_ini_file) #sched.start() ## Schedules job_function to be run once each minute #sched.add_job(checkAndSend, second='5') # simulate day global my_date my_date = date.today() # Start the scheduler sched = BlockingScheduler() @sched.scheduled_job('interval', seconds=5) def checkAndSend(): date_string = my_date.strftime('%Y-%m-%d') print(date_string) try: #I just want my group to receive msg line_bot_api.push_message(my_group_id, TextSendMessage(text=date_string)) line_bot_api.push_message(my_group_id, ImageSendMessage(original_content_url='https://image.ibb.co/mjCpra/S_75849824.jpg', preview_image_url='https://image.ibb.co/mjCpra/S_75849824.jpg')) except LineBotApiError as e: abort(400) global my_date my_date += datetime.timedelta(days=1) #@sched.scheduled_job('cron', day_of_week='mon-fri', hour=10) #def scheduled_job(): # print('This job is run every weekday at 10am.') #sched.configure(options_from_ini_file) sched.start()
Python
0.000001
@@ -3435,27 +3435,8 @@ 00)%0A - global my_date%0A @@ -3473,16 +3473,21 @@ days=1)%0A + %0A #@sched.
005c684b88e6383aabe5294bfa0104ba4fb3ed40
Use the fancier tmp_file management in tests
test/ops/test_index.py
test/ops/test_index.py
""" Tests for index operations """ from unittest import TestCase import os import xarray as xr import pandas as pd import numpy as np from datetime import datetime from cate.ops import index from cate.ops import subset def assert_dataset_equal(expected, actual): # this method is functionally equivalent to # `assert expected == actual`, but it checks each aspect # of equality separately for easier debugging assert expected.equals(actual), (expected, actual) class TestIndices(TestCase): def test_n34(self): """ Test ENSO index calculation using Nino34 region """ tmp_path = 'temp_lta.nc' dataset = xr.Dataset({ 'first': (['lat', 'lon', 'time'], np.ones([45, 90, 24])), 'second': (['lat', 'lon', 'time'], np.ones([45, 90, 24])), 'lat': np.linspace(-88, 88, 45), 'lon': np.linspace(-178, 178, 90), 'time': ([datetime(2001, x, 1) for x in range(1, 13)] + [datetime(2002, x, 1) for x in range(1, 13)])}) actual = subset.subset_spatial(dataset, "-20, -10, 20, 10") expected = xr.Dataset({ 'first': (['lat', 'lon', 'time'], np.ones([5, 10, 24])), 'second': (['lat', 'lon', 'time'], np.ones([5, 10, 24])), 'lat': np.linspace(-8, 8, 5), 'lon': np.linspace(-18, 18, 10), 'time': ([datetime(2001, x, 1) for x in range(1, 13)] + [datetime(2002, x, 1) for x in range(1, 13)])}) assert_dataset_equal(expected, actual) lta = xr.Dataset({ 'first': (['lat', 'lon', 'time'], np.ones([45, 90, 12])), 'second': (['lat', 'lon', 'time'], np.ones([45, 90, 12])), 'lat': np.linspace(-88, 88, 45), 'lon': np.linspace(-178, 178, 90), 'time': [x for x in range(1,13)]}) lta = 2*lta lta.to_netcdf(tmp_path) ret = index.enso_nino34(dataset, 'first', tmp_path) print(ret) try: os.remove(tmp_path) except OSError: # Doesn't exist pass def test_preset_region(self): """ Test ENSO index calculation using a pre-defined region """ pass def test_custom(self): """ Test ENSO index calculation using a user-supplied region """ pass def test_oni(self): """ Test ONI index calculation. """ pass
Python
0
@@ -70,16 +70,27 @@ port os%0A +import sys%0A import x @@ -101,16 +101,16 @@ y as xr%0A - import p @@ -169,16 +169,101 @@ datetime +%0Aimport tempfile%0Aimport shutil%0Afrom contextlib import contextmanager%0Aimport itertools %0A%0Afrom c @@ -572,16 +572,388 @@ ctual)%0A%0A +_counter = itertools.count()%0AON_WIN = sys.platform == 'win32'%0A%0A@contextmanager%0Adef create_tmp_file():%0A tmp_dir = tempfile.mkdtemp()%0A path = os.path.join(tmp_dir, 'tmp_file_%7B%7D.nc'.format(next(_counter)))%0A try:%0A yield path%0A finally:%0A try:%0A shutil.rmtree(tmp_dir)%0A except OSError:%0A if not ON_WIN:%0A raise%0A%0A %0Aclass T @@ -1058,32 +1058,32 @@ g Nino34 region%0A + %22%22%22%0A @@ -1081,41 +1081,8 @@ %22%22%22 -%0A tmp_path = 'temp_lta.nc' %0A%0A @@ -2317,16 +2317,64 @@ = 2*lta%0A + with create_tmp_file() as tmp_file:%0A @@ -2387,30 +2387,34 @@ _netcdf(tmp_ -path)%0A +file)%0A ret @@ -2459,147 +2459,36 @@ tmp_ -path)%0A print(ret)%0A%0A try:%0A os.remove(tmp_path)%0A except OSError:%0A # Doesn't exist%0A pass +file)%0A print(ret) %0A%0A
759a6994441c35400965beea19e6425b377cf4e8
add datetime_format
cloud.py
cloud.py
# coding: utf-8 import leancloud from leancloud import Engine from leancloud import LeanEngineError from app import app from logentries import LogentriesHandler import logging from qiniu import Auth from qiniu import BucketManager import requests import os import json import time engine = Engine(app) log = logging.getLogger('logentries') log.setLevel(logging.INFO) log.addHandler(LogentriesHandler(os.environ.get('logentries_key'))) access_key = os.environ.get('qiniu_ak') secret_key = os.environ.get('qiniu_sk') bucket_name = os.environ.get('qiniu_bn') bucket_domain = os.environ.get('qiniu_bd') q = Auth(access_key, secret_key) bucket = BucketManager(q) hook_url = os.environ.get('hook_url') def cache_sina_stock_gif(stock_code): if stock_code.startswith('60'): sina_code = 'sh'+stock_code else: sina_code = 'sz'+stock_code image_url = 'http://image.sinajs.cn/newchart/min/n/{sina_code}.gif'.format(sina_code=sina_code) ts = int(time.time()) key = stock_code +'-'+str(ts) + '-sina.gif' ret, info = bucket.fetch(image_url, bucket_name, key) # log.info(stock_code+' '+str(info)) if '200' in str(info)[0:50]: return bucket_domain+key else: return image_url def alarming_bearychat(msg): stock_code = msg['stock_code'] img_url = cache_sina_stock_gif(stock_code) src = u'新图' if 'sinajs' in img_url else u'缓存' bearychat_msg ={ "text": '**'+msg['name']+' '+ stock_code+'**\n>'+' | '.join(msg['time_list']), "markdown": True, "attachments": [{ "text": msg['name']+u" 分时图 ("+ src +') '+time.strftime(datetime_format), "color": "#ff0000", "images": [{"url": img_url}] }] } headers = { 'Content-Type': 'application/json' } requests.post(hook_url,headers = headers,data = json.dumps(bearychat_msg)) def test_alarming_bearychat(msg): stock_code = msg['stock_code'] img_url = cache_sina_stock_gif(stock_code) src = u'新图' if 'sinajs' in img_url else u'缓存' bearychat_msg ={ "text": '**'+str(msg['index'])+'.'+msg['name']+' '+ stock_code+'**\n>'+' | '.join(msg['time_list']), "markdown": True, "attachments": [{ "text": msg['name']+u" 分时图 ("+ src +') '+time.strftime(datetime_format), "color": "#ff0000", "images": [{"url": img_url}] }] } headers = { 'Content-Type': 'application/json' } log.info(json.dumps(bearychat_msg)) requests.post(hook_url,headers = headers,data = json.dumps(bearychat_msg)) @engine.after_save('Alert') # Alert 为需要 hook 的 class 的名称 def after_alert_save(alert): try: msg = alert.get('msg') test_alarming_bearychat(msg) log.info(msg) except leancloud.LeanCloudError: raise leancloud.LeanEngineError(message='An error occurred while trying to save the Alert. ')
Python
0.002308
@@ -700,16 +700,219 @@ _url')%0A%0A +# local_time = time.localtime()%0A# # day_stamp = time.strftime(%22%25Y-%25m-%25d%22)%0A# day_stamp = '20161013'%0A# collection = db%5B'realtime_quotes_'+day_stamp%5D%0Adatetime_format = %22%25Y-%25m-%25d %25H:%25M:%25S%22%0A%0Agranularity =10%0A%0A def cach
853dc8de1d077494c707a5ec8a6b75ac0e0628cf
Add trailing slash to URL for consistency.
cadorsfeed/views.py
cadorsfeed/views.py
from werkzeug import redirect, Response from werkzeug.exceptions import NotFound from cadorsfeed.utils import expose, url_for, db from parse import parse from fetch import fetchLatest, fetchReport @expose('/report/latest') def latest_report(request): if 'latest' in db: latestDate = db['latest'] else: latestDate = fetchLatest() db['latest'] = latestDate db.expire('latest',60*60) (year, month, day) = latestDate.split('-') return redirect(url_for('do_report', year=year, month=month, day=day)) @expose('/report/<int:year>/<int:month>/<int:day>/') def do_report(request, year, month, day): refetch = request.args.get('refetch','0') == '1' reparse = request.args.get('reparse','0') == '1' or refetch date = "{year:04.0f}-{month:02.0f}-{day:02.0f}".format( year=year, month=month, day=day) key = "report:"+date if db.hexists(key, "output") and not reparse: output = db.hget(key, "output") else: if db.hexists(key, "input") and not refetch: input = db.hget(key, "input").decode('utf-8') else: input = fetchReport(date) db.hset(key, "input", input) output = parse(input) db.hset(key,"output", output) return Response(output, mimetype="application/atom+xml")
Python
0
@@ -214,16 +214,17 @@ t/latest +/ ')%0Adef l
cb50a43435de4e3b62324d1b738f3775cabe7367
Fix reverse url in RecentChangesFeed
candidates/feeds.py
candidates/feeds.py
from __future__ import unicode_literals import re from django.contrib.sites.models import Site from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse from django.utils.feedgenerator import Atom1Feed from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from .models import LoggedAction lock_re = re.compile(r'^(?:Unl|L)ocked\s*constituency (.*) \((\d+)\)$') class RecentChangesFeed(Feed): site_name = Site.objects.get_current().name title = _("{site_name} recent changes").format(site_name=site_name) description = _("Changes to {site_name} candidates").format(site_name=site_name) link = "/feeds/changes.xml" feed_type = Atom1Feed def items(self): return LoggedAction.objects.order_by('-updated')[:50] def item_title(self, item): m = lock_re.search(item.source) if m: return "{0} - {1}".format( m.group(1), item.action_type ) else: return "{0} - {1}".format( item.person_id, item.action_type ) def item_description(self, item): updated = _("Updated at {0}").format(str(item.updated)) description = "{0}\n\n{1}\n".format(item.source, updated) return description def item_link(self, item): # As a hack for the moment, constituencies are just mentioned # in the source message: m = lock_re.search(item.source) if m: return reverse('constituency', kwargs={ 'post_id': m.group(2), 'ignored_slug': slugify(m.group(1)) }) else: if item.person_id: return reverse('person-view', args=[item.person_id]) else: return '/'
Python
0.999993
@@ -859,225 +859,35 @@ -m = lock_re.search(item.source)%0A if m:%0A return %22%7B0%7D - %7B1%7D%22.format(%0A m.group(1),%0A item.action_type%0A )%0A else:%0A return %22%7B0%7D - %7B1%7D%22.format(%0A +return %22%7B0%7D - %7B1%7D%22.format(%0A @@ -910,20 +910,16 @@ son_id,%0A - @@ -939,20 +939,16 @@ on_type%0A - @@ -1285,238 +1285,8 @@ ge:%0A - m = lock_re.search(item.source)%0A if m:%0A return reverse('constituency', kwargs=%7B%0A 'post_id': m.group(2),%0A 'ignored_slug': slugify(m.group(1))%0A %7D)%0A else:%0A @@ -1308,20 +1308,16 @@ son_id:%0A - @@ -1385,22 +1385,14 @@ - else:%0A -
63caf1fceb94d185e73858c2b58c82bf5912b7c4
Add documentation for coding formatter
beetsplug/hook.py
beetsplug/hook.py
# This file is part of beets. # Copyright 2015, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. """Allows custom commands to be run when an event is emitted by beets""" from __future__ import division, absolute_import, print_function import string import subprocess from beets.plugins import BeetsPlugin from beets.ui import _arg_encoding from beets.util import shlex_split class CodingFormatter(string.Formatter): def __init__(self, coding): self._coding = coding def format(self, format_string, *args, **kwargs): try: format_string = format_string.decode(self._coding) except UnicodeEncodeError: pass return super(CodingFormatter, self).format(format_string, *args, **kwargs) def convert_field(self, value, conversion): converted = super(CodingFormatter, self).convert_field(value, conversion) try: converted = converted.decode(self._coding) except UnicodeEncodeError: pass return converted class HookPlugin(BeetsPlugin): """Allows custom commands to be run when an event is emitted by beets""" def __init__(self): super(HookPlugin, self).__init__() self.config.add({ 'hooks': [] }) hooks = self.config['hooks'].get(list) for hook_index in range(len(hooks)): hook = self.config['hooks'][hook_index] hook_event = hook['event'].get() hook_command = hook['command'].get() self.create_and_register_hook(hook_event, hook_command) def create_and_register_hook(self, event, command): def hook_function(**kwargs): if command is None or len(command) == 0: self._log.error('invalid command "{0}"', command) return encoding = _arg_encoding() formatter = CodingFormatter(encoding) formatted_command = formatter.format(command, event=event, **kwargs) command_pieces = shlex_split(formatted_command) self._log.debug(u'running command "{0}" for event {1}', formatted_command, event) try: subprocess.Popen(command_pieces).wait() except OSError as exc: self._log.error(u'hook for {0} failed: {1}', event, exc) self.register_listener(event, hook_function)
Python
0
@@ -971,120 +971,526 @@ -def __init__(self, coding):%0A self._coding = coding%0A%0A def format(self, format_string, *args, **kwargs): +%22%22%22A custom string formatter that decodes the format string and it's%0A fields.%0A %22%22%22%0A%0A def __init__(self, coding):%0A %22%22%22Creates a new coding formatter with the provided coding.%22%22%22%0A self._coding = coding%0A%0A def format(self, format_string, *args, **kwargs):%0A %22%22%22Formats the provided string using the provided arguments and keyword%0A arguments.%0A%0A This method decodes the format string using the formatter's coding.%0A%0A See str.format and string.Formatter.format.%0A %22%22%22 %0A @@ -1794,24 +1794,224 @@ onversion):%0A + %22%22%22Converts the provided value given a conversion type.%0A%0A This method decodes the converted value using the formatter's coding.%0A%0A See string.Formatter.convert_field.%0A %22%22%22%0A conv
847d9c4a1e88b9e00a3be082db635743866a8abd
Fix tests
catalog/__init__.py
catalog/__init__.py
from os import environ from flask import Flask from flask_wtf.csrf import CSRFProtect from flask_sqlalchemy import SQLAlchemy DB_URL = 'postgresql:///catalog' + ('_test' if environ.get('ENV') == 'test' else '') app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) csrf = CSRFProtect() csrf.init_app(app)
Python
0.000003
@@ -44,47 +44,8 @@ ask%0A -from flask_wtf.csrf import CSRFProtect%0A from @@ -312,16 +312,96 @@ y(app)%0A%0A +if environ.get('ENV') != 'test':%0A from flask_wtf.csrf import CSRFProtect%0A csrf = C @@ -413,16 +413,20 @@ otect()%0A + csrf.ini @@ -431,12 +431,75 @@ nit_app(app) +%0Aelse:%0A app.jinja_env.globals%5B'csrf_token'%5D = lambda: 'test'
31fd889ec6d8851ce61085b0cbd15b86195905a8
remove unused imports
test/scripts/window.py
test/scripts/window.py
#!/usr/bin/env python """ This program is carefully crafted to exercise a number of corner-cases in Qtile. """ from __future__ import print_function import sys import time import struct import xcffib import xcffib.xproto try: from StringIO import StringIO # Python 2 except ImportError: from io import StringIO # Python 3 def configure(window): window.configure( width=100, height=100, x=0, y=0, border_width=1, ) for i in range(20): try: conn = xcffib.connect(display=sys.argv[1]) except xcffib.ConnectionException: time.sleep(0.1) continue except Exception as v: print("Error opening test window: ", type(v), v, file=sys.stderr) sys.exit(1) break else: print("Could not open window on display %s" % (sys.argv[1]), file=sys.stderr) sys.exit(1) screen = conn.get_setup().roots[conn.pref_screen] window = conn.generate_id() background = conn.core.AllocColor(screen.default_colormap, 0x2828, 0x8383, 0xCECE).reply().pixel # Color "#2883ce" conn.core.CreateWindow(xcffib.CopyFromParent, window, screen.root, 100, 100, 100, 100, 1, xcffib.xproto.WindowClass.InputOutput, screen.root_visual, xcffib.xproto.CW.BackPixel | xcffib.xproto.CW.EventMask, [background, xcffib.xproto.EventMask.StructureNotify | xcffib.xproto.EventMask.Exposure]) conn.core.ChangeProperty(xcffib.xproto.PropMode.Replace, window, xcffib.xproto.Atom.WM_NAME, xcffib.xproto.Atom.STRING, 8, len(sys.argv[2]), sys.argv[2]) wm_protocols = "WM_PROTOCOLS" wm_protocols = conn.core.InternAtom(0, len(wm_protocols), wm_protocols).reply().atom wm_delete_window = "WM_DELETE_WINDOW" wm_delete_window = conn.core.InternAtom(0, len(wm_delete_window), wm_delete_window).reply().atom conn.core.ChangeProperty(xcffib.xproto.PropMode.Replace, window, wm_protocols, xcffib.xproto.Atom.ATOM, 32, 1, [wm_delete_window]) conn.core.ConfigureWindow(window, xcffib.xproto.ConfigWindow.X | xcffib.xproto.ConfigWindow.Y | xcffib.xproto.ConfigWindow.Width | xcffib.xproto.ConfigWindow.Height | xcffib.xproto.ConfigWindow.BorderWidth, [0, 0, 100, 100, 1]) conn.core.MapWindow(window) conn.flush() conn.core.ConfigureWindow(window, xcffib.xproto.ConfigWindow.X | xcffib.xproto.ConfigWindow.Y | xcffib.xproto.ConfigWindow.Width | xcffib.xproto.ConfigWindow.Height | xcffib.xproto.ConfigWindow.BorderWidth, [0, 0, 100, 100, 1]) try: while 1: event = conn.wait_for_event() if event.__class__ == xcffib.xproto.ClientMessageEvent: if conn.core.GetAtomName(event.type).reply().name.as_string() == "WM_DELETE_WINDOW": sys.exit(1) except xcffib.XcffibException: pass
Python
0.000001
@@ -177,22 +177,8 @@ ime%0A -import struct%0A impo @@ -212,118 +212,8 @@ oto%0A -try:%0A from StringIO import StringIO # Python 2%0Aexcept ImportError:%0A from io import StringIO # Python 3%0A%0A %0Adef
7d26429acac78b2b1388a5d069d807038038bd1c
Add a folded indicator
examples/gui_integration/python_editor.py
examples/gui_integration/python_editor.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # PCEF - Python/Qt Code Editing Framework # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Integrates the generic editor using the pcef qt designer plugin. """ import logging logging.basicConfig(level=logging.INFO) import os import sys os.environ.setdefault("QT_API", "PyQt") from pcef.qt import QtCore, QtGui from pcef.core import FoldingIndicator if sys.version_info[0] == 3: from examples.gui_integration.ui.python_editor_ui3 import Ui_MainWindow logging.info("Using python3") else: from examples.gui_integration.ui.python_editor_ui import Ui_MainWindow logging.info("Using python2") class PythonEditorWindow(QtGui.QMainWindow, Ui_MainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.setupUi(self) self.editor.foldingPanel.addIndicator(FoldingIndicator(22, 30)) self.editor.foldingPanel.addIndicator(FoldingIndicator(25, 28)) self.editor.foldingPanel.addIndicator(FoldingIndicator(50, 60)) self.editor.dirtyChanged.connect(self.actionSave.setEnabled) self.actionSave.triggered.connect(self.editor.saveToFile) mnu = QtGui.QMenu("Edit", self.menubar) mnu.addActions(self.editor.actions()) self.menubar.addMenu(mnu) # Add modes to the modes menu for k, v in self.editor.modes().items(): a = QtGui.QAction(self.menuModes) a.setText(k) a.setCheckable(True) a.setChecked(True) a.changed.connect(self.onModeCheckStateChanged) a.mode = v self.menuModes.addAction(a) # Add panels to the panels menu for zones, panel_dic in self.editor.panels().items(): for k, v in panel_dic.items(): a = QtGui.QAction(self.menuModes) a.setText(k) a.setCheckable(True) a.setChecked(True) a.changed.connect(self.onPanelCheckStateChanged) a.panel = v self.menuPanels.addAction(a) try: self.editor.openFile(__file__) except (OSError, IOError) as e: pass except AttributeError: pass @QtCore.Slot() def on_actionOpen_triggered(self): filePath = QtGui.QFileDialog.getOpenFileName( self, "Choose a file", os.path.expanduser("~")) if filePath: self.editor.openFile(filePath) def onPanelCheckStateChanged(self): action = self.sender() action.panel.enabled = action.isChecked() def onModeCheckStateChanged(self): action = self.sender() action.mode.enabled = action.isChecked() def main(): app = QtGui.QApplication(sys.argv) win = PythonEditorWindow() win.show() app.exec_() if __name__ == "__main__": main()
Python
0.000001
@@ -1166,16 +1166,83 @@ 5, 28))%0A + fi = FoldingIndicator(50, 60)%0A fi.state = fi.FOLDED%0A @@ -1283,32 +1283,10 @@ tor( -FoldingIndicator(50, 60) +fi )%0A
147a24ea0ba9da03b3774b7993e20e785776e027
Use sys.nstates in stead of using A.shape[0]
control/passivity.py
control/passivity.py
''' Author: Mark Yeatman Date: May 15, 2022 ''' from . import statesp as ss import numpy as np import cvxopt as cvx def is_passive(sys): ''' Indicates if a linear time invarient system is passive Constructs a linear matrix inequality and a feasibility optimization such that is a solution exists, the system is passive. The source for the algorithm is: McCourt, Michael J., and Panos J. Antsaklis. "Demonstrating passivity and dissipativity using computational methods." ISIS 8 (2013). ''' A = sys.A B = sys.B C = sys.C D = sys.D def make_LMI_matrix(P): V = np.vstack(( np.hstack((A.T @ P + P@A, P@B)), np.hstack((B.T@P, np.zeros_like(D)))) ) return V P = np.zeros_like(A) matrix_list = [] state_space_size = A.shape[0] for i in range(0, state_space_size): for j in range(0, state_space_size): if j <= i: P = P*0.0 P[i, j] = 1.0 P[j, i] = 1.0 matrix_list.append(make_LMI_matrix(P).flatten()) coefficents = np.vstack(matrix_list).T constants = -np.vstack(( np.hstack((np.zeros_like(A), - C.T)), np.hstack((- C, -D - D.T))) ) number_of_opt_vars = int( (state_space_size**2-state_space_size)/2 + state_space_size) c = cvx.matrix(0.0, (number_of_opt_vars, 1)) # crunch feasibility solution sol = cvx.solvers.sdp(c, Gs=[cvx.matrix(coefficents)], hs=[cvx.matrix(constants)]) return (sol["x"] is not None)
Python
0.000008
@@ -825,18 +825,19 @@ e = -A.shape%5B0%5D +sys.nstates %0A
b8e556871ff4aff9b85c67cc010814a0e6f60386
Add new constants and change existing file names.
const.py
const.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module defines constant values for the ScrambleSuit protocol. While some values can be changed, in general they should not. If you do not obey, be at least careful because the protocol could easily break. """ # FIXME - Directory where long-lived information is stored. DATA_DIRECTORY = "/tmp/" # Divisor (in seconds) for the UNIX epoch used to defend against replay # attacks. EPOCH_GRANULARITY = 3600 # Flags which can be set in a ScrambleSuit protocol message. FLAG_PAYLOAD = (1 << 0) FLAG_NEW_TICKET = (1 << 1) FLAG_CONFIRM_TICKET = (1 << 2) # Length of ScrambleSuit's header in bytes. HDR_LENGTH = 16 + 2 + 2 + 1 # Length of the HMAC-SHA256-128 in bytes. HMAC_LENGTH = 16 # Key rotation time for session ticket keys in seconds. KEY_ROTATION_TIME = 60 * 60 * 24 * 7 # File where session ticket keys are stored. KEY_STORE = DATA_DIRECTORY + "ticket_keys.bin" # Marker used to easily locate the HMAC authenticating handshake messages in # bytes. MARKER_LENGTH = 16 # Key length for the master key in bytes. MASTER_KEY_LENGTH = 32 # The maximum amount of padding to be appended to handshake data. MAX_PADDING_LENGTH = 4096 # Length of ScrambleSuit's MTU in bytes. MTU = 1460 # Maximum payload unit of a ScrambleSuit message in bytes. MPU = MTU - HDR_LENGTH # Length of a UniformDH public key. PUBLIC_KEY_LENGTH = 192 # Files which hold the replay dictionaries. UNIFORMDH_REPLAY_FILE = DATA_DIRECTORY + "uniformdh_replay_dict.pickle" TICKET_REPLAY_FILE = DATA_DIRECTORY + "ticket_replay_dict.pickle" # Life time of session tickets in seconds. SESSION_TICKET_LIFETIME = 60 * 60 * 24 * 7 # SHA256's digest length in bytes. SHA256_DIGEST_LENGTH = 32 # The length of the UniformDH shared secret in bytes. SHARED_SECRET_LENGTH = 32 # States which are used for the protocol state machine. ST_WAIT_FOR_AUTH = 0 ST_CONNECTED = 1 # File which holds our session ticket. # FIXME - multiple session tickets for multiple servers must be supported. TICKET_FILE = DATA_DIRECTORY + "session_ticket.bin" # Length of a session ticket in bytes. TICKET_LENGTH = 112 # The protocol name which is used in log messages. TRANSPORT_NAME = "ScrambleSuit"
Python
0
@@ -261,16 +261,165 @@ k.%0A%22%22%22%0A%0A +# Length of the HMAC used to authenticate the ticket.%0AHMAC_KEY_LENGTH = 32%0A%0A# Length of the AES key used to encrypt the ticket.%0AAES_KEY_LENGTH = 16%0A%0A # FIXME @@ -470,16 +470,16 @@ stored.%0A - DATA_DIR @@ -758,16 +758,47 @@ (1 %3C%3C 2) +%0AFLAG_PRNG_SEED = (1 %3C%3C 3) %0A%0A# Leng @@ -1105,19 +1105,22 @@ et_keys. -bin +pickle %22%0A%0A# Mar @@ -1576,16 +1576,109 @@ = 192%0A%0A +# Length of the PRNG seed used to generate probability distributions.%0APRNG_SEED_LENGTH = 32%0A%0A # Files @@ -1852,16 +1852,127 @@ ickle%22%0A%0A +# File which holds the server's state information.%0ASERVER_STATE_FILE = DATA_DIRECTORY + %22server_state.pickle%22%0A%0A # Life t @@ -2449,19 +2449,22 @@ _ticket. -bin +pickle %22%0A%0A# Len
84bcae49475d0d0ce0c14d671b363c488d93bb9f
Add skip reason
fmriprep/workflows/bold/tests/test_util.py
fmriprep/workflows/bold/tests/test_util.py
''' Testing module for fmriprep.workflows.bold.util ''' import pytest import os import numpy as np from nipype.utils.filemanip import fname_presuffix from nilearn.image import load_img from ..util import init_bold_reference_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) @pytest.mark.skipif(not os.getenv('FMRIPREP_REGRESSION_SOURCE') or not os.getenv('FMRIPREP_REGRESSION_TARGETS')) @pytest.mark.parametrize('input_fname,expected_fname', [ (os.path.join(os.getenv('FMRIPREP_REGRESSION_SOURCE', ''), base_fname), fname_presuffix(base_fname, suffix='_mask', use_ext=True, newpath=os.getenv('FMRIPREP_REGRESSION_TARGETS', ''))) for base_fname in ( 'ds000116/sub-12_task-visualoddballwithbuttonresponsetotargetstimuli_run-02_bold.nii.gz', # 'ds000133/sub-06_ses-post_task-rest_run-01_bold.nii.gz', # 'ds000140/sub-32_task-heatpainwithregulationandratings_run-02_bold.nii.gz', # 'ds000157/sub-23_task-passiveimageviewing_bold.nii.gz', # 'ds000210/sub-06_task-rest_run-01_echo-1_bold.nii.gz', # 'ds000210/sub-06_task-rest_run-01_echo-2_bold.nii.gz', # 'ds000210/sub-06_task-rest_run-01_echo-3_bold.nii.gz', # 'ds000216/sub-03_task-rest_echo-1_bold.nii.gz', # 'ds000216/sub-03_task-rest_echo-2_bold.nii.gz', # 'ds000216/sub-03_task-rest_echo-3_bold.nii.gz', # 'ds000216/sub-03_task-rest_echo-4_bold.nii.gz', # 'ds000237/sub-03_task-MemorySpan_acq-multiband_run-01_bold.nii.gz', # 'ds000237/sub-06_task-MemorySpan_acq-multiband_run-01_bold.nii.gz', ) ]) def test_masking(input_fname, expected_fname): bold_reference_wf = init_bold_reference_wf(enhance_t2=True) bold_reference_wf.inputs.inputnode.bold_file = input_fname res = bold_reference_wf.run() combine_masks = [node for node in res.nodes if node.name.endswith('combine_masks')][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap > 0.95, input_fname
Python
0.000001
@@ -612,16 +612,100 @@ ARGETS') +,%0A reason='FMRIPREP_REGRESSION_%7BSOURCE,TARGETS%7D env vars not set' )%0A@pytes
ae0a02ed13c42537dae9ae9909ea310bb9ee1a10
remove unused config change detection code
ceilometer/agent.py
ceilometer/agent.py
# # Copyright 2013 Intel Corp. # Copyright 2014 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. import hashlib import os import pkg_resources from oslo_log import log from oslo_utils import fnmatch import six import yaml LOG = log.getLogger(__name__) class ConfigException(Exception): def __init__(self, cfg_type, message, cfg): self.cfg_type = cfg_type self.msg = message self.cfg = cfg def __str__(self): return '%s %s: %s' % (self.cfg_type, self.cfg, self.msg) class SourceException(Exception): def __init__(self, message, cfg): self.msg = message self.cfg = cfg def __str__(self): return 'Source definition invalid: %s (%s)' % (self.msg, self.cfg) class ConfigManagerBase(object): """Base class for managing configuration file refresh""" def __init__(self, conf): self.conf = conf self.cfg_loc = None def load_config(self, cfg_file, fallback_cfg_prefix='pipeline/data/'): """Load a configuration file and set its refresh values.""" if os.path.exists(cfg_file): self.cfg_loc = cfg_file else: self.cfg_loc = self.conf.find_file(cfg_file) if not self.cfg_loc and fallback_cfg_prefix is not None: LOG.debug("No pipeline definitions configuration file found! " "Using default config.") self.cfg_loc = pkg_resources.resource_filename( __name__, fallback_cfg_prefix + cfg_file) with open(self.cfg_loc) as fap: data = fap.read() conf = yaml.safe_load(data) self.cfg_mtime = self.get_cfg_mtime() self.cfg_hash = self.get_cfg_hash() LOG.info("Config file: %s", conf) return conf def get_cfg_mtime(self): """Return modification time of cfg file""" return os.path.getmtime(self.cfg_loc) if self.cfg_loc else None def get_cfg_hash(self): """Return hash of configuration file""" if not self.cfg_loc: return None with open(self.cfg_loc) as fap: data = fap.read() if six.PY3: data = data.encode('utf-8') file_hash = hashlib.md5(data).hexdigest() return file_hash def cfg_changed(self): """Returns hash of changed cfg else False.""" mtime = self.get_cfg_mtime() if mtime > self.cfg_mtime: LOG.info('Configuration file has been updated.') self.cfg_mtime = mtime _hash = self.get_cfg_hash() if _hash != self.cfg_hash: LOG.info("Detected change in configuration.") return _hash return False class Source(object): """Represents a generic source""" def __init__(self, cfg): self.cfg = cfg try: self.name = cfg['name'] except KeyError as err: raise SourceException( "Required field %s not specified" % err.args[0], cfg) def __str__(self): return self.name def check_source_filtering(self, data, d_type): """Source data rules checking - At least one meaningful datapoint exist - Included type and excluded type can't co-exist on the same pipeline - Included type meter and wildcard can't co-exist at same pipeline """ if not data: raise SourceException('No %s specified' % d_type, self.cfg) if ([x for x in data if x[0] not in '!*'] and [x for x in data if x[0] == '!']): raise SourceException( 'Both included and excluded %s specified' % d_type, self.cfg) if '*' in data and [x for x in data if x[0] not in '!*']: raise SourceException( 'Included %s specified with wildcard' % d_type, self.cfg) @staticmethod def is_supported(dataset, data_name): # Support wildcard like storage.* and !disk.* # Start with negation, we consider that the order is deny, allow if any(fnmatch.fnmatch(data_name, datapoint[1:]) for datapoint in dataset if datapoint[0] == '!'): return False if any(fnmatch.fnmatch(data_name, datapoint) for datapoint in dataset if datapoint[0] != '!'): return True # if we only have negation, we suppose the default is allow return all(datapoint.startswith('!') for datapoint in dataset)
Python
0.000005
@@ -605,23 +605,8 @@ se.%0A -import hashlib%0A impo @@ -693,19 +693,8 @@ tch%0A -import six%0A impo @@ -1366,36 +1366,8 @@ conf -%0A self.cfg_loc = None %0A%0A @@ -1548,37 +1548,32 @@ e):%0A -self. cfg_loc = cfg_fi @@ -1593,37 +1593,32 @@ se:%0A -self. cfg_loc = self.c @@ -1645,36 +1645,35 @@ le)%0A + if not -self. cfg_loc and @@ -1705,16 +1705,20 @@ t None:%0A + @@ -1806,16 +1806,20 @@ + %22Using d @@ -1843,29 +1843,28 @@ -self. + cfg_loc = pk @@ -1894,16 +1894,20 @@ lename(%0A + @@ -1968,541 +1968,90 @@ -with open(self.cfg_loc) as fap:%0A data = fap.read()%0A conf = yaml.safe_load(data)%0A self.cfg_mtime = self.get_cfg_mtime()%0A self.cfg_hash = self.get_cfg_hash()%0A LOG.info(%22Config file: %25s%22, conf)%0A return conf%0A%0A def get_cfg_mtime(self):%0A %22%22%22Return modification time of cfg file%22%22%22%0A return os.path.getmtime(self.cfg_loc) if self.cfg_loc else None%0A%0A def get_cfg_hash(self):%0A %22%22%22Return hash of configuration file%22%22%22%0A if not self.cfg_loc:%0A return None%0A + else:%0A raise RuntimeError(%22No configuration file can be found%22) %0A @@ -2065,21 +2065,16 @@ th open( -self. cfg_loc) @@ -2098,320 +2098,35 @@ -data = fap.read()%0A if six.PY3:%0A data = data.encode('utf-8')%0A%0A file_hash = hashlib.md5(data).hexdigest()%0A return file_hash%0A%0A def cfg_changed(self):%0A %22%22%22Returns hash of changed cfg else False.%22%22%22%0A mtime = self.get_cfg_mtime()%0A if mtime %3E self.cfg_mtime:%0A +conf = yaml.safe_load(fap)%0A @@ -2142,236 +2142,41 @@ nfo( -' +%22 Config -uration file has been updated.')%0A self.cfg_mtime = mtime%0A _hash = self.get_cfg_hash()%0A if _hash != self.cfg_hash:%0A LOG.info(%22Detected change in configuration.%22)%0A + file: %25s%22, conf)%0A @@ -2175,45 +2175,19 @@ - return -_hash%0A return False +conf %0A%0A%0Ac
f6efc8ee2e026dcc1bdad9d52afff8a489784eb1
correct commissions
compfipy/portfolio.py
compfipy/portfolio.py
""" portfolio.py Define a specifc group of Assets along with functions that pertain to the portfolio. ### Portfolio - [x] Aggregate specific Assets in Table - [x] keep track of positions - [x] keep track of fees - [x] keep track of cost - [x] keep track of value - [x] Enter and Exit position - [ ] ???Rebalance whole Portfolio??? - [x] Return weights - [ ] Total Unrealized Performance measures (based on specific time) - [ ] Total Unrealized Risk measures (based on specific time) - [ ] Total Unrealized Market Comparisons (based on specific time) - [ ] Total Realized Performance measures (based on holdings) - [ ] Total Realized Risk measures (based on holdings) - [ ] Total Realized Market Comparisons (based on holdings) - [ ] Summarize Portfolio - [ ] """ # libs used import copy import datetime as dt import pandas as pd import numpy as np import scipy.stats import collections import tabulate class Portfolio(object): """ define a collection of assets with holdings """ def __init__(self, assets=None, initial_positions=None, cash=10000.0): # create empty tables empty_table = pd.DataFrame( np.zeros((len(assets[0].close), len(assets))), columns=[symbol for symbol in assets.keys()], index=assets[0].close.index ) positions = copy.deepcopy(empty_table) trades = copy.deepcopy(empty_table) # initial position if given for symbol, value in initial_positions.items(): trades[symbol][0] = value * assets[symbol].close[0] positions[symbol][:] = value self.init_cash = cash self.cash = cash self.assets = assets self.positions = positions self.trades = trades def summary(self): """ "summarize all the holdings and performance of the portfolio """ pass def trade(self, symbol='', date=-1, amount=0.0, commission_min=1.0, commission=0.0075): """ execute a trade and update positions """ self.trades[symbol][date] = amount * self.assets[symbol].close[date] + min(commission_min, commission * amount) self.positions[symbol][date:] = self.positions[symbol][date] + amount # Calculate Asset-wise numbers and statistics def close(self, date_range=slice(None, None, None)): """return closing price for each asset""" return pd.DataFrame({symbol: asset.close[date_range] for symbol, asset in self.assets.items()}) def pct_change(self, date_range=slice(None, None, None)): """return closing price returns for each asset""" return 100.0 * self.close(date_range).pct_change() def values(self, date_range=slice(None, None, None)): """ calculate value of each position (shares * close) """ return self.positions[:][date_range] * self.close(date_range) def weights(self, date_range=slice(None, None, None)): """ return asset weights of portfolio """ return self.values(date_range=date_range) / self.total_value(date_range=date_range) def cost_bases(self, date_range=slice(None, None, None)): """ calculate cost basis of assets """ costs = self.trades.cumsum() return costs[date_range] def gains(self, date_range=slice(None, None, None)): """ calculate gain of assets""" return self.values(date_range=date_range) - self.cost_bases(date_range=date_range) def returns(self, date_range=slice(None, None, None)): """calculate returns of assets""" return 100.0 * self.gains(date_range=date_range) / self.cost_bases(date_range=date_range) # Calculate Portfolio totals as sums or weighted sums of individual assets def total_value(self, date_range=slice(None, None, None)): """calculate portfolio value""" return self.values(date_range=date_range).sum(axis=1) def total_value(self, date_range=slice(None, None, None)): """calculate portfolio balance (asset value + cash)""" return self.total_value(date_range=date_range) + self.cash def total_cost_basis(self, date_range=slice(None, None, None)): """calculate portfolio cost basis""" return self.cost_bases(date_range=date_range).sum(axis=1) # Total Performance def total_gain(self, date_range=slice(None, None, None)): """calculate portfolio gain""" return self.gains(date_range=date_range).sum(axis=1) def total_return(self, date_range=slice(None, None, None)): """calculate portfolio returns""" return (self.weights(date_range=date_range) * self.returns(date_range=date_range)).sum(axis=1)
Python
0.000006
@@ -1997,24 +1997,25 @@ ons %22%22%22%0A +%0A self.tra @@ -2010,33 +2010,19 @@ -self.trades%5Bsymbol%5D%5Bdate%5D +trade_price = a @@ -2064,18 +2064,18 @@ ate%5D + m -in +ax (commiss @@ -2083,16 +2083,20 @@ on_min, +abs( commissi @@ -2107,16 +2107,110 @@ amount) +)%0A%0A self.cash = self.cash - trade_price%0A self.trades%5Bsymbol%5D%5Bdate%5D = trade_price %0A
2a030ce151cdb6eaaa3933bd7f958edf658ab209
Make the parent directory part of the Python path for custom management commands to work.
manage.py
manage.py
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
0
@@ -15,16 +15,77 @@ python%0A +import os%0Aimport sys%0Asys.path.append(os.path.abspath(%22..%22))%0A%0A from dja
0feb5947af0dacc53ba624723593dd88b0b4653a
Fix shop creation
byceps/services/shop/shop/service.py
byceps/services/shop/shop/service.py
""" byceps.services.shop.shop.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from typing import Optional from ....database import db from ....typing import PartyID from .models import Shop as DbShop from .transfer.models import Shop, ShopID def create_shop(party_id: PartyID) -> Shop: """Create a shop.""" shop = DbShop(party_id) db.session.add(shop) db.session.commit() return _db_entity_to_shop(shop) def find_shop(shop_id: ShopID) -> Optional[Shop]: """Return the shop with that id, or `None` if not found.""" shop = DbShop.query.get(shop_id) return _db_entity_to_shop(shop) def _db_entity_to_shop(shop: DbShop) -> Shop: return Shop( shop.id, shop.party_id, )
Python
0.000001
@@ -414,24 +414,34 @@ op = DbShop( +party_id, party_id)%0A%0A
c0e903c3dab9fea0594d023ab9c049ca408bd9a4
Cover text: outlined
cover.py
cover.py
from PIL import Image, ImageDraw, ImageFont from io import BytesIO import textwrap def make_cover(title, author, width=600, height=800, fontname="Helvetica", fontsize=40, bgcolor=(120, 20, 20), textcolor=(255, 255, 255), wrapat=30): img = Image.new("RGBA", (width, height), bgcolor) draw = ImageDraw.Draw(img) title = textwrap.fill(title, wrapat) author = textwrap.fill(author, wrapat) font = ImageFont.truetype(font=fontname, size=fontsize) title_size = draw.textsize(title, font=font) draw.text(((width - title_size[0]) / 2, 100), title, textcolor, font=font) font = ImageFont.truetype(font=fontname, size=fontsize - 2) author_size = draw.textsize(author, font=font) draw.text(((width - author_size[0]) / 2, 100 + title_size[1] + 70), author, textcolor, font=font) draw = ImageDraw.Draw(img) output = BytesIO() img.save(output, "PNG") output.name = 'cover.png' # writing left the cursor at the end of the file, so reset it output.seek(0) return output if __name__ == '__main__': f = make_cover('Test of a Title which is quite long and will require multiple lines', 'Some Dude') with open('output.png', 'wb') as out: out.write(f.read())
Python
0.999509
@@ -504,32 +504,128 @@ , font=font)%0A + draw_text_outlined(draw, ((width - title_size%5B0%5D) / 2, 100), title, textcolor, font=font)%0A # draw.text(((wid @@ -804,30 +804,45 @@ nt)%0A draw -. +_ text -( +_outlined(draw, ((width - au @@ -922,40 +922,8 @@ t)%0A%0A - draw = ImageDraw.Draw(img)%0A%0A @@ -1104,16 +1104,516 @@ utput%0A%0A%0A +def draw_text_outlined(draw, xy, text, fill=None, font=None, anchor=None):%0A x, y = xy%0A%0A # Outline%0A draw.text((x - 1, y), text=text, fill=(0, 0, 0), font=font, anchor=anchor)%0A draw.text((x + 1, y), text=text, fill=(0, 0, 0), font=font, anchor=anchor)%0A draw.text((x, y - 1), text=text, fill=(0, 0, 0), font=font, anchor=anchor)%0A draw.text((x, y + 1), text=text, fill=(0, 0, 0), font=font, anchor=anchor)%0A%0A # Fill%0A draw.text(xy, text=text, fill=fill, font=font, anchor=anchor)%0A%0A%0A if __nam
99bfdd1f038865a3558e212777b0a5641d87c170
Add report types to NEA.
inspectors/nea.py
inspectors/nea.py
#!/usr/bin/env python import datetime import logging import os import re from urllib.parse import urljoin from bs4 import BeautifulSoup from utils import utils, inspector # http://arts.gov/oig # Oldest report: 2005 # options: # standard since/year options for a year range to fetch from. # report_id: only bother to process a single report # # Notes for IG's web team: # AUDIT_REPORTS_URL = "http://arts.gov/oig/reports/audits" SPECIAL_REVIEWS_URL = "http://arts.gov/oig/reports/specials" SEMIANNUAL_REPORTS_URL = "http://arts.gov/oig/reports/semi-annual" PEER_REVIEWS_URL = "http://arts.gov/oig/reports/external-peer-reviews" FISMA_REPORTS_URL = "http://arts.gov/oig/reports/fisma" REPORT_URLS = [ AUDIT_REPORTS_URL, SPECIAL_REVIEWS_URL, SEMIANNUAL_REPORTS_URL, PEER_REVIEWS_URL, FISMA_REPORTS_URL, ] def run(options): year_range = inspector.year_range(options) only_report_id = options.get('report_id') # Pull the reports for url in REPORT_URLS: doc = BeautifulSoup(utils.download(url)) results = doc.select("div.field-item li") for result in results: report = report_from(result, url, year_range) if report: # debugging convenience: can limit to single report if only_report_id and (report['report_id'] != only_report_id): continue inspector.save_report(report) def report_from(result, landing_url, year_range): link = result.find("a") if not link: return title = link.text report_url = urljoin(landing_url, link.get('href')) report_filename = report_url.split("/")[-1] report_id, _ = os.path.splitext(report_filename) estimated_date = False try: published_on_text = title.split("-")[-1].split("–")[-1].strip() published_on = datetime.datetime.strptime(published_on_text, '%B %d, %Y') except ValueError: # For reports where we can only find the year, set them to Nov 1st of that year try: published_on_year = int(result.find_previous("h3").text.strip()) except AttributeError: published_on_year = int(re.search('(\d+)', title).group()) published_on = datetime.datetime(published_on_year, 11, 1) estimated_date = True if published_on.year not in year_range: logging.debug("[%s] Skipping, not in requested range." % report_url) return report = { 'inspector': 'nea', 'inspector_url': 'http://arts.gov/oig', 'agency': 'nea', 'agency_name': 'National Endowment for the Arts', 'report_id': report_id, 'url': report_url, 'title': title, 'published_on': datetime.datetime.strftime(published_on, "%Y-%m-%d"), } if estimated_date: report['estimated_date'] = estimated_date return report utils.run(run) if (__name__ == "__main__") else None
Python
0
@@ -704,11 +704,20 @@ S = -%5B +%7B %0A + %22audit%22: AUD @@ -733,16 +733,30 @@ S_URL,%0A + %22evaluation%22: SPECIAL @@ -770,16 +770,37 @@ S_URL,%0A + %22semiannual_report%22: SEMIANN @@ -817,16 +817,31 @@ S_URL,%0A + %22peer_review%22: PEER_RE @@ -852,16 +852,25 @@ S_URL,%0A + %22fisma%22: FISMA_R @@ -881,17 +881,17 @@ TS_URL,%0A -%5D +%7D %0A%0Adef ru @@ -1019,16 +1019,29 @@ ts%0A for + report_type, url in @@ -1051,16 +1051,24 @@ ORT_URLS +.items() :%0A do @@ -1214,24 +1214,37 @@ result, url, + report_type, year_range) @@ -1452,16 +1452,16 @@ eport)%0A%0A - def repo @@ -1488,16 +1488,29 @@ ing_url, + report_type, year_ra @@ -2568,16 +2568,41 @@ Arts',%0A + 'type': report_type,%0A 'rep
91a8c5312c58edff070915fc5d182b35f60ef0fa
allow for error recovery in cases where a file sync fails.
sync-dropbox-to-ftp.py
sync-dropbox-to-ftp.py
#!/usr/bin/env python3 """The initial options file should look like: { "state": { "cursor": null }, "options": { "ftp": { "auth": { "host": "FTP_HOST", "user": "FTP_USER", "passwd": "FTP_PASSWORD" }, "path": "FTP_DIRECTORY_NAME" }, "dropbox": { "auth": { "access_token": "ACCESS_TOKEN" }, "path": "DROPBOX_DIRECTORY_NAME" } } } """ import argparse import contextlib import ftplib import json import os.path import sys import urllib.parse import urllib.request class Dropbox: def __init__(self, access_token): self._access_token = access_token def _urlopen(self, url, data=None, headers={}): headers['Authorization'] = 'Bearer ' + self._access_token if data is not None: data = urllib.parse.urlencode(data).encode() request = urllib.request.Request(url=url, data=data, headers=headers) return urllib.request.urlopen(request, cadefault=True) def get_added_files(self, path, cursor): # http.client.HTTPConnection.debuglevel = 1 data = {'path_prefix': path} deltas = {'has_more': True} while deltas['has_more']: if cursor: data['cursor'] = cursor deltas = json.loads( self._urlopen(url='https://api.dropbox.com/1/delta', data=data) .read().decode()) added_files = [entry[0] for entry in deltas['entries'] if entry[1]] cursor = deltas['cursor'] return added_files, cursor def get_file(self, path): return self._urlopen('https://api-content.dropbox.com/1/files/auto/' + path) @contextlib.contextmanager def Ftp(host, user, passwd): with ftplib.FTP(host=host) as ftp: ftp.login(user=user, passwd=passwd) class Actions: def __init__(self, ftp): self._ftp = ftp def upload(self, path, f, callback=lambda num_bytes: None): num_bytes = [0] def cb(buff): num_bytes[0] += len(buff) callback(num_bytes[0]) self._ftp.storbinary('STOR ' + os.path.join(self._ftp.pwd(), path), f, callback=cb) yield Actions(ftp) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--conf", default="~/.sync-dropbox-to-ftp.conf") parser.add_argument("--noupdate", action="store_true", default=False, help="Do not update the configuration file.") args = parser.parse_args() conf_file = os.path.expanduser(args.conf) with open(conf_file) as f: conf = json.load(f) options = conf['options'] state = conf['state'] db = Dropbox(**options['dropbox']['auth']) added_files, state['cursor'] = db.get_added_files(options['dropbox']['path'], state['cursor']) with Ftp(**options['ftp']['auth']) as ftp: for path in added_files: def display(num_bytes): print('{}: Uploaded {} bytes...'.format(path, num_bytes), end='\r', file=sys.stderr, flush=True) display(0) ftp.upload(os.path.join(options['ftp']['path'], os.path.basename(path)), db.get_file(path), callback=display) print(path) if not args.noupdate: with open(conf_file, 'w') as f: json.dump(conf, f, indent=2)
Python
0
@@ -93,16 +93,28 @@ r%22: null +, %22left%22: %5B%5D %7D,%0A %22o @@ -2554,27 +2554,79 @@ th'%5D)%0A -added_files +left, state%5B'left'%5D = state%5B'left'%5D, %5B%5D%0A if not left:%0A left , state%5B @@ -2767,21 +2767,27 @@ in -added_files:%0A +left:%0A try:%0A @@ -2812,16 +2812,18 @@ bytes):%0A + @@ -2879,30 +2879,16 @@ _bytes), -%0A end='%5Cr @@ -2925,16 +2925,18 @@ )%0A + display( @@ -2939,16 +2939,18 @@ lay(0)%0A%0A + ft @@ -3037,16 +3037,18 @@ + db.get_f @@ -3058,16 +3058,18 @@ (path),%0A + @@ -3105,18 +3105,261 @@ -print(path +except Exception as e:%0A print('%5Cn%7B%7D: Failed with %7B%7D'.format(path, e), file=sys.stderr, flush=True)%0A state%5B'left'%5D.append(path)%0A else:%0A print('%5Cn%7B%7D: Done'.format(path), file=sys.stderr, flush=True)%0A print(path, flush=True )%0A%0A
5f15ad2da19cc3872b5e6fbbaa5db8b902cef720
Revert "we don't want this commit"
manage.py
manage.py
#!/usr/bin/env python """ Usage: manage.py {lms|cms} [--settings env] ... Run django management commands. Because edx-platform contains multiple django projects, the first argument specifies which project to run (cms [Studio] or lms [Learning Management System]). By default, those systems run in with a settings file appropriate for development. However, by passing the --settings flag, you can specify what environment specific settings file to use. Any arguments not understood by this manage.py will be passed to django-admin.py """ import os import sys import importlib from argparse import ArgumentParser def parse_args(): """Parse edx specific arguments to manage.py""" parser = ArgumentParser() subparsers = parser.add_subparsers(title='system', description='edX service to run') lms = subparsers.add_parser( 'lms', help='Learning Management System', add_help=False, usage='%(prog)s [options] ...' ) lms.add_argument('-h', '--help', action='store_true', help='show this help message and exit') lms.add_argument( '--settings', help="Which django settings module to use under lms.envs. If not provided, the DJANGO_SETTINGS_MODULE " "environment variable will be used if it is set, otherwise it will default to lms.envs.dev") lms.add_argument( '--service-variant', choices=['lms', 'lms-xml', 'lms-preview'], default='lms', help='Which service variant to run, when using the aws environment') lms.set_defaults( help_string=lms.format_help(), settings_base='lms/envs', default_settings='lms.envs.dev', startup='lms.startup', ) cms = subparsers.add_parser( 'cms', help='Studio', add_help=False, usage='%(prog)s [options] ...' ) cms.add_argument( '--settings', help="Which django settings module to use under cms.envs. If not provided, the DJANGO_SETTINGS_MODULE " "environment variable will be used if it is set, otherwise it will default to cms.envs.dev") cms.add_argument('-h', '--help', action='store_true', help='show this help message and exit') cms.set_defaults( help_string=cms.format_help(), settings_base='cms/envs', default_settings='cms.envs.dev', service_variant='cms', startup='cms.startup', ) edx_args, django_args = parser.parse_known_args() if edx_args.help: print "edX:" print edx_args.help_string return edx_args, django_args if __name__ == "__main__": edx_args, django_args = parse_args() if edx_args.settings: os.environ["DJANGO_SETTINGS_MODULE"] = edx_args.settings_base.replace('/', '.') + "." + edx_args.settings else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", edx_args.default_settings) os.environ.setdefault("SERVICE_VARIANT", edx_args.service_variant) if edx_args.help: print "Django:" # This will trigger django-admin.py to print out its help django_args.append('--help') startup = importlib.import_module(edx_args.startup) startup.run() from django.core.management import execute_from_command_line # this is a commited changed,that we dont want execute_from_command_line([sys.argv[0]] + django_args)
Python
0
@@ -3238,58 +3238,8 @@ ine%0A - # this is a commited changed,that we dont want %0A
8c233868e82a6828d21574b0d488699c1c7b1443
Update test_ValueType.py
cairis/cairis/test/test_ValueType.py
cairis/cairis/test/test_ValueType.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 unittest import os import json import BorgFactory from Borg import Borg from ValueTypeParameters import ValueTypeParameters class ValueTypeTest(unittest.TestCase): def setUp(self): BorgFactory.initialise() f = open(os.environ['CAIRIS_SRC'] + '/test/valuetypes.json') d = json.load(f) f.close() self.iVtypes = d['valuetypes'] def testValueType(self): ivt1 = ValueTypeParameters(self.iVtypes[0]["theName"], self.iVtypes[0]["theDescription"], self.iVtypes[0]["vulnerability_type"]) ivt2 = ValueTypeParameters(self.iVtypes[1]["theName"], self.iVtypes[1]["theDescription"], self.iVtypes[1]["threat_type"]) b = Borg() b.dbProxy.addValueType(ivt1) b.dbProxy.addValueType(ivt2) oVtypes = b.dbProxy.getValueTypes() ovt1 = oVtypes[self.iVtypes[0]["theName"]] self.assertEqual(ivt1.name(), ovt1.name()) self.assertEqual(ivt1.description(),ovt1.description()) self.assertEqual(ivt1.type(),ovt1.type()) ovt2 = oVtypes[self.iVtypes[1]["theName"]] self.assertEqual(ivt2.name(), ovt2.name()) self.assertEqual(ivt2.description(),ovt2.description()) self.assertEqual(ivt2.type(),ovt2.type()) b.dbProxy.deleteVulnerabilityType(ovt1.id()) b.dbProxy.deleteThreatType(ovt2.id()) def tearDown(self): b = Borg() b.dbProxy.close() if __name__ == '__main__': unittest.main()
Python
0.000001
@@ -1294,23 +1294,12 @@ 0%5D%5B%22 -vulnerability_t +theT ype%22 @@ -1418,14 +1418,10 @@ %5B%22th -reat_t +eT ype%22
278c7817120370c22cad2e56471e7d1673312e3e
Use functools.wraps rather than manually setting __name__
curry.py
curry.py
from inspect import signature, isclass import sys import unittest def get_arg_count(fun): if isclass(fun): return len(signature(fun.__call__).parameters) else: return len(signature(fun).parameters) def curry(fun): arg_count = get_arg_count(fun) def curried(*old_args, **old_kwargs): args_store = list(old_args) kwargs_store = old_kwargs def _inner(*new_args, **new_kwargs): nonlocal args_store, kwargs_store new_args = args_store + list(new_args) kwargs_store.update(new_kwargs) args_store = new_args _inner.__name__ = fun.__name__ if len(args_store) + len(kwargs_store) == arg_count: return fun(*args_store, **kwargs_store) else: return _inner _inner.__name__ = fun.__name__ return _inner curried.__name__ = fun.__name__ return curried class CurryTest(unittest.TestCase): def test_two_args(self): add = curry(lambda a, b: a + b) self.assertEqual(3, add(1)(2)) def test_three_args(self): add3 = curry(lambda a, b, c: a + b + c) self.assertEqual(6, add3(1)(2)(3)) def test_args_dont_persist(self): add = curry(lambda a, b: a + b) add1 = add(1) add2 = add(2) self.assertEqual(2, add1(1)) self.assertEqual(3, add2(1)) def test_mutable_args(self): def concat(a, b): ret = [] ret.extend(a) ret.extend(b) return ret concat = curry(concat) self.assertEqual([1, 2, 3, 4], concat([1, 2])([3, 4])) def test_builtin(self): add_1_to_each = curry(map)(lambda x: x + 1) self.assertEqual([2, 3, 4, 5], list(add_1_to_each([1, 2, 3, 4]))) def test_positional_kwargs(self): add_default = curry(lambda a, b=10: a + b) self.assertEqual(3, add_default(1)(2)) def test_kwargs(self): @curry def add(a, *, b): return a + b self.assertEqual(12, add(2)(b=10)) def test_preserve_name(self): def add(a, b): return a + b add = curry(add) self.assertEqual('add', add.__name__) self.assertEqual('add', add(1).__name__) if __name__ == '__main__': unittest.main()
Python
0
@@ -1,8 +1,36 @@ +from functools import wraps%0A from ins @@ -298,16 +298,36 @@ nt(fun)%0A + %0A @wraps(fun) %0A def @@ -427,24 +427,52 @@ old_kwargs%0A + %0A @wraps(fun) %0A def @@ -686,51 +686,8 @@ gs%0A%0A - _inner.__name__ = fun.__name__%0A @@ -864,97 +864,22 @@ -_inner.__name__ = fun.__name__%0A return _inner%0A%0A curried.__name__ = fun.__name__ +return _inner%0A %0A
7cac8f8ba591315d68e223503c4e93f976c8d89d
Set default race and class without extra database queries
characters/views.py
characters/views.py
from django.shortcuts import get_object_or_404, redirect, render from characters.forms import CharacterForm from characters.models import Character, Class, Race def index(request): all_characters = Character.objects.all() context = {'all_characters': all_characters} return render(request, 'characters/index.html', context) def view_character(request, character_id): character = get_object_or_404(Character, pk=character_id) context = {'character': character} return render(request, 'characters/view_character.html', context) def create_character(request): form = CharacterForm(request.POST or None) if request.method == 'POST' and form.is_valid(): race = Race.objects.get(id=1) cclass = Class.objects.get(id=1) character = Character( name=request.POST['name'], background=request.POST['background'], race=race, cclass=cclass ) character.save() return redirect('characters:view', character_id=character.id) context = {'form': form} return render(request, 'characters/create_character.html', context)
Python
0
@@ -687,88 +687,8 @@ ):%0A%0A - race = Race.objects.get(id=1)%0A cclass = Class.objects.get(id=1)%0A%0A @@ -836,13 +836,13 @@ race -=race +_id=1 ,%0A @@ -865,15 +865,13 @@ lass -=cclass +_id=1 %0A
daabf57935c9bec91ee4ce0bcd4713790fe928ea
use celery
daily.py
daily.py
from totalimpactwebapp.user import User from totalimpactwebapp import db import datetime import tasks """ requires these env vars be set in this environment: DATABASE_URL """ def page_query(q): offset = 0 while True: r = False for elem in q.limit(100).offset(offset): r = True yield elem offset += 100 if not r: break def add_profile_deets_for_everyone(): for user in page_query(User.query.order_by(User.url_slug.asc())): print user.url_slug # tasks.add_profile_deets.delay(user) tasks.add_profile_deets(user) def deduplicate_everyone(): for user in page_query(User.query.order_by(User.url_slug.asc())): print user.url_slug removed_tiids = tasks.deduplicate.delay(user) def put_linked_account_users_on_queue(): i = 0 # now = datetime.datetime.utcnow().isoformat() now = "2013-06-24" # for user in page_query(User.query.filter(User.next_refresh < now).order_by(User.next_refresh.asc())): # for user in page_query(User.query.filter(User.next_refresh <= now)): # for user in page_query(User.query): # linked_accounts_to_sync = { # "figshare": user.figshare_id, # "github": user.github_id, # "orcid": user.orcid_id, # "slideshare": user.slideshare_id # } # has_linked_account = [account for account in linked_accounts_to_sync if linked_accounts_to_sync[account]] # if has_linked_account: # i += 1 # print u"{i} user {url_slug} has linked account: {has_linked_account} {next_refresh} ".format( # i=i, url_slug=user.url_slug, has_linked_account=has_linked_account, next_refresh=user.next_refresh) # for account in has_linked_account: # tiids = update_from_linked_account.delay(user, account) db.create_all() add_profile_deets_for_everyone()
Python
0.000618
@@ -536,18 +536,16 @@ %0A - # tasks.a @@ -577,46 +577,8 @@ er)%0A - tasks.add_profile_deets(user)%0A %0A%0Ade
a2cc8a5e6009bda68edf85a432d9a8ec002e99a1
Fix #80
adapter/__init__.py
adapter/__init__.py
import sys PY2 = sys.version_info[0] == 2 if PY2: is_string = lambda v: isinstance(v, basestring) to_lldb_str = lambda s: s.encode('utf8', 'backslashreplace') from_lldb_str = lambda s: s.decode('utf8', 'replace') xrange = xrange else: is_string = lambda v: isinstance(v, str) to_lldb_str = str from_lldb_str = str xrange = range import adapter.main
Python
0.000001
@@ -96,16 +96,82 @@ string)%0A + # python2-based LLDB accepts utf8-encoded ascii strings only.%0A to_l @@ -222,24 +222,57 @@ ashreplace') + if isinstance(s, unicode) else s %0A from_ll
8c73f52d180e602b79031228367411fe9610b856
Fix mcp tests.
scikits/image/graph/tests/test_mcp.py
scikits/image/graph/tests/test_mcp.py
import numpy as np from numpy.testing import * import scikits.image.graph.mcp as mcp a = np.ones((8,8), dtype=np.float32) a[1:-1, 1] = 0 a[1, 1:-1] = 0 ## array([[ 1., 1., 1., 1., 1., 1., 1., 1.], ## [ 1., 0., 0., 0., 0., 0., 0., 1.], ## [ 1., 0., 1., 1., 1., 1., 1., 1.], ## [ 1., 0., 1., 1., 1., 1., 1., 1.], ## [ 1., 0., 1., 1., 1., 1., 1., 1.], ## [ 1., 0., 1., 1., 1., 1., 1., 1.], ## [ 1., 0., 1., 1., 1., 1., 1., 1.], ## [ 1., 1., 1., 1., 1., 1., 1., 1.]], dtype=float32) def test_basic(): m = mcp.MCP(a, fully_connected=True) costs, traceback = m.find_costs([(1,6)]) return_path = m.traceback((7, 2)) assert_array_equal(costs, [[ 1., 1., 1., 1., 1., 1., 1., 1.], [ 1., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 1., 1., 1., 1., 1., 1.], [ 1., 0., 1., 2., 2., 2., 2., 2.], [ 1., 0., 1., 2., 3., 3., 3., 3.], [ 1., 0., 1., 2., 3., 4., 4., 4.], [ 1., 0., 1., 2., 3., 4., 5., 5.], [ 1., 1., 1., 2., 3., 4., 5., 6.]]) assert_array_equal(return_path, [(1, 6), (1, 5), (1, 4), (1, 3), (1, 2), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 2)]) def test_neg_inf(): expected_costs = numpy.where(a==1, np.inf, 0) expected_path = [(1, 6), (1, 5), (1, 4), (1, 3), (1, 2), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1)] test_neg = numpy.where(a==1, -1, 0) test_inf = numpy.where(a==1, np.inf, 0) m = mcp.MCP(test_neg, fully_connected=True) costs, traceback = m.find_costs([(1, 6)]) return_path = m.traceback((6, 1)) assert_array_equal(costs, expected_costs) assert_array_equal(return_path, expected_path) m = mcp.MCP(test_inf, fully_connected=True) costs, traceback = m.find_costs([(1, 6)]) return_path = m.traceback((6, 1)) assert_array_equal(costs, expected_costs) assert_array_equal(return_path, expected_path) def test_route(): return_path, cost = mcp.route_through_array(a, (1,6), (7,2), geometric=True) assert_almost_equal(cost, np.sqrt(2)/2) assert_array_equal(return_path, [(1, 6), (1, 5), (1, 4), (1, 3), (1, 2), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 2)]) def test_no_diagonal(): m = mcp.MCP(a, fully_connected=False) costs, traceback = m.find_costs([(1,6)]) return_path = m.traceback((7, 2)) assert_array_equal(costs, [[ 2., 1., 1., 1., 1., 1., 1., 2.], [ 1., 0., 0., 0., 0., 0., 0., 1.], [ 1., 0., 1., 1., 1., 1., 1., 2.], [ 1., 0., 1., 2., 2., 2., 2., 3.], [ 1., 0., 1., 2., 3., 3., 3., 4.], [ 1., 0., 1., 2., 3., 4., 4., 5.], [ 1., 0., 1., 2., 3., 4., 5., 6.], [ 2., 1., 2., 3., 4., 5., 6., 7.]]) assert_array_equal(return_path, [(1, 6), (1, 5), (1, 4), (1, 3), (1, 2), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (7, 2)]) def test_crashing(): for shape in [(100, 100), (5, 8, 13, 17)]: yield _test_random, shape def _test_random(shape): # Just tests for crashing -- not for correctness. np.random.seed(0) a = np.random.random(shape).astype(np.float32) starts = [[0]*len(shape), [-1]*len(shape), (np.random.random(len(shape))*shape).astype(int)] ends = [(np.random.random(len(shape))*shape).astype(int) for i in range(4)] m = mcp.MCP(a, fully_connected=True) costs, offsets = m.find_costs(starts) for point in [(np.random.random(len(shape))*shape).astype(int) for i in range(4)]: m.traceback(point) m._reset() m.find_costs(starts, ends) for end in ends: m.traceback(end) return a, costs, offsets if __name__ == "__main__": run_module_suite()
Python
0
@@ -1711,28 +1711,25 @@ ed_costs = n -umpy +p .where(a==1, @@ -2042,28 +2042,25 @@ test_neg = n -umpy +p .where(a==1, @@ -2083,20 +2083,17 @@ _inf = n -umpy +p .where(a
537e3855e0d4d323844b711c3f72bef21eaa565c
Update streets_helper.py
cea/datamanagement/streets_helper.py
cea/datamanagement/streets_helper.py
""" This script extracts streets from Open street maps """ from __future__ import division from __future__ import print_function import os import osmnx as ox from geopandas import GeoDataFrame as Gdf import cea.config import cea.inputlocator from cea.utilities.standardize_coordinates import get_projected_coordinate_system, get_geographic_coordinate_system __author__ = "Jimeno Fonseca" __copyright__ = "Copyright 2018, Architecture and Building Systems - ETH Zurich" __credits__ = ["Jimeno Fonseca"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" def calc_bounding_box(shapefile_surroundings, shapefile_zone): #connect both files and avoid repetition data_zone = Gdf.from_file(shapefile_zone) data_dis = Gdf.from_file(shapefile_surroundings) data_dis = data_dis.loc[~data_dis["Name"].isin(data_zone["Name"])] data = data_dis.append(data_zone, ignore_index = True, sort=True) data = data.to_crs(get_geographic_coordinate_system()) result = data.total_bounds # in float return result def geometry_extractor_osm(locator, config): """this is where the action happens if it is more than a few lines in ``main``. NOTE: ADD YOUR SCRIPT'S DOCUMENATION HERE (how) NOTE: RENAME THIS FUNCTION (SHOULD PROBABLY BE THE SAME NAME AS THE MODULE) """ # local variables: list_of_bounding_box = config.streets_helper.bbox type_of_streets = config.streets_helper.streets shapefile_out_path = locator.get_street_network() extra_border = 0.0010 # adding extra 150m (in degrees equivalent) to avoid errors of no data #get the bounding box coordinates if list_of_bounding_box == []: # the list is empty, we then revert to get the bounding box for the district assert os.path.exists( locator.get_surroundings_geometry()), 'Get surroundings geometry file first or the coordinates of the area where to extract the streets from in the next format: lon_min, lat_min, lon_max, lat_max: %s' print("generating streets from Surroundings Geometry") bounding_box_surroundings_file = calc_bounding_box(locator.get_surroundings_geometry(), locator.get_zone_geometry()) lon_min = bounding_box_surroundings_file[0]-extra_border lat_min = bounding_box_surroundings_file[1]-extra_border lon_max = bounding_box_surroundings_file[2]+extra_border lat_max = bounding_box_surroundings_file[3]+extra_border elif len(list_of_bounding_box) == 4: print("generating streets from your bounding box") # the list is not empty, the user has indicated a specific set of coordinates lon_min = list_of_bounding_box[0]-extra_border lat_min = list_of_bounding_box[1]-extra_border lon_max = list_of_bounding_box[2]+extra_border lat_max = list_of_bounding_box[3]+extra_border elif len(list_of_bounding_box) != 4: raise ValueError( "Please indicate the coordinates of the area where to extract the streets from in the next format: lon_min, lat_min, lon_max, lat_max") #get and clean the streets G = ox.graph_from_bbox(north=lat_max, south=lat_min, east=lon_max, west=lon_min, network_type=type_of_streets) data = ox.save_load.graph_to_gdfs(G, nodes=False, edges=True, node_geometry=False, fill_edge_geometry=True) #project coordinate system data = data.to_crs(get_projected_coordinate_system(float(lat_min), float(lon_min))) #clean data and save to shapefile data.loc[:, "highway"] = [x[0] if type(x) == list else x for x in data["highway"].values] data.loc[:, "name"] = [x[0] if type(x) == list else x for x in data["name"].values] data.fillna(value="Unknown", inplace=True) data[['geometry', "name", "highway"]].to_file(shapefile_out_path) def main(config): """ This is the main entry point to your script. Any parameters used by your script must be present in the ``config`` parameter. The CLI will call this ``main`` function passing in a ``config`` object after adjusting the configuration to reflect parameters passed on the command line - this is how the ArcGIS interface interacts with the scripts BTW. :param config: :type config: cea.config.Configuration :return: """ assert os.path.exists(config.scenario), 'Scenario not found: %s' % config.scenario locator = cea.inputlocator.InputLocator(config.scenario) geometry_extractor_osm(locator, config) if __name__ == '__main__': main(cea.config.Configuration())
Python
0.000003
@@ -3902,365 +3902,35 @@ -This is the main entry point to your script. Any parameters used by your script must be present in the %60%60config%60%60%0A parameter. The CLI will call this %60%60main%60%60 function passing in a %60%60config%60%60 object after adjusting the configuration%0A to reflect parameters passed on the command line - this is how the ArcGIS interface interacts with the scripts%0A BTW +Create the streets.shp file .%0A%0A
2930d355421ed3804d5c675fad20c82f27066d7e
Support numpy 1.9
chainer/functions/array/broadcast.py
chainer/functions/array/broadcast.py
import six from chainer import cuda from chainer import function from chainer.utils import type_check def _backward_one(x, g): if g is None: xp = cuda.get_array_module(x) return xp.zeros_like(x) if g.ndim != x.ndim: g = g.sum(axis=tuple(range(g.ndim - x.ndim))) # An input variable is always an array, not a scalar. # We need to convert a scalar value to a zero-dim array. xp = cuda.get_array_module(x) if xp.isscalar(g): g = xp.array(g) axis = tuple(i for i, sx in enumerate(x.shape) if sx == 1) if len(axis) > 0: return g.sum(keepdims=True, axis=axis) else: return g class Broadcast(function.Function): """Function that broadcasts given arrays.""" def check_type_forward(self, in_types): type_check.expect(in_types.size() > 0) shapes = [t.eval().shape for t in in_types] r_shapes = [s[::-1] for s in shapes] r_filled = six.moves.zip_longest(*r_shapes, fillvalue=1) for ss in r_filled: d = max(ss) if not all(s == d or s == 1 for s in ss): expect = 'each dimension has the same size or is 1' actual = 'shapes: ' + ', '.join(map(str, shapes)) raise type_check.InvalidType(expect, actual) def forward(self, xs): xp = cuda.get_array_module(*xs) return tuple(xp.broadcast_arrays(*xs)) def backward(self, xs, grads): return tuple(_backward_one(x, g) for x, g in six.moves.zip(xs, grads)) def broadcast(*args): """Broadcast given variables. Args: args (Variables): Variables to be broadcasted. Returns: ``tuple``: Tuple of :class:`~chainer.Variable` objects which are broadcasted from given arguments. """ return Broadcast()(*args) class BroadcastTo(function.Function): """Function that broadcasts an array to a new shape.""" def __init__(self, shape): shape = tuple(shape) self._shape = shape def check_type_forward(self, in_types): type_check.expect(in_types.size() == 1) ndim = type_check.Variable(len(self._shape), 'len(shape)') type_check.expect(in_types[0].ndim <= ndim) shape = in_types[0].shape.eval() for i in range(len(shape)): j = -i - 1 if shape[j] == self._shape[j] or shape[j] == 1: continue expect = 'in_type[0].shape[%d] == %d' % (j, self._shape[j]) if self._shape[j] != 1: expect += ' or in_type[0].shape[%d] == 1' % j actual = 'in_type[0].shape: %s' % str(shape) raise type_check.InvalidType(expect, actual) def forward(self, xs): xp = cuda.get_array_module(*xs) x = xs[0] return xp.broadcast_to(x, self._shape), def backward(self, xs, grads): return tuple(_backward_one(x, g) for x, g in six.moves.zip(xs, grads)) def broadcast_to(x, shape): return BroadcastTo(shape)(x)
Python
0.00004
@@ -2805,46 +2805,279 @@ -return xp.broadcast_to(x, self._shape) +if hasattr(xp, 'broadcast_to'):%0A return xp.broadcast_to(x, self._shape),%0A else:%0A # numpy 1.9 doesn't support broadcast_to method%0A dummy = xp.empty(self._shape)%0A bx, _ = xp.broadcast_arrays(x, dummy)%0A return bx ,%0A%0A
65202bc31623d4bf16bb60a5d6084c8215f01c7d
fix bug in layor
script/suntomorrow/train_predictor.py
script/suntomorrow/train_predictor.py
#!/usr/bin/env python """Chainer example: autoencoder of a solar image. """ # c.f. # http://nonbiri-tereka.hatenablog.com/entry/2015/06/21/220506 # http://qiita.com/kenmatsu4/items/99d4a54d5a57405ecaf8 import argparse import numpy as np import operator import re import six import subprocess import random import chainer from chainer import computational_graph as c from chainer import cuda, Variable, FunctionSet, optimizers import chainer.functions as F from chainer import optimizers parser = argparse.ArgumentParser(description='Chainer example: MNIST') parser.add_argument('--gpu', '-g', default=-1, type=int, help='GPU ID (negative value indicates CPU)') args = parser.parse_args() logfn = 'log-training.txt' subprocess.call('rm '+ logfn,shell=True) def zoom_x2(batch): shape = batch.data.shape channel_shape = shape[0:-2] height, width = shape[-2:] volume = reduce(operator.mul,shape,1) b1 = F.reshape(batch,(volume,1)) b2 = F.concat([b1,b1],1) b3 = F.reshape(b2,(volume/width,2*width)) b4 = F.concat([b3,b3],1) return F.reshape(b4, channel_shape + (2*height ,) + (2*width ,)) gpu_flag=(args.gpu >= 0) # load the numpy 2D arrays located under the folder. p=subprocess.Popen('find scaled-1024/',shell=True, stdout=subprocess.PIPE) stdout, _ = p.communicate() sun_data = [] for fn in stdout.split('\n'): if not re.search('\.npy$',fn) : continue sun_data.append(np.load(fn)) if len(sun_data)==0: # where no data is available, add a dummy data for debugging for i in range(10): x=32*[0.333*i*i] xy=32*[x] sun_data.append(xy) model=chainer.FunctionSet( convA1 = F.Convolution2D( 4, 8,3,stride=1,pad=1), convA2 = F.Convolution2D( 8,16,3,stride=1,pad=1), convA3 = F.Convolution2D(16,32,3,stride=1,pad=1), convV3 = F.Convolution2D(32,16,3,stride=1,pad=1), convV2 = F.Convolution2D(16, 8,3,stride=1,pad=1), convV1 = F.Convolution2D( 8, 4,3,stride=1,pad=1), convY = F.Convolution2D( 4, 1,3,stride=1,pad=1), ) if gpu_flag: cuda.init(0) model.to_gpu() def forward(x_data,y_data,train=True): deploy = False x = Variable(x_data, volatile = not train) y = Variable(y_data, volatile = not train) hc1 = F.dropout(F.leaky_relu(model.convA1(x)), train=train and deploy) hm1 = F.max_pooling_2d(hc1,2) hc2 = F.dropout(F.leaky_relu(model.convA2(hm1)), train=train and deploy) hm2 = F.max_pooling_2d(hc2,2) hc3 = F.dropout(F.leaky_relu(model.convA2(hm2)), train=train and deploy) hm3 = F.max_pooling_2d(hc3,2) hv4 = hm3 hz3 = zoom_x2(hv4) hv3 = F.dropout(F.leaky_relu(model.convV2(hz3)), train=train and deploy) hz2 = zoom_x2(hv3) hv2 = F.dropout(F.leaky_relu(model.convV2(hz2)), train=train and deploy) hz1 = zoom_x2(hv2) hv1 = F.dropout(F.leaky_relu(model.convV1(hz1)), train=train and deploy) y_pred = model.convY(hv1) return F.mean_squared_error(y,y_pred) optimizer = optimizers.Adam() optimizer.setup(model.collect_parameters()) epoch=0 while True: epoch+=1 batch_input = []; batch_output = [] for i in range(1): n = 4 start = random.randrange(len(sun_data)-n-1) batch_input.append(sun_data[start:start+n]) batch_output.append(sun_data[start+n]) batch_input=np.array(batch_input) batch_output=np.array(batch_output) if gpu_flag : batch_input = cuda.to_gpu(batch_input) batch_output = cuda.to_gpu(batch_output) optimizer.zero_grads() loss = forward(batch_input, batch_output, train=True) loss.backward() optimizer.update() print epoch,loss.data with(open(logfn,'a')) as fp: fp.write('{} {}\n'.format(epoch,loss.data))
Python
0
@@ -2520,17 +2520,17 @@ el.convA -2 +3 (hm2)), @@ -2668,17 +2668,17 @@ el.convV -2 +3 (hz3)),
460aabe9184f220f9444599f6352c0fd12db26cb
convert expiration to string
batch.py
batch.py
from datetime import datetime, timedelta import json import celery from emails import send_email from pytz import timezone import requests import stripe from helpers import amount_to_charge from salesforce import SalesforceConnection from config import STRIPE_KEYS from config import ACCOUNTING_MAIL_RECIPIENT from config import TIMEZONE zone = timezone(TIMEZONE) stripe.api_key = STRIPE_KEYS['secret_key'] class Log(object): """ This encapulates sending to the console/stdout and email all in one. """ def __init__(self): self.log = list() def it(self, string): """ Add something to the log. """ print(string) self.log.append(string) def send(self): """ Send the assembled log out as an email. """ body = '\n'.join(self.log) recipient = ACCOUNTING_MAIL_RECIPIENT subject = 'Batch run' send_email(body=body, recipient=recipient, subject=subject) def process_charges(query, log): print(query) sf = SalesforceConnection() response = sf.query(query) # TODO: check response code log.it('Found {} opportunities available to process.'.format( len(response))) for item in response: # print (item) amount = amount_to_charge(item) try: log.it("---- Charging ${} to {} ({})".format(amount / 100, item['Stripe_Customer_ID__c'], item['Name'])) if item['Shipping_address_name__c'] != '': shipping_address = {'line1' : item['Shipping_address_street__c'], 'city' : item['Shipping_address_city__c'], 'state' : item['Shipping_address_state__c'], 'postal_code' : item['Shipping_address_ZIP__c'], 'country' : item['Shipping_address_country__c']} shipping_details = {'name' : item['Shipping_address_name__c'], 'address' : shipping_address} else: shipping_details = NULL charge = stripe.Charge.create( customer=item['Stripe_Customer_ID__c'], amount=amount, currency='usd', description=item['Description'], metadata={'source': item['Referring_page__c']}, shipping=shipping_details ) except stripe.error.CardError as e: # look for decline code: print('Unable to extract decline code') return jsonify(e) except stripe.error.InvalidRequestError as e: log.it("Problem: {}".format(e)) continue # print ('Charge: {}'.format(charge)) # TODO: check for success # TODO: catch other errors # print ("Charge id: {}".format(charge.id)) update = { 'Stripe_Transaction_Id__c': charge.id, 'Stripe_Card__c': charge.source.id, 'Card_type__c': charge.source.brand, 'Card_expiration_date__c': charge.source.exp_month + ' / ' + charge.source.exp_year, 'Card_acct_last_4__c': charge.source.last4, 'StageName': 'Closed Won', } path = item['attributes']['url'] url = '{}{}'.format(sf.instance_url, path) # print (url) resp = requests.patch(url, headers=sf.headers, data=json.dumps(update)) # TODO: check 'errors' and 'success' too # print (resp) if resp.status_code == 204: log.it("ok") else: log.it("problem") raise Exception('problem') @celery.task() def charge_cards(): log = Log() log.it('---Starting batch job...') three_days_ago = (datetime.now(tz=zone) - timedelta( days=3)).strftime('%Y-%m-%d') today = datetime.now(tz=zone).strftime('%Y-%m-%d') # regular (non Circle) pledges: log.it('---Processing regular charges...') query = """ SELECT Amount, Name, Stripe_Customer_Id__c, Description, Stripe_Agreed_to_pay_fees__c, Referring_page__c, Shipping_address_name__c, Shipping_address_street__c, Shipping_address_city__c, Shipping_address_state__c, Shipping_address_ZIP__c, Shipping_address_country__c FROM Opportunity WHERE CloseDate <= {} AND CloseDate >= {} AND StageName = 'Pledged' AND Stripe_Customer_Id__c != '' """.format(today, three_days_ago) process_charges(query, log) # # Circle transactions are different from the others. The Close Dates for a # given Circle donation are all identical. That's so that the gift can be # recognized all at once on the donor wall. So we use another field to # determine when the card is actually charged: # Giving_Circle_Expected_Giving_Date__c. So we process charges separately # for Circles. # # log.it('---Processing Circle charges...') # query = """ # SELECT Amount, Name, Stripe_Customer_Id__c, Description, # Stripe_Agreed_to_pay_fees__c # FROM Opportunity # WHERE Giving_Circle_Expected_Giving_Date__c <= {} # AND Giving_Circle_Expected_Giving_Date__c >= {} # AND StageName = 'Pledged' # AND Stripe_Customer_Id__c != '' # AND Type = 'Giving Circle' # """.format(today, three_days_ago) # process_charges(query, log) # log.send() if __name__ == '__main__': charge_cards()
Python
0.999999
@@ -2994,24 +2994,28 @@ n_date__c': +str( charge.sourc @@ -3025,16 +3025,17 @@ xp_month +) + ' / ' @@ -3037,16 +3037,20 @@ ' / ' + +str( charge.s @@ -3063,16 +3063,17 @@ exp_year +) ,%0A
dc50a4ec058f9893e87a069bc64e4715ecfa0bea
Add initial status code assertion
haas_rest_test/plugins/assertions.py
haas_rest_test/plugins/assertions.py
# -*- coding: utf-8 -*- # Copyright (c) 2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals class StatusCodeAssertion(object): _schema = { } def __init__(self, valid_codes): super(StatusCodeAssertion, self).__init__() self.valid_codes = valid_codes @classmethod def from_dict(cls, data): # FIXME: Validate input with jsonschema return cls(valid_codes=data['expected'])
Python
0.000004
@@ -271,60 +271,510 @@ ls%0A%0A -%0Aclass StatusCodeAssertion(object):%0A%0A _schema = %7B +from jsonschema.exceptions import ValidationError%0Aimport jsonschema%0A%0Afrom ..exceptions import YamlParseError%0A%0A%0Aclass StatusCodeAssertion(object):%0A%0A _schema = %7B%0A '$schema': 'http://json-schema.org/draft-04/schema#',%0A 'title': 'Assertion on status code ',%0A 'description': 'Test case markup for Haas Rest Test',%0A 'type': 'object',%0A 'properties': %7B%0A 'expected': %7B%0A 'type': 'integer',%0A %7D,%0A %7D,%0A 'required': %5B'expected'%5D %0A @@ -800,26 +800,30 @@ _(self, -valid_code +expected_statu s):%0A @@ -887,32 +887,40 @@ elf. -valid_codes = valid_code +expected_status = expected_statu s%0A%0A @@ -977,47 +977,141 @@ -# FIXME: Validate input with jsonschema +try:%0A jsonschema.validate(data, cls._schema)%0A except ValidationError as e:%0A raise YamlParseError(str(e)) %0A @@ -1130,18 +1130,22 @@ cls( -valid_code +expected_statu s=da @@ -1160,8 +1160,64 @@ cted'%5D)%0A +%0A def run(self, case, response):%0A case.fail()%0A
b9ea36d80ec256988a772e621eb91481cff5e464
Bump version to 0.3
cicoclient/shell.py
cicoclient/shell.py
# Copyright Red Hat, Inc. 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 sys import os from cliff.app import App from cliff.commandmanager import CommandManager class CicoCli(App): """ CLI interface boilerplate with cliff """ def __init__(self): super(CicoCli, self).__init__( description='CLI interface to admin.ci.centos.org', version='0.2', command_manager=CommandManager('cico.cli'), deferred_help=True, ) def build_option_parser(self, description, version): parser = super(CicoCli, self).build_option_parser(description, version) # Global arguments parser.add_argument( '--endpoint', metavar='<endpoint>', help='Endpoint to the admin.ci.centos.org service.\n' ' Defaults to: http://admin.ci.centos.org:8080/', default='http://admin.ci.centos.org:8080/' ) parser.add_argument( '--api-key', metavar='<api-key>', help='API key to admin.ci.centos.org service. Defaults to' ' environment variable for CICO_API_KEY.', default=os.getenv('CICO_API_KEY', None) ) return parser def initialize_app(self, argv): self.LOG.debug('initialize_app') def prepare_to_run_command(self, cmd): self.LOG.debug('prepare_to_run_command %s', cmd.__class__.__name__) def clean_up(self, cmd, result, err): self.LOG.debug('clean_up %s', cmd.__class__.__name__) if err: self.LOG.debug('got an error: %s', err) def main(argv=sys.argv[1:]): cicocli = CicoCli() return cicocli.run(argv) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
Python
0
@@ -934,17 +934,17 @@ sion='0. -2 +3 ',%0A
79323b06acebed5243b7d40364497c72751441e3
Add example of creating a ioctl read helper function.
ioctl/__init__.py
ioctl/__init__.py
import ctypes import ctypes.util import fcntl import os import sys # In Python 2, the bytearray()-type does not support the buffer interface, # and can therefore not be used in ioctl(). # This creates a couple of helper functions for converting to and from if sys.version_info < (3, 0): import array def _to_bytearray(value): return array.array('B', value) def _from_bytearray(value): return value.tostring() else: def _to_bytearray(value): return bytearray(value) def _from_bytearray(value): return bytes(value) try: libc_name = ctypes.util.find_library('c') if not libc_name: raise Exception('Unable to find c library') libc = ctypes.CDLL(libc_name, use_errno=True) ioctl_fn = libc.ioctl except Exception as e: ioctl_fn = None ioctl_err = e def ioctl(fd, request, *args): """ Call the C library ioctl()-function directly. This function invokes ioctl() through ctypes. This gives greater control over the parameters passed to ioctl(). :param fd: File descriptor to operate on. :param request: The ioctl request to call. :param args: parameter to pass to ioctl. :return: The return value of the ioctl-call. """ if not isinstance(fd, int): raise TypeError('fd must be an integer, but was {}'.format(fd.__class__.__name__)) if fd < 0: raise ValueError('fd cannot be negative') if not isinstance(request, int) and not isinstance(request, long): raise TypeError('request must be an integer, but was {}'.format(request.__class__.__name__)) if not ioctl_fn: raise NotImplementedError('Unable to get ioctl()-function from C library: {err}'.format(err=str(ioctl_err))) ioctl_args = [ ctypes.c_int(fd), ctypes.c_ulong(request)] + list(args) res = ioctl_fn(*ioctl_args) if res < 0: err = ctypes.get_errno() raise OSError(err, os.strerror(err)) return res def ioctl_fn_ptr_r(request, datatype, return_python=None): """ Create a helper function for invoking a ioctl() read call. This function creates a helper function for creating a ioctl() read function. It will call the ioctl() function with a pointer to data, and return the contents of the data after the call. If the datatype is a integer type (int, long, etc), it will be returned as a python int or long. :param request: The ioctl request to call. :param datatype: The data type of the data returned by the ioctl() call. :param return_python: Whether we should attempt to convert the return data to a Python value. Defaults to True for fundamental ctypes data types. :return: A function for invoking the specified ioctl(). """ if not isinstance(request, int) and not isinstance(request, long): raise TypeError('request must be an integer, but was {}'.format(request.__class__.__name__)) if request < 0: raise ValueError('request cannot be negative') valid_datatypes = ( ctypes._SimpleCData, ctypes.Union, ctypes.BigEndianStructure, ctypes.LittleEndianStructure, ctypes.Structure, ) if not any([ issubclass(datatype, cls) for cls in valid_datatypes ]): raise TypeError('datatype must be a ctypes data type, but was {}'.format(datatype.__name__)) if return_python is not None and not isinstance(return_python, bool): raise TypeError('return_python must be None or a boolean, but was {}'.format(return_python.__class__.__name__)) if return_python is None: return_python = issubclass(datatype, ctypes._SimpleCData) def fn(fd): if not isinstance(fd, int): raise TypeError('fd must be an integer, but was {}'.format(fd.__class__.__name__)) if fd < 0: raise ValueError('fd cannot be negative') value = datatype() ioctl(fd, request, ctypes.byref(value)) if return_python: return value.value else: return value return fn def ioctl_ptr_int(fd, request, value=0): """Call ioctl() with an ``int *`` argument. :param fd: File descriptor to operate on. :param request: The ioctl request to call. :param value: Optional value to pass to the ioctl() operation. Defaults to 0. :return: Tuple of ``(ioctl_return, updated_value)``. ``ioctl_return`` is the return value of the ioctl()-call, while ``updated_value`` is the value of the integer argument after the ioctl()-call. """ res = ctypes.c_int(value) ioctl_return = fcntl.ioctl(fd, request, res) return (ioctl_return, res.value) def ioctl_ptr_size_t(fd, request, value=0): """Call ioctl() with a ``size_t *`` argument. :param fd: File descriptor to operate on. :param request: ioctl request to call. :param value: Optional value to pass to the ioctl() operation. Defaults to 0. :return: Tuple of ``(ioctl_return, updated_value)``. ``ioctl_return`` is the return value of the ioctl()-call, while ``updated_value`` is the value of the size_t argument after the ioctl()-call. """ res = ctypes.c_size_t(value) ioctl_return = fcntl.ioctl(fd, request, res) return (ioctl_return, res.value) def ioctl_ptr_buffer(fd, request, value=None, length=None): """Call ioctl() with a ``void *`` argument. You must specify either the ``value`` parameter or the ``length`` parameter. If the ``length`` parameter is specified, this function will allocate a byte buffer of the specified length to pass to ioctl(). :param fd: File descriptor to operate on. :param request: ioctl request to call. :param value: Optional contents of the byte buffer at the start of the call. :param length: Optional length of the byte buffer. :return: Tuple of ``(ioctl_return, updated_value)``. ``ioctl_return`` is the return value of the ioctl()-call, while ``updated_value`` is the contents of the buffer after the ioctl()-call. """ request = int(request) if value is None and length is None: raise ValueError('Must specify either `value` or `length`') if value is not None and length is not None: raise ValueError('Cannot specify both `value` and `length`') if value is None: value = [0] * length data = _to_bytearray(value) ioctl_return = fcntl.ioctl(fd, request, data) data = _from_bytearray(data) return (ioctl_return, data)
Python
0
@@ -2705,16 +2705,347 @@ ioctl(). +%0A%0A :Example:%0A ::%0A%0A import os%0A import ioctl%0A import ioctl.linux%0A RNDGETENTCNT = ioctl.linux.IOR('R', 0x00, ctypes.c_int)%0A rndgetentcnt = ioctl.ioctl_fn_ptr_r(RNDGETENTCNT, ctypes.c_int)%0A fd = os.open('/dev/random', os.O_RDONLY)%0A entropy_avail = rndgetentcnt(fd) %0A %22%22%22
6d41c4f58c94367f922117b52fcd15a131e96344
implement Patent.classes
lib/new_xml_parsing/xml_driver.py
lib/new_xml_parsing/xml_driver.py
#!/usr/bin/env python from itertools import chain from collections import deque from xml.sax import make_parser, handler class ChainList(list): """ This is the base structure that handles the tree created by XMLElement and XMLHandler. Overriding __getattr__ allows us to chain queries on a list in order to traverse the tree. """ def contents_of(self, tag): res = [] for item in self: res.extend( item.contents_of(tag) ) return ChainList(res) def __getattr__(self, key): res = [] scope = deque(self) while scope: current = scope.popleft() if current._name == key: res.append(current) else: scope.extend(current.children) return ChainList(res) class XMLElement(object): """ Represents XML elements from a document. These will assist us in representing an XML document as a Python object. Heavily inspired from: https://github.com/stchris/untangle/blob/master/untangle.py """ def __init__(self, name, attributes): self._name = name self._attributes = attributes self.content = '' self.children = ChainList() self.is_root = False def __iter__(self): yield self def __nonzero__(self): return self.is_root or self._name is not None def __getitem__(self, key): return self.get_attribute(key) def __getattr__(self, key): res = [] scope = deque(self.children) while scope: current = scope.popleft() if current._name == key: res.append(current) else: scope.extend(current.children) if res: self.__dict__[key] = ChainList(res) return ChainList(res) else: return ChainList('') def contents_of(self, key): candidates = self.__getattr__(key) if candidates: return [x.content for x in candidates] else: return ChainList('') def add_child(self, child): self.children.append(child) def get_attribute(self, key): return self._attributes.get(key, None) def get_xmlelements(self, name): return filter(lambda x: x._name == name, self.children) \ if name else \ self.children class XMLHandler(handler.ContentHandler): """ SAX Handler to create the Python object while parsing """ def __init__(self): self.root = XMLElement(None, None) self.root.is_root = True self.elements = ChainList() def startElement(self, name, attributes): name = name.replace('-','_').replace('.','_').replace(':','_') xmlelem = XMLElement(name, dict(attributes.items())) if self.elements: self.elements[-1].add_child(xmlelem) else: self.root.add_child(xmlelem) self.elements.append(xmlelem) def endElement(self, name): if self.elements: self.elements.pop() def characters(self, content): if content.strip(): self.elements[-1].content = content class Patent(object): def __init__(self, filename): xh = XMLHandler() parser = make_parser() parser.setContentHandler(xh) parser.setFeature(handler.feature_external_ges, False) parser.parse(filename) self.xml = xh.root.us_patent_grant.us_bibliographic_data_grant self.country = self.xml.publication_reference.contents_of('country')[0] self.patent = self.xml.publication_reference.contents_of('doc_number')[0] self.kind = self.xml.publication_reference.contents_of('kind')[0] self.date_grant = self.xml.publication_reference.contents_of('date')[0] #TODO: better handling of attributes self.pat_type = 'not implemented' self.date_app = self.xml.application_reference.contents_of('date')[0] self.country_app = self.xml.application_reference.contents_of('country')[0] self.patent_app = self.xml.application_reference.contents_of('doc_number')[0] self.code_app = self.xml.contents_of('us_application_series_code')[0] self.clm_num = self.xml.contents_of('number_of_claims')[0]
Python
0.000017
@@ -4223,15 +4223,360 @@ ms')%5B0%5D%0A -%0A + self.classes = self._classes()%0A%0A def _classes(self):%0A main = self.xml.classification_national.contents_of('main_classification')%0A further = self.xml.classification_national.contents_of('further_classification')%0A it = %5Bx%5B0%5D for x in (main,further) if x%5D%0A return %5B %5Bx%5B:3%5D.replace(' ',''), x%5B3:%5D.replace(' ','')%5D for x in it%5D%0A %0A%0A
591b974d0630ff26c82ede7652fc667dbf3fef2e
Remove unused import
test/test_gatherbot.py
test/test_gatherbot.py
import re import unittest from unittest import mock import discord from .helper import async_test, get_mock_coro from gather.gatherbot import GatherBot class TestGatherBotCommands(unittest.TestCase): def test_register(self): bot = GatherBot() self.assertEqual({}, bot.actions) regex = r'^test' action = mock.Mock() bot.register_action(regex, action) self.assertEqual( {regex: (re.compile(regex, re.IGNORECASE), action)}, bot.actions ) def test_overwrite(self): bot = GatherBot() self.assertEqual({}, bot.actions) regex = r'^test' action = mock.Mock() bot.register_action(regex, action) new_action = mock.Mock() bot.register_action(regex, new_action) self.assertEqual( {regex: (re.compile(regex, re.IGNORECASE), new_action)}, bot.actions ) @async_test async def test_on_message_from_bot(self): bot = GatherBot() bot.username = 'testuser' regex = r'^test' action = get_mock_coro(True) bot.actions = {regex: (re.compile(regex, re.IGNORECASE), action)} mock_message = mock.Mock() mock_message.author = 'testuser' mock_message.content = 'test' await bot.on_message(mock_message) action.assert_not_called() @async_test async def test_on_message_from_other(self): bot = GatherBot() bot.username = 'testuser' regex = r'^test' action = get_mock_coro(True) bot.actions = {regex: (re.compile(regex, re.IGNORECASE), action)} mock_message = mock.Mock() mock_message.author = 'anotheruser' mock_message.content = 'test' await bot.on_message(mock_message) self.assertTrue(action.called) class TestGatherBot(unittest.TestCase): def test_player_count_display_with_zero(self): bot = GatherBot() bot.organiser.queues['testchannel'] = set() self.assertEqual( '(0/10)', bot.player_count_display('testchannel') ) def test_player_count_display_with_players(self): bot = GatherBot() bot.organiser.queues['testchannel'] = set(['player1', 'player2']) self.assertEqual( '(2/10)', bot.player_count_display('testchannel') ) @unittest.mock.patch('discord.Client') @unittest.mock.patch('gather.organiser.Organiser') def test_init(self, mock_organiser, mock_client): bot = GatherBot() bot.run('testtoken') self.assertIsNotNone(bot.organiser) self.assertIsNotNone(bot.client) @unittest.mock.patch('discord.Client') @unittest.mock.patch('gather.organiser.Organiser') @async_test async def test_say(self, mock_organiser, mock_client): bot = GatherBot() bot.run('testtoken') bot.client.send_message = get_mock_coro(True) await bot.say('test channel', 'test message') bot.client.send_message.assert_called_with( 'test channel', 'test message' ) @unittest.mock.patch('discord.Client') @unittest.mock.patch('gather.organiser.Organiser') @async_test async def test_say_lines(self, mock_organiser, mock_client): bot = GatherBot() bot.run('testtoken') bot.client.send_message = get_mock_coro(True) await bot.say_lines( 'test channel', [ 'test message 1', 'test message 2', ] ) bot.client.send_message.assert_has_calls([ unittest.mock.call('test channel', 'test message 1'), unittest.mock.call('test channel', 'test message 2'), ]) @unittest.mock.patch('discord.Client') @unittest.mock.patch('gather.organiser.Organiser') @async_test async def test_announce_players(self, mock_organiser, mock_client): bot = GatherBot() bot.run('testtoken') bot.client.send_message = get_mock_coro(True) bot.player_count_display = unittest.mock.Mock(return_value='(1/10)') bot.organiser.queues['test channel'] = set(['mac']) await bot.announce_players('test channel') bot.client.send_message.assert_called_with( 'test channel', 'Currently signed in players (1/10): mac' )
Python
0.000001
@@ -49,23 +49,8 @@ ock%0A -import discord%0A from
561de1d124289058eafde34547e8fc773c3e9793
Rename strips to d_strips
board.py
board.py
import direction_strips as ds_m from pente_exceptions import * from defines import * class Board(): def __init__(self, size, clone_it=False): self.size = size if not clone_it: self.set_to_empty() def set_to_empty(self): self.strips = [] # TODO Rename to d_strips self.strips.append(ds_m.EDirectionStrips(self.size)) self.strips.append(ds_m.SEDirectionStrips(self.size)) self.strips.append(ds_m.SDirectionStrips(self.size)) self.strips.append(ds_m.SWDirectionStrips(self.size)) def key(self): return tuple(self.strips[0].strips) def get_direction_strips(self): return self.strips def clone(self): new_board = Board(self.size, clone_it=True) new_board.strips = [s.clone() for s in self.strips] return new_board def __repr__(self): size = self.size rep = '\n' for j in range(size-1,-1,-1): line = [ ['.','B','W'][self.strips[0].get_occ((i,j))] for i in range(size) ] rep = rep + ' '.join(line) + '\n' return rep def get_size(self): return self.size def off_board(self, pos): x,y = pos size = self.size return x < 0 or \ x >= size or \ y < 0 or \ y >= size def get_occ(self, pos): if self.off_board(pos): raise OffBoardException colour_new = self.strips[0].get_occ(pos) return colour_new def set_occ(self, pos, colour): if self.off_board(pos): raise OffBoardException for s in self.strips: # We maintain the board position in four ways, update them all s.set_occ(pos, colour)
Python
0.999681
@@ -261,24 +261,26 @@ self. +d_ strips = %5B%5D @@ -282,34 +282,8 @@ = %5B%5D - # TODO Rename to d_strips %0A @@ -284,32 +284,34 @@ %5B%5D%0A self. +d_ strips.append(ds @@ -347,32 +347,34 @@ ))%0A self. +d_ strips.append(ds @@ -411,32 +411,34 @@ ))%0A self. +d_ strips.append(ds @@ -478,24 +478,26 @@ self. +d_ strips.appen @@ -565,26 +565,39 @@ -return tuple( +k = 0%0A estrips = self. +d_ stri @@ -605,16 +605,109 @@ s%5B0%5D -.strips) +%0A for s in estrips.strips:%0A k += s%0A k *= 4 ** self.size%0A return k %0A%0A @@ -756,24 +756,26 @@ return self. +d_ strips%0A %0A @@ -865,16 +865,18 @@ w_board. +d_ strips = @@ -897,24 +897,26 @@ r s in self. +d_ strips%5D%0A @@ -1079,24 +1079,26 @@ ','W'%5D%5Bself. +d_ strips%5B0%5D.ge @@ -1546,20 +1546,16 @@ lour -_new = self. stri @@ -1546,24 +1546,26 @@ lour = self. +d_ strips%5B0%5D.ge @@ -1600,12 +1600,8 @@ lour -_new %0A%0A @@ -1725,16 +1725,18 @@ in self. +d_ strips:%0A
62e9510fe2fbe3186c7c817a5c287322a65b1dc9
Fix linearPotential import to new package structure
galpy/potential/IsothermalDiskPotential.py
galpy/potential/IsothermalDiskPotential.py
############################################################################### # IsothermalDiskPotential.py: class that implements the one-dimensional # self-gravitating isothermal disk ############################################################################### import numpy from galpy.util import bovy_conversion from galpy.potential_src.linearPotential import linearPotential, _APY_LOADED if _APY_LOADED: from astropy import units class IsothermalDiskPotential(linearPotential): """Class representing the one-dimensional self-gravitating isothermal disk .. math:: \\rho(x) = \\mathrm{amp}\\,\\mathrm{sech}^2\\left(\\frac{x}{2H}\\right) where the scale height :math:`H^2 = \\sigma^2/[8\\pi G \\,\\mathrm{amp}]`. The parameter to setup the disk is the velocity dispersion :math:`\\sigma`. """ def __init__(self,amp=1.,sigma=0.1,ro=None,vo=None): """ NAME: __init__ PURPOSE: Initialize an IsothermalDiskPotential INPUT: amp - an overall amplitude sigma - velocity dispersion (can be a Quantity) OUTPUT: instance HISTORY: 2018-04-11 - Written - Bovy (UofT) """ linearPotential.__init__(self,amp=amp,ro=ro,vo=vo) if _APY_LOADED and isinstance(sigma,units.Quantity): sigma= sigma.to(units.km/units.s).value/self._vo self._sigma2= sigma**2. self._H= sigma/numpy.sqrt(8.*numpy.pi*self._amp) def _evaluate(self,x,t=0.): return 2.*self._sigma2*numpy.log(numpy.cosh(0.5*x/self._H)) def _force(self,x,t=0.): return -self._sigma2*numpy.tanh(0.5*x/self._H)/self._H
Python
0.000022
@@ -314,66 +314,8 @@ rom -galpy.util import bovy_conversion%0Afrom galpy.potential_src .lin
1e012f6fc25e2be5bc55b7cae9f04a3a33ac86e5
use static url for ckeditor media serving
ckeditor/widgets.py
ckeditor/widgets.py
from django import forms from django.conf import settings from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.html import conditional_escape from django.utils.encoding import force_unicode from django.utils import simplejson from django.core.exceptions import ImproperlyConfigured from django.forms.util import flatatt json_encode = simplejson.JSONEncoder().encode DEFAULT_CONFIG = { 'skin': 'django', 'toolbar': 'Full', 'height': 291, 'width': 835, 'filebrowserWindowWidth': 940, 'filebrowserWindowHeight': 725, } class CKEditorWidget(forms.Textarea): """ Widget providing CKEditor for Rich Text Editing. Supports direct image uploads and embed. """ class Media: try: js = ( settings.CKEDITOR_MEDIA_PREFIX + 'ckeditor/ckeditor.js', ) except AttributeError: raise ImproperlyConfigured("django-ckeditor requires \ CKEDITOR_MEDIA_PREFIX setting. This setting specifies a \ URL prefix to the ckeditor JS and CSS media (not \ uploaded media). Make sure to use a trailing slash: \ CKEDITOR_MEDIA_PREFIX = '/media/ckeditor/'") def __init__(self, config_name='default', *args, **kwargs): super(CKEditorWidget, self).__init__(*args, **kwargs) # Setup config from defaults. self.config = DEFAULT_CONFIG.copy() # Try to get valid config from settings. configs = getattr(settings, 'CKEDITOR_CONFIGS', None) if configs != None: if isinstance(configs, dict): # Make sure the config_name exists. if config_name in configs: config = configs[config_name] # Make sure the configuration is a dictionary. if not isinstance(config, dict): raise ImproperlyConfigured('CKEDITOR_CONFIGS["%s"] \ setting must be a dictionary type.' % \ config_name) # Override defaults with settings config. self.config.update(config) else: raise ImproperlyConfigured("No configuration named '%s' \ found in your CKEDITOR_CONFIGS setting." % \ config_name) else: raise ImproperlyConfigured('CKEDITOR_CONFIGS setting must be a\ dictionary type.') def render(self, name, value, attrs={}): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) self.config['filebrowserUploadUrl'] = reverse('ckeditor_upload') self.config['filebrowserBrowseUrl'] = reverse('ckeditor_browse') return mark_safe(render_to_string('ckeditor/widget.html', { 'final_attrs': flatatt(final_attrs), 'value': conditional_escape(force_unicode(value)), 'id': final_attrs['id'], 'config': json_encode(self.config) }) )
Python
0
@@ -876,33 +876,31 @@ ngs. -CKEDITOR_MEDIA_PREFIX + ' +STATIC_URL + 'ckeditor/ cked
b927fe276af848b6c9a4653e04421a739e63037c
remove unused import
test/test_graphprot.py
test/test_graphprot.py
from scripttest import TestFileEnvironment import re import os # from filecmp import cmp bindir = "graphprot/" script = "graphprot_seqmodel" # test file environment datadir = "test/" testdir = "test/testenv_graphprot_seqmodel/" # directories relative to test file environment bindir_rel = "../../" + bindir datadir_rel = "../../" + datadir env = TestFileEnvironment(testdir) def test_invocation_no_params(): "Call without parameters should return usage information." call = bindir_rel + script run = env.run( call, expect_error=True) assert run.returncode == 2 assert re.match("usage", run.stderr), "stderr should contain usage information: {}".format(run.stderr) def test_simple_fit(): "Train a model on 10 positive and 10 negative sequences using default paramters." outfile = "test_simple_fit.model" call = bindir_rel + script + " -vvv fit -p {} -n {} --output-dir ./ --model-file {} --n-iter 1".format( datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.positives.fa", datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.negatives.fa", outfile ) # ../../graphprot/graphprot_seqmodel -vvv fit -p ../../test/PARCLIP_MOV10_Sievers_100seqs.train.positives.fa -n ../../test/PARCLIP_MOV10_Sievers_100seqs.train.negatives.fa --output-dir ./ --model-file test_simple_fit.model --n-iter 1 env.run(call) call = bindir_rel + script + " -vvv estimate -p {} -n {} --output-dir ./ --model-file {} --cross-validation".format( datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.positives.fa", datadir_rel + "PARCLIP_MOV10_Sievers_10seqs.train.negatives.fa", outfile ) # ../../graphprot/graphprot_seqmodel -vvv estimate -p ../../test/PARCLIP_MOV10_Sievers_1kseqs.train.positives.fa -n ../../test/PARCLIP_MOV10_Sievers_1kseqs.train.negatives.fa --output-dir ./ --model-file test_simple_fit.model --cross-validation run = env.run( call, expect_stderr=True, ) stdout = open(testdir + "test_simple_fit_estimate.out", "w") stdout.write(run.stdout)
Python
0.000001
@@ -50,18 +50,8 @@ re%0A -import os%0A # fr
c04bd5e52b4a516e31f98231cc6ccb7853040d2b
fix bad middleware arg
corehq/middleware.py
corehq/middleware.py
import logging import os import datetime from django.conf import settings try: import psutil except ImportError: psutil = None # this isn't OR specific, but we like it to be included OPENROSA_ACCEPT_LANGUAGE = "HTTP_ACCEPT_LANGUAGE" OPENROSA_VERSION_HEADER = "HTTP_X_OPENROSA_VERSION" OPENROSA_DATE_HEADER = "HTTP_DATE" OPENROSA_HEADERS = [OPENROSA_VERSION_HEADER, OPENROSA_DATE_HEADER, OPENROSA_ACCEPT_LANGUAGE] class OpenRosaMiddleware(object): """ Middleware to support OpenRosa request/response standards compliance https://bitbucket.org/javarosa/javarosa/wiki/OpenRosaRequest """ def __init__(self): pass def process_request(self, request): # if there's a date header specified add that to the request # as a first class property or_headers = {} for header in OPENROSA_HEADERS: if header in request.META: or_headers[header] = request.META[header] request.openrosa_headers = or_headers def process_response(self, request, response): response[OPENROSA_VERSION_HEADER] = settings.OPENROSA_VERSION return response profile_logger = logging.getLogger('profile_middleware') class MemoryUsageMiddleware(object): """ Stolen and modified from http://stackoverflow.com/a/12254394/8207 This is a pretty poor, blunt tool and is not recommended to be treated as definitive truth. """ _psutil_installed = None def _check_psutil(self): if self._psutil_installed is None: if psutil is None: profile_logger.warning('Install dev-requirements (psutil) in order to use MemoryUsageMiddleware') self._psutil_installed = False else: self._psutil_installed = True return self._psutil_installed def process_request(self, request): if self._check_psutil(): request._profile_memory = psutil.Process(os.getpid()).get_memory_info() def process_response(self, request, response): if self._check_psutil() and hasattr(request, '_profile_memory'): mem = psutil.Process(os.getpid()).get_memory_info() diff = (mem.rss - request._profile_memory.rss) / 1024 profile_logger.info('{} memory usage {} KB'.format(request.path, diff)) return response class TimingMiddleware(object): def process_request(self, request): request._profile_starttime = datetime.datetime.utcnow() def process_response(self, request, response): if hasattr(request, '_profile_starttime'): duration = datetime.datetime.utcnow() - request._profile_starttime profile_logger.info('{} time {}'.format(request.path, duration), extras={'duration': duration}) return response
Python
0.000169
@@ -2759,17 +2759,16 @@ ), extra -s =%7B'durat
3eac07253f843384247b5dde6cd2a3ed2c362ffd
Add test case for static user sheet
tests/frontend/user/test_basic_actions.py
tests/frontend/user/test_basic_actions.py
from flask import url_for from pycroft import config from pycroft.model import session from pycroft.model.user import User from pycroft.model.facilities import Room from tests.fixtures import permissions from tests.fixtures.dummy import user as dummy_user_fixtures, facilities from . import UserFrontendTestBase, LegacyUserFrontendTestBase class UserViewingPagesTestCase(UserFrontendTestBase): def test_user_overview_access(self): self.assert200(self.client.get(url_for('user.overview'))) def test_user_viewing_himself(self): user_id = self.admin.id self.assert200(self.client.get(url_for('user.user_show', user_id=user_id))) def test_user_search_access(self): self.assert200(self.client.get(url_for('user.search'))) def test_user_by_group_access(self): self.assert200(self.client.get(url_for('user.show_by_group'))) class UserBlockingTestCase(LegacyUserFrontendTestBase): def setUp(self): super().setUp() username = permissions.UserData.user3_user.login self.test_user_id = User.q.filter_by(login=username).one().id def test_blocking_and_unblocking_works(self): user_show_endpoint = url_for("user.user_show", user_id=self.test_user_id) response = self.client.get(user_show_endpoint) self.assert200(response) response = self.client.post(url_for("user.suspend", user_id=self.test_user_id), data={'ends_at-unlimited': 'y', 'reason': 'Ist doof'}) self.assertRedirects(response, user_show_endpoint) self.assert_message_flashed("Nutzer gesperrt", 'success') response = self.client.post(url_for("user.unblock", user_id=self.test_user_id)) self.assertRedirects(response, user_show_endpoint) self.assert_message_flashed("Nutzer entsperrt", 'success') def test_unblocked_user_cannot_be_unblocked(self): response = self.client.post(url_for("user.unblock", user_id=self.test_user_id)) self.assert404(response) self.assert_message_substr_flashed("ist nicht gesperrt!", category='error') class UserMovingOutTestCase(LegacyUserFrontendTestBase): def setUp(self): super().setUp() username = permissions.UserData.user3_user.login self.user = User.q.filter_by(login=username).one() def test_user_cannot_be_moved_back_in(self): # attempt to move the user back in endpoint = url_for('user.move_back_in', user_id=self.user.id) response = self.client.post(endpoint, data={ # Will be serialized to str implicitly 'building': self.user.room.building.id, 'level': self.user.room.level, 'room_number': self.user.room.number, 'mac': "00:de:ad:be:ef:00", }) self.assert_404(response) self.assert_message_flashed("Nutzer {} ist nicht ausgezogen!" .format(self.user.id), category='error') def test_user_moved_out_correctly(self): endpoint = url_for('user.move_out', user_id=self.user.id) response = self.client.post(endpoint) self.assert_redirects(response, url_for('user.user_show', user_id=self.user.id)) self.assertMessageFlashed("Nutzer wurde ausgezogen", 'success') # TODO: Test whether everything has been done on the library side! class UserMovedOutTestCase(LegacyUserFrontendTestBase): def setUp(self): super().setUp() # Taking the dummy user because the one from the `permission` # fixtures is member in `config.member_group` username = dummy_user_fixtures.UserData.dummy.login self.user = User.q.filter_by(login=username).one() def test_user_cannot_be_moved_out(self): endpoint = url_for('user.move_out', user_id=self.user.id) response = self.client.post(endpoint, data={'comment': "Ist doof"}) self.assert_404(response) self.assert_message_flashed("Nutzer {} ist aktuell nirgends eingezogen!" .format(self.user.id), category='error') def test_user_can_be_moved_back_in(self): # This test will fail due to unusable fixtures. I recommend # against trying to fix them (they are “only” missing a # default traffic group for a building), because I tried that # and it takes far too long and far too much code duplication # that we shuold wait until somebody implements usable # factories. # user_id = self.user.id # endpoint = url_for('user.move_back_in', user_id=user_id) # # Pick a room, any room # room = Room.q.filter_by(inhabitable=True).limit(1).one() # response = self.client.post(endpoint, data={ # # Will be serialized to str implicitly # 'building': room.building.id, # 'level': room.level, # 'room_number': room.number, # 'mac': "00:de:ad:be:ef:00", # }) # self.assert_redirects(response, url_for('user.user_show', user_id=user_id)) # self.assert_message_flashed("Nutzer wurde wieder eingezogen", category='success') pass
Python
0
@@ -5211,8 +5211,499 @@ pass%0A +%0A def test_static_datasheet(self):%0A endpoint = url_for('user.static_datasheet', user_id=self.user.id)%0A response = self.client.get(endpoint)%0A self.assertTrue(response.data.startswith(b%22%25PDF%22))%0A self.assert200(response)%0A self.assertEqual(response.headers.get('Content-Type'), %22application/pdf%22)%0A self.assertEqual(response.headers.get('Content-Disposition'),%0A %22inline; filename=user_sheet_plain_%7B%7D.pdf%22.format(self.user.id))%0A
db3e3dd65c50b58e1a371f3d60be209d1322cfb9
Remove extra "Disconnected" message from console stub
host/python/keyglove_stub_console.py
host/python/keyglove_stub_console.py
#!/usr/bin/env python """ ================================================================================ Keyglove host control console demo application 2014-12-06 by Jeff Rowberg <jeff@rowberg.net> Changelog: 2014-12-06 - Initial release ================================================================================ Keyglove source code is placed under the MIT license Copyright (c) 2014 Jeff Rowberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ """ __author__ = "Jeff Rowberg" __license__ = "MIT" __version__ = "2014-12-06" __email__ = "jeff@rowberg.net" import sys, signal, time import kglib keyglove = None # Keyglove device instance (see 'kglib.KeygloveDevice') kgapi = kglib.KGAPI() # API protocol parser instance (see 'kglib.KGAPI') def my_on_connected(sender, args): print("+++ Keyglove connected") def my_on_disconnected(sender, args): print("--- Keyglove disconnected") def my_on_unplugged(sender, args): print("!!! Keyglove device unplugged, no communication possible at this time") def my_on_api_timeout(sender, args): print("??? API command timed out waiting for response, device may be disconnected") def my_kg_evt_touch_status(sender, args): print("*** Touch update: %s" % (' '.join(['%02X' % b for b in args['status']]))) def main(): global keyglove print("=================================") print("Keyglove Console Application Stub") print("=================================\n") # show available transports/backends print("USB options: %s" % kglib.usb_options) print("USB selected: %s" % kglib.usb_selected) print("Serial options: %s" % kglib.serial_options) print("Serial selected: %s\n" % kglib.serial_selected) # list all available devices print("Keyglove devices:") index = 0 devices = list(kglib.get_devices()) if len(devices) > 0: for device in devices: print(" #%d: %s @ %s" % (index, device.description, device.port)) index = index + 1 print("") else: # no devices available (no backends or nothing connected) print(" No devices found!") print(" Please make sure Keyglove is connected and") print(" PySerial, PyWinUSB, and/or PyUSB is available") exit(1) # attempt to connect and use Keyglove print("Connecting to first device in list...") keyglove = devices[0] try: # assign custom event handlers for connection/disconnection/unplug keyglove.on_connected += my_on_connected keyglove.on_disconnected += my_on_disconnected keyglove.on_unplugged += my_on_unplugged keyglove.on_api_timeout += my_on_api_timeout # assign custom event handler for kg_evt_touch_status() API event kgapi.kg_evt_touch_status += my_kg_evt_touch_status if keyglove.connect(kgapi): # repeatedly ping Keyglove device (SIGINT/Ctrl+C will break) while keyglove.connected: # build outgoing command packet cmd_packet = kgapi.kg_cmd_system_ping() # -------- get friendly info (completely unnecessary in production) -------- friendly = kgapi.friendly_packet(cmd_packet, False) if friendly: print("--> %s: %s" % (friendly['name'], friendly['payload'])) else: print("--> ERROR GETTING FRIENDLY PACKET INFO FOR COMMAND") # -------------------------------------------------------------------------- response = keyglove.send_and_return(cmd_packet, 1) if response: # -------- get friendly info (completely unnecessary in production) -------- friendly = kgapi.friendly_packet(response['raw'], True) if friendly: print("<-- %s: %s" % (friendly['name'], friendly['payload'])) else: print("<-- ERROR GETTING FRIENDLY PACKET INFO FOR RESPONSE") # -------------------------------------------------------------------------- # wait 5 seconds before repeating if keyglove.connected: time.sleep(5) except kglib.KeygloveError as e: print("Keyglove error (%s): %s" % (type(e), e)) if __name__ == '__main__': try: main() except KeyboardInterrupt: if keyglove != None: print("Disconnecting from Keyglove...") if keyglove.disconnect(): print("Disconnected") else: print("Could not disconnect!") print("Goodbye!") sys.exit(0)
Python
0.000001
@@ -5510,18 +5510,41 @@ != None + and keyglove.connected :%0A - @@ -5594,32 +5594,36 @@ %0A if +not keyglove.disconn @@ -5633,64 +5633,8 @@ ():%0A - print(%22Disconnected%22)%0A else:%0A