Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Clean up comments, fixing imports.
''' File: braket.py Author: Ivan Gonzalez Description: A function to implement quantum-mechanics brakets ''' from numpy import inner from core.exceptions import DMRGException def braket(bra, ket): """Takes a bra and a ket and return their braket You use this function to calculate the quantum mechanical braket...
''' File: braket.py Author: Ivan Gonzalez Description: A function to implement quantum-mechanics brakets ''' from numpy import inner, conjugate from dmrg_exceptions import DMRGException def braket(bra, ket): """Takes a bra and a ket and return their braket You use this function to calculate the quantum mechan...
Remove obsolete 'utils' entry from '__all__
from __future__ import absolute_import import etcd3.etcdrpc as etcdrpc from etcd3.client import Etcd3Client from etcd3.client import Transactions from etcd3.client import client from etcd3.leases import Lease from etcd3.locks import Lock from etcd3.members import Member __author__ = 'Louis Taylor' __email__ = 'louis@...
from __future__ import absolute_import import etcd3.etcdrpc as etcdrpc from etcd3.client import Etcd3Client from etcd3.client import Transactions from etcd3.client import client from etcd3.leases import Lease from etcd3.locks import Lock from etcd3.members import Member __author__ = 'Louis Taylor' __email__ = 'louis@...
Return None with invalid sample_width from sample_width_to_string.
# Copyright 2017 Google 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, ...
# Copyright 2017 Google 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, ...
Fix incorrect ne_NP locale tests
from __future__ import unicode_literals import unittest import re from faker import Factory from faker.utils import text from .. import string_types class ne_NP_FactoryTestCase(unittest.TestCase): def setUp(self): self.factory = Factory.create('ne_NP') def test_address(self): from fa...
from __future__ import unicode_literals import unittest from faker import Factory from .. import string_types class NeNPFactoryTestCase(unittest.TestCase): def setUp(self): self.factory = Factory.create('ne_NP') def test_address(self): from faker.providers.address.ne_NP import Prov...
Allow requests module to correctly encode query parameters.
#!/usr/bin/env python import json, os, requests from awsauth import S3Auth key = os.environ.get('UWOPENDATA_APIKEY') service = 'FoodMenu' # output = 'json' # callback = 'None' request = 'http://api.uwaterloo.ca/public/v1/' def getMenu(): url = request + '?' + 'key=' + key + '&' + 'service=' + service r = requests...
#!/usr/bin/env python import json, os, requests from awsauth import S3Auth key = os.environ.get('UWOPENDATA_APIKEY') service = 'FoodMenu' def getMenu(): payload = {'key': key, 'service': service} r = requests.get('http://api.uwaterloo.ca/public/v1/', params=payload) return r.text menu = getMenu() ACCESS_KEY = os....
Add command test for '--help' option
"""Unittest of command entry point.""" # Copyright 2015 Masayuki Yamamoto # # 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 r...
"""Unittest of command entry point.""" # Copyright 2015 Masayuki Yamamoto # # 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 r...
Add help text and a 'filenames' argument.
import tablib from django.core.management.base import BaseCommand from painter.models import Card class Command(BaseCommand): def handle(self, *args, **options): dataset = tablib.Dataset()
import tablib from django.core.management.base import BaseCommand from painter.models import Card class Command(BaseCommand): help = ('Clears the database of cards, then fills it with the contents of one or' + ' more specified CSV files.') def add_arguments(self, parser): parser.add_argu...
Support negative numbers in qtcreator debugging
from dumper import * def qdump__FixedPoint(d, value): d.putNumChild(3) raw = [ value["v"]["s"][i].integer() for i in range( value["v"]["numWords"].integer() ) ] ss = value["v"]["storageSize"].integer() exp = [raw[i] * 2**(i * ss) for i in range(len(raw)) ] d.putValue(sum(exp) * 2**-value["fractiona...
from dumper import * def qdump__FixedPoint(d, value): d.putNumChild(3) raw = [ value["v"]["s"][i].integer() for i in range( value["v"]["numWords"].integer() ) ] ss = value["v"]["storageSize"].integer() exp = [raw[i] * 2**(i * ss) for i in range(len(raw)) ] if raw[-1] >= 2**(ss-1): exp += [ ...
Send correct expiration timing in login email
from celery import shared_task from django.conf import settings from django.utils import timezone from agir.people.actions.mailing import send_mosaico_email def interleave_spaces(s, n=3): return ' '.join([s[i:i+n] for i in range(0, len(s), n)]) @shared_task def send_login_email(email, short_code, expiry_time):...
from celery import shared_task from django.conf import settings from django.utils import timezone from agir.people.actions.mailing import send_mosaico_email def interleave_spaces(s, n=3): return ' '.join([s[i:i+n] for i in range(0, len(s), n)]) @shared_task def send_login_email(email, short_code, expiry_time):...
Remove import for lib not commited yet.
from apt import APT_RECORDS, ATT_RECORDS, RWY_RECORDS, RMK_RECORDS, APT_RECORD_MAP from arb import ARB_RECORDS from awos import AWOS_RECORDS
from apt import APT_RECORDS, ATT_RECORDS, RWY_RECORDS, RMK_RECORDS, APT_RECORD_MAP from awos import AWOS_RECORDS
Define the structure of PyCArgObject in ctypes.
# hack a byref_at function from ctypes import * try: set except NameError: from sets import Set as set def _determine_layout(): result = set() for obj in (c_int(), c_longlong(), c_float(), c_double(), (c_int * 32)()): ref = byref(obj) result.add((c_void_p * 32).from_address(id(ref))[:...
from ctypes import * """ struct tagPyCArgObject { PyObject_HEAD ffi_type *pffi_type; char tag; union { char c; char b; short h; int i; long l; #ifdef HAVE_LONG_LONG PY_LONG_LONG q; #endif double d; float f; void *p; } value; PyObject *obj; int size; /* for the 'V' tag */ }; """ class value(Un...
Update Request, only return response time
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): ...
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): ...
Fix recursion issue with zip/rar files
import gzip import bz2 import rarfile import zipfile import tarfile class PackageHandler: def __init__(self, buffer): self.buffer = buffer def __iter__(self): for name in self.archive.namelist(): with self.archive.open(name) as ar: # TODO: Handle archives ...
import gzip import bz2 import rarfile import zipfile import tarfile class PackageHandler: def __init__(self, buffer): self.buffer = buffer def __iter__(self): for name in self.archive.namelist(): info = self.archive.getinfo(name) if hasattr(info, 'isdir') and info.isdir...
Make sure we use our own vendored packages
import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), 'resources', 'site-packages')) from xbmctorrent import plugin if __name__ == '__main__': plugin.run()
import sys, os sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'resources', 'site-packages')) from xbmctorrent import plugin if __name__ == '__main__': plugin.run()
Fix test in request parsing
import pytest from app.controllers.github_controller import GithubController pytestmark = pytest.mark.asyncio async def test_get_req_json(gh_sut: GithubController, mock_request): assert await gh_sut.get_request_json(mock_request) == 'json' async def test_get_req_event_header(gh_sut: GithubController, mock_req...
import pytest from app.controllers.github_controller import GithubController pytestmark = pytest.mark.asyncio async def test_get_req_json(gh_sut: GithubController, mock_request): assert await gh_sut.get_request_json(mock_request) == {'json': 'json'} async def test_get_req_event_header(gh_sut: GithubController...
Use count() on queryset instead of len()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from django.utils import timezone try: from django.core.management.base import BaseCommand except ImportError: from django.core.management.base import NoArgsCommand as BaseCommand ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from django.utils import timezone try: from django.core.management.base import BaseCommand except ImportError: from django.core.management.base import NoArgsCommand as BaseCommand ...
Disable data migration for deployment
# Generated by Django 2.2.24 on 2021-10-22 19:54 from django.db import migrations def resave_packets(apps, schema_editor): ''' Re-save all existing packets to update their URLs based on the new value of MERGE_HOST. ''' for packet in ('BillPacket', 'EventPacket'): packet_model = apps.get_m...
# Generated by Django 2.2.24 on 2021-10-22 19:54 from django.db import migrations def resave_packets(apps, schema_editor): ''' Re-save all existing packets to update their URLs based on the new value of MERGE_HOST. ''' # for packet in ('BillPacket', 'EventPacket'): # packet_model = apps.get...
Use the right style of request.
from flask import Flask from flask import request import os from dogapi import dog_http_api as api app = Flask(__name__) api.api_key = os.environ.get('DD_API_KEY') action_url = "/" + os.environ.get('BASE_URL') + "/" @app.route(action_url, methods=['POST', 'GET']) def hello(): api.metric('mailgun.event', (reques...
from flask import Flask from flask import request import os from dogapi import dog_http_api as api app = Flask(__name__) api.api_key = os.environ.get('DD_API_KEY') action_url = "/" + os.environ.get('BASE_URL') + "/" @app.route(action_url, methods=['POST', 'GET']) def hello(): api.metric('mailgun.event', (reques...
Remove the dollar from the regex to avoid problems including URLs.
from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() # Examples: # url(r'^$', 'gettingstarted.views.home', name='home'), # url(r'^blog/', include('blog.urls')), urlpatterns = [ url(r'^$', include('rog.urls')), url(r'^admin/', include(admin.site.urls)), ]
from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() # Examples: # url(r'^$', 'gettingstarted.views.home', name='home'), # url(r'^blog/', include('blog.urls')), urlpatterns = [ url(r'^', include('rog.urls')), url(r'^admin/', include(admin.site.urls)), ]
Set product_configurator_mrp to uninstallable until fixing / refactoring
{ 'name': 'Product Configurator Manufacturing', 'version': '11.0.1.0.0', 'category': 'Manufacturing', 'summary': 'BOM Support for configurable products', 'author': 'Pledra', 'license': 'AGPL-3', 'website': 'http://www.pledra.com/', 'depends': ['mrp', 'product_configurator'], "data": ...
{ 'name': 'Product Configurator Manufacturing', 'version': '11.0.1.0.0', 'category': 'Manufacturing', 'summary': 'BOM Support for configurable products', 'author': 'Pledra', 'license': 'AGPL-3', 'website': 'http://www.pledra.com/', 'depends': ['mrp', 'product_configurator'], "data": ...
Add topic to PublicBodyAdmin list_filter and list_display
from django.contrib import admin from froide.publicbody.models import PublicBody, FoiLaw class PublicBodyAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("geography", "name",)} list_display = ('name', 'classification', 'geography') list_filter = ('classification',) search_fields = ['name', "des...
from django.contrib import admin from froide.publicbody.models import PublicBody, FoiLaw class PublicBodyAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("geography", "name",)} list_display = ('name', 'classification', 'topic', 'geography') list_filter = ('classification', 'topic',) search_fiel...
Reduce number of queries to DB
from inboxen.models import Alias, Attachment, Email, Header from config.settings import datetime_format, recieved_header_name from datetime import datetime def make_email(message, alias, domain): inbox = Alias.objects.filter(alias=alias, domain__domain=domain)[0] user = inbox.user body = message.base.body ...
from inboxen.models import Alias, Attachment, Email, Header from config.settings import datetime_format, recieved_header_name from datetime import datetime def make_email(message, alias, domain): inbox = Alias.objects.filter(alias=alias, domain__domain=domain)[0] user = inbox.user body = message.base.body ...
Add appearance count to the API.
# -*- coding: utf-8 -*- from rest_framework import serializers from apps.broadcasts.models import Broadcast, Host, Raid, Series from apps.games.models import Game, Platform from apps.subscribers.models import Ticket class HostSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'timestamp...
# -*- coding: utf-8 -*- from rest_framework import serializers from apps.broadcasts.models import Broadcast, Host, Raid, Series from apps.games.models import Game, Platform from apps.subscribers.models import Ticket class HostSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'timestamp...
Use < instead of <= in environment markers.
from buckle.version import VERSION from setuptools import setup, find_packages setup( name='buckle', version=VERSION, description='Buckle: It ties your toolbelt together', author='Nextdoor', author_email='eng@nextdoor.com', packages=find_packages(exclude=['ez_setup']), scripts=['bin/buckle...
from buckle.version import VERSION from setuptools import setup, find_packages setup( name='buckle', version=VERSION, description='Buckle: It ties your toolbelt together', author='Nextdoor', author_email='eng@nextdoor.com', packages=find_packages(exclude=['ez_setup']), scripts=['bin/buckle...
Add support for Python 3 by doing 2to3 conversion when installing the package with distutils. This way we don't have to maintain two separate repositories to support Python 2.x and Python 3.x.
#!/usr/bin/env python #from distutils.core import setup from setuptools import setup, find_packages setup( name="imaplib2", version="2.28.3", description="A threaded Python IMAP4 client.", author="Piers Lauder", url="http://github.com/bcoe/imaplib2", classifiers = [ "Programming Languag...
#!/usr/bin/env python # from distutils.core import setup from setuptools import setup, find_packages try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: from distutils.command.build_py import build_py setup( name="imaplib2", version="2.28.4", description="A th...
Allow Django Evolution to install along with Django >= 1.7.
#!/usr/bin/env python # # Setup script for Django Evolution from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test from django_evolution import get_package_version, VERSION def run_tests(*args): import os os.system('tests/ru...
#!/usr/bin/env python # # Setup script for Django Evolution from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test from django_evolution import get_package_version, VERSION def run_tests(*args): import os os.system('tests/ru...
Add some more trivial bql2sql tests.
# -*- coding: utf-8 -*- # Copyright (c) 2010-2014, MIT Probabilistic Computing Project # # 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/LICENS...
# -*- coding: utf-8 -*- # Copyright (c) 2010-2014, MIT Probabilistic Computing Project # # 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/LICENS...
Revert version number on release branch.
"""Spherical harmonic vector wind analysis.""" # Copyright (c) 2012-2014 Andrew Dawson # # 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 ...
"""Spherical harmonic vector wind analysis.""" # Copyright (c) 2012-2014 Andrew Dawson # # 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 ...
Fix encoding error preventing install
from setuptools import setup, find_packages setup( # packaging information that is likely to be updated between versions name='icecake', version='0.6.0', packages=['icecake'], py_modules=['cli', 'templates', 'livejs'], entry_points=''' [console_scripts] icecake=icecake.cli:cli ...
from setuptools import setup, find_packages from codec import open setup( # packaging information that is likely to be updated between versions name='icecake', version='0.6.0', packages=['icecake'], py_modules=['cli', 'templates', 'livejs'], entry_points=''' [console_scripts] ic...
Add x-y flipping code for SlicePlot
# -*- coding: utf-8 -*- """ Created on Fri Jan 9 12:52:31 2015 @author: stuart """ import os import glob import yt model = 'spruit' datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/') files = glob.glob(datadir+'/*') files.sort() print(files) ds = yt.load(files[0]) slc = yt.SlicePlot(ds, fields='density...
# -*- coding: utf-8 -*- """ Created on Fri Jan 9 12:52:31 2015 @author: stuart """ import os import glob import yt model = 'spruit' datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/') files = glob.glob(datadir+'/*') files.sort() print(files) ds = yt.load(files[0]) # Axes flip for normal='y' #ds.coordin...
Update error in 3.7 release
import os import re import sys import platform import subprocess import multiprocessing from setuptools import setup, Extension from setuptools.command.build_ext import build_ext from distutils.version import LooseVersion cores = multiprocessing.cpu_count()*1.25 threads="-j" + str(int(cores)) class CMakeExtension...
import os import re import sys import platform import subprocess import multiprocessing from setuptools import setup, Extension from setuptools.command.build_ext import build_ext from distutils.version import LooseVersion cores = multiprocessing.cpu_count()*1.25 threads="-j" + str(int(cores)) class CMakeExtension...
Change the smoke test imports to a relative import for consistency.
# -*- coding: utf-8 -*- import unittest import sys sys.path.insert(0, '../mafia') from game import Game from game import Player from testclient.testmessenger import TestMessenger class SmokeTest(unittest.TestCase): def setUp(self): self.messenger = TestMessenger() def test_smoke_test(self):...
# -*- coding: utf-8 -*- import unittest import sys sys.path.insert(0, '../') from mafia.game import Game from mafia.game import Player from testclient.testmessenger import TestMessenger class SmokeTest(unittest.TestCase): def setUp(self): self.messenger = TestMessenger() def test_smoke_test...
Make things a little better
from hello_world import hello_world from unittest import TestCase class BasicTest(TestCase): def test_basic_hello_world(self): """ Test basic hello world messaging """ False
from hello_world import hello_world from unittest import TestCase class BasicTest(TestCase): def test_basic_hello_world(self): """ Test basic hello world messaging """ self.assertTrue(callable(hello_world))
Fix issue with enum not accepting null
from enum import IntEnum from discord import Embed class OpStatus(IntEnum): SUCCESS = 0x2ECC71, FAILURE = 0xc0392B, WARNING = 0xf39C12, NONE = None def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed: name = ctx.message.server.me.nick if ctx.message.server.me.nick is ...
from enum import IntEnum from discord import Embed class OpStatus(IntEnum): SUCCESS = 0x2ECC71, FAILURE = 0xc0392B, WARNING = 0xf39C12, NONE = -1 def build_embed(ctx, desc: str, title: str = '', status: OpStatus = OpStatus.SUCCESS) -> Embed: name = ctx.message.server.me.nick if ctx.message.server.me.nick is no...
Add extra endpoint for posts?
# Author: Braedy Kuzma from django.conf.urls import url from . import views urlpatterns = [ url(r'^posts/$', views.PostsView.as_view(), name='posts'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(), name='post'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$', views.Com...
# Author: Braedy Kuzma from django.conf.urls import url from . import views urlpatterns = [ url(r'^posts/$', views.PostsView.as_view(), name='posts'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/$', views.PostView.as_view(), name='post'), url(r'^posts/(?P<pid>[0-9a-fA-F\-]+)/comments/$', views.Com...
Implement Eternal Sentinel, Stormcrack and Hammer of Twilight
from ..utils import * ## # Minions class OG_023: "Primal Fusion" play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM) OG_023t = buff(+1, +1) class OG_209: "Hallazeal the Ascended" events = Damage(source=SPELL + FRIENDLY).on(Heal(FRIENDLY_HERO, Damage.AMOUNT))
from ..utils import * ## # Minions class OG_023: "Primal Fusion" play = Buff(TARGET, "OG_023t") * Count(FRIENDLY_MINIONS + TOTEM) OG_023t = buff(+1, +1) class OG_026: "Eternal Sentinel" play = UnlockOverload(CONTROLLER) class OG_209: "Hallazeal the Ascended" events = Damage(source=SPELL + FRIENDLY).on(Hea...
Use the fqdn when registering with the master.
import json import requests from flask import request, jsonify from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/', methods=['POS...
import json import socket import requests from flask import request, jsonify from dadd.worker import app from dadd.worker.proc import ChildProcess @app.route('/run/', methods=['POST']) def run_process(): proc = ChildProcess(request.json) proc.run() return jsonify(proc.info()) @app.route('/register/',...
Build out hash function of hash table class
#!/usr/bin/env python '''Implementation of a simple hash table. The table has `hash`, `get` and `set` methods. The hash function uses a very basic hash algorithm to insert the value into the table. ''' class HashItem(object): def __init__(self): pass class Hash(object): def __init__(self, size=1024...
#!/usr/bin/env python '''Implementation of a simple hash table. The table has `hash`, `get` and `set` methods. The hash function uses a very basic hash algorithm to insert the value into the table. ''' class HashItem(object): def __init__(self): pass class Hash(object): def __init__(self, size=1024...
Add the deletion of the app users
from django.core.management.base import BaseCommand, CommandError from app.models import Author, Location, AutoComment, Comment, Idea, Vote class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write('Starting to clean app tables...') try: Idea.objects.all().delet...
from django.core.management.base import BaseCommand, CommandError from app.models import Author, Location, AutoComment, Comment, Idea, Vote, SocialNetworkAppUser class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write('Starting to clean app tables...') try: Id...
Fix was_published_recently reporting polls from the future
from django.db import models from django.utils import timezone from datetime import timedelta class Poll(models.Model): text = models.CharField(max_length=200) created_ts = models.DateTimeField() updated_ts = models.DateTimeField(null=True, default=None) is_published = models.BooleanField(default=Fals...
from django.db import models from django.utils import timezone from datetime import timedelta class Poll(models.Model): text = models.CharField(max_length=200) created_ts = models.DateTimeField() updated_ts = models.DateTimeField(null=True, default=None) is_published = models.BooleanField(default=Fals...
Add a legacy version for older versions of Django.
from django.db import transaction, connection class TransactionMiddleware(object): def process_job(self, job): if not connection.in_atomic_block: transaction.set_autocommit(False) def process_result(self, job, result, duration): if not connection.in_atomic_block: transa...
from django.db import transaction, connection class TransactionMiddleware(object): def process_job(self, job): if not connection.in_atomic_block: transaction.set_autocommit(False) def process_result(self, job, result, duration): if not connection.in_atomic_block: transa...
Use removing rather than copying
#!/usr/bin/env python from pathlib import Path from random import shuffle from shutil import copy # configs N = 10000 SAMPLED_DIR_PATH = Path('sampled/') # mkdir if doesn't exist if not SAMPLED_DIR_PATH.exists(): SAMPLED_DIR_PATH.mkdir() # sample and copy paths = [p for p in Path('preprocessed/').iterdir()...
#!/usr/bin/env python from pathlib import Path from random import sample from os import remove # configs N = 10000 # remove unsampled paths = [path for path in Path('preprocessed/').iterdir()] paths_len = len(paths) if paths_len <= N: raise RuntimeError('file count {:,} <= N {:,}'.format(paths_len, N)) for...
Add node id to url.
from django.conf.urls import url from api.wb import views app_name = 'osf' urlpatterns = [ url(r'^move/', views.MoveFile.as_view(), name=views.MoveFile.view_name), url(r'^copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name), ]
from django.conf.urls import url from api.wb import views app_name = 'osf' urlpatterns = [ url(r'^(?P<node_id>\w+)/move/', views.MoveFile.as_view(), name=views.MoveFile.view_name), url(r'^(?P<node_id>\w+)/copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name), ]
Change tender init handlers names
from pyramid.events import subscriber from openprocurement.tender.core.events import TenderInitializeEvent from openprocurement.tender.core.utils import get_now, calculate_business_date @subscriber(TenderInitializeEvent, procurementMethodType="reporting") def tender_init_handler(event): """ initialization handler...
from pyramid.events import subscriber from openprocurement.tender.core.events import TenderInitializeEvent from openprocurement.tender.core.utils import get_now, calculate_business_date @subscriber(TenderInitializeEvent, procurementMethodType="reporting") def tender_init_handler_1(event): """ initialization handl...
Fix object storage apiType for S3 and Swift.
"""List Object Storage accounts.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import formatting @click.command() @environment.pass_env def cli(env): """List object storage accounts.""" mgr = SoftLayer.ObjectStorageM...
"""List Object Storage accounts.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import formatting @click.command() @environment.pass_env def cli(env): """List object storage accounts.""" mgr = SoftLayer.ObjectStorageM...
Use is_authenticated as a property.
from .models import Observer class ObserverMiddleware(object): """ Attaches an observer instance to every request coming from an authenticated user. """ def process_request(self, request): assert hasattr(request, 'user'), "ObserverMiddleware requires auth middleware to be installed." ...
from .models import Observer class ObserverMiddleware(object): """ Attaches an observer instance to every request coming from an authenticated user. """ def process_request(self, request): assert hasattr(request, 'user'), "ObserverMiddleware requires auth middleware to be installed." ...
Make tag and key be a composite primary key
from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.schema import UniqueConstraint Base = declarative_base() class Store(Base): __tablename__ = 'store' id = Column(Integer, primary_key=True, autoincrement=True) key = Column(String) tag...
from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.schema import PrimaryKeyConstraint Base = declarative_base() class Store(Base): __tablename__ = 'store' key = Column(String) tag = Column(String) value = Column(String) __table_ar...
Add missing --name flag to 'envy snapshot'
from cloudenvy.envy import Envy class EnvySnapshot(object): """Create a snapshot of an ENVy.""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('snapshot', help='snapshot help') subparser.se...
from cloudenvy.envy import Envy class EnvySnapshot(object): """Create a snapshot of an ENVy.""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('snapshot', help='snapshot help') subparser.se...
Add taza, tazon and vaso global conversions
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, division import logging logger = logging.getLogger(__name__) # pylint: disable=invalid-name DATA_DIR = 'data' DEFAULT_CONVERSIONS = { 'kg': {'g': 1000}, 'l': {'ml': 1000}, } # yapf: disable
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, division import logging logger = logging.getLogger(__name__) # pylint: disable=invalid-name DATA_DIR = 'data' DEFAULT_CONVERSIONS = { 'kg': {'g': 1000}, 'l': {'ml': 1000}, 'taza': {'ml': 250}, 't...
Put correct directory for profiles in test_hmmsearch
import os import unittest import sys # hack to allow tests to find inmembrane in directory above module_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(module_dir, '..')) import inmembrane class TestHmmsearch3(unittest.TestCase): def setUp(self): self.dir = os.path.join(modul...
import os import unittest import sys # hack to allow tests to find inmembrane in directory above module_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(module_dir, '..')) import inmembrane class TestHmmsearch3(unittest.TestCase): def setUp(self): self.dir = os.path.join(modul...
Fix Color enum setup when TERM isn't set
import enum import os import subprocess import sys import blessings from .misc import isatty if isatty(sys.stdout) and os.getenv("TERM"): Terminal = blessings.Terminal else: class Terminal: def __getattr__(self, name): return "" TERM = Terminal() class Color(enum.Enum): none = ...
import enum import os import subprocess import sys import blessings from .misc import isatty if isatty(sys.stdout) and os.getenv("TERM"): Terminal = blessings.Terminal else: # XXX: Mock terminal that returns "" for all attributes class TerminalValue: registry = {} @classmethod d...
FIX only pass S52 test
from expects import expect, equal from primestg.report import Report with fdescription('Report S52 example'): with before.all: self.data_filename = 'spec/data/MRTR000000822522_0_S52_1_20200929001048' self.report = {} with open(self.data_filename) as data_file: self.report = R...
from expects import expect, equal from primestg.report import Report with description('Report S52 example'): with before.all: self.data_filename = 'spec/data/MRTR000000822522_0_S52_1_20200929001048' self.report = {} with open(self.data_filename) as data_file: self.report = Re...
Fix tests on Python 3.3 and 3.4
import attr def Field(*args, default=attr.NOTHING, **kwargs): if callable(default): default = attr.Factory(default) return attr.ib(*args, default=default, **kwargs) def ManyToManyField(cls, *args, **kwargs): metadata = { 'related': { 'target': cls, 'type': 'ManyT...
import attr def Field(*args, default=attr.NOTHING, **kwargs): if callable(default): default = attr.Factory(default) return attr.ib(*args, default=default, **kwargs) def ManyToManyField(cls, *args, **kwargs): metadata = { 'related': { 'target': cls, 'type': 'ManyT...
Add NecropsyReport in Model Necropsy
# -*- coding: utf-8 -*- from django.db import models # Create your models here. class Necropsy (models.Model): clinical_information = models.TextField(null=True, blank=True) macroscopic = models.TextField(null=True, blank=True) microscopic = models.TextField(null=True, blank=True) conclusion = models.TextField(nul...
# -*- coding: utf-8 -*- from django.db import models from modeling.exam import Exam from modeling.report import ReportStatus class NecropsyStatus(models.Model): description = models.CharField(max_length=50) class Necropsy(models.Model): clinical_information = models.TextField(null=True, blank=True) main...
Set the default prefix for ProjectSurveys to gsoc_program.
#!/usr/bin/python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
#!/usr/bin/python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
Update test case for 2014
import unittest2 import datetime from google.appengine.ext import testbed from datafeeds.datafeed_fms import DatafeedFms class TestDatafeedFmsTeams(unittest2.TestCase): def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_urlfetch_stub() se...
import unittest2 import datetime from google.appengine.ext import testbed from datafeeds.datafeed_fms import DatafeedFms class TestDatafeedFmsTeams(unittest2.TestCase): def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_urlfetch_stub() se...
Add hook for protactor params
# -*- coding: utf-8 -*- import os import subprocess class ProtractorTestCaseMixin(object): protractor_conf = 'protractor.conf.js' suite = None specs = None @classmethod def setUpClass(cls): super(ProtractorTestCaseMixin, cls).setUpClass() with open(os.devnull, 'wb') as f: ...
# -*- coding: utf-8 -*- import os import subprocess class ProtractorTestCaseMixin(object): protractor_conf = 'protractor.conf.js' suite = None specs = None @classmethod def setUpClass(cls): super(ProtractorTestCaseMixin, cls).setUpClass() with open(os.devnull, 'wb') as f: ...
Work on classical_risk test_case_1 and test_case_2
import unittest from nose.plugins.attrib import attr from openquake.qa_tests_data.classical_risk import ( case_1, case_2, case_3, case_4) from openquake.calculators.tests import CalculatorTestCase class ClassicalRiskTestCase(CalculatorTestCase): @attr('qa', 'risk', 'classical_risk') def test_case_1(self...
import unittest from nose.plugins.attrib import attr from openquake.qa_tests_data.classical_risk import ( case_1, case_2, case_3, case_4) from openquake.calculators.tests import CalculatorTestCase class ClassicalRiskTestCase(CalculatorTestCase): @attr('qa', 'risk', 'classical_risk') def test_case_1(self...
Fix reversed condition for ignoring "can't allocate region" errors
#!/usr/bin/env python # Look for "szone_error" (Tiger), "malloc_error_break" (Leopard), "MallocHelp" (?) # which are signs of malloc being unhappy (double free, out-of-memory, etc). def amiss(logPrefix): foundSomething = False currentFile = file(logPrefix + "-err", "r") pline = "" ppline = "" ...
#!/usr/bin/env python # Look for "szone_error" (Tiger), "malloc_error_break" (Leopard), "MallocHelp" (?) # which are signs of malloc being unhappy (double free, out-of-memory, etc). def amiss(logPrefix): foundSomething = False currentFile = file(logPrefix + "-err", "r") pline = "" ppline = "" ...
Add proper logging to tests when in verbose mode
####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################...
####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################...
Switch to using popen as the function name to stick more to subprocess naming
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout ...
#! /usr/bin/env python from subprocess import Popen, PIPE def popen(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout ...
Add cell-boundary preprocessing to HaralickTexture measurement
from . import Measurement import feature_extraction.util.cleanup as cleanup class HaralickTexture(Measurement): def compute(self, image): return []
from . import Measurement import feature_extraction.util.cleanup as cleanup from skimage.morphology import binary_erosion, disk class HaralickTexture(Measurement): default_options = { 'clip_cell_borders': True, 'erode_cell': False, 'erode_cell_amount': False, } def __init__(self, options=None): super(Harali...
Sort the rows in CSV output on (constituency, last name)
import csv import StringIO from .models import CSV_ROW_FIELDS def encode_row_values(d): return { k: unicode('' if v is None else v).encode('utf-8') for k, v in d.items() } def list_to_csv(candidates_list): output = StringIO.StringIO() writer = csv.DictWriter( output, f...
import csv import StringIO from .models import CSV_ROW_FIELDS def encode_row_values(d): return { k: unicode('' if v is None else v).encode('utf-8') for k, v in d.items() } def candidate_sort_key(row): return (row['constituency'], row['name'].split()[-1]) def list_to_csv(candidates_list):...
Add test_i_filter_random_empty_words() to assert that a list that contains an empty string will return the stock phrase
import chatbot_brain import input_filters def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_...
import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def te...
Add linting for pipeline step existence
from .node import Node class ExecutionNode(Node): type = 'execution' def __init__(self, name, step, override=None): if override is None: override = {} self.name = name self.step = step self.override = override
from .node import Node class ExecutionNode(Node): type = 'execution' def __init__(self, name, step, override=None): if override is None: override = {} self.name = name self.step = step self.override = override def lint(self, lint_result, context): supe...
Fix django 1.5 warning - provide debug filter
# A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, '...
# A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, '...
Reduce how often this runs
from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('cron', hour="*/3", minute=0) def updater(): """ Run our update command every three hours. """ # Set env import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")...
from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('cron', hour="10", minute=0) def updater(): """ Run our update command every three hours. """ # Set env import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") ...
Use argparse instead of manually parsing
#!/usr/bin/env python3 # ############################################################################# # Copyright (c) 2018-present lzutao <taolzu(at)gmail.com> # All rights reserved. # # This source code is licensed under both the BSD-style license (found in the # LICENSE file in the root directory of this source t...
#!/usr/bin/env python3 # ############################################################################# # Copyright (c) 2018-present lzutao <taolzu(at)gmail.com> # All rights reserved. # # This source code is licensed under both the BSD-style license (found in the # LICENSE file in the root directory of this source t...
Improve report format and information
#!/usr/bin/env python import rethinkdb as r from optparse import OptionParser def compute_project_size(project_id, conn): total = 0 for f in r.table('project2datafile').get_all(project_id, index="project_id").eq_join('datafile_id', r.table( 'datafiles')).zip().run(conn): total = total + f...
#!/usr/bin/env python import rethinkdb as r from optparse import OptionParser def compute_project_size(project_id, conn): total = 0 count = 0 for f in r.table('project2datafile').get_all(project_id, index="project_id").eq_join('datafile_id', r.table( 'datafiles')).zip().run(conn): tot...
Remove a no cover pragma having no effect (since the pragma only affects the current line)
# pragma: no cover import warnings import django if django.VERSION < (3, 2): from feincms3.applications import * # noqa warnings.warn( "Django 3.2 will start autodiscovering app configs inside '.apps' modules." " We cannot continue using feincms3.apps because the AppsMixin inside this" ...
import warnings import django if django.VERSION < (3, 2): from feincms3.applications import * # noqa warnings.warn( "Django 3.2 will start autodiscovering app configs inside '.apps' modules." " We cannot continue using feincms3.apps because the AppsMixin inside this" " module can on...
Remove matplotlib from required dependencies
from setuptools import setup from tools.generate_pyi import generate_pyi def main(): # Generate .pyi files import pyxtf.xtf_ctypes generate_pyi(pyxtf.xtf_ctypes) import pyxtf.vendors.kongsberg generate_pyi(pyxtf.vendors.kongsberg) # Run setup script setup(name='pyxtf', version='0...
from setuptools import setup from tools.generate_pyi import generate_pyi def main(): # Generate .pyi files import pyxtf.xtf_ctypes generate_pyi(pyxtf.xtf_ctypes) import pyxtf.vendors.kongsberg generate_pyi(pyxtf.vendors.kongsberg) # Run setup script setup(name='pyxtf', version='0...
Enable project search form API.
from django.conf.urls.defaults import patterns, url, include from surlex.dj import surl from .api import ProjectResource, ProjectDetailResource from .views import ProjectListView, ProjectDetailView, ProjectMapView project_resource = ProjectResource() projectdetail_resource = ProjectDetailResource() urlpatterns = p...
from django.conf.urls.defaults import patterns, url, include from surlex.dj import surl from .api import ProjectResource, ProjectDetailResource, ProjectSearchFormResource from .views import ProjectListView, ProjectDetailView, ProjectMapView project_resource = ProjectResource() projectdetail_resource = ProjectDetailR...
Adjust loop delay to take into account switch undecidedness (Step one in presentation)
import time import urllib import RPi.GPIO as GPIO # GPIO input pin to use LPR_PIN = 3 # URL to get image from SOURCE = 'http://192.168.0.13:8080/photoaf.jpg' # Path to save image locally FILE = 'img.jpg' # Use GPIO pin numbers GPIO.setmode(GPIO.BCM) # Disable "Ports already in use" warning GPIO.setwarnings(False) # ...
import time import urllib import RPi.GPIO as GPIO # GPIO input pin to use LPR_PIN = 3 # URL to get image from SOURCE = 'http://192.168.0.13:8080/photoaf.jpg' # Path to save image locally FILE = 'img.jpg' # Use GPIO pin numbers GPIO.setmode(GPIO.BCM) # Disable "Ports already in use" warning GPIO.setwarnings(False) # ...
Fix unmatched field in Authorization
""" .. module: lemur.authorizations.models :platform: unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Netflix Secops <secops@netflix.com> """ from sqlalchemy import Column, Integer, String from sqlalchemy_utils import JSONType...
""" .. module: lemur.authorizations.models :platform: unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Netflix Secops <secops@netflix.com> """ from sqlalchemy import Column, Integer, String from sqlalchemy_utils import JSONType...
Use www.wikidata.org instead of wikidata.org Rewrite-followup to r11105
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'wikidata.org', 'repo': 'wik...
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'www.wikidata.org', 'repo': ...
Add a comment about where the basic example was taken [skip CI]
import sys from browser import BrowserDialog from PyQt4 import QtGui from PyQt4.QtCore import QUrl from PyQt4.QtWebKit import QWebView class MyBrowser(QtGui.QDialog): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) QWebView.__init__(self) self.ui = BrowserDialog() ...
# Basic example for testing purposes, taken from # https://pythonspot.com/creating-a-webbrowser-with-python-and-pyqt-tutorial/ import sys from browser import BrowserDialog from PyQt4 import QtGui from PyQt4.QtCore import QUrl from PyQt4.QtWebKit import QWebView class MyBrowser(QtGui.QDialog): def __init__(self, ...
Save the image to png
#! /usr/bin/env python from theora import Ogg from numpy import concatenate, zeros_like from scipy.misc import toimage f = open("video.ogv") o = Ogg(f) Y, Cb, Cr = o.test() Cb2 = zeros_like(Y) for i in range(Cb2.shape[0]): for j in range(Cb2.shape[1]): Cb2[i, j] = Cb[i/2, j/2] Cr2 = zeros_like(Y) for i in...
#! /usr/bin/env python from theora import Ogg from numpy import concatenate, zeros_like from scipy.misc import toimage f = open("video.ogv") o = Ogg(f) Y, Cb, Cr = o.test() Cb2 = zeros_like(Y) for i in range(Cb2.shape[0]): for j in range(Cb2.shape[1]): Cb2[i, j] = Cb[i/2, j/2] Cr2 = zeros_like(Y) for i in...
Disable flaky MSR power monitor unit test.
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import time import unittest from telemetry import decorators from telemetry.internal.platform.power_monitor import msr_power_monitor from tel...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import time import unittest from telemetry import decorators from telemetry.internal.platform.power_monitor import msr_power_monitor from tel...
Fix url include for api app
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'gnome_developer_network.views.home', name='home'), # url(r'^gnome_developer_networ...
# vim: tabstop=4 noexpandtab shiftwidth=4 softtabstop=4 from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'gnome_developer_network.views....
Halt on unrecognized constant pool tag
#!/usr/bin/python import argparse import struct import sys ############### ### CLASSES ### ############### class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) ################### ### SUBROUTINES ### ###...
#!/usr/bin/python import argparse import os import struct import sys ############### ### CLASSES ### ############### class MyParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_help() sys.exit(2) ################### ### SUBROUTIN...
Use tempdir to ensure there will always be a directory which can be accessed.
''' Tests for the file state ''' # Import python libs import os # # Import salt libs from saltunittest import TestLoader, TextTestRunner import integration from integration import TestDaemon class CMDTest(integration.ModuleCase): ''' Validate the cmd state ''' def test_run(self): ''' c...
''' Tests for the file state ''' # Import python libs # Import salt libs import integration import tempfile class CMDTest(integration.ModuleCase): ''' Validate the cmd state ''' def test_run(self): ''' cmd.run ''' ret = self.run_state('cmd.run', name='ls', cwd=tempfil...
Add markers to time series
import plotly as py import plotly.graph_objs as go from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) sleep_durations = [] nap_durations = [] for date, rests in raw_data.items(): sleep_total = nap_total = 0 for r in rests: rest, wake, is_nap ...
import plotly as py import plotly.graph_objs as go from sys import argv import names from csvparser import parse data_file = argv[1] raw_data = parse(data_file) sleep_durations = [] nap_durations = [] for date, rests in raw_data.items(): sleep_total = nap_total = 0 for r in rests: rest, wake, is_nap ...
Fix various small issues in DB support
import abc import sqlite3 import Config class Db(object): __metaclass__ = abc.ABCMeta def __init__(self): self._connection = self.connect() @abc.abstractmethod def connect(self, config_file = None): raise NotImplementedError("Called method is not implemented") @abc.abstrac...
import abc import sqlite3 from ebroker.Config import Config def getDb(config_file = None): return SQLiteDb(config_file) class Db(object): __metaclass__ = abc.ABCMeta def __init__(self, config_file = None): self._config_file = config_file self._connection = None # make sure attribute ...
Fix for Qt5 in plugins that use matplotlib
# # Plot.py -- Plotting function for Ginga FITS viewer. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # # GUI imports from ginga.qtw.QtHelp import QtGui, QtCore from g...
# # Plot.py -- Plotting function for Ginga FITS viewer. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # # GUI imports from ginga.qtw.QtHelp import QtGui, QtCore from g...
Stop manually specifying name of task.
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj from mysite.search import controllers import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): ...
from datetime import timedelta from mysite.search.models import Project from celery.task import PeriodicTask from celery.registry import tasks from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj from mysite.search import controllers import mysite.customs.miro class GrabLaunchpadBugs(PeriodicTask): ...
Remove no longer needed package_data
#!/usr/bin/env python from setuptools import setup, find_packages __about__ = {} with open("warehouse/__about__.py") as fp: exec(fp, None, __about__) setup( name=__about__["__title__"], version=__about__["__version__"], description=__about__["__summary__"], long_description=open("README.rst").re...
#!/usr/bin/env python from setuptools import setup, find_packages __about__ = {} with open("warehouse/__about__.py") as fp: exec(fp, None, __about__) setup( name=__about__["__title__"], version=__about__["__version__"], description=__about__["__summary__"], long_description=open("README.rst").re...
Add project description for PyPI
import versioneer from setuptools import setup, find_packages setup( name='domain-event-broker', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='Send and receive domain events via RabbitMQ', author='Ableton AG', author_email='webteam@ableton.com', url='ht...
import versioneer from setuptools import setup, find_packages # Add README as description from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='domain-event-broker', vers...
Fix unicode string bug in previous commit
from django.contrib import admin from django.utils.html import format_html from django.utils.translation import ugettext_lazy as _ from . models import Meal import os class MealAdmin(admin.ModelAdmin): def file(self): class Meta: allow_tags = True verbose_name = _('File') r...
from django.contrib import admin from django.utils.html import format_html from django.utils.translation import ugettext_lazy as _ from . models import Meal import os class MealAdmin(admin.ModelAdmin): def file(self): class Meta: allow_tags = True verbose_name = _('File') r...
Move ecdsa from extras_require to install_requires
#from distribute_setup import use_setuptools #use_setuptools() from setuptools import setup, find_packages from os.path import dirname, join here = dirname(__file__) setup( name='btchip-python', version='0.1.28', author='BTChip', author_email='hello@ledger.fr', description='Python library to commu...
#from distribute_setup import use_setuptools #use_setuptools() from setuptools import setup, find_packages from os.path import dirname, join here = dirname(__file__) setup( name='btchip-python', version='0.1.28', author='BTChip', author_email='hello@ledger.fr', description='Python library to commu...
Add Python 3.6 to list trove classifiers
from setuptools import setup from sky_area import __version__ as version setup( name='skyarea', packages=['sky_area'], scripts=['bin/run_sky_area'], version=version, description='Compute credible regions on the sky from RA-DEC MCMC samples', author='Will M. Farr', author_email='will.farr@li...
from setuptools import setup from sky_area import __version__ as version setup( name='skyarea', packages=['sky_area'], scripts=['bin/run_sky_area'], version=version, description='Compute credible regions on the sky from RA-DEC MCMC samples', author='Will M. Farr', author_email='will.farr@li...
Use io.open with encoding='utf-8' and flake8 compliance
from setuptools import setup, find_packages long_description = ( open('README.rst').read() + '\n' + open('CHANGES.txt').read()) setup( name='more.forwarded', version='0.3.dev0', description="Forwarded header support for Morepath", long_description=long_description, author="Martijn Faas...
import io from setuptools import setup, find_packages long_description = '\n'.join(( io.open('README.rst', encoding='utf-8').read(), io.open('CHANGES.txt', encoding='utf-8').read() )) setup( name='more.forwarded', version='0.3.dev0', description="Forwarded header support for Morepath", long_de...
Revert "Add AuthorFactory and BookFactory."
import datetime from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from random import randint from .models import Author from .models import Book class UserFactory(DjangoModelFactory): class Meta: model = 'auth.User' django_get_or_create = ('u...
import datetime from django.template.defaultfilters import slugify from factory import DjangoModelFactory, lazy_attribute from random import randint class UserFactory(DjangoModelFactory): class Meta: model = 'auth.User' django_get_or_create = ('username',) first_name = 'John' last_name = ...
Remove any whitespace from values
from .tabulate import _text_type def pad(field, total, char=u" "): return field + (char * (total - len(field))) def expanded_table(rows, headers): header_len = max([len(x) for x in headers]) max_row_len = 0 results = [] sep = u"-[ RECORD {0} ]-------------------------\n" padded_headers = [pad...
from .tabulate import _text_type def pad(field, total, char=u" "): return field + (char * (total - len(field))) def expanded_table(rows, headers): header_len = max([len(x) for x in headers]) max_row_len = 0 results = [] sep = u"-[ RECORD {0} ]-------------------------\n" padded_headers = [pad...
Split training and validation data
from numpy import * from mnist import * from util import Counter # def loadData(): # images, labels = load_mnist('training') def defineFeatures(imageList, n): imageList = imageList[0:] featureList = [] for image in imageList: imgFeature = Counter() for i in range(len(image)): ...
from mnist import * from util import Counter def loadData(): """ loadData() pulls data from MNIST training set, splits it into training and validation data, then parses the data into features """ # load data from MNIST files images, labels = load_mnist('training') # find out where to split ...
Add testing function for blobs
import numpy as np import skimage.filter as filters def generate_linear_structure(size, with_noise=False): """Generate a basic linear structure, optionally with noise""" linear_structure = np.zeros(shape=(size,size)) linear_structure[:,size/2] = np.ones(size) if with_noise: linear_structure = ...
import numpy as np import skimage.filter as filters def generate_linear_structure(size, with_noise=False): """Generate a basic linear structure, optionally with noise""" linear_structure = np.zeros(shape=(size,size)) linear_structure[:,size/2] = np.ones(size) if with_noise: linear_structure = ...
Bump version number to 0.5
#!/usr/bin/env python from setuptools import setup setup(name='programmabletuple', version='0.4.0', description='Python metaclass for making named tuples with programmability', long_description=open('README.rst').read(), author='Tschijnmo TSCHAU', author_email='tschijnmotschau@gmail.com'...
#!/usr/bin/env python from setuptools import setup setup(name='programmabletuple', version='0.5.0', description='Python metaclass for making named tuples with programmability', long_description=open('README.rst').read(), author='Tschijnmo TSCHAU', author_email='tschijnmotschau@gmail.com'...
Update dependencies to ones compatible with Python 3.
from setuptools import setup, find_packages setup(name='googleanalytics', description='A wrapper for the Google Analytics API.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='stijn@debrouwere.org', url='https://github.com/debrouwere/google-analytics/', dow...
from setuptools import setup, find_packages setup(name='googleanalytics', description='A wrapper for the Google Analytics API.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='stijn@debrouwere.org', url='https://github.com/debrouwere/google-analytics/', dow...
Change package name from VCCS to vccs_auth.
#!/usr/bin/env python # from setuptools import setup, find_packages import sys, os from distutils import versionpredicate here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README')).read() version = '0.1dev' install_requires = [ 'pyhsm >= 1.0.3', 'ndnkdf >= 0.1', 'py-bcr...
#!/usr/bin/env python # from setuptools import setup, find_packages import sys, os from distutils import versionpredicate here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README')).read() version = '0.1dev' install_requires = [ 'pyhsm >= 1.0.3', 'ndnkdf >= 0.1', 'py-bcr...
Fix version dependency on nuit
from setuptools import find_packages, setup from shorty.version import __VERSION__ dependencies=[ 'django', 'django-autoconfig', 'django-nuit', ] test_dependencies=[ 'django-setuptest', ] setup( name='djshorty', version=__VERSION__, description='A Django URL shortening app', author='B...
from setuptools import find_packages, setup from shorty.version import __VERSION__ dependencies=[ 'django', 'django-autoconfig', 'django-nuit >= 1.0.0, < 2.0.0', ] test_dependencies=[ 'django-setuptest', ] setup( name='djshorty', version=__VERSION__, description='A Django URL shortening a...
Add long description for PyPI
#!/usr/bin/env python from os import environ from setuptools import Extension, find_packages, setup # Opt-in to building the C extensions for Python 2 by setting the # ENABLE_DJB_HASH_CEXT environment variable if environ.get('ENABLE_DJB_HASH_CEXT'): ext_modules = [ Extension('cdblib._djb_hash', sources=['...
#!/usr/bin/env python from os import environ from setuptools import Extension, find_packages, setup # Opt-in to building the C extensions for Python 2 by setting the # ENABLE_DJB_HASH_CEXT environment variable if environ.get('ENABLE_DJB_HASH_CEXT'): ext_modules = [ Extension('cdblib._djb_hash', sources=['...