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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b9b046a9ad58406155a3005050f90b5184ba1758 | bpython/__init__.py | bpython/__init__.py | # The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... | # The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... | Set the version name for the default branch to mercurial so we can tell when we run from the repository | Set the version name for the default branch to mercurial so we can tell when we run from the repository
| Python | mit | 5monkeys/bpython | # The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... | Set the version name for the default branch to mercurial so we can tell when we run from the repository
# The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... |
91bb9574ec760efd8aba2d9ae8fe67fe2e69d0a2 | jacquard/buckets/tests/test_bucket.py | jacquard/buckets/tests/test_bucket.py | import pytest
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_three_buckets_per_percent():
assert NUM_BUCKETS / 100 >= 3
| import pytest
from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_thr... | Add a test for getting an empty bucket | Add a test for getting an empty bucket
| Python | mit | prophile/jacquard,prophile/jacquard | import pytest
from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_thr... | Add a test for getting an empty bucket
import pytest
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_three_buckets_per_percent():
... |
27c9da3129c6fbdd8d54276cf054c1f46e665aaf | flask_app.py | flask_app.py | from flask import Flask, abort, jsonify
from flask_caching import Cache
from flask_cors import CORS
import main
import slack
app = Flask(__name__)
cache = Cache(app, config={"CACHE_TYPE": "simple"})
cors = CORS(app, resources={r"/*": {"origins": "*"}})
app.register_blueprint(slack.blueprint, url_prefix="/api/slack")... | import flask
import flask_caching
import flask_cors
import main
import slack
app = flask.Flask(__name__)
cache = flask_caching.Cache(app, config={"CACHE_TYPE": "simple"})
cors = flask_cors.CORS(app, resources={r"/*": {"origins": "*"}})
app.register_blueprint(slack.blueprint, url_prefix="/api/slack")
@app.route("/a... | Remove trailing slashes, add origin url to responses | Remove trailing slashes, add origin url to responses
| Python | bsd-3-clause | talavis/kimenu | import flask
import flask_caching
import flask_cors
import main
import slack
app = flask.Flask(__name__)
cache = flask_caching.Cache(app, config={"CACHE_TYPE": "simple"})
cors = flask_cors.CORS(app, resources={r"/*": {"origins": "*"}})
app.register_blueprint(slack.blueprint, url_prefix="/api/slack")
@app.route("/a... | Remove trailing slashes, add origin url to responses
from flask import Flask, abort, jsonify
from flask_caching import Cache
from flask_cors import CORS
import main
import slack
app = Flask(__name__)
cache = Cache(app, config={"CACHE_TYPE": "simple"})
cors = CORS(app, resources={r"/*": {"origins": "*"}})
app.regist... |
9ef92435a94d01d963b25e10bfb681daf04df193 | dbaas/integrations/iaas/manager.py | dbaas/integrations/iaas/manager.py | from dbaas_cloudstack.provider import CloudStackProvider
from pre_provisioned.pre_provisioned_provider import PreProvisionedProvider
from integrations.monitoring.manager import MonitoringManager
import logging
LOG = logging.getLogger(__name__)
class IaaSManager():
@classmethod
def destroy_instance(cls, ... | from dbaas_cloudstack.provider import CloudStackProvider
from pre_provisioned.pre_provisioned_provider import PreProvisionedProvider
from integrations.monitoring.manager import MonitoringManager
import logging
LOG = logging.getLogger(__name__)
class IaaSManager():
@classmethod
def destroy_instance(cls, ... | Remove monitoring only after database quarantine | Remove monitoring only after database quarantine
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | from dbaas_cloudstack.provider import CloudStackProvider
from pre_provisioned.pre_provisioned_provider import PreProvisionedProvider
from integrations.monitoring.manager import MonitoringManager
import logging
LOG = logging.getLogger(__name__)
class IaaSManager():
@classmethod
def destroy_instance(cls, ... | Remove monitoring only after database quarantine
from dbaas_cloudstack.provider import CloudStackProvider
from pre_provisioned.pre_provisioned_provider import PreProvisionedProvider
from integrations.monitoring.manager import MonitoringManager
import logging
LOG = logging.getLogger(__name__)
class IaaSManager():
... |
c3e034de03ee45bb161c06bcff870839f9ed4d4b | django_lti_tool_provider/tests/urls.py | django_lti_tool_provider/tests/urls.py | from django.conf.urls import patterns, url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | Remove reference to deprecated "patterns" function. | Remove reference to deprecated "patterns" function.
This function is no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10
| Python | agpl-3.0 | open-craft/django-lti-tool-provider | from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | Remove reference to deprecated "patterns" function.
This function is no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10
from django.conf.urls import patterns, url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
... |
2cc2a1318da0980911dd0cd0868efb8fad4dd1d8 | python/ctci-is-binary-search-tree.py | python/ctci-is-binary-search-tree.py | """ Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
import sys
def checkBST(root):
return validBST(root)
def validBST(node):
if emptyNode(node):
return True
if not validNode(node):
return False
... | Solve is binary search tree | Solve is binary search tree
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank | """ Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
import sys
def checkBST(root):
return validBST(root)
def validBST(node):
if emptyNode(node):
return True
if not validNode(node):
return False
... | Solve is binary search tree
| |
8b519628839bc2360d2f0f48231e2cf7b9edc6b3 | scripts/analytics/run_keen_summaries.py | scripts/analytics/run_keen_summaries.py | from framework.celery_tasks import app as celery_app
from scripts.analytics.user_summary import UserSummary
from scripts.analytics.node_summary import NodeSummary
from scripts.analytics.base import DateAnalyticsHarness
class SummaryHarness(DateAnalyticsHarness):
@property
def analytics_classes(self):
... | from framework.celery_tasks import app as celery_app
from scripts.analytics.user_summary import UserSummary
from scripts.analytics.node_summary import NodeSummary
from scripts.analytics.institution_summary import InstitutionSummary
from scripts.analytics.base import DateAnalyticsHarness
class SummaryHarness(DateAnaly... | Add new InstitutionSummary to run_keen_summarries harness | Add new InstitutionSummary to run_keen_summarries harness
| Python | apache-2.0 | leb2dg/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,laurenrevere/osf.io,brianjgeiger/osf.io,caneruguz/osf.io,saradbowman/osf.io,chrisseto/osf.io,cwisecarver/osf.io,mluo613/osf.io,cwisecarver/osf.io,alexschiller/osf.io,acshi/osf.io,laurenrevere/osf.io,Nesiehr/osf.io,sloria/osf.io,mluo613/osf.io,pattisdr/osf.io,... | from framework.celery_tasks import app as celery_app
from scripts.analytics.user_summary import UserSummary
from scripts.analytics.node_summary import NodeSummary
from scripts.analytics.institution_summary import InstitutionSummary
from scripts.analytics.base import DateAnalyticsHarness
class SummaryHarness(DateAnaly... | Add new InstitutionSummary to run_keen_summarries harness
from framework.celery_tasks import app as celery_app
from scripts.analytics.user_summary import UserSummary
from scripts.analytics.node_summary import NodeSummary
from scripts.analytics.base import DateAnalyticsHarness
class SummaryHarness(DateAnalyticsHarnes... |
937a5e32c77ca57917d60a891616fbcf19ab19f9 | respite/utils.py | respite/utils.py | from django import forms
def generate_form(model):
"""
Generate a form from a model.
Arguments:
model -- A Django model.
"""
_model = model
class Form(forms.ModelForm):
class Meta:
model = _model
return Form
def parse_http_accept_header(header):
"""
Return ... | from django import forms
def generate_form(model):
"""
Generate a form from a model.
Arguments:
model -- A Django model.
"""
_model = model
class Form(forms.ModelForm):
class Meta:
model = _model
return Form
def parse_http_accept_header(header):
"""
Return ... | Fix a bug that caused HTTP Accept headers with whitespace to be parsed incorrectly | Fix a bug that caused HTTP Accept headers with whitespace to be parsed incorrectly
| Python | mit | jgorset/django-respite,jgorset/django-respite,jgorset/django-respite | from django import forms
def generate_form(model):
"""
Generate a form from a model.
Arguments:
model -- A Django model.
"""
_model = model
class Form(forms.ModelForm):
class Meta:
model = _model
return Form
def parse_http_accept_header(header):
"""
Return ... | Fix a bug that caused HTTP Accept headers with whitespace to be parsed incorrectly
from django import forms
def generate_form(model):
"""
Generate a form from a model.
Arguments:
model -- A Django model.
"""
_model = model
class Form(forms.ModelForm):
class Meta:
model... |
fd1a0850f9c4c5c34accf64af47ac9bbf25faf74 | setup.py | setup.py | import re
from pathlib import Path
from setuptools import setup, find_packages
with Path(__file__).with_name('dvhb_hybrid').joinpath('__init__.py').open() as f:
VERSION = re.compile(r'.*__version__ = \'(.*?)\'', re.S).match(f.read()).group(1)
setup(
name='dvhb-hybrid',
version=VERSION,
description='... | import re
from pathlib import Path
from setuptools import setup, find_packages
with Path(__file__).with_name('dvhb_hybrid').joinpath('__init__.py').open() as f:
VERSION = re.compile(r'.*__version__ = \'(.*?)\'', re.S).match(f.read()).group(1)
setup(
name='dvhb-hybrid',
version=VERSION,
description='... | Add aioauth-client into package install_requires | Add aioauth-client into package install_requires
| Python | mit | dvhbru/dvhb-hybrid | import re
from pathlib import Path
from setuptools import setup, find_packages
with Path(__file__).with_name('dvhb_hybrid').joinpath('__init__.py').open() as f:
VERSION = re.compile(r'.*__version__ = \'(.*?)\'', re.S).match(f.read()).group(1)
setup(
name='dvhb-hybrid',
version=VERSION,
description='... | Add aioauth-client into package install_requires
import re
from pathlib import Path
from setuptools import setup, find_packages
with Path(__file__).with_name('dvhb_hybrid').joinpath('__init__.py').open() as f:
VERSION = re.compile(r'.*__version__ = \'(.*?)\'', re.S).match(f.read()).group(1)
setup(
name='dv... |
8f60ea444d2732b5e0f1b73a24cd8e753f160e79 | corehq/apps/userreports/specs.py | corehq/apps/userreports/specs.py | from jsonobject import StringProperty
def TypeProperty(value):
"""
Shortcut for making a required property and restricting it to a single specified
value. This adds additional validation that the objects are being wrapped as expected
according to the type.
"""
return StringProperty(required=Tr... | from jsonobject import StringProperty
def TypeProperty(value):
"""
Shortcut for making a required property and restricting it to a single specified
value. This adds additional validation that the objects are being wrapped as expected
according to the type.
"""
return StringProperty(required=Tr... | Set default iteration on EvaluationContext initializer | Set default iteration on EvaluationContext initializer
| Python | bsd-3-clause | dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq | from jsonobject import StringProperty
def TypeProperty(value):
"""
Shortcut for making a required property and restricting it to a single specified
value. This adds additional validation that the objects are being wrapped as expected
according to the type.
"""
return StringProperty(required=Tr... | Set default iteration on EvaluationContext initializer
from jsonobject import StringProperty
def TypeProperty(value):
"""
Shortcut for making a required property and restricting it to a single specified
value. This adds additional validation that the objects are being wrapped as expected
according to... |
03c479bce1d135e9d1c4acfbb085340b14679feb | fedmsg.d/fmn.py | fedmsg.d/fmn.py | import socket
hostname = socket.gethostname().split('.')[-1]
config = {
# Consumer stuff
"fmn.consumer.enabled": True,
"fmn.sqlalchemy.uri": "sqlite:////var/tmp/fmn-dev-db.sqlite",
## Backend stuff ##
# Email
"fmn.email.mailserver": "127.0.0.1:25",
"fmn.email.from_address": "fedmsg-notifi... | import socket
hostname = socket.gethostname().split('.')[-1]
import fmn.lib
config = {
# General stuff
"fmn.valid_code_paths": fmn.lib.load_filters(),
# Consumer stuff
"fmn.consumer.enabled": True,
"fmn.sqlalchemy.uri": "sqlite:////var/tmp/fmn-dev-db.sqlite",
## Backend stuff ##
# Email... | Load code paths into the fedmsg dict. | Load code paths into the fedmsg dict.
| Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn | import socket
hostname = socket.gethostname().split('.')[-1]
import fmn.lib
config = {
# General stuff
"fmn.valid_code_paths": fmn.lib.load_filters(),
# Consumer stuff
"fmn.consumer.enabled": True,
"fmn.sqlalchemy.uri": "sqlite:////var/tmp/fmn-dev-db.sqlite",
## Backend stuff ##
# Email... | Load code paths into the fedmsg dict.
import socket
hostname = socket.gethostname().split('.')[-1]
config = {
# Consumer stuff
"fmn.consumer.enabled": True,
"fmn.sqlalchemy.uri": "sqlite:////var/tmp/fmn-dev-db.sqlite",
## Backend stuff ##
# Email
"fmn.email.mailserver": "127.0.0.1:25",
"... |
e2bb78a1587b7d5c0416c3632ca9674339826d55 | src/yawf/creation.py | src/yawf/creation.py | from django.db import transaction
from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR
from yawf import get_workflow, get_workflow_by_instance
from yawf import dispatch
from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError
@transaction.commit_on_success
def create(workflow_type, sende... | from django.db import transaction
from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR
from yawf import get_workflow, get_workflow_by_instance
from yawf import dispatch
from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError
@transaction.commit_on_success
def create(workflow_type, sende... | Make start_message_params optional in start_workflow() | Make start_message_params optional in start_workflow()
| Python | mit | freevoid/yawf | from django.db import transaction
from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR
from yawf import get_workflow, get_workflow_by_instance
from yawf import dispatch
from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError
@transaction.commit_on_success
def create(workflow_type, sende... | Make start_message_params optional in start_workflow()
from django.db import transaction
from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR
from yawf import get_workflow, get_workflow_by_instance
from yawf import dispatch
from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError
@trans... |
21799c73bdc6f0dc7410edc61db5de5694ab911a | django/hello/world/models.py | django/hello/world/models.py | from django.db import models
# Create your models here.
class World(models.Model):
randomnumber = models.IntegerField()
class Meta:
db_table = 'world'
class Fortune(models.Model):
message = models.CharField(max_length=65535)
class Meta:
db_table = 'fortune'
| from django.db import models
# Create your models here.
class World(models.Model):
randomnumber = models.IntegerField()
class Meta:
db_table = 'World'
class Fortune(models.Model):
message = models.CharField(max_length=65535)
class Meta:
db_table = 'Fortune'
| Fix table name for MySQL | Fix table name for MySQL
| Python | bsd-3-clause | dmacd/FB-try1,julienschmidt/FrameworkBenchmarks,zapov/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,methane/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks... | from django.db import models
# Create your models here.
class World(models.Model):
randomnumber = models.IntegerField()
class Meta:
db_table = 'World'
class Fortune(models.Model):
message = models.CharField(max_length=65535)
class Meta:
db_table = 'Fortune'
| Fix table name for MySQL
from django.db import models
# Create your models here.
class World(models.Model):
randomnumber = models.IntegerField()
class Meta:
db_table = 'world'
class Fortune(models.Model):
message = models.CharField(max_length=65535)
class Meta:
db_table = 'fortune'
|
ac44a041e3e7808305b025e1087f48b7d4a9234a | tools/bitly/delete_bitly_blobs.py | tools/bitly/delete_bitly_blobs.py | #!/usr/bin/env python3
import argparse
import boto3
import os
from typing import List
from mediawords.util.log import create_logger
l = create_logger(__name__)
def delete_bitly_blobs(story_ids: List[int]):
session = boto3.Session(profile_name='mediacloud')
s3 = session.resource('s3')
bucket = s3.Bucket... | Add script to delete Bit.ly raw results from S3 | Add script to delete Bit.ly raw results from S3
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud | #!/usr/bin/env python3
import argparse
import boto3
import os
from typing import List
from mediawords.util.log import create_logger
l = create_logger(__name__)
def delete_bitly_blobs(story_ids: List[int]):
session = boto3.Session(profile_name='mediacloud')
s3 = session.resource('s3')
bucket = s3.Bucket... | Add script to delete Bit.ly raw results from S3
| |
42db9ceae490152040651a23d397e7ad4c950712 | flask/flask/tests/test_template.py | flask/flask/tests/test_template.py | from flask import Flask, render_template_string
import jinja2
def test_undefined_variable__no_error():
app = Flask(__name__)
assert issubclass(app.jinja_env.undefined, jinja2.Undefined)
@app.route('/')
def endpoint():
return render_template_string('foo = [{{bar}}]', foo='blabla')
resp = a... | # -*- coding: utf-8 -*-
from flask import Flask, render_template_string
import jinja2
def test_undefined_variable__no_error():
app = Flask(__name__)
assert issubclass(app.jinja_env.undefined, jinja2.Undefined)
@app.route('/')
def endpoint():
return render_template_string('foo = [{{bar}}]', foo... | Fix source code encoding error | [flask] Fix source code encoding error
| Python | mit | imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning | # -*- coding: utf-8 -*-
from flask import Flask, render_template_string
import jinja2
def test_undefined_variable__no_error():
app = Flask(__name__)
assert issubclass(app.jinja_env.undefined, jinja2.Undefined)
@app.route('/')
def endpoint():
return render_template_string('foo = [{{bar}}]', foo... | [flask] Fix source code encoding error
from flask import Flask, render_template_string
import jinja2
def test_undefined_variable__no_error():
app = Flask(__name__)
assert issubclass(app.jinja_env.undefined, jinja2.Undefined)
@app.route('/')
def endpoint():
return render_template_string('foo =... |
e17e436b7671b3c6834d286c91f541ee768fadac | script/gen-iana-rclasses.py | script/gen-iana-rclasses.py | import enumgen
from pprint import pprint
import os
import os.path
data = enumgen.fetch_csv(
"http://www.iana.org/assignments/dns-parameters/dns-parameters-2.csv")
data_dict = []
for row in data:
if '-' in row[0]: continue
if ' ' in row[2]:
row[2] = row[2].split(' ')[-1].strip('()')
if row[2] in [i['name'] for i... | Add RRClass generation script to git | Add RRClass generation script to git
| Python | bsd-2-clause | oko/rust-dns | import enumgen
from pprint import pprint
import os
import os.path
data = enumgen.fetch_csv(
"http://www.iana.org/assignments/dns-parameters/dns-parameters-2.csv")
data_dict = []
for row in data:
if '-' in row[0]: continue
if ' ' in row[2]:
row[2] = row[2].split(' ')[-1].strip('()')
if row[2] in [i['name'] for i... | Add RRClass generation script to git
| |
84942c895343d7803144b0a95feeabe481fe0e3d | behave/formatter/base.py | behave/formatter/base.py | class Formatter(object):
name = None
description = None
def __init__(self, stream, config):
self.stream = stream
self.config = config
def uri(self, uri):
pass
def feature(self, feature):
pass
def background(self, background):
pass
def scenario(sel... | class Formatter(object):
name = None
description = None
def __init__(self, stream, config):
self.stream = stream
self.config = config
def uri(self, uri):
pass
def feature(self, feature):
pass
def background(self, background):
pass
def scenario(sel... | Remove blank line at end of file. | Remove blank line at end of file.
| Python | bsd-2-clause | hugeinc/behave-parallel,metaperl/behave,KevinOrtman/behave,KevinOrtman/behave,connorsml/behave,Gimpneek/behave,charleswhchan/behave,charleswhchan/behave,vrutkovs/behave,mzcity123/behave,Gimpneek/behave,spacediver/behave,KevinMarkVI/behave-parallel,jenisys/behave,memee/behave,allanlewis/behave,vrutkovs/behave,mzcity123/... | class Formatter(object):
name = None
description = None
def __init__(self, stream, config):
self.stream = stream
self.config = config
def uri(self, uri):
pass
def feature(self, feature):
pass
def background(self, background):
pass
def scenario(sel... | Remove blank line at end of file.
class Formatter(object):
name = None
description = None
def __init__(self, stream, config):
self.stream = stream
self.config = config
def uri(self, uri):
pass
def feature(self, feature):
pass
def background(self, background):... |
5b2691dcc89fb9d9b7b1db77e9512976950adf45 | setup.py | setup.py | """Package Keysmith."""
import codecs
import os.path
import setuptools # type: ignore
import keysmith # This project only depends on the standard library.
def read(*parts):
"""Read a file in this repository."""
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, *pa... | """Package Keysmith."""
import codecs
import os.path
import setuptools # type: ignore
import keysmith # This project only depends on the standard library.
def read(*parts):
"""Read a file in this repository."""
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, *pa... | Update the project Development Status | Update the project Development Status
| Python | bsd-3-clause | dmtucker/keysmith | """Package Keysmith."""
import codecs
import os.path
import setuptools # type: ignore
import keysmith # This project only depends on the standard library.
def read(*parts):
"""Read a file in this repository."""
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, *pa... | Update the project Development Status
"""Package Keysmith."""
import codecs
import os.path
import setuptools # type: ignore
import keysmith # This project only depends on the standard library.
def read(*parts):
"""Read a file in this repository."""
here = os.path.abspath(os.path.dirname(__file__))
... |
50cf6e64955d1e82ba702b8817b830c23534da11 | simple_faq/models.py | simple_faq/models.py | from django.db import models
from tinymce import models as tinymce_models
photos_path = "/simple-faq/"
class Topic(models.Model):
text = models.CharField(max_length=200)
number = models.IntegerField()
class Meta:
ordering = ['number']
def __unicode__(self):
return u'(%s) %s' % (self... | from django.db import models
from tinymce import models as tinymce_models
photos_path = "simple-faq/"
class Topic(models.Model):
text = models.CharField(max_length=200)
number = models.IntegerField()
class Meta:
ordering = ['number']
def __unicode__(self):
return u'(%s) %s' % (self.... | Fix path where the images are saved. | Fix path where the images are saved.
| Python | mit | devartis/django-simple-faq,devartis/django-simple-faq | from django.db import models
from tinymce import models as tinymce_models
photos_path = "simple-faq/"
class Topic(models.Model):
text = models.CharField(max_length=200)
number = models.IntegerField()
class Meta:
ordering = ['number']
def __unicode__(self):
return u'(%s) %s' % (self.... | Fix path where the images are saved.
from django.db import models
from tinymce import models as tinymce_models
photos_path = "/simple-faq/"
class Topic(models.Model):
text = models.CharField(max_length=200)
number = models.IntegerField()
class Meta:
ordering = ['number']
def __unicode__(se... |
6edd1b4856956436a9a6844a29856681e1df6248 | leetcode/287-Find-the-Duplicate-Number/FindtheDupNum_001.py | leetcode/287-Find-the-Duplicate-Number/FindtheDupNum_001.py | class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l, r = 1, len(nums) - 1
while l < r:
m = l + (r - l) / 2
cnt = 0
for num in nums:
if num <= m:
cnt ... | Add the bin search py version of FindtheDupNum | Add the bin search py version of FindtheDupNum | Python | mit | Chasego/codirit,cc13ny/algo,cc13ny/Allin,Chasego/codirit,Chasego/cod,Chasego/codirit,cc13ny/algo,Chasego/cod,cc13ny/Allin,Chasego/codirit,Chasego/codi,Chasego/cod,Chasego/codi,Chasego/cod,cc13ny/Allin,Chasego/codi,Chasego/codi,cc13ny/algo,Chasego/codi,cc13ny/algo,Chasego/codirit,Chasego/cod,cc13ny/Allin,cc13ny/algo,cc1... | class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l, r = 1, len(nums) - 1
while l < r:
m = l + (r - l) / 2
cnt = 0
for num in nums:
if num <= m:
cnt ... | Add the bin search py version of FindtheDupNum
| |
6a957fd279ed1b305879bcfa41515c2a6e6d423c | mediacloud/mediawords/util/perl.py | mediacloud/mediawords/util/perl.py | #
# Perl (Inline::Perl) helpers
#
# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_string_from_bytes_if_needed(string):
"""Convert 'bytes' string to 'unicode' if needed.
(http://search.cpan.org/dist/Inline-Python/Python.pod#PORTING_YOUR_INLINE_PYTHON_CODE_FROM_2_TO_3)"""
... | #
# Perl (Inline::Perl) helpers
#
# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_string_from_bytes_if_needed(string):
"""Convert 'bytes' string to 'unicode' if needed.
(http://search.cpan.org/dist/Inline-Python/Python.pod#PORTING_YOUR_INLINE_PYTHON_CODE_FROM_2_TO_3)"""
... | Add comment describing what does the method do | Add comment describing what does the method do
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud | #
# Perl (Inline::Perl) helpers
#
# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_string_from_bytes_if_needed(string):
"""Convert 'bytes' string to 'unicode' if needed.
(http://search.cpan.org/dist/Inline-Python/Python.pod#PORTING_YOUR_INLINE_PYTHON_CODE_FROM_2_TO_3)"""
... | Add comment describing what does the method do
#
# Perl (Inline::Perl) helpers
#
# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_string_from_bytes_if_needed(string):
"""Convert 'bytes' string to 'unicode' if needed.
(http://search.cpan.org/dist/Inline-Python/Python.pod#P... |
1704e66caa06524d9b595c312d3a5f5d93683261 | app/models/cnes_bed.py | app/models/cnes_bed.py | from sqlalchemy import Column, Integer, String, func
from app import db
class CnesBed(db.Model):
__tablename__ = 'cnes_bed'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
microregion = Colum... | from sqlalchemy import Column, Integer, String, func
from app import db
class CnesBed(db.Model):
__tablename__ = 'cnes_bed'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
microregion = Colum... | Add bed_type to cnes_establishment model | Add bed_type to cnes_establishment model
| Python | mit | DataViva/dataviva-api,daniel1409/dataviva-api | from sqlalchemy import Column, Integer, String, func
from app import db
class CnesBed(db.Model):
__tablename__ = 'cnes_bed'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
microregion = Colum... | Add bed_type to cnes_establishment model
from sqlalchemy import Column, Integer, String, func
from app import db
class CnesBed(db.Model):
__tablename__ = 'cnes_bed'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), p... |
9f30d2dd142116f46dd0257bcf093e8e8dc2c11a | wagtail/admin/tests/test_dismissibles.py | wagtail/admin/tests/test_dismissibles.py | from django.test import TestCase
from django.urls import reverse
from wagtail.test.utils import WagtailTestUtils
from wagtail.users.models import UserProfile
class TestDismissiblesView(TestCase, WagtailTestUtils):
def setUp(self):
self.user = self.login()
self.profile = UserProfile.get_for_user(s... | Add tests for Dismissibles view | Add tests for Dismissibles view
| Python | bsd-3-clause | rsalmaso/wagtail,thenewguy/wagtail,rsalmaso/wagtail,thenewguy/wagtail,rsalmaso/wagtail,wagtail/wagtail,wagtail/wagtail,rsalmaso/wagtail,zerolab/wagtail,wagtail/wagtail,zerolab/wagtail,zerolab/wagtail,thenewguy/wagtail,zerolab/wagtail,wagtail/wagtail,rsalmaso/wagtail,wagtail/wagtail,thenewguy/wagtail,zerolab/wagtail,the... | from django.test import TestCase
from django.urls import reverse
from wagtail.test.utils import WagtailTestUtils
from wagtail.users.models import UserProfile
class TestDismissiblesView(TestCase, WagtailTestUtils):
def setUp(self):
self.user = self.login()
self.profile = UserProfile.get_for_user(s... | Add tests for Dismissibles view
| |
db4ecaba64a4fbd9d432b461ca0df5b63dd11fb4 | marathon_acme/cli.py | marathon_acme/cli.py | import argparse
import sys
def main(raw_args=sys.argv[1:]):
"""
A tool to automatically request, renew and distribute Let's Encrypt
certificates for apps running on Marathon and served by marathon-lb.
"""
parser = argparse.ArgumentParser(
description='Automatically manage ACME certificates... | import argparse
import sys
def main(raw_args=sys.argv[1:]):
"""
A tool to automatically request, renew and distribute Let's Encrypt
certificates for apps running on Marathon and served by marathon-lb.
"""
parser = argparse.ArgumentParser(
description='Automatically manage ACME certificates... | Add --group option to CLI | Add --group option to CLI
| Python | mit | praekeltfoundation/certbot,praekeltfoundation/certbot | import argparse
import sys
def main(raw_args=sys.argv[1:]):
"""
A tool to automatically request, renew and distribute Let's Encrypt
certificates for apps running on Marathon and served by marathon-lb.
"""
parser = argparse.ArgumentParser(
description='Automatically manage ACME certificates... | Add --group option to CLI
import argparse
import sys
def main(raw_args=sys.argv[1:]):
"""
A tool to automatically request, renew and distribute Let's Encrypt
certificates for apps running on Marathon and served by marathon-lb.
"""
parser = argparse.ArgumentParser(
description='Automatical... |
067bbbc6c9edbf55606fe6f236c70affd86a1fc0 | tests/convert/test_unit.py | tests/convert/test_unit.py | from unittest.mock import patch
from smif.convert.unit import parse_unit
def test_parse_unit_valid():
"""Parse a valid unit
"""
meter = parse_unit('m')
assert str(meter) == 'meter'
@patch('smif.convert.unit.LOGGER.warning')
def test_parse_unit_invalid(warning_logger):
"""Warn if unit not recogni... | import numpy as np
from unittest.mock import patch
from smif.convert.unit import parse_unit
from smif.convert import UnitConvertor
def test_parse_unit_valid():
"""Parse a valid unit
"""
meter = parse_unit('m')
assert str(meter) == 'meter'
@patch('smif.convert.unit.LOGGER.warning')
def test_parse_uni... | Add test for normal unit conversion | Add test for normal unit conversion
| Python | mit | tomalrussell/smif,tomalrussell/smif,nismod/smif,nismod/smif,tomalrussell/smif,nismod/smif,nismod/smif,willu47/smif,willu47/smif,willu47/smif,willu47/smif,tomalrussell/smif | import numpy as np
from unittest.mock import patch
from smif.convert.unit import parse_unit
from smif.convert import UnitConvertor
def test_parse_unit_valid():
"""Parse a valid unit
"""
meter = parse_unit('m')
assert str(meter) == 'meter'
@patch('smif.convert.unit.LOGGER.warning')
def test_parse_uni... | Add test for normal unit conversion
from unittest.mock import patch
from smif.convert.unit import parse_unit
def test_parse_unit_valid():
"""Parse a valid unit
"""
meter = parse_unit('m')
assert str(meter) == 'meter'
@patch('smif.convert.unit.LOGGER.warning')
def test_parse_unit_invalid(warning_log... |
7fd09bd791661ab0b12921dfd977591690d9c01a | accounts/tests/test_forms.py | accounts/tests/test_forms.py | """accounts app unittests for views
"""
from django.test import TestCase
from accounts.forms import LoginForm
class LoginFormTest(TestCase):
"""Tests the form which validates the email used for login.
"""
def test_valid_email_accepted(self):
form = LoginForm({'email': 'newvisitor@example.com'})... | Add form tests for LoginForm | Add form tests for LoginForm
| Python | mit | randomic/aniauth-tdd,randomic/aniauth-tdd | """accounts app unittests for views
"""
from django.test import TestCase
from accounts.forms import LoginForm
class LoginFormTest(TestCase):
"""Tests the form which validates the email used for login.
"""
def test_valid_email_accepted(self):
form = LoginForm({'email': 'newvisitor@example.com'})... | Add form tests for LoginForm
| |
f6e5d7134e1510211b7cd4cc5d87f69b7db98d5d | telemetry/telemetry/page/actions/action_runner_unittest.py | telemetry/telemetry/page/actions/action_runner_unittest.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import tracing_backend
from telemetry.core.timeline import model
from telemetry.page.actions import action_runner as actio... | Add unittests for action_runner.BeginInteraction and action_runner.EndInteraction. | Add unittests for action_runner.BeginInteraction and action_runner.EndInteraction.
This is a reland of https://codereview.chromium.org/294943006 after it's reverted in
https://codereview.chromium.org/284183014/.
BUG=368767
Review URL: https://codereview.chromium.org/299443017
git-svn-id: de016e52bd170d2d4f2344f9bf9... | Python | bsd-3-clause | benschmaus/catapult,catapult-project/catapult,sahiljain/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult-csm,sahiljain/catapult,catapult-project/catapult-csm,catapult-project/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,benschmaus/ca... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core.backends.chrome import tracing_backend
from telemetry.core.timeline import model
from telemetry.page.actions import action_runner as actio... | Add unittests for action_runner.BeginInteraction and action_runner.EndInteraction.
This is a reland of https://codereview.chromium.org/294943006 after it's reverted in
https://codereview.chromium.org/284183014/.
BUG=368767
Review URL: https://codereview.chromium.org/299443017
git-svn-id: de016e52bd170d2d4f2344f9bf9... | |
78977a0f976615e76db477b0ab7b35193b34d189 | api/__init__.py | api/__init__.py | from flask import Flask
app = Flask(__name__)
app.secret_key = ''
import api.userview
| from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension
# Use DictStore until the code is ready for production
store = DictStore()
app = Flask(__name__)
app.secret_key = ''
KVSessionExtension(store, app)
import api.userview
| Change so that kvsession (server side sessions) is used instead of flask default | Change so that kvsession (server side sessions) is used instead of flask default
| Python | isc | tobbez/lys-reader | from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension
# Use DictStore until the code is ready for production
store = DictStore()
app = Flask(__name__)
app.secret_key = ''
KVSessionExtension(store, app)
import api.userview
| Change so that kvsession (server side sessions) is used instead of flask default
from flask import Flask
app = Flask(__name__)
app.secret_key = ''
import api.userview
|
661baf5e280f64824bf983b710c54efccb93a41a | oscar/apps/wishlists/forms.py | oscar/apps/wishlists/forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
... | # -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args,... | Set size on wishlist line quantity form field | Set size on wishlist line quantity form field
This doesn't actually work since there is an overriding CSS style. When
issue #851 is resolved, this should start working.
| Python | bsd-3-clause | sasha0/django-oscar,nickpack/django-oscar,elliotthill/django-oscar,DrOctogon/unwash_ecom,josesanch/django-oscar,bnprk/django-oscar,kapari/django-oscar,marcoantoniooliveira/labweb,solarissmoke/django-oscar,kapt/django-oscar,nickpack/django-oscar,machtfit/django-oscar,jlmadurga/django-oscar,marcoantoniooliveira/labweb,Bo... | # -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory, fields_for_model
WishList = get_model('wishlists', 'WishList')
Line = get_model('wishlists', 'Line')
class WishListForm(forms.ModelForm):
def __init__(self, user, *args,... | Set size on wishlist line quantity form field
This doesn't actually work since there is an overriding CSS style. When
issue #851 is resolved, this should start working.
# -*- coding: utf-8 -*-
from django import forms
from django.db.models import get_model
from django.forms.models import inlineformset_factory
WishL... |
e52b134704951f4ff66a24e348bd20c5a3e85391 | adhocracy4/filters/filters.py | adhocracy4/filters/filters.py | import django_filters
class PagedFilterSet(django_filters.FilterSet):
"""Removes page parameters from the query when applying filters."""
page_kwarg = 'page'
def __init__(self, data, *args, **kwargs):
if self.page_kwarg in data:
# Create a mutable copy
data = data.copy()
... | import django_filters
class PagedFilterSet(django_filters.FilterSet):
"""Removes page parameters from the query when applying filters."""
page_kwarg = 'page'
def __init__(self, data, *args, **kwargs):
if self.page_kwarg in data:
# Create a mutable copy
data = data.copy()
... | Make constructor of DefaultFilterSet compatible | Make constructor of DefaultFilterSet compatible
- arguments had different names than FilterSet before
| Python | agpl-3.0 | liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4 | import django_filters
class PagedFilterSet(django_filters.FilterSet):
"""Removes page parameters from the query when applying filters."""
page_kwarg = 'page'
def __init__(self, data, *args, **kwargs):
if self.page_kwarg in data:
# Create a mutable copy
data = data.copy()
... | Make constructor of DefaultFilterSet compatible
- arguments had different names than FilterSet before
import django_filters
class PagedFilterSet(django_filters.FilterSet):
"""Removes page parameters from the query when applying filters."""
page_kwarg = 'page'
def __init__(self, data, *args, **kwargs)... |
b682339c19702e01de228d0ff982ca086ef9906f | aleph/migrate/versions/a8849e4e6784_match_table.py | aleph/migrate/versions/a8849e4e6784_match_table.py | """Remove the match table.
Revision ID: a8849e4e6784
Revises: 2979a1322381
Create Date: 2020-03-14 20:16:35.882396
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = 'a8849e4e6784'
down_revision = '2979a1322381'
def upgrade():
op.drop_index('ix_match_collection_id', table_name='matc... | Drop the old xref table | Drop the old xref table
| Python | mit | pudo/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,pudo/aleph,alephdata/aleph,pudo/aleph,alephdata/aleph | """Remove the match table.
Revision ID: a8849e4e6784
Revises: 2979a1322381
Create Date: 2020-03-14 20:16:35.882396
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = 'a8849e4e6784'
down_revision = '2979a1322381'
def upgrade():
op.drop_index('ix_match_collection_id', table_name='matc... | Drop the old xref table
| |
34c427200c6ab50fb64fa0d6116366a8fa9186a3 | netman/core/objects/bond.py | netman/core/objects/bond.py | # Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | # Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | Support deprecated use of the interface property of Bond. | Support deprecated use of the interface property of Bond.
| Python | apache-2.0 | idjaw/netman,internaphosting/netman,internap/netman,godp1301/netman,mat128/netman,lindycoder/netman | # Copyright 2015 Internap.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | Support deprecated use of the interface property of Bond.
# Copyright 2015 Internap.
#
# 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
#
# Un... |
80650a2f32ce8e3de4c26f2bc3fce4bab34cb36f | test/__init__.py | test/__init__.py | # -*- coding: utf-8 -*-
import os
from betamax import Betamax
from betamax_serializers import pretty_json
URL = os.environ.get('CONTENT_SERVICE_URL', 'http://dockerdev:9000')
APIKEY = os.environ.get('CONTENT_SERVICE_APIKEY', '12341234')
Betamax.register_serializer(pretty_json.PrettyJSONSerializer)
with Betamax.conf... | # -*- coding: utf-8 -*-
import os
from betamax import Betamax
from betamax_serializers import pretty_json
URL = os.environ.get('CONTENT_SERVICE_URL', 'http://dockerdev:9000')
APIKEY = os.environ.get('CONTENT_SERVICE_APIKEY', '12341234')
if URL.endswith('/'):
URL = URL[:-1]
Betamax.register_serializer(pretty_js... | Normalize URL for test cases. | Normalize URL for test cases.
| Python | apache-2.0 | deconst/submitter,deconst/submitter | # -*- coding: utf-8 -*-
import os
from betamax import Betamax
from betamax_serializers import pretty_json
URL = os.environ.get('CONTENT_SERVICE_URL', 'http://dockerdev:9000')
APIKEY = os.environ.get('CONTENT_SERVICE_APIKEY', '12341234')
if URL.endswith('/'):
URL = URL[:-1]
Betamax.register_serializer(pretty_js... | Normalize URL for test cases.
# -*- coding: utf-8 -*-
import os
from betamax import Betamax
from betamax_serializers import pretty_json
URL = os.environ.get('CONTENT_SERVICE_URL', 'http://dockerdev:9000')
APIKEY = os.environ.get('CONTENT_SERVICE_APIKEY', '12341234')
Betamax.register_serializer(pretty_json.PrettyJS... |
825ab4f2a26e7a5c4348f1adfa8e5163013e43f7 | setup.py | setup.py | #!/usr/bin/env python
#coding: utf-8
from cms import VERSION
from setuptools import setup, find_packages
EXCLUDE_FROM_PACKAGES = ['cms.bin']
setup(
name="onespacemedia-cms",
version=".".join(str(n) for n in VERSION),
url="https://github.com/onespacemedia/cms",
author="Daniel Samuels",
author_ema... | #!/usr/bin/env python
#coding: utf-8
from cms import VERSION
from setuptools import setup, find_packages
EXCLUDE_FROM_PACKAGES = ['cms.bin']
setup(
name="onespacemedia-cms",
version=".".join(str(n) for n in VERSION),
url="https://github.com/onespacemedia/cms",
author="Daniel Samuels",
author_ema... | Add raven to the dependancy list. | Add raven to the dependancy list. | Python | bsd-3-clause | jamesfoley/cms,danielsamuels/cms,lewiscollard/cms,danielsamuels/cms,lewiscollard/cms,dan-gamble/cms,lewiscollard/cms,dan-gamble/cms,jamesfoley/cms,danielsamuels/cms,dan-gamble/cms,jamesfoley/cms,jamesfoley/cms | #!/usr/bin/env python
#coding: utf-8
from cms import VERSION
from setuptools import setup, find_packages
EXCLUDE_FROM_PACKAGES = ['cms.bin']
setup(
name="onespacemedia-cms",
version=".".join(str(n) for n in VERSION),
url="https://github.com/onespacemedia/cms",
author="Daniel Samuels",
author_ema... | Add raven to the dependancy list.
#!/usr/bin/env python
#coding: utf-8
from cms import VERSION
from setuptools import setup, find_packages
EXCLUDE_FROM_PACKAGES = ['cms.bin']
setup(
name="onespacemedia-cms",
version=".".join(str(n) for n in VERSION),
url="https://github.com/onespacemedia/cms",
autho... |
aa7fdb1d7a7b42dee7bcfcf1eb4a4a5efcb3a2e3 | go/api/go_api/tests/utils.py | go/api/go_api/tests/utils.py | import json
from django.conf import settings
from mock import Mock, patch
class MockRpc(object):
def setUp(self):
self.response = self.set_response()
self.request = None
self.rpc_patcher = patch('go.api.go_api.client.rpc')
self.mock_rpc = self.rpc_patcher.start()
self.mo... | Add MockRpc test utility class | Add MockRpc test utility class
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | import json
from django.conf import settings
from mock import Mock, patch
class MockRpc(object):
def setUp(self):
self.response = self.set_response()
self.request = None
self.rpc_patcher = patch('go.api.go_api.client.rpc')
self.mock_rpc = self.rpc_patcher.start()
self.mo... | Add MockRpc test utility class
| |
60368c4b7d3d48945381aac89e95217a58c1e3a4 | politics/__init__.py | politics/__init__.py | # encoding: utf-8
# 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")... | Add module info for politics. | Add module info for politics.
| Python | apache-2.0 | chrismattmann/politics-hacking | # encoding: utf-8
# 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")... | Add module info for politics.
| |
b826571c35de75a62d23b2b92530508a9466b7d0 | tests/test_simdata.py | tests/test_simdata.py | import nose
import cle
import os
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.join('..', '..', 'binaries', 'tests'))
def test_progname():
filename = os.path.join(test_location, 'x86_64', 'cat')
ld = cle.Loader(filename, auto_loa... | Add test for simdata and GOT relocations | Add test for simdata and GOT relocations
| Python | bsd-2-clause | angr/cle | import nose
import cle
import os
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.join('..', '..', 'binaries', 'tests'))
def test_progname():
filename = os.path.join(test_location, 'x86_64', 'cat')
ld = cle.Loader(filename, auto_loa... | Add test for simdata and GOT relocations
| |
6e3151cd9e4c5309959c93b2ed683bb74d88a640 | backend/breach/tests/test_sniffer.py | backend/breach/tests/test_sniffer.py | from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
self.sniffer = Sniffer(self.endpoint)
self.source_ip = '147.102.239.229'
self.destination_host = 'dionyziz.c... | from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
self.sniffer = Sniffer(self.endpoint, '147.102.239.229', 'dionyziz.com', 'wlan0', '8080')
@patch('breach.sniffer.request... | Migrate Sniffer unit test to new API | Migrate Sniffer unit test to new API
| Python | mit | esarafianou/rupture,esarafianou/rupture,dimriou/rupture,dimriou/rupture,dimkarakostas/rupture,dimriou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dionyziz/rupture,dionyziz/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dionyziz/rupture,dimkarako... | from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
self.sniffer = Sniffer(self.endpoint, '147.102.239.229', 'dionyziz.com', 'wlan0', '8080')
@patch('breach.sniffer.request... | Migrate Sniffer unit test to new API
from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
self.sniffer = Sniffer(self.endpoint)
self.source_ip = '147.102.239.229'
... |
ba500886eb0d49fc92188ec2cce7a14326d63ef1 | setup.py | setup.py | from setuptools import setup
setup(name='striketracker',
version='0.5',
description='Command line interface to the Highwinds CDN',
url='https://github.com/Highwinds/striketracker',
author='Mark Cahill',
author_email='support@highwinds.com',
license='MIT',
packages=['striketrac... | from setuptools import setup
setup(name='striketracker',
version='0.5.1',
description='Command line interface to the Highwinds CDN',
url='https://github.com/Highwinds/striketracker',
author='Mark Cahill',
author_email='support@highwinds.com',
license='MIT',
packages=['striketr... | Bump version number for host clone functionality | Bump version number for host clone functionality
| Python | mit | Highwinds/striketracker | from setuptools import setup
setup(name='striketracker',
version='0.5.1',
description='Command line interface to the Highwinds CDN',
url='https://github.com/Highwinds/striketracker',
author='Mark Cahill',
author_email='support@highwinds.com',
license='MIT',
packages=['striketr... | Bump version number for host clone functionality
from setuptools import setup
setup(name='striketracker',
version='0.5',
description='Command line interface to the Highwinds CDN',
url='https://github.com/Highwinds/striketracker',
author='Mark Cahill',
author_email='support@highwinds.com'... |
1b1a40646a08e6a01927279eb7dff8399adec740 | markups/common.py | markups/common.py | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.exp... | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.exp... | Update MathJax URL to 2.7.2 | Update MathJax URL to 2.7.2
| Python | bsd-3-clause | mitya57/pymarkups,retext-project/pymarkups | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.exp... | Update MathJax URL to 2.7.2
# This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2017
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.gete... |
8bb1172a67ad978e11f5b3f24828b130ff61def7 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]
setup(
author="Ryan Gibson",
author_email="ryanalexandergibson@gmail.com",
name... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]
setup(
author="Ryan Gibson",
author_email="ryanalexandergibson@gmail.com",
name... | Remove support for end-of-life Python 3.6 in next release | Remove support for end-of-life Python 3.6 in next release
Checked again just now and we are still waiting on Python 3.10 stability | Python | mit | ragibson/Steganography | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]
setup(
author="Ryan Gibson",
author_email="ryanalexandergibson@gmail.com",
name... | Remove support for end-of-life Python 3.6 in next release
Checked again just now and we are still waiting on Python 3.10 stability
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["Pillow>=... |
817d9c78f939de2b01ff518356ed0414178aaa6d | avalonstar/apps/api/serializers.py | avalonstar/apps/api/serializers.py | # -*- coding: utf-8 -*-
from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
class SeriesSerializer(serializers.ModelSerializ... | # -*- coding: utf-8 -*-
from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Raid, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
class RaidSerializer(serializers.ModelSeri... | Add Raid to the API. | Add Raid to the API.
| Python | apache-2.0 | bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv | # -*- coding: utf-8 -*-
from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Raid, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
class RaidSerializer(serializers.ModelSeri... | Add Raid to the API.
# -*- coding: utf-8 -*-
from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
class SeriesSerializer(ser... |
2431ce65da38d50c83f2f23b55dab64a6b4c0b89 | boxsdk/object/__init__.py | boxsdk/object/__init__.py | # coding: utf-8
from __future__ import unicode_literals
import six
__all__ = [
'collaboration',
'events',
'file',
'folder',
'group',
'group_membership',
'search',
'user',
]
if six.PY2:
__all__ = [unicode.encode(x, 'utf-8') for x in __all__]
| # coding: utf-8
from __future__ import unicode_literals
from six.moves import map # pylint:disable=redefined-builtin
__all__ = list(map(str, ['collaboration', 'events', 'file', 'folder', 'group', 'group_membership', 'search', 'user']))
| Change format of sub-module names in the object module to str | Change format of sub-module names in the object module to str
| Python | apache-2.0 | box/box-python-sdk | # coding: utf-8
from __future__ import unicode_literals
from six.moves import map # pylint:disable=redefined-builtin
__all__ = list(map(str, ['collaboration', 'events', 'file', 'folder', 'group', 'group_membership', 'search', 'user']))
| Change format of sub-module names in the object module to str
# coding: utf-8
from __future__ import unicode_literals
import six
__all__ = [
'collaboration',
'events',
'file',
'folder',
'group',
'group_membership',
'search',
'user',
]
if six.PY2:
__all__ = [unicode.encode(x, 'u... |
f61870d3e3c5684101034fa800f6bece03f08c66 | disasm.py | disasm.py | import MOS6502
import instructions
def disasm(memory):
index = 0
lines = []
while index < len(memory):
currInst = instructions.instructions[memory[index]]
line = currInst.mnem + " "
line += currInst.operType + " "
if currInst.size > 1:
for i in range(1,... | Add quick dumb disassembler for upcoming debugger | Add quick dumb disassembler for upcoming debugger
| Python | bsd-2-clause | pusscat/refNes | import MOS6502
import instructions
def disasm(memory):
index = 0
lines = []
while index < len(memory):
currInst = instructions.instructions[memory[index]]
line = currInst.mnem + " "
line += currInst.operType + " "
if currInst.size > 1:
for i in range(1,... | Add quick dumb disassembler for upcoming debugger
| |
9bd2d607e52b50ae79ff51199118395e57cedfdc | custom/icds/tests/test_views.py | custom/icds/tests/test_views.py | from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
class TestViews(TestCase):
@override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.html')
def test_custom_login(self):
... | from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
class TestViews(TestCase):
@override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.html')
def test_custom_login_old_fo... | Add test for new custom landing format | Add test for new custom landing format
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
class TestViews(TestCase):
@override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.html')
def test_custom_login_old_fo... | Add test for new custom landing format
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
class TestViews(TestCase):
@override_settings(CUSTOM_LANDING_TEMPLATE='icds/login.... |
b6b9a926704ffe570bd4cedf6cabd9920dc41cad | setup.py | setup.py | from setuptools import setup, find_packages
import os
setup(
name='yamlicious',
packages=find_packages(),
scripts=[os.path.join('bin', p) for p in os.listdir('bin')],
)
| from setuptools import setup, find_packages
import os
setup(
name='yamlicious',
packages=find_packages(),
scripts=[os.path.join('bin', p) for p in os.listdir('bin')],
install_requires=[
'pyyaml',
]
)
| Add YAML as a dep. | Add YAML as a dep.
| Python | bsd-2-clause | derrley/yamlicious,derrley/yamlicious | from setuptools import setup, find_packages
import os
setup(
name='yamlicious',
packages=find_packages(),
scripts=[os.path.join('bin', p) for p in os.listdir('bin')],
install_requires=[
'pyyaml',
]
)
| Add YAML as a dep.
from setuptools import setup, find_packages
import os
setup(
name='yamlicious',
packages=find_packages(),
scripts=[os.path.join('bin', p) for p in os.listdir('bin')],
)
|
86f3c9b12e46c34d38fbebdefb70380a45526fe3 | tmaps/config/default.py | tmaps/config/default.py | import datetime
# Override this key with a secret one
SECRET_KEY = 'default_secret_key'
HASHIDS_SALT = 'default_secret_salt'
# This should be set to true in the production config when using NGINX
USE_X_SENDFILE = False
DEBUG = True
JWT_EXPIRATION_DELTA = datetime.timedelta(days=2)
JWT_NOT_BEFORE_DELTA = datetime.tim... | import datetime
# Override this key with a secret one
SECRET_KEY = 'default_secret_key'
HASHIDS_SALT = 'default_secret_salt'
# This should be set to true in the production config when using NGINX
USE_X_SENDFILE = False
DEBUG = True
JWT_EXPIRATION_DELTA = datetime.timedelta(days=2)
JWT_NOT_BEFORE_DELTA = datetime.tim... | Remove gc3pie session dir from config | Remove gc3pie session dir from config
| Python | agpl-3.0 | TissueMAPS/TmServer | import datetime
# Override this key with a secret one
SECRET_KEY = 'default_secret_key'
HASHIDS_SALT = 'default_secret_salt'
# This should be set to true in the production config when using NGINX
USE_X_SENDFILE = False
DEBUG = True
JWT_EXPIRATION_DELTA = datetime.timedelta(days=2)
JWT_NOT_BEFORE_DELTA = datetime.tim... | Remove gc3pie session dir from config
import datetime
# Override this key with a secret one
SECRET_KEY = 'default_secret_key'
HASHIDS_SALT = 'default_secret_salt'
# This should be set to true in the production config when using NGINX
USE_X_SENDFILE = False
DEBUG = True
JWT_EXPIRATION_DELTA = datetime.timedelta(days... |
7f0684583de39552e4117df8cd12c3e030c98f3e | securesystemslib/__init__.py | securesystemslib/__init__.py | import logging
# Configure a basic 'securesystemslib' top-level logger with a StreamHandler
# (print to console) and the WARNING log level (print messages of type
# warning, error or critical). This is similar to what 'logging.basicConfig'
# would do with the root logger. All 'securesystemslib.*' loggers default to
# ... | Configure basic securesystemslib top-level logger | Configure basic securesystemslib top-level logger
As pointed out by @FlorianVeaux in #210, securesystemslib does not
correctly initialize its loggers. As a consequence the logging
module logs a one-off "No handler could be found ..." warning when
used for the first time (only on Python 2).
The logging module then cal... | Python | mit | secure-systems-lab/securesystemslib,secure-systems-lab/securesystemslib | import logging
# Configure a basic 'securesystemslib' top-level logger with a StreamHandler
# (print to console) and the WARNING log level (print messages of type
# warning, error or critical). This is similar to what 'logging.basicConfig'
# would do with the root logger. All 'securesystemslib.*' loggers default to
# ... | Configure basic securesystemslib top-level logger
As pointed out by @FlorianVeaux in #210, securesystemslib does not
correctly initialize its loggers. As a consequence the logging
module logs a one-off "No handler could be found ..." warning when
used for the first time (only on Python 2).
The logging module then cal... | |
56e3225329d2f7fae37139ec1d6727784718d339 | test_portend.py | test_portend.py | import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = None
port = portend.find_available_local_port()
family = socket.AF_UNSPEC
socktype = socket.SOCK_STREAM
return socket.getaddrinfo(host, port, family, socktype)
def id_for_info(inf... | import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = None # all available interfaces
port = portend.find_available_local_port()
family = socket.AF_UNSPEC
socktype = socket.SOCK_STREAM
return socket.getaddrinfo(host, port, family, soc... | Add indication of what None means | Add indication of what None means
| Python | mit | jaraco/portend | import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = None # all available interfaces
port = portend.find_available_local_port()
family = socket.AF_UNSPEC
socktype = socket.SOCK_STREAM
return socket.getaddrinfo(host, port, family, soc... | Add indication of what None means
import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = None
port = portend.find_available_local_port()
family = socket.AF_UNSPEC
socktype = socket.SOCK_STREAM
return socket.getaddrinfo(host, port, fami... |
03a3f15daf7c90f8146987f09491c69b899a0130 | corehq/apps/domainsync/management/commands/copy_utils.py | corehq/apps/domainsync/management/commands/copy_utils.py | from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct
def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
"""
Copies a set of data associated with a list of doc-ids from a remote postgres
databas... | from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct
from phonelog.models import DeviceReportEntry
def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
"""
Copies a set of data associated with a list... | Add phonelog to postgres models copied by copy_domain | Add phonelog to postgres models copied by copy_domain
| Python | bsd-3-clause | dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq | from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct
from phonelog.models import DeviceReportEntry
def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
"""
Copies a set of data associated with a list... | Add phonelog to postgres models copied by copy_domain
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct
def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
"""
Copies a set of data associated wi... |
a1e1340285e190f5b0cc3cce2c4155cb313df6a7 | wafer/schedule/serializers.py | wafer/schedule/serializers.py | from rest_framework import serializers
from wafer.talks.models import Talk
from wafer.pages.models import Page
from wafer.schedule.models import ScheduleItem, Venue, Slot
class ScheduleItemSerializer(serializers.HyperlinkedModelSerializer):
page = serializers.PrimaryKeyRelatedField(
allow_null=True, quer... | from rest_framework import serializers
from wafer.talks.models import Talk
from wafer.pages.models import Page
from wafer.schedule.models import ScheduleItem, Venue, Slot
class ScheduleItemSerializer(serializers.HyperlinkedModelSerializer):
page = serializers.PrimaryKeyRelatedField(
allow_null=True, quer... | Clear extra fields when changing items through the schedule view | Clear extra fields when changing items through the schedule view
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer | from rest_framework import serializers
from wafer.talks.models import Talk
from wafer.pages.models import Page
from wafer.schedule.models import ScheduleItem, Venue, Slot
class ScheduleItemSerializer(serializers.HyperlinkedModelSerializer):
page = serializers.PrimaryKeyRelatedField(
allow_null=True, quer... | Clear extra fields when changing items through the schedule view
from rest_framework import serializers
from wafer.talks.models import Talk
from wafer.pages.models import Page
from wafer.schedule.models import ScheduleItem, Venue, Slot
class ScheduleItemSerializer(serializers.HyperlinkedModelSerializer):
page =... |
074dcf9c822827c6609dc11c0047aa79dd8c1ad8 | tests/test_cli.py | tests/test_cli.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pyutrack` package."""
import unittest
from click.testing import CliRunner
from pyutrack import cli
class TestYoutrack_cli(unittest.TestCase):
def test_improt(self):
import pyutrack
def test_command_line_interface(self):
runner =... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pyutrack` package."""
import unittest
from click.testing import CliRunner
from pyutrack import cli
from tests import PyutrackTest
class TestYoutrack_cli(PyutrackTest):
def test_improt(self):
import pyutrack
def test_command_line_interface(... | Set cli tests to base test class | Set cli tests to base test class
| Python | mit | alisaifee/pyutrack,alisaifee/pyutrack | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pyutrack` package."""
import unittest
from click.testing import CliRunner
from pyutrack import cli
from tests import PyutrackTest
class TestYoutrack_cli(PyutrackTest):
def test_improt(self):
import pyutrack
def test_command_line_interface(... | Set cli tests to base test class
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `pyutrack` package."""
import unittest
from click.testing import CliRunner
from pyutrack import cli
class TestYoutrack_cli(unittest.TestCase):
def test_improt(self):
import pyutrack
def test_command_line... |
38ed00b38d9cb005f9b25643afa7ce480da6febe | examples/enable/resize_tool_demo.py | examples/enable/resize_tool_demo.py | """
This demonstrates the most basic drawing capabilities using Enable. A new
component is created and added to a container.
"""
from enable.example_support import DemoFrame, demo_main
from enable.api import Component, Container, Window
from enable.tools.resize_tool import ResizeTool
class Box(Component):
resiz... | """
This demonstrates the resize tool.
"""
from enable.example_support import DemoFrame, demo_main
from enable.api import Component, Container, Window
from enable.tools.resize_tool import ResizeTool
class Box(Component):
resizable = ""
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
... | Fix resize tool demo comments. | Fix resize tool demo comments.
| Python | bsd-3-clause | tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable | """
This demonstrates the resize tool.
"""
from enable.example_support import DemoFrame, demo_main
from enable.api import Component, Container, Window
from enable.tools.resize_tool import ResizeTool
class Box(Component):
resizable = ""
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
... | Fix resize tool demo comments.
"""
This demonstrates the most basic drawing capabilities using Enable. A new
component is created and added to a container.
"""
from enable.example_support import DemoFrame, demo_main
from enable.api import Component, Container, Window
from enable.tools.resize_tool import ResizeTool
... |
a460713d36e8310a9f975d13d49579e77d83dfe7 | examples/with-shapely.py | examples/with-shapely.py |
import logging
import sys
from shapely.geometry import mapping, shape
from fiona import collection
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
with collection("docs/data/test_uk.shp", "r") as input:
schema = input.schema.copy()
with collection(
"with-shapely.shp", "w",... |
import logging
import sys
from shapely.geometry import mapping, shape
from fiona import collection
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
with collection("docs/data/test_uk.shp", "r") as input:
schema = input.schema.copy()
with collection(
"with-shapely.shp", "w",... | Fix validity assertion and add another. | Fix validity assertion and add another.
| Python | bsd-3-clause | johanvdw/Fiona,Toblerity/Fiona,rbuffat/Fiona,Toblerity/Fiona,perrygeo/Fiona,perrygeo/Fiona,sgillies/Fiona,rbuffat/Fiona |
import logging
import sys
from shapely.geometry import mapping, shape
from fiona import collection
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
with collection("docs/data/test_uk.shp", "r") as input:
schema = input.schema.copy()
with collection(
"with-shapely.shp", "w",... | Fix validity assertion and add another.
import logging
import sys
from shapely.geometry import mapping, shape
from fiona import collection
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
with collection("docs/data/test_uk.shp", "r") as input:
schema = input.schema.copy()
with collect... |
bed98e0769d067857dadf69079dc049d76d65fd0 | kitchen/lib/__init__.py | kitchen/lib/__init__.py | import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_nodes():
retval = {}
nodes_dir = os.path.join(KITCHEN_LOCATION, 'nodes')
for filename in os.listdir(nodes_dir):
f = open(os.path.join(nodes_dir, filename), 'r')
retval[filename[:-5]] = json.load(f)
f.close... | Add function to load data from nodes files | Add function to load data from nodes files
| Python | apache-2.0 | edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen | import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_nodes():
retval = {}
nodes_dir = os.path.join(KITCHEN_LOCATION, 'nodes')
for filename in os.listdir(nodes_dir):
f = open(os.path.join(nodes_dir, filename), 'r')
retval[filename[:-5]] = json.load(f)
f.close... | Add function to load data from nodes files
| |
1fd2aef4fcaabddcb533ffe2f999e55d1e3ce7fe | docs/source/conf.py | docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import subprocess
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if on_rtd:
subprocess.call('cd ..; doxygen', shell=True)
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
def set... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import subprocess
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if on_rtd:
subprocess.call('cd ..; doxygen', shell=True)
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
def se... | Fix build with Sphinx 4. | Fix build with Sphinx 4.
`add_stylesheet` was deprecated in 1.8 and removed in 4.0 [1]. The
replacement, `add_css_file` was added in 1.0, which is older than any
version required by `breathe`.
[1] https://www.sphinx-doc.org/en/master/extdev/deprecated.html?highlight=add_stylesheet
| Python | bsd-3-clause | xtensor-stack/xtl,xtensor-stack/xtl | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import subprocess
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if on_rtd:
subprocess.call('cd ..; doxygen', shell=True)
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
def se... | Fix build with Sphinx 4.
`add_stylesheet` was deprecated in 1.8 and removed in 4.0 [1]. The
replacement, `add_css_file` was added in 1.0, which is older than any
version required by `breathe`.
[1] https://www.sphinx-doc.org/en/master/extdev/deprecated.html?highlight=add_stylesheet
#!/usr/bin/env python3
# -*- coding... |
aa6d6e59be8c0b8577517bd16de3e75de7f0e570 | project_name/urls.py | project_name/urls.py | """{{project_name}} URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... | # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.views.generic import TemplateView
from django.conf.urls.static import static
from django.views import defaults as default_views
urlpatterns = [
url(settings.ADMIN_URL, in... | Improve url patterns structure, enable debugging common error pages while debugging | Improve url patterns structure, enable debugging common error pages while debugging
| Python | mit | Nikola-K/django-template,Nikola-K/django-template | # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.views.generic import TemplateView
from django.conf.urls.static import static
from django.views import defaults as default_views
urlpatterns = [
url(settings.ADMIN_URL, in... | Improve url patterns structure, enable debugging common error pages while debugging
"""{{project_name}} URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_ap... |
d3c5c5612c23c2ffcc103402d1f4d2acf7b81009 | photutils/utils/tests/test_moments.py | photutils/utils/tests/test_moments.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_equal, assert_allclose
import pytest
from .._moments import _moments, _moments_central
def ... | Add tests for new moment functions | Add tests for new moment functions
| Python | bsd-3-clause | astropy/photutils,larrybradley/photutils | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_equal, assert_allclose
import pytest
from .._moments import _moments, _moments_central
def ... | Add tests for new moment functions
| |
4bac6dab8168170cca42f70f2c13dad5467d3cbb | ffdc/plugins/date_time_utils.py | ffdc/plugins/date_time_utils.py | #!/usr/bin/env python
r"""
This module contains functions having to do with date time filter.
"""
from datetime import datetime
def convert_string_dateime(date_str, date_format, desired_format):
r"""
Return a date time formatted from a string datetime.
Description of arguments(s):
date_str ... | Add date time util module | Plugin: Add date time util module
Change-Id: I6ab1d8bb8df63b8590ce7800e60415d90ea3bad3
Signed-off-by: George Keishing <bef0a9ecac45fb57611777c8270153994e13fd2e@in.ibm.com>
| Python | apache-2.0 | openbmc/openbmc-test-automation,openbmc/openbmc-test-automation | #!/usr/bin/env python
r"""
This module contains functions having to do with date time filter.
"""
from datetime import datetime
def convert_string_dateime(date_str, date_format, desired_format):
r"""
Return a date time formatted from a string datetime.
Description of arguments(s):
date_str ... | Plugin: Add date time util module
Change-Id: I6ab1d8bb8df63b8590ce7800e60415d90ea3bad3
Signed-off-by: George Keishing <bef0a9ecac45fb57611777c8270153994e13fd2e@in.ibm.com>
| |
4531017c7c9e96a7a1108f39a906ddcac25ebd59 | setup.py | setup.py | import os
from setuptools import setup
from setuptools import find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.rst')) as f:
CHANGES = f.read()
except:
README = ''
... | import io
from setuptools import setup, find_packages
long_description = '\n'.join((
io.open('README.rst', encoding='utf-8').read(),
io.open('CHANGES.txt', encoding='utf-8').read()
))
setup(
name='importscan',
version='0.2.dev0',
description='Recursively import modules and sub-packages',
long_... | Use io.open with encoding='utf-8' and flake8 compliance | Use io.open with encoding='utf-8' and flake8 compliance
| Python | bsd-3-clause | faassen/importscan | import io
from setuptools import setup, find_packages
long_description = '\n'.join((
io.open('README.rst', encoding='utf-8').read(),
io.open('CHANGES.txt', encoding='utf-8').read()
))
setup(
name='importscan',
version='0.2.dev0',
description='Recursively import modules and sub-packages',
long_... | Use io.open with encoding='utf-8' and flake8 compliance
import os
from setuptools import setup
from setuptools import find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.rst')) ... |
29cb760030021f97906d5eaec1c0b885e8bb2930 | example/gravity.py | example/gravity.py | """
Compute the force of gravity between the Earth and Sun.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
# Import the gravitational constant and the Quantity class
from dimensionful import G, Quantity
# Supply the mass of Earth, mass of Sun, and the distance between.
mass_earth = Quant... | """
Compute the force of gravity between the Earth and Sun.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
# Import the gravitational constant and the Quantity class
from dimensionful import G, Quantity
# Supply the mass of Earth, mass of Sun, and the distance between.
mass_earth = Quant... | Add what the example should output. | Add what the example should output. | Python | bsd-2-clause | caseywstark/dimensionful | """
Compute the force of gravity between the Earth and Sun.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
# Import the gravitational constant and the Quantity class
from dimensionful import G, Quantity
# Supply the mass of Earth, mass of Sun, and the distance between.
mass_earth = Quant... | Add what the example should output.
"""
Compute the force of gravity between the Earth and Sun.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
# Import the gravitational constant and the Quantity class
from dimensionful import G, Quantity
# Supply the mass of Earth, mass of Sun, and the ... |
fe4f86b9635fadd6a0c79065e4c9888327e31b80 | DeleteDataFromUrlTest.py | DeleteDataFromUrlTest.py | __author__ = 'chuqiao'
import script
# DELETE ALL DATA
script.deleteDataInSolr()
# ADD DATA FROM 2 SORCES
script.addDataToSolrFromUrl("http://www.elixir-europe.org:8080/events", "http://www.elixir-europe.org:8080/events");
script.addDataToSolrFromUrl("http://localhost/ep/events?state=published&field_type_tid=All", "htt... | Create delete data from url test script | Create delete data from url test script
| Python | mit | elixirhub/events-portal-scraping-scripts | __author__ = 'chuqiao'
import script
# DELETE ALL DATA
script.deleteDataInSolr()
# ADD DATA FROM 2 SORCES
script.addDataToSolrFromUrl("http://www.elixir-europe.org:8080/events", "http://www.elixir-europe.org:8080/events");
script.addDataToSolrFromUrl("http://localhost/ep/events?state=published&field_type_tid=All", "htt... | Create delete data from url test script
| |
836845abde53ee55bca93f098ece78880ab6b5c6 | examples/events/create_massive_dummy_events.py | examples/events/create_massive_dummy_events.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from keys import misp_url, misp_key, misp_verifycert
import argparse
import tools
def init(url, key):
return PyMISP(url, key, misp_verifycert, 'json')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create a give... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from keys import url, key
import argparse
import tools
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create a given number of event containing a given number of attributes eachh.')
parser.add_argument("-l", "--... | Use same variable names as testing environment | Use same variable names as testing environment
| Python | bsd-2-clause | pombredanne/PyMISP,iglocska/PyMISP | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from keys import url, key
import argparse
import tools
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create a given number of event containing a given number of attributes eachh.')
parser.add_argument("-l", "--... | Use same variable names as testing environment
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from keys import misp_url, misp_key, misp_verifycert
import argparse
import tools
def init(url, key):
return PyMISP(url, key, misp_verifycert, 'json')
if __name__ == '__main__':
parser = ar... |
dac3cedaee583db4cc3c05a9cb2c4f15a707123e | pylib/mapit/middleware.py | pylib/mapit/middleware.py | import re
class JSONPMiddleware(object):
def process_response(self, request, response):
if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')):
response.content = request.GET.get('callback') + '(' + response.content + ')'
return response
| import re
class JSONPMiddleware(object):
def process_response(self, request, response):
if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')):
response.content = request.GET.get('callback') + '(' + response.content + ')'
response.status_code = 20... | Set up JSONP requests to always return 200. | Set up JSONP requests to always return 200.
| Python | agpl-3.0 | Sinar/mapit,Code4SA/mapit,New-Bamboo/mapit,opencorato/mapit,Sinar/mapit,opencorato/mapit,opencorato/mapit,chris48s/mapit,chris48s/mapit,Code4SA/mapit,chris48s/mapit,New-Bamboo/mapit,Code4SA/mapit | import re
class JSONPMiddleware(object):
def process_response(self, request, response):
if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')):
response.content = request.GET.get('callback') + '(' + response.content + ')'
response.status_code = 20... | Set up JSONP requests to always return 200.
import re
class JSONPMiddleware(object):
def process_response(self, request, response):
if request.GET.get('callback') and re.match('[a-zA-Z0-9_]+$', request.GET.get('callback')):
response.content = request.GET.get('callback') + '(' + response.conten... |
f571c0754a519f1b2aa6a7ecc4f9de2c23ce0a0c | x10d.py | x10d.py | #!/usr/bin/env python
from daemon import Daemon, SerialDispatcher
from serial import Serial
from threading import Thread
import sys
def callback(event):
if event:
print("EVENT: {0.house}{0.unit}: {0.command}".format(event))
def listen(daemon):
house, unit, act = input().split()
unit = int(unit)
... | #!/usr/bin/env python
from daemon import Daemon, SerialDispatcher
from serial import Serial
from threading import Thread
import sys
def callback(event):
if event:
print("EVENT: {0.house}{0.unit}: {0.command}".format(event))
def listen(daemon):
house, unit, act = input().split()
unit = int(unit)
... | Add user input to daemon | Add user input to daemon
| Python | unlicense | umbc-hackafe/x10-controller | #!/usr/bin/env python
from daemon import Daemon, SerialDispatcher
from serial import Serial
from threading import Thread
import sys
def callback(event):
if event:
print("EVENT: {0.house}{0.unit}: {0.command}".format(event))
def listen(daemon):
house, unit, act = input().split()
unit = int(unit)
... | Add user input to daemon
#!/usr/bin/env python
from daemon import Daemon, SerialDispatcher
from serial import Serial
from threading import Thread
import sys
def callback(event):
if event:
print("EVENT: {0.house}{0.unit}: {0.command}".format(event))
def listen(daemon):
house, unit, act = input().split... |
3055fa16010a1b855142c2e5b866d76daee17c8f | markdown_gen/test/attributes_test.py | markdown_gen/test/attributes_test.py |
import unittest
import markdown_gen.MardownGen as md
class AttributesTests(unittest.TestCase):
def test_italic(self):
expected = "*italic text*"
self.assertEqual(expected, md.gen_italic("italic text"))
expected = "_italic text alternative_"
self.assertEqual(expected, md.gen_it... |
import unittest
import markdown_gen.MardownGen as md
class AttributesTests(unittest.TestCase):
def test_italic(self):
expected = "*italic text*"
self.assertEqual(expected, md.gen_italic("italic text"))
expected = "_italic text alternative_"
self.assertEqual(expected, md.gen_it... | Add test for bold and italic text | Add test for bold and italic text | Python | epl-1.0 | LukasWoodtli/PyMarkdownGen |
import unittest
import markdown_gen.MardownGen as md
class AttributesTests(unittest.TestCase):
def test_italic(self):
expected = "*italic text*"
self.assertEqual(expected, md.gen_italic("italic text"))
expected = "_italic text alternative_"
self.assertEqual(expected, md.gen_it... | Add test for bold and italic text
import unittest
import markdown_gen.MardownGen as md
class AttributesTests(unittest.TestCase):
def test_italic(self):
expected = "*italic text*"
self.assertEqual(expected, md.gen_italic("italic text"))
expected = "_italic text alternative_"
se... |
20699a38f8ab28fa605abbe110d0bfdb2b571662 | workers/exec/examples/dummy_worker.py | workers/exec/examples/dummy_worker.py | #!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT... | #!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT... | Add flush for dummy exec worker | Add flush for dummy exec worker
| Python | bsd-3-clause | timofey-barmin/mzbench,timofey-barmin/mzbench,timofey-barmin/mzbench,machinezone/mzbench,timofey-barmin/mzbench,timofey-barmin/mzbench,machinezone/mzbench,machinezone/mzbench,machinezone/mzbench,machinezone/mzbench | #!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT... | Add flush for dummy exec worker
#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.coun... |
61e542ab3fab4ef15cff8e1d5189652f8e10b5cf | scriptOffsets.py | scriptOffsets.py | from msc import *
from sys import argv
with open(argv[1], 'rb') as f:
mscFile = MscFile()
mscFile.readFromFile(f)
if len(argv) > 2:
nums = [int(i,0) for i in argv[2:]]
for num in nums:
for i,script in enumerate(mscFile):
if script.bounds[0] == num:
... | Add dev tool script to print off script names from offsets | Add dev tool script to print off script names from offsets
| Python | mit | jam1garner/pymsc | from msc import *
from sys import argv
with open(argv[1], 'rb') as f:
mscFile = MscFile()
mscFile.readFromFile(f)
if len(argv) > 2:
nums = [int(i,0) for i in argv[2:]]
for num in nums:
for i,script in enumerate(mscFile):
if script.bounds[0] == num:
... | Add dev tool script to print off script names from offsets
| |
312c0d463940257cb1f777d3720778550b5bdb2d | bluebottle/organizations/serializers.py | bluebottle/organizations/serializers.py | from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_l... | from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_l... | Revert "Make the name of an organization required" | Revert "Make the name of an organization required"
This reverts commit 02140561a29a2b7fe50f7bf2402da566e60be641.
| Python | bsd-3-clause | jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer):
class Meta:
model = Organization
fields = ('id', 'name', 'slug', 'address_line1', 'address_l... | Revert "Make the name of an organization required"
This reverts commit 02140561a29a2b7fe50f7bf2402da566e60be641.
from rest_framework import serializers
from bluebottle.organizations.models import Organization
from bluebottle.utils.serializers import URLField
class OrganizationSerializer(serializers.ModelSerializer... |
dac5f9e406f3c205d6ed212d4414ca55c94b8f15 | tests/local/test_search.py | tests/local/test_search.py | from __future__ import unicode_literals
import unittest
from mopidy.local import search
from mopidy.models import Album, Track
class LocalLibrarySearchTest(unittest.TestCase):
def test_find_exact_with_album_query(self):
expected_tracks = [Track(album=Album(name='foo'))]
tracks = [Track(), Track(... | Add test for exact search with album query | Add test for exact search with album query
| Python | apache-2.0 | pacificIT/mopidy,hkariti/mopidy,bencevans/mopidy,jmarsik/mopidy,swak/mopidy,swak/mopidy,diandiankan/mopidy,vrs01/mopidy,dbrgn/mopidy,jodal/mopidy,tkem/mopidy,quartz55/mopidy,hkariti/mopidy,ali/mopidy,swak/mopidy,mokieyue/mopidy,mokieyue/mopidy,swak/mopidy,dbrgn/mopidy,SuperStarPL/mopidy,kingosticks/mopidy,tkem/mopidy,g... | from __future__ import unicode_literals
import unittest
from mopidy.local import search
from mopidy.models import Album, Track
class LocalLibrarySearchTest(unittest.TestCase):
def test_find_exact_with_album_query(self):
expected_tracks = [Track(album=Album(name='foo'))]
tracks = [Track(), Track(... | Add test for exact search with album query
| |
b214a69136225459b514cbf6f3eb503228ae4ec4 | server/openslides/saml/management/commands/create-saml-settings.py | server/openslides/saml/management/commands/create-saml-settings.py | import os
from django.core.management.base import BaseCommand
from ...settings import create_saml_settings, get_settings_dir_and_path
class Command(BaseCommand):
"""
Command to create the saml_settings.json file.
"""
help = "Create the saml_settings.json settings file."
def add_arguments(self,... | import os
from django.core.management.base import BaseCommand
from ...settings import create_saml_settings, get_settings_dir_and_path
class Command(BaseCommand):
"""
Command to create the saml_settings.json file.
"""
help = "Create the saml_settings.json settings file."
def add_arguments(self,... | Fix check on wrong variable | Fix check on wrong variable | Python | mit | jwinzer/OpenSlides,CatoTH/OpenSlides,jwinzer/OpenSlides,jwinzer/OpenSlides,FinnStutzenstein/OpenSlides,FinnStutzenstein/OpenSlides,FinnStutzenstein/OpenSlides,jwinzer/OpenSlides,CatoTH/OpenSlides,CatoTH/OpenSlides,jwinzer/OpenSlides,CatoTH/OpenSlides,FinnStutzenstein/OpenSlides | import os
from django.core.management.base import BaseCommand
from ...settings import create_saml_settings, get_settings_dir_and_path
class Command(BaseCommand):
"""
Command to create the saml_settings.json file.
"""
help = "Create the saml_settings.json settings file."
def add_arguments(self,... | Fix check on wrong variable
import os
from django.core.management.base import BaseCommand
from ...settings import create_saml_settings, get_settings_dir_and_path
class Command(BaseCommand):
"""
Command to create the saml_settings.json file.
"""
help = "Create the saml_settings.json settings file."
... |
75606e2b13a29a5d68894eda86dbede8292fb0c8 | website/project/taxonomies/__init__.py | website/project/taxonomies/__init__.py | from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, default=lambda: str(ObjectId()))
text = fields.String... | import pymongo
from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
__indices__ = [
{
'unique': True,
'key_or_list':... | Add unique index on the subject model for @chrisseto | Add unique index on the subject model for @chrisseto
| Python | apache-2.0 | hmoco/osf.io,alexschiller/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,aaxelb/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,crcresearch/osf.io,chrisseto/osf.io,alexschiller/osf.io,aaxel... | import pymongo
from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
__indices__ = [
{
'unique': True,
'key_or_list':... | Add unique index on the subject model for @chrisseto
from modularodm import fields
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website.util import api_v2_url
@mongo_utils.unique_on(['text'])
class Subject(StoredObject):
_id = fields.StringField(primary=True, def... |
1307d737a73122d948fd106ca39274b7cf505f89 | Lib/test/test_threading.py | Lib/test/test_threading.py | # Very rudimentary test of threading module
# Create a bunch of threads, let each do some work, wait until all are done
from test_support import verbose
import random
import threading
import time
numtasks = 10
# no more than 3 of the 10 can run at once
sema = threading.BoundedSemaphore(value=3)
mutex = threading.RL... | # Very rudimentary test of threading module
# Create a bunch of threads, let each do some work, wait until all are done
from test_support import verbose
import random
import threading
import time
# This takes about n/3 seconds to run (about n/3 clumps of tasks, times
# about 1 second per clump).
numtasks = 10
# no ... | Test failed because these was no expected-output file, but always printed to stdout. Repaired by not printing at all except in verbose mode. | Test failed because these was no expected-output file, but always printed
to stdout. Repaired by not printing at all except in verbose mode.
Made the test about 6x faster -- envelope analysis showed it took time
proportional to the square of the # of tasks. Now it's linear.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | # Very rudimentary test of threading module
# Create a bunch of threads, let each do some work, wait until all are done
from test_support import verbose
import random
import threading
import time
# This takes about n/3 seconds to run (about n/3 clumps of tasks, times
# about 1 second per clump).
numtasks = 10
# no ... | Test failed because these was no expected-output file, but always printed
to stdout. Repaired by not printing at all except in verbose mode.
Made the test about 6x faster -- envelope analysis showed it took time
proportional to the square of the # of tasks. Now it's linear.
# Very rudimentary test of threading modu... |
5de36454db293c03039bec3c8c628995f07825b0 | src/txkube/_compat.py | src/txkube/_compat.py | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Helpers for Python 2/3 compatibility.
"""
from json import dumps
from twisted.python.compat import unicode
def dumps_bytes(obj):
"""
Serialize ``obj`` to JSON formatted ``bytes``.
"""
b = dumps(obj)
if isinstance(b, unicode)... | Add a dumps_bytes() helper method to handle Python 2/3 compatibility. | Add a dumps_bytes() helper method to handle Python 2/3 compatibility.
| Python | mit | LeastAuthority/txkube | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Helpers for Python 2/3 compatibility.
"""
from json import dumps
from twisted.python.compat import unicode
def dumps_bytes(obj):
"""
Serialize ``obj`` to JSON formatted ``bytes``.
"""
b = dumps(obj)
if isinstance(b, unicode)... | Add a dumps_bytes() helper method to handle Python 2/3 compatibility.
| |
782fc597ab79acb3cbd0d9dffb4ed77cc561d894 | gimlet/tests/test_session.py | gimlet/tests/test_session.py | from unittest import TestCase
from webob import Request
from gimlet.factories import session_factory_factory
class TestSession(TestCase):
def _make_session(self, secret='secret', **options):
request = Request.blank('/')
return session_factory_factory(secret, **options)(request)
def test_se... | Add unit tests for Session | Add unit tests for Session
| Python | mit | storborg/gimlet | from unittest import TestCase
from webob import Request
from gimlet.factories import session_factory_factory
class TestSession(TestCase):
def _make_session(self, secret='secret', **options):
request = Request.blank('/')
return session_factory_factory(secret, **options)(request)
def test_se... | Add unit tests for Session
| |
c6566b2917adce3f94cd1233671ecba07f7ea4e0 | problem_3/solution.py | problem_3/solution.py | def largest_prime_factor(n, h):
for i in xrange(2, n+1):
d, m = divmod(n, i)
if m == 0:
largest_prime_factor(d, i)
break
if n == 1: print h
largest_prime_factor(600851475143, 0)
| Add python implementation for problem 3 | Add python implementation for problem 3
| Python | mit | mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler | def largest_prime_factor(n, h):
for i in xrange(2, n+1):
d, m = divmod(n, i)
if m == 0:
largest_prime_factor(d, i)
break
if n == 1: print h
largest_prime_factor(600851475143, 0)
| Add python implementation for problem 3
| |
8e608c2155a4a466f1a4bf87df05c4e4ebd90c1c | django/__init__.py | django/__init__.py | VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
| VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if ... | Update django.VERSION in trunk per previous discussion | Update django.VERSION in trunk per previous discussion
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@9103 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| Python | bsd-3-clause | blindroot/django,lsqtongxin/django,jgoclawski/django,blighj/django,fenginx/django,riklaunim/django-custom-multisite,jn7163/django,alrifqi/django,ryangallen/django,charettes/django,eugena/django,AndrewGrossman/django,yakky/django,eugena/django,denys-duchier/django,EliotBerriot/django,dwightgunning/django,hassanabidpk/dj... | VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if ... | Update django.VERSION in trunk per previous discussion
git-svn-id: 4f9f921b081c523744c7bf24d959a0db39629563@9103 bcc190cf-cafb-0310-a4f2-bffc1f526a37
VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VER... |
312a742e31fb33b43a946da0016db201ca809799 | seria/utils.py | seria/utils.py | # -*- coding: utf-8 -*-
def str_to_num(i, exact_match=True):
"""
Attempts to convert a str to either an int or float
"""
# TODO: Cleanup -- this is really ugly
if not isinstance(i, str):
return i
try:
_ = int(i)
if not exact_match:
return _
elif str(_... | # -*- coding: utf-8 -*-
def str_to_num(i, exact_match=True):
"""
Attempts to convert a str to either an int or float
"""
# TODO: Cleanup -- this is really ugly
if not isinstance(i, str):
return i
try:
if not exact_match:
return int(i)
elif str(int(i)) == i:
... | Refactor str_to_num to be more concise | Refactor str_to_num to be more concise
Functionally nothing has changed. We just need not try twice nor
define the variable _ twice.
| Python | mit | rtluckie/seria | # -*- coding: utf-8 -*-
def str_to_num(i, exact_match=True):
"""
Attempts to convert a str to either an int or float
"""
# TODO: Cleanup -- this is really ugly
if not isinstance(i, str):
return i
try:
if not exact_match:
return int(i)
elif str(int(i)) == i:
... | Refactor str_to_num to be more concise
Functionally nothing has changed. We just need not try twice nor
define the variable _ twice.
# -*- coding: utf-8 -*-
def str_to_num(i, exact_match=True):
"""
Attempts to convert a str to either an int or float
"""
# TODO: Cleanup -- this is really ugly
if n... |
1a2e892539cde260934ceffe58d399c5a3222d0c | actions/cloudbolt_plugins/multi_user_approval/two_user_approval.py | actions/cloudbolt_plugins/multi_user_approval/two_user_approval.py | """
Two User Approval
Overrides CloudBolt's standard Order Approval workflow. This Orchestration
Action requires two users to approve an order before it is becomes Active.
"""
from utilities.logger import ThreadLogger
logger = ThreadLogger(__name__)
def run(order, *args, **kwargs):
# Return the order's status ... | """
Two User Approval
Overrides CloudBolt's standard Order Approval workflow. This Orchestration
Action requires two users to approve an order before it becomes Active.
Requires CloudBolt 8.8
"""
def run(order, *args, **kwargs):
# Return the order's status to "PENDING" if fewer than two users have
# approve... | Remove logger and fix typos | Remove logger and fix typos
[DEV-12140]
| Python | apache-2.0 | CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge | """
Two User Approval
Overrides CloudBolt's standard Order Approval workflow. This Orchestration
Action requires two users to approve an order before it becomes Active.
Requires CloudBolt 8.8
"""
def run(order, *args, **kwargs):
# Return the order's status to "PENDING" if fewer than two users have
# approve... | Remove logger and fix typos
[DEV-12140]
"""
Two User Approval
Overrides CloudBolt's standard Order Approval workflow. This Orchestration
Action requires two users to approve an order before it is becomes Active.
"""
from utilities.logger import ThreadLogger
logger = ThreadLogger(__name__)
def run(order, *args, *... |
c2859bd8da741862ee01a276a1350fb4a5931dbc | data_access.py | data_access.py | #!/usr/bin/env python
import sys
import mysql.connector
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
cursor.close()
print("Inserting employees...... | #!/usr/bin/env python
from random import randint
import sys
import mysql.connector
NUM_EMPLOYEES = 10000
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
... | Change data access script to issue SELECTs that actually return a value | Change data access script to issue SELECTs that actually return a value
This makes the part about tracing the SQL statements and tracing the
number of rows returned a little more interesting.
| Python | mit | goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop | #!/usr/bin/env python
from random import randint
import sys
import mysql.connector
NUM_EMPLOYEES = 10000
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
... | Change data access script to issue SELECTs that actually return a value
This makes the part about tracing the SQL statements and tracing the
number of rows returned a little more interesting.
#!/usr/bin/env python
import sys
import mysql.connector
def insert():
cursor = connection.cursor()
try:
curs... |
4883bd13c6e07a0568c29fd26a141888b52292b7 | utils/player_draft_retriever.py | utils/player_draft_retriever.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import requests
from lxml import html
from db.team import Team
from db.player_draft import PlayerDraft
class PlayerDraftRetriever():
NHL_PLAYER_DRAFT_PREFIX = "https://www.nhl.com/player"
DRAFT_INFO_REGEX = re.compile(
"(\d{4})\s(.+),\s(\d+).+... | Add retriever object for player draft information | Add retriever object for player draft information
| Python | mit | leaffan/pynhldb | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import requests
from lxml import html
from db.team import Team
from db.player_draft import PlayerDraft
class PlayerDraftRetriever():
NHL_PLAYER_DRAFT_PREFIX = "https://www.nhl.com/player"
DRAFT_INFO_REGEX = re.compile(
"(\d{4})\s(.+),\s(\d+).+... | Add retriever object for player draft information
| |
253e4e9df1b6a6cec7c20bc34a8ccf9423c8018e | scripts/create_neurohdf.py | scripts/create_neurohdf.py | #!/usr/bin/python
# Create a project and stack associated HDF5 file with additional
# data such as labels, meshes etc.
import os.path as op
import h5py
from contextlib import closing
import numpy as np
project_id = 1
stack_id = 1
filepath = '/home/stephan/dev/CATMAID/django/hdf5'
with closing(h5py.File(op.join(fil... | #!/usr/bin/python
# Create a project and stack associated HDF5 file with additional
# data such as labels, meshes etc.
import os.path as op
import h5py
from contextlib import closing
import numpy as np
project_id = 1
stack_id = 2
filepath = '/home/stephan/dev/CATMAID/django/hdf5'
with closing(h5py.File(op.join(fil... | Change in coordinates in the NeuroHDF create | Change in coordinates in the NeuroHDF create
| Python | agpl-3.0 | htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID | #!/usr/bin/python
# Create a project and stack associated HDF5 file with additional
# data such as labels, meshes etc.
import os.path as op
import h5py
from contextlib import closing
import numpy as np
project_id = 1
stack_id = 2
filepath = '/home/stephan/dev/CATMAID/django/hdf5'
with closing(h5py.File(op.join(fil... | Change in coordinates in the NeuroHDF create
#!/usr/bin/python
# Create a project and stack associated HDF5 file with additional
# data such as labels, meshes etc.
import os.path as op
import h5py
from contextlib import closing
import numpy as np
project_id = 1
stack_id = 1
filepath = '/home/stephan/dev/CATMAID/dj... |
aa110dca3b424141d57ad5804efc5e90db52aa3c | cfgrib/__main__.py | cfgrib/__main__.py |
import argparse
import sys
from . import eccodes
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--selfcheck', default=False, action='store_true')
args = parser.parse_args()
if args.selfcheck:
eccodes.codes_get_api_version()
print("Your system is ready.")
else... | Add a basic selfcheck easily callable from the command line. | Add a basic selfcheck easily callable from the command line.
| Python | apache-2.0 | ecmwf/cfgrib |
import argparse
import sys
from . import eccodes
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--selfcheck', default=False, action='store_true')
args = parser.parse_args()
if args.selfcheck:
eccodes.codes_get_api_version()
print("Your system is ready.")
else... | Add a basic selfcheck easily callable from the command line.
| |
d343ba2abc476e1c6a26e273b9262aa5974b8ab5 | fireplace/rules.py | fireplace/rules.py | """
Base game rules (events, etc)
"""
from .actions import Attack, Damage, Destroy, Hit
from .dsl.selector import FRIENDLY_HERO, MINION, SELF
POISONOUS = Damage(MINION, None, SELF).on(Destroy(Damage.TARGETS))
class WeaponRules:
base_events = [
Attack(FRIENDLY_HERO).on(Hit(SELF, 1))
]
| """
Base game rules (events, etc)
"""
from .actions import Attack, Damage, Destroy, Hit
from .dsl.selector import FRIENDLY_HERO, MINION, SELF
POISONOUS = Damage(MINION, None, SELF).on(Destroy(Damage.TARGETS))
class WeaponRules:
base_events = [
Attack(FRIENDLY_HERO).after(Hit(SELF, 1))
]
| Move Weapon durability hits to Attack.after() | Move Weapon durability hits to Attack.after()
| Python | agpl-3.0 | smallnamespace/fireplace,smallnamespace/fireplace,jleclanche/fireplace,amw2104/fireplace,NightKev/fireplace,beheh/fireplace,Ragowit/fireplace,Ragowit/fireplace,amw2104/fireplace | """
Base game rules (events, etc)
"""
from .actions import Attack, Damage, Destroy, Hit
from .dsl.selector import FRIENDLY_HERO, MINION, SELF
POISONOUS = Damage(MINION, None, SELF).on(Destroy(Damage.TARGETS))
class WeaponRules:
base_events = [
Attack(FRIENDLY_HERO).after(Hit(SELF, 1))
]
| Move Weapon durability hits to Attack.after()
"""
Base game rules (events, etc)
"""
from .actions import Attack, Damage, Destroy, Hit
from .dsl.selector import FRIENDLY_HERO, MINION, SELF
POISONOUS = Damage(MINION, None, SELF).on(Destroy(Damage.TARGETS))
class WeaponRules:
base_events = [
Attack(FRIENDLY_HERO).... |
e6d3d60265db1947b8af2d1c59c575c632ddc20b | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by @kungfusheep
# Copyright (c) 2016 @kungfusheep
#
# License: MIT
#
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provide... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by @kungfusheep
# Copyright (c) 2016 @kungfusheep
#
# License: MIT
#
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provide... | Add support for handling errors and warnings | Add support for handling errors and warnings
| Python | mit | lzwme/SublimeLinter-contrib-stylelint,lzwme/SublimeLinter-contrib-stylelint,kungfusheep/SublimeLinter-contrib-stylelint | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by @kungfusheep
# Copyright (c) 2016 @kungfusheep
#
# License: MIT
#
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provide... | Add support for handling errors and warnings
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by @kungfusheep
# Copyright (c) 2016 @kungfusheep
#
# License: MIT
#
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, ... |
d2bcba204d36a8ffd1e6a1ed79b89fcb6f1c88c5 | ideas/test_kmc.py | ideas/test_kmc.py | # This code will test out the idea of using kmc to
# 1. quickly enumerate the k-mers
# 2. intersect these with the training database, output as fasta
# 3. use that reduced fasta of intersecting kmers as the query to CMash
####################################################################
# First, I will need to dump... | Add file to test out kmc approach. Dump training k-mers to fasta file | Add file to test out kmc approach. Dump training k-mers to fasta file
| Python | bsd-3-clause | dkoslicki/CMash,dkoslicki/CMash | # This code will test out the idea of using kmc to
# 1. quickly enumerate the k-mers
# 2. intersect these with the training database, output as fasta
# 3. use that reduced fasta of intersecting kmers as the query to CMash
####################################################################
# First, I will need to dump... | Add file to test out kmc approach. Dump training k-mers to fasta file
| |
1cd217777c1c0f9643fe203c68cdd091e00fc909 | tests/test_validate_export.py | tests/test_validate_export.py | import Bio.Phylo
from io import StringIO
from pathlib import Path
import pytest
import sys
# we assume (and assert) that this script is running from the tests/ directory
sys.path.append(str(Path(__file__).parent.parent.parent))
from augur.export_v2 import convert_tree_to_json_structure
from augur.validate import Vali... | Add unit tests for ensure_no_duplicate_names | Add unit tests for ensure_no_duplicate_names
Adds minimal tests for validation of no duplicate names. Instead of
mocking up the tree JSON directly, these tests build a minimal BioPython
tree and use augur's own tree-to-JSON function to make the more verbose
JSON structure expected by the validation function.
| Python | agpl-3.0 | nextstrain/augur,nextstrain/augur,nextstrain/augur,blab/nextstrain-augur | import Bio.Phylo
from io import StringIO
from pathlib import Path
import pytest
import sys
# we assume (and assert) that this script is running from the tests/ directory
sys.path.append(str(Path(__file__).parent.parent.parent))
from augur.export_v2 import convert_tree_to_json_structure
from augur.validate import Vali... | Add unit tests for ensure_no_duplicate_names
Adds minimal tests for validation of no duplicate names. Instead of
mocking up the tree JSON directly, these tests build a minimal BioPython
tree and use augur's own tree-to-JSON function to make the more verbose
JSON structure expected by the validation function.
| |
e721f5fc7481e7970ba5e281e37b426123b415c3 | ruledxml/tests/test_order.py | ruledxml/tests/test_order.py | #!/usr/bin/env python3
import io
import unittest
import ruledxml
from . import utils
class TestRuledXmlForeach(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src:
ruledxml.run(src, utils.data('030_rules.py'), result)
... | #!/usr/bin/env python3
import io
import unittest
import ruledxml
from . import utils
class TestRuledXmlOrder(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src:
ruledxml.run(src, utils.data('030_rules.py'), result)
wi... | Fix name: should be TestRuledXmlOrder, not TestRuledXmlForeach. | Fix name: should be TestRuledXmlOrder, not TestRuledXmlForeach.
| Python | bsd-3-clause | meisterluk/ruledxml | #!/usr/bin/env python3
import io
import unittest
import ruledxml
from . import utils
class TestRuledXmlOrder(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src:
ruledxml.run(src, utils.data('030_rules.py'), result)
wi... | Fix name: should be TestRuledXmlOrder, not TestRuledXmlForeach.
#!/usr/bin/env python3
import io
import unittest
import ruledxml
from . import utils
class TestRuledXmlForeach(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src:
... |
44d820daf3a56284f3204f4e1d586ddd5938a29f | bin/physicsforum_scraper.py | bin/physicsforum_scraper.py | #!/usr/bin/env python
import argparse
import os
import os.path
from bs4 import BeautifulSoup
import requests
def post_filter(tag):
if tag.name != 'blockquote':
return False
if not tag.has_attr('class'):
return False
return isinstance(tag['class'], list) and 'messageText' in tag['class']
... | Write scraper script for Physicsforum forum | Write scraper script for Physicsforum forum
| Python | mit | kemskems/otdet | #!/usr/bin/env python
import argparse
import os
import os.path
from bs4 import BeautifulSoup
import requests
def post_filter(tag):
if tag.name != 'blockquote':
return False
if not tag.has_attr('class'):
return False
return isinstance(tag['class'], list) and 'messageText' in tag['class']
... | Write scraper script for Physicsforum forum
| |
62d5682fa3be9dfbae80b2acae9839cd1278dcb6 | whatismyip.py | whatismyip.py | #! /usr/bin/python
import requests
from bs4 import BeautifulSoup
def main():
r = requests.get('http://www.whatismyip.com')
soup = BeautifulSoup(r.text)
ip_address = ''
for span in soup.find('div', 'the-ip'):
ip_address += span.text
print(ip_address)
if __name__ == '__main__':
ma... | #! /usr/bin/python
import requests
from bs4 import BeautifulSoup
def main():
r = requests.get('http://www.whatismyip.com')
soup = BeautifulSoup(r.text, 'lxml')
ip_address = ''
for span in soup.find('div', 'the-ip'):
ip_address += span.text
print(ip_address)
if __name__ == '__main__'... | Use lxml as a parsing engine for bs4 | Use lxml as a parsing engine for bs4
| Python | apache-2.0 | MichaelAquilina/whatismyip | #! /usr/bin/python
import requests
from bs4 import BeautifulSoup
def main():
r = requests.get('http://www.whatismyip.com')
soup = BeautifulSoup(r.text, 'lxml')
ip_address = ''
for span in soup.find('div', 'the-ip'):
ip_address += span.text
print(ip_address)
if __name__ == '__main__'... | Use lxml as a parsing engine for bs4
#! /usr/bin/python
import requests
from bs4 import BeautifulSoup
def main():
r = requests.get('http://www.whatismyip.com')
soup = BeautifulSoup(r.text)
ip_address = ''
for span in soup.find('div', 'the-ip'):
ip_address += span.text
print(ip_addres... |
a726625e13ac08d0b6c2c686de476b6e78bc0f48 | dlstats/fetchers/test__skeleton.py | dlstats/fetchers/test__skeleton.py | import unittest
from datetime import datetime
from _skeleton import Dataset
class DatasetTestCase(unittest.TestCase):
def test_full_example(self):
self.assertIsInstance(Dataset(provider='Test provider',name='GDP',dataset_code='nama_gdp_fr',dimension_list=[{'name':'COUNTRY','values':[('FR','France'),('DE','... | Add unit test for _skeleton | Add unit test for _skeleton
| Python | agpl-3.0 | MichelJuillard/dlstats,mmalter/dlstats,Widukind/dlstats,MichelJuillard/dlstats,mmalter/dlstats,Widukind/dlstats,MichelJuillard/dlstats,mmalter/dlstats | import unittest
from datetime import datetime
from _skeleton import Dataset
class DatasetTestCase(unittest.TestCase):
def test_full_example(self):
self.assertIsInstance(Dataset(provider='Test provider',name='GDP',dataset_code='nama_gdp_fr',dimension_list=[{'name':'COUNTRY','values':[('FR','France'),('DE','... | Add unit test for _skeleton
| |
3c0db422301955430ecd572103097fc68fec254d | tests/testapp/admin.py | tests/testapp/admin.py | from django import forms
from django.contrib import admin
from django.db import models
from content_editor.admin import ContentEditor, ContentEditorInline
from .models import Article, Download, RichText, Thing
class RichTextarea(forms.Textarea):
def __init__(self, attrs=None):
default_attrs = {"class": ... | from django import forms
from django.contrib import admin
from django.db import models
from content_editor.admin import ContentEditor, ContentEditorInline
from .models import Article, Download, RichText, Thing
class RichTextarea(forms.Textarea):
def __init__(self, attrs=None):
default_attrs = {"class": ... | Use sets to define allowed regions for plugins | Use sets to define allowed regions for plugins
| Python | bsd-3-clause | matthiask/django-content-editor,matthiask/django-content-editor,matthiask/feincms2-content,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/django-content-editor,matthiask/feincms2-content | from django import forms
from django.contrib import admin
from django.db import models
from content_editor.admin import ContentEditor, ContentEditorInline
from .models import Article, Download, RichText, Thing
class RichTextarea(forms.Textarea):
def __init__(self, attrs=None):
default_attrs = {"class": ... | Use sets to define allowed regions for plugins
from django import forms
from django.contrib import admin
from django.db import models
from content_editor.admin import ContentEditor, ContentEditorInline
from .models import Article, Download, RichText, Thing
class RichTextarea(forms.Textarea):
def __init__(self,... |
9e5ec6fc67c863dea2de26ce742f0940ad43562c | Communication/benchPrototypeAPI.py | Communication/benchPrototypeAPI.py | import sys
sys.path.append('/home/bat/Python-Arduino-Proto-API-v2/arduino')
import time
locations = ['/dev/ttyACM0','/dev/ttyACM1','/dev/ttyACM2','/dev/ttyACM3','/dev/ttyACM4','/dev/ttyACM5','/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyUSB2','/dev/ttyUSB3','/dev/ttyS0','/dev/ttyS1','/dev/ttyS2','/dev/ttyS3']
from firmata im... | Add a script to benchmark python to arduino libraries | Add a script to benchmark python to arduino libraries
| Python | mit | baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite,baptistelabat/robokite | import sys
sys.path.append('/home/bat/Python-Arduino-Proto-API-v2/arduino')
import time
locations = ['/dev/ttyACM0','/dev/ttyACM1','/dev/ttyACM2','/dev/ttyACM3','/dev/ttyACM4','/dev/ttyACM5','/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyUSB2','/dev/ttyUSB3','/dev/ttyS0','/dev/ttyS1','/dev/ttyS2','/dev/ttyS3']
from firmata im... | Add a script to benchmark python to arduino libraries
| |
75a70e31791c523da6bf6b0ce4409a77f2784ed5 | byceps/services/user/transfer/models.py | byceps/services/user/transfer/models.py | """
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import Optional
from attr import attrs
from ....typing import UserID
@attrs(auto_attribs=True, frozen=True, slots=True)
class Us... | """
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from dataclasses import dataclass
from typing import Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserI... | Change user transfer model from `attrs` to `dataclass` | Change user transfer model from `attrs` to `dataclass`
| Python | bsd-3-clause | m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | """
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from dataclasses import dataclass
from typing import Optional
from ....typing import UserID
@dataclass(frozen=True)
class User:
id: UserI... | Change user transfer model from `attrs` to `dataclass`
"""
byceps.services.user.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from typing import Optional
from attr import attrs
from ....typing import UserID
@at... |
c47c043e76ac037456b8e966a5f9d60a151e3120 | elodie/geolocation.py | elodie/geolocation.py | from os import path
from ConfigParser import ConfigParser
import requests
import sys
def reverse_lookup(lat, lon):
if(lat is None or lon is None):
return None
if not path.exists('./config.ini'):
return None
config = ConfigParser()
config.read('./config.ini')
if('MapQuest' ... | from os import path
from ConfigParser import ConfigParser
import requests
import sys
def reverse_lookup(lat, lon):
if(lat is None or lon is None):
return None
config_file = '%s/config.ini' % path.dirname(path.dirname(path.abspath(__file__)))
if not path.exists(config_file):
return None
... | Use absolute path for config file so it works with apps like Hazel | Use absolute path for config file so it works with apps like Hazel
| Python | apache-2.0 | zserg/elodie,zingo/elodie,jmathai/elodie,jmathai/elodie,zingo/elodie,zserg/elodie,zserg/elodie,jmathai/elodie,zserg/elodie,jmathai/elodie,zingo/elodie | from os import path
from ConfigParser import ConfigParser
import requests
import sys
def reverse_lookup(lat, lon):
if(lat is None or lon is None):
return None
config_file = '%s/config.ini' % path.dirname(path.dirname(path.abspath(__file__)))
if not path.exists(config_file):
return None
... | Use absolute path for config file so it works with apps like Hazel
from os import path
from ConfigParser import ConfigParser
import requests
import sys
def reverse_lookup(lat, lon):
if(lat is None or lon is None):
return None
if not path.exists('./config.ini'):
return None
config... |
8420a10364176f1b5fbb15774f72497b55b44d81 | flaskapp/tests/test_getters_setters.py | flaskapp/tests/test_getters_setters.py | import pytest
from appname.models import db, Tag
@pytest.mark.usefixtures("testapp")
class TestModels:
def test_Tag(self, testapp):
t = Tag('tagName')
assert t.namex == 'tagName'
t.namex = 'blah'
assert t.namex == 'blah'
assert t.idx == t.id
| Add get/set for Tags, and test | Add get/set for Tags, and test
| Python | bsd-3-clause | ikinsella/squall,ikinsella/squall,ikinsella/squall,ikinsella/squall | import pytest
from appname.models import db, Tag
@pytest.mark.usefixtures("testapp")
class TestModels:
def test_Tag(self, testapp):
t = Tag('tagName')
assert t.namex == 'tagName'
t.namex = 'blah'
assert t.namex == 'blah'
assert t.idx == t.id
| Add get/set for Tags, and test
| |
7039e4f25d8eecdf2d5d2b4a4a769e05c5075222 | bluebottle/members/migrations/0020_auto_20171031_1048.py | bluebottle/members/migrations/0020_auto_20171031_1048.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-10-31 09:48
from __future__ import unicode_literals
from django.db import migrations
def rename_full_member_permission(apps, schema_editor):
Permission = apps.get_model('auth', 'Permission')
perm = Permission.objects.get(codename='api_read_full_me... | Fix description of 'api_read_full_member' permission | Fix description of 'api_read_full_member' permission
BB-11023 #resolve
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2017-10-31 09:48
from __future__ import unicode_literals
from django.db import migrations
def rename_full_member_permission(apps, schema_editor):
Permission = apps.get_model('auth', 'Permission')
perm = Permission.objects.get(codename='api_read_full_me... | Fix description of 'api_read_full_member' permission
BB-11023 #resolve
| |
89f3aabf89357dae539fd31979b44c05bbdf5a05 | cas/log.py | cas/log.py | from __future__ import absolute_import
from cas.config import DEBUG
import logging
LOG = logging.getLogger()
if DEBUG:
logging.basicConfig()
LOG.setLevel(logging.DEBUG)
| from __future__ import absolute_import
from cas.config import DEBUG
import logging
LOG = logging.getLogger()
def enable_debug():
logging.basicConfig()
LOG.setLevel(logging.DEBUG)
if DEBUG:
enable_debug()
| Allow other parts of the lib to enable debugging | Allow other parts of the lib to enable debugging
| Python | bsd-3-clause | jcmcken/cas | from __future__ import absolute_import
from cas.config import DEBUG
import logging
LOG = logging.getLogger()
def enable_debug():
logging.basicConfig()
LOG.setLevel(logging.DEBUG)
if DEBUG:
enable_debug()
| Allow other parts of the lib to enable debugging
from __future__ import absolute_import
from cas.config import DEBUG
import logging
LOG = logging.getLogger()
if DEBUG:
logging.basicConfig()
LOG.setLevel(logging.DEBUG)
|
b260040bc3ca48b4e76d73c6efe60b964fa5c108 | tests/UnreachableSymbolsRemove/RemovingTerminalsTest.py | tests/UnreachableSymbolsRemove/RemovingTerminalsTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 17.08.2017 14:23
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import main, TestCase
from grammpy import *
from grammpy_transforms import *
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class D(Nonterminal):... | Add test of removing unreachable terminals | Add test of removing unreachable terminals
| Python | mit | PatrikValkovic/grammpy | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 17.08.2017 14:23
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import main, TestCase
from grammpy import *
from grammpy_transforms import *
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class D(Nonterminal):... | Add test of removing unreachable terminals
| |
914e419cd753f6815b2aa308b49d7ed357b523d6 | muzicast/web/__init__.py | muzicast/web/__init__.py | import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
app.secret_key = os.urandom(24)
| import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
#from muzicast.web.music import artist, album, track
#app.register_module(artist, url_prefix='/artist')
#app.register_module(album, url_prefix='/album')
#app.register_module(tr... | Add handler modules as required | Add handler modules as required
| Python | mit | nikhilm/muzicast,nikhilm/muzicast | import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
#from muzicast.web.music import artist, album, track
#app.register_module(artist, url_prefix='/artist')
#app.register_module(album, url_prefix='/album')
#app.register_module(tr... | Add handler modules as required
import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
app.secret_key = os.urandom(24)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.