commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 19 3.3k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
bf1f62cb7d91458e768ac31c26deb9ff67ff3a1e | rcamp/rcamp/settings/auth.py | rcamp/rcamp/settings/auth.py | AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'curc-twofactor-duo',
'csu': 'csu'
}
| AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'login',
'csu': 'csu'
}
| Change PAM stack back to login | Change PAM stack back to login
| Python | mit | ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP | AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'login',
'csu': 'csu'
}
| Change PAM stack back to login
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'lib.pam_backend.PamBackend',
)
AUTH_USER_MODEL = 'accounts.User'
LOGIN_URL = '/login'
PAM_SERVICES = {
'default': 'curc-twofactor-duo',
'csu': 'csu'
}
|
5f69bf0adeee796ce2d66b605f1e65c67bc791bb | mininet/test/test_util.py | mininet/test/test_util.py | #!/usr/bin/env python
"""Package: mininet
Test functions defined in mininet.util."""
import unittest
from mininet.util import quietRun
class testQuietRun( unittest.TestCase ):
"""Test quietRun that runs a command and returns its merged output from
STDOUT and STDIN"""
@staticmethod
def getEchoCmd... | Add unit tests for util | Add unit tests for util
| Python | bsd-3-clause | mininet/mininet,mininet/mininet,mininet/mininet | #!/usr/bin/env python
"""Package: mininet
Test functions defined in mininet.util."""
import unittest
from mininet.util import quietRun
class testQuietRun( unittest.TestCase ):
"""Test quietRun that runs a command and returns its merged output from
STDOUT and STDIN"""
@staticmethod
def getEchoCmd... | Add unit tests for util
| |
d5ff70922ca22673cbdbadcd8cf745f81f47e7c1 | app.py | app.py | #!/usr/bin/env python3
import os
import flask
class BlogAPI:
def __init__(self):
self.app = flask.Flask(__name__)
self.log = self.app.logger
self.app.config.update(dict(
DATABASE=os.path.join(self.app.root_path, 'blog.db'),
PORT=8080,
))
@self.app.... | #!/usr/bin/env python3
import os
import flask
import sqlite3
from flask import request
import json
class BlogAPI:
def __init__(self):
self.app = flask.Flask(__name__)
self.log = self.app.logger
self.app.config.update(dict(
DATABASE=os.path.join(self.app.root_path, 'blog.db'),... | Implement API endpoints with flask | Implement API endpoints with flask
| Python | mit | stormbeta/blogapi-example,stormbeta/blogapi-example | #!/usr/bin/env python3
import os
import flask
import sqlite3
from flask import request
import json
class BlogAPI:
def __init__(self):
self.app = flask.Flask(__name__)
self.log = self.app.logger
self.app.config.update(dict(
DATABASE=os.path.join(self.app.root_path, 'blog.db'),... | Implement API endpoints with flask
#!/usr/bin/env python3
import os
import flask
class BlogAPI:
def __init__(self):
self.app = flask.Flask(__name__)
self.log = self.app.logger
self.app.config.update(dict(
DATABASE=os.path.join(self.app.root_path, 'blog.db'),
PORT=... |
155822548be11161aefdb0d93d5ec86095ab3624 | rt.py | rt.py | import queue
import threading
def loop(queue, actor):
while True:
message = queue.get()
actor.behavior(message)
class Actor(object):
def __init__(self):
pass
def _start_loop(self):
self.queue = queue.Queue()
self.dispatcher = threading.Thread(
... | import queue
import threading
def indiviual_loop(queue, actor):
while True:
message = queue.get()
actor.behavior(message)
def global_loop(queue):
while True:
actor, message = queue.get()
actor.behavior(message)
class EventLoop(object):
loop = None
def __init__... | Refactor to allow different event loops | Refactor to allow different event loops | Python | mit | waltermoreira/tartpy | import queue
import threading
def indiviual_loop(queue, actor):
while True:
message = queue.get()
actor.behavior(message)
def global_loop(queue):
while True:
actor, message = queue.get()
actor.behavior(message)
class EventLoop(object):
loop = None
def __init__... | Refactor to allow different event loops
import queue
import threading
def loop(queue, actor):
while True:
message = queue.get()
actor.behavior(message)
class Actor(object):
def __init__(self):
pass
def _start_loop(self):
self.queue = queue.Queue()
... |
4f369b62be57052e534ee48015a383db6c3c7468 | util/web/websockets.py | util/web/websockets.py | # Oxypanel
# File: util/web/websockets.py
# Desc: helpers to make authed websocket requests
from uuid import uuid4
import config
from app import redis_client
from util.web.user import get_current_user
def make_websocket_request(websocket, websocket_data):
# Generate request key
request_key = str(uuid4())
... | Add helpers to create websocket requests | Add helpers to create websocket requests
| Python | mit | oxyio/oxyio,oxyio/oxyio,oxyio/oxyio,oxyio/oxyio | # Oxypanel
# File: util/web/websockets.py
# Desc: helpers to make authed websocket requests
from uuid import uuid4
import config
from app import redis_client
from util.web.user import get_current_user
def make_websocket_request(websocket, websocket_data):
# Generate request key
request_key = str(uuid4())
... | Add helpers to create websocket requests
| |
5bdbdfa94d06065c0536b684e6694b94ad80047b | authentication/authentication.py | authentication/authentication.py | from flask import Flask, jsonify, request
from requests import codes
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
username = request.form['email']
password = request.form['password']
response_content = {'email': username, 'password': password}
return jsonify(response_conte... | from flask import Flask, jsonify, request
from requests import codes
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
email = request.form['email']
password = request.form['password']
response_content = {'email': email, 'password': password}
return jsonify(response_content), c... | Use email variable name where appropriate | Use email variable name where appropriate
| Python | mit | jenca-cloud/jenca-authentication | from flask import Flask, jsonify, request
from requests import codes
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
email = request.form['email']
password = request.form['password']
response_content = {'email': email, 'password': password}
return jsonify(response_content), c... | Use email variable name where appropriate
from flask import Flask, jsonify, request
from requests import codes
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
username = request.form['email']
password = request.form['password']
response_content = {'email': username, 'password': ... |
b0648969f03dfa1cd55cf1f201883ec82afd97be | test/test_command_parser.py | test/test_command_parser.py | from string import ascii_letters
import pytest
from nex.codes import CatCode
from nex.instructions import Instructions
from nex.instructioner import (Instructioner,
make_unexpanded_control_sequence_instruction,
char_cat_instr_tok)
from nex.utils import asc... | Add test for command parsing, without executing | Add test for command parsing, without executing
| Python | mit | eddiejessup/nex | from string import ascii_letters
import pytest
from nex.codes import CatCode
from nex.instructions import Instructions
from nex.instructioner import (Instructioner,
make_unexpanded_control_sequence_instruction,
char_cat_instr_tok)
from nex.utils import asc... | Add test for command parsing, without executing
| |
13be198c8aec08f5738eecbb7da2bfdcafd57a48 | pygraphc/clustering/MaxCliquesPercolationSA.py | pygraphc/clustering/MaxCliquesPercolationSA.py | from MaxCliquesPercolation import MaxCliquesPercolationWeighted
class MaxCliquesPercolationSA(MaxCliquesPercolationWeighted):
def __init__(self, graph, edges_weight, nodes_id, k, threshold):
super(MaxCliquesPercolationSA, self).__init__(graph, edges_weight, nodes_id, k, threshold)
def get_maxcliques_... | from MaxCliquesPercolation import MaxCliquesPercolationWeighted
from pygraphc.optimization.SimulatedAnnealing import SimulatedAnnealing
from numpy import linspace
class MaxCliquesPercolationSA(MaxCliquesPercolationWeighted):
def __init__(self, graph, edges_weight, nodes_id, k, threshold, tmin, tmax, alpha, energy... | Add constructor and get method with SA | Add constructor and get method with SA
| Python | mit | studiawan/pygraphc | from MaxCliquesPercolation import MaxCliquesPercolationWeighted
from pygraphc.optimization.SimulatedAnnealing import SimulatedAnnealing
from numpy import linspace
class MaxCliquesPercolationSA(MaxCliquesPercolationWeighted):
def __init__(self, graph, edges_weight, nodes_id, k, threshold, tmin, tmax, alpha, energy... | Add constructor and get method with SA
from MaxCliquesPercolation import MaxCliquesPercolationWeighted
class MaxCliquesPercolationSA(MaxCliquesPercolationWeighted):
def __init__(self, graph, edges_weight, nodes_id, k, threshold):
super(MaxCliquesPercolationSA, self).__init__(graph, edges_weight, nodes_id... |
1f5f821ac464e9986025988f6c306c742dd842fa | Instanssi/ext_blog/templatetags/blog_tags.py | Instanssi/ext_blog/templatetags/blog_tags.py | # -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entrie... | # -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entrie... | Tag for getting a valid RSS feed url for event. | ext_blog: Tag for getting a valid RSS feed url for event.
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | # -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id=int(event_id), public=True)
return {'entries': entrie... | ext_blog: Tag for getting a valid RSS feed url for event.
# -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_i... |
8c4af64413a34f9cd47053a4994f2e4773a4f6ac | setup.py | setup.py | from setuptools import setup
setup(
name='kubespawner',
version='0.1',
description='JupyterHub Spawner targetting Kubernetes',
url='http://github.com/yuvipanda/jupyterhub-kubernetes-spawner',
author='Yuvi Panda',
author_email='yuvipanda@riseup.net',
license='BSD',
packages=['kubespawner... | from setuptools import setup
setup(
name='kubespawner',
version='0.1',
install_requires=[
'requests-futures>=0.9.7',
'jupyterhub>=0.4.0',
],
description='JupyterHub Spawner targetting Kubernetes',
url='http://github.com/yuvipanda/jupyterhub-kubernetes-spawner',
author='Yuvi ... | Add explit dependencies to packaging | Add explit dependencies to packaging
| Python | bsd-3-clause | yuvipanda/jupyterhub-kubernetes-spawner,jbmarcille/kubespawner,ktong/kubespawner,jupyterhub/kubespawner | from setuptools import setup
setup(
name='kubespawner',
version='0.1',
install_requires=[
'requests-futures>=0.9.7',
'jupyterhub>=0.4.0',
],
description='JupyterHub Spawner targetting Kubernetes',
url='http://github.com/yuvipanda/jupyterhub-kubernetes-spawner',
author='Yuvi ... | Add explit dependencies to packaging
from setuptools import setup
setup(
name='kubespawner',
version='0.1',
description='JupyterHub Spawner targetting Kubernetes',
url='http://github.com/yuvipanda/jupyterhub-kubernetes-spawner',
author='Yuvi Panda',
author_email='yuvipanda@riseup.net',
lic... |
669433c6d83917f0e3939c13dcbdc328536d9bae | project_fish/whats_fresh/models.py | project_fish/whats_fresh/models.py | from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField
class Image(models.Model):
"""
The Image model holds an image and related data.
The Created and Modified time fields are created automatically by
Django when the object is created or modified,... | from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField
class Image(models.Model):
"""
The Image model holds an image and related data.
The Created and Modified time fields are created automatically by
Django when the object is created or modified,... | Change image upload directory to images/ | Change image upload directory to images/
| Python | apache-2.0 | iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api | from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField
class Image(models.Model):
"""
The Image model holds an image and related data.
The Created and Modified time fields are created automatically by
Django when the object is created or modified,... | Change image upload directory to images/
from django.contrib.gis.db import models
import os
from phonenumber_field.modelfields import PhoneNumberField
class Image(models.Model):
"""
The Image model holds an image and related data.
The Created and Modified time fields are created automatically by
Djan... |
f820ef6cef8037942d18dcc912fb6de093ecc8de | txircd/modules/rfc/cmd_userhost.py | txircd/modules/rfc/cmd_userhost.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class UserhostCommand(ModuleData, Command):
implements(IPlugin, IModuleData, ICommand)
name = "UserhostCommand"
core = Tru... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class UserhostCommand(ModuleData, Command):
implements(IPlugin, IModuleData, ICommand)
name = "UserhostCommand"
core = Tru... | Check away status of the target, not user, of USERHOST | Check away status of the target, not user, of USERHOST
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class UserhostCommand(ModuleData, Command):
implements(IPlugin, IModuleData, ICommand)
name = "UserhostCommand"
core = Tru... | Check away status of the target, not user, of USERHOST
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements
class UserhostCommand(ModuleData, Command):
implements(IPlugin, IModul... |
5a744dc3a27564f0d8c7fe618c6900bff711420a | funnel/forms/usergroup.py | funnel/forms/usergroup.py | # -*- coding: utf-8 -*-
from baseframe import __
import baseframe.forms as forms
from baseframe.forms.sqlalchemy import AvailableName
__all__ = ['UserGroupForm']
class UserGroupForm(forms.Form):
name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), forms.validators.ValidName(), A... | # -*- coding: utf-8 -*-
from baseframe import __
import baseframe.forms as forms
from baseframe.forms.sqlalchemy import AvailableName
from ..models import User
from .. import lastuser
__all__ = ['UserGroupForm']
class UserGroupForm(forms.Form):
name = forms.StringField(__("URL name"), validators=[forms.validato... | Change to user select widget | Change to user select widget
| Python | agpl-3.0 | hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel | # -*- coding: utf-8 -*-
from baseframe import __
import baseframe.forms as forms
from baseframe.forms.sqlalchemy import AvailableName
from ..models import User
from .. import lastuser
__all__ = ['UserGroupForm']
class UserGroupForm(forms.Form):
name = forms.StringField(__("URL name"), validators=[forms.validato... | Change to user select widget
# -*- coding: utf-8 -*-
from baseframe import __
import baseframe.forms as forms
from baseframe.forms.sqlalchemy import AvailableName
__all__ = ['UserGroupForm']
class UserGroupForm(forms.Form):
name = forms.StringField(__("URL name"), validators=[forms.validators.DataRequired(), f... |
6c8122be60b25bbe9ba4ff8a714370e801e6ae70 | cufflinks/offline.py | cufflinks/offline.py | import plotly.offline as py_offline
### Offline Mode
def go_offline(connected=False):
try:
py_offline.init_notebook_mode(connected)
except TypeError:
#For older versions of plotly
py_offline.init_notebook_mode()
py_offline.__PLOTLY_OFFLINE_INITIALIZED=True
def go_online():
py_offline.__PLOTLY_OFFLINE_INIT... | import plotly.offline as py_offline
### Offline Mode
def run_from_ipython():
try:
__IPYTHON__
return True
except NameError:
return False
def go_offline(connected=False):
if run_from_ipython():
try:
py_offline.init_notebook_mode(connected)
except TypeE... | Call init_notebook_mode only if inside IPython | Call init_notebook_mode only if inside IPython
| Python | mit | santosjorge/cufflinks | import plotly.offline as py_offline
### Offline Mode
def run_from_ipython():
try:
__IPYTHON__
return True
except NameError:
return False
def go_offline(connected=False):
if run_from_ipython():
try:
py_offline.init_notebook_mode(connected)
except TypeE... | Call init_notebook_mode only if inside IPython
import plotly.offline as py_offline
### Offline Mode
def go_offline(connected=False):
try:
py_offline.init_notebook_mode(connected)
except TypeError:
#For older versions of plotly
py_offline.init_notebook_mode()
py_offline.__PLOTLY_OFFLINE_INITIALIZED=True
de... |
d2793192f88cfc7f5054048583fb514ac1904ffd | posts.py | posts.py | import json
import pprint
import requests
def sample_valid_reddit_response():
r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json')
response_json = r.json()
if 'data' not in response_json:
print("Trying again")
response_json = sample_valid_reddit_response()
return response_json
response_js... | import json
import pprint
import requests
def sample_valid_reddit_response():
r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json')
response_json = r.json()
if 'data' not in response_json:
print("Trying again")
response_json = sample_valid_reddit_response()
return response_json
def save_sam... | Move stuff to function for ross | Move stuff to function for ross
| Python | mit | RossCarriga/repost-data | import json
import pprint
import requests
def sample_valid_reddit_response():
r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json')
response_json = r.json()
if 'data' not in response_json:
print("Trying again")
response_json = sample_valid_reddit_response()
return response_json
def save_sam... | Move stuff to function for ross
import json
import pprint
import requests
def sample_valid_reddit_response():
r = requests.get('http://www.reddit.com/r/cscareerquestions/top.json')
response_json = r.json()
if 'data' not in response_json:
print("Trying again")
response_json = sample_valid_reddit_response()
r... |
e3d1c8bbf238516d7a10e03aea0fbd378c4a4f6f | profile_collection/startup/99-bluesky.py | profile_collection/startup/99-bluesky.py |
def detselect(detector_object, suffix="_stats_total1"):
"""Switch the active detector and set some internal state"""
gs.DETS =[detector_object]
gs.PLOT_Y = detector_object.name + suffix
gs.TABLE_COLS = [gs.PLOT_Y]
|
def detselect(detector_object, suffix="_stats_total1"):
"""Switch the active detector and set some internal state"""
gs.DETS =[detector_object]
gs.PLOT_Y = detector_object.name + suffix
gs.TABLE_COLS = [gs.PLOT_Y]
def chx_plot_motor(scan):
fig = None
if gs.PLOTMODE == 1:
fig = plt.gcf... | Add 'better' plotting control for live plots | ENH: Add 'better' plotting control for live plots
| Python | bsd-2-clause | NSLS-II-CHX/ipython_ophyd,NSLS-II-CHX/ipython_ophyd |
def detselect(detector_object, suffix="_stats_total1"):
"""Switch the active detector and set some internal state"""
gs.DETS =[detector_object]
gs.PLOT_Y = detector_object.name + suffix
gs.TABLE_COLS = [gs.PLOT_Y]
def chx_plot_motor(scan):
fig = None
if gs.PLOTMODE == 1:
fig = plt.gcf... | ENH: Add 'better' plotting control for live plots
def detselect(detector_object, suffix="_stats_total1"):
"""Switch the active detector and set some internal state"""
gs.DETS =[detector_object]
gs.PLOT_Y = detector_object.name + suffix
gs.TABLE_COLS = [gs.PLOT_Y]
|
ed0c44ad01a1b88b0e6109a629455ae44ff91011 | office365/sharepoint/actions/download_file.py | office365/sharepoint/actions/download_file.py | from office365.runtime.http.http_method import HttpMethod
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
class DownloadFileQuery(ServiceOperationQuery):
def __init__(self, web, file_url, file_object):
"""
A download file content query
:type file_url: ... | from office365.runtime.http.http_method import HttpMethod
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
class DownloadFileQuery(ServiceOperationQuery):
def __init__(self, web, file_url, file_object):
... | Support correctly weird characters in filenames when downloading | Support correctly weird characters in filenames when downloading
This commit add support for the following:
- Correctly encoded oData parameter sent to the endpoint.
- Support for # and % in filenames by using a newer 365 endpoint.
Summary:
Current implementation was injecting an URL directly quoted to
the endpoint,... | Python | mit | vgrem/Office365-REST-Python-Client | from office365.runtime.http.http_method import HttpMethod
from office365.runtime.odata.odata_path_parser import ODataPathParser
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
class DownloadFileQuery(ServiceOperationQuery):
def __init__(self, web, file_url, file_object):
... | Support correctly weird characters in filenames when downloading
This commit add support for the following:
- Correctly encoded oData parameter sent to the endpoint.
- Support for # and % in filenames by using a newer 365 endpoint.
Summary:
Current implementation was injecting an URL directly quoted to
the endpoint,... |
3131ea5c8dd41d18192f685e61c1bc8987038193 | vcs_info_panel/tests/test_clients/test_git.py | vcs_info_panel/tests/test_clients/test_git.py | import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
class GitClientTestCase(TestCase):
def setUp(self):
self.client = GitClient()
def _test_called_check_output(self, commands):
with patch('subprocess.check_output... | import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
def without_git_repository(func):
def inner(*args, **kwargs):
with patch('subprocess.check_output') as _check_output:
_check_output.side_effect = subprocess.Call... | Use decorator to patch git repository is not exist | Use decorator to patch git repository is not exist
| Python | mit | giginet/django-debug-toolbar-vcs-info,giginet/django-debug-toolbar-vcs-info | import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
def without_git_repository(func):
def inner(*args, **kwargs):
with patch('subprocess.check_output') as _check_output:
_check_output.side_effect = subprocess.Call... | Use decorator to patch git repository is not exist
import subprocess
from unittest.mock import patch
from django.test import TestCase
from vcs_info_panel.clients.git import GitClient
class GitClientTestCase(TestCase):
def setUp(self):
self.client = GitClient()
def _test_called_check_output(self, co... |
cdaeb420e0cd817ebf570d5eda46362f4c61c691 | tests/chainer_tests/functions_tests/utils_tests/test_forget.py | tests/chainer_tests/functions_tests/utils_tests/test_forget.py | import unittest
import numpy
import chainer
from chainer import functions
from chainer import gradient_check
from chainer import testing
class TestForget(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (3, 4)).astype(numpy.float32)
self.y = numpy.random.uniform(-1, 1, ... | Add test for forget function | Add test for forget function
| Python | mit | wkentaro/chainer,keisuke-umezawa/chainer,okuta/chainer,wkentaro/chainer,hvy/chainer,niboshi/chainer,hvy/chainer,niboshi/chainer,hvy/chainer,niboshi/chainer,kiyukuta/chainer,okuta/chainer,okuta/chainer,cupy/cupy,keisuke-umezawa/chainer,ronekko/chainer,ktnyt/chainer,jnishi/chainer,hvy/chainer,tkerola/chainer,keisuke-umez... | import unittest
import numpy
import chainer
from chainer import functions
from chainer import gradient_check
from chainer import testing
class TestForget(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (3, 4)).astype(numpy.float32)
self.y = numpy.random.uniform(-1, 1, ... | Add test for forget function
| |
c0ad7a6e3048b7691daabeef7779f044709d6a81 | admin/simpleloadtest.py | admin/simpleloadtest.py | # A simple loadtest using locust.
# launch using: locust -f simpleloadtest.py --host=http://pencilcode.net
from locust import HttpLocust, TaskSet, task
import simplejson, random
class MyTaskSet(TaskSet):
def userbase(self, user):
return self.client.base_url.replace('//', '//' + user + '.')
def topget(s... | Add a simple load test. | Add a simple load test.
| Python | mit | davidbau/pencilcode,davidbau/pencilcode,sakagg/pencilcode,dweintrop/pencilcode,cacticouncil/pencilcode,sakagg/pencilcode,Dinuka2013513/pencilcode,davidbau/pencilcode,davidbau/pencilcode,Dinuka2013513/pencilcode,xinan/pencilcode,davidbau/pencilcode,PencilCode/pencilcode,cacticouncil/pencilcode,cacticouncil/pencilcode,dw... | # A simple loadtest using locust.
# launch using: locust -f simpleloadtest.py --host=http://pencilcode.net
from locust import HttpLocust, TaskSet, task
import simplejson, random
class MyTaskSet(TaskSet):
def userbase(self, user):
return self.client.base_url.replace('//', '//' + user + '.')
def topget(s... | Add a simple load test.
| |
7bdb5b717560a147dc70b6c566cad6fa621a8902 | setup.py | setup.py | #!/usr/bin/env python
import os
import codecs
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def... | #!/usr/bin/env python
import os
import codecs
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def... | Update boto3 requirement to latest version | Update boto3 requirement to latest version
| Python | bsd-3-clause | pelme/rds-log,pelme/rds-log | #!/usr/bin/env python
import os
import codecs
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def... | Update boto3 requirement to latest version
#!/usr/bin/env python
import os
import codecs
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file... |
7111a61a66affcb3c60ea207084e537b2109da61 | mangaki/mangaki/management/commands/top.py | mangaki/mangaki/management/commands/top.py | from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
from django.db import connection
from mangaki.models import Rating, Anime
from collections import Counter
import json
import sys
class Command(BaseCommand):
args = ''
help = 'Builds top'
def handle(self, *a... | from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
from django.db import connection
from mangaki.models import Rating, Anime
from collections import Counter
import json
import sys
class Command(BaseCommand):
args = ''
help = 'Builds top'
def handle(self, *a... | Add ID to Artist in Top | Add ID to Artist in Top
| Python | agpl-3.0 | Mako-kun/mangaki,Elarnon/mangaki,Elarnon/mangaki,Mako-kun/mangaki,Mako-kun/mangaki,Elarnon/mangaki | from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
from django.db import connection
from mangaki.models import Rating, Anime
from collections import Counter
import json
import sys
class Command(BaseCommand):
args = ''
help = 'Builds top'
def handle(self, *a... | Add ID to Artist in Top
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Count
from django.db import connection
from mangaki.models import Rating, Anime
from collections import Counter
import json
import sys
class Command(BaseCommand):
args = ''
help = 'Builds top... |
a65d65ce536a0a6dbc01f7f31db4bbabd08ec223 | project_template/project_settings.py | project_template/project_settings.py | # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`
from icekit.project.settings.glamkit import * # glamkit, icekit
# Override the def... | # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`
from icekit.project.settings.icekit import * # glamkit, icekit
# Override the defa... | Use ICEkit settings by default again. | Use ICEkit settings by default again.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | # Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`
from icekit.project.settings.icekit import * # glamkit, icekit
# Override the defa... | Use ICEkit settings by default again.
# Do not commit secrets to VCS.
# Local environment variables will be loaded from `.env.local`.
# Additional environment variables will be loaded from `.env.$DOTENV`.
# Local settings will be imported from `project_settings_local.py`
from icekit.project.settings.glamkit import *... |
e4b47c9bc3de18c83a2fb718c806b7668b492de6 | authentication/urls.py | authentication/urls.py | from django.conf.urls import patterns, include, url
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/$', 'login', {'template_name': 'authentication/login.html'}),
url(r'^logout/$', 'logout_then_login')) | from django.conf.urls import patterns, include, url
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/$', 'login', {'template_name': 'authentication/login.html'}),
url(r'^logout/$', 'logout_then_login',name='logout')) | Add name to logout url regex | Add name to logout url regex
| Python | mit | DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune | from django.conf.urls import patterns, include, url
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/$', 'login', {'template_name': 'authentication/login.html'}),
url(r'^logout/$', 'logout_then_login',name='logout')) | Add name to logout url regex
from django.conf.urls import patterns, include, url
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/$', 'login', {'template_name': 'authentication/login.html'}),
url(r'^logout/$', 'logout_then_login')) |
53b8d4089299e85caef8b65aaa3b074acb243ccb | Next_Greater_Element_I.py | Next_Greater_Element_I.py | # You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
# The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exi... | Solve Next Greater Element I | Solve Next Greater Element I
| Python | mit | Kunal57/Python_Algorithms | # You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
# The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exi... | Solve Next Greater Element I
| |
833d0ee1622530200ebd2614bc6939abba30493c | setup/bin/swc-nano-installer.py | setup/bin/swc-nano-installer.py | #!/usr/bin/env python
"""Software Carpentry Nano Installer for Windows
Installs nano and makes it the default editor in msysgit
To use:
1. Install Python
2. Install msysgit
http://code.google.com/p/msysgit/downloads/list?q=full+installer+official+git
3. Run swc_nano_installer.py
You should be able to simply d... | Add a Nano installer for Windows | Add a Nano installer for Windows
1. Downloads and installs Nano into the users home directory
2. Adds Nano to the path
3. Makes Nano the default editor
| Python | bsd-2-clause | selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,selimnairb/2014-02-25-swctest,swcarpentry/windows-installer,wking/swc-windows-installer,ethanwhite/windows-installer | #!/usr/bin/env python
"""Software Carpentry Nano Installer for Windows
Installs nano and makes it the default editor in msysgit
To use:
1. Install Python
2. Install msysgit
http://code.google.com/p/msysgit/downloads/list?q=full+installer+official+git
3. Run swc_nano_installer.py
You should be able to simply d... | Add a Nano installer for Windows
1. Downloads and installs Nano into the users home directory
2. Adds Nano to the path
3. Makes Nano the default editor
| |
1418112d0ba752d3ebac6cdf2d727fdd71a2cf6f | test/unit/interfaces/test_map_ctp.py | test/unit/interfaces/test_map_ctp.py | import sys, os, re, shutil
from nose.tools import *
import logging
logger = logging.getLogger(__name__)
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from qipipe.interfaces import MapCTP
ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
"""The test parent director... | Test the Map CTP interface. | Test the Map CTP interface.
| Python | bsd-2-clause | ohsu-qin/qipipe | import sys, os, re, shutil
from nose.tools import *
import logging
logger = logging.getLogger(__name__)
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from qipipe.interfaces import MapCTP
ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
"""The test parent director... | Test the Map CTP interface.
| |
61398045cb6bb5a0849fd203ebbe85bfa305ea60 | favicon/templatetags/favtags.py | favicon/templatetags/favtags.py | from django import template
from django.utils.safestring import mark_safe
from favicon.models import Favicon, config
register = template.Library()
@register.simple_tag(takes_context=True)
def placeFavicon(context):
"""
Gets Favicon-URL for the Model.
Template Syntax:
{% placeFavicon %}
""... | from django import template
from django.utils.safestring import mark_safe
from favicon.models import Favicon, config
register = template.Library()
@register.simple_tag(takes_context=True)
def placeFavicon(context):
"""
Gets Favicon-URL for the Model.
Template Syntax:
{% placeFavicon %}
""... | Mark comment as safe. Otherwise it is displayed. | Mark comment as safe. Otherwise it is displayed. | Python | mit | arteria/django-favicon-plus | from django import template
from django.utils.safestring import mark_safe
from favicon.models import Favicon, config
register = template.Library()
@register.simple_tag(takes_context=True)
def placeFavicon(context):
"""
Gets Favicon-URL for the Model.
Template Syntax:
{% placeFavicon %}
""... | Mark comment as safe. Otherwise it is displayed.
from django import template
from django.utils.safestring import mark_safe
from favicon.models import Favicon, config
register = template.Library()
@register.simple_tag(takes_context=True)
def placeFavicon(context):
"""
Gets Favicon-URL for the Model.
Tem... |
786de8ec482ed67b78696357c66dfa9292eea62f | tk/templatetags.py | tk/templatetags.py | from django.core.urlresolvers import reverse, resolve
from django.template import Library
from django.utils import translation
from django.templatetags.i18n import register
@register.simple_tag(takes_context=True)
def translate_url(context, language):
view = resolve(context['request'].path)
args = [a for a in... | from django.core.urlresolvers import reverse, resolve
from django.template import Library
from django.utils import translation
from django.templatetags.i18n import register
@register.simple_tag(takes_context=True)
def translate_url(context, language):
if hasattr(context.get('object', None), 'get_absolute_url'):
... | Fix getting the translated urls for material detail views | Fix getting the translated urls for material detail views
| Python | agpl-3.0 | GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa,GISAElkartea/tresna-kutxa | from django.core.urlresolvers import reverse, resolve
from django.template import Library
from django.utils import translation
from django.templatetags.i18n import register
@register.simple_tag(takes_context=True)
def translate_url(context, language):
if hasattr(context.get('object', None), 'get_absolute_url'):
... | Fix getting the translated urls for material detail views
from django.core.urlresolvers import reverse, resolve
from django.template import Library
from django.utils import translation
from django.templatetags.i18n import register
@register.simple_tag(takes_context=True)
def translate_url(context, language):
vie... |
0b0a11d01378368fb795c117ffd931811eaf9b76 | pyhunter/exceptions.py | pyhunter/exceptions.py |
class PyhunterError(Exception):
"""
Generic exception class for the library
"""
pass
class MissingCompanyError(PyhunterError):
pass
class MissingNameError(PyhunterError):
pass
class HunterApiError(PyhunterError):
"""
Represents something went wrong in the call to the Hunter API
... | class PyhunterError(Exception):
"""
Generic exception class for the library
"""
pass
class MissingCompanyError(PyhunterError):
pass
class MissingNameError(PyhunterError):
pass
class HunterApiError(PyhunterError):
"""
Represents something went wrong in the call to the Hunter API
... | Add new line at end of file | Add new line at end of file
| Python | mit | VonStruddle/PyHunter | class PyhunterError(Exception):
"""
Generic exception class for the library
"""
pass
class MissingCompanyError(PyhunterError):
pass
class MissingNameError(PyhunterError):
pass
class HunterApiError(PyhunterError):
"""
Represents something went wrong in the call to the Hunter API
... | Add new line at end of file
class PyhunterError(Exception):
"""
Generic exception class for the library
"""
pass
class MissingCompanyError(PyhunterError):
pass
class MissingNameError(PyhunterError):
pass
class HunterApiError(PyhunterError):
"""
Represents something went wrong in ... |
ceb3a49fc3e3ca149d203e8489bd4b17b286d6c3 | event/urls.py | event/urls.py | from django.conf.urls import url
from . import views
app_name = 'event'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^artist/$', views.ArtistView.as_view(), name='artist'),
url(r'^artist/(?P<pk>\d+)$', views.ArtistDetailView.as_view(), name='artist_detail'),
url(r'^event/... | from django.conf.urls import url
from . import views
app_name = 'event'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^artist/$', views.ArtistView.as_view(), name='artist'),
url(r'^artist/(?P<pk>\d+)/$', views.ArtistDetailView.as_view(), name='artist_detail'),
url(r'^event... | Fix Artist detail view url | Fix Artist detail view url
| Python | mit | FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack | from django.conf.urls import url
from . import views
app_name = 'event'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^artist/$', views.ArtistView.as_view(), name='artist'),
url(r'^artist/(?P<pk>\d+)/$', views.ArtistDetailView.as_view(), name='artist_detail'),
url(r'^event... | Fix Artist detail view url
from django.conf.urls import url
from . import views
app_name = 'event'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^artist/$', views.ArtistView.as_view(), name='artist'),
url(r'^artist/(?P<pk>\d+)$', views.ArtistDetailView.as_view(), name='artist... |
26e0d89e5178fb05b95f56cbef58ac37bfa6f1d9 | camera_opencv.py | camera_opencv.py | import cv2
from base_camera import BaseCamera
class Camera(BaseCamera):
video_source = 0
@staticmethod
def set_video_source(source):
Camera.video_source = source
@staticmethod
def frames():
camera = cv2.VideoCapture(Camera.video_source)
if not camera.isOpened():
... | import os
import cv2
from base_camera import BaseCamera
class Camera(BaseCamera):
video_source = 0
def __init__(self):
if os.environ.get('OPENCV_CAMERA_SOURCE'):
Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
super(Camera, self).__init__()
@staticmethod
... | Use OPENCV_CAMERA_SOURCE environment variable to set source | Use OPENCV_CAMERA_SOURCE environment variable to set source
| Python | mit | miguelgrinberg/flask-video-streaming,miguelgrinberg/flask-video-streaming | import os
import cv2
from base_camera import BaseCamera
class Camera(BaseCamera):
video_source = 0
def __init__(self):
if os.environ.get('OPENCV_CAMERA_SOURCE'):
Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
super(Camera, self).__init__()
@staticmethod
... | Use OPENCV_CAMERA_SOURCE environment variable to set source
import cv2
from base_camera import BaseCamera
class Camera(BaseCamera):
video_source = 0
@staticmethod
def set_video_source(source):
Camera.video_source = source
@staticmethod
def frames():
camera = cv2.VideoCapture(Cam... |
85697d8a1d79a599071fea4cc41216f3df3f3586 | setup.py | setup.py | from distutils.core import setup
setup(
name='flickruper',
version='0.1.0',
author='Igor Katson',
author_email='igor.katson@gmail.com',
py_modules=['flickruper'],
scripts=['bin/flickruper'],
entry_points={
'console_scripts': ['flickruper = flickruper:main'],
},
url='http://p... | from distutils.core import setup
setup(
name='flickruper',
version='0.1.0',
author='Igor Katson',
author_email='igor.katson@gmail.com',
py_modules=['flickruper'],
scripts=['bin/flickruper'],
entry_points={
'console_scripts': ['flickruper = flickruper:main'],
},
url='https://... | Make it installable with PyPI | Make it installable with PyPI
| Python | mit | ikatson/flickruper | from distutils.core import setup
setup(
name='flickruper',
version='0.1.0',
author='Igor Katson',
author_email='igor.katson@gmail.com',
py_modules=['flickruper'],
scripts=['bin/flickruper'],
entry_points={
'console_scripts': ['flickruper = flickruper:main'],
},
url='https://... | Make it installable with PyPI
from distutils.core import setup
setup(
name='flickruper',
version='0.1.0',
author='Igor Katson',
author_email='igor.katson@gmail.com',
py_modules=['flickruper'],
scripts=['bin/flickruper'],
entry_points={
'console_scripts': ['flickruper = flickruper:m... |
84b907ad78f03d614e8af14578c21e1228ab723d | top.py | top.py | """
Hacker News Top:
-Get top stories from Hacker News' official API
-Record all users who comment on those stories
Author: Rylan Santinon
"""
from api_connector import *
from csv_io import *
def main():
conn = ApiConnector()
csvio = CsvIo()
article_list = conn.get_top()
stories = []
for i in article_... | """
Hacker News Top:
-Get top stories from Hacker News' official API
-Record all users who comment on those stories
Author: Rylan Santinon
"""
from api_connector import *
from csv_io import *
def main():
conn = ApiConnector()
csvio = CsvIo()
article_list = conn.get_top()
stories = []
for i in article_... | Use common object for csvio calls | Use common object for csvio calls
| Python | apache-2.0 | rylans/hackernews-top,davande/hackernews-top | """
Hacker News Top:
-Get top stories from Hacker News' official API
-Record all users who comment on those stories
Author: Rylan Santinon
"""
from api_connector import *
from csv_io import *
def main():
conn = ApiConnector()
csvio = CsvIo()
article_list = conn.get_top()
stories = []
for i in article_... | Use common object for csvio calls
"""
Hacker News Top:
-Get top stories from Hacker News' official API
-Record all users who comment on those stories
Author: Rylan Santinon
"""
from api_connector import *
from csv_io import *
def main():
conn = ApiConnector()
csvio = CsvIo()
article_list = conn.get_top()
... |
a84c02b4369bf698c82be22b6231fe412ad67c63 | Cauldron/ext/click/__init__.py | Cauldron/ext/click/__init__.py | # -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_p... | # -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_p... | Fix a bug in Cauldron click extension | Fix a bug in Cauldron click extension
| Python | bsd-3-clause | alexrudy/Cauldron | # -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend."""
if not value or ctx.resilient_p... | Fix a bug in Cauldron click extension
# -*- coding: utf-8 -*-
try:
import click
except ImportError:
raise ImportError("Cauldron.ext.click requires the click package.")
from ...api import use
__all__ = ['backend', 'service']
def select_backend(ctx, param, value):
"""Callback to set the Cauldron backend.... |
2cbc977e71acded15cc66bea9e36f02ce3934eb8 | real_estate_agency/resale/migrations/0004_ordering_by_id.py | real_estate_agency/resale/migrations/0004_ordering_by_id.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-09-11 21:35
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('resale', '0003_change_coords'),
]
operations = [
migrations.AlterModelOptions(
... | Add skipped migration in resale app connected with ordering. | Add skipped migration in resale app connected with ordering.
| Python | mit | Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-09-11 21:35
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('resale', '0003_change_coords'),
]
operations = [
migrations.AlterModelOptions(
... | Add skipped migration in resale app connected with ordering.
| |
27e137ef5f3b6c4f6c8679edc6412b2c237b8fb4 | plasmapy/physics/tests/test_parameters_cython.py | plasmapy/physics/tests/test_parameters_cython.py | """Tests for functions that calculate plasma parameters using cython."""
import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter
from ...utils.exceptions import RelativityWarning, RelativityError
from ...utils.exceptions import PhysicsError
from ...constants import c, m_p, m_... | """Tests for functions that calculate plasma parameters using cython."""
import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter
from plasmapy.utils.exceptions import RelativityWarning, RelativityError
from plasmapy.utils.exceptions import PhysicsError
from plasmapy.constants... | Update tests for cython parameters | Update tests for cython parameters
| Python | bsd-3-clause | StanczakDominik/PlasmaPy | """Tests for functions that calculate plasma parameters using cython."""
import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter
from plasmapy.utils.exceptions import RelativityWarning, RelativityError
from plasmapy.utils.exceptions import PhysicsError
from plasmapy.constants... | Update tests for cython parameters
"""Tests for functions that calculate plasma parameters using cython."""
import numpy as np
import pytest
from astropy import units as u
from warnings import simplefilter
from ...utils.exceptions import RelativityWarning, RelativityError
from ...utils.exceptions import PhysicsError... |
9da01f39c8d9b73025d85be72b71399b6930b6fb | src/encoded/cache.py | src/encoded/cache.py | from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold ... | from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold ... | Use LRUCache correctly (minimal improvement) | Use LRUCache correctly (minimal improvement)
| Python | mit | ENCODE-DCC/encoded,kidaa/encoded,hms-dbmi/fourfront,philiptzou/clincoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,hms-dbmi/fourfront,philiptzou/clincoded,ENCODE-DCC/snovault,4dn-dcic/fourfront,ClinGen/clincoded,ClinGen/clincoded,4dn-dcic/fourfront,ENCODE-DCC/snovault,4dn-dcic/fourfront,ENCODE-DCC/encoded,T2DREAM/t2dream... | from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capacity = default_capacity
self.threshold ... | Use LRUCache correctly (minimal improvement)
from pyramid.threadlocal import manager
from sqlalchemy.util import LRUCache
class ManagerLRUCache(object):
""" Override capacity in settings.
"""
def __init__(self, name, default_capacity=100, threshold=.5):
self.name = name
self.default_capac... |
8cc88e1f6e09e91f2ffc5bbf43b58b2d129a12c9 | bnc.py | bnc.py | import nltk.corpus.reader.bnc
| import nltk.corpus.reader.bnc
import time
start_time = time.perf_counter()
BNC_data = nltk.corpus.reader.bnc.BNCCorpusReader(root='/home/ubuntu/ug-d/bncbaby/',
fileids=r'aca/\w*\.xml', # r'aca/\w*\.xml', # r'[a-z]{3}/\w*\.xml')
la... | Load BNC into memory and time process. | Load BNC into memory and time process.
| Python | mit | albertomh/ug-dissertation | import nltk.corpus.reader.bnc
import time
start_time = time.perf_counter()
BNC_data = nltk.corpus.reader.bnc.BNCCorpusReader(root='/home/ubuntu/ug-d/bncbaby/',
fileids=r'aca/\w*\.xml', # r'aca/\w*\.xml', # r'[a-z]{3}/\w*\.xml')
la... | Load BNC into memory and time process.
import nltk.corpus.reader.bnc
|
a9eb6f7c9b23b0434aacfa601e0acb7fc72cb29b | setup.py | setup.py | import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ ==... | import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ ==... | Add python_requires to help pip | Add python_requires to help pip
When old Python versions are dropped, this will help pip install the right version for people still running those old Python versions.
For more info on how this works:
* https://hackernoon.com/phasing-out-python-runtimes-gracefully-956f112f33c4
* https://github.com/pypa/python-pac... | Python | cc0-1.0 | remagio/twarc,hugovk/twarc,DocNow/twarc,remagio/twarc,edsu/twarc | import sys
import os
from os.path import join
from setuptools import setup
# Also in twarc.py
__version__ = '1.4.0'
if sys.version_info[0] < 3:
dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
dependencies = open(join('requirements', 'python3.txt')).read().split()
if __name__ ==... | Add python_requires to help pip
When old Python versions are dropped, this will help pip install the right version for people still running those old Python versions.
For more info on how this works:
* https://hackernoon.com/phasing-out-python-runtimes-gracefully-956f112f33c4
* https://github.com/pypa/python-pac... |
0b55d97573fcd196a318b3c901f6dcac1b0a4eef | chrome/test/functional/test_basic.py | chrome/test/functional/test_basic.py | #!/usr/bin/python
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from pyauto import PyUITest
class SimpleTest(PyUITest):
def testCanOpenGoogle(self):
self.NavigateToURL("http... | Create a placeholder for pyauto test scripts. | Create a placeholder for pyauto test scripts.
Including a hello world script.
Review URL: http://codereview.chromium.org/668004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@40579 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | ropik/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,ropik/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromi... | #!/usr/bin/python
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from pyauto import PyUITest
class SimpleTest(PyUITest):
def testCanOpenGoogle(self):
self.NavigateToURL("http... | Create a placeholder for pyauto test scripts.
Including a hello world script.
Review URL: http://codereview.chromium.org/668004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@40579 0039d316-1c4b-4281-b951-d872f2087c98
| |
6279341682ae45a228302972dbd106a2e44e0b12 | examples/example_test.py | examples/example_test.py | import unittest
from flask import Flask
from flask_json import json_response, FlaskJSON, JsonTestResponse
def our_app():
app = Flask(__name__)
app.test_value = 0
FlaskJSON(app)
@app.route('/increment')
def increment():
app.test_value += 1
return json_response(value=app.test_value)... | Add example usage of the JsonTestResponse. | Add example usage of the JsonTestResponse.
| Python | bsd-3-clause | craig552uk/flask-json | import unittest
from flask import Flask
from flask_json import json_response, FlaskJSON, JsonTestResponse
def our_app():
app = Flask(__name__)
app.test_value = 0
FlaskJSON(app)
@app.route('/increment')
def increment():
app.test_value += 1
return json_response(value=app.test_value)... | Add example usage of the JsonTestResponse.
| |
d0bf235af3742a17c722488fe3679d5b73a0d945 | thinc/neural/_classes/softmax.py | thinc/neural/_classes/softmax.py | from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
from ...check import has_shape
from ... import check
@describe.attributes(
W=Synapses("Weights matrix",
lambda obj: (obj.nO, obj.nI),
lambda W, ops: None)
)
class Softmax(Affine):
name = 'so... | from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
from ...check import has_shape
from ... import check
@describe.attributes(
W=Synapses("Weights matrix",
lambda obj: (obj.nO, obj.nI),
lambda W, ops: None)
)
class Softmax(Affine):
name = 'so... | Fix gemm calls in Softmax | Fix gemm calls in Softmax
| Python | mit | spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc | from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
from ...check import has_shape
from ... import check
@describe.attributes(
W=Synapses("Weights matrix",
lambda obj: (obj.nO, obj.nI),
lambda W, ops: None)
)
class Softmax(Affine):
name = 'so... | Fix gemm calls in Softmax
from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
from ...check import has_shape
from ... import check
@describe.attributes(
W=Synapses("Weights matrix",
lambda obj: (obj.nO, obj.nI),
lambda W, ops: None)
)
class Soft... |
7b94c8390f4756aa69a0e88737b9f4f749e13acd | test/test_sparql_base_ref.py | test/test_sparql_base_ref.py | from rdflib import ConjunctiveGraph, Literal
from StringIO import StringIO
import unittest
test_data = """
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
<http://example.org/alice> a foaf:Person;
foaf:name "Alice";
foaf:knows <http://exa... | Test for use of BASE <..> | Test for use of BASE <..>
| Python | bsd-3-clause | yingerj/rdflib,yingerj/rdflib,marma/rdflib,avorio/rdflib,marma/rdflib,avorio/rdflib,yingerj/rdflib,RDFLib/rdflib,avorio/rdflib,armandobs14/rdflib,dbs/rdflib,armandobs14/rdflib,ssssam/rdflib,armandobs14/rdflib,ssssam/rdflib,avorio/rdflib,dbs/rdflib,armandobs14/rdflib,ssssam/rdflib,marma/rdflib,RDFLib/rdflib,RDFLib/rdfli... | from rdflib import ConjunctiveGraph, Literal
from StringIO import StringIO
import unittest
test_data = """
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
<http://example.org/alice> a foaf:Person;
foaf:name "Alice";
foaf:knows <http://exa... | Test for use of BASE <..>
| |
a8997dad913fbc5a12def6a31931efab16efd285 | {{cookiecutter.project_slug}}/search/views.py | {{cookiecutter.project_slug}}/search/views.py | from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
from wagtail.core.models import Page
from wagtail.search.models import Query
def search(request):
search_query = request.GET.get('query', None)
page = request.GET.get('page', 1)
# Search
if s... | from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
from wagtail.core.models import Page
from wagtail.search.models import Query
def search(request):
search_query = request.GET.get('q', None)
page = request.GET.get('page', 1)
# Search
if searc... | Make search parameter match template parameter name | Make search parameter match template parameter name | Python | mit | chrisdev/wagtail-cookiecutter-foundation,chrisdev/wagtail-cookiecutter-foundation,ilendl2/wagtail-cookiecutter-foundation,ilendl2/wagtail-cookiecutter-foundation,ilendl2/wagtail-cookiecutter-foundation,chrisdev/wagtail-cookiecutter-foundation | from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
from wagtail.core.models import Page
from wagtail.search.models import Query
def search(request):
search_query = request.GET.get('q', None)
page = request.GET.get('page', 1)
# Search
if searc... | Make search parameter match template parameter name
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render
from wagtail.core.models import Page
from wagtail.search.models import Query
def search(request):
search_query = request.GET.get('query', None)
page... |
5d36b16fde863cccf404f658f53eac600ac9ddb1 | foomodules/link_harvester/common_handlers.py | foomodules/link_harvester/common_handlers.py | import re
import socket
import urllib
from bs4 import BeautifulSoup
WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/")
def default_handler(metadata):
return {key: getattr(metadata, key) for key in
["original_url", "url", "title", "description",
"human_readable_type"]}
def wu... | import logging
import re
import socket
import urllib
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/")
def default_handler(metadata):
return {key: getattr(metadata, key) for key in
["original_url", "url", "title", "descript... | Print warning when wurstball downloads fail | Print warning when wurstball downloads fail
| Python | mit | horazont/xmpp-crowd | import logging
import re
import socket
import urllib
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/")
def default_handler(metadata):
return {key: getattr(metadata, key) for key in
["original_url", "url", "title", "descript... | Print warning when wurstball downloads fail
import re
import socket
import urllib
from bs4 import BeautifulSoup
WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/")
def default_handler(metadata):
return {key: getattr(metadata, key) for key in
["original_url", "url", "title", "description",
... |
2e72dcb52c23690c6f1b41cfff1948f18506293b | exercises/chapter_03/exercise_03_04/exercise_04_04.py | exercises/chapter_03/exercise_03_04/exercise_04_04.py | # 3-4 Guest List
guest_list = ["Albert Einstein", "Isac Newton", "Marie Curie", "Galileo Galilei"]
message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_l... | Add solution to exercise 4.4. | Add solution to exercise 4.4.
| Python | mit | HenrikSamuelsson/python-crash-course | # 3-4 Guest List
guest_list = ["Albert Einstein", "Isac Newton", "Marie Curie", "Galileo Galilei"]
message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)
message = "Hi " + guest_l... | Add solution to exercise 4.4.
| |
435e8fc4d9ad8c071a96e37e483fcbc194a94fc6 | tests/integration/files/file/base/_modules/runtests_decorators.py | tests/integration/files/file/base/_modules/runtests_decorators.py | # -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
import time
# Import Salt libs
import salt.utils.decorators
def _fallbackfunc():
return False, 'fallback'
def working_function():
'''
CLI Example:
.. code-block:: bash
'''
return True
@salt.utils.decorato... | # -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
import time
# Import Salt libs
import salt.utils.decorators
def _fallbackfunc():
return False, 'fallback'
def working_function():
'''
CLI Example:
.. code-block:: bash
'''
return True
@salt.utils.decorat... | Fix tests: add module function docstring | Fix tests: add module function docstring
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | # -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
import time
# Import Salt libs
import salt.utils.decorators
def _fallbackfunc():
return False, 'fallback'
def working_function():
'''
CLI Example:
.. code-block:: bash
'''
return True
@salt.utils.decorat... | Fix tests: add module function docstring
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
import time
# Import Salt libs
import salt.utils.decorators
def _fallbackfunc():
return False, 'fallback'
def working_function():
'''
CLI Example:
.. code-block:: bash
... |
ee3b11a7a15535ffe52a6bdd493819fbd76b2300 | vroom/graphics.py | vroom/graphics.py | import pygame
class Graphic:
car_color = (255, 50, 50)
car_width = 3
road_color = (255, 255, 255)
road_width = 6
draw_methods = {
'Car': 'draw_car',
'Road': 'draw_road',
}
def __init__(self, surface):
self.surface = surface
def draw(self, obj):
object_... | import pygame
class Graphic:
car_color = (255, 50, 50)
car_width = 3
road_color = (255, 255, 255)
road_width = 6
draw_methods = {
'Car': 'draw_car',
'Road': 'draw_road',
}
def __init__(self, surface):
self.surface = surface
def draw(self, obj):
object_... | Make color easier to read | Make color easier to read
| Python | mit | thibault/vroom | import pygame
class Graphic:
car_color = (255, 50, 50)
car_width = 3
road_color = (255, 255, 255)
road_width = 6
draw_methods = {
'Car': 'draw_car',
'Road': 'draw_road',
}
def __init__(self, surface):
self.surface = surface
def draw(self, obj):
object_... | Make color easier to read
import pygame
class Graphic:
car_color = (255, 50, 50)
car_width = 3
road_color = (255, 255, 255)
road_width = 6
draw_methods = {
'Car': 'draw_car',
'Road': 'draw_road',
}
def __init__(self, surface):
self.surface = surface
def draw(... |
8f21fcc4611bba391761df517de8dec3c8e53d9a | scripts/data_download/rais/create_all_files.py | scripts/data_download/rais/create_all_files.py | import os
import commands
import time
import logging
import sys
if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']):
print "ERROR! Use:\n python scripts/data_download/rais/create_files.py en/pt output_path\n"
exit()
logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[... | Add file to create all files to rais. | Add file to create all files to rais.
| Python | mit | DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site | import os
import commands
import time
import logging
import sys
if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']):
print "ERROR! Use:\n python scripts/data_download/rais/create_files.py en/pt output_path\n"
exit()
logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[... | Add file to create all files to rais.
| |
3e483c2dcfd89227d9a2c56578a6532439b8fca4 | core/data/DataTransformer.py | core/data/DataTransformer.py | """
DataTransformer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:t... | Add a simple transform helper class. | Add a simple transform helper class.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop | """
DataTransformer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:t... | Add a simple transform helper class.
| |
d0fb729183f702711127b63b1e0898a9a601a7f4 | bitbucket/tests/private/private.py | bitbucket/tests/private/private.py | # -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
... | # -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
... | Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods. | Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods.
Signed-off-by: Baptiste Millou <1cfd48a9a65a966defdcd720f66cd790094000c4@smoothie-creative.com>
| Python | isc | robwilkerson/BitBucket-api,wadevries/BitBucket-api,chaiapodi/BitBucket-api,affinitic/BitBucket-api,Sheeprider/BitBucket-api,CBitLabs/BitBucket-api,Sheeprider/BitBucket-api,kubilayeksioglu/BitBucket-api,chaiapodi/BitBucket-api | # -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD
TEST_REPO_SLUG = 'test_bitbucket_api'
class AuthenticatedBitbucketTest(unittest.TestCase):
""" Bitbucket test base class for authenticated methods."""
def setUp(self):
... | Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods.
Signed-off-by: Baptiste Millou <1cfd48a9a65a966defdcd720f66cd790094000c4@smoothie-creative.com>
# -*- coding: utf-8 -*-
import unittest
from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSW... |
95da47010839da430223700345e07078b2157131 | evewspace/account/models.py | evewspace/account/models.py | from django.db import models
from django.contrib.auth.models import User, Group
from evewspace.Map.models import Map
from django.db.models.signals import post_save
# Create your models here.
class UserProfile(models.Model):
"""UserProfile defines custom fields tied to each User record in the Django auth DB."... | from django.db import models
from django.contrib.auth.models import User, Group
from evewspace.Map.models import Map
from django.db.models.signals import post_save
# Create your models here.
class PlayTime(models.Model):
"""PlayTime represents a choice of play times for use in several forms."""
fromtime = ... | Add PlayTime class and tie it to user profiles | Add PlayTime class and tie it to user profiles
Created a PlayTime class in account with from and to times.
Added ManyToManyField to UserProfile to keep track of play times.
| Python | apache-2.0 | evewspace/eve-wspace,Maarten28/eve-wspace,proycon/eve-wspace,gpapaz/eve-wspace,Unsettled/eve-wspace,acdervis/eve-wspace,Unsettled/eve-wspace,marbindrakon/eve-wspace,hybrid1969/eve-wspace,Unsettled/eve-wspace,acdervis/eve-wspace,marbindrakon/eve-wspace,Maarten28/eve-wspace,mmalyska/eve-wspace,acdervis/eve-wspace,nyrocro... | from django.db import models
from django.contrib.auth.models import User, Group
from evewspace.Map.models import Map
from django.db.models.signals import post_save
# Create your models here.
class PlayTime(models.Model):
"""PlayTime represents a choice of play times for use in several forms."""
fromtime = ... | Add PlayTime class and tie it to user profiles
Created a PlayTime class in account with from and to times.
Added ManyToManyField to UserProfile to keep track of play times.
from django.db import models
from django.contrib.auth.models import User, Group
from evewspace.Map.models import Map
from django.db.models.sig... |
799d6738bd189fa202f45c10e7b5361f71f14c57 | bin/request_domain.py | bin/request_domain.py | #!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""
import requests, sys, json
otp = sys.argv[1]
domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'
print('retrieving domain for bli... | #!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""
import requests, sys, json
otp = sys.argv[1]
domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'
print('retrieving domain for bli... | Clarify error if otp is wrong | Clarify error if otp is wrong | Python | agpl-3.0 | cloudfleet/blimp-engineroom,cloudfleet/blimp-engineroom | #!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""
import requests, sys, json
otp = sys.argv[1]
domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'
print('retrieving domain for bli... | Clarify error if otp is wrong
#!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""
import requests, sys, json
otp = sys.argv[1]
domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'
pr... |
ed350a7387c376538f51a8a7a8cfde5469baba8a | tests/testutils.py | tests/testutils.py | import psycopg2
import os
import getpass
def get_pg_connection():
return psycopg2.connect(
"dbname=bedquilt_test user={}".format(getpass.getuser())
)
| import psycopg2
import os
import getpass
# CREATE DATABASE bedquilt_test
# WITH OWNER = {{owner}}
# ENCODING = 'UTF8'
# TABLESPACE = pg_default
# LC_COLLATE = 'en_GB.UTF-8'
# LC_CTYPE = 'en_GB.UTF-8'
# CONNECTION LIMIT = -1;
def get_pg_connection():
return psycopg2.connect(
... | Add the sql to create the test database | Add the sql to create the test database
| Python | mit | BedquiltDB/bedquilt-core | import psycopg2
import os
import getpass
# CREATE DATABASE bedquilt_test
# WITH OWNER = {{owner}}
# ENCODING = 'UTF8'
# TABLESPACE = pg_default
# LC_COLLATE = 'en_GB.UTF-8'
# LC_CTYPE = 'en_GB.UTF-8'
# CONNECTION LIMIT = -1;
def get_pg_connection():
return psycopg2.connect(
... | Add the sql to create the test database
import psycopg2
import os
import getpass
def get_pg_connection():
return psycopg2.connect(
"dbname=bedquilt_test user={}".format(getpass.getuser())
)
|
bdc554d18dc67cd4979bac3bc5d4b7d01b23b8b4 | grako/rendering.py | grako/rendering.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | Allow override of template through return value of render_fields. | Allow override of template through return value of render_fields.
| Python | bsd-2-clause | swayf/grako,swayf/grako | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**f... | Allow override of template through return value of render_fields.
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
... |
1224e7e2f12b455ffa1f8c102b30012d63716cae | flask_bracket/errors.py | flask_bracket/errors.py | """API errors."""
from werkzeug.exceptions import HTTPException
class Error(Exception):
status = 500
error = "internal server error"
def __init__(self, error=None, status=None):
"""Create an API error with the given error and status code."""
self.status = status or self.__class__.status
... | """API errors."""
from werkzeug.exceptions import HTTPException
class Error(Exception):
status = 500
error = "internal server error"
def __init__(self, error=None, status=None):
"""Create an API error with the given error and status code."""
self.status = status or self.__class__.status
... | Remove redundant status code from error response body. | Remove redundant status code from error response body.
| Python | bsd-3-clause | JsonChiu/flask-bracket | """API errors."""
from werkzeug.exceptions import HTTPException
class Error(Exception):
status = 500
error = "internal server error"
def __init__(self, error=None, status=None):
"""Create an API error with the given error and status code."""
self.status = status or self.__class__.status
... | Remove redundant status code from error response body.
"""API errors."""
from werkzeug.exceptions import HTTPException
class Error(Exception):
status = 500
error = "internal server error"
def __init__(self, error=None, status=None):
"""Create an API error with the given error and status code."""... |
d030e9bfaf8cd4f83d0db7728f4f546c48bd8934 | harness/ext/SciKit.py | harness/ext/SciKit.py |
# coding: utf-8
# A jinja extension for the harness
# In[9]:
try:
from .base import HarnessExtension
except:
from base import HarnessExtension
import pandas, sklearn.model_selection as model_selection
from toolz.curried import first
# In[11]:
get_ipython().magic('pinfo2 model_selection.ShuffleSplit')
... |
# coding: utf-8
# A jinja extension for the harness
# In[9]:
try:
from .base import HarnessExtension
except:
from base import HarnessExtension
import pandas, sklearn.model_selection as model_selection
from toolz.curried import first
# In[10]:
class SciKitExtension(HarnessExtension):
alias = 'sklearn... | Fix error message in the scikitlearn extension. | Fix error message in the scikitlearn extension.
| Python | bsd-3-clause | tonyfast/tidy-harness,tonyfast/tidy-harness |
# coding: utf-8
# A jinja extension for the harness
# In[9]:
try:
from .base import HarnessExtension
except:
from base import HarnessExtension
import pandas, sklearn.model_selection as model_selection
from toolz.curried import first
# In[10]:
class SciKitExtension(HarnessExtension):
alias = 'sklearn... | Fix error message in the scikitlearn extension.
# coding: utf-8
# A jinja extension for the harness
# In[9]:
try:
from .base import HarnessExtension
except:
from base import HarnessExtension
import pandas, sklearn.model_selection as model_selection
from toolz.curried import first
# In[11]:
get_ipython(... |
fc73dfb33f4e19d649672f19a1dc4cf09b229d29 | echo_server.py | echo_server.py | #! /usr/bin/env python
"""Echo server in socket connection: receives and sends back a message."""
import socket
if __name__ == '__main__':
"""Run from terminal, this will recieve a messages and send them back."""
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
... | #! /usr/bin/env python
"""Echo server in socket connection: receives and sends back a message."""
import socket
def response_ok():
"""Return byte string 200 ok response."""
return u"HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-length: 18\n\r\neverything is okay".encode('utf-8')
def reponse_error(error... | Add response_ok and response_error methods which return byte strings. | Add response_ok and response_error methods which return byte strings.
| Python | mit | bm5w/network_tools | #! /usr/bin/env python
"""Echo server in socket connection: receives and sends back a message."""
import socket
def response_ok():
"""Return byte string 200 ok response."""
return u"HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-length: 18\n\r\neverything is okay".encode('utf-8')
def reponse_error(error... | Add response_ok and response_error methods which return byte strings.
#! /usr/bin/env python
"""Echo server in socket connection: receives and sends back a message."""
import socket
if __name__ == '__main__':
"""Run from terminal, this will recieve a messages and send them back."""
server_socket = socket.soc... |
957422118d31def826d336f26152de1d0399fe4e | py/src/ai/h2o/sparkling/H2OConf.py | py/src/ai/h2o/sparkling/H2OConf.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument | [SW-1971][FollowUp] Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument
| Python | apache-2.0 | h2oai/sparkling-water,h2oai/sparkling-water,h2oai/sparkling-water,h2oai/sparkling-water | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | [SW-1971][FollowUp] Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright owners... |
a5b3e991d128693e0d1f1ed6892c9c1c4a507a3d | src/apps/processing/ala/management/commands/ala_import.py | src/apps/processing/ala/management/commands/ala_import.py | import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Import data from ALA stations, optionally you can pass date.... | import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Import data from ALA stations, optionally you can pass date.... | Make default ALA's date the day before yesterday | Make default ALA's date the day before yesterday
| Python | bsd-3-clause | gis4dis/poster,gis4dis/poster,gis4dis/poster | import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Import data from ALA stations, optionally you can pass date.... | Make default ALA's date the day before yesterday
import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Import dat... |
14dcd8789c764743cfcb2e7a7b9b7d33b21a2779 | fluent_blogs/models/managers.py | fluent_blogs/models/managers.py | """
The manager class for the CMS models
"""
from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
class EntryQuerySet(QuerySet):
def published(self):
"""
Return only published entries
"""
f... | """
The manager class for the CMS models
"""
from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
class EntryQuerySet(QuerySet):
def published(self):
"""
Return only published entries
"""
f... | Fix .published() to accept current date as well. | Fix .published() to accept current date as well.
| Python | apache-2.0 | edoburu/django-fluent-blogs,edoburu/django-fluent-blogs | """
The manager class for the CMS models
"""
from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
class EntryQuerySet(QuerySet):
def published(self):
"""
Return only published entries
"""
f... | Fix .published() to accept current date as well.
"""
The manager class for the CMS models
"""
from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
class EntryQuerySet(QuerySet):
def published(self):
"""
R... |
17e26fa55e70de657d52e340cb6b66691310a663 | bettertexts/forms.py | bettertexts/forms.py | from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
... | from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
... | Fix checkboxes inform and involved | CL011: Fix checkboxes inform and involved
| Python | mit | citizenline/citizenline,citizenline/citizenline,citizenline/citizenline,citizenline/citizenline | from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentForm, self).__init__(*args, **kwargs)
... | CL011: Fix checkboxes inform and involved
from django_comments.forms import CommentForm
from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment
class TextCommentForm(CommentForm):
def __init__(self, *args, **kwargs):
super(TextCommentF... |
6b0774eab70c42fbdd28869b6bcdab9b81183b8e | run_tests.py | run_tests.py | #!/usr/bin/env python
# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
from bluesky.testing.noseclasses import KnownFailure
import pytest
try:
from pcaspy import Driver, SimpleServer
from multiprocessing import Process
def to_subproc():
prefix = 'BSTEST:'
pv... | #!/usr/bin/env python
# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
import pytest
try:
from pcaspy import Driver, SimpleServer
from multiprocessing import Process
def to_subproc():
prefix = 'BSTEST:'
pvdb = {
'VAL': {
'prec': 3... | Remove deleted subpackage. Add better args to pytest | TST: Remove deleted subpackage. Add better args to pytest
| Python | bsd-3-clause | ericdill/bluesky,ericdill/bluesky | #!/usr/bin/env python
# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
import pytest
try:
from pcaspy import Driver, SimpleServer
from multiprocessing import Process
def to_subproc():
prefix = 'BSTEST:'
pvdb = {
'VAL': {
'prec': 3... | TST: Remove deleted subpackage. Add better args to pytest
#!/usr/bin/env python
# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
from bluesky.testing.noseclasses import KnownFailure
import pytest
try:
from pcaspy import Driver, SimpleServer
from multiprocessing import Process
... |
0ca727f0ce5877ba2ca3ef74c9309c752a51fbf6 | src/sentry/web/frontend/project_plugin_enable.py | src/sentry/web/frontend/project_plugin_enable.py | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView
class ProjectPluginEnableView(ProjectView):
required_scope = 'project:write'
def post(self, request, organization, team, project, slug):
... | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView
class ProjectPluginEnableView(ProjectView):
required_scope = 'project:write'
def post(self, request, organization, team, project, slug):
... | Fix enable action on plugins | Fix enable action on plugins
| Python | bsd-3-clause | looker/sentry,looker/sentry,jean/sentry,ifduyue/sentry,jean/sentry,BuildingLink/sentry,fotinakis/sentry,zenefits/sentry,BuildingLink/sentry,jean/sentry,fotinakis/sentry,daevaorn/sentry,looker/sentry,alexm92/sentry,fotinakis/sentry,beeftornado/sentry,JackDanger/sentry,nicholasserra/sentry,BuildingLink/sentry,mvaled/sent... | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView
class ProjectPluginEnableView(ProjectView):
required_scope = 'project:write'
def post(self, request, organization, team, project, slug):
... | Fix enable action on plugins
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView
class ProjectPluginEnableView(ProjectView):
required_scope = 'project:write'
def post(self, request, organiza... |
86fa8271b5788aadcbbde3decbcd413b9d22871c | util/namespace.py | util/namespace.py | """
Stuff for building namespace
"""
from _compat import *
class Namespace(object):
"""
Backport of SimpleNamespace() class added in Python 3.3
"""
__slots__ = '__doc__', '__dict__', '__weakref__'
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __iter__(self):
... | """
Stuff for building namespace
"""
from _compat import *
class Namespace(object):
"""
Backport of SimpleNamespace() class added in Python 3.3
"""
__slots__ = '__doc__', '__dict__', '__weakref__'
def __init__(self, **kwargs):
super(Namespace, self).__init__()
self.__dict__.update... | Call super __init__ from Namespace.__init__ | util: Call super __init__ from Namespace.__init__
| Python | unknown | embox/mybuild,abusalimov/mybuild,embox/mybuild,abusalimov/mybuild | """
Stuff for building namespace
"""
from _compat import *
class Namespace(object):
"""
Backport of SimpleNamespace() class added in Python 3.3
"""
__slots__ = '__doc__', '__dict__', '__weakref__'
def __init__(self, **kwargs):
super(Namespace, self).__init__()
self.__dict__.update... | util: Call super __init__ from Namespace.__init__
"""
Stuff for building namespace
"""
from _compat import *
class Namespace(object):
"""
Backport of SimpleNamespace() class added in Python 3.3
"""
__slots__ = '__doc__', '__dict__', '__weakref__'
def __init__(self, **kwargs):
self.__dict... |
ff0ae66ee16bc3ac07cb88ddacb52ffa41779757 | tests/test_func.py | tests/test_func.py | from .utils import assert_eval
def test_simple_func():
assert_eval('(def @a $a 8) (@a)', 1, 8)
def test_simple_func_args():
assert_eval(
'(def @a $a $a)'
'(@a 1)'
'(@a 2)'
'(@a 5)',
1,
1,
2,
5)
def test_func_args_overwrite_globals():
asse... | from .utils import assert_eval
def test_simple_func():
assert_eval('(def @a $a 8) (@a)', 1, 8)
def test_simple_func_args():
assert_eval(
'(def @a $a $a)'
'(@a 1)'
'(@a 2)'
'(@a 5)',
1,
1,
2,
5)
def test_func_args_overwrite_globals():
asse... | Add some more function tests. | Add some more function tests.
| Python | bsd-3-clause | sapir/tinywhat,sapir/tinywhat,sapir/tinywhat | from .utils import assert_eval
def test_simple_func():
assert_eval('(def @a $a 8) (@a)', 1, 8)
def test_simple_func_args():
assert_eval(
'(def @a $a $a)'
'(@a 1)'
'(@a 2)'
'(@a 5)',
1,
1,
2,
5)
def test_func_args_overwrite_globals():
asse... | Add some more function tests.
from .utils import assert_eval
def test_simple_func():
assert_eval('(def @a $a 8) (@a)', 1, 8)
def test_simple_func_args():
assert_eval(
'(def @a $a $a)'
'(@a 1)'
'(@a 2)'
'(@a 5)',
1,
1,
2,
5)
def test_func_arg... |
9f5adef59a8065f0524cc9c16c2ddc46e46f57cc | google-stt.py | google-stt.py | from scikits.samplerate import resample
from tempfile import mkstemp
from os import remove
import scikits.audiolab as audiolab
# if you want make the down sample rate using scipy.signal
#import scipy.signal
import urllib2
import sys
if len(sys.argv)<2 :
print 'Usage: %s <audio file.wav>' %sys.argv[0]
s... | Add google speech to text sample | Add google speech to text sample | Python | mit | voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts | from scikits.samplerate import resample
from tempfile import mkstemp
from os import remove
import scikits.audiolab as audiolab
# if you want make the down sample rate using scipy.signal
#import scipy.signal
import urllib2
import sys
if len(sys.argv)<2 :
print 'Usage: %s <audio file.wav>' %sys.argv[0]
s... | Add google speech to text sample
| |
b077df615eb4354f416877cc2857fb9848e158eb | saleor/core/templatetags/shop.py | saleor/core/templatetags/shop.py | from __future__ import unicode_literals
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
from django.template import Library
from django.utils.http import urlencode
register = Library()
@register.filter
def slice(items, group_size=1):
args = [... | from __future__ import unicode_literals
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
from django.template import Library
from django.utils.http import urlencode
register = Library()
@register.filter
def slice(items, group_size=1):
args = [... | Fix get_sort_by_toggle to work with QueryDicts with multiple values | Fix get_sort_by_toggle to work with QueryDicts with multiple values
| Python | bsd-3-clause | UITools/saleor,mociepka/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,UITools/saleor | from __future__ import unicode_literals
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
from django.template import Library
from django.utils.http import urlencode
register = Library()
@register.filter
def slice(items, group_size=1):
args = [... | Fix get_sort_by_toggle to work with QueryDicts with multiple values
from __future__ import unicode_literals
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
from django.template import Library
from django.utils.http import urlencode
register = Libr... |
ac84d8743b50a00c49a8ceb81ed69661841bce70 | wagtail/core/middleware.py | wagtail/core/middleware.py | import warnings
from django.utils.deprecation import MiddlewareMixin
from wagtail.core.models import Site
from wagtail.utils.deprecation import RemovedInWagtail28Warning
class SiteMiddleware(MiddlewareMixin):
def process_request(self, request):
"""
Set request.site to contain the Site object resp... | import warnings
from django.utils.deprecation import MiddlewareMixin
from wagtail.core.models import Site
from wagtail.utils.deprecation import RemovedInWagtail211Warning
class SiteMiddleware(MiddlewareMixin):
def process_request(self, request):
"""
Set request.site to contain the Site object res... | Revert SiteMiddleware to setting request.site | Revert SiteMiddleware to setting request.site
This way, SiteMiddleware continues to support existing user / third-party code that has not yet been migrated from request.site to Site.find_for_request
| Python | bsd-3-clause | takeflight/wagtail,takeflight/wagtail,thenewguy/wagtail,thenewguy/wagtail,timorieber/wagtail,wagtail/wagtail,gasman/wagtail,takeflight/wagtail,kaedroho/wagtail,mixxorz/wagtail,wagtail/wagtail,timorieber/wagtail,kaedroho/wagtail,kaedroho/wagtail,rsalmaso/wagtail,rsalmaso/wagtail,FlipperPA/wagtail,thenewguy/wagtail,mixxo... | import warnings
from django.utils.deprecation import MiddlewareMixin
from wagtail.core.models import Site
from wagtail.utils.deprecation import RemovedInWagtail211Warning
class SiteMiddleware(MiddlewareMixin):
def process_request(self, request):
"""
Set request.site to contain the Site object res... | Revert SiteMiddleware to setting request.site
This way, SiteMiddleware continues to support existing user / third-party code that has not yet been migrated from request.site to Site.find_for_request
import warnings
from django.utils.deprecation import MiddlewareMixin
from wagtail.core.models import Site
from wagtail... |
b8598cf14e2c9d0be404082c0761b4abecf7f97d | bioagents/resources/make_trips_ontology.py | bioagents/resources/make_trips_ontology.py | import os
import sys
import xml.etree.ElementTree as ET
from rdflib import Graph, Namespace, Literal
trips_ns = Namespace('http://trips.ihmc.us/concepts/')
isa_rel = Namespace('http://trips.ihmc.us/relations/').term('isa')
def save_hierarchy(g, path):
with open(path, 'wb') as out_file:
g_bytes = g.seria... | Implement script to make TRIPS ontology | Implement script to make TRIPS ontology
| Python | bsd-2-clause | sorgerlab/bioagents,bgyori/bioagents | import os
import sys
import xml.etree.ElementTree as ET
from rdflib import Graph, Namespace, Literal
trips_ns = Namespace('http://trips.ihmc.us/concepts/')
isa_rel = Namespace('http://trips.ihmc.us/relations/').term('isa')
def save_hierarchy(g, path):
with open(path, 'wb') as out_file:
g_bytes = g.seria... | Implement script to make TRIPS ontology
| |
4dceb440069d63133bffe928b5c8aa756574a41c | lowfat/validator.py | lowfat/validator.py | """
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.urlopen(url)
except HTTPError as excepti... | """
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.urlopen(url)
except HTTPError as excepti... | Fix problem with sites that blocks bots | Fix problem with sites that blocks bots
| Python | bsd-3-clause | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat | """
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.urlopen(url)
except HTTPError as excepti... | Fix problem with sites that blocks bots
"""
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.url... |
e615855f6ea90e63df3eb2ff42f79afa0329ae01 | migrations/versions/dceb6cd3c41e_.py | migrations/versions/dceb6cd3c41e_.py | """Add policycondition table, remove unused condition column from policy table
Revision ID: dceb6cd3c41e
Revises: b9131d0686eb
Create Date: 2019-07-02 12:19:19.646528
"""
# revision identifiers, used by Alembic.
revision = 'dceb6cd3c41e'
down_revision = 'b9131d0686eb'
from alembic import op, context
import sqlalche... | Add migration script for policycondition table | Add migration script for policycondition table
| Python | agpl-3.0 | privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea,privacyidea/privacyidea | """Add policycondition table, remove unused condition column from policy table
Revision ID: dceb6cd3c41e
Revises: b9131d0686eb
Create Date: 2019-07-02 12:19:19.646528
"""
# revision identifiers, used by Alembic.
revision = 'dceb6cd3c41e'
down_revision = 'b9131d0686eb'
from alembic import op, context
import sqlalche... | Add migration script for policycondition table
| |
fdfa3aae605eaadf099c6d80c86a9406f34fb71c | bluebottle/organizations/urls/api.py | bluebottle/organizations/urls/api.py | from django.conf.urls import url
from bluebottle.organizations.views import (
OrganizationList, OrganizationDetail,
OrganizationContactList, OrganizationContactDetail
)
urlpatterns = [
url(r'^$', OrganizationList.as_view(), name='organization_list'),
url(r'^/(?P<pk>\d+)$', OrganizationDetail.as_view()... | from django.conf.urls import url
from bluebottle.organizations.views import (
OrganizationList, OrganizationDetail,
OrganizationContactList, OrganizationContactDetail
)
urlpatterns = [
url(r'^$', OrganizationList.as_view(), name='organization_list'),
url(r'^/(?P<pk>\d+)$', OrganizationDetail.as_view()... | Fix organization-contact url having an extra slash | Fix organization-contact url having an extra slash
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | from django.conf.urls import url
from bluebottle.organizations.views import (
OrganizationList, OrganizationDetail,
OrganizationContactList, OrganizationContactDetail
)
urlpatterns = [
url(r'^$', OrganizationList.as_view(), name='organization_list'),
url(r'^/(?P<pk>\d+)$', OrganizationDetail.as_view()... | Fix organization-contact url having an extra slash
from django.conf.urls import url
from bluebottle.organizations.views import (
OrganizationList, OrganizationDetail,
OrganizationContactList, OrganizationContactDetail
)
urlpatterns = [
url(r'^$', OrganizationList.as_view(), name='organization_list'),
... |
f2000016a9e2acd4cad28b1ea301620723140a4e | sheldon/bot.py | sheldon/bot.py | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
from sheldon.utils import logger
... | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
from sheldon.utils import logger
... | Change error status with config problems to critical | Change error status with config problems to critical
| Python | mit | lises/sheldon | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
from sheldon.utils import logger
... | Change error status with config problems to critical
# -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheld... |
9870fdd4b0996254216ff85a4dc0f9706843ca50 | tests/basics/while_nest_exc.py | tests/basics/while_nest_exc.py | # test nested whiles within a try-except
while 1:
print(1)
try:
print(2)
while 1:
print(3)
break
except:
print(4)
print(5)
break
| Add test for nested while with exc and break. | tests: Add test for nested while with exc and break.
| Python | mit | ruffy91/micropython,jmarcelino/pycom-micropython,henriknelson/micropython,puuu/micropython,neilh10/micropython,xuxiaoxin/micropython,utopiaprince/micropython,cwyark/micropython,aethaniel/micropython,tuc-osg/micropython,vitiral/micropython,orionrobots/micropython,noahchense/micropython,paul-xxx/micropython,ganshun666/mi... | # test nested whiles within a try-except
while 1:
print(1)
try:
print(2)
while 1:
print(3)
break
except:
print(4)
print(5)
break
| tests: Add test for nested while with exc and break.
| |
4fb24d18cefc76b8622b53427a064fc430b9bfee | tests/test_search.py | tests/test_search.py | from . import TestCase
from memopol.search.templatetags.search_tags import simple_search_shortcut
class TestSearchTemplateTags(TestCase):
def test_simple_search_shortcut(self):
url = simple_search_shortcut('country:FR or country:BR')
self.assertEqual(url, "/search/?q=country%3AFR%20or%20country%3... | Add a basic test for simple_search_shortcut templatetag | [enh] Add a basic test for simple_search_shortcut templatetag
| Python | agpl-3.0 | yohanboniface/memopol-core,yohanboniface/memopol-core,yohanboniface/memopol-core | from . import TestCase
from memopol.search.templatetags.search_tags import simple_search_shortcut
class TestSearchTemplateTags(TestCase):
def test_simple_search_shortcut(self):
url = simple_search_shortcut('country:FR or country:BR')
self.assertEqual(url, "/search/?q=country%3AFR%20or%20country%3... | [enh] Add a basic test for simple_search_shortcut templatetag
| |
6cb38efab37f8953c8ba56662ba512af0f84432f | tests/semver_test.py | tests/semver_test.py | # -*- coding: utf-8 -*-
from unittest import TestCase
from semver import compare
from semver import match
from semver import parse
class TestSemver(TestCase):
def test_should_parse_version(self):
self.assertEquals(
parse("1.2.3-alpha.1.2+build.11.e0f985a"),
{'major': 1,
... | # -*- coding: utf-8 -*-
from unittest import TestCase
from semver import compare
from semver import match
from semver import parse
class TestSemver(TestCase):
def test_should_parse_version(self):
self.assertEquals(
parse("1.2.3-alpha.1.2+build.11.e0f985a"),
{'major': 1,
... | Add tests for error cases that proves incompatibility with Python 2.5 and early versions. | Add tests for error cases that proves incompatibility with Python 2.5 and early versions.
| Python | bsd-3-clause | python-semver/python-semver,k-bx/python-semver | # -*- coding: utf-8 -*-
from unittest import TestCase
from semver import compare
from semver import match
from semver import parse
class TestSemver(TestCase):
def test_should_parse_version(self):
self.assertEquals(
parse("1.2.3-alpha.1.2+build.11.e0f985a"),
{'major': 1,
... | Add tests for error cases that proves incompatibility with Python 2.5 and early versions.
# -*- coding: utf-8 -*-
from unittest import TestCase
from semver import compare
from semver import match
from semver import parse
class TestSemver(TestCase):
def test_should_parse_version(self):
self.assertEquals... |
23f2306617a4e4bceecd20190c328b2b3418abc4 | setup.py | setup.py | #! /usr/bin/python
"""Setuptools-based setup script for datreant.
For a basic installation just type the command::
python setup.py install
"""
from setuptools import setup
setup(name='datreant',
version='0.5.1',
author='David Dotson',
author_email='dotsdl@gmail.com',
packages=['datreant'... | #! /usr/bin/python
"""Setuptools-based setup script for datreant.
For a basic installation just type the command::
python setup.py install
"""
from setuptools import setup
setup(name='datreant',
version='0.5.1',
author='David Dotson',
author_email='dotsdl@gmail.com',
packages=['datreant',... | Add PyYAML & numpy dependency | Add PyYAML & numpy dependency
I'm adding numpy too because we import it directly.
| Python | bsd-3-clause | datreant/datreant,dotsdl/datreant,datreant/datreant.core,datreant/datreant.core,datreant/datreant,datreant/datreant.data | #! /usr/bin/python
"""Setuptools-based setup script for datreant.
For a basic installation just type the command::
python setup.py install
"""
from setuptools import setup
setup(name='datreant',
version='0.5.1',
author='David Dotson',
author_email='dotsdl@gmail.com',
packages=['datreant',... | Add PyYAML & numpy dependency
I'm adding numpy too because we import it directly.
#! /usr/bin/python
"""Setuptools-based setup script for datreant.
For a basic installation just type the command::
python setup.py install
"""
from setuptools import setup
setup(name='datreant',
version='0.5.1',
autho... |
cc55521c1e2af71893eff701bebc51acc112fa75 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
... | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
... | Update requests requirement from <2.24,>=2.4.2 to >=2.4.2,<2.25 | Update requests requirement from <2.24,>=2.4.2 to >=2.4.2,<2.25
Updates the requirements on [requests](https://github.com/psf/requests) to permit the latest version.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md)
- [Commits](https://git... | Python | apache-2.0 | zooniverse/panoptes-python-client | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
... | Update requests requirement from <2.24,>=2.4.2 to >=2.4.2,<2.25
Updates the requirements on [requests](https://github.com/psf/requests) to permit the latest version.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md)
- [Commits](https://git... |
a5cc18bab108f83ab45073272fa467fc62a2649b | run_python_tests.py | run_python_tests.py | #!/usr/bin/python
import os
import optparse
import sys
import unittest
USAGE = """%prog SDK_PATH TEST_PATH
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation.
TEST_PATH Path to package containing test modules.
WEBTEST_PATH Path to the webtest library."""
def main(sdk_path, test_path, ... | #!/usr/bin/python
import os
import optparse
import sys
import unittest
USAGE = """%prog SDK_PATH TEST_PATH
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation.
TEST_PATH Path to package containing test modules.
WEBTEST_PATH Path to the webtest library."""
def main(sdk_path, test_path, ... | Revert "Python tests now return an error code on fail." | Revert "Python tests now return an error code on fail."
| Python | bsd-3-clause | pquochoang/samples,jiayliu/apprtc,todotobe1/apprtc,jan-ivar/adapter,82488059/apprtc,shelsonjava/apprtc,procandi/apprtc,4lejandrito/adapter,overtakermtg/samples,mvenkatesh431/samples,JiYou/apprtc,martin7890/samples,Zauberstuhl/adapter,TribeMedia/samples,jiayliu/apprtc,bpyoung92/apprtc,aadebuger/docker-apprtc,xdumaine/ad... | #!/usr/bin/python
import os
import optparse
import sys
import unittest
USAGE = """%prog SDK_PATH TEST_PATH
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation.
TEST_PATH Path to package containing test modules.
WEBTEST_PATH Path to the webtest library."""
def main(sdk_path, test_path, ... | Revert "Python tests now return an error code on fail."
#!/usr/bin/python
import os
import optparse
import sys
import unittest
USAGE = """%prog SDK_PATH TEST_PATH
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation.
TEST_PATH Path to package containing test modules.
WEBTEST_PATH Path to... |
83b060b573bee654708e5fbb41c9e3b2913e4d9c | generatechangedfilelist.py | generatechangedfilelist.py | import sys
import os
import commands
import fnmatch
import re
import subprocess, shlex
def cmdsplit(args):
if os.sep == '\\':
args = args.replace('\\', '\\\\')
return shlex.split(args)
def main():
md5dir = os.path.abspath(sys.argv[1])
list_file = os.path.abspath(sys.argv[2])
prelist = os.p... | import sys
import os
import commands
import fnmatch
import re
import subprocess, shlex
mcp_root = os.path.abspath(sys.argv[1])
sys.path.append(os.path.join(mcp_root,"runtime"))
from filehandling.srgshandler import parse_srg
def cmdsplit(args):
if os.sep == '\\':
args = args.replace('\\', '\\\\')
retur... | Tweak file list script to print obf names | Tweak file list script to print obf names
| Python | lgpl-2.1 | MinecraftForge/FML,aerospark/FML,aerospark/FML,aerospark/FML | import sys
import os
import commands
import fnmatch
import re
import subprocess, shlex
mcp_root = os.path.abspath(sys.argv[1])
sys.path.append(os.path.join(mcp_root,"runtime"))
from filehandling.srgshandler import parse_srg
def cmdsplit(args):
if os.sep == '\\':
args = args.replace('\\', '\\\\')
retur... | Tweak file list script to print obf names
import sys
import os
import commands
import fnmatch
import re
import subprocess, shlex
def cmdsplit(args):
if os.sep == '\\':
args = args.replace('\\', '\\\\')
return shlex.split(args)
def main():
md5dir = os.path.abspath(sys.argv[1])
list_file = os.p... |
c784fb30beac7abe958867345161f74876ca940d | causalinfo/__init__.py | causalinfo/__init__.py | from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
... | from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
... | Fix silly boiler plate copy issue. | Fix silly boiler plate copy issue.
| Python | mit | brettc/causalinfo | from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ = "0.1.0"
__title__ = "causalinfo"
... | Fix silly boiler plate copy issue.
from .probability import (
vs,
Variable,
make_variables,
UniformDist,
JointDist,
JointDistByState
)
from .network import CausalGraph, Equation
from .measure import MeasureCause, MeasureSuccess
from .payoff import PayoffMatrix
import equations
__version__ ... |
98b6f81f68ce4338e932afc14b7b9d4c8a810e71 | src/dirtyfields/dirtyfields.py | src/dirtyfields/dirtyfields.py | # Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
post_save.connect(reset_state, sender=self.__cl... | # Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
post_save.connect(reset_state, sender=self.__cl... | Use field.to_python to do django type conversions on the field before checking if dirty. | Use field.to_python to do django type conversions on the field before checking if dirty.
This solves issues where you might have a decimal field that you write a string to, eg:
>>> m = MyModel.objects.get(id=1)
>>> m.my_decimal_field
Decimal('1.00')
>>> m.my_decimal_field = u'1.00' # from a form or something
>>> m.is_... | Python | bsd-3-clause | mattcaldwell/django-dirtyfields,georgemarshall/django-dirtyfields | # Adapted from http://stackoverflow.com/questions/110803/dirty-fields-in-django
from django.db.models.signals import post_save
class DirtyFieldsMixin(object):
def __init__(self, *args, **kwargs):
super(DirtyFieldsMixin, self).__init__(*args, **kwargs)
post_save.connect(reset_state, sender=self.__cl... | Use field.to_python to do django type conversions on the field before checking if dirty.
This solves issues where you might have a decimal field that you write a string to, eg:
>>> m = MyModel.objects.get(id=1)
>>> m.my_decimal_field
Decimal('1.00')
>>> m.my_decimal_field = u'1.00' # from a form or something
>>> m.is_... |
4bf955998c6f25d79105de067ceaa74a5023385c | bot/action/standard/asynchronous.py | bot/action/standard/asynchronous.py | from bot.action.core.action import IntermediateAction
from bot.multithreading.work import Work
class AsynchronousAction(IntermediateAction):
def __init__(self, name: str, min_workers: int = 1, max_workers: int = 4, max_seconds_idle: int = 15):
super().__init__()
self.name = name
self.min_w... | from bot.action.core.action import IntermediateAction
from bot.multithreading.work import Work
class AsynchronousAction(IntermediateAction):
def __init__(self, name: str, min_workers: int = 0, max_workers: int = 4, max_seconds_idle: int = 60):
super().__init__()
self.name = name
self.min_w... | Update AsynchronousAction default values of min_workers to 0 and max_seconds_idle to 60 | Update AsynchronousAction default values of min_workers to 0 and max_seconds_idle to 60
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | from bot.action.core.action import IntermediateAction
from bot.multithreading.work import Work
class AsynchronousAction(IntermediateAction):
def __init__(self, name: str, min_workers: int = 0, max_workers: int = 4, max_seconds_idle: int = 60):
super().__init__()
self.name = name
self.min_w... | Update AsynchronousAction default values of min_workers to 0 and max_seconds_idle to 60
from bot.action.core.action import IntermediateAction
from bot.multithreading.work import Work
class AsynchronousAction(IntermediateAction):
def __init__(self, name: str, min_workers: int = 1, max_workers: int = 4, max_second... |
c8a0279d421c2837e4f7e4ef1eaf2cc9cb94210c | scripts/mkstdlibs.py | scripts/mkstdlibs.py | #!/usr/bin/env python3
from sphinx.ext.intersphinx import fetch_inventory
URL = "https://docs.python.org/{}/objects.inv"
PATH = "isort/stdlibs/py{}.py"
VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8")]
DOCSTRING = """
File contains the standard library of Python {}.
DO NOT EDIT. If the standar... | #!/usr/bin/env python3
from sphinx.ext.intersphinx import fetch_inventory
URL = "https://docs.python.org/{}/objects.inv"
PATH = "isort/stdlibs/py{}.py"
VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8"), ("3", "9")]
DOCSTRING = """
File contains the standard library of Python {}.
DO NOT EDIT. If... | Update script to include empty user agent | Update script to include empty user agent
| Python | mit | PyCQA/isort,PyCQA/isort | #!/usr/bin/env python3
from sphinx.ext.intersphinx import fetch_inventory
URL = "https://docs.python.org/{}/objects.inv"
PATH = "isort/stdlibs/py{}.py"
VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8"), ("3", "9")]
DOCSTRING = """
File contains the standard library of Python {}.
DO NOT EDIT. If... | Update script to include empty user agent
#!/usr/bin/env python3
from sphinx.ext.intersphinx import fetch_inventory
URL = "https://docs.python.org/{}/objects.inv"
PATH = "isort/stdlibs/py{}.py"
VERSIONS = [("2", "7"), ("3", "5"), ("3", "6"), ("3", "7"), ("3", "8")]
DOCSTRING = """
File contains the standard library... |
d59f3259875ffac49668ffb3ce34ca511385ebb7 | rated/settings.py | rated/settings.py |
from django.conf import settings
DEFAULT_REALM = getattr(settings, 'RATED_DEFAULT_REALM', 'default')
DEFAULT_LIMIT = getattr(settings, 'RATED_DEFAULT_LIMIT', 100)
DEFAULT_DURATION = getattr(settings, 'RATED_DEFAULT_DURATION', 60 * 60)
RESPONSE_CODE = getattr(settings, 'RATED_RESPONSE_CODE', 429)
RESPONSE_MESSAGE = g... |
from django.conf import settings
DEFAULT_REALM = getattr(settings, 'RATED_DEFAULT_REALM', 'default')
DEFAULT_LIMIT = getattr(settings, 'RATED_DEFAULT_LIMIT', 100)
DEFAULT_DURATION = getattr(settings, 'RATED_DEFAULT_DURATION', 60 * 60)
RESPONSE_CODE = getattr(settings, 'RATED_RESPONSE_CODE', 429)
RESPONSE_MESSAGE = g... | Fix USE_X_FORWARDED_FOR for proxied environments | Fix USE_X_FORWARDED_FOR for proxied environments
The settings for USE_X_FORWARDED_FOR were not being respected because the settings were not being passed through. | Python | bsd-3-clause | funkybob/django-rated |
from django.conf import settings
DEFAULT_REALM = getattr(settings, 'RATED_DEFAULT_REALM', 'default')
DEFAULT_LIMIT = getattr(settings, 'RATED_DEFAULT_LIMIT', 100)
DEFAULT_DURATION = getattr(settings, 'RATED_DEFAULT_DURATION', 60 * 60)
RESPONSE_CODE = getattr(settings, 'RATED_RESPONSE_CODE', 429)
RESPONSE_MESSAGE = g... | Fix USE_X_FORWARDED_FOR for proxied environments
The settings for USE_X_FORWARDED_FOR were not being respected because the settings were not being passed through.
from django.conf import settings
DEFAULT_REALM = getattr(settings, 'RATED_DEFAULT_REALM', 'default')
DEFAULT_LIMIT = getattr(settings, 'RATED_DEFAULT_LIMI... |
c12ec403fe382484b1963738143fe1ea2cbdb000 | opps/images/templatetags/images_tags.py | opps/images/templatetags/images_tags.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
... | Fix pep8, E231 missing whitespace after ',' | Fix pep8, E231 missing whitespace after ','
| Python | mit | williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,jeanmask/opps,opps/opps,opps/opps | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
... | Fix pep8, E231 missing whitespace after ','
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
d... |
49d1d8ce0221af7f9732b09370cd0c0ec85b7191 | indra/sources/process_mentions.py | indra/sources/process_mentions.py | import json
from indra.statements import Activation, Agent
def process_mentions(fname):
with open(fname, 'r') as fh:
jd = json.load(fh)
mentions = jd['mentions']
events = [m for m in mentions if m['type'] == 'EventMention']
events = [e for e in events if len(e['arguments']) == 2]
event... | Add initial mention processing code | Add initial mention processing code
| Python | bsd-2-clause | sorgerlab/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/indra,bgyori/indra,sorgerlab/belpy,johnbachman/indra,pvtodorov/indra,bgyori/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra | import json
from indra.statements import Activation, Agent
def process_mentions(fname):
with open(fname, 'r') as fh:
jd = json.load(fh)
mentions = jd['mentions']
events = [m for m in mentions if m['type'] == 'EventMention']
events = [e for e in events if len(e['arguments']) == 2]
event... | Add initial mention processing code
| |
6e2dae94239252f6b0338e609a838fa31e417842 | checks.d/veneur.py | checks.d/veneur.py | import datetime
from urlparse import urljoin
import requests
# project
from checks import AgentCheck
class Veneur(AgentCheck):
VERSION_METRIC_NAME = 'veneur.deployed_version'
BUILDAGE_METRIC_NAME = 'veneur.build_age'
ERROR_METRIC_NAME = 'veneur.agent_check.errors_total'
def check(self, instance):
... | import datetime
from urlparse import urljoin
import requests
# project
from checks import AgentCheck
class Veneur(AgentCheck):
VERSION_METRIC_NAME = 'veneur.deployed_version'
BUILDAGE_METRIC_NAME = 'veneur.build_age'
ERROR_METRIC_NAME = 'veneur.agent_check.errors_total'
def check(self, instance):
... | Add the sha to the tags in a way that won't cause an error | Add the sha to the tags in a way that won't cause an error
| Python | mit | stripe/stripe-datadog-checks,stripe/datadog-checks | import datetime
from urlparse import urljoin
import requests
# project
from checks import AgentCheck
class Veneur(AgentCheck):
VERSION_METRIC_NAME = 'veneur.deployed_version'
BUILDAGE_METRIC_NAME = 'veneur.build_age'
ERROR_METRIC_NAME = 'veneur.agent_check.errors_total'
def check(self, instance):
... | Add the sha to the tags in a way that won't cause an error
import datetime
from urlparse import urljoin
import requests
# project
from checks import AgentCheck
class Veneur(AgentCheck):
VERSION_METRIC_NAME = 'veneur.deployed_version'
BUILDAGE_METRIC_NAME = 'veneur.build_age'
ERROR_METRIC_NAME = 'veneur.... |
fd951edbef26dcab2a4b89036811520b22e77fcf | marry-fuck-kill/main.py | marry-fuck-kill/main.py | #!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# 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 b... | #!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# 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 b... | Remove TODO -- handlers have been cleaned up. | Remove TODO -- handlers have been cleaned up.
| Python | apache-2.0 | hjfreyer/marry-fuck-kill,hjfreyer/marry-fuck-kill | #!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# 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 b... | Remove TODO -- handlers have been cleaned up.
#!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# 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... |
830888cb9c795313917e6540f11b411ea002b6b6 | comics/comics/kalscartoon.py | comics/comics/kalscartoon.py | from dateutil.parser import parse
from comics.aggregator.crawler import CrawlerBase, CrawlerResult
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = "KAL's Cartoon"
language = 'en'
url = 'http://www.economist.com'
start_date = '2006-01-05'
rights = 'Kevin Kallaugher'
class Crawle... | Add crawler for KAL's cartoon | Add crawler for KAL's cartoon
| Python | agpl-3.0 | klette/comics,jodal/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,klette/comics,datagutten/comics,datagutten/comics,datagutten/comics,klette/comics | from dateutil.parser import parse
from comics.aggregator.crawler import CrawlerBase, CrawlerResult
from comics.meta.base import MetaBase
class Meta(MetaBase):
name = "KAL's Cartoon"
language = 'en'
url = 'http://www.economist.com'
start_date = '2006-01-05'
rights = 'Kevin Kallaugher'
class Crawle... | Add crawler for KAL's cartoon
| |
554572f327e4b9c920f65b416bfc6a3a5b549846 | numba/tests/npyufunc/test_parallel_env_variable.py | numba/tests/npyufunc/test_parallel_env_variable.py | from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test... | from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test... | Reset the num threads to the env variable, not the default | Reset the num threads to the env variable, not the default
| Python | bsd-2-clause | numba/numba,stonebig/numba,cpcloud/numba,gmarkall/numba,sklam/numba,stuartarchibald/numba,seibert/numba,seibert/numba,cpcloud/numba,numba/numba,sklam/numba,IntelLabs/numba,stuartarchibald/numba,IntelLabs/numba,IntelLabs/numba,gmarkall/numba,cpcloud/numba,seibert/numba,stuartarchibald/numba,numba/numba,sklam/numba,seibe... | from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test... | Reset the num threads to the env variable, not the default
from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
... |
2f268a124a5aceabab6dcdb545cf14648c297e2c | lava_results_app/admin.py | lava_results_app/admin.py | # Copyright (C) 2015 Linaro Limited
#
# Author: Stevan Radakovic <stevan.radakovic@linaro.org>
#
# This file is part of Lava Server.
#
# Lava Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software Foundat... | # Copyright (C) 2015 Linaro Limited
#
# Author: Stevan Radakovic <stevan.radakovic@linaro.org>
#
# This file is part of Lava Server.
#
# Lava Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software Foundat... | Fix deprecation warnings - RemovedInDjango19Warning | Fix deprecation warnings - RemovedInDjango19Warning
Extend fix in review #9160 for subsequent changes.
Change-Id: I25fbe759cfd28ac683ef94b58a8da098141e8d48
| Python | agpl-3.0 | Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server | # Copyright (C) 2015 Linaro Limited
#
# Author: Stevan Radakovic <stevan.radakovic@linaro.org>
#
# This file is part of Lava Server.
#
# Lava Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software Foundat... | Fix deprecation warnings - RemovedInDjango19Warning
Extend fix in review #9160 for subsequent changes.
Change-Id: I25fbe759cfd28ac683ef94b58a8da098141e8d48
# Copyright (C) 2015 Linaro Limited
#
# Author: Stevan Radakovic <stevan.radakovic@linaro.org>
#
# This file is part of Lava Server.
#
# Lava Server is free soft... |
d1e64b8cf97f8a89d61ecd5d5bd7f9ba6f5ff6b8 | extruct/jsonld.py | extruct/jsonld.py | # -*- coding: utf-8 -*-
"""
JSON-LD extractor
"""
import json
import re
import lxml.etree
import lxml.html
HTML_OR_JS_COMMENTLINE = re.compile('^\s*(//.*|<!--.*-->)')
class JsonLdExtractor(object):
_xp_jsonld = lxml.etree.XPath('descendant-or-self::script[@type="application/ld+json"]')
def extract(self, ... | # -*- coding: utf-8 -*-
"""
JSON-LD extractor
"""
import json
import re
import lxml.etree
import lxml.html
HTML_OR_JS_COMMENTLINE = re.compile('^\s*(//.*|<!--.*-->)')
class JsonLdExtractor(object):
_xp_jsonld = lxml.etree.XPath('descendant-or-self::script[@type="application/ld+json"]')
def extract(self, ... | Remove leading comments and allow control characters directly. | Mod: Remove leading comments and allow control characters directly.
| Python | bsd-3-clause | scrapinghub/extruct | # -*- coding: utf-8 -*-
"""
JSON-LD extractor
"""
import json
import re
import lxml.etree
import lxml.html
HTML_OR_JS_COMMENTLINE = re.compile('^\s*(//.*|<!--.*-->)')
class JsonLdExtractor(object):
_xp_jsonld = lxml.etree.XPath('descendant-or-self::script[@type="application/ld+json"]')
def extract(self, ... | Mod: Remove leading comments and allow control characters directly.
# -*- coding: utf-8 -*-
"""
JSON-LD extractor
"""
import json
import re
import lxml.etree
import lxml.html
HTML_OR_JS_COMMENTLINE = re.compile('^\s*(//.*|<!--.*-->)')
class JsonLdExtractor(object):
_xp_jsonld = lxml.etree.XPath('descendant-o... |
cd27adc357655e9cd25c5d23a171920addd7c8f5 | jupyter_notebook_config.py | jupyter_notebook_config.py | # Based off of https://github.com/jupyter/notebook/blob/master/docs/source/extending/savehooks.rst
import io
import os
from notebook.utils import to_api_path
_script_exporter = None
_html_exporter = None
def script_post_save(model, os_path, contents_manager, **kwargs):
"""convert notebooks to Python script after... | Add script to automatically save py file in jupyter. | Add script to automatically save py file in jupyter.
| Python | bsd-3-clause | daichi-yoshikawa/dnn | # Based off of https://github.com/jupyter/notebook/blob/master/docs/source/extending/savehooks.rst
import io
import os
from notebook.utils import to_api_path
_script_exporter = None
_html_exporter = None
def script_post_save(model, os_path, contents_manager, **kwargs):
"""convert notebooks to Python script after... | Add script to automatically save py file in jupyter.
| |
8d08a7caeb4da705b2ab5a6f55528d1beae5bedb | menpofit/clm/expert/base.py | menpofit/clm/expert/base.py | import numpy as np
from menpofit.math.correlationfilter import mccf, imccf
# TODO: document me!
class IncrementalCorrelationFilterThinWrapper(object):
r"""
"""
def __init__(self, cf_callable=mccf, icf_callable=imccf):
self.cf_callable = cf_callable
self.icf_callable = icf_callable
def... | Add dummy wrapper for correlation filters | Add dummy wrapper for correlation filters
| Python | bsd-3-clause | yuxiang-zhou/menpofit,yuxiang-zhou/menpofit,grigorisg9gr/menpofit,grigorisg9gr/menpofit | import numpy as np
from menpofit.math.correlationfilter import mccf, imccf
# TODO: document me!
class IncrementalCorrelationFilterThinWrapper(object):
r"""
"""
def __init__(self, cf_callable=mccf, icf_callable=imccf):
self.cf_callable = cf_callable
self.icf_callable = icf_callable
def... | Add dummy wrapper for correlation filters
| |
d741b41e814930130a30e99b0fece893786f7190 | src/pybel/struct/mutation/__init__.py | src/pybel/struct/mutation/__init__.py | # -*- coding: utf-8 -*-
"""This module contains functions that mutate or make transformations on a network."""
from . import deletion, expansion, induction, inference, metadata, transfer
from .deletion import *
from .expansion import *
from .induction import *
from .inference import *
from .metadata import *
from .tr... | # -*- coding: utf-8 -*-
"""This module contains functions that mutate or make transformations on a network."""
from . import collapse, deletion, expansion, induction, inference, metadata, transfer
from .collapse import *
from .deletion import *
from .expansion import *
from .induction import *
from .inference import ... | Add collapse to star import | Add collapse to star import
| Python | mit | pybel/pybel,pybel/pybel,pybel/pybel | # -*- coding: utf-8 -*-
"""This module contains functions that mutate or make transformations on a network."""
from . import collapse, deletion, expansion, induction, inference, metadata, transfer
from .collapse import *
from .deletion import *
from .expansion import *
from .induction import *
from .inference import ... | Add collapse to star import
# -*- coding: utf-8 -*-
"""This module contains functions that mutate or make transformations on a network."""
from . import deletion, expansion, induction, inference, metadata, transfer
from .deletion import *
from .expansion import *
from .induction import *
from .inference import *
fro... |
54461c89b61ba118ef98389c09b45138b32224ab | stagecraft/apps/datasets/admin/backdrop_user.py | stagecraft/apps/datasets/admin/backdrop_user.py | from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
f... | from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
f... | Add filter_horizontal to backdrop user admin | Add filter_horizontal to backdrop user admin
- Provides a much more usable interface to filter and add data_sets for backdrop admin users
| Python | mit | alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft | from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
f... | Add filter_horizontal to backdrop user admin
- Provides a much more usable interface to filter and add data_sets for backdrop admin users
from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import Bac... |
4f27be336a58d0bba66a4f7ab57126d9dd734ab9 | talks/views.py | talks/views.py | from django.shortcuts import render, get_object_or_404
from config.utils import get_active_event
from .models import Talk
def list_talks(request):
event = get_active_event()
talks = event.talks.prefetch_related(
'applicants',
'applicants__user',
'skill_level',
'sponsor',
... | from django.shortcuts import render, get_object_or_404
from config.utils import get_active_event
from .models import Talk
def list_talks(request):
event = get_active_event()
talks = event.talks.prefetch_related(
'applicants',
'applicants__user',
'skill_level',
'sponsor',
... | Revert "Temporarily make talks visible only to committee" | Revert "Temporarily make talks visible only to committee"
This reverts commit 57050b7025acb3de66024fe01255849a5ba5f1fc.
| Python | bsd-3-clause | WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web | from django.shortcuts import render, get_object_or_404
from config.utils import get_active_event
from .models import Talk
def list_talks(request):
event = get_active_event()
talks = event.talks.prefetch_related(
'applicants',
'applicants__user',
'skill_level',
'sponsor',
... | Revert "Temporarily make talks visible only to committee"
This reverts commit 57050b7025acb3de66024fe01255849a5ba5f1fc.
from django.shortcuts import render, get_object_or_404
from config.utils import get_active_event
from .models import Talk
def list_talks(request):
event = get_active_event()
talks = even... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.