commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
24e3c89f0093bafd9618dd5c3eb5ad147be0f4c3 | project/apps/api/filters.py | project/apps/api/filters.py | import rest_framework_filters as filters
from .models import (
Chart,
Convention,
Group,
Person,
Venue,
)
class ChartFilter(filters.FilterSet):
class Meta:
model = Chart
fields = {
'name': filters.ALL_LOOKUPS,
}
class ConventionFilter(filters.FilterSet):
... | import rest_framework_filters as filters
from .models import (
Chart,
Convention,
Group,
Person,
Venue,
)
class ChartFilter(filters.FilterSet):
class Meta:
model = Chart
fields = {
'name': filters.ALL_LOOKUPS,
}
class ConventionFilter(filters.FilterSet):
... | Add season to Convention filter | Add season to Convention filter
| Python | bsd-2-clause | barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore-django,dbinetti/barberscore-django,barberscore/barberscore-api |
43732458a09c136cc64b0c1c46584c9ba1ed5300 | exploratory_analysis/time_scan.py | exploratory_analysis/time_scan.py | import os
from utils import Reader
if __name__ == '__main__':
working_directory = os.getcwd()
files = Reader.read_directory(working_directory)
for f in files:
tweets = Reader.read_file(f)
for tweet in tweets:
print '{}, {}'.format(tweet.verb(), tweet.timestamp())
| import os
from utils import Reader
if __name__ == '__main__':
working_directory = os.getcwd()
files = Reader.read_directory(working_directory)
for f in files:
tweets = Reader.read_file(f)
eng_tweets = filter(lambda t: t.language() == 'en', tweets)
for tweet in tweets:
pr... | Return only english tweet and print the body of the tweet for analysis via other tools | Return only english tweet and print the body of the tweet for analysis via other tools
| Python | apache-2.0 | chuajiesheng/twitter-sentiment-analysis |
e3f1531ff0583f5710d7067b3f31a2ae65f8a747 | stackviz_deployer/db/database.py | stackviz_deployer/db/database.py | # Copyright 2016 Hewlett-Packard Development Company, L.P.
#
# 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... | # Copyright 2016 Hewlett-Packard Development Company, L.P.
#
# 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... | Allow environment variable overrides for DB connection. | Allow environment variable overrides for DB connection.
This allows docker-style environment variables to override the default
database connection info.
| Python | apache-2.0 | timothyb89/stackviz-deployer,timothyb89/stackviz-deployer,timothyb89/stackviz-deployer |
fa1d67d3fc10f1c5a2c253b3c3609db4be9c599c | src/foremast/pipeline/create_pipeline_manual.py | src/foremast/pipeline/create_pipeline_manual.py | # Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# 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... | # Foremast - Pipeline Tooling
#
# Copyright 2016 Gogo, LLC
#
# 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... | Use filename for Pipeline name | fix: Use filename for Pipeline name
See also: #72
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast |
8c982822009cb414411bc4488591e35c8d4a8bcb | migrations/0007_make_ds_name_unique.py | migrations/0007_make_ds_name_unique.py | from redash.models import db
if __name__ == '__main__':
db.connect_db()
with db.database.transaction():
# Make sure all data sources names are unique.
db.database.execute_sql("""UPDATE data_sources SET name = name || ' ' || id;""")
# Add unique constraint on data_sources.name.
... | from redash.models import db
if __name__ == '__main__':
db.connect_db()
with db.database.transaction():
# Make sure all data sources names are unique.
db.database.execute_sql("""
UPDATE data_sources
SET name = new_names.name
FROM (
SELECT id, name || ' ' || ... | Rename only data sources with duplicates | Rename only data sources with duplicates
| Python | bsd-2-clause | stefanseifert/redash,akariv/redash,M32Media/redash,EverlyWell/redash,imsally/redash,ninneko/redash,crowdworks/redash,alexanderlz/redash,akariv/redash,easytaxibr/redash,pubnative/redash,stefanseifert/redash,denisov-vlad/redash,alexanderlz/redash,pubnative/redash,jmvasquez/redashtest,easytaxibr/redash,EverlyWell/redash,a... |
db0be000a99e0dac7c9d37817cfd5000b7121ef3 | stream/rest/views.py | stream/rest/views.py | # Author: Braedy Kuzma
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
import uuid
from dash.models import Post
from .serializers import PostSerializer
# Initially taken from
# http://www.django-rest-framework.org/tutorial/1-s... | # Author: Braedy Kuzma
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
import uuid
from dash.models import Post
from .serializers import PostSerializer
# Initially taken from
# http://www.django-rest-framework.org/tutorial/1-s... | Add multiple objects returned error. | Add multiple objects returned error.
| Python | apache-2.0 | CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project |
902e4ce0848cc2c3afa7192a85d413ed2919c798 | csunplugged/tests/plugging_it_in/models/test_testcase.py | csunplugged/tests/plugging_it_in/models/test_testcase.py | from plugging_it_in.models import TestCase
from tests.BaseTestWithDB import BaseTestWithDB
from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator
class TestCaseModelTest(BaseTestWithDB):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.test_data = Top... | from tests.BaseTestWithDB import BaseTestWithDB
from tests.topics.TopicsTestDataGenerator import TopicsTestDataGenerator
class TestCaseModelTest(BaseTestWithDB):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.test_data = TopicsTestDataGenerator()
def create_testc... | Fix models unit test for plugging it in | Fix models unit test for plugging it in
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged |
ae655d0979816892f4cb0a4f8a9b3cbe910d7248 | stock_request_direction/models/stock_request_order.py | stock_request_direction/models/stock_request_order.py | # Copyright (c) 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = "stock.request.order"
direction = fields.Selection(
[("outbound", "Outbound"), ("inbound", "Inboun... | # Copyright (c) 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = "stock.request.order"
direction = fields.Selection(
[("outbound", "Outbound"), ("inbound", "Inboun... | Add warehouse_id to existing onchange. | [IMP] Add warehouse_id to existing onchange.
| Python | agpl-3.0 | OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse |
010d3501afce9ae9ae79a01d5c2e6118a9009df2 | tests/cupy_tests/random_tests/test_sample.py | tests/cupy_tests/random_tests/test_sample.py | import unittest
from cupy import testing
@testing.gpu
class TestSample(unittest.TestCase):
_multiprocess_can_split_ = True
| import mock
import unittest
import numpy
from cupy import random
from cupy import testing
@testing.gpu
class TestSample(unittest.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
random.random_sample = mock.Mock()
def test_rand(self):
random.rand(1, 2, 3, dtype=numpy.float32... | Add unittest for rand and randn | Add unittest for rand and randn
| Python | mit | delta2323/chainer,okuta/chainer,kiyukuta/chainer,cupy/cupy,sinhrks/chainer,kashif/chainer,tscohen/chainer,ktnyt/chainer,hvy/chainer,cemoody/chainer,niboshi/chainer,kikusu/chainer,jnishi/chainer,okuta/chainer,niboshi/chainer,ronekko/chainer,benob/chainer,truongdq/chainer,cupy/cupy,aonotas/chainer,ktnyt/chainer,benob/cha... |
baf65a0c73a21e5080006a2f5e6be71abdc1feff | tests/test_class_to_config.py | tests/test_class_to_config.py | from __future__ import absolute_import, division, print_function
import os
import attr
import pytest
import environ
@environ.config(prefix="APP")
class AppConfig(object):
host = environ.var("127.0.0.1")
port = environ.var(5000, converter=int)
def test_default():
cfg = AppConfig.from_environ()
asse... | from __future__ import absolute_import, division, print_function
import environ
@environ.config(prefix="APP")
class AppConfig(object):
host = environ.var("127.0.0.1")
port = environ.var(5000, converter=int)
def test_default():
cfg = AppConfig.from_environ()
assert cfg.host == "127.0.0.1"
assert... | Fix formatting, remove unused vars | Fix formatting, remove unused vars
| Python | apache-2.0 | hynek/environ_config |
884071638140d4f351fde68e81117ce95f418557 | tetrahydra/tests/test_core.py | tetrahydra/tests/test_core.py | """Test core functions."""
import numpy as np
from tetrahydra.core import closure, perturb, power
def test_closure():
"""Test closure operator."""
# Given
data = np.random.random([2, 3])
expected = np.ones(2)
# When
output = np.sum(closure(data), axis=1)
# Then
assert output == pytest... | """Test core functions."""
import pytest
import numpy as np
from tetrahydra.core import closure, perturb, power
def test_closure():
"""Test closure operator."""
# Given
data = np.random.random([2, 3])
expected = np.ones(2)
# When
output = np.sum(closure(data), axis=1)
# Then
assert ou... | Revert prev commit in this file. | Revert prev commit in this file.
| Python | bsd-3-clause | ofgulban/tetrahydra |
b0e39088d326557192486a24c87df3b68bf617ce | api/models.py | api/models.py | from django.db import models
class Page(models.Model):
"""A Page in Dyanote."""
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, default='')
parent = models.ForeignKey('api.Page', null=True, related_name='children')
body = models.TextField(blank=True, defau... | from django.db import models
class Page(models.Model):
"""A Page in Dyanote."""
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, default='')
parent = models.ForeignKey('api.Page', null=True, blank=True, related_name='children')
body = models.TextField(blank... | Mark Page's parent field as 'blank' | Mark Page's parent field as 'blank'
| Python | mit | MatteoNardi/dyanote-server,MatteoNardi/dyanote-server |
1231c5e2c9fd4edc033e6021372950ca9b89c2f1 | ansible/module_utils/dcos.py | ansible/module_utils/dcos.py | import requests
def dcos_api(method, endpoint, body=None, params=None):
url = "{url}acs/api/v1{endpoint}".format(
url=params['dcos_credentials']['url'],
endpoint=endpoint)
headers = {
'Content-Type': 'application/json',
'Authorization': "t... | import requests
import urlparse
def dcos_api(method, endpoint, body=None, params=None):
result = urlparse.urlsplit(params['dcos_credentials']['url'])
netloc = result.netloc.split('@')[-1]
result = result._replace(netloc=netloc)
path = "acs/api/v1{endpoint}".format(endpoint=endpoint)
result = result... | Fix for urls with user/pass | Fix for urls with user/pass
| Python | mit | TerryHowe/ansible-modules-dcos,TerryHowe/ansible-modules-dcos |
027c7ba3036540f678ea757fa20dcb46edb079dc | mozillians/users/migrations/0038_auto_20180815_0108.py | mozillians/users/migrations/0038_auto_20180815_0108.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-08-15 08:08
from __future__ import unicode_literals
from django.db import migrations
from django.conf import settings
def add_missing_employee_vouches(apps, schema_editor):
UserProfile = apps.get_model('users', 'UserProfile')
IdpProfile = apps.get... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-08-15 08:08
from __future__ import unicode_literals
from django.db import migrations
from django.conf import settings
from django.utils.timezone import now
def add_missing_employee_vouches(apps, schema_editor):
UserProfile = apps.get_model('users', 'U... | Fix datamigration definition, model methods not available when migrating. | Fix datamigration definition, model methods not available when migrating.
| Python | bsd-3-clause | akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians |
81768b4a3ae0afc71ab7e07f0d3c45eaf0d1b5a7 | Importacions_F1_Q1/Fact_impF1_eliminar_Ja_existeix.py | Importacions_F1_Q1/Fact_impF1_eliminar_Ja_existeix.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from ooop import OOOP
import configdb
O = OOOP(**configdb.ooop)
imp_obj = O.GiscedataFacturacioImportacioLinia
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like','Ja existeix una factura')])
imp_del_ids += imp_obj.search([('state','=','erroni')... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from ooop import OOOP
import configdb
O = OOOP(**configdb.ooop)
imp_obj = O.GiscedataFacturacioImportacioLinia
imp_del_ids = imp_obj.search([('state','=','erroni'),('info','like',"Aquest fitxer XML ja s'ha processat en els següents IDs")])
#imp_del_ids += imp_obj.search(... | Refactor to new F1 erro's message | Refactor to new F1 erro's message
| Python | agpl-3.0 | Som-Energia/invoice-janitor |
0974a39c758a4ff3282e5441568befa79e50ead4 | plugins/twilio/twilio_sms.py | plugins/twilio/twilio_sms.py |
from twilio.rest import TwilioRestClient
from alerta.app import app
from alerta.plugins import PluginBase
LOG = app.logger
TWILIO_ACCOUNT_SID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
TWILIO_AUTH_TOKEN = ''
TWILIO_TO_NUMBER = ''
TWILIO_FROM_NUMBER = ''
class SendSMSMessage(PluginBase):
def pre_receive(self, al... |
import os
from twilio.rest import TwilioRestClient
from alerta.app import app
from alerta.plugins import PluginBase
LOG = app.logger
TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN')
TWILIO_TO_NUMBER = os.environ.get('TWILIO_TO_NUMBER')
TWILIO_FROM_N... | Use env vars to config twilio sms plugin | Use env vars to config twilio sms plugin
| Python | mit | alerta/alerta-contrib,alerta/alerta-contrib,msupino/alerta-contrib,alerta/alerta-contrib,msupino/alerta-contrib |
a4cffc0e74f9dd972357eb9dc49a57e10f1fe944 | core/forms.py | core/forms.py | from collections import namedtuple
from django import forms
IMAGE = "img"
UploadType = namedtuple("UploadType", ["directory", "label"])
FILE_TYPE_CHOICES = (
UploadType(directory=IMAGE, label="Image"),
UploadType(directory="thumb", label="Thumbnail"),
UploadType(directory="doc", label="Document"),
U... | from collections import namedtuple
from django import forms
IMAGE = "img"
UploadType = namedtuple("UploadType", ["directory", "label"])
FILE_TYPE_CHOICES = (
UploadType(directory=IMAGE, label="Image"),
UploadType(directory="thumb", label="Thumbnail"),
UploadType(directory="doc", label="Document"),
U... | Check names of files for spaces | Check names of files for spaces
| Python | bsd-3-clause | ahernp/DMCM,ahernp/DMCM,ahernp/DMCM |
63ef169253dbf4f9673880bccc29d97e62fdf19d | astropy/tests/image_tests.py | astropy/tests/image_tests.py | import matplotlib
from matplotlib import pyplot as plt
from ..utils.decorators import wraps
MPL_VERSION = matplotlib.__version__
ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/"
IMAGE_REFERENCE_DIR = ROOT.format(server='astropy.github.io/astropy-data', mpl_version=MPL_VERSION[:3] +... | import matplotlib
from matplotlib import pyplot as plt
from ..utils.decorators import wraps
MPL_VERSION = matplotlib.__version__
ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/"
IMAGE_REFERENCE_DIR = ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x')
def i... | Fix reference URL for images | Fix reference URL for images | Python | bsd-3-clause | pllim/astropy,larrybradley/astropy,bsipocz/astropy,StuartLittlefair/astropy,pllim/astropy,larrybradley/astropy,dhomeier/astropy,DougBurke/astropy,mhvk/astropy,saimn/astropy,larrybradley/astropy,dhomeier/astropy,lpsinger/astropy,MSeifert04/astropy,lpsinger/astropy,funbaker/astropy,DougBurke/astropy,saimn/astropy,StuartL... |
35fde537a48e4abbc98b065924fad784533cd4ee | jsonconfigparser/test/__init__.py | jsonconfigparser/test/__init__.py | import unittest
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'# comment comment\n' + \
'foo = "bar"\n' + \
... | import unittest
import tempfile
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'# comment comment\n' + \
'foo = "bar"\n... | Add basic test for read_file method | Add basic test for read_file method
| Python | bsd-3-clause | bwhmather/json-config-parser |
e50aee5973a2593546d1308b5ba77cd0905dd2be | app/models.py | app/models.py | # Data Models
# (C) Poren Chiang 2020
import dataclasses
from ntuweather import Weather
from sqlalchemy import Table, Column, DateTime, Integer, Float
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class WeatherData(Base):
"""Represents a weather record saved in the database.""... | # Data Models
# (C) Poren Chiang 2020
import dataclasses
from ntuweather import Weather
from sqlalchemy import Table, Column, DateTime, Integer, Float
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class WeatherData(Base):
"""Represents a weather record saved in the database.""... | Fix excessive fields in conversion | Fix excessive fields in conversion
| Python | agpl-3.0 | rschiang/ntu-weather,rschiang/ntu-weather |
338c904eb9efc01e9c84c8ec91d810227582e1e3 | tests/test_postgres_processor.py | tests/test_postgres_processor.py | import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from scrapi.linter.document import NormalizedDocument, RawDocument
# Need to force cassandra to ignore set keyspace
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
test_db = PostgresPr... | import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from scrapi.linter.document import NormalizedDocument, RawDocument
from scrapi.processing.postgres import PostgresProcessor, Document
from . import utils
test_db = PostgresProcessor()
engine = create_engine('postgresql://lo... | Remove test db setup from postgres processor | Remove test db setup from postgres processor
| Python | apache-2.0 | CenterForOpenScience/scrapi,mehanig/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,mehanig/scrapi,fabianvf/scrapi,felliott/scrapi,felliott/scrapi,fabianvf/scrapi |
0e5b3bdd05ba0621c25db4cb4117bd7b93a67725 | only_one.py | only_one.py | #!/usr/bin/env python2.7
from __future__ import absolute_import
import redis
import json
#POOL = redis.ConnectionPool(max_connections=4, host='localhost', db=5, port=6379)
#REDIS_CLIENT = redis.Redis(connection_pool=POOL)
data = json.load(open('config.json'))
REDIS_CLIENT = redis.Redis(host=data['oohost'], db=data['o... | #!/usr/bin/env python2.7
from __future__ import absolute_import
import redis
import json
import os
#POOL = redis.ConnectionPool(max_connections=4, host='localhost', db=5, port=6379)
#REDIS_CLIENT = redis.Redis(connection_pool=POOL)
configfile = "%s/config.json" % (os.path.dirname(os.path.realpath(__file__)))
data = j... | Set full static path for config.json file. Necessary for launching manually | Set full static path for config.json file. Necessary for launching manually
| Python | mit | viable-hartman/mage_scheduler,viable-hartman/mage_scheduler |
305892bc4e6c12fb24d42e16b35621ad90553c7c | testdoc/formatter.py | testdoc/formatter.py | """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class ... | """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class ... | Put a blank line before section headings. | Put a blank line before section headings. | Python | mit | testing-cabal/testdoc |
29e6e77b03569d39e484b47efd3b8230f30ee195 | eduid_signup/db.py | eduid_signup/db.py | import pymongo
from eduid_signup.compat import urlparse
DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
DEFAULT_MONGODB_PORT,
... | import pymongo
DEFAULT_MONGODB_HOST = 'localhost'
DEFAULT_MONGODB_PORT = 27017
DEFAULT_MONGODB_NAME = 'eduid'
DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST,
DEFAULT_MONGODB_PORT,
DEFAULT_MONGODB_NAME)
cla... | Allow Mongo connections to Mongo Replicaset Cluster | Allow Mongo connections to Mongo Replicaset Cluster
| Python | bsd-3-clause | SUNET/eduid-signup,SUNET/eduid-signup,SUNET/eduid-signup |
51dcc5fddeb649ec582c435d6244ea4d2e4f8991 | zproject/jinja2/__init__.py | zproject/jinja2/__init__.py |
from typing import Any
from django.contrib.staticfiles.storage import staticfiles_storage
from django.template.defaultfilters import slugify, pluralize
from django.urls import reverse
from django.utils import translation
from jinja2 import Environment
from two_factor.templatetags.two_factor import device_action
from... |
from typing import Any
from django.contrib.staticfiles.storage import staticfiles_storage
from django.template.defaultfilters import slugify, pluralize
from django.urls import reverse
from django.utils import translation
from django.utils.timesince import timesince
from jinja2 import Environment
from two_factor.templ... | Add django timesince filter to jinja2 filters. | templates: Add django timesince filter to jinja2 filters.
| Python | apache-2.0 | eeshangarg/zulip,brainwane/zulip,rht/zulip,brainwane/zulip,rishig/zulip,brainwane/zulip,brainwane/zulip,eeshangarg/zulip,synicalsyntax/zulip,punchagan/zulip,eeshangarg/zulip,synicalsyntax/zulip,zulip/zulip,punchagan/zulip,andersk/zulip,kou/zulip,zulip/zulip,punchagan/zulip,kou/zulip,rishig/zulip,showell/zulip,punchagan... |
446fe01898a89c4d6beea6ac85b2fbe642b87265 | cross_platform_codecs.py | cross_platform_codecs.py | import sublime
import sys
class CrossPlaformCodecs():
@classmethod
def decode_line(self, line):
line = line.rstrip()
decoded_line = self.force_decode(line) if sys.version_info >= (3, 0) else line
return str(decoded_line) + "\n"
@classmethod
def force_decode(self, text):
... | import sublime
import sys
import re
class CrossPlaformCodecs():
@classmethod
def decode_line(self, line):
line = line.rstrip()
decoded_line = self.force_decode(line) if sys.version_info >= (3, 0) else line
decoded_line = re.sub(r'\033\[(\d{1,2}m|\d\w)', '', str(decoded_line))
re... | Remove terminal Unicode Escape codes | Remove terminal Unicode Escape codes
| Python | mit | nickgzzjr/sublime-gulp,NicoSantangelo/sublime-gulp,nickgzzjr/sublime-gulp,NicoSantangelo/sublime-gulp |
d2967110a2025c255dd496b85313c5c948b4150a | debuild/models/package.py | debuild/models/package.py | # Copyright (c) 2012 Paul Tagliamonte <paultag@debian.org>
#
# 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, modif... | # Copyright (c) 2012 Paul Tagliamonte <paultag@debian.org>
#
# 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, modif... | Move to a generator thinger. | Move to a generator thinger.
| Python | mit | opencollab/debile-web,opencollab/debile-web,paultag/debuild.me,opencollab/debile-web,paultag/debuild.me |
fb7766a4155a229f31af0e33d1b2aedc1d2ff380 | myip/views.py | myip/views.py | from flask import Blueprint, request, jsonify, render_template
bp = Blueprint('views', __name__, url_prefix='')
@bp.route('/ip', methods=['GET'])
def get_ip():
return jsonify(ip=request.remote_addr)
@bp.route('/', methods=['GET'])
def index():
return render_template('index.html')
| from flask import Blueprint, request, render_template
bp = Blueprint('views', __name__, url_prefix='')
@bp.route('/', methods=['GET'])
def index():
return render_template('index.html', ip=request.remote_addr)
| Remove json route for retrieving the ip. | Remove json route for retrieving the ip.
| Python | mit | brotatos/myip,brotatos/myip |
273f9842bbe407e2e4548c712fed8c709c29dd0a | examples/cassandra_db.py | examples/cassandra_db.py | """Cassandra database example
This example demonstrates connecting to a Cassandra database and executing a query. Note that
using the database driver remains exactly the same. The only difference is that we're
monkey-patching everything (including the Cassandra driver), making it guv-friendly.
Adjust this example to... | """Cassandra database example
This example demonstrates connecting to a Cassandra database and executing a query. Note that
using the database driver remains exactly the same. The only difference is that we're
monkey-patching everything (including the Cassandra driver), making it guv-friendly.
Adjust this example to... | Remove warning message (now fixed) | Remove warning message (now fixed)
| Python | mit | veegee/guv,veegee/guv |
8aab29ad2a9f4d4b89ca3e1e54894ccc7a9a6c68 | django_jinja/cache.py | django_jinja/cache.py | # -*- coding: utf-8 -*-
import django
from django.utils.functional import cached_property
from jinja2 import BytecodeCache as _BytecodeCache
class BytecodeCache(_BytecodeCache):
"""
A bytecode cache for Jinja2 that uses Django's caching framework.
"""
def __init__(self, cache_name):
self._cac... | # -*- coding: utf-8 -*-
import django
from django.utils.functional import cached_property
from jinja2 import BytecodeCache as _BytecodeCache
class BytecodeCache(_BytecodeCache):
"""
A bytecode cache for Jinja2 that uses Django's caching framework.
"""
def __init__(self, cache_name):
self._cac... | Remove unnecessary Django < 1.8 check | Remove unnecessary Django < 1.8 check
Support for old Djangos was dropped in 4f9df0f7b764eda520b2f0428da798db02f66d97
| Python | bsd-3-clause | akx/django-jinja,niwinz/django-jinja,akx/django-jinja,akx/django-jinja,niwinz/django-jinja,akx/django-jinja,niwinz/django-jinja |
81a5997227cb9c8086b3cebf305e539eb2bf1990 | daas.py | daas.py | from death_extractor import youtube as yt
from death_extractor import set_interval
from death_extractor import extract_and_upload
def death_as_a_service(vid_path = 'vids', post_interval=3600*2, search_interval=3600*12, dl_interval=3600*6, max_downloads=5, to_imgur=True, to_tumblr=True):
"""Run periodic search/do... | import os
from death_extractor import youtube as yt
from death_extractor import set_interval
from death_extractor import extract_and_upload
def death_as_a_service(vid_path = 'vids', post_interval=3600*2, search_interval=3600*6, dl_interval=3600*3, max_downloads=4, to_imgur=True, to_tumblr=True):
"""Run periodic ... | Stop getting videos every time script starts | Stop getting videos every time script starts
| Python | mit | BooDoo/death_extractor |
cb97436aa76ffc65d4c6488ddac854eeca0dbd36 | fullcalendar/admin.py | fullcalendar/admin.py | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(TabularDynamicInlineA... | from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin
from fullcalendar.models import *
class EventCategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
class OccurrenceInline(TabularDynamicInlineA... | Reorder fields for occurence inline | Reorder fields for occurence inline
| Python | mit | jonge-democraten/mezzanine-fullcalendar |
9d05f18dcb4b52c1d4e68f53f24e5ccebab10a58 | bot/models.py | bot/models.py | from sqlalchemy import create_engine, Column, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def db_connect():
"""
Performs database connection
Returns sqlalchemy engine instance
"""
return create_engine('postgres://avvcurseaphtxf:X0466JySVtLq6nyq_5pb7BQ... | from sqlalchemy import create_engine, Column, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def db_connect():
"""
Performs database connection
Returns sqlalchemy engine instance
"""
return create_engine('postgres://fbcmeskynsvati:aURfAdENt6-kumO0j224GuX... | Change database url for create_engine() | Change database url for create_engine()
| Python | mit | alexbotello/BastionBot |
80e4caad24bceabd8e15133a96a6aaddd9a97c07 | code/type_null_true_false.py | code/type_null_true_false.py | def if_value(values):
print('"if value":')
for k, v in values:
print("%s - %s" % (k, 'true' if v else 'false'))
print()
def nil_value(values):
print('"if value is None":')
for k, v in values:
print("%s - %s" % (k, 'true' if v is None else 'false'))
print()
def empty_value(values):
print('"if len... | def check(label, fn, values):
print(label)
for value in values:
try:
result = 'true' if fn(value) else 'false'
except TypeError as e:
result = 'error: %s' % e
print(" %-9r - %s" % (value, result))
print()
values = ['string', '', [1, 2, 3], [], 5, 0, True, Fa... | Refactor Null/True/False to look more pythonic | Refactor Null/True/False to look more pythonic
| Python | mit | evmorov/lang-compare,Evmorov/ruby-coffeescript,evmorov/lang-compare,evmorov/lang-compare,Evmorov/ruby-coffeescript,evmorov/lang-compare,Evmorov/ruby-coffeescript,evmorov/lang-compare,evmorov/lang-compare |
645cbd9a4445898f69b1ecd9f3db7d5e7b7b9dbd | libqtile/layout/__init__.py | libqtile/layout/__init__.py | from stack import Stack
from max import Max
from tile import Tile
from floating import Floating
from ratiotile import RatioTile
from tree import TreeTab
from slice import Slice
| from stack import Stack
from max import Max
from tile import Tile
from floating import Floating
from ratiotile import RatioTile
from tree import TreeTab
from slice import Slice
from xmonad import MonadTall
| Add MonadTall to layout module proper. | Add MonadTall to layout module proper.
Fixes #126
| Python | mit | nxnfufunezn/qtile,qtile/qtile,de-vri-es/qtile,jdowner/qtile,tych0/qtile,w1ndy/qtile,soulchainer/qtile,rxcomm/qtile,flacjacket/qtile,w1ndy/qtile,ramnes/qtile,andrewyoung1991/qtile,frostidaho/qtile,himaaaatti/qtile,cortesi/qtile,encukou/qtile,himaaaatti/qtile,de-vri-es/qtile,kopchik/qtile,qtile/qtile,zordsdavini/qtile,St... |
e99697b18c7ec6052ed161467197b0e86ed3603d | nbgrader/preprocessors/execute.py | nbgrader/preprocessors/execute.py | from nbconvert.preprocessors import ExecutePreprocessor
from traitlets import Bool, List
from . import NbGraderPreprocessor
class Execute(NbGraderPreprocessor, ExecutePreprocessor):
interrupt_on_timeout = Bool(True)
allow_errors = Bool(True)
extra_arguments = List(["--HistoryManager.hist_file=:memory:"])... | from nbconvert.preprocessors import ExecutePreprocessor
from traitlets import Bool, List
from textwrap import dedent
from . import NbGraderPreprocessor
class Execute(NbGraderPreprocessor, ExecutePreprocessor):
interrupt_on_timeout = Bool(True)
allow_errors = Bool(True)
extra_arguments = List([], config=T... | Change options so other kernels work with nbgrader | Change options so other kernels work with nbgrader
| Python | bsd-3-clause | ellisonbg/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,ellisonbg/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,jupyter/nbgrader,jhamrick/nbgrader |
9454bfa12e36cdab9bf803cf169c1d979bb27381 | cmus_notify/notifications.py | cmus_notify/notifications.py | """Contains code related to notifications."""
import notify2
from .constants import (DEFAULT_ICON_PATH,
DEFAULT_TIMEOUT,
ICONS_BY_STATUS)
from .formatters import format_notification_message
def send_notification(arguments, information):
"""Send the notification to... | """Contains code related to notifications."""
from .constants import (DEFAULT_ICON_PATH,
DEFAULT_TIMEOUT,
ICONS_BY_STATUS)
from .formatters import format_notification_message
def send_notification(arguments, information):
"""Send the notification to the OS with a P... | Fix notify2 being imported with the module | Fix notify2 being imported with the module
| Python | mit | AntoineGagne/cmus-notify |
67733d8093980035ae4d212c8bf74fde9a59d983 | manoseimas/settings/testing.py | manoseimas/settings/testing.py | from manoseimas.settings.base import * # noqa
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
WEBPACK_LOADER.update({
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BUILD... | from manoseimas.settings.base import * # noqa
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
WEBPACK_LOADER.update({
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BUILD... | Fix annoying database issue when running tests | Fix annoying database issue when running tests
Now database name is taken from 'read_default_file' parameter which points to a
my.cnf configuration, where database name should be defined.
But this does not work when running tests for a single file, database name is
set to 'test_', but when running all tests, then dat... | Python | agpl-3.0 | ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt |
cc93d6b9ade1d15236904978f012f91b0a9d567d | examples/manage.py | examples/manage.py | import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# sqlalchemy.configure_manager(manager, ap... | import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# [from aiopg.sa import create_engine]
# s... | Update sqlalchemy command configuration example | Update sqlalchemy command configuration example
| Python | bsd-3-clause | rrader/aio_manager |
0e8a17868731f459d15b754ac0d9cda5a4321a4a | tasks/check_einstein.py | tasks/check_einstein.py | import json
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
class CheckPermSetLicenses(BaseSalesforceApiTask):
task_options = {
"permission_sets": {
"description": "List of permission set names to check for, (ex: EinsteinAnalyticsUser)",
"required": True,
}
... | import json
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
class CheckPermSetLicenses(BaseSalesforceApiTask):
task_options = {
"permission_sets": {
"description": "List of permission set names to check for, (ex: EinsteinAnalyticsUser)",
"required": True,
}
... | Fix analytics template preflight check | Fix analytics template preflight check
Returning from _run_task didn't work, and using
```python
self.return_values = True
```
results in `return_values` being coerced to an empty dictionary that
evaluates as False.
| Python | bsd-3-clause | SalesforceFoundation/HEDAP,SalesforceFoundation/HEDAP,SalesforceFoundation/HEDAP |
0ce6ea2ca75c3839b0a1e41f0fa32e5a9816f653 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
def read(name):
from os import path
return open(path.join(path.dirname(__file__), name)).read()
setup(
name='django-facebook-auth',
version='3.3.3',
description="Authorisation app for Facebook API.",
long_description=read("README.rst"),
... | #!/usr/bin/env python
from distutils.core import setup
def read(name):
from os import path
return open(path.join(path.dirname(__file__), name)).read()
setup(
name='django-facebook-auth',
version='3.3.4',
description="Authorisation app for Facebook API.",
long_description=read("README.rst"),
... | Add management commands to package. | Add management commands to package.
Change-Id: I6c35981fbe47639e72066ddd802eb4d4d4d2d4a0
Reviewed-on: http://review.pozytywnie.pl:8080/19737
Reviewed-by: Jan <14e793d896ddc8ca6911747228e86464cf420065@pozytywnie.pl>
Tested-by: Jenkins
| Python | mit | jgoclawski/django-facebook-auth,jgoclawski/django-facebook-auth,pozytywnie/django-facebook-auth,pozytywnie/django-facebook-auth |
1c0302c7137af550314b05f6e3cc87134c9bdc65 | flaskrst/modules/staticpages/__init__.py | flaskrst/modules/staticpages/__init__.py | # -*- coding: utf-8 -*-
"""
flask-rst.modules.staticfiles
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2011 by Christoph Heer.
:license: BSD, see LICENSE for more details.
"""
import os
from flask import Blueprint, current_app, render_template
from flaskrst.parsers import rstDocument
static_pages =... | # -*- coding: utf-8 -*-
"""
flask-rst.modules.staticfiles
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2011 by Christoph Heer.
:license: BSD, see LICENSE for more details.
"""
from flask import Blueprint, current_app, render_template, safe_join
from flaskrst.parsers import rstDocument
staticpages = ... | Rename blueprint static_pages to staticpages and rename staticpages.show to staticpages.page | Rename blueprint static_pages to staticpages and rename staticpages.show to staticpages.page
| Python | bsd-3-clause | jarus/flask-rst |
eea0f026a8fed261283c081d7bc447ec480ff6e5 | tasks.py | tasks.py | #!/usr/bin/env python3
import subprocess
from invoke import task
@task
def test():
# invoke.run() does not color output, unfortunately
nosetests = subprocess.Popen(['nosetests', '--rednose'])
nosetests.wait()
@task
def cover():
nosetests = subprocess.Popen(['nosetests', '--with-coverage',
... | #!/usr/bin/env python3
import os
import subprocess
from invoke import task
@task
def test():
# invoke.run() does not respect colored output, unfortunately
nosetests = subprocess.Popen(['nosetests', '--rednose'])
nosetests.wait()
@task
def cover():
try:
os.mkdir('cover')
except OSError:
... | Fix bug that raised error when generating coverage | Fix bug that raised error when generating coverage
| Python | mit | caleb531/ssh-wp-backup,caleb531/ssh-wp-backup |
ba115c2087b7fc5b07073ee42af6e2548d462245 | scripts/scripts/current_track.py | scripts/scripts/current_track.py | import subprocess
def main():
st = subprocess.getoutput("mpc")
lin = st.split("\n")
if len(lin) > 1:
sn_status = lin[1]
duration = lin[1].split()
if "paused" in sn_status:
print(lin[0].split("-")[-1] + " [paused]")
elif "playing" in sn_status:
print(... | import subprocess
def text_split(text):
new_text = text.split()
new_text_len = len(new_text)
if new_text_len < 2:
return new_text[0]
elif new_text_len == 2:
return text
else:
return " ".join(new_text[0:2]) + "..."
def main():
st = subprocess.getoutput("mpc")
lin = ... | Use `spotify-now` to get current song info in i3blocks | [track] Use `spotify-now` to get current song info in i3blocks
| Python | mit | iAmMrinal0/dotfiles,iAmMrinal0/dotfiles |
5ebd910a5665402b68e50f540d8480d8c3bd4e64 | pyflation/analysis/deltaprel.py | pyflation/analysis/deltaprel.py | ''' pyflation.analysis.deltaprel - Module to calculate relative pressure
perturbations.
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
| ''' pyflation.analysis.deltaprel - Module to calculate relative pressure
perturbations.
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
'''
def soundspeeds(Vphi, phidot, H):
"""Sound speeds of the background fields
Arguments
---------
... | Add outlines of functions and code for soundspeeds. | Add outlines of functions and code for soundspeeds.
| Python | bsd-3-clause | ihuston/pyflation,ihuston/pyflation |
b612d7a6d67e999f96917de642230946ccf02106 | qnd/experiment.py | qnd/experiment.py | import tensorflow as tf
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
from .inputs import def_def_train_input_fn, def_def_eval_input_fn
def def_def_experiment_fn(batch_inputs=True,
prepare_filename_queues=True,
distributed=False):
adde... | import tensorflow as tf
from .flag import FLAGS, FlagAdder
from .estimator import def_estimator
from .inputs import def_def_train_input_fn, def_def_eval_input_fn
def def_def_experiment_fn(batch_inputs=True,
prepare_filename_queues=True,
distributed=False):
adde... | Fix help message of --min_eval_frequency flag | Fix help message of --min_eval_frequency flag
| Python | unlicense | raviqqe/tensorflow-qnd,raviqqe/tensorflow-qnd |
2a8816e07eec2cfc4680c76c1c5e080a78f149b4 | etc/bin/xcode_bot_script.py | etc/bin/xcode_bot_script.py | # This script should be copied into the Run Script trigger of an Xcode Bot
# `Xcode Bot > Edit Bot > Triggers > After Integration > Run Script`
| # This script should be copied into the Run Script trigger of an Xcode Bot
# `Xcode Bot > Edit Bot > Triggers > After Integration > Run Script`
# Utilizes `cavejohnson` for various integrations
# https://github.com/drewcrawford/CaveJohnson
#!/bin/bash
PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH
... | Add displaying integration status on GitHub | Add displaying integration status on GitHub
| Python | bsd-3-clause | apptentive/apptentive-ios,sahara108/apptentive-ios,Jawbone/apptentive-ios,hibu/apptentive-ios,ALHariPrasad/apptentive-ios,apptentive/apptentive-ios,hibu/apptentive-ios,apptentive/apptentive-ios,hibu/apptentive-ios,sahara108/apptentive-ios,Jawbone/apptentive-ios,ALHariPrasad/apptentive-ios |
e2aa41bb84984fea4c6b8ea475caf7f7af051dd9 | gaphor/codegen/codegen.py | gaphor/codegen/codegen.py | #!/usr/bin/env python
"""The Gaphor code generator CLI.
Provides the CLI for the code generator which transforms a Gaphor models
(with .gaphor file extension) in to a data model in Python.
"""
import argparse
from distutils.util import byte_compile
from pathlib import Path
from gaphor.codegen import profile_coder, u... | #!/usr/bin/env python
"""The Gaphor code generator CLI.
Provides the CLI for the code generator which transforms a Gaphor models
(with .gaphor file extension) in to a data model in Python.
"""
import argparse
from distutils.util import byte_compile
from pathlib import Path
from gaphor.codegen import profile_coder, u... | Use positional argument to improve clarity | Use positional argument to improve clarity
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor |
f5d00ed283da255b8cd2c82b36e19ab9504a7dd4 | webmanager/management/commands/create_default_super_user.py | webmanager/management/commands/create_default_super_user.py | from django.core.management.base import BaseCommand
from djangoautoconf.local_key_manager import get_local_key, ConfigurableAttributeGetter
from web_manage_tools.user_creator import create_admin
def create_default_admin():
super_username = get_local_key("admin_account.admin_username", "webmanager.keys_default")
... | from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from djangoautoconf.local_key_manager import get_local_key, ConfigurableAttributeGetter
from web_manage_tools.user_creator import create_admin
def create_default_admin():
super_username = get_local_key("admin_account.... | Check before creating default super user. | Check before creating default super user.
| Python | bsd-3-clause | weijia/webmanager,weijia/webmanager,weijia/webmanager |
106d56e734140d006a083965e55560a55e21e428 | NGrams.py | NGrams.py | def generate_ngrams(text, n):
''' Generates all possible n-grams of a
piece of text
>>> text = 'this is a random piece'
>>> n = 2
>>> generate_ngrams(text, n)
this is
is a
a random
random piece
'''
text_array = text.split(' ')
for i in range(0, len(text_array) - n + 1):
... | def generate_ngrams(text, n):
''' Generates all possible n-grams of a
piece of text
>>> text = 'this is a random piece'
>>> n = 2
>>> generate_ngrams(text, n)
this is
is a
a random
random piece
'''
text_array = text.split(' ')
ngram_list = []
for i in range(0, len(te... | Return a list of lists | Return a list of lists
| Python | bsd-2-clause | ambidextrousTx/RNLTK |
1157fb15f938aae8cfc10392fe816d691c3b41e7 | todoist/managers/generic.py | todoist/managers/generic.py | # -*- coding: utf-8 -*-
class Manager(object):
# should be re-defined in a subclass
state_name = None
object_type = None
def __init__(self, api):
self.api = api
# shortcuts
@property
def state(self):
return self.api.state
@property
def queue(self):
return... | # -*- coding: utf-8 -*-
class Manager(object):
# should be re-defined in a subclass
state_name = None
object_type = None
def __init__(self, api):
self.api = api
# shortcuts
@property
def state(self):
return self.api.state
@property
def queue(self):
return... | Use the remote getter call only on objects with an object_type. | Use the remote getter call only on objects with an object_type.
| Python | mit | Doist/todoist-python |
aaaa20be61e96daf61e397fdf54dfaf6bec461e8 | falcom/api/worldcat/data.py | falcom/api/worldcat/data.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from ..common import ReadOnlyDataStructure
class WorldcatData (ReadOnlyDataStructure):
@property
def title (self):
return s... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from ..common import ReadOnlyDataStructure
class WorldcatData (ReadOnlyDataStructure):
auto_properties = ("title",)
def __iter__ (... | Use new property format for WorldcatData | Use new property format for WorldcatData
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation |
0ff547915fc9de3d5edb80cc31a0f561453f3687 | salt/returners/syslog_return.py | salt/returners/syslog_return.py | '''
Return data to the host operating system's syslog facility
Required python modules: syslog, json
The syslog returner simply reuses the operating system's syslog
facility to log return data
'''
# Import python libs
import syslog
import json
def __virtual__():
return 'syslog'
def returner(ret):
'''
... | '''
Return data to the host operating system's syslog facility
Required python modules: syslog, json
The syslog returner simply reuses the operating system's syslog
facility to log return data
'''
# Import python libs
import syslog
import json
try:
import syslog
HAS_SYSLOG = True
except ImportError:
HAS_... | Check for syslog. Doesn't exist on Windows | Check for syslog. Doesn't exist on Windows
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
791d378d1c5cb2e9729877bc70261b9354bdb590 | testsuite/cases/pillow_rotate_right.py | testsuite/cases/pillow_rotate_right.py | # coding: utf-8
from __future__ import print_function, unicode_literals, absolute_import
from PIL import Image
from .base import rpartial
from .pillow import PillowTestCase
class RotateRightCase(PillowTestCase):
def handle_args(self, name, transposition):
self.name = name
self.transposition = t... | # coding: utf-8
from __future__ import print_function, unicode_literals, absolute_import
from PIL import Image
from .base import rpartial
from .pillow import PillowTestCase
class RotateRightCase(PillowTestCase):
def handle_args(self, name, transposition):
self.name = name
self.transposition = t... | Transpose and Transpose180 for all Pillow versions | Transpose and Transpose180 for all Pillow versions
| Python | mit | python-pillow/pillow-perf,python-pillow/pillow-perf |
20df58bb9e605ecc53848ade31a3acb98118f00b | scripts/extract_clips_from_hdf5_file.py | scripts/extract_clips_from_hdf5_file.py | from pathlib import Path
import wave
import h5py
DIR_PATH = Path('/Users/harold/Desktop/Clips')
INPUT_FILE_PATH = DIR_PATH / 'Clips.h5'
CLIP_COUNT = 5
def main():
with h5py.File(INPUT_FILE_PATH, 'r') as file_:
clip_group = file_['clips']
for i, clip_id in enumerate(clip_group):
... | from pathlib import Path
import wave
import h5py
DIR_PATH = Path('/Users/harold/Desktop/Clips')
INPUT_FILE_PATH = DIR_PATH / 'Clips.h5'
CLIP_COUNT = 5
def main():
with h5py.File(INPUT_FILE_PATH, 'r') as file_:
clip_group = file_['clips']
for i, clip_id in enumerate(clip_group):
... | Add attribute display to clip extraction script. | Add attribute display to clip extraction script.
| Python | mit | HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper |
73856ac73abd9dc68909a67077c016d003888cdd | credentials/apps/records/migrations/0006_auto_20180718_1256.py | credentials/apps/records/migrations/0006_auto_20180718_1256.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-07-17 20:02
from __future__ import unicode_literals
from django.db import migrations
from credentials.apps.catalog.models import Program
from credentials.apps.records.models import ProgramCertRecord
def seed_program_cert_records(apps, schema_editor):
... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-07-17 20:02
from __future__ import unicode_literals
from django.db import migrations
from credentials.apps.catalog.models import Program
from credentials.apps.records.models import ProgramCertRecord
def seed_program_cert_records(apps, schema_editor):
... | Add site guarding for ProgramCertRecord data migration | Add site guarding for ProgramCertRecord data migration
| Python | agpl-3.0 | edx/credentials,edx/credentials,edx/credentials,edx/credentials |
b0e101f523fd853392e65b1b30204a56e3ec34ec | tests/test_twitter.py | tests/test_twitter.py | # -*- coding: utf-8 -*-
import pytest
import tweepy
import vcr
from secrets import TWITTER_ACCESS, TWITTER_SECRET
from secrets import CONSUMER_KEY, CONSUMER_SECRET
class TestTweepyIntegration():
"""Test class to ensure tweepy functionality works as expected"""
# Class level client to use across tests
aut... | # -*- coding: utf-8 -*-
import pytest
import tweepy
import vcr
from secrets import TWITTER_ACCESS, TWITTER_SECRET
from secrets import TWITTER_CONSUMER_ACCESS, TWITTER_CONSUMER_SECRET
class TestTweepyIntegration():
"""Test class to ensure tweepy functionality works as expected"""
# Class level client to use a... | Update access token variable names | Update access token variable names
| Python | mit | nestauk/inet |
6cb215211bff754f531126ac44df03e761b3d7fc | pagerduty_events_api/tests/test_pagerduty_incident.py | pagerduty_events_api/tests/test_pagerduty_incident.py | from unittest import TestCase
from unittest.mock import patch
from pagerduty_events_api import PagerdutyIncident
class TestPagerdutyIncident(TestCase):
def setUp(self):
super().setUp()
self.__subject = PagerdutyIncident('my_service_key', 'my_incident_key')
def test_get_service_key_should_ret... | from ddt import ddt, data, unpack
from unittest import TestCase
from unittest.mock import patch
from pagerduty_events_api import PagerdutyIncident
@ddt
class TestPagerdutyIncident(TestCase):
def setUp(self):
super().setUp()
self.__subject = PagerdutyIncident('my_service_key', 'my_incident_key')
... | Use data provider in PD incident tests. | Use data provider in PD incident tests.
| Python | mit | BlasiusVonSzerencsi/pagerduty-events-api |
dbfe5fcb87762d68580756d6466bc61fa8ab4a56 | histomicstk/preprocessing/color_deconvolution/utils.py | histomicstk/preprocessing/color_deconvolution/utils.py | import numpy
from .stain_color_map import stain_color_map
def get_stain_vector(args, index):
"""Get the stain corresponding to args.stain_$index and
args.stain_$index_vector. If the former is not "custom", the
latter must be None.
"""
args = vars(args)
stain = args['stain_' + str(index)]
... | import numpy
from .stain_color_map import stain_color_map
def get_stain_vector(args, index):
"""Get the stain corresponding to args.stain_$index and
args.stain_$index_vector. If the former is not "custom", the
latter must be None.
"""
args = vars(args)
stain = args['stain_' + str(index)]
... | Enhance get_stain_matrix to take any desired number of vectors | Enhance get_stain_matrix to take any desired number of vectors
| Python | apache-2.0 | DigitalSlideArchive/HistomicsTK,DigitalSlideArchive/HistomicsTK |
05094307c2f49b7a6207ddaa049ac79e759c03da | lily/users/authentication/social_auth/providers/google.py | lily/users/authentication/social_auth/providers/google.py | from django.conf import settings
from ..exceptions import InvalidProfileError
from .base import BaseAuthProvider
class GoogleAuthProvider(BaseAuthProvider):
client_id = settings.SOCIAL_AUTH_GOOGLE_CLIENT_ID
client_secret = settings.SOCIAL_AUTH_GOOGLE_SECRET
scope = [
'https://www.googleapis.com/a... | from django.conf import settings
from ..exceptions import InvalidProfileError
from .base import BaseAuthProvider
class GoogleAuthProvider(BaseAuthProvider):
client_id = settings.SOCIAL_AUTH_GOOGLE_CLIENT_ID
client_secret = settings.SOCIAL_AUTH_GOOGLE_SECRET
scope = [
'openid',
'email',
... | Fix deprecation of social OAuth scopes | LILY-3349: Fix deprecation of social OAuth scopes
| Python | agpl-3.0 | HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily |
6ec656a4ab0a255bad85c3157a045849da001352 | ggplot/utils/date_breaks.py | ggplot/utils/date_breaks.py | from matplotlib.dates import DayLocator, WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks =>... | from matplotlib.dates import MinuteLocator, HourLocator, DayLocator
from matplotlib.dates import WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,unit... | Add more granular date locators | Add more granular date locators
| Python | mit | has2k1/plotnine,has2k1/plotnine |
ef62cec8673f255dd9ce909d23a877ba93bd6bf5 | voidpp_tools/json_config.py | voidpp_tools/json_config.py |
import os
import json
class JSONConfigLoader():
def __init__(self):
self.sources = [
os.path.dirname(os.getcwd()),
os.path.dirname(os.path.abspath(__file__)),
os.path.expanduser('~'),
'/etc',
]
def load(self, filename):
for source in sel... |
import os
import json
class JSONConfigLoader():
def __init__(self, base_path):
self.sources = [
os.path.dirname(os.getcwd()),
os.path.dirname(os.path.abspath(base_path)),
os.path.expanduser('~'),
'/etc',
]
def load(self, filename):
tries... | Raise exception in case of config load error | Raise exception in case of config load error
| Python | mit | voidpp/python-tools |
a48ae09ce927622e8a5931dbcb843523d8f4bd23 | wagtail/tests/test_utils.py | wagtail/tests/test_utils.py | # -*- coding: utf-8 -*
from __future__ import absolute_import, unicode_literals
import warnings
from django.test import SimpleTestCase
from wagtail.utils.deprecation import RemovedInWagtail17Warning, SearchFieldsShouldBeAList
class TestThisShouldBeAList(SimpleTestCase):
def test_add_a_list(self):
with ... | # -*- coding: utf-8 -*
from __future__ import absolute_import, unicode_literals
import warnings
from django.test import SimpleTestCase
from wagtail.utils.deprecation import RemovedInWagtail17Warning, SearchFieldsShouldBeAList
class TestThisShouldBeAList(SimpleTestCase):
def test_add_a_list(self):
with ... | Reset warnings before testing warnings | Reset warnings before testing warnings
| Python | bsd-3-clause | nimasmi/wagtail,torchbox/wagtail,mikedingjan/wagtail,kaedroho/wagtail,zerolab/wagtail,zerolab/wagtail,wagtail/wagtail,chrxr/wagtail,hamsterbacke23/wagtail,rsalmaso/wagtail,kurtrwall/wagtail,quru/wagtail,chrxr/wagtail,kaedroho/wagtail,Toshakins/wagtail,zerolab/wagtail,nealtodd/wagtail,nutztherookie/wagtail,Toshakins/wag... |
a436470f00dddcb1764da6b6dc244e86bc71d473 | gscripts/ipython_imports.py | gscripts/ipython_imports.py | import numpy as np
import pandas as pd
import matplotlib_venn
import matplotlib.pyplot as plt
import brewer2mpl
import itertools
set1 = brewer2mpl.get_map('Set1', 'qualitative', 9).mpl_colors
red = set1[0]
blue = set1[1]
green = set1[2]
purple = set1[3]
orange = set1[4]
yellow = set1[5]
brown = set1[6]
pink = set1[7]
... | import numpy as np
import pandas as pd
import matplotlib_venn
import matplotlib.pyplot as plt
import brewer2mpl
import itertools
import seaborn as sns
import collections
import itertools
set1 = brewer2mpl.get_map('Set1', 'qualitative', 9).mpl_colors
red = set1[0]
blue = set1[1]
green = set1[2]
purple = set1[3]
orange ... | Add seaborn, collections, itertools to IPython imports | Add seaborn, collections, itertools to IPython imports
| Python | mit | YeoLab/gscripts,YeoLab/gscripts,YeoLab/gscripts,YeoLab/gscripts |
7fb1212ab97bca6301d9826258a594f8935bba28 | mopidy_ttsgpio/tts.py | mopidy_ttsgpio/tts.py | import urllib
import gst
music_level = 30
class TTS():
def __init__(self, frontend, config):
self.frontend = frontend
self.player = gst.element_factory_make("playbin", "tts")
output = gst.parse_bin_from_description(config['audio']['output'],
... | import os
from threading import Thread
music_level = 30
class TTS():
def __init__(self, frontend, config):
self.frontend = frontend
def speak_text(self, text):
t = Thread(target=self.speak_text_thread, args=(text,))
t.start()
def speak_text_thread(self, text):
os.system... | Change from Google TTS to Festival | Change from Google TTS to Festival
| Python | apache-2.0 | 9and3r/mopidy-ttsgpio |
6da0aaf77fe221286981b94eaf7d304568f55957 | examples/stories/movie_lister/movies/__init__.py | examples/stories/movie_lister/movies/__init__.py | """Movies package.
Top-level package of movies library. This package contains catalog of movies
module components - ``MoviesModule``. It is recommended to use movies library
functionality by fetching required instances from ``MoviesModule`` providers.
Each of ``MoviesModule`` providers could be overridden.
"""
from ... | """Movies package.
Top-level package of movies library. This package contains catalog of movies
module components - ``MoviesModule``. It is recommended to use movies library
functionality by fetching required instances from ``MoviesModule`` providers.
Each of ``MoviesModule`` providers could be overridden.
"""
from ... | Update imports for MovieLister standrard module | Update imports for MovieLister standrard module
| Python | bsd-3-clause | rmk135/objects,ets-labs/python-dependency-injector,ets-labs/dependency_injector,rmk135/dependency_injector |
91bd7690c1e48b52a270bc45626e771663828c28 | pact/group.py | pact/group.py | from .base import PactBase
from .utils import GroupWaitPredicate
class PactGroup(PactBase):
def __init__(self, pacts):
super(PactGroup, self).__init__()
self._pacts = list(pacts)
def __iadd__(self, other):
self._pacts.append(other)
return self
def _is_finished(self):
... | from .base import PactBase
from .utils import GroupWaitPredicate
class PactGroup(PactBase):
def __init__(self, pacts):
self._pacts = list(pacts)
super(PactGroup, self).__init__()
def __iadd__(self, other):
self._pacts.append(other)
return self
def _is_finished(self):
... | Fix PactGroup created log message | Fix PactGroup created log message
| Python | bsd-3-clause | vmalloc/pact |
6db1ddd9c7776cf07222ae58dc9b2c44135ac59a | spacy/__init__.py | spacy/__init__.py | # coding: utf8
from __future__ import unicode_literals
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
# These are imported as part of the API
from thinc.neural.util import prefer_gpu, require_gpu
from .cli.in... | # coding: utf8
from __future__ import unicode_literals
import warnings
import sys
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
# These are imported as part of the API
from thinc.neural.util import prefer_gpu, require_gpu
f... | Raise ValueError for narrow unicode build | Raise ValueError for narrow unicode build
| Python | mit | explosion/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy |
ad4b6663a2de08fddc0ebef8a08e1f405c0cb80a | pkgcmp/cli.py | pkgcmp/cli.py | '''
Parse CLI options
'''
# Import python libs
import os
import copy
import argparse
# Import pkgcmp libs
import pkgcmp.scan
# Import third party libs
import yaml
DEFAULTS = {'cachedir': '/var/cache/pkgcmp'}
def parse():
'''
Parse!!
'''
parser = argparse.ArgumentParser(description='The pkgcmp map gen... | '''
Parse CLI options
'''
# Import python libs
import os
import copy
import argparse
# Import pkgcmp libs
import pkgcmp.scan
# Import third party libs
import yaml
DEFAULTS = {'cachedir': '/var/cache/pkgcmp',
'extension_modules': ''}
def parse():
'''
Parse!!
'''
parser = argparse.ArgumentP... | Add extension_modueles to the default configuration | Add extension_modueles to the default configuration
| Python | apache-2.0 | SS-RD/pkgcmp |
88773c6757540c9f1d4dfca2a287512e74bdbc24 | python_scripts/mc_config.py | python_scripts/mc_config.py | #!/usr/bin/python
import yaml
import os.path
_config_file_base_name = 'mediawords.yml'
_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml'))
def read_config():
yml_file = open(_config_file_name, 'rb')
config_file = yaml.load( yml_file )
return config_file
| #!/usr/bin/python
import yaml
import os.path
_config_file_base_name = 'mediawords.yml'
_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml'))
_defaults_config_file_base_name = 'defaults.yml'
_defaults_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__fil... | Read the defaults config file and merge it with mediawords.yml | Read the defaults config file and merge it with mediawords.yml
| Python | agpl-3.0 | berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT... |
25ba4aea17d869022682fd70d4c3ccbade19955f | openfisca_country_template/situation_examples/__init__.py | openfisca_country_template/situation_examples/__init__.py | """This file provides a function to load json example situations."""
import json
import os
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
def parse(file_name):
"""Load json example situations."""
file_path = os.path.join(DIR_PATH, file_name)
with open(file_path, "r") as file:
return json... | """This file provides a function to load json example situations."""
import json
import os
DIR_PATH = os.path.dirname(os.path.abspath(__file__))
def parse(file_name):
"""Load json example situations."""
file_path = os.path.join(DIR_PATH, file_name)
with open(file_path, "r", encoding="utf8") as file:
... | Add encoding to open file | Add encoding to open file
| Python | agpl-3.0 | openfisca/country-template,openfisca/country-template |
eb1921615cd9070564d09c934d2c687897619c3a | froide/campaign/listeners.py | froide/campaign/listeners.py | from .models import Campaign
def connect_campaign(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
parts = reference.split(':', 1)
if len(parts) != 2:
return
namespace = parts[0]
try:
campaign = Campaign.objects.get(ident=namespace)
ex... | from .models import Campaign
def connect_campaign(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
parts = reference.split(':', 1)
if len(parts) != 2:
return
namespace = parts[0]
try:
campaign = Campaign.objects.get(ident=namespace)
ex... | Add tags of campaign to user | Add tags of campaign to user | Python | mit | stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide |
b8a5655520449148e5f71790f85dfafd84faebec | python/peacock/tests/postprocessor_tab/gold/TestPostprocessorPluginManager_test_script.py | python/peacock/tests/postprocessor_tab/gold/TestPostprocessorPluginManager_test_script.py | #* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgpl-2.1.html
"""
python ... | """
python TestPostprocessorPluginManager_test_script.py
"""
import matplotlib.pyplot as plt
import mooseutils
# Create Figure and Axes
figure = plt.figure(facecolor='white')
axes0 = figure.add_subplot(111)
axes1 = axes0.twinx()
# Read Postprocessor Data
data = mooseutils.PostprocessorReader('../input/white_elephant_... | Remove header added to gold file | Remove header added to gold file
| Python | lgpl-2.1 | nuclear-wizard/moose,YaqiWang/moose,harterj/moose,milljm/moose,sapitts/moose,dschwen/moose,jessecarterMOOSE/moose,sapitts/moose,andrsd/moose,sapitts/moose,lindsayad/moose,andrsd/moose,harterj/moose,jessecarterMOOSE/moose,idaholab/moose,jessecarterMOOSE/moose,dschwen/moose,lindsayad/moose,dschwen/moose,SudiptaBiswas/moo... |
e53c66f9ab12fe0c90c447176b083513cd3a4cf5 | store/urls.py | store/urls.py | from django.conf.urls import url
from .views import ProductCatalogue, ProductDetail, product_review
urlpatterns = [
url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'),
url(r'^(?P<slug>[\w\-]+)/$', ProductDetail.as_view(), name='detail'),
url(r'^review/$', product_review, name='review')
]
| from django.conf.urls import url
from .views import ProductCatalogue, ProductDetail, product_review
urlpatterns = [
url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'),
url(r'^review/$', product_review, name='review'),
url(r'^(?P<slug>[\w\-]+)/$', ProductDetail.as_view(), name='detail'),
]... | Move products:review URLConf above product:detail | Move products:review URLConf above product:detail
The product:detail view is greedy and previously caused the review
URLConf never to be resolved by the correct view
| Python | bsd-3-clause | kevgathuku/compshop,andela-kndungu/compshop,kevgathuku/compshop,kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,andela-kndungu/compshop |
de02c92510a6117aad01be7666d737d2ad861fd7 | send_sms.py | send_sms.py | #!/usr/bin/env python
import datetime
import json
import sys
import requests
import pytz
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_mes... | #!/usr/bin/env python
import json
import sys
import requests
from twilio.rest import TwilioRestClient
import conf
def send(s):
client.sms.messages.create(to=conf.TO, from_=conf.FROM, body=s)
# Use the first arg as the message to send, or use the default if not specified
default_message = "You haven't committe... | Improve logic in determining latest contribution | Improve logic in determining latest contribution
Looks like the list will always contain data for the last 366 days, and
the last entry in the list will always contain data for the current day
(PST). Much simpler this way.
Added some generic error-handling just in case this isn't true.
| Python | mit | dellsystem/github-streak-saver |
5b18ec2219cbdfa479a1d32f9bf62f7460171f09 | live_studio/queue/models.py | live_studio/queue/models.py | import datetime
from django.db import models
from .managers import EntryManager
class Entry(models.Model):
config = models.ForeignKey('config.Config')
enqueued = models.DateTimeField(default=datetime.datetime.utcnow)
started = models.DateTimeField(null=True)
finished = models.DateTimeField(null=True... | import datetime
from django.db import models
from .managers import EntryManager
class Entry(models.Model):
config = models.ForeignKey('config.Config')
enqueued = models.DateTimeField(default=datetime.datetime.utcnow)
started = models.DateTimeField(null=True)
finished = models.DateTimeField(null=True... | Set verbose_name_plural properly for queue.Entry. | Set verbose_name_plural properly for queue.Entry.
Signed-off-by: Chris Lamb <29e6d179a8d73471df7861382db6dd7e64138033@debian.org>
| Python | agpl-3.0 | debian-live/live-studio,debian-live/live-studio,lamby/live-studio,lamby/live-studio,lamby/live-studio,debian-live/live-studio |
0f183708aa8a0c9503d847a65f072de07dc800ea | tests.py | tests.py | import unittest
from gtlaunch import Launcher
class MockOptions(object):
def __init__(self):
self.verbose = False
self.config = ''
self.project = ''
class LauncherTestCase(unittest.TestCase):
def test_lazy_init(self):
options = MockOptions()
launcher = Launcher(optio... | import unittest
from gtlaunch import Launcher
class MockOptions(object):
def __init__(self):
self.verbose = False
self.config = ''
self.project = ''
class LauncherTestCase(unittest.TestCase):
def test_lazy_init(self):
options = MockOptions()
launcher = Launcher(optio... | Check for maximize in args. | Check for maximize in args.
| Python | mit | GoldenLine/gtlaunch |
e055874545dcc0e1205bad2b419076c204ffcf9c | duty_cycle.py | duty_cycle.py | #!/usr/bin/env python
from blinkenlights import dimmer, setup, cleanup
pin = 18
setup(pin)
up = range(10)
down = range(9)
down.reverse()
bpm = 70
period = 60.0 / bpm # seconds
time_per_level = period / len(up + down)
for i in range(10):
for j in (up + down):
brightness = (j+1) / 10.0
dimmer(... | #!/usr/bin/env python
from blinkenlights import dimmer, setup, cleanup
pin = 18
bpm = 70
setup(pin)
up = range(10)
down = range(9)
down.reverse()
spectrum = up + down + [-1]
period = 60.0 / bpm # seconds
time_per_level = period / len(spectrum)
for i in range(10):
for j in (spectrum):
brightness = (j+1... | Add a 0.0 duty cycle: brief moment of off time. | Add a 0.0 duty cycle: brief moment of off time.
| Python | mit | zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie |
0e740b5fd924b113173b546f2dd2b8fa1e55d074 | indra/sparser/sparser_api.py | indra/sparser/sparser_api.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import logging
import xml.etree.ElementTree as ET
from indra.util import UnicodeXMLTreeBuilder as UTB
from indra.sparser.processor import SparserProcessor
logger = logging.getLogger('sparser')
def process_xml(xml_s... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import logging
import xml.etree.ElementTree as ET
from indra.util import UnicodeXMLTreeBuilder as UTB
from indra.sparser.processor import SparserProcessor
logger = logging.getLogger('sparser')
def process_xml(xml_s... | Print XML parse errors in Sparser API | Print XML parse errors in Sparser API
| Python | bsd-2-clause | sorgerlab/belpy,bgyori/indra,johnbachman/belpy,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra |
0a850f935ce6cc48a68cffbef64c127daa22a42f | write.py | write.py | import colour
import csv
import json
import os
import pprint
# write to file as json, csv, markdown, plaintext or print table
def write_data(data, user, format=None):
if format is not None:
directory = './data/'
if not os.path.exists(directory):
os.makedirs(directory)
f = ... | import csv
import json
import os
from tabulate import tabulate
def write_data(d, u, f=None):
if f is not None:
directory = './data/'
if not os.path.exists(directory):
os.makedirs(directory)
file = open(directory + u + '.' + f, 'w')
if f == 'json':
file.w... | Print table if no file format provided | Print table if no file format provided
| Python | mit | kshvmdn/github-list,kshvmdn/github-list,kshvmdn/github-list |
991889003ca31bf13b326b7c1788ecbe32801528 | profile_collection/startup/99-bluesky.py | profile_collection/startup/99-bluesky.py | from bluesky.global_state import (resume, abort, stop, panic, all_is_well,
state)
from bluesky.callbacks.olog import OlogCallback
from bluesky.global_state import gs
olog_cb = OlogCallback('Data Acquisition')
gs.RE.subscribe('start', olog_cb)
from bluesky.scientific_callbacks impor... | from bluesky.global_state import (resume, abort, stop, panic, all_is_well,
state)
from bluesky.callbacks.olog import OlogCallback
from bluesky.global_state import gs
olog_cb = OlogCallback('Data Acquisition')
gs.RE.subscribe('start', olog_cb)
gs.DETS.append(det4)
#from bluesky.sci... | Add det4 to global dets | Add det4 to global dets
| Python | bsd-2-clause | NSLS-II-IXS/ipython_ophyd,NSLS-II-IXS/ipython_ophyd |
b65c5157c9e4515b01558201b983727d3a3154bd | src/syntax/relative_clauses.py | src/syntax/relative_clauses.py | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The Relative clauses class
class RelativeClauses:
# Constructor for the Relative Clauses class
def __init__(self):
self.has_wh_word = False
# Break the tree
def break_tree(self, tree):
t = Tree.fromstring(str(tree))
... | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The Relative clauses class
class RelativeClauses:
# Constructor for the Relative Clauses class
def __init__(self):
self.has_wh_word = False
# Break the tree
def break_tree(self, tree):
t = Tree.fromstring(str(tree))
... | Fix detection of relative clause | Fix detection of relative clause
| Python | mit | Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify |
02e4a051e6e463d06195e9efe6a25c84cc046b55 | tests/base.py | tests/base.py | import unittest
from app import create_app, db
class Base(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.client = self.app.test_client()
self.user = {
"username": "brian",
"password": "password"
}
with self.app.app_contex... | import unittest
import json
from app import create_app, db
from app.models import User
class Base(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.client = self.app.test_client()
self.user = json.dumps({
"username": "brian",
"password": "pa... | Add authorization and content-type headers to request for tests | [CHORE] Add authorization and content-type headers to request for tests
| Python | mit | brayoh/bucket-list-api |
6ad77e5a9cdbe63ca706bd7c7d3aebb7a34e4cc5 | mopidy/__init__.py | mopidy/__init__.py | from __future__ import absolute_import, print_function, unicode_literals
import platform
import sys
import warnings
compatible_py2 = (2, 7) <= sys.version_info < (3,)
compatible_py3 = (3, 7) <= sys.version_info
if not (compatible_py2 or compatible_py3):
sys.exit(
'ERROR: Mopidy requires Python 2.7 or >=... | from __future__ import absolute_import, print_function, unicode_literals
import platform
import sys
import warnings
if not sys.version_info >= (3, 7):
sys.exit(
'ERROR: Mopidy requires Python >= 3.7, but found %s.' %
platform.python_version())
warnings.filterwarnings('ignore', 'could not open d... | Exit if imported on Python 2 | Exit if imported on Python 2
| Python | apache-2.0 | kingosticks/mopidy,adamcik/mopidy,jcass77/mopidy,jodal/mopidy,mopidy/mopidy,kingosticks/mopidy,mopidy/mopidy,adamcik/mopidy,jcass77/mopidy,kingosticks/mopidy,jodal/mopidy,jodal/mopidy,mopidy/mopidy,jcass77/mopidy,adamcik/mopidy |
ce9cbc4144c105e9cb59836274ef25a29a9b20a7 | webserver/codemanagement/tasks.py | webserver/codemanagement/tasks.py | from celery import task
from celery.result import AsyncResult
from .models import TeamSubmission
import logging
logger = logging.getLogger(__name__)
@task()
def create_shellai_tag(instance):
"""Tags the repo's HEAD as "ShellAI" to provide a default tag for
the arena to use"""
team_name = instance.team.... | from celery import task
from celery.result import AsyncResult
from .models import TeamSubmission
import logging
logger = logging.getLogger(__name__)
@task()
def create_shellai_tag(instance):
"""Tags the repo's HEAD as "ShellAI" to provide a default tag for
the arena to use"""
team_name = instance.team.... | Handle attempts to tag empty shell repos | Handle attempts to tag empty shell repos
| Python | bsd-3-clause | siggame/webserver,siggame/webserver,siggame/webserver |
855c7b56ff92efce90dc4953ebabc4aca07f5eb8 | domains/integrator_chains/fmrb_sci_examples/scripts/lqr.py | domains/integrator_chains/fmrb_sci_examples/scripts/lqr.py | #!/usr/bin/env python
from __future__ import print_function
import roslib; roslib.load_manifest('dynamaestro')
import rospy
from dynamaestro.msg import VectorStamped
class LQRController(rospy.Subscriber):
def __init__(self, intopic, outtopic):
rospy.Subscriber.__init__(self, outtopic, VectorStamped, self... | #!/usr/bin/env python
from __future__ import print_function
import roslib; roslib.load_manifest('dynamaestro')
import rospy
from dynamaestro.msg import VectorStamped
from control import lqr
import numpy as np
class StateFeedback(rospy.Subscriber):
def __init__(self, intopic, outtopic, K=None):
rospy.Sub... | Improve LQR example for integrator_chains domain | Improve LQR example for integrator_chains domain
| Python | bsd-3-clause | fmrchallenge/fmrbenchmark,fmrchallenge/fmrbenchmark,fmrchallenge/fmrbenchmark |
6a830973fa8f29278015d55819dcbd87f0472ac9 | post_office/test_urls.py | post_office/test_urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls), name='admin'),
)
| from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls), name='admin'),
]
| Fix Django 1.10 url patterns warning | Fix Django 1.10 url patterns warning
| Python | mit | ui/django-post_office,JostCrow/django-post_office,RafRaf/django-post_office,ui/django-post_office,yprez/django-post_office,jrief/django-post_office |
480c89d81e1610d698269c41f4543c38193bef13 | test/test_orthomcl_database.py | test/test_orthomcl_database.py | import shutil
import tempfile
import unittest
import orthomcl_database
class Test(unittest.TestCase):
def setUp(self):
self.run_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.run_dir)
def test_get_configuration_file(self):
conffile = orthomcl_database.get_confi... | import MySQLdb
import shutil
import tempfile
import unittest
import orthomcl_database
class Test(unittest.TestCase):
def setUp(self):
self.run_dir = tempfile.mkdtemp()
self.credentials = orthomcl_database._get_root_credentials()
def tearDown(self):
shutil.rmtree(self.run_dir)
d... | Expand test to include query on the created database as restricted user | Expand test to include query on the created database as restricted user | Python | mit | ODoSE/odose.nl |
082ac65c32c323c36036e0ddac140a87942e9b00 | tests/window/WINDOW_CAPTION.py | tests/window/WINDOW_CAPTION.py | #!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the ... | #!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the ... | Make windows bigger in this test so the captions can be read. | Make windows bigger in this test so the captions can be read.
Index: tests/window/WINDOW_CAPTION.py
===================================================================
--- tests/window/WINDOW_CAPTION.py (revision 777)
+++ tests/window/WINDOW_CAPTION.py (working copy)
@@ -19,8 +19,8 @@
class WINDOW_CAPTION(unittest.... | Python | bsd-3-clause | infowantstobeseen/pyglet-darwincore,infowantstobeseen/pyglet-darwincore,infowantstobeseen/pyglet-darwincore,infowantstobeseen/pyglet-darwincore,infowantstobeseen/pyglet-darwincore |
4f4c3fabe1ccb91ca8f510a6ab81b6f2eb588c17 | openstack/tests/functional/telemetry/v2/test_statistics.py | openstack/tests/functional/telemetry/v2/test_statistics.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Fix the telemetry statistics test | Fix the telemetry statistics test
This test worked fine on devstack, but failed on the test gate
because not all meters have statistics. Look for a meter with
statistics.
Partial-bug: #1665495
Change-Id: Ife0f1f11c70e926801b48000dd0b4e9d863a865f
| Python | apache-2.0 | briancurtin/python-openstacksdk,dtroyer/python-openstacksdk,dtroyer/python-openstacksdk,openstack/python-openstacksdk,openstack/python-openstacksdk,briancurtin/python-openstacksdk,stackforge/python-openstacksdk,stackforge/python-openstacksdk |
0dabb6f4b18ff73f16088b207894d5e647494afb | colors.py | colors.py | from tcpgecko import TCPGecko
from textwrap import wrap
from struct import pack
from binascii import hexlify, unhexlify
import sys
def pokecolor(pos, string):
color = textwrap.wrap(string, 4)
tcp.pokemem(pos, struct.unpack(">I", color[0])[0])
tcp.pokemem(pos + 4, struct.unpack(">I", color[1])[0])
tcp... | from tcpgecko import TCPGecko
from textwrap import wrap
from struct import pack
from binascii import unhexlify
import sys
tcp = TCPGecko("192.168.0.8") #Wii U IP address
Colors = b""
for i in range(1, 4): #Ignores Alpha since it doesn't use it
Color = wrap(sys.argv[i], 2) #Split it into 2 character chunks
fo... | Update ColorHax to 2.3.0 address | Update ColorHax to 2.3.0 address
Need to make pyGecko auto-find it all
| Python | mit | wiiudev/pyGecko,wiiudev/pyGecko |
14b3ac31e7c46ce7c0482fd926a5306234a4f1e6 | taipan/_compat.py | taipan/_compat.py | """
Compatibility shims for different Python versions and platforms.
"""
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
import django.utils.simplejson as json
import sys
IS_PY3 = sys.version_info[0] == 3
import platform
IS_PYPY = platform.python_im... | """
Compatibility shims for different Python versions and platforms.
"""
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
import django.utils.simplejson as json
import sys
IS_PY26 = sys.version[:2] == (2, 6)
IS_PY3 = sys.version_info[0] == 3
import p... | Fix the accidental removal of IS_PY26 | Fix the accidental removal of IS_PY26
| Python | bsd-2-clause | Xion/taipan |
f52f2aafc204c3b19e04d05ac6fc1f10a4ea2463 | rcbi/rcbi/items.py | rcbi/rcbi/items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class Part(scrapy.Item):
name = scrapy.Field()
site = scrapy.Field()
manufacturer = scrapy.Field()
sku = scrapy.Field()
weight = scr... | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class Part(scrapy.Item):
name = scrapy.Field()
site = scrapy.Field()
manufacturer = scrapy.Field()
sku = scrapy.Field()
weight = scr... | Update comment to be more specific about stock fields | Update comment to be more specific about stock fields
| Python | apache-2.0 | rcbuild-info/scrape,rcbuild-info/scrape |
288508e0693da5dbfc467a01ac18b31c4f8cc16c | nymms/tests/test_registry.py | nymms/tests/test_registry.py | import unittest
from nymms import registry
from nymms.resources import Command, MonitoringGroup
from weakref import WeakValueDictionary
class TestRegistry(unittest.TestCase):
def tearDown(self):
# Ensure we have a fresh registry after every test
Command.registry.clear()
def test_empty_regist... | import unittest
from nymms import registry
from nymms.resources import Command, MonitoringGroup
from weakref import WeakValueDictionary
class TestRegistry(unittest.TestCase):
def setUp(self):
# Ensure we have a fresh registry before every test
Command.registry.clear()
def test_empty_registry... | Clear command registry BEFORE each test. | Clear command registry BEFORE each test.
| Python | bsd-2-clause | cloudtools/nymms |
c1dc571faa9bf2ae0e0a580365943806826ced4a | src/adhocracy_spd/adhocracy_spd/workflows/digital_leben.py | src/adhocracy_spd/adhocracy_spd/workflows/digital_leben.py | """Digital leben workflow."""
from adhocracy_core.workflows import add_workflow
from adhocracy_core.workflows.standard import standard_meta
digital_leben_meta = standard_meta \
.transform(('states', 'participate', 'acm'),
{'principals': [ 'parti... | """Digital leben workflow."""
from adhocracy_core.workflows import add_workflow
from adhocracy_core.workflows.standard import standard_meta
digital_leben_meta = standard_meta \
.transform(('states', 'participate', 'acm'),
{'principals': ['participan... | Make flake8 happy for spd | Make flake8 happy for spd
| Python | agpl-3.0 | liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adh... |
9ad85a6986c8350cb082f23d9508301c40ca440d | resolwe_bio/api/views.py | resolwe_bio/api/views.py | from django.db.models import Q
from rest_framework.decorators import list_route
from rest_framework.response import Response
from resolwe.flow.models import Collection
from resolwe.flow.views import CollectionViewSet
class SampleViewSet(CollectionViewSet):
queryset = Collection.objects.filter(descriptor_schema_... | from django.db.models import Max, Q
from rest_framework.decorators import list_route
from rest_framework.response import Response
from resolwe.flow.models import Collection
from resolwe.flow.views import CollectionViewSet
class SampleViewSet(CollectionViewSet):
queryset = Collection.objects.filter(descriptor_sc... | Order samples by date created of the newest Data | Order samples by date created of the newest Data
| Python | apache-2.0 | genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio |
08995bcb577276af1d5b2b8ed8eb68d2678ddc4d | game/tests.py | game/tests.py | import datetime
from django.utils import timezone
from django.test import TestCase
from django.urls import reverse | import datetime
from django.utils import timezone
from django.test import TestCase
from django.urls import reverse
def create_user(question_text, days):
pass
class UserViewTests(TestCase):
def test_users_view_exists(self):
response = self.client.get(reverse('game:users'))
self.assertEqual(res... | Set up test.py file and add skeleton for UserViewTests and RegistrationTests. Also add test to make sure user view exists | Set up test.py file and add skeleton for UserViewTests and RegistrationTests. Also add test to make sure user view exists
| Python | mit | shintouki/augmented-pandemic,shintouki/augmented-pandemic,shintouki/augmented-pandemic |
336769417acfdc7d61394008952dc124cc889b3c | changes/api/serializer/models/jobstep.py | changes/api/serializer/models/jobstep.py | from changes.api.serializer import Serializer, register
from changes.models import JobStep
@register(JobStep)
class JobStepSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'phase': {
'i... | from changes.api.serializer import Serializer, register
from changes.models import JobStep
@register(JobStep)
class JobStepSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'name': instance.label,
'phase': {
'i... | Add data to JobStep serializer | Add data to JobStep serializer
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes |
6d97b723915e5de7a008e5d7bdd44e7883967fdc | retdec/tools/__init__.py | retdec/tools/__init__.py | #
# Project: retdec-python
# Copyright: (c) 2015-2016 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tools that use the library to analyze and decompile files."""
from retdec import DEFAULT_API_URL
from retdec import __version__
def _add_arguments_sh... | #
# Project: retdec-python
# Copyright: (c) 2015-2016 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tools that use the library to analyze and decompile files."""
from retdec import DEFAULT_API_URL
from retdec import __version__
def _add_arguments_sh... | Simplify the help message for the -k/--api-key parameter. | Simplify the help message for the -k/--api-key parameter.
We can use the '%(default)s' placeholder instead of string formatting.
| Python | mit | s3rvac/retdec-python |
c1893024ebd04a8eee14e2197791d6bab1985f2b | sheldon/storage.py | sheldon/storage.py | # -*- coding: utf-8 -*-
"""
Interface to Redis-storage.
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from .utils import logger
# We will catch all import exceptions in bot.py
from redis import StrictRedis
class Storage:
def __init__(self, bot):
... | # -*- coding: utf-8 -*-
"""
Interface to Redis-storage.
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from .utils import logger
# We will catch all import exceptions in bot.py
from redis import StrictRedis
class Storage:
def __init__(self, bot):
... | Delete 'return' to refactor code | Delete 'return' to refactor code
| Python | mit | lises/sheldon |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.