commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
64c8fd3fa18dd6644a67cbd9e9aa5f20eb5e85a7 | var/spack/packages/mrnet/package.py | var/spack/packages/mrnet/package.py | from spack import *
class Mrnet(Package):
"""The MRNet Multi-Cast Reduction Network."""
homepage = "http://paradyn.org/mrnet"
url = "ftp://ftp.cs.wisc.edu/paradyn/mrnet/mrnet_4.0.0.tar.gz"
version('4.0.0', 'd00301c078cba57ef68613be32ceea2f')
version('4.1.0', '5a248298b395b329e2371bf25366115c'... | from spack import *
class Mrnet(Package):
"""The MRNet Multi-Cast Reduction Network."""
homepage = "http://paradyn.org/mrnet"
url = "ftp://ftp.cs.wisc.edu/paradyn/mrnet/mrnet_4.0.0.tar.gz"
version('4.0.0', 'd00301c078cba57ef68613be32ceea2f')
version('4.1.0', '5a248298b395b329e2371bf25366115c'... | Add krelloptions variant that is used to turn on a configuration option to build the thread safe lightweight libraries. | Add krelloptions variant that is used to turn on a configuration option to build the thread safe lightweight libraries.
| Python | lgpl-2.1 | EmreAtes/spack,krafczyk/spack,matthiasdiener/spack,matthiasdiener/spack,tmerrick1/spack,krafczyk/spack,LLNL/spack,matthiasdiener/spack,EmreAtes/spack,lgarren/spack,iulian787/spack,EmreAtes/spack,mfherbst/spack,krafczyk/spack,matthiasdiener/spack,skosukhin/spack,skosukhin/spack,mfherbst/spack,EmreAtes/spack,TheTimmy/spa... | ---
+++
@@ -8,12 +8,17 @@
version('4.0.0', 'd00301c078cba57ef68613be32ceea2f')
version('4.1.0', '5a248298b395b329e2371bf25366115c')
+ variant('krelloptions', default=False, description="Also build the MRNet LW threadsafe libraries")
parallel = False
depends_on("boost")
def install(se... |
42b6e51df4377e933e6ee24b12a5d83d42a655da | backend/setup.py | backend/setup.py | from setuptools import setup, find_packages
setup(
name="maguire",
version="0.1",
url='https://github.com/picsadotcom/maguire',
license='BSD',
author='Picsa',
author_email='admin@picsa.com',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django',
... | from setuptools import setup, find_packages
setup(
name="maguire",
version="0.1",
url='https://github.com/picsadotcom/maguire',
license='BSD',
author='Picsa',
author_email='admin@picsa.com',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django',
... | Add missing packages to backend | Add missing packages to backend
| Python | bsd-3-clause | picsadotcom/maguire | ---
+++
@@ -34,6 +34,8 @@
'boto3',
'django-storages',
'opbeat',
+ 'postmarker',
+ 'django-extensions',
],
classifiers=[
'Development Status :: 4 - Beta', |
51a505747d29198ea3df0a43c32b1018a40e6bc9 | monopoly/Bank/g.py | monopoly/Bank/g.py | import time
import json
import sqlite3
import socket
from collections import deque
class safesocket(socket.socket):
def __init__(self, *args):
self.floodQueue = deque([0] * 10, maxlen=10)
super().__init__(*args)
def send(self, message, *args):
try:
elapsed = int(time.time()... | import time
import json
import sqlite3
import socket
from collections import deque
class ratelimit:
def __init__(self, max, duration):
self.max = max
self.duration = duration # in milliseconds
self.rateQueue = deque([0] * max, maxlen=max)
def queue(self, job):
elapsed = int(tim... | Move ratelimit functionality into its own class | Move ratelimit functionality into its own class
| Python | mit | laneshetron/monopoly | ---
+++
@@ -4,22 +4,32 @@
import socket
from collections import deque
+class ratelimit:
+ def __init__(self, max, duration):
+ self.max = max
+ self.duration = duration # in milliseconds
+ self.rateQueue = deque([0] * max, maxlen=max)
+
+ def queue(self, job):
+ elapsed = int(tim... |
f52287bfc6a38b35daf9d880886cc159550a157c | mutant/__init__.py | mutant/__init__.py | import logging
__version__ = VERSION = (0, 0, 1)
logger = logging.getLogger('mutant')
import hacks | import logging
__version__ = VERSION = (0, 0, 1)
logger = logging.getLogger('mutant')
| Make sure to avoid loading hacks on mutant loading | Make sure to avoid loading hacks on mutant loading
| Python | mit | charettes/django-mutant | ---
+++
@@ -3,5 +3,3 @@
__version__ = VERSION = (0, 0, 1)
logger = logging.getLogger('mutant')
-
-import hacks |
4585ab22a4185122162b987cf8cc845a63ed5a05 | pyheufybot/modules/say.py | pyheufybot/modules/say.py | from module_interface import Module, ModuleType
class Say(Module):
def __init__(self):
self.trigger = "say"
self.moduleType = ModuleType.ACTIVE
self.messagesTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say the given line"
def execute(self, message, ... | from module_interface import Module, ModuleType
from message import IRCResponse, ResponseType
class Say(Module):
def __init__(self):
self.trigger = "say"
self.moduleType = ModuleType.ACTIVE
self.messagesTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say th... | Make it possible for modules to send a response | Make it possible for modules to send a response
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | ---
+++
@@ -1,4 +1,5 @@
from module_interface import Module, ModuleType
+from message import IRCResponse, ResponseType
class Say(Module):
def __init__(self):
@@ -8,4 +9,4 @@
self.helpText = "Usage: say <message> | Makes the bot say the given line"
def execute(self, message, serverInfo):
- ... |
0f4fd0d49ba06963b0b97e032fd2e6eedf8e597a | cloacina/extract_from_b64.py | cloacina/extract_from_b64.py | from bs4 import BeautifulSoup
import json
import re
def extract_from_b64(encoded_doc):
#doc = base64.urlsafe_b64decode(encoded_doc)
doc = encoded_doc.decode("base64")
doc = re.sub("</p><p>", " ", doc)
soup = BeautifulSoup(doc)
news_source = soup.find("meta", {"name":"sourceName"})['content']
ar... | from bs4 import BeautifulSoup
import json
import re
def extract_from_b64(encoded_doc):
#doc = base64.urlsafe_b64decode(encoded_doc)
doc = encoded_doc.decode("base64")
doc = re.sub("</p><p>", " ", doc)
doc = re.sub('<div class="BODY-2">', " ", doc)
soup = BeautifulSoup(doc)
news_source = soup.fi... | Fix missing space between lede and rest of article | Fix missing space between lede and rest of article
| Python | mit | ahalterman/cloacina | ---
+++
@@ -6,6 +6,7 @@
#doc = base64.urlsafe_b64decode(encoded_doc)
doc = encoded_doc.decode("base64")
doc = re.sub("</p><p>", " ", doc)
+ doc = re.sub('<div class="BODY-2">', " ", doc)
soup = BeautifulSoup(doc)
news_source = soup.find("meta", {"name":"sourceName"})['content']
articl... |
51d37f7ac6bebf9b1d4c6efd16a968b7410a7791 | rcnmf/tests/test_tsqr2.py | rcnmf/tests/test_tsqr2.py | import dask.array as da
from into import into
from dask.array.into import discover
from dask.dot import dot_graph
import tempfile
import rcnmf.tsqr
x = da.random.standard_normal(size=(100, 100), blockshape=(100, 50))
temp_file = tempfile.NamedTemporaryFile(suffix='.hdf5')
uri = temp_file.name + '::/X'
into(uri, x)
... | import dask.array as da
from into import into
from dask.array.into import discover
from dask.dot import dot_graph
import tempfile
import rcnmf.tsqr
x = da.random.standard_normal(size=(100, 100), blockshape=(100, 50))
temp_file = tempfile.NamedTemporaryFile(suffix='.hdf5')
uri = temp_file.name + '::/X'
into(uri, x)
... | Save mul at the end to force execution. | Save mul at the end to force execution.
| Python | bsd-2-clause | marianotepper/csnmf | ---
+++
@@ -29,4 +29,7 @@
dot_graph(q.dask, filename='q')
dot_graph(mul.dask, filename='mul')
+uri = temp_file.name + '::/mul'
+into(uri, mul)
+
temp_file.close() |
359040acc4b8c54db84e154b15cabfb23b4e18a6 | src/aiy/vision/models/utils.py | src/aiy/vision/models/utils.py | """Utility to load compute graphs from diffrent sources."""
import os
def load_compute_graph(name):
path = os.path.join('/opt/aiy/models', name)
with open(path, 'rb') as f:
return f.read()
| """Utility to load compute graphs from diffrent sources."""
import os
def load_compute_graph(name):
path = os.environ.get('VISION_BONNET_MODELS_PATH', '/opt/aiy/models')
with open(os.path.join(path, name), 'rb') as f:
return f.read()
| Use VISION_BONNET_MODELS_PATH env var for custom models path. | Use VISION_BONNET_MODELS_PATH env var for custom models path.
Change-Id: I687ca96e4cf768617fa45d50d68dadffde750b87
| Python | apache-2.0 | google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian | ---
+++
@@ -2,8 +2,8 @@
import os
+
def load_compute_graph(name):
- path = os.path.join('/opt/aiy/models', name)
- with open(path, 'rb') as f:
+ path = os.environ.get('VISION_BONNET_MODELS_PATH', '/opt/aiy/models')
+ with open(os.path.join(path, name), 'rb') as f:
return f.read()
- |
209c0d0201b76a0f2db7d8b507b2eaa2df03fcae | lib/stats.py | lib/stats.py | """
Statistics.
"""
from numpy import exp
from scipy.stats import rv_continuous
from scipy.special import gamma
class grw_gen(rv_continuous):
"""
Generalized Reverse Weibull distribution.
PDF:
a/gamma(g) * x^(a*g-1) * exp(-x^a)
for x,a,g >= 0
"""
def _pdf(self,x,a,g):
... | """
Statistics.
"""
import numpy as np
from scipy.stats import gengamma, norm
"""
Set default starting parameters for fitting a generalized gamma distribution.
These parameters are sensible for ATLAS v_n distributions.
Order: (a, c, loc, scale) where a,c are shape params.
"""
gengamma._fitstart = lambda data: (... | Replace custom GRW dist with scipy gengamma. Implement file fitting function. | Replace custom GRW dist with scipy gengamma. Implement file fitting function.
| Python | mit | jbernhard/ebe-analysis | ---
+++
@@ -3,27 +3,58 @@
"""
-from numpy import exp
-from scipy.stats import rv_continuous
-from scipy.special import gamma
+import numpy as np
+from scipy.stats import gengamma, norm
-class grw_gen(rv_continuous):
+"""
+Set default starting parameters for fitting a generalized gamma distribution.
+
+These ... |
313aafc11f76888614e2a0523e9e858e71765eaa | tests/test_wc.py | tests/test_wc.py | # Copyright (C) 2005-2007 Jelmer Vernooij <jelmer@samba.org>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# This p... | # Copyright (C) 2005-2007 Jelmer Vernooij <jelmer@samba.org>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# This p... | Add some more tests for wc module. | Add some more tests for wc module. | Python | lgpl-2.1 | jelmer/subvertpy,jelmer/subvertpy | ---
+++
@@ -16,9 +16,24 @@
"""Subversion ra library tests."""
from bzrlib.tests import TestCase
-import ra
+import wc
class VersionTest(TestCase):
def test_version_length(self):
- self.assertEquals(4, len(ra.version()))
+ self.assertEquals(4, len(wc.version()))
+class WorkingCopyTests(Test... |
e5f662d9cebe4133705eca74a300c325d432ad04 | anvil/components/cinder_client.py | anvil/components/cinder_client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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.or... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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.or... | Remove destruction of pips/test requires entries that don't exist. | Remove destruction of pips/test requires entries that don't exist.
| Python | apache-2.0 | stackforge/anvil,stackforge/anvil,mc2014/anvil,mc2014/anvil | ---
+++
@@ -26,15 +26,6 @@
def __init__(self, *args, **kargs):
comp.PythonInstallComponent.__init__(self, *args, **kargs)
- def _filter_pip_requires_line(self, line):
- if line.lower().find('keystoneclient') != -1:
- return None
- if line.lower().find('novaclient') != -1:
-... |
2a2c9dc43a7d096dd5601f51c0407c36433e73e1 | astropy/coordinates/__init__.py | astropy/coordinates/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains classes and functions for celestial coordinates
of astronomical objects. It also contains a framework for conversions
between coordinate systems.
"""
from __future__ import (absolute_import, division, print_function,
... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This subpackage contains classes and functions for celestial coordinates
of astronomical objects. It also contains a framework for conversions
between coordinate systems.
"""
from __future__ import (absolute_import, division, print_function,
... | Make coordinate 'frames' be imported | Make coordinate 'frames' be imported
| Python | bsd-3-clause | kelle/astropy,lpsinger/astropy,dhomeier/astropy,StuartLittlefair/astropy,DougBurke/astropy,astropy/astropy,stargaser/astropy,AustereCuriosity/astropy,lpsinger/astropy,stargaser/astropy,pllim/astropy,astropy/astropy,funbaker/astropy,joergdietrich/astropy,joergdietrich/astropy,kelle/astropy,aleksandr-bakanov/astropy,kell... | ---
+++
@@ -10,11 +10,11 @@
from .errors import *
from .angles import *
-from .coordsystems import *
+from .baseframe import *
from .distances import *
from .earth import *
from .transformations import *
-from .builtin_systems import *
+from .builtin_frames import *
from .name_resolve import *
from .matching... |
ab1028ccd73ea39d14f1eee57b91b303b31e2d63 | briefcase/__init__.py | briefcase/__init__.py | from __future__ import print_function, unicode_literals, absolute_import, division
__all__ = [
'__version__',
]
# Examples of valid version strings
# __version__ = '1.2.3.dev1' # Development release 1
# __version__ = '1.2.3a1' # Alpha Release 1
# __version__ = '1.2.3b1' # Beta Release 1
# __version__ = '... | from __future__ import print_function, unicode_literals, absolute_import, division
__all__ = [
'__version__',
]
# Examples of valid version strings
# __version__ = '1.2.3.dev1' # Development release 1
# __version__ = '1.2.3a1' # Alpha Release 1
# __version__ = '1.2.3b1' # Beta Release 1
# __version__ = '... | Bump version for v0.2.0 release. | Bump version for v0.2.0 release.
| Python | bsd-3-clause | pybee/briefcase | ---
+++
@@ -12,4 +12,4 @@
# __version__ = '1.2.3' # Final Release
# __version__ = '1.2.3.post1' # Post Release 1
-__version__ = '0.1.9'
+__version__ = '0.2.0' |
87d1b24d8ee806c5aa6cf73d83472b129b0f87fe | mitty/simulation/genome/sampledgenome.py | mitty/simulation/genome/sampledgenome.py | import pysam
from numpy.random import choice
import math
def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01):
vcf_pointer = pysam.VariantFile(filename=input_vcf)
new_header = vcf_pointer.header.copy()
if "GT" not in new_header.formats:
new_header.formats.add("GT", "1", "Str... | import pysam
from numpy.random import choice
def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01):
vcf_pointer = pysam.VariantFile(filename=input_vcf)
new_header = vcf_pointer.header.copy()
if "GT" not in new_header.formats:
new_header.formats.add("GT", "1", "String", "Conse... | Add random GT to a given vcf | Add random GT to a given vcf
| Python | apache-2.0 | sbg/Mitty,sbg/Mitty | ---
+++
@@ -1,6 +1,5 @@
import pysam
from numpy.random import choice
-import math
def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01):
@@ -10,7 +9,7 @@
new_header.formats.add("GT", "1", "String", "Consensus Genotype across all datasets with called genotype")
new_header... |
1f8b54d22cee5653254514bf07c1b4cb1eb147cb | _grabconfig.py | _grabconfig.py | #!/usr/bin/env python2
import os, shutil
files = ["/etc/crontab",
"/usr/local/bin/ssu", "/usr/local/bin/xyzzy",
"/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim",
"/home/dagon/.config/bless", "/home/... | #!/usr/bin/env python2
import os, shutil
files = ["/etc/crontab",
"/usr/local/bin/ssu", "/usr/local/bin/xyzzy",
"/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim",
"/home/dagon/.config/bless", "/home/... | Remove test item from config grabbing script | Remove test item from config grabbing script
| Python | unlicense | weloxux/dotfiles,weloxux/dotfiles | ---
+++
@@ -4,7 +4,7 @@
files = ["/etc/crontab",
"/usr/local/bin/ssu", "/usr/local/bin/xyzzy",
"/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim",
- "/home/dagon/.config/bless", "/home/dagon/.confi... |
dd1bcf71c6548f99e6bc133bf890c87440e13535 | taskflow/states.py | taskflow/states.py | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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
#
# ... | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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
#
# ... | Add a running state which can be used to know when a workflow is running. | Add a running state which can be used to know when a workflow is running.
| Python | apache-2.0 | openstack/taskflow,jessicalucci/TaskManagement,jimbobhickville/taskflow,openstack/taskflow,citrix-openstack-build/taskflow,jimbobhickville/taskflow,junneyang/taskflow,varunarya10/taskflow,pombredanne/taskflow-1,jessicalucci/TaskManagement,citrix-openstack-build/taskflow,junneyang/taskflow,pombredanne/taskflow-1,varunar... | ---
+++
@@ -32,6 +32,7 @@
STARTED = 'STARTED'
SUCCESS = SUCCESS
RESUMING = RESUMING
+RUNNING = 'RUNNING'
# Task states.
FAILURE = FAILURE |
cfeca089dd10a6853d2b969d2d248a0f7d506d1a | emission/net/usercache/formatters/android/motion_activity.py | emission/net/usercache/formatters/android/motion_activity.py | import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
... | import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
... | Handle the weird field names from the new version of the API | Handle the weird field names from the new version of the API
As part of the switch to cordova, we moved to a newer version of the google
play API. Unfortunately, this meant that the weird field names for the
confidence and type changed to a different set of weird field names. We should
really use a standard wrapper cl... | Python | bsd-3-clause | e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server,e-mission/e-mission-server,joshzarrabi/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,joshzarrabi/e-mission-server,joshzarrabi/e-mission-server,yw374cornell/e-mis... | ---
+++
@@ -16,8 +16,16 @@
formatted_entry.metadata = metadata
data = ad.AttrDict()
- data.type = ecwa.MotionTypes(entry.data.agb).value
- data.confidence = entry.data.agc
+ if 'agb' in entry.data:
+ data.type = ecwa.MotionTypes(entry.data.agb).value
+ else:
+ data.type = ecwa.Mo... |
5aa3dbf8f520f9ffaaed51ed397eb9f4c722882a | sample_app/__init__.py | sample_app/__init__.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # 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 t... | Fix pep8 order import issue | Fix pep8 order import issue
| Python | apache-2.0 | brantlk/python-sample-app | ---
+++
@@ -10,8 +10,8 @@
# License for the specific language governing permissions and limitations
# under the License.
+import ConfigParser
import json
-import ConfigParser
import falcon
|
4146551d191152ae486f079911f53086f3a60a07 | api/models.py | api/models.py | from django.db import models
from rest_framework import serializers
class Question(models.Model):
version = models.CharField(primary_key=True, max_length=8)
text = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Choice(mode... | from django.db import models
from rest_framework import serializers
class Question(models.Model):
version = models.CharField(primary_key=True, max_length=8)
text = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Choice(mode... | Rename version field in Choice to question | Rename version field in Choice to question
| Python | mit | holycattle/pysqueak-api,holycattle/pysqueak-api | ---
+++
@@ -9,7 +9,7 @@
class Choice(models.Model):
text = models.TextField()
- version = models.ForeignKey(Question, on_delete=models.CASCADE)
+ question = models.ForeignKey(Question, on_delete=models.CASCADE)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeFi... |
b9d54da73e5c4d859aa5ad8e9d8b96bb7527ae6d | api/models.py | api/models.py | from django.db import models
# Create your models here.
class User(models.Model):
uid = models.AutoField(primary_key=True)
uname = models.CharField(max_length=128)
session = models.CharField(max_length=35,unique=True)
class Box(models.Model):
bid = models.AutoField(primary_key=True)
level = models... | from django.db import models
# Create your models here.
class User(models.Model):
uid = models.AutoField(primary_key=True)
uname = models.CharField(max_length=128)
session = models.CharField(max_length=35,unique=True)
class Box(models.Model):
bid = models.AutoField(primary_key=True)
level = models... | Add position table and add field mid in box tables | Add position table and add field mid in box tables
| Python | apache-2.0 | g82411/s_square | ---
+++
@@ -9,6 +9,7 @@
class Box(models.Model):
bid = models.AutoField(primary_key=True)
level = models.IntegerField()
+ mid = models.ForeignKey("Monster")
owner = models.ForeignKey("User")
class Party(models.Model):
@@ -18,6 +19,13 @@
thi = models.ForeignKey("Box",related_name="third")
... |
c28de15fd8cade476fa8d7af904826dcea3c0f3e | python.py | python.py | # Python Notes
# Version 2.7
# for loop
for i in range(10):
print i
# check list elements of matching string
randList = ["a", "ab", "bc", "de", "abc"]
toFind = "a"
print [x for x in randList if toFind in x]
# read file
with open("filename.txt", "r") as fh:
data = fh.readline() # read line by line
# data ... | # Python Notes
# Version 2.7
# for loop
for i in range(10):
print i
# check list elements of matching string
randList = ["a", "ab", "bc", "de", "abc"]
toFind = "a"
print [x for x in randList if toFind in x]
# read file
with open("filename.txt", "r") as fh:
data = fh.readline() # read line by line
# data ... | Add Python note on simple unit test | Add Python note on simple unit test
| Python | cc0-1.0 | erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes | ---
+++
@@ -32,3 +32,10 @@
# clone instead of point to a set object
setA = set([1, 2, 3, 4])
setB = set(setA)
+
+# unit testing with unittest
+def fun(x):
+ return x + 1
+class TestAddingMethod(unittest.TestCase):
+ def test_three(self):
+ self.assertEqual(fun(3), 4) |
80cdc54dbe41c243c4620472aa8ba5c6ece40324 | etl_framework/DataTable.py | etl_framework/DataTable.py | class DataRow(dict):
"""object for holding row of data"""
def row_values(self, field_names, default_value=None):
"""returns row value of specified field_names"""
return tuple(self.get(field_name, default_value) for field_name in field_names)
class DataTable(object):
"""object for holding ... | class DataRow(dict):
"""object for holding row of data"""
def __init__(self, *args, **kwargs):
"""creates instance of DataRow"""
super(DataRow, self).__init__(*args, **kwargs)
self.target_table = None
def row_values(self, field_names, default_value=None):
"""returns row v... | Add target_table attribute to DataRow | Add target_table attribute to DataRow
| Python | mit | pantheon-systems/etl-framework | ---
+++
@@ -1,10 +1,27 @@
class DataRow(dict):
"""object for holding row of data"""
+
+ def __init__(self, *args, **kwargs):
+ """creates instance of DataRow"""
+
+ super(DataRow, self).__init__(*args, **kwargs)
+
+ self.target_table = None
def row_values(self, field_names, defaul... |
837b63918c29c1cd45a2a0daf8e6ff6e3b28bfb7 | merc/features/ts6/sid.py | merc/features/ts6/sid.py | from merc import errors
from merc import feature
from merc import message
from merc import util
class SidFeature(feature.Feature):
NAME = __name__
install = SidFeature.install
@SidFeature.register_server_command
class Sid(message.Command):
NAME = "SID"
MIN_ARITY = 4
def __init__(self, server_name, hopcou... | from merc import errors
from merc import feature
from merc import message
from merc import util
class SidFeature(feature.Feature):
NAME = __name__
install = SidFeature.install
@SidFeature.register_server_command
class Sid(message.Command):
NAME = "SID"
MIN_ARITY = 4
def __init__(self, server_name, hopcou... | Fix typo breaking the TS6 feature. | Fix typo breaking the TS6 feature.
| Python | mit | merc-devel/merc | ---
+++
@@ -27,6 +27,7 @@
def handle_for(self, app, server, prefix):
# TODO: handle me!
+ pass
@SidFeature.hook("network.burst.sid") |
cad48e91776ded810b23c336380797c88dd456c0 | services/netflix.py | services/netflix.py | import urlparse
import foauth.providers
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_QUERY
class Netflix(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'https://www.netflix.com/'
docs_url = 'http://developer.netflix.com/docs'
# URLs to interact with the API
requ... | import urlparse
import foauth.providers
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_QUERY
class Netflix(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'https://www.netflix.com/'
docs_url = 'http://developer.netflix.com/docs'
# URLs to interact with the API
requ... | Fix Netflix in light of the new scope selection system | Fix Netflix in light of the new scope selection system
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org | ---
+++
@@ -22,8 +22,8 @@
https = False
signature_type = SIGNATURE_TYPE_QUERY
- def get_authorize_params(self, redirect_uri):
- params = super(Netflix, self).get_authorize_params(redirect_uri)
+ def get_authorize_params(self, *args, **kwargs):
+ params = super(Netflix, self).get_author... |
6eae9369cc122b23577715951d6b0f59991b0f65 | saleor/csv/__init__.py | saleor/csv/__init__.py | class ExportEvents:
"""The different csv events types."""
EXPORT_PENDING = "export_pending"
EXPORT_SUCCESS = "export_success"
EXPORT_FAILED = "export_failed"
EXPORT_DELETED = "export_deleted"
EXPORTED_FILE_SENT = "exported_file_sent"
CHOICES = [
(EXPORT_PENDING, "Data export was st... | class ExportEvents:
"""The different csv events types."""
EXPORT_PENDING = "export_pending"
EXPORT_SUCCESS = "export_success"
EXPORT_FAILED = "export_failed"
EXPORT_DELETED = "export_deleted"
EXPORTED_FILE_SENT = "exported_file_sent"
CHOICES = [
(EXPORT_PENDING, "Data export was st... | Update choices descriptions in FileTypes | Update choices descriptions in FileTypes
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | ---
+++
@@ -24,6 +24,6 @@
XLSX = "xlsx"
CHOICES = [
- (CSV, "Plain csv file."),
- (XLSX, "Excel .xlsx file."),
+ (CSV, "Plain CSV file."),
+ (XLSX, "Excel XLSX file."),
] |
b6f04f32556fc8251566212c56159dcfff7bf596 | pi_approach/Distance_Pi/distance.py | pi_approach/Distance_Pi/distance.py | # Lidar Project Distance Subsystem
import serial
import socket
import time
import sys
sys.path.insert(0, "/home/pi/lidar/pi_approach/Libraries")
import serverxclient as cli
arduino_dist = serial.Serial('/dev/ttyUSB0',9600)
client = cli.Client()
class distance_controller(object):
"""An all-powerful distance-finding ... | # Lidar Project Distance Subsystem
import serial
import socket
import time
import sys
sys.path.insert(0, "/home/pi/lidar/pi_approach/Libraries")
import serverxclient as cli
arduino_dist = serial.Serial('/dev/ttyUSB0',9600)
client = cli.Client()
class distance_controller(object):
"""An all-powerful distance-finding ... | Add unexpected character bug fix | Add unexpected character bug fix
| Python | mit | the-raspberry-pi-guy/lidar | ---
+++
@@ -43,6 +43,8 @@
client.send_data(result)
except:
print "Unexpected character"
+ client.send_data("0")
+
def main(self):
self.setup_handshake() |
069e98f036c77f635a955ea2c48580709089e702 | src/conference_scheduler/resources.py | src/conference_scheduler/resources.py | from typing import NamedTuple, Sequence, Dict, Iterable, List
from datetime import datetime
class Slot(NamedTuple):
venue: str
starts_at: datetime
duration: int
capacity: int
session: str
class Event(NamedTuple):
name: str
duration: int
demand: int
tags: List[str] = []
unavai... | from typing import NamedTuple, Sequence, Dict, Iterable, List
from datetime import datetime
class Slot(NamedTuple):
venue: str
starts_at: datetime
duration: int
capacity: int
session: str
class BaseEvent(NamedTuple):
name: str
duration: int
demand: int
tags: List[str]
unavail... | Set default values for `tags` and `availability` | Set default values for `tags` and `availability`
| Python | mit | PyconUK/ConferenceScheduler | ---
+++
@@ -10,12 +10,26 @@
session: str
-class Event(NamedTuple):
+class BaseEvent(NamedTuple):
name: str
duration: int
demand: int
- tags: List[str] = []
- unavailability: List = []
+ tags: List[str]
+ unavailability: List
+
+
+class Event(BaseEvent):
+
+ __slots__ = ()
+
+ ... |
1112f3602c147f469c21181c5c61d480b3f2ed75 | opps/api/views/generic/list.py | opps/api/views/generic/list.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from rest_framework.generics import ListAPIView as RestListAPIView
from opps.views.generic.base import View
from opps.containers.models import ContainerBox
class ListView(View, Re... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from rest_framework.generics import ListAPIView as RestListAPIView
from opps.views.generic.base import View
from opps.containers.models import ContainerBox
class ListView(View, Re... | Fix not exis channel_long_slug on API access | Fix not exis channel_long_slug on API access
| Python | mit | YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,opps/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps | ---
+++
@@ -28,10 +28,13 @@
queryset = super(ListView, self).get_queryset()
filters = {}
filters['site_domain'] = self.site.domain
- filters['channel_long_slug__in'] = self.channel_long_slug
+ try:
+ if queryset.model._meta.get_field_by_name('channel_long_slug'):
+ ... |
6b8f66ed0bcaa62b3afd9fea7d749916d768847d | scripts/midnightRun.py | scripts/midnightRun.py | from recover.models import *
from recover.patient_data import *
from datetime import date
def midnightRun():
physicians = User.objects()
for physician in physicians:
patients = physician.patients
for patient in patients:
data = PatientData(patient)
last_synced = patient.... | from recover.models import *
from recover.patient_data import *
import datetime
def midnightRun():
physicians = User.objects()
for physician in physicians:
patients = physician.patients
for patient in patients:
data = PatientData(patient)
last_synced = patient.date_last... | Update 'date_last_synced' field on each patient after midnight fetching | Update 'date_last_synced' field on each patient after midnight fetching
| Python | mit | SLU-Capstone/Recover,SLU-Capstone/Recover,SLU-Capstone/Recover | ---
+++
@@ -1,6 +1,7 @@
from recover.models import *
from recover.patient_data import *
-from datetime import date
+import datetime
+
def midnightRun():
physicians = User.objects()
@@ -12,3 +13,4 @@
last_synced = last_synced[0:10]
data.get_heart_rate_data_for_date_range(last_synced... |
f5bb9e5f388c4ac222da2318638266fdfbe925f0 | beam/vendor.py | beam/vendor.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import six
@six.python_2_unicode_compatible
class Vendor(object):
"""
Represents a VPS provider.
"""
def __init__(self, name, endpoint):
"""
Initialise a new vendor object.
:param name: The name of the vendor, e... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import six
@six.python_2_unicode_compatible
class Vendor(object):
"""
Represents a VPS provider.
"""
def __init__(self, name, endpoint):
"""
Initialise a new vendor object.
:param name: The name of the vendor, e... | Add documentation to Vendor properties | Add documentation to Vendor properties
| Python | mit | gebn/beam,gebn/beam | ---
+++
@@ -19,7 +19,9 @@
protocol.
"""
self.name = name
+ """ The vendor's name, e.g. "RamNode". """
self.endpoint = endpoint
+ """ The hostname of the SolusVM control panel, with protocol. """
def __hash__(self):
""" |
3793ef9014b72d5f48e7df0e91521cfdb4b06134 | pycroft/lib/infrastructure.py | pycroft/lib/infrastructure.py | from pycroft.lib.logging import log_room_event, log_event
from pycroft.model.host import SwitchPort, Host, Switch
from pycroft.model.port import PatchPort
from pycroft.model.session import with_transaction, session
from pycroft.model.user import User
@with_transaction
def edit_port_relation(switchport, patchport, swi... | Add lib functions to add/edit/delete port relations | Add lib functions to add/edit/delete port relations
| Python | apache-2.0 | agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft | ---
+++
@@ -0,0 +1,43 @@
+from pycroft.lib.logging import log_room_event, log_event
+from pycroft.model.host import SwitchPort, Host, Switch
+from pycroft.model.port import PatchPort
+from pycroft.model.session import with_transaction, session
+from pycroft.model.user import User
+
+
+@with_transaction
+def edit_port... | |
c4b8cce856777b08a8ffd5a85567389102aea2c2 | qregexeditor/api/quick_ref.py | qregexeditor/api/quick_ref.py | """
Contains the quick reference widget
"""
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
| """
Contains the quick reference widget
"""
import re
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)... | Allow the user to zoom in/out the quick reference text using Ctrl+Mouse Wheel | Allow the user to zoom in/out the quick reference text using Ctrl+Mouse Wheel
See issue #1
| Python | mit | ColinDuquesnoy/QRegexEditor | ---
+++
@@ -1,6 +1,7 @@
"""
Contains the quick reference widget
"""
+import re
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui
@@ -9,3 +10,14 @@
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
+ self._fix_defa... |
d16988174f5570334b6b3986dbd0b35148566a62 | opps/flatpages/models.py | opps/flatpages/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from googl.short import GooglUrlShort
from opps.core.models import Publishable, BaseConfig
class FlatPage(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
headline =... | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from googl.short import GooglUrlShort
from opps.core.models import Publishable, BaseConfig
class FlatPage(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
headline =... | Add field short_url on flatpages model | Add field short_url on flatpages model
| Python | mit | opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps | ---
+++
@@ -16,6 +16,10 @@
max_length=150,
unique=True,
)
+ short_url = models.URLField(
+ _("Short URL"),
+ null=True, blank=False,
+ )
show_in_menu = models.BooleanField(_(u"Show in menu?"), default=False)
main_image = models.ForeignKey(
'images.Image',
... |
00bb631437fdf45c7a067da43aa042f8b1f6ef8e | osf_models/models/tag.py | osf_models/models/tag.py | from django.db import models
from .base import BaseModel
class Tag(BaseModel):
_id = models.CharField(max_length=1024)
lower = models.CharField(max_length=1024)
system = models.BooleanField(default=False)
| from django.db import models
from .base import BaseModel
class Tag(BaseModel):
_id = models.CharField(max_length=1024)
lower = models.CharField(max_length=1024)
system = models.BooleanField(default=False)
class Meta:
unique_together = ('_id', 'system')
| Add unique together on _id and system | Add unique together on _id and system
| Python | apache-2.0 | Nesiehr/osf.io,adlius/osf.io,erinspace/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,crcresearch/osf.io,caneruguz/osf.io,caseyrollins/osf.io,laurenrevere/osf.io,Nesiehr/osf.io,baylee-d/osf.io,leb2dg/osf.io,acshi/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,chrisseto/osf.io,chennan47/osf.io,... | ---
+++
@@ -7,3 +7,6 @@
_id = models.CharField(max_length=1024)
lower = models.CharField(max_length=1024)
system = models.BooleanField(default=False)
+
+ class Meta:
+ unique_together = ('_id', 'system') |
e203f76177de390fb02a2770499679c099c4f87c | cacheops/__init__.py | cacheops/__init__.py | VERSION = (3, 0, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
from .utils import ... | VERSION = (3, 0, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsCon... | Remove debug_cache_key from entry point | Remove debug_cache_key from entry point
| Python | bsd-3-clause | Suor/django-cacheops,LPgenerator/django-cacheops | ---
+++
@@ -9,7 +9,6 @@
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
-from .utils import debug_cache_key # noqa
class CacheopsConfig(AppConfig): |
a2ee2f617ae561ce5b905a6c3960371ce6f157e3 | tests/test_open.py | tests/test_open.py | #!/usr/bin/env python
import unittest
import yv_suggest.open as yvs
import inspect
class WebbrowserMock(object):
'''mock the builtin webbrowser module'''
def open(self, url):
'''mock the webbrowser.open() function'''
self.url = url
class OpenTestCase(unittest.TestCase):
'''test the handli... | #!/usr/bin/env python
import unittest
import yv_suggest.open as yvs
import inspect
class WebbrowserMock(object):
'''mock the builtin webbrowser module'''
def open(self, url):
'''mock the webbrowser.open() function'''
self.url = url
class OpenTestCase(unittest.TestCase):
'''test the handli... | Fix 'open reference' test case | Fix 'open reference' test case
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest | ---
+++
@@ -26,7 +26,7 @@
def test_url_open(self):
'''should attempt to open URL using webbrowser module'''
- mock = self.WebbrowserMock()
+ mock = WebbrowserMock()
yvs.webbrowser = mock
yvs.main('nlt/jhn.3.17')
self.assertEqual(mock.url, 'https://www.bible.com... |
c2d681f0df11d2111fe1ade63a0c045f9c9ebad7 | aws_profile.py | aws_profile.py | #!/usr/bin/env python
# Reads a profile from ~/.aws/config and calls the command with
# AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY set correctly.
import ConfigParser
import os
import subprocess
import sys
c = ConfigParser.SafeConfigParser()
c.read(os.path.expanduser('~/.aws/config'))
section = sys.argv[1]
cmd = sys.... | #!/usr/bin/env python
# Reads a profile from ~/.aws/config and calls the command with
# AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY set correctly.
import ConfigParser
import os
import subprocess
import sys
c = ConfigParser.SafeConfigParser()
c.read(os.path.expanduser('~/.aws/credentials'))
section = sys.argv[1]
cmd =... | Fix profile script to correctly use the credentials file | Fix profile script to correctly use the credentials file
| Python | mit | mivok/tools,mivok/tools,mivok/tools,mivok/tools | ---
+++
@@ -7,13 +7,13 @@
import sys
c = ConfigParser.SafeConfigParser()
-c.read(os.path.expanduser('~/.aws/config'))
+c.read(os.path.expanduser('~/.aws/credentials'))
section = sys.argv[1]
cmd = sys.argv[2:]
-if section != 'default':
- section = 'profile %s' % section
+#if section != 'default':
+# se... |
fb21faaec025a0a6ca2d98c8b2381902f3b1444a | pybug/align/lucaskanade/__init__.py | pybug/align/lucaskanade/__init__.py | import appearance
import image
from residual import (LSIntensity,
ECC,
GradientImages,
GradientCorrelation)
| import appearance
import image
from residual import (LSIntensity,
ECC,
GaborFourier,
GradientImages,
GradientCorrelation)
| Add GaborFourier to default import | Add GaborFourier to default import
| Python | bsd-3-clause | menpo/menpo,yuxiang-zhou/menpo,grigorisg9gr/menpo,mozata/menpo,mozata/menpo,mozata/menpo,mozata/menpo,grigorisg9gr/menpo,menpo/menpo,menpo/menpo,jabooth/menpo-archive,jabooth/menpo-archive,jabooth/menpo-archive,yuxiang-zhou/menpo,grigorisg9gr/menpo,patricksnape/menpo,yuxiang-zhou/menpo,jabooth/menpo-archive,patricksnap... | ---
+++
@@ -4,5 +4,6 @@
from residual import (LSIntensity,
ECC,
+ GaborFourier,
GradientImages,
GradientCorrelation) |
e275fb1406f0a8e70bb3a9d4a50a82400f7e2c29 | signac/gui/__init__.py | signac/gui/__init__.py | """Graphical User Interface (GUI) for configuration and database inspection.
The GUI is a leight-weight interface which makes the configuration
of the signac framework and data inspection more straight-forward."""
import warnings
try:
import PySide # noqa
except ImportError:
warnings.warn("Failed to import Py... | """Graphical User Interface (GUI) for configuration and database inspection.
The GUI is a leight-weight interface which makes the configuration
of the signac framework and data inspection more straight-forward."""
import warnings
try:
import PySide # noqa
import pymongo # noqa
except ImportError as error:
... | Remove hard dependency for pymongo. | Remove hard dependency for pymongo.
Caused by pulling the gui package into the signac namespace.
Fixes issue #24.
| Python | bsd-3-clause | csadorf/signac,csadorf/signac | ---
+++
@@ -5,16 +5,16 @@
import warnings
try:
import PySide # noqa
-except ImportError:
- warnings.warn("Failed to import PySide. "
- "gui will not be available.", ImportWarning)
+ import pymongo # noqa
+except ImportError as error:
+ msg = "{}. The signac gui is not available.".fo... |
4da5ebbad11a5c5cdbea307668657d843d6d1005 | cotracker/checkouts/middleware.py | cotracker/checkouts/middleware.py | """Checkouts application middleware"""
import logging
logger = logging.getLogger('analytics')
class Analytics():
"""Tracks request details useful for analysis of usage patterns.
To ensure that the name of the logged in user can be accessed, this
middleware should come after Django's built-in Authent... | """Checkouts application middleware"""
import logging
import time
logger = logging.getLogger('analytics')
class Analytics():
"""Tracks request details useful for analysis of usage patterns.
To ensure that the name of the logged in user can be accessed, this
middleware should come after Django's buil... | Enhance analytics with timing and status code info | Enhance analytics with timing and status code info
| Python | mit | eallrich/checkniner,eallrich/checkniner,eallrich/checkniner | ---
+++
@@ -1,6 +1,7 @@
"""Checkouts application middleware"""
import logging
+import time
logger = logging.getLogger('analytics')
@@ -12,8 +13,8 @@
in the project settings.
"""
- def process_request(self, request):
- """Organizes info from each request and saves it to a log."""
+ ... |
f566e0e36269ea2cd1e82c6af712097917effd4a | dlrn/migrations/versions/2d503b5034b7_rename_artifacts.py | dlrn/migrations/versions/2d503b5034b7_rename_artifacts.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # 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 t... | Fix alembic migration for rpms->artifacts rename | Fix alembic migration for rpms->artifacts rename
The migration does not work on MySQL-based engines, because it
requires setting the existing_type parameter [1]. It worked fine
on SQLite, though.
[1] - https://alembic.sqlalchemy.org/en/latest/ops.html#alembic.operations.Operations.alter_column
Change-Id: If0cc05af84... | Python | apache-2.0 | openstack-packages/delorean,openstack-packages/delorean,openstack-packages/DLRN,openstack-packages/DLRN | ---
+++
@@ -19,6 +19,7 @@
"""
from alembic import op
+import sqlalchemy as sa
# revision identifiers, used by Alembic.
@@ -30,9 +31,11 @@
def upgrade():
with op.batch_alter_table("commits") as batch_op:
- batch_op.alter_column('rpms', new_column_name='artifacts')
+ batch_op.alter_column... |
51b7fba10a85136877c8a918d4d24d5a431a2a7f | mzalendo/run_all_tests_with_coverage.py | mzalendo/run_all_tests_with_coverage.py | #!/bin/bash
find . -name '*.pyc' -delete
coverage erase
OMIT="$(python -c 'import sys; print sys.prefix')"
coverage run --omit=$OMIT ./manage.py test \
core \
feedback \
hansard \
helpers \
images \
info \
scorecards \
search ... | #!/bin/bash
find . -name '*.pyc' -delete
coverage erase
OMIT="$(python -c 'import sys; print sys.prefix')/*"
coverage run --omit=$OMIT ./manage.py test \
core \
feedback \
hansard \
helpers \
images \
info \
scorecards \
search ... | Correct the --omit parameter for coverage.py | Correct the --omit parameter for coverage.py
Despite what some things on the web suggest, you seem to need
to have a wildcard at the end of a path in the --omit list.
| Python | agpl-3.0 | hzj123/56th,patricmutwiri/pombola,ken-muturi/pombola,patricmutwiri/pombola,mysociety/pombola,mysociety/pombola,ken-muturi/pombola,ken-muturi/pombola,patricmutwiri/pombola,geoffkilpin/pombola,ken-muturi/pombola,hzj123/56th,patricmutwiri/pombola,ken-muturi/pombola,mysociety/pombola,mysociety/pombola,hzj123/56th,mysociety... | ---
+++
@@ -4,7 +4,7 @@
coverage erase
-OMIT="$(python -c 'import sys; print sys.prefix')"
+OMIT="$(python -c 'import sys; print sys.prefix')/*"
coverage run --omit=$OMIT ./manage.py test \
core \ |
fbd37fe6404bfc1e7cec4b2137c19e7323cdde02 | street_score/project/urls.py | street_score/project/urls.py | from django.conf.urls import patterns, include, url
from django.views import generic as views
from . import resources
# Uncomment the next two lines to enable the admin:
from django.contrib.gis import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'project.views.home', name='ho... | from django.conf.urls import patterns, include, url
from django.views import generic as views
from . import resources
# Uncomment the next two lines to enable the admin:
from django.contrib.gis import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'project.views.home', name='ho... | Correct the url for the rating instance resource | Correct the url for the rating instance resource
| Python | mit | openplans/streetscore,openplans/streetscore,openplans/streetscore | ---
+++
@@ -24,7 +24,7 @@
url(r'^ratings/$',
resources.RatingListView.as_view(),
name='rating_list'),
- url(r'^ratings/(P<id>\d+)$',
+ url(r'^ratings/(?P<id>\d+)$',
resources.RatingInstanceView.as_view(),
name='rating_instance'),
|
141e8303fe8f1d6fe554770d7480ef50797d4735 | books/forms.py | books/forms.py | from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from books.models import BookType
from egielda import settings
class BookForm(ModelForm):
# Different max_length than in model (to allow dividers in ISBN number)
isbn = forms.CharField(max_leng... | from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from books.models import BookType
from egielda import settings
class BookForm(ModelForm):
# Different max_length than in model (to allow dashes in ISBN)
isbn = forms.CharField(max_length=20, la... | Improve ISBN field in Book Type form | Improve ISBN field in Book Type form
- Add required, pattern (to allow only numbers and dashes in HTML5-supporting browsers) and title properties
- Remove a bit of redundant code
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda | ---
+++
@@ -7,21 +7,21 @@
class BookForm(ModelForm):
- # Different max_length than in model (to allow dividers in ISBN number)
- isbn = forms.CharField(max_length=20, label=_("ISBN"))
+ # Different max_length than in model (to allow dashes in ISBN)
+ isbn = forms.CharField(max_length=20, label=_("ISB... |
779c01d3932c02f2b9c45e300c7efb54f81749e9 | tests/rietveld/test_event_handler.py | tests/rietveld/test_event_handler.py | from __future__ import absolute_import, print_function
import unittest
from qtpy.QtWidgets import QApplication
from addie.rietveld import event_handler
class RietveldEventHandlerTests(unittest.TestCase):
def setUp(self):
self.main_window = QApplication([])
'''
def tearDown(self):
self.mai... | from __future__ import absolute_import, print_function
import unittest
from qtpy.QtWidgets import QApplication
from addie.rietveld import event_handler
class RietveldEventHandlerTests(unittest.TestCase):
def setUp(self):
self.main_window = QApplication([])
'''
def tearDown(self):
self.mai... | Add exception to test title | Add exception to test title
| Python | mit | neutrons/FastGR,neutrons/FastGR,neutrons/FastGR | ---
+++
@@ -13,7 +13,7 @@
self.main_window.quit()
'''
- def test_evt_change_gss_mode(self):
+ def test_evt_change_gss_mode_exception(self):
"""Test we can extract a bank id from bank workspace name"""
f = event_handler.evt_change_gss_mode
self.assertRaises(NotImplement... |
8afb48e23b91efa3432ffad568002a46384eb021 | fantasyland.py | fantasyland.py | import numpy as np
import random
import game as g
import hand_optimizer
game = g.PineappleGame1()
NUM_ITERS = 1000
utilities = []
for iter_num in xrange(NUM_ITERS):
print "{:5} / {:5}".format(iter_num, NUM_ITERS), '\r',
draw = random.sample(game.cards, 14)
utilities += [hand_optimizer.optimize_hand([[], [], [... | import argparse
import numpy as np
import random
import game as g
import hand_optimizer
parser = argparse.ArgumentParser(description='Simulate fantasyland like situations.')
parser.add_argument('--num-games', type=int, default=1000,
help='number of games to play')
parser.add_argument('--num-cards'... | Add command line interface to vary num-games and num-cards. | Add command line interface to vary num-games and num-cards.
| Python | mit | session-id/pineapple-ai | ---
+++
@@ -1,19 +1,26 @@
+import argparse
import numpy as np
import random
import game as g
import hand_optimizer
+parser = argparse.ArgumentParser(description='Simulate fantasyland like situations.')
+parser.add_argument('--num-games', type=int, default=1000,
+ help='number of games to pl... |
5f67934da00ff36044e9fd620b690e36968570c0 | salt/output/overstatestage.py | salt/output/overstatestage.py | '''
Display clean output of an overstate stage
'''
#[{'group2': {'match': ['fedora17-2', 'fedora17-3'],
# 'require': ['group1'],
# 'sls': ['nginx', 'edit']}
# }
# ]
# Import Salt libs
import salt.utils
def output(data):
'''
Format the data for printing stage ... | '''
Display clean output of an overstate stage
'''
#[{'group2': {'match': ['fedora17-2', 'fedora17-3'],
# 'require': ['group1'],
# 'sls': ['nginx', 'edit']}
# }
# ]
# Import Salt libs
import salt.utils
def output(data):
'''
Format the data for printing stage ... | Make stage outputter a little cleaner | Make stage outputter a little cleaner
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -21,9 +21,12 @@
ostr = ''
for comp in data:
for name, stage in comp.items():
- ostr += '{0}{1}:{2}\n'.format(colors['LIGHT_BLUE'], name, colors['ENDC'])
+ ostr += '{0}{1}: {2}\n'.format(
+ colors['LIGHT_BLUE'],
+ name,
+ ... |
4b8de0203d2eec87c2d05c3521df8af3365f73a4 | IPython/testing/nose_assert_methods.py | IPython/testing/nose_assert_methods.py | """Add some assert methods to nose.tools. These were added in Python 2.7/3.1, so
once we stop testing on Python 2.6, this file can be removed.
"""
import nose.tools as nt
def assert_in(item, collection):
assert item in collection, '%r not in %r' % (item, collection)
if not hasattr(nt, 'assert_in'):
nt.assert... | """Add some assert methods to nose.tools. These were added in Python 2.7/3.1, so
once we stop testing on Python 2.6, this file can be removed.
"""
import nose.tools as nt
def assert_in(item, collection):
assert item in collection, '%r not in %r' % (item, collection)
if not hasattr(nt, 'assert_in'):
nt.assert... | Add assert_not_in method for Python2.6 | Add assert_not_in method for Python2.6
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -9,3 +9,9 @@
if not hasattr(nt, 'assert_in'):
nt.assert_in = assert_in
+
+def assert_not_in(item, collection):
+ assert item not in collection, '%r in %r' % (item, collection)
+
+if not hasattr(nt, 'assert_not_in'):
+ nt.assert_not_in = assert_not_in |
6ad4a0d511f874ccb94a6c8b02f0d4f5e99947ee | bigbuild/management/commands/cachepages.py | bigbuild/management/commands/cachepages.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
from datetime import datetime
from bigbuild.models import PageList
from bigbuild import get_archive_directory
from django.core.management.base import BaseCommand
def serializer(obj):
"""
JSON serializer for objects not serializable by default... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import json
from datetime import datetime
from bigbuild.models import PageList
from bigbuild import get_archive_directory
from django.core.management.base import BaseCommand
def serializer(obj):
"""
JSON serializer for objects not serializable ... | Write out page cache as unicode utf8 | Write out page cache as unicode utf8
| Python | mit | datadesk/django-bigbuild,datadesk/django-bigbuild,datadesk/django-bigbuild | ---
+++
@@ -1,5 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+import io
import os
import json
from datetime import datetime
@@ -33,9 +34,10 @@
page_list = PageList()
# Save the archived pages out to a new cache
- with open(archive_cache_path, 'w') as f:
- json.dump(... |
751819ea58389eaa1baf3de243459be4948b15f1 | rpc_client/rpc_client_tests.py | rpc_client/rpc_client_tests.py | import unittest
class Test(unittest.TestCase):
def setUp(self):
self.seq = range(10)
#def test_shuffle(self):
# # make sure the shuffled sequence does not lose any elements
# random.shuffle(self.seq)
# self.seq.sort()
# self.assertEqual(self.seq, range(10))
#def test_... | import unittest, xmlrpclib, couchdb
from ConfigParser import SafeConfigParser
class Test(unittest.TestCase):
def setUp(self):
self.cfg = SafeConfigParser()
self.cfg.read(('rpc_client.ini', '../stats/basicStats.ini'))
host = self.cfg.get('connection', 'server')
port = self.cfg.getin... | Make some simple unit test for RPC server. | Make some simple unit test for RPC server.
| Python | apache-2.0 | anthony-kolesov/kts46,anthony-kolesov/kts46,anthony-kolesov/kts46,anthony-kolesov/kts46 | ---
+++
@@ -1,24 +1,46 @@
-import unittest
+import unittest, xmlrpclib, couchdb
+from ConfigParser import SafeConfigParser
class Test(unittest.TestCase):
def setUp(self):
- self.seq = range(10)
+ self.cfg = SafeConfigParser()
+ self.cfg.read(('rpc_client.ini', '../stats/basicStats.ini')... |
73609d84871973449e2e4520fdeac027131d0e6d | tests/list_pubs.py | tests/list_pubs.py | import azurerm
import json
# Load Azure app defaults
try:
with open('azurermconfig.json') as configFile:
configData = json.load(configFile)
except FileNotFoundError:
print("Error: Expecting vmssConfig.json in current folder")
sys.exit()
tenant_id = configData['tenantId']
app_id = configData['app... | import azurerm
import json
# Load Azure app defaults
try:
with open('azurermconfig.json') as configFile:
configData = json.load(configFile)
except FileNotFoundError:
print("Error: Expecting vmssConfig.json in current folder")
sys.exit()
tenant_id = configData['tenantId']
app_id = configData['app... | Fix ubuntu version in test prog | Fix ubuntu version in test prog
| Python | mit | gbowerman/azurerm | ---
+++
@@ -30,7 +30,7 @@
print(sku['name'])
'''
#versions = azurerm.list_sku_versions(access_token, subscription_id, 'eastus', 'MicrosoftWindowsServer', 'WindowsServer', '2012-R2-Datacenter')
-versions = azurerm.list_sku_versions(access_token, subscription_id, 'eastus', 'Canonical', 'UbuntuServer', '15.04')
+... |
377d0634a77c63ce9e3d937f31bdd82ebe695cbb | ev3dev/auto.py | ev3dev/auto.py | import platform
# -----------------------------------------------------------------------------
# Guess platform we are running on
def current_platform():
machine = platform.machine()
if machine == 'armv5tejl':
return 'ev3'
elif machine == 'armv6l':
return 'brickpi'
else:
return... | import platform
import sys
# -----------------------------------------------------------------------------
if sys.version_info < (3,4):
raise SystemError('Must be using Python 3.4 or higher')
# -----------------------------------------------------------------------------
# Guess platform we are running on
def c... | Enforce the use of Python 3.4 or higher | Enforce the use of Python 3.4 or higher
| Python | mit | rhempel/ev3dev-lang-python,dwalton76/ev3dev-lang-python,dwalton76/ev3dev-lang-python | ---
+++
@@ -1,7 +1,14 @@
import platform
+import sys
+
+# -----------------------------------------------------------------------------
+
+if sys.version_info < (3,4):
+ raise SystemError('Must be using Python 3.4 or higher')
# -----------------------------------------------------------------------------
# Gu... |
122507fb2c68a0d5734082bdc67ce7cf91293870 | python/sierrapy/fastareader.py | python/sierrapy/fastareader.py | # -*- coding: utf-8 -*-
def load(fp):
sequences = []
header = None
curseq = ''
for line in fp:
if line.startswith('>'):
if header and curseq:
sequences.append({
'header': header,
'sequence': curseq
})
... | # -*- coding: utf-8 -*-
def load(fp):
sequences = []
header = None
curseq = ''
for line in fp:
if line.startswith('>'):
if header and curseq:
sequences.append({
'header': header,
'sequence': curseq
})
... | Fix a bug which prepend the header to NA sequence | Fix a bug which prepend the header to NA sequence
| Python | mit | hivdb/sierra-client | ---
+++
@@ -14,7 +14,7 @@
})
header = line[1:].strip()
curseq = ''
- if line.startswith('#'):
+ elif line.startswith('#'):
continue
else:
curseq += line.strip() |
9856361b48bb481f7913eaf69be668225c5bb818 | api/files/urls.py | api/files/urls.py | from django.conf.urls import url
from api.files import views
urlpatterns = [
url(r'^$', views.FileList.as_view(), name='file-list'),
url(r'^(?P<file_id>\w+)/$', views.FileDetail.as_view(), name='file-detail'),
url(r'^(?P<file_id>\w+)/versions/$', views.FileVersionsList.as_view(), name='file-versions'),
... | from django.conf.urls import url
from api.files import views
urlpatterns = [
url(r'^(?P<file_id>\w+)/$', views.FileDetail.as_view(), name='file-detail'),
url(r'^(?P<file_id>\w+)/versions/$', views.FileVersionsList.as_view(), name='file-versions'),
url(r'^(?P<file_id>\w+)/versions/(?P<version_id>\w+)/$', v... | Remove the files list endpoint | Remove the files list endpoint
| Python | apache-2.0 | acshi/osf.io,aaxelb/osf.io,cslzchen/osf.io,felliott/osf.io,brandonPurvis/osf.io,wearpants/osf.io,Ghalko/osf.io,CenterForOpenScience/osf.io,cwisecarver/osf.io,abought/osf.io,TomBaxter/osf.io,SSJohns/osf.io,amyshi188/osf.io,GageGaskins/osf.io,laurenrevere/osf.io,erinspace/osf.io,DanielSBrown/osf.io,asanfilippo7/osf.io,co... | ---
+++
@@ -3,7 +3,6 @@
from api.files import views
urlpatterns = [
- url(r'^$', views.FileList.as_view(), name='file-list'),
url(r'^(?P<file_id>\w+)/$', views.FileDetail.as_view(), name='file-detail'),
url(r'^(?P<file_id>\w+)/versions/$', views.FileVersionsList.as_view(), name='file-versions'),
... |
648b128542f737da37dc696a02bd71ace6dbb28c | tests/test_deps.py | tests/test_deps.py | import os
import subprocess
import sys
import pytest
def test_adding_deps(tmpdir):
with pytest.raises(ImportError):
import sentinels
projdir = tmpdir.join('proj')
yaml = projdir.join('.cob-project.yml')
python = str(projdir.join('.cob/env/bin/python'))
with yaml.open('a', ensure=True) ... | import os
import subprocess
import sys
import pytest
def test_adding_deps(tmpdir):
with pytest.raises(ImportError):
import pact
projdir = tmpdir.join('proj')
yaml = projdir.join('.cob-project.yml')
python = str(projdir.join('.cob/env/bin/python'))
with yaml.open('a', ensure=True) as f:... | Change import name in deps test | Change import name in deps test
| Python | bsd-3-clause | getweber/weber-cli | ---
+++
@@ -7,7 +7,7 @@
def test_adding_deps(tmpdir):
with pytest.raises(ImportError):
- import sentinels
+ import pact
projdir = tmpdir.join('proj')
yaml = projdir.join('.cob-project.yml')
@@ -20,14 +20,14 @@
assert os.path.exists(python)
- assert subprocess.call([python... |
48f643b99c93fc10c042fe10e4a06c64df245d0d | lobster/cmssw/actions.py | lobster/cmssw/actions.py | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots ... | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots ... | Allow users to add foremen plots for daemonized plotting. | Allow users to add foremen plots for daemonized plotting.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster | ---
+++
@@ -13,13 +13,15 @@
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots in {0} will be updated automatically'.format(config['plotdir']))
+ if 'foremen logs' in config:
+ logger.info('foremen logs will be included from: {0}'.format(', '.jo... |
2f2f6cba331515b8d563d0e2f7869111df4227c3 | txlege84/core/management/commands/updateconveningtimes.py | txlege84/core/management/commands/updateconveningtimes.py | from django.core.management.base import BaseCommand
from core.models import ConveneTime
from legislators.models import Chamber
import requests
class Command(BaseCommand):
help = u'Scrape TLO for convening times.'
def handle(self, *args, **kwargs):
self.update_time('House')
self.update_time(... | from django.core.management.base import BaseCommand
from django.utils import timezone
from core.models import ConveneTime
from legislators.models import Chamber
from dateutil.parser import parse
import requests
class Command(BaseCommand):
help = u'Scrape TLO for convening times.'
def handle(self, *args, **... | Update scraper to account for new fields | Update scraper to account for new fields
| Python | mit | texastribune/txlege84,texastribune/txlege84,texastribune/txlege84,texastribune/txlege84 | ---
+++
@@ -1,8 +1,10 @@
from django.core.management.base import BaseCommand
+from django.utils import timezone
from core.models import ConveneTime
from legislators.models import Chamber
+from dateutil.parser import parse
import requests
@@ -20,11 +22,16 @@
'/SessionTime/{}Ses... |
d9f10a5ac329522f06f41cb52ed113b0703b87a1 | syncplay/__init__.py | syncplay/__init__.py | version = '1.3.0'
milestone = 'Chami'
release_number = '4'
projectURL = 'http://syncplay.pl/'
| version = '1.3.0'
milestone = 'Chami'
release_number = '5'
projectURL = 'http://syncplay.pl/'
| Increase release number to 5 (1.3.0 Beta 3a) | Increase release number to 5 (1.3.0 Beta 3a)
| Python | apache-2.0 | NeverDecaf/syncplay,alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay,alby128/syncplay,NeverDecaf/syncplay | ---
+++
@@ -1,4 +1,4 @@
version = '1.3.0'
milestone = 'Chami'
-release_number = '4'
+release_number = '5'
projectURL = 'http://syncplay.pl/' |
205616b0a23143cdc5ceb6fb8333cf6074ce737b | kitchen/pycompat25/collections/__init__.py | kitchen/pycompat25/collections/__init__.py | try:
from collections import defaultdict
except ImportError:
from _defaultdict import defaultdict
__all__ = ('defaultdict',)
| try:
#:E0611: deafultdict doesn't exist in python-2.4 or less but that's why we
# have it in a try: except:. So we can use our version if necessary.
from collections import defaultdict
except ImportError:
from kitchen.pycompat25.collections._defaultdict import defaultdict
__all__ = ('defaultdict',)
| Fix pylint error in this module | Fix pylint error in this module
| Python | lgpl-2.1 | fedora-infra/kitchen,fedora-infra/kitchen | ---
+++
@@ -1,6 +1,8 @@
try:
+ #:E0611: deafultdict doesn't exist in python-2.4 or less but that's why we
+ # have it in a try: except:. So we can use our version if necessary.
from collections import defaultdict
except ImportError:
- from _defaultdict import defaultdict
+ from kitchen.pycompat2... |
b0ae4cb386411ae8ae5fd27b19ddb415d0772cf3 | democracy_club/apps/everyelection/forms.py | democracy_club/apps/everyelection/forms.py | from django.forms import (ModelForm, CheckboxSelectMultiple,
MultipleChoiceField)
from .models import AuthorityElection, AuthorityElectionPosition
class AuthorityAreaForm(ModelForm):
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user =... | from django.forms import (ModelForm, CheckboxSelectMultiple,
MultipleChoiceField)
from .models import AuthorityElection, AuthorityElectionPosition
class AuthorityAreaForm(ModelForm):
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user =... | Check that at least one area has been checked | Check that at least one area has been checked
| Python | bsd-3-clause | DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website | ---
+++
@@ -21,10 +21,11 @@
fields = []
def clean(self, *args, **kwargs):
- for area in self.cleaned_data['areas']:
- AuthorityElectionPosition.objects.get_or_create(
- authority_election=self.instance,
- user=self.user,
- area_id=area
- ... |
1e5d68e8cbd592f1bd7535c74948f2bf5f95b4f1 | mqtt_logger/tests.py | mqtt_logger/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from models import *
class SubscriptionTests(TestCase):
@classmethod
def setUpTestData(cls):
sub = MQTTSubscription(server='localhost', topic='#')
sub.save()
cls.sub = sub
def test_callback_function(self):
sub = type(self).sub
# C... | Add test of callback function. | Add test of callback function.
| Python | mit | ast0815/mqtt-hub,ast0815/mqtt-hub | ---
+++
@@ -1,3 +1,32 @@
from django.test import TestCase
-# Create your tests here.
+from models import *
+
+class SubscriptionTests(TestCase):
+
+ @classmethod
+ def setUpTestData(cls):
+ sub = MQTTSubscription(server='localhost', topic='#')
+ sub.save()
+ cls.sub = sub
+
+ def test... |
e7e0b8b723382e7a187e02c6a3052dacefc84bbe | faaopendata/faa_data_cleaner.py | faaopendata/faa_data_cleaner.py | ## A quick script to fix the ridiculous format of the raw FAA download data (at least it's available though!)
import csv
# MASTER.txt is from https://www.faa.gov/licenses_certificates/aircraft_certification/aircraft_registry/releasable_aircraft_download/
with open("MASTER.txt") as orig_file:
orig_file_reader = cs... | ## A quick script to fix the ridiculous format of the raw FAA download data (at least it's available though!)
import csv
# MASTER.txt is from https://www.faa.gov/licenses_certificates/aircraft_certification/aircraft_registry/releasable_aircraft_download/
with open("MASTER.txt") as orig_file:
orig_file_reader = cs... | Add comments to explain what the script is doing on ingest | Add comments to explain what the script is doing on ingest
| Python | apache-2.0 | GISDev01/adsbpostgis | ---
+++
@@ -8,7 +8,11 @@
with open("/temp/MASTER_CLEANED.csv", "w", newline='') as clean_file:
writer = csv.writer(clean_file)
for orig_record in orig_file_reader:
+ # some of the data contains trailing spaces/tabs, so we remove those first
new_row = [old_field_data.stri... |
6d888061089648f2363f77f48fb7458a7ff16735 | pyportify/serializers.py | pyportify/serializers.py | class Track():
artist = ""
name = ""
track_id = ""
def __init__(self, artist, name, track_id=""):
self.artist = artist
self.name = name
self.track_id = track_id
@staticmethod
def from_spotify(self, track):
track_id = track.get("id")
name = track.get("nam... | class Track():
artist = ""
name = ""
track_id = ""
def __init__(self, artist, name, track_id=""):
self.artist = artist
self.name = name
self.track_id = track_id
@classmethod
def from_spotify(cls, track):
track_id = track.get("id")
name = track.get("name"... | Change from_spotify and from_gpm to classmethods | Change from_spotify and from_gpm to classmethods
| Python | apache-2.0 | rckclmbr/pyportify,rckclmbr/pyportify,rckclmbr/pyportify,rckclmbr/pyportify | ---
+++
@@ -8,19 +8,19 @@
self.name = name
self.track_id = track_id
- @staticmethod
- def from_spotify(self, track):
+ @classmethod
+ def from_spotify(cls, track):
track_id = track.get("id")
name = track.get("name")
artist = ""
if "artists" in track:... |
1071e663eb38a3981cea047c1b2e24d6e119f94d | db/api/serializers.py | db/api/serializers.py | from rest_framework import serializers
from db.base.models import Satellite, Transponder
class SatelliteSerializer(serializers.ModelSerializer):
class Meta:
model = Satellite
class TransponderSerializer(serializers.ModelSerializer):
norad = serializers.SerializerMethodField()
class Meta:
... | from rest_framework import serializers
from db.base.models import Satellite, Transponder
class SatelliteSerializer(serializers.ModelSerializer):
class Meta:
model = Satellite
class TransponderSerializer(serializers.ModelSerializer):
norad_cat_id = serializers.SerializerMethodField()
class Meta... | Change norad API field to proper name | Change norad API field to proper name
| Python | agpl-3.0 | Roboneet/satnogs-db,Roboneet/satnogs-db,Roboneet/satnogs-db,Roboneet/satnogs-db | ---
+++
@@ -9,13 +9,13 @@
class TransponderSerializer(serializers.ModelSerializer):
- norad = serializers.SerializerMethodField()
+ norad_cat_id = serializers.SerializerMethodField()
class Meta:
model = Transponder
fields = ('uuid', 'description', 'alive', 'uplink_low', 'uplink_hig... |
990de574769cf6b64dfc90128838e209af377ae0 | sourcestats/collector/__main__.py | sourcestats/collector/__main__.py | # Source Server Stats
# File: sourcestats/collector/__main__.py
# Desc: __main__ for the collector
from gevent import monkey
monkey.patch_all()
import sys
import logging
import gevent
from coloredlogs import ColoredStreamHandler
from .. import logger
from . import find, collect, index
if __name__ == '__main__':
... | # Source Server Stats
# File: sourcestats/collector/__main__.py
# Desc: __main__ for the collector
from gevent import monkey
monkey.patch_all()
import sys
import logging
import gevent
from coloredlogs import ColoredStreamHandler
from .. import logger
from . import find, collect, index
if __name__ == '__main__':
... | Make the collector exit if one of it's greenlets fails. | Make the collector exit if one of it's greenlets fails.
| Python | mit | Fizzadar/SourceServerStats,Fizzadar/SourceServerStats,Fizzadar/SourceServerStats | ---
+++
@@ -28,12 +28,26 @@
logger.addHandler(handler)
logger.info('Starting find, collect & index workers...')
- gevent.spawn(find)
- gevent.spawn(collect)
- gevent.spawn(index)
+
+ greenlets = [
+ gevent.spawn(find),
+ gevent.spawn(collect),
+ gevent.spawn(index)
+ ]
... |
900f5fab722d32762b8a5fa214838f84b3fc376c | speech_recognition/__main__.py | speech_recognition/__main__.py | import speech_recognition as sr
r = sr.Recognizer()
m = sr.Microphone()
print("A moment of silence, please...")
with m as source:
r.adjust_for_ambient_noise(source)
print("Set minimum energy threshold to {}".format(r.energy_threshold))
while True:
print("Say something!")
audio = r.listen(s... | import speech_recognition as sr
r = sr.Recognizer()
m = sr.Microphone()
try:
print("A moment of silence, please...")
with m as source:
r.adjust_for_ambient_noise(source)
print("Set minimum energy threshold to {}".format(r.energy_threshold))
while True:
print("Say something!... | Handle Ctrl + C when running demo in the terminal. | Handle Ctrl + C when running demo in the terminal.
| Python | bsd-3-clause | adrianzhang/speech_recognition,Python-Devs-Brasil/speech_recognition,Uberi/speech_recognition,Python-Devs-Brasil/speech_recognition,Zenohm/speech_recognition,jjsg/speech_recognition,Uberi/speech_recognition,adrianzhang/speech_recognition,Zenohm/speech_recognition,jjsg/speech_recognition,arvindch/speech_recognition,arvi... | ---
+++
@@ -3,19 +3,22 @@
r = sr.Recognizer()
m = sr.Microphone()
-print("A moment of silence, please...")
-with m as source:
- r.adjust_for_ambient_noise(source)
- print("Set minimum energy threshold to {}".format(r.energy_threshold))
- while True:
- print("Say something!")
- audio = r.lis... |
61427695c0abb3c9385610a13c78cb21eec388d3 | moa/factory_registers.py | moa/factory_registers.py | from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('Digita... | from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('Digita... | Update factory registers with new classes. | Update factory registers with new classes.
| Python | mit | matham/moa | ---
+++
@@ -23,3 +23,5 @@
r('MoaStage', module='moa.stage')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
+r('DigitalGateStage', module='moa.stage.gate')
+r('AnalogGateStage', module='moa.stage.gate') |
1cc83f902fbfaaf571c15927aa633af361c47f78 | aafig/setup.py | aafig/setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the aafigure Sphinx extension.
Allow embeded ASCII art figure to be rendered as nice images.
'''
requires = ['Sphinx>=0.6']
setup(
name='aafig',
version='0.1',
url='http://bitbucket.org/birkenfeld/... | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
long_desc = '''
This package contains the aafigure Sphinx extension.
Allow embeded ASCII art figure to be rendered as nice images.
'''
requires = ['Sphinx>=0.6']
setup(
name='sphinxcontrib-aafig',
version='0.1',
url='http://bitbucket.o... | Rename package as sphinxcontrib-aafig * * * aafig: Fix package name in PYPI URL | aafig: Rename package as sphinxcontrib-aafig
* * *
aafig: Fix package name in PYPI URL
| Python | bsd-2-clause | sphinx-contrib/spelling,sphinx-contrib/spelling | ---
+++
@@ -11,10 +11,10 @@
requires = ['Sphinx>=0.6']
setup(
- name='aafig',
+ name='sphinxcontrib-aafig',
version='0.1',
url='http://bitbucket.org/birkenfeld/sphinx-contrib',
- download_url='http://pypi.python.org/pypi/aafig',
+ download_url='http://pypi.python.org/pypi/sphinxcontrib-aafig... |
073d4d65edc93247c24f179ee93d061a0024057a | web/migrations/0001_initial.py | web/migrations/0001_initial.py | # Generated by Django 3.2.6 on 2021-08-23 18:33
# pylint:disable=line-too-long
# pylint:disable=missing-module-docstring
# pylint:disable=
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = ... | # Generated by Django 3.2.6 on 2021-08-23 18:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SiteVisit',
fields=[
... | Remove pylint disables (for now) | Remove pylint disables (for now)
| Python | agpl-3.0 | codethesaurus/codethesaur.us,codethesaurus/codethesaur.us | ---
+++
@@ -1,7 +1,5 @@
# Generated by Django 3.2.6 on 2021-08-23 18:33
-# pylint:disable=line-too-long
-# pylint:disable=missing-module-docstring
-# pylint:disable=
+
from django.db import migrations, models
import django.db.models.deletion
|
71f00a03d6cbe4dc4d3cd2362ef91bd192a9a31e | who_broke_build.py | who_broke_build.py | import json
import re
import requests
import socket
import settings
def get_responsible_user(full_url):
members = settings.TEAM_MEMBERS
response = requests.get(
full_url,
auth=(
settings.JENKINS_USERNAME,
settings.JENKINS_PASSWORD
)
)
for each in membe... | import json
import re
import requests
import socket
import settings
def get_responsible_user(full_url):
members = settings.TEAM_MEMBERS
response = requests.get(
full_url,
auth=(
settings.JENKINS_USERNAME,
settings.JENKINS_PASSWORD
)
)
for each in membe... | Add point to execute program | Add point to execute program
| Python | mit | mrteera/who-broke-build-slack,mrteera/who-broke-build-slack,zkan/who-broke-build-slack,prontodev/who-broke-build-slack,prontodev/who-broke-build-slack,zkan/who-broke-build-slack | ---
+++
@@ -41,3 +41,7 @@
target = get_responsible_user(
notification_data['build']['full_url']
)
+
+
+if __name__ == '__main__':
+ jenkins_wait_for_event() |
acfd2165c400b7318cea7c4e74db050968f9a123 | api.py | api.py | import json
from os import environ
from eve import Eve
from eve.io.mongo import Validator
from settings import API_NAME, URL_PREFIX
class KeySchemaValidator(Validator):
def _validate_keyschema(self, schema, field, dct):
"Validate all keys of dictionary `dct` against schema `schema`."
for key, va... | import json
from os import environ
from eve import Eve
from eve.io.mongo import Validator
from settings import API_NAME, URL_PREFIX
class KeySchemaValidator(Validator):
def _validate_keyschema(self, schema, field, dct):
"Validate all keys of dictionary `dct` against schema `schema`."
for key, va... | Add utility method to register a resource | Add utility method to register a resource
| Python | apache-2.0 | gwob/Maarifa,gwob/Maarifa,gwob/Maarifa,gwob/Maarifa,gwob/Maarifa | ---
+++
@@ -27,6 +27,18 @@
"Delete all documents of the given resource."
return api.test_client().delete('/' + URL_PREFIX + '/' + resource)
+
+def register_resource(resource, schema):
+ """Register a new resource with the given schema.
+
+ .. note:: This method calls Flask's add_url_rule under the h... |
fdb7617539d63cd3522c41489817eb841374f525 | django_gears/views.py | django_gears/views.py | import mimetypes
import posixpath
import urllib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.contrib.staticfiles.views import serve as staticfiles_serve
from django.http import HttpResponse
from gears.assets import build_asset
from .settings import environment
... | import mimetypes
import posixpath
import urllib
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.contrib.staticfiles.views import serve as staticfiles_serve
from django.http import HttpResponse
from gears.assets import build_asset
from gears.exceptions import FileNo... | Handle FileNotFound exception from build_asset | Handle FileNotFound exception from build_asset
| Python | isc | juliomenendez/django-gears,juliomenendez/django-gears,wiserthanever/django-gears,juliomenendez/django-gears,gears/django-gears,juliomenendez/django-gears,wiserthanever/django-gears,gears/django-gears,wiserthanever/django-gears,wiserthanever/django-gears,gears/django-gears | ---
+++
@@ -8,6 +8,8 @@
from django.http import HttpResponse
from gears.assets import build_asset
+from gears.exceptions import FileNotFound
+
from .settings import environment
@@ -17,8 +19,9 @@
"The gears view can only be used in debug mode or if the "
"--insecure option of 'runser... |
966c466fd31c1d07d6b978fa4b26d6d068fd8b37 | mysite/profile/management/commands/profile_hourly_tasks.py | mysite/profile/management/commands/profile_hourly_tasks.py | import datetime
import logging
from django.core.management.base import BaseCommand
import mysite.profile.tasks
import mysite.search.models
import mysite.search.tasks
## FIXME: Move to a search management command?
def periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch():
logging.info("Checking if bu... | import datetime
import logging
from django.core.management.base import BaseCommand
import mysite.profile.tasks
import mysite.search.models
import mysite.search.tasks
## FIXME: Move to a search management command?
def periodically_check_if_bug_epoch_eclipsed_the_cached_search_epoch():
logging.info("Checking if bu... | Set default logging level to WARN. | Set default logging level to WARN.
| Python | agpl-3.0 | jledbetter/openhatch,heeraj123/oh-mainline,willingc/oh-mainline,vipul-sharma20/oh-mainline,moijes12/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,SnappleCap/oh-mainline,sudheesh001/oh-mainline,moijes12/oh-mainline,heeraj123/oh-mainline,ojengwa/oh-mainline,ojengwa/oh-mainline,nirmeshk/oh-mainline,... | ---
+++
@@ -22,6 +22,8 @@
help = "Run this once hourly for the OpenHatch profile app."
def handle(self, *args, **options):
+ rootLogger = logging.getLogger('')
+ rootLogger.setLevel(logging.WARN)
mysite.profile.tasks.sync_bug_epoch_from_model_then_fill_recommended_bugs_cache()
... |
cf12d0560e8eaedae054c3276857be84c425a89c | ir/__init__.py | ir/__init__.py | from aqt import mw
from .main import ReadingManager
__version__ = '4.3.1'
mw.readingManager = ReadingManager()
| from aqt import mw
from .main import ReadingManager
mw.readingManager = ReadingManager()
| Remove version number from init | Remove version number from init
| Python | isc | luoliyan/incremental-reading-for-anki,luoliyan/incremental-reading-for-anki | ---
+++
@@ -2,6 +2,4 @@
from .main import ReadingManager
-__version__ = '4.3.1'
-
mw.readingManager = ReadingManager() |
f57f3a5a7abec6c9c6077c213cf29ef3fd9b4483 | tools/test_sneeze.py | tools/test_sneeze.py |
import os
from tempfile import mkdtemp
from shutil import rmtree
from nipy.testing import *
from sneeze import find_pkg, run_nose
import_strings = ["from nipype.interfaces.afni import To3d",
"from nipype.interfaces import afni",
"import nipype.interfaces.afni"]
def test_from_name... |
import os
from tempfile import mkdtemp
from shutil import rmtree
from nipy.testing import *
from sneeze import find_pkg, run_nose
import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit",
"from nipype.interfaces import afni",
"import nipype.interfaces.afni",
... | Add more tests for sneeze. | Add more tests for sneeze. | Python | bsd-3-clause | yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD | ---
+++
@@ -6,21 +6,23 @@
from nipy.testing import *
from sneeze import find_pkg, run_nose
-import_strings = ["from nipype.interfaces.afni import To3d",
+import_strings = ["from nipype.interfaces.afni import To3d, ThreeDRefit",
"from nipype.interfaces import afni",
- "import ni... |
3f728b83eb407527588dd5a13a06cc5d1cd11df5 | mfh.py | mfh.py | import mfhclient
import os
import Queue
import sys
import threading
import trigger
import update
def main():
q = Queue.Queue()
updateq = Queue.Queue()
mfhclient_thread = threading.Thread(
args=(q,),
name="mfhclient_thread",
target=mfhclient.main,
)
mfhclient_thread.star... | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import update
from arguments import parse
def main():
q = Event()
mfhclient_process = Process(
args=(args, q,),
name="mfhclient_process",
target=mfhclient.main,
)
mfhclient_process... | Switch from multithreading to multiprocessing | Switch from multithreading to multiprocessing
It is easier to work with processes in terms of the current task.
The task was to make the client and updater work at the same time.
Threads have a lot of limitations and are harder to get right, so I
switched to processes.
The code went pretty much straightforward.
Not on... | Python | mit | Zloool/manyfaced-honeypot | ---
+++
@@ -1,42 +1,36 @@
+import os
+import sys
+import time
+from multiprocessing import Process, Event
+
import mfhclient
-import os
-import Queue
-import sys
-import threading
-import trigger
import update
+from arguments import parse
def main():
- q = Queue.Queue()
- updateq = Queue.Queue()
- mfh... |
36a2051e8f0c36923d93e172d453ce0e6fe18512 | src/tarsnapper/test.py | src/tarsnapper/test.py | from datetime import datetime
from expire import expire as default_expire_func
__all__ = ('BackupSimulator',)
try:
from collections import OrderedDict # Python 2.7
except ImportError:
# Install from: http://pypi.python.org/pypi/ordereddict
from ordereddict import OrderedDict
class BackupSimulator(o... | from datetime import datetime
from expire import expire as default_expire_func
from config import parse_deltas
__all__ = ('BackupSimulator',)
try:
from collections import OrderedDict # Python 2.7
except ImportError:
# Install from: http://pypi.python.org/pypi/ordereddict
from ordereddict import Order... | Allow using strings for deltas and dates. | Allow using strings for deltas and dates.
| Python | bsd-2-clause | jyrkij/tarsnapper | ---
+++
@@ -1,5 +1,6 @@
from datetime import datetime
from expire import expire as default_expire_func
+from config import parse_deltas
__all__ = ('BackupSimulator',)
@@ -18,10 +19,18 @@
"""
def __init__(self, deltas, expire_func=default_expire_func):
+ if isinstance(deltas, basestring):
+ ... |
64f68922cce077716b9b8ec3de0a04ee31b7b7a9 | mkt/api/tests/test_base.py | mkt/api/tests/test_base.py | from tastypie import http
from tastypie.authorization import Authorization
from test_utils import RequestFactory
from amo.tests import TestCase
from mkt.api.base import MarketplaceResource
class TestMarketplace(TestCase):
def setUp(self):
self.resource = MarketplaceResource()
self.resource._meta.... | from tastypie import http
from tastypie.authentication import Authentication
from tastypie.authorization import Authorization
from test_utils import RequestFactory
from amo.tests import TestCase
from mkt.api.base import MarketplaceResource
class TestMarketplace(TestCase):
def setUp(self):
self.resource =... | Fix failing TestMarketplace test by ensuring vanilla authentication and authorization | Fix failing TestMarketplace test by ensuring vanilla authentication and authorization
| Python | bsd-3-clause | kumar303/addons-server,psiinon/addons-server,jasonthomas/zamboni,Witia1/olympia,Revanth47/addons-server,Joergen/zamboni,eviljeff/zamboni,jamesthechamp/zamboni,wagnerand/zamboni,clouserw/zamboni,wagnerand/zamboni,mstriemer/addons-server,diox/olympia,Hitechverma/zamboni,clouserw/zamboni,Nolski/olympia,mozilla/addons-serv... | ---
+++
@@ -1,4 +1,5 @@
from tastypie import http
+from tastypie.authentication import Authentication
from tastypie.authorization import Authorization
from test_utils import RequestFactory
@@ -9,7 +10,11 @@
class TestMarketplace(TestCase):
def setUp(self):
self.resource = MarketplaceResource()
+
+... |
ea748053152c048f9ac763a4fb6b97a1815082df | wcsaxes/datasets/__init__.py | wcsaxes/datasets/__init__.py | """Downloads the FITS files that are used in image testing and for building documentation.
"""
from astropy.utils.data import download_file
from astropy.io import fits
def msx_hdu(cache=True):
filename = download_file("http://astrofrog.github.io/wcsaxes-datasets/msx.fits", cache=cache)
return fits.open(fil... | """Downloads the FITS files that are used in image testing and for building documentation.
"""
from astropy.utils.data import download_file
from astropy.io import fits
URL = 'http://astrofrog.github.io/wcsaxes-datasets/'
def get_hdu(filename, cache=True):
path = download_file(URL + filename, cache=cache)
re... | Simplify datasets functions a bit | Simplify datasets functions a bit
| Python | bsd-3-clause | saimn/astropy,saimn/astropy,StuartLittlefair/astropy,dhomeier/astropy,astropy/astropy,stargaser/astropy,astropy/astropy,larrybradley/astropy,bsipocz/astropy,bsipocz/astropy,kelle/astropy,pllim/astropy,funbaker/astropy,dhomeier/astropy,mhvk/astropy,pllim/astropy,StuartLittlefair/astropy,astropy/astropy,dhomeier/astropy,... | ---
+++
@@ -1,32 +1,32 @@
"""Downloads the FITS files that are used in image testing and for building documentation.
-
-
"""
from astropy.utils.data import download_file
from astropy.io import fits
+URL = 'http://astrofrog.github.io/wcsaxes-datasets/'
+
+
+def get_hdu(filename, cache=True):
+ path = downlo... |
bf307c6fa8c7259d49da2888f91d6bce9fc921cd | src/idea/utility/state_helper.py | src/idea/utility/state_helper.py | from idea.models import State
def get_first_state():
""" Get the first state for an idea. """
return State.objects.get(previous__isnull=True)
| from idea.models import State
def get_first_state():
""" Get the first state for an idea. """
#return State.objects.get(previous__isnull=True)
# previous__isnull breaks functionality if someone creates a new state
# without a previous state set. since we know the initial state
# is id=1 per fixtur... | Fix add_idea when multiple States have no previous | Fix add_idea when multiple States have no previous
| Python | cc0-1.0 | cfpb/idea-box,cfpb/idea-box,cfpb/idea-box | ---
+++
@@ -2,4 +2,8 @@
def get_first_state():
""" Get the first state for an idea. """
- return State.objects.get(previous__isnull=True)
+ #return State.objects.get(previous__isnull=True)
+ # previous__isnull breaks functionality if someone creates a new state
+ # without a previous state set. s... |
0948e7a25e79b01dae3c5b6cf9b0c272e2d196b7 | moviepy/video/fx/scroll.py | moviepy/video/fx/scroll.py | import numpy as np
def scroll(clip, h=None, w=None, x_speed=0, y_speed=0,
x_start=0, y_start=0, apply_to="mask"):
""" Scrolls horizontally or vertically a clip, e.g. to make end
credits """
if h is None: h = clip.h
if w is None: w = clip.w
xmax = clip.w-w-1
ymax = clip.h-h-1... | import numpy as np
def scroll(clip, h=None, w=None, x_speed=0, y_speed=0,
x_start=0, y_start=0, apply_to="mask"):
""" Scrolls horizontally or vertically a clip, e.g. to make end
credits """
if h is None: h = clip.h
if w is None: w = clip.w
xmax = clip.w-w-1
ymax = clip.h-h-1... | Add int() wrapper to prevent floats | Add int() wrapper to prevent floats
| Python | mit | Zulko/moviepy,ssteo/moviepy,kerstin/moviepy | ---
+++
@@ -11,8 +11,8 @@
ymax = clip.h-h-1
def f(gf,t):
- x = max(0, min(xmax, x_start+ np.round(x_speed*t)))
- y = max(0, min(ymax, y_start+ np.round(y_speed*t)))
+ x = int(max(0, min(xmax, x_start+ np.round(x_speed*t))))
+ y = int(max(0, min(ymax, y_start+ np.round(y_speed*t... |
88e7859d3cca4a07265fc831c3ef6952af3e3d70 | test/connect_remote/TestConnectRemote.py | test/connect_remote/TestConnectRemote.py | """
Test lldb 'process connect' command.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class ConnectRemoteTestCase(TestBase):
mydir = "connect_remote"
def test_connect_remote(self):
"""Test "process connect connect:://localhost:12345"."""
# First, we'll start a fak... | """
Test lldb 'process connect' command.
"""
import os, time
import unittest2
import lldb
from lldbtest import *
class ConnectRemoteTestCase(TestBase):
mydir = "connect_remote"
@unittest2.expectedFailure
def test_connect_remote(self):
"""Test "process connect connect:://localhost:12345"."""
... | Add an expectedFailure decorator to the test_connect_remote() test case. It fails when running within the context of the test suite, but succeeds when running alone. | Add an expectedFailure decorator to the test_connect_remote() test case.
It fails when running within the context of the test suite, but succeeds
when running alone.
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@127290 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb | ---
+++
@@ -11,6 +11,7 @@
mydir = "connect_remote"
+ @unittest2.expectedFailure
def test_connect_remote(self):
"""Test "process connect connect:://localhost:12345"."""
|
9f13b732b68c62a90bbfd2f3fc9ad0c93d54f1e7 | likes/utils.py | likes/utils.py | from likes.signals import likes_enabled_test, can_vote_test
from likes.exceptions import LikesNotEnabledException, CannotVoteException
def _votes_enabled(obj):
"""See if voting is enabled on the class. Made complicated because
secretballot.enable_voting_on takes parameters to set attribute names, so
we can... | from secretballot.models import Vote
from likes.signals import likes_enabled_test, can_vote_test
from likes.exceptions import LikesNotEnabledException, CannotVoteException
def _votes_enabled(obj):
"""See if voting is enabled on the class. Made complicated because
secretballot.enable_voting_on takes parameters... | Add common predicate for can_vote | Add common predicate for can_vote
| Python | bsd-3-clause | sandow-digital/django-likes,just-work/django-likes,Afnarel/django-likes,Afnarel/django-likes,just-work/django-likes,chuck211991/django-likes,Afnarel/django-likes,sandow-digital/django-likes,chuck211991/django-likes,chuck211991/django-likes,just-work/django-likes | ---
+++
@@ -1,3 +1,5 @@
+from secretballot.models import Vote
+
from likes.signals import likes_enabled_test, can_vote_test
from likes.exceptions import LikesNotEnabledException, CannotVoteException
@@ -23,6 +25,14 @@
def can_vote(obj, user, request):
if not _votes_enabled(obj):
return False
+
+ ... |
e2962b3888a2a82cff8f0f01a213c0a123873f60 | application.py | application.py | #!/usr/bin/env python
import os
from dmutils import init_manager
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
manager = init_manager(application, 5000, ['./json_schemas'])
@manager.command
def update_index(index_name):
from app.main.services.search_service ... | #!/usr/bin/env python
import os
from dmutils import init_manager
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
manager = init_manager(application, 5001, ['./mappings'])
@manager.command
def update_index(index_name):
from app.main.services.search_service impo... | Fix local search-api port to 5001 | Fix local search-api port to 5001
When upgrading dmutils I've copied the new `init_manager` code from
the API but forgot to update the port.
Also adds mappings to the list of watched locations for the development
server, so the app will restart if the files are modified.
| Python | mit | alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api | ---
+++
@@ -7,7 +7,7 @@
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
-manager = init_manager(application, 5000, ['./json_schemas'])
+manager = init_manager(application, 5001, ['./mappings'])
@manager.command |
d51b9786b1cc72dd01549a8547f06efc27aab4c3 | tests/test_settings.py | tests/test_settings.py |
from test_app.settings import *
INSTALLED_APPS += ("cmsplugin_rst",)
## DJANGO CMSPLUGIN RST CONF ##
CMSPLUGIN_RST_WRITER_NAME = "html4css1"
CMSPLUGIN_RST_CONTENT_PREFIX = """
.. |nbsp| unicode:: 0xA0
:trim:
*Global Prefix: Start of Content*
"""
CMSPLUGIN_RST_CONTENT_SUFFIX = \
"""*Global Suffix: End... |
from textwrap import dedent
from test_app.settings import *
INSTALLED_APPS += ("cmsplugin_rst",)
## DJANGO CMSPLUGIN RST CONF ##
if not os.environ.get("CMSPLUGIN_RST_SKIP_CONF"): # use this flag to test the zero-conf case
CMSPLUGIN_RST_WRITER_NAME = "html4css1"
CMSPLUGIN_RST_CONTENT_PREFIX = dedent("""... | Make test settings skippable via CMSPLUGIN_RST_SKIP_CONF environment variable. | Make test settings skippable via CMSPLUGIN_RST_SKIP_CONF environment variable.
| Python | bsd-3-clause | pakal/cmsplugin-rst,ojii/cmsplugin-rst | ---
+++
@@ -1,40 +1,38 @@
+from textwrap import dedent
from test_app.settings import *
INSTALLED_APPS += ("cmsplugin_rst",)
-
+
## DJANGO CMSPLUGIN RST CONF ##
-CMSPLUGIN_RST_WRITER_NAME = "html4css1"
+if not os.environ.get("CMSPLUGIN_RST_SKIP_CONF"): # use this flag to test the zero-conf case
-CMSPLUG... |
ecab0066c8ecd63c1aae85ffd04b970539eae71b | genderator/utils.py | genderator/utils.py | from unidecode import unidecode
class Normalizer:
def normalize(text):
text = Normalizer.remove_extra_whitespaces(text)
text = Normalizer.replace_hyphens(text)
# text = Normalizer.remove_accent_marks(text)
return text.lower()
@staticmethod
def replace_hyphens(text):
... | from unidecode import unidecode
class Normalizer:
def normalize(text):
"""
Normalize a given text applying all normalizations.
Params:
text: The text to be processed.
Returns:
The text normalized.
"""
text = Normalizer.remove_extra_whitesp... | Add accent marks normalization and missing docstrings | Add accent marks normalization and missing docstrings
| Python | mit | davidmogar/genderator | ---
+++
@@ -4,20 +4,59 @@
class Normalizer:
def normalize(text):
+ """
+ Normalize a given text applying all normalizations.
+
+ Params:
+ text: The text to be processed.
+
+ Returns:
+ The text normalized.
+ """
text = Normalizer.remove_extra_... |
1a43628a42f249a69e0f8846ebbf88ef0af9bb9d | flow/__init__.py | flow/__init__.py | from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature
from data import \
IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBui... | from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature
from data import \
IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBui... | Make PersistenceSettings a top-level export | Make PersistenceSettings a top-level export
| Python | mit | JohnVinyard/featureflow,JohnVinyard/featureflow | ---
+++
@@ -23,3 +23,5 @@
from decoder import Decoder
from lmdbstore import LmdbDatabase
+
+from persistence import PersistenceSettings |
4ac6905ee4867c038f0574c9c14827164c10f6a6 | tools/unicode_tests.py | tools/unicode_tests.py | # coding: utf-8
"""These tests have to be run separately from the main test suite (iptest),
because that sets the default encoding to utf-8, and it cannot be changed after
the interpreter is up and running. The default encoding in a Python 2.x
environment is ASCII."""
import unittest, sys
from IPython.core import com... | #!/usr/bin/env python
# coding: utf-8
"""These tests have to be run separately from the main test suite (iptest),
because that sets the default encoding to utf-8, and it cannot be changed after
the interpreter is up and running. The default encoding in a Python 2.x
environment is ASCII."""
import unittest
import sys, ... | Add test for reloading history including unicode (currently fails). | Add test for reloading history including unicode (currently fails).
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -1,11 +1,16 @@
+#!/usr/bin/env python
# coding: utf-8
"""These tests have to be run separately from the main test suite (iptest),
because that sets the default encoding to utf-8, and it cannot be changed after
the interpreter is up and running. The default encoding in a Python 2.x
environment is ASCI... |
78aabbc9c66bc92fdedec740e32ad9fbd9ee8937 | pygraphc/clustering/ConnectedComponents.py | pygraphc/clustering/ConnectedComponents.py | import networkx as nx
class ConnectedComponents:
"""This is a class for connected component detection method to cluster event logs [1]_.
References
----------
.. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication log
clustering, in Proceedings... | import networkx as nx
from ClusterUtility import ClusterUtility
class ConnectedComponents:
"""This is a class for connected component detection method to cluster event logs [1]_.
References
----------
.. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication... | Change cluster data structure from list to dict | Change cluster data structure from list to dict
| Python | mit | studiawan/pygraphc | ---
+++
@@ -1,4 +1,5 @@
import networkx as nx
+from ClusterUtility import ClusterUtility
class ConnectedComponents:
@@ -7,36 +8,35 @@
References
----------
.. [1] H. Studiawan, B. A. Pratomo, and R. Anggoro, Connected component detection for authentication log
- clustering, in Proceedin... |
a39b1e480499c19eee1e7f341964f7c94d6cdbad | st2auth_ldap_backend/__init__.py | st2auth_ldap_backend/__init__.py | # Licensed to the StackStorm, Inc ('StackStorm') 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 th... | # Licensed to the StackStorm, Inc ('StackStorm') 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 th... | Fix code so it works under Python 3. | Fix code so it works under Python 3.
| Python | apache-2.0 | StackStorm/st2-auth-backend-ldap | ---
+++
@@ -13,7 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from ldap_backend import LDAPAuthenticationBackend
+from __future__ import absolute_import
+
+from .ldap_backend import LDAPAuthenticationBackend
__all__ = [
'LDAPAuthenticatio... |
51dcf283fda1492d8e75da2c036848ab4149030d | imagekit/conf.py | imagekit/conf.py | from appconf import AppConf
from django.conf import settings
class ImageKitConf(AppConf):
CACHEFILE_NAMER = 'imagekit.cachefiles.namers.hash'
SPEC_CACHEFILE_NAMER = 'imagekit.cachefiles.namers.source_name_as_path'
CACHEFILE_DIR = 'CACHE/images'
DEFAULT_CACHEFILE_BACKEND = 'imagekit.cachefiles.backends... | from appconf import AppConf
from django.conf import settings
class ImageKitConf(AppConf):
CACHEFILE_NAMER = 'imagekit.cachefiles.namers.hash'
SPEC_CACHEFILE_NAMER = 'imagekit.cachefiles.namers.source_name_as_path'
CACHEFILE_DIR = 'CACHE/images'
DEFAULT_CACHEFILE_BACKEND = 'imagekit.cachefiles.backends... | Fix default cache backend for Django < 1.3 | Fix default cache backend for Django < 1.3
| Python | bsd-3-clause | tawanda/django-imagekit,FundedByMe/django-imagekit,tawanda/django-imagekit,FundedByMe/django-imagekit | ---
+++
@@ -16,5 +16,8 @@
def configure_cache_backend(self, value):
if value is None:
- value = 'django.core.cache.backends.dummy.DummyCache' if settings.DEBUG else 'default'
+ if getattr(settings, 'CACHES', None):
+ value = 'django.core.cache.backends.dummy.DummyC... |
53a1c2ccbd43a8fcb90d8d9b7814c8ed129c0635 | thumbor_botornado/s3_http_loader.py | thumbor_botornado/s3_http_loader.py | from botornado.s3.bucket import AsyncBucket
from botornado.s3.connection import AsyncS3Connection
from botornado.s3.key import AsyncKey
from thumbor_botornado.s3_loader import S3Loader
from thumbor.loaders.http_loader import HttpLoader
def load(context, url, callback):
p = re.compile('/^https?:/i')
m = p.match(url)... | import thumbor_botornado.s3_loader as S3Loader
import thumbor.loaders.http_loader as HttpLoader
import re
def load(context, url, callback):
if re.match('https?:', url, re.IGNORECASE):
HttpLoader.load(context, url, callback)
else:
S3Loader.load(context, url, callback)
| Add s3-http loader which delegates based on the uri | Add s3-http loader which delegates based on the uri
| Python | mit | 99designs/thumbor_botornado,Jimdo/thumbor_botornado,99designs/thumbor_botornado,Jimdo/thumbor_botornado | ---
+++
@@ -1,14 +1,9 @@
-from botornado.s3.bucket import AsyncBucket
-from botornado.s3.connection import AsyncS3Connection
-from botornado.s3.key import AsyncKey
-
-from thumbor_botornado.s3_loader import S3Loader
-from thumbor.loaders.http_loader import HttpLoader
+import thumbor_botornado.s3_loader as S3Loader
+i... |
be83b28d5a2dedd8caa39cfac57f398af69b2042 | piper/utils.py | piper/utils.py | class DotDict(object):
"""
Immutable dict-like objects accessible by dot notation
Used because the amount of configuration access is very high and just using
dots instead of the dict notation feels good.
"""
def __init__(self, data):
self.data = data
def __repr__(self): # pragma... | class DotDict(object):
"""
Immutable dict-like objects accessible by dot notation
Used because the amount of configuration access is very high and just using
dots instead of the dict notation feels good.
"""
def __init__(self, data):
self.data = data
def __repr__(self): # pragma... | Make dict comparisons possible for DotDicts | Make dict comparisons possible for DotDicts
| Python | mit | thiderman/piper | ---
+++
@@ -26,6 +26,9 @@
return val
def __eq__(self, other):
+ if isinstance(other, dict):
+ # If we are comparing to a dict, just check directly
+ return self.data == other
return self.data == other.data
# So that we can still access as dicts |
e331e49d39b6e60f953a982c90f800cd07dfbc2d | libptp/tools/wapiti/signatures.py | libptp/tools/wapiti/signatures.py | """
Wapiti does not provide ranking for the vulnerabilities it has found.
This file tries to define a ranking for every vulnerability Wapiti might
find.
"""
from libptp.constants import HIGH, MEDIUM, LOW, INFO
SIGNATURES = {
# High ranked vulnerabilities
'SQL Injection': HIGH,
'Blind SQL I... | """
Wapiti does not provide ranking for the vulnerabilities it has found.
This file tries to define a ranking for every vulnerability Wapiti might
find.
"""
from libptp.constants import HIGH, MEDIUM, LOW, INFO
SIGNATURES = {
# High ranked vulnerabilities
'SQL Injection': HIGH,
'Blind SQL I... | Add one signature for wapiti 2.2.1 | [wapitit] Add one signature for wapiti 2.2.1
| Python | bsd-3-clause | DoomTaper/ptp,owtf/ptp | ---
+++
@@ -20,6 +20,7 @@
'Htaccess Bypass': MEDIUM,
'Cross Site Scripting': MEDIUM,
'CRLF Injection': MEDIUM,
+ 'CRLF': MEDIUM,
# Low ranked vulnerabilities
'File Handling': LOW, # a.k.a Path or Directory listing |
cca106b4cb647e82838deb359cf6f9ef813992a9 | dbaas/integrations/credentials/admin/integration_credential.py | dbaas/integrations/credentials/admin/integration_credential.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
list_display = ("user","endpoint",)
save_on_top = True | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
list_display = ("endpoint","user",)
save_on_top = True | Change field order at integration credential admin index page | Change field order at integration credential admin index page
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -5,5 +5,5 @@
class IntegrationCredentialAdmin(admin.ModelAdmin):
search_fields = ("endpoint",)
- list_display = ("user","endpoint",)
+ list_display = ("endpoint","user",)
save_on_top = True |
97cc8b9dd87d43e38d6ff2a20dc4cab2ffcc3d54 | tests/test_requests.py | tests/test_requests.py | import pytest
import ib_insync as ibi
pytestmark = pytest.mark.asyncio
async def test_request_error_raised(ib):
contract = ibi.Stock('MMM', 'SMART', 'USD')
order = ibi.MarketOrder('BUY', 100)
orderState = await ib.whatIfOrderAsync(contract, order)
assert orderState.commission > 0
ib.RaiseReques... | import pytest
import ib_insync as ibi
pytestmark = pytest.mark.asyncio
async def test_request_error_raised(ib):
contract = ibi.Forex('EURUSD')
order = ibi.MarketOrder('BUY', 100)
orderState = await ib.whatIfOrderAsync(contract, order)
assert orderState.commission > 0
ib.RaiseRequestErrors = Tru... | Use EURUSD for test order. | Use EURUSD for test order.
| Python | bsd-2-clause | erdewit/ib_insync,erdewit/ib_insync | ---
+++
@@ -6,7 +6,7 @@
async def test_request_error_raised(ib):
- contract = ibi.Stock('MMM', 'SMART', 'USD')
+ contract = ibi.Forex('EURUSD')
order = ibi.MarketOrder('BUY', 100)
orderState = await ib.whatIfOrderAsync(contract, order)
assert orderState.commission > 0 |
99609e3643c320484c7978440ffedd892f8bb088 | Toolkit/PlayPen/xscale_2_hkl.py | Toolkit/PlayPen/xscale_2_hkl.py | from iotbx.xds.read_ascii import reader
import sys
for n, argv in enumerate(sys.argv[1:]):
r = reader(open(argv))
mas = r.as_miller_arrays(merge_equivalents = False)
assert(len(mas) == 1)
ma = mas[0].apply_scaling(target_max = 9.99e5)
i = ma.data()
s = ma.sigmas()
hkl = ma.indices()
fo... | from iotbx.xds.read_ascii import reader
import sys
for n, argv in enumerate(sys.argv[1:]):
r = reader(open(argv))
mas = r.as_miller_arrays(merge_equivalents = False)
assert(len(mas) == 1)
ma = mas[0].apply_scaling(target_max = 9.99e5)
i = ma.data()
s = ma.sigmas()
hkl = ma.indices()
fo... | Exclude reflections with -ve sigma (needed when reading XDS_ASCII.HKL as input) | Exclude reflections with -ve sigma (needed when reading XDS_ASCII.HKL as input) | Python | bsd-3-clause | xia2/xia2,xia2/xia2 | ---
+++
@@ -17,6 +17,7 @@
_s = ('%f' % s[j])[:7]
assert('.' in _s)
- print '%4d%4d%4d%8s%8s%4d' % (h[0], h[1], h[2],
- _i, _s, n + 1)
+ if s[j] >= 0.0:
+ print '%4d%4d%4d%8s%8s%4d' % (h[0], h[1], h[2],
+ ... |
06bed92f55396c33a4f55c109fdb7871737fea7a | query/forms.py | query/forms.py | """
Forms for the rdap_explorer project, query app.
"""
from django import forms
class QueryForm(forms.Form):
query = forms.CharField(
label='',
max_length=45, # Max length of an IPv6 address.
widget=forms.TextInput(attrs={
'class': 'form-input input-lg', # TODO: Move this i... | """
Forms for the rdap_explorer project, query app.
"""
from django import forms
class QueryForm(forms.Form):
query = forms.CharField(
label='',
max_length=45, # Max length of an IPv6 address.
widget=forms.TextInput(attrs={
'autofocus': 'autofocus',
'class': 'form... | Add HTML5 autofocus attribute to query form field. | Add HTML5 autofocus attribute to query form field.
| Python | mit | cdubz/rdap-explorer,cdubz/rdap-explorer | ---
+++
@@ -10,6 +10,7 @@
label='',
max_length=45, # Max length of an IPv6 address.
widget=forms.TextInput(attrs={
+ 'autofocus': 'autofocus',
'class': 'form-input input-lg', # TODO: Move this in theme!
'placeholder': 'IPv4/6 address'
}) |
e09d60380f626502532e78494314f9ed97eca7c8 | build-cutline-map.py | build-cutline-map.py | #!/usr/bin/env python
from osgeo import ogr
from osgeo import osr
from glob import glob
import os.path
driver = ogr.GetDriverByName("ESRI Shapefile")
ds = driver.CreateDataSource("summary-maps/cutline-map.shp")
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
layer = ds.CreateLayer("tiles", srs, ogr.wkbPolygon)... | #!/usr/bin/env python
from osgeo import ogr
from osgeo import osr
from glob import glob
import os.path
driver = ogr.GetDriverByName("ESRI Shapefile")
ds = driver.CreateDataSource("summary-maps/cutline-map.shp")
srs = osr.SpatialReference()
srs.ImportFromEPSG(26915)
cutline_srs = osr.SpatialReference()
cutline_srs.Im... | Put cutline map in 26915 | Put cutline map in 26915
| Python | mit | simonsonc/mn-glo-mosaic,simonsonc/mn-glo-mosaic,simonsonc/mn-glo-mosaic | ---
+++
@@ -8,7 +8,12 @@
ds = driver.CreateDataSource("summary-maps/cutline-map.shp")
srs = osr.SpatialReference()
-srs.ImportFromEPSG(4326)
+srs.ImportFromEPSG(26915)
+
+cutline_srs = osr.SpatialReference()
+cutline_srs.ImportFromEPSG(4326)
+
+coord_trans = osr.CoordinateTransformation(cutline_srs, srs)
layer... |
6d7910deebeb68e12c7d7f721c54ada031560024 | src/WhiteLibrary/keywords/items/textbox.py | src/WhiteLibrary/keywords/items/textbox.py | from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword
class TextBoxKeywords(LibraryComponent):
@keyword
def input_text_to_textbox(self, locator, input):
"""
Writes text to a textbox... | from TestStack.White.UIItems import TextBox
from WhiteLibrary.keywords.librarycomponent import LibraryComponent
from WhiteLibrary.keywords.robotlibcore import keyword
class TextBoxKeywords(LibraryComponent):
@keyword
def input_text_to_textbox(self, locator, input_value):
"""
Writes text to a t... | Change to better argument name | Change to better argument name
| Python | apache-2.0 | Omenia/robotframework-whitelibrary,Omenia/robotframework-whitelibrary | ---
+++
@@ -5,16 +5,16 @@
class TextBoxKeywords(LibraryComponent):
@keyword
- def input_text_to_textbox(self, locator, input):
+ def input_text_to_textbox(self, locator, input_value):
"""
Writes text to a textbox.
``locator`` is the locator of the text box.
- ``inpu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.