commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
b81d3d9cf19da3303d408bebdc602406e5185e1f | bump version number | creimers/cmsplugin_multipinmap,creimers/cmsplugin_multipinmap | cmsplugin_multipinmap/__init__.py | cmsplugin_multipinmap/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Chirstoph Reimers'
__email__ = 'christoph@superservice-international.com'
__version__ = '0.1.0.b10'
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Chirstoph Reimers'
__email__ = 'christoph@superservice-international.com'
__version__ = '0.1.0.b9'
| bsd-2-clause | Python |
afbec2b1caaecc7d5bdcfad825e071f0efa458b2 | Update interstateincidents.py | meaton00/class_project | bin/interstateincidents.py | bin/interstateincidents.py | import csv
import sys
data_file = open("IncidentData_24OCT14.csv", "rU")
data = csv.DictReader(data_file)
results = []
for item in data:
print item
if sys.argv[1] in item["Location"]:
t = item["Location"].split("@")
m = ""
if len(t) == 2:
m = t[1]
results.append({"Location": t[0], "Mile Marker": m, ... | import csv
import sys
data_file = open("ritis-eventsdec13.csv", "rU")
data = csv.DictReader(data_file)
results = []
for item in data:
print item
if sys.argv[1] in item["Location"]:
t = item["Location"].split("@")
m = ""
if len(t) == 2:
m = t[1]
results.append({"Location": t[0], "Mile Marker": m, "T... | mit | Python |
d53c25a2f2fe653911d403dbfc76c3b8bc949fb6 | add login_required | ideal/bublfish | api/request.py | api/request.py | # -*- encoding: utf-8 -*-
from functools import wraps
from django.http import HttpResponse
from django.utils.decorators import available_attrs
from api.response import JsonpResponse
from api.response import KWARGS_JSON
from api.response import DATA_ERR
def login_required(function=None, is_json=True):
"""
Ret... | # -*- encoding: utf-8 -*-
from functools import wraps
from django.http import HttpResponse
from django.utils.decorators import available_attrs
from api.response import JsonpResponse
from api.response import KWARGS_JSON
from api.response import DATA_ERR
def login_required(function=None, is_json=True):
"""
"""... | bsd-3-clause | Python |
8203ec3db0152b6c503158ba4adab6781d082b7a | Append current directory to sys path. | ushahidi/riverid-python,ushahidi/riverid-python,ushahidi/riverid-python | api/riverid.py | api/riverid.py | # RiverID Controller
# ==================
#
# This file is part of RiverID.
#
# RiverID is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | # RiverID Controller
# ==================
#
# This file is part of RiverID.
#
# RiverID is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | agpl-3.0 | Python |
f74ea1b92d57e59e5b07a600752004f8ae908453 | add missing newline | michelesr/coding-events,codeeu/coding-events,ercchy/coding-events,joseihf/coding-events,ercchy/coding-events,ercchy/coding-events,ercchy/coding-events,ioana-chiorean/coding-events,joseihf/coding-events,michelesr/coding-events,ercchy/coding-events,codeeu/coding-events,michelesr/coding-events,ioana-chiorean/coding-events... | codeweekeu/settings_production.py | codeweekeu/settings_production.py | from .settings import *
import os, dj_database_url
DEBUG = False
dbconfig = dj_database_url.config()
if dbconfig:
DATABASES['default'] = dbconfig
else:
del DATABASES['default']
SECRET_KEY = os.environ.get('SECRET_KEY', '')
STATIC_URL = '/static/'
STATIC_ROOT = join(DJANGO_ROOT, 'staticfiles')
STATICFILES_DIRS = ... | from .settings import *
import os, dj_database_url
DEBUG = False
dbconfig = dj_database_url.config()
if dbconfig:
DATABASES['default'] = dbconfig
else:
del DATABASES['default']
SECRET_KEY = os.environ.get('SECRET_KEY', '')
STATIC_URL = '/static/'
STATIC_ROOT = join(DJANGO_ROOT, 'staticfiles')
STATICFILES_DIRS = ... | mit | Python |
9ebd4dde25a62e56cb96244cdf75ba67a709d4c9 | add distance of compnaies | lkc9015/freestyle_project | app/NLP_LDA.py | app/NLP_LDA.py | import csv
import sklearn.feature_extraction.text as text
import numpy as np
from sklearn.decomposition import LatentDirichletAllocation
import matplotlib.pyplot as plt
## Read csv file ###
letters = []
company = []
shareholders_letter = "data\shareholders_letter.csv"
with open(shareholders_letter, "r") as csv_file:
... | import csv
import sklearn.feature_extraction.text as text
import numpy as np
from sklearn.decomposition import LatentDirichletAllocation
import matplotlib.pyplot as plt
## Read csv file ###
letters = []
company = []
csv_file_path = "data\shareholders_letter.csv"
with open(csv_file_path, "r") as csv_file:
reader =... | mit | Python |
10d01f2071b51c8b9ca5f1a8b1c12bb4e2c401be | Add docstring/help message to /roll command | andrewlin16/duckbot,andrewlin16/duckbot | app/duckbot.py | app/duckbot.py | import discord
import duckbot_settings
import random
import re
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()
range_regex = re.compile('\d+-\d+')
@bot.command(pass_context=True)
async def roll(ctx, x=None, y=... | import discord
import duckbot_settings
import random
import re
from discord.ext import commands
_DESCRIPTION = '''quack'''
bot = commands.Bot(command_prefix='/', description=_DESCRIPTION)
rand = random.SystemRandom()
range_regex = re.compile('\d+-\d+')
@bot.command(pass_context=True)
async def roll(ctx, bound1=Non... | mit | Python |
dcf2dcb41e66ce01e386d526370ce23064e6e2a3 | Improve formatting of schema format exception messages | gamechanger/schemer | schemer/exceptions.py | schemer/exceptions.py |
class SchemaFormatException(Exception):
"""Exception which encapsulates a problem found during the verification of a
a schema."""
def __init__(self, message, path):
self._message = message.format('\"{}\"'.format(path))
self._path = path
@property
def path(self):
"""The fi... |
class SchemaFormatException(Exception):
"""Exception which encapsulates a problem found during the verification of a
a schema."""
def __init__(self, message, path):
self._message = message.format(path)
self._path = path
@property
def path(self):
"""The field path at which... | mit | Python |
2823b35d3bf3d521ae3c9769e2696455bbed8318 | Expand home directory wildcards to ensure path is valid | jasedit/scriptorium,jasedit/papers_base | scriptorium/config.py | scriptorium/config.py | #!/usr/bin/env python
"""Configuration related functionality for scriptorium."""
import os
import yaml
import scriptorium
_DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium')
_CFG_FILE = os.path.join(_DEFAULT_DIR, 'config')
_DEFAULT_CFG = {
'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates')... | #!/usr/bin/env python
"""Configuration related functionality for scriptorium."""
import os
import yaml
import scriptorium
_DEFAULT_DIR = os.path.join(os.path.expanduser("~"), '.scriptorium')
_CFG_FILE = os.path.join(_DEFAULT_DIR, 'config')
_DEFAULT_CFG = {
'TEMPLATE_DIR': os.path.join(_DEFAULT_DIR, 'templates')... | mit | Python |
89b9b65631d265a68254ba022c67c8f03ac2ea24 | Clean up imports slightly | StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native,StoDevX/AAO-React-Native | scripts/stav-covid.py | scripts/stav-covid.py | import requests
from bs4 import BeautifulSoup
# Fetch the output to a string, `output`.
url = "https://wp.stolaf.edu/reslife/dining-hours/"
output = requests.get(url).text
# Now, parse it.
output = BeautifulSoup(output)
# NOTE(rye): There is no filtering to prevent loading tables that aren't valid,
# so please doubl... | # For loading HTTP data, just use requests...
import requests
# ...and BeautifulSoup for parsing and getting data out.
from bs4 import BeautifulSoup
# Fetch the output to a string, `output`.
url = "https://wp.stolaf.edu/reslife/dining-hours/"
output = requests.get(url).text
# Now, parse it.
output = BeautifulSoup(ou... | agpl-3.0 | Python |
be35a402c6062b77d501680d185a2c93388cbf5f | Bump version | njvack/scorify | src/scorify/_metadata.py | src/scorify/_metadata.py | # -*- coding: utf-8 -*-
version = "0.8.0"
author = "Nathan Vack"
author_email = "njvack@wisc.edu"
license = "MIT"
copyright = "Copyright 2017 Boards of Regent of the University of Wisconsin System"
url = "https://github.com/njvack/scorify"
| # -*- coding: utf-8 -*-
version = "0.7.0"
author = "Nathan Vack"
author_email = "njvack@wisc.edu"
license = "MIT"
copyright = "Copyright 2017 Boards of Regent of the University of Wisconsin System"
url = "https://github.com/njvack/scorify"
| mit | Python |
010e4559dcd274bf42b5e458f4dbab559dd9a202 | Handle 2xx codes correctly | pauloschilling/sentry,zenefits/sentry,ngonzalvez/sentry,beeftornado/sentry,gencer/sentry,wujuguang/sentry,songyi199111/sentry,imankulov/sentry,jean/sentry,wujuguang/sentry,looker/sentry,1tush/sentry,boneyao/sentry,gencer/sentry,jean/sentry,drcapulet/sentry,BuildingLink/sentry,Natim/sentry,JackDanger/sentry,wong2/sentry... | src/sentry/api/client.py | src/sentry/api/client.py | from __future__ import absolute_import
__all__ = ('ApiClient',)
from django.core.urlresolvers import resolve
from rest_framework.test import APIRequestFactory
from sentry.utils import json
class ApiError(Exception):
def __init__(self, status_code, body):
self.status_code = status_code
self.body... | from __future__ import absolute_import
__all__ = ('ApiClient',)
from django.core.urlresolvers import resolve
from rest_framework.test import APIRequestFactory
from sentry.utils import json
class ApiError(Exception):
def __init__(self, status_code, body):
self.status_code = status_code
self.body... | bsd-3-clause | Python |
b331632e0fd999083ca7e2fe035ad64c2b210470 | Remove unused import statement | agt-the-walker/shogi-utils,agt-the-walker/shogi-utils | analyze_81dojo_game_test.py | analyze_81dojo_game_test.py | #!/usr/bin/env python3
from analyze_81dojo_game import parse_game
def test_parse_game():
parse_game(open("4471112.json"))
| #!/usr/bin/env python3
import json
from analyze_81dojo_game import parse_game
def test_parse_game():
parse_game(open("4471112.json"))
| mit | Python |
58915da451e59400d5f5a2a757c5af0919e87b61 | Allow OAR file rule to use non-OSGI jars | y-higuchi/onos,donNewtonAlpha/onos,VinodKumarS-Huawei/ietf96yang,kuujo/onos,LorenzReinhart/ONOSnew,gkatsikas/onos,maheshraju-Huawei/actn,VinodKumarS-Huawei/ietf96yang,gkatsikas/onos,opennetworkinglab/onos,mengmoya/onos,osinstom/onos,sdnwiselab/onos,osinstom/onos,sdnwiselab/onos,LorenzReinhart/ONOSnew,y-higuchi/onos,Lor... | buck-tools/onos_oar.py | buck-tools/onos_oar.py | #!/usr/bin/env python
#FIXME Add license
from zipfile import ZipFile
def generateOar(output, files=[]):
# Note this is not a compressed zip
with ZipFile(output, 'w') as zip:
for file, mvnCoords in files:
filename = file.split('/')[-1]
if mvnCoords == 'NONE':
des... | #!/usr/bin/env python
#FIXME Add license
from zipfile import ZipFile
def generateOar(output, files=[]):
# Note this is not a compressed zip
with ZipFile(output, 'w') as zip:
for file, mvnCoords in files:
filename = file.split('/')[-1]
if mvnCoords == 'NONE':
des... | apache-2.0 | Python |
4d50041557b379da178aba398a62b5c035fbfc05 | Update sentiment database | ArVID220u/LoveAgainstHate | sentiment_database.py | sentiment_database.py | # this is a file meant to coordinate the database of abusive and nonabusive tweets
# it also acts as a tool to easily classify streamed tweets, via the add_tweet method
# get tweets
# this function returns only the tweets (not the ids)
# accepted arguments: "hateful", "neutral" and "kind"
def get_tweets(version):
... | # this is a file meant to coordinate the database of abusive and nonabusive tweets
# it also acts as a tool to easily classify streamed tweets, via the add_tweet method
# get tweets
# this function returns only the tweets (not the ids)
# accepted arguments: "hateful", "neutral" and "kind"
def get_tweets(version):
... | mit | Python |
6da2c12fb0cad4f5d153703374c6146c0e07bc74 | Update version | architecture-building-systems/CEAforArcGIS,architecture-building-systems/CEAforArcGIS | cea/__init__.py | cea/__init__.py | __version__ = "2.30.0"
class ConfigError(Exception):
"""Raised when the configuration of a tool contains some invalid values."""
rc = 100 # sys.exit(rc)
class CustomDatabaseNotFound(Exception):
"""Raised when the InputLocator can't find a user-provided database (region=='custom')"""
rc = 101 # sys... | __version__ = "2.29.0"
class ConfigError(Exception):
"""Raised when the configuration of a tool contains some invalid values."""
rc = 100 # sys.exit(rc)
class CustomDatabaseNotFound(Exception):
"""Raised when the InputLocator can't find a user-provided database (region=='custom')"""
rc = 101 # sys... | mit | Python |
d1004fde1230a835d8ca35a118ee575121bfd640 | add custom exceptions | Widukind/dlstats,Widukind/dlstats | dlstats/errors.py | dlstats/errors.py |
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args,... |
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args,... | agpl-3.0 | Python |
326b14ba9b326689d008529a6e2137923a82386e | Improve prerequisite fail message | gs0510/coala-bears,horczech/coala-bears,incorrectusername/coala-bears,yashtrivedi96/coala-bears,madhukar01/coala-bears,Asnelchristian/coala-bears,aptrishu/coala-bears,naveentata/coala-bears,refeed/coala-bears,coala/coala-bears,vijeth-aradhya/coala-bears,vijeth-aradhya/coala-bears,Shade5/coala-bears,coala-analyzer/coala... | bears/c_languages/CSecurityBear.py | bears/c_languages/CSecurityBear.py | from coalib.bearlib.abstractions.Linter import linter
from dependency_management.requirements.DistributionRequirement import (
DistributionRequirement)
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
@linter(executable='flawfinder',
output_format='regex',
output_regex=r'.+:(?P<line>\d+)... | from coalib.bearlib.abstractions.Linter import linter
from dependency_management.requirements.DistributionRequirement import (
DistributionRequirement)
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
@linter(executable='flawfinder',
output_format='regex',
output_regex=r'.+:(?P<line>\d+)... | agpl-3.0 | Python |
3ca53584d7627ade6aa54599c6ee9db2bb5e1e68 | Remove comment [ci skip] | julienr/vispy,drufat/vispy,dchilds7/Deysha-Star-Formation,sh4wn/vispy,michaelaye/vispy,hronoses/vispy,sbtlaarzc/vispy,kkuunnddaannkk/vispy,drufat/vispy,Eric89GXL/vispy,jay3sh/vispy,sbtlaarzc/vispy,dchilds7/Deysha-Star-Formation,ghisvail/vispy,RebeccaWPerry/vispy,bollu/vispy,hronoses/vispy,hronoses/vispy,bollu/vispy,mic... | vispy/visuals/tests/test_text.py | vispy/visuals/tests/test_text.py | # -*- coding: utf-8 -*-
from vispy.scene.visuals import Text
from vispy.testing import (requires_application, TestingCanvas,
assert_image_equal, run_tests_if_main)
@requires_application()
def test_text():
"""Test basic text support"""
with TestingCanvas(bgcolor='w', size=(92, 9... | # -*- coding: utf-8 -*-
from vispy.scene.visuals import Text
from vispy.testing import (requires_application, TestingCanvas,
assert_image_equal, run_tests_if_main)
@requires_application()
def test_text():
"""Test basic text support"""
with TestingCanvas(bgcolor='w', size=(92, 9... | bsd-3-clause | Python |
35e7f9f027278783ee89befcce0f2adec6bc79d5 | fix rpc-6 client example (#214) | mosquito/aio-pika | docs/source/rabbitmq-tutorial/examples/6-rpc/rpc_client.py | docs/source/rabbitmq-tutorial/examples/6-rpc/rpc_client.py | import asyncio
import uuid
from aio_pika import connect, IncomingMessage, Message
class FibonacciRpcClient:
def __init__(self, loop):
self.connection = None
self.channel = None
self.callback_queue = None
self.futures = {}
self.loop = loop
async def connect(self):
... | import asyncio
import uuid
from aio_pika import connect, IncomingMessage, Message
class FibonacciRpcClient:
def __init__(self, loop):
self.connection = None
self.channel = None
self.callback_queue = None
self.futures = {}
self.loop = loop
async def connect(self):
... | apache-2.0 | Python |
d4d53812629dae119935a954e57d413b26bc56a6 | Fix an ugly typo | batiste/django-page-cms,remik/django-page-cms,remik/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,oliciv/django-page-cms,remik/django-page-cms,batiste/django-page-cm... | pages/tests.py | pages/tests.py | from django.test import TestCase
from pages.models import *
class PagesTestCase(TestCase):
fixtures = ['tests']
def test_01_managers(self):
"""Check the managers"""
pages = Page.published.all()
for p in pages:
self.assertEqual(p.status, 1)
pages = Page.drafts.all()
... | from django.test import TestCase
from pages.models import *
class PagesTestCase(TestCase):
fixtures = ['tests']
def test_01_managers(self):
"""Check the managers"""
pages = Page.published.all()
for p in pages:
self.assertEqual(p.status, 1)
pages = Page.drafts.all()
... | bsd-3-clause | Python |
aa7629b15d90a4d1b0ded41786aa0d009e6e5295 | fix webutil unit tests | groppe/mario | src/test/webutil_test.py | src/test/webutil_test.py | #!/usr/bin/python3.6
import json
import unittest
from lib import webutil as webutil
class RankTests(unittest.TestCase):
def testRespondSuccess(self):
# Arrange
message = 'message'
expected_result = {
'statusCode': 200,
'headers': {
'Content-Type':... | #!/usr/bin/python3.6
import json
import unittest
from lib import webutil as webutil
class RankTests(unittest.TestCase):
def testRespondSuccess(self):
# Arrange
message = 'message'
expected_result = {
'statusCode': 200,
'headers': {
'Content-Type':... | mit | Python |
d02adf760bd32bd2cb169c01750e34bd487dc7ff | include sommerfest in topic | dennisausbremen/tunefish,dennisausbremen/tunefish,dennisausbremen/tunefish | server/bands/mails.py | server/bands/mails.py | # coding=utf-8
from email.header import Header
from email.mime.text import MIMEText
import smtplib
from flask.templating import render_template
from server.app import celery
SENDER = "noreply@vorstrasse-bremen.de"
@celery.task
def __sendmail(message, app):
server = smtplib.SMTP(app.config['MAIL_SERVER'], app.co... | # coding=utf-8
from email.header import Header
from email.mime.text import MIMEText
import smtplib
from flask.templating import render_template
from server.app import celery
SENDER = "noreply@vorstrasse-bremen.de"
@celery.task
def __sendmail(message, app):
server = smtplib.SMTP(app.config['MAIL_SERVER'], app.co... | apache-2.0 | Python |
807a11768bc85c7d5ba8cb66f66c20a428de8990 | add created_by_identity to machine serializer | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend | api/serializers/provider_machine_serializer.py | api/serializers/provider_machine_serializer.py | from core.models.application import ApplicationScore
from core.models.machine import ProviderMachine
from core.models import Tag
from core.models.instance_source import InstanceSource
from rest_framework import serializers
from .cleaned_identity_serializer import CleanedIdentitySerializer
from .license_serializer impor... | from core.models.application import ApplicationScore
from core.models.machine import ProviderMachine
from core.models import Tag
from core.models.instance_source import InstanceSource
from rest_framework import serializers
from .license_serializer import LicenseSerializer
from .tag_related_field import TagRelatedField
... | apache-2.0 | Python |
8805eb9af00a25344a0b62dcf808d04cf34dd5a5 | Replace yaml.load() with yaml.safe_load() for security reasons. | ramitsurana/boto,Asana/boto,pfhayes/boto,ocadotechnology/boto,weebygames/boto,elainexmas/boto,dimdung/boto,nishigori/boto,SaranyaKarthikeyan/boto,zachmullen/boto,revmischa/boto,bryx-inc/boto,vishnugonela/boto,bleib1dj/boto,khagler/boto,shaunbrady/boto,TiVoMaker/boto,vijaylbais/boto,Pretio/boto,yangchaogit/boto,janslow/... | boto/contrib/ymlmessage.py | boto/contrib/ymlmessage.py | # Copyright (c) 2006,2007 Chris Moyer
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, di... | # Copyright (c) 2006,2007 Chris Moyer
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, di... | mit | Python |
9a5efef01fccfbc562dfc08588f3449f1a20b280 | Fix typing annotation crash for generate_visualization | tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets | tensorflow_datasets/scripts/documentation/generate_visualization.py | tensorflow_datasets/scripts/documentation/generate_visualization.py | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | apache-2.0 | Python |
a0f04b81b58aec40b5e6246eb102f6ecae20d1b6 | Update store.py | MtnFranke/rpi-photo-frame,MtnFranke/rpi-photo-frame,MtnFranke/rpi-photo-frame,MtnFranke/rpi-photo-frame | server/image/store.py | server/image/store.py | import datetime
import glob
import os
import random
from operator import itemgetter
import numpy
from PIL.ExifTags import TAGS
from functional import seq
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from PIL import Image
class ImageStore:
def __init__(self, image_dir,... | import datetime
import glob
import os
from operator import itemgetter
import numpy
from PIL.ExifTags import TAGS
from functional import seq
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from PIL import Image
class ImageStore:
def __init__(self, image_dir, img_decay):
... | apache-2.0 | Python |
8b34605eac7106f921a61a50a810a6bcc305d3cb | Test all stars, and skip one test since it's slow | DanielAndreasen/SWEETer-Cat,DanielAndreasen/SWEETer-Cat | sweetercat/test_app.py | sweetercat/test_app.py | import pytest
import flask
from flask import url_for
from app import app as sc_app
from utils import readSC
# app fixture required for pytest-flask client
@pytest.fixture
def app():
sc_app.testing = True
sc_app.debug = True
return sc_app
# First test using the client fixture from pytest-flask
def test_s... | import pytest
import flask
from flask import url_for
from app import app as sc_app
# app fixture required for pytest-flask client
@pytest.fixture
def app():
sc_app.testing = True
sc_app.debug = True
return sc_app
# First test using the client fixture from pytest-flask
def test_status_codes(client):
... | mit | Python |
2d57d87b15c73fe1f9b884dc57ecf2c25a5e7454 | Add `from_tensor` classmethod to `TensorSpec` in the Numpy backend. | tensorflow/probability,tensorflow/probability | tensorflow_probability/python/internal/backend/numpy/tensor_spec.py | tensorflow_probability/python/internal/backend/numpy/tensor_spec.py | # Copyright 2021 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | # Copyright 2021 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | apache-2.0 | Python |
620f123bd7b8b5da348aab12216b56202d405457 | update example | hkwi/twink | test/example_switch.py | test/example_switch.py | import binascii
import twink
from twink.ofp4 import *
import twink.ofp4.parse as p
import twink.ofp4.build as b
import twink.ofp4.oxm as oxm
import logging
logging.basicConfig(level=logging.DEBUG)
def switch_proc(message, channel):
msg = p.parse(message)
if msg.header.type == OFPT_FEATURES_REQUEST:
c... | import binascii
import twink
import twink.gevent
from twink.ofp4 import *
import twink.ofp4.parse as p
import twink.ofp4.build as b
import twink.ofp4.oxm as oxm
import logging
logging.basicConfig(level=logging.DEBUG)
def switch_proc(message, channel):
msg = p.parse(message)
if msg.header.type == OFPT_F... | apache-2.0 | Python |
a757e39a4c09d2fcb102605cf41950b41e9e59bf | simplify screw example | nschloe/python4gmsh | test/examples/screw.py | test/examples/screw.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygmsh as pg
import numpy as np
def generate():
# Draw a cross.
poly = pg.add_polygon([
[0.0, 0.5, 0.0],
[-0.1, 0.1, 0.0],
[-0.5, 0.0, 0.0],
[-0.1, -0.1, 0.0],
[0.0, -0.5, 0.0],
[0.1, -0.1, 0.0],
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygmsh as pg
import numpy as np
def generate():
'''Screw
'''
# Form a cross.
X = np.array([
[0.0, 0.5, 0.0],
[-0.1, 0.1, 0.0],
[-0.5, 0.0, 0.0],
[-0.1, -0.1, 0.0],
[0.0, -0.5, 0.0],
[0.1, -0.1, ... | bsd-3-clause | Python |
239098c8fbf9701cc44abe7db76e9608a57d4420 | update middleware to support multi site | wlashell/lyrical_page,wlashell/lyrical_page | site_content/middleware.py | site_content/middleware.py | from django.http import Http404
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.cache import cache
from site_content.views import site_page
def make_tls_property(default=None):
"""Creates a class-wide instance property with a thread-specific value."""
class TLSPr... | from django.http import Http404
from django.conf import settings
from site_content.views import site_page
class SitePageFallbackMiddleware(object):
def process_response(self, request, response):
if response.status_code != 404:
return response
try:
return site_page(... | apache-2.0 | Python |
10c8411e715b3b2852e40fc41051e54078b645b0 | fix conditional ipdb import | sha-red/django-shared-utils,sha-red/django-shared-utils | shared/utils/templatetags/debug_utils.py | shared/utils/templatetags/debug_utils.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import template
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
register = template.Library()
try:
import ipdb
@register.filter
def ipdb_inspect(value):
ipdb.set_trace()
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import template
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
try:
import ipdb
register = template.Library()
@register.filter
def ipdb_inspect(value):
ipdb.set_trace()
... | mit | Python |
73ab9edf96fa9594e64c962e01fb93440bfead92 | Add SUGGESTED_CONFIG | cihai/cihai,cihai/cihai,cihai/cihai-python | cihai/config.py | cihai/config.py | # -*- coding: utf8 - *-
from __future__ import absolute_import, print_function, unicode_literals
import os
from appdirs import AppDirs
from cihai._compat import string_types
#: XDG App directory locations
dirs = AppDirs("cihai", "cihai team") # appname # app author
#: Default configuration
DEFAULT_CONFIG = {
... | # -*- coding: utf8 - *-
from __future__ import absolute_import, print_function, unicode_literals
import os
from appdirs import AppDirs
from cihai._compat import string_types
#: XDG App directory locations
dirs = AppDirs("cihai", "cihai team") # appname # app author
#: Default configuration
DEFAULT_CONFIG = {
... | mit | Python |
855317fe362fd9b3a1d2a6df3f8f1ad1637218f7 | Create prueba.py | aescoda/TFG | prueba.py | prueba.py | from flask import Flask
from flask import request
import xml.etree.ElementTree as ET
from threading import Thread
app = Flask(__name__)
def send_email(xml):
print "2"
print xml
return None
@app.route('/webhook', methods=['POST','GET'])
def webhook():
print "webhook"
xml = "hola"
... | from flask import Flask
from flask import request
import xml.etree.ElementTree as ET
from threading import Thread
app = Flask(__name__)
def send_email(xml):
data = ET.fromstring(xml)
iccid = req[0]
admin_details = get_admin(iccid)
customer_email = get_email(admin_details[0])
email_alert(customer... | apache-2.0 | Python |
3455982ad76a28f022c922a62f3c666421a87696 | Remove unused import | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/warehouse/models/shared.py | corehq/warehouse/models/shared.py |
class WarehouseTable(object):
@classmethod
def commit(cls, start_datetime, end_datetime):
raise NotImplementedError
@classmethod
def dependencies(cls):
'''Returns a list of slugs that the warehouse table is dependent on'''
raise NotImplementedError
| from django.db import transaction
class WarehouseTable(object):
@classmethod
def commit(cls, start_datetime, end_datetime):
raise NotImplementedError
@classmethod
def dependencies(cls):
'''Returns a list of slugs that the warehouse table is dependent on'''
raise NotImplemente... | bsd-3-clause | Python |
8d6c83c31fa5d15fe342056380f06967d54cf785 | Bump version to 0.27.0 | thombashi/SimpleSQLite,thombashi/SimpleSQLite | simplesqlite/__version__.py | simplesqlite/__version__.py | # encoding: utf-8
from datetime import datetime
__author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2016-{}, {}".format(datetime.now().year, __author__)
__license__ = "MIT License"
__version__ = "0.27.0"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| # encoding: utf-8
from datetime import datetime
__author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2016-{}, {}".format(datetime.now().year, __author__)
__license__ = "MIT License"
__version__ = "0.26.0"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| mit | Python |
20b6d7dde22ae5c7efaa26cddcebca88bcbd1ba7 | Break out the acces control into a mixin | CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer | wafer/users/views.py | wafer/users/views.py | from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.views.generic import DetailView, UpdateView
from django.views.generic.list import ListView
from wafer.users.forms import UserForm, UserProfileForm
from wafer.users.mo... | from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.views.generic import DetailView, UpdateView
from django.views.generic.list import ListView
from wafer.users.forms import UserForm, UserProfileForm
from wafer.users.mo... | isc | Python |
311e02e13bf7ffd9f138fb562b02d51283e89abd | Remove old style db config | wheelcms/wheel-site,wheelcms/wheel-site | wheel_cms/settings/production.py | wheel_cms/settings/production.py | from settings.base import *
from wheelcms_project.settings.base.util import get_env_variable
DEBUG=False
STRACKS_URL = get_env_variable('STRACKS_URL', '')
STRACKS_CONNECTOR = None
if STRACKS_URL:
from stracks_api.connector import ASyncHTTPConnector
STRACKS_CONNECTOR = ASyncHTTPConnector(STRACKS_URL)
MID... | from settings.base import *
from wheelcms_project.settings.base.util import get_env_variable
if not DATABASE_URL:
PG_DEFAULT_DB = {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': get_env_variable('DB_NAME'),
'USER': get_env_variable('DB_USER'),
'PASSWORD... | bsd-2-clause | Python |
04084261e52386682ac9b748150ba366cebbdebf | Use assert_array_almost_equal in test_block_rdd | bikash/spylearn,ogrisel/spylearn,bikash/spylearn,ogrisel/spylearn | test/test_block_rdd.py | test/test_block_rdd.py | import shutil
import tempfile
import numpy as np
from common import SpylearnTestCase
from spylearn.block_rdd import block_rdd
from numpy.testing import assert_array_almost_equal
class TestUtils(SpylearnTestCase):
def setUp(self):
super(TestUtils, self).setUp()
self.outputdir = tempfile.mkdtemp()... | from common import SpylearnTestCase
import shutil
import tempfile
from spylearn.block_rdd import block_rdd
import numpy as np
class TestUtils(SpylearnTestCase):
def setUp(self):
super(TestUtils, self).setUp()
self.outputdir = tempfile.mkdtemp()
def tearDown(self):
super(TestUtils, se... | bsd-3-clause | Python |
58cd12de539bc3bd5ba9f761c5b85773d922d831 | bump version | SystemRDL/systemrdl-compiler,SystemRDL/systemrdl-compiler,SystemRDL/systemrdl-compiler,SystemRDL/systemrdl-compiler | systemrdl/__about__.py | systemrdl/__about__.py | __version__ = "1.15.1"
| __version__ = "1.15.0"
| mit | Python |
7448dcea6591f632026e56f3246593782867923d | Fix optimizers tests | nebw/keras,kemaswill/keras,keras-team/keras,keras-team/keras,relh/keras,dolaameng/keras,kuza55/keras,DeepGnosis/keras | tests/keras/test_optimizers.py | tests/keras/test_optimizers.py | from __future__ import print_function
import pytest
from keras.utils.test_utils import get_test_data
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.utils.np_utils import to_categorical
(X_train,... | from __future__ import print_function
import pytest
from keras.utils.test_utils import get_test_data
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.utils.np_utils import to_categorical
(X_train,... | mit | Python |
242bcbf8bb6c1b7fbcc8122f8f4aeb32e2a2669d | Add docstring to `Task` model | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft | pycroft/model/task.py | pycroft/model/task.py | import builtins
from collections.abc import Mapping
from marshmallow import Schema
from sqlalchemy import Column, Enum, Integer, ForeignKey, String
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import relationship, backref
from typing import TypeVar, Generic
from pycroft.helpers import AutoNumb... | import builtins
from collections.abc import Mapping
from marshmallow import Schema
from sqlalchemy import Column, Enum, Integer, ForeignKey, String
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import relationship, backref
from typing import TypeVar, Generic
from pycroft.helpers import AutoNumb... | apache-2.0 | Python |
ff1db0d306017dfad3fa1287d57edba58d66db5b | add interface test for cs2 soap provider | NORDUnet/opennsa,NORDUnet/opennsa,jab1982/opennsa,NORDUnet/opennsa,jab1982/opennsa | test/test_interface.py | test/test_interface.py | from twisted.trial import unittest
from zope.interface.verify import verifyObject
from opennsa.interface import INSIProvider, INSIRequester
from opennsa import aggregator
from opennsa.backends.common import genericbackend
from opennsa.protocols.nsi2 import provider, requester
class InterfaceTest(unittest.TestCas... | from twisted.trial import unittest
from zope.interface.verify import verifyObject
from opennsa.interface import INSIProvider, INSIRequester
from opennsa import aggregator
from opennsa.backends.common import genericbackend
from opennsa.protocols.nsi2 import provider
class InterfaceTest(unittest.TestCase):
de... | bsd-3-clause | Python |
213a9b7db221363ea3299e4368bc4bfca5dadfb8 | Bump version nr to 0.9, as all basic functions are working and have tests | Robots-Linti/pyFirmata,tino/pyFirmata,JoseU/pyFirmata,jochasinga/pyFirmata | pyfirmata/__init__.py | pyfirmata/__init__.py | from pyfirmata import Board
__version__ = '0.9' | from pyfirmata import Board
__version__ = '0.1' | mit | Python |
9ae4a7feb42fe1b71ce7ba2e5ab9c7b1de92ea23 | check for cb_id as first thing in __new__ | ciappi/Yaranullin | yaranullin/weakcallback.py | yaranullin/weakcallback.py | # yaranullin/weakcallback.py
#
# Copyright (c) 2012 Marco Scopesi <marco.scopesi@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTW... | # yaranullin/weakcallback.py
#
# Copyright (c) 2012 Marco Scopesi <marco.scopesi@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTW... | isc | Python |
ba5bfeb652804e57203b1794c6293b8227590ac1 | Add proper logging support for consoles that don't accept ANSI | notcammy/PyInstaLive | pyinstalive/logger.py | pyinstalive/logger.py | import sys
import os
def colors(state):
color = ''
if (state == 'BLUE'):
color = '\033[94m'
if (state == 'GREEN'):
color = '\033[92m'
if (state == 'YELLOW'):
color = '\033[93m'
if (state == 'RED'):
color = '\033[91m'
if (state == 'ENDC'):
color = '\033[0m'
if (state == 'WHITE'):
color = '\033[... | def colors(state):
color = ''
if (state == 'BLUE'):
color = '\033[94m'
if (state == 'GREEN'):
color = '\033[92m'
if (state == 'YELLOW'):
color = '\033[93m'
if (state == 'RED'):
color = '\033[91m'
if (state == 'ENDC'):
color = '\033[0m'
if (state == 'WHITE'):
color = '\033[0m'
return color
de... | mit | Python |
37b16cea115419d1353cf1213698fc4a0d229fa7 | Make it possible to force an external url with the url_for helper | robhudson/warehouse,mattrobenolt/warehouse,techtonik/warehouse,mattrobenolt/warehouse,robhudson/warehouse,techtonik/warehouse,mattrobenolt/warehouse | warehouse/helpers.py | warehouse/helpers.py | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | apache-2.0 | Python |
24c0f99a9e78d4686114d4d7a5e1fe58fa960992 | normalize quotes | shawnbot/feed-funnel | funnel.py | funnel.py | #!/usr/bin/env python
import feedparser
import time, datetime
import json
def funnel(feeds, limit=100, **options):
def to_feed(feed):
f = {}
f.update(options)
if type(feed) is dict:
f.update(feed)
else:
f['url'] = feed
return f
feeds = map(lambda ... | #!/usr/bin/env python
import feedparser
import time, datetime
import json
def funnel(feeds, limit=100, **options):
def to_feed(feed):
f = {}
f.update(options)
if type(feed) is dict:
f.update(feed)
else:
f['url'] = feed
return f
feeds = map(lambda ... | bsd-3-clause | Python |
da72c3669f5a7d3f806ae691eb0f5463d56023fa | Fix build | mlassnig/pilot2,PalNilsson/pilot2,mlassnig/pilot2,PalNilsson/pilot2,TWAtGH/pilot2 | pilot/control/lifetime.py | pilot/control/lifetime.py | #!/usr/bin/env python
# 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
#
# Authors:
# - Mario Lassnig, mario.lassnig@cern.ch, 2017
import time
from ... | #!/usr/bin/env python
# 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
#
# Authors:
# - Mario Lassnig, mario.lassnig@cern.ch, 2017
import time
from ... | apache-2.0 | Python |
93bb9094393f86845122932341f8c8824539bedb | Fix typo | pinax/pinax-submissions | pinax/submissions/urls.py | pinax/submissions/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^submit/$", views.SubmissionKindList.as_view(), name="submission_submit"),
url(r"^submit/(?P<kind_slug>[\w-]+)/$", views.SubmissionAdd.as_view(), name="submission_submit_kind"),
url(r"^(?P<pk>\d+)/$", views.SubmissionDetail.as_vie... | from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^submit/$", views.SubmissionKindList.as_view(), name="submission_submit"),
url(r"^submit/(?P<kind_slug>[\w-]+)/$", views.SubmissionAdd.as_view(), name="submission_submit_kind"),
url(r"^(?P<pk>\d+)/$", views.SubmissionDetail.as_vie... | mit | Python |
59a6745759540e95b28ac818975b56634711d7b2 | Use BUP_MAIN_EXE to invoke the correct bup. | gevaerts/bup,tjanez/bup,apenwarr/bup,apenwarr/bup,ToxicFrog/bup,jbaber/bup,pombredanne/bup,tjanez/bup,gevaerts/bup,jbaber/bup,jbaber/bup,ToxicFrog/bup,pombredanne/bup,mhoeher/bup,mhoeher/bup,gevaerts/bup,pombredanne/bup,ToxicFrog/bup,tjanez/bup,mhoeher/bup,pombredanne/bup,gevaerts/bup,jbaber/bup,pombredanne/bup,mhoeher... | cmd/help-cmd.py | cmd/help-cmd.py | #!/usr/bin/env python
import sys, os, glob
from bup import options
optspec = """
bup help <command>
"""
o = options.Options('bup help', optspec)
(opt, flags, extra) = o.parse(sys.argv[1:])
if len(extra) == 0:
# the wrapper program provides the default usage string
os.execvp(os.environ['BUP_MAIN_EXE'], ['bup']... | #!/usr/bin/env python
import sys, os, glob
from bup import options
optspec = """
bup help <command>
"""
o = options.Options('bup help', optspec)
(opt, flags, extra) = o.parse(sys.argv[1:])
if len(extra) == 0:
# the wrapper program provides the default usage string
os.execvp('bup', ['bup'])
elif len(extra) == ... | lgpl-2.1 | Python |
f2366223f24609a8041a8b77109d18c62444cf90 | Bump version number to 1.9.12 | jamesfoley/cms,dan-gamble/cms,dan-gamble/cms,jamesfoley/cms,jamesfoley/cms,dan-gamble/cms,jamesfoley/cms | cms/__init__.py | cms/__init__.py | """
A collection of Django extensions that add content-management facilities to Django projects.
Developed by Dave Hall.
<http://etianen.com/>
"""
# Always use 3 parts, not 1, 2, or 4.
VERSION = (1, 9, 12)
| """
A collection of Django extensions that add content-management facilities to Django projects.
Developed by Dave Hall.
<http://etianen.com/>
"""
VERSION = (1, 9, 11, 3)
| bsd-3-clause | Python |
bcb9775a3632fa3c7f4284101257a147420c4d08 | Bump version | rsalmaso/django-cms,yakky/django-cms,irudayarajisawa/django-cms,jproffitt/django-cms,FinalAngel/django-cms,dhorelik/django-cms,benzkji/django-cms,timgraham/django-cms,vad/django-cms,Jaccorot/django-cms,jeffreylu9/django-cms,chkir/django-cms,benzkji/django-cms,nimbis/django-cms,benzkji/django-cms,yakky/django-cms,FinalA... | cms/__init__.py | cms/__init__.py | # -*- coding: utf-8 -*-
__version__ = '3.0.9'
default_app_config = 'cms.apps.CMSConfig'
| # -*- coding: utf-8 -*-
__version__ = '3.0.9.dev1'
default_app_config = 'cms.apps.CMSConfig'
| bsd-3-clause | Python |
fa339a8b70c0f532b93dd38aa593a2793c0f22f6 | Fix firmware verification for examples | ZachMassia/platformio,jrobeson/platformio,atyenoria/platformio,platformio/platformio,mplewis/platformio,dkuku/platformio,platformio/platformio-core,eiginn/platformio,valeros/platformio,jrobeson/platformio,bkudria/platformio,bkudria/platformio,mseroczynski/platformio,bkudria/platformio,bkudria/platformio,platformio/plat... | tests/test_examples.py | tests/test_examples.py | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from glob import glob
from os import listdir, walk
from os.path import dirname, getsize, isdir, isfile, join, normpath
from shutil import rmtree
import pytest
from platformio.util import exec_command
def pytest_generate_tests(metafunc):
... | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from glob import glob
from os import listdir, walk
from os.path import dirname, getsize, isdir, isfile, join, normpath
from shutil import rmtree
import pytest
from platformio.util import exec_command
def pytest_generate_tests(metafunc):
... | apache-2.0 | Python |
fc99443190b617e56385143aefb1e64116a17670 | fix test | angr/cle | tests/test_minidump.py | tests/test_minidump.py | #!/usr/bin/env python
import archinfo
import logging
import nose
import os
import cle
TEST_BASE = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.join('..', '..', 'binaries'))
def test_minidump():
exe = os.path.join(TEST_BASE, 'tests', 'x86', 'windows', 'jusched_x86.dmp')
ld = cle.Load... | #!/usr/bin/env python
import archinfo
import logging
import nose
import os
import cle
TEST_BASE = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.join('..', '..', 'binaries'))
def test_minidump():
exe = os.path.join(TEST_BASE, 'tests', 'x86', 'windows', 'jusched_x86.dmp')
ld = cle.Load... | bsd-2-clause | Python |
aa9ee566359bc492f361db119ea4994da3ca07f5 | fix test_remoting issue | geromueller/rpyc,sponce/rpyc,pombredanne/rpyc,kwlzn/rpyc,glpatcern/rpyc,gleon99/rpyc,pyq881120/rpyc,eplaut/rpyc,siemens/rpyc | tests/test_remoting.py | tests/test_remoting.py | import os
import tempfile
import shutil
import unittest
from nose import SkipTest
import rpyc
class Test_Remoting(unittest.TestCase):
def setUp(self):
self.conn = rpyc.classic.connect_thread()
def tearDown(self):
self.conn.close()
def test_files(self):
base = tempfile.mkdtemp()
... | import os
import tempfile
import shutil
import unittest
from nose import SkipTest
import rpyc
class Test_Remoting(unittest.TestCase):
def setUp(self):
self.conn = rpyc.classic.connect_thread()
def tearDown(self):
self.conn.close()
def test_files(self):
base = tempfile.mkdtemp()
... | mit | Python |
dc716928f1ee357e99ba679c3e4bc7f071e882a1 | Add missing middleware. | etesync/journal-manager | tests/test_settings.py | tests/test_settings.py | import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = False
SECRET_KEY = 'fake-key'
ROOT_URLCONF = 'tests.test_urls'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'djan... | import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = False
SECRET_KEY = 'fake-key'
ROOT_URLCONF = 'tests.test_urls'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'djan... | agpl-3.0 | Python |
58920478dc86f344185f8ee62d7bcfa980b529b1 | update timer interface | nathants/py-util | util/time.py | util/time.py | import signal
import contextlib
import time
@contextlib.contextmanager
def timer(msg=None, print_fn=print):
val = {'seconds': None}
start = time.time()
try:
yield val
except:
raise
finally:
val['seconds'] = time.time() - start
if msg:
print_fn(msg, int(va... | import signal
import contextlib
import time
@contextlib.contextmanager
def timer():
val = {'seconds': None}
start = time.time()
try:
yield val
except:
raise
finally:
val['seconds'] = time.time() - start
@contextlib.contextmanager
def timeout(seconds=1, message='timeout'):
... | mit | Python |
e3b2fdeb048a2f226287a8e9b8973e5a54886511 | clean example | ratnania/pyccel,ratnania/pyccel | tests/macro/scripts/MPI/ex1.py | tests/macro/scripts/MPI/ex1.py | from mpi4py import MPI
rank = -1
#we must initialize rank
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
data = [0,0]
if rank == 0:
data = [7,4]
comm.send(data, 1, tag=11)
elif rank == 1:
data = comm.recv(source=0, tag=11)
print(data)
| from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
data = [0,0]
if rank == 0:
data = [7,4]
comm.send(data, 1, tag=11)
elif rank == 1:
data = comm.recv(source=0, tag=11)
print(data)
| mit | Python |
174582a9fe0381d526cec1b908c1a90a1cdc5413 | fix node cloud functions resource autodetection | googleapis/env-tests-logging,googleapis/env-tests-logging,googleapis/env-tests-logging,googleapis/env-tests-logging,googleapis/env-tests-logging | tests/nodejs/test_functions.py | tests/nodejs/test_functions.py | # Copyright 2021 Google 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 by applicable law or agreed to in writing, s... | # Copyright 2021 Google 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 by applicable law or agreed to in writing, s... | apache-2.0 | Python |
27e2cc73f43c5ca8eedee52009652b6195e76198 | Add a test for the blog announcement | gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com | tests/py/test_notifications.py | tests/py/test_notifications.py | from gratipay.testing import Harness
class TestNotifications(Harness):
def test_add_single_notification(self):
alice = self.make_participant('alice')
alice.add_notification('abcd')
assert alice.notifications == ["abcd"]
def test_add_multiple_notifications(self):
alice = self.ma... | from gratipay.testing import Harness
class TestNotifications(Harness):
def test_add_single_notification(self):
alice = self.make_participant('alice')
alice.add_notification('abcd')
assert alice.notifications == ["abcd"]
def test_add_multiple_notifications(self):
alice = self.ma... | mit | Python |
7c003123501f0e8bd7585e306afaf20911df5edd | Add test for str.encode() errors argument "backslashreplace" | brython-dev/brython,brython-dev/brython,brython-dev/brython | www/tests/test_string_methods.py | www/tests/test_string_methods.py | x = "zer"
assert x.capitalize() == "Zer"
assert str.capitalize(x) == "Zer"
assert "center".center(30) == ' center '
y="center"
assert y.center(30) == ' center '
assert str.center(y,30) == ' center '
x = "azert$t y t"
assert x.count('t') == 3
assert st... | x = "zer"
assert x.capitalize() == "Zer"
assert str.capitalize(x) == "Zer"
assert "center".center(30) == ' center '
y="center"
assert y.center(30) == ' center '
assert str.center(y,30) == ' center '
x = "azert$t y t"
assert x.count('t') == 3
assert st... | bsd-3-clause | Python |
ed5774f644c561e9dd4455ce8782bcbb179ddf87 | call super initial_data | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/apps/aggregate_ucrs/admin.py | corehq/apps/aggregate_ucrs/admin.py | from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib import admin
from . import models
class TimeAggregationDefinitionAdmin(admin.ModelAdmin):
def get_changeform_initial_data(self, request):
initial_data = super(TimeAggregationDefinitionAdmin, self).get_chang... | from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib import admin
from . import models
class TimeAggregationDefinitionAdmin(admin.ModelAdmin):
def get_changeform_initial_data(self, request):
return {
'start_column': 'opened_date',
'end... | bsd-3-clause | Python |
7c6fed4dc08529a281d1694924797e8e4021d73f | fix and flesh out the admin a bit more | crateio/crate.io | crate_project/apps/history/admin.py | crate_project/apps/history/admin.py | from django.contrib import admin
from history.models import Event
class EventAdmin(admin.ModelAdmin):
list_display = ["package", "version", "action", "data", "created"]
list_filter = ["action", "created"]
search_fields = ["package", "version"]
admin.site.register(Event, EventAdmin)
| from django.contrib import admin
from history.models import Event
class EventAdmin(admin.ModelAdmin):
list_display = ["package", "version", "data", "created"]
list_filter = ["created"]
search_fields = ["package", "version"]
admin.register(Event, EventAdmin)
| bsd-2-clause | Python |
6face5a0933eb6cc31fcff6ac8c8d4a204a3c2c2 | Fix #101. Call UCCSD method when ROHF method is input in cc.RCCSD | sunqm/pyscf,gkc1000/pyscf,gkc1000/pyscf,gkc1000/pyscf,gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf | cc/__init__.py | cc/__init__.py | '''
Coupled Cluster
===============
Simple usage::
>>> from pyscf import gto, scf, cc
>>> mol = gto.M(atom='H 0 0 0; H 0 0 1')
>>> mf = scf.RHF(mol).run()
>>> cc.CCSD(mf).run()
:func:`cc.CCSD` returns an instance of CCSD class. Followings are parameters
to control CCSD calculation.
verbose : in... | '''
Coupled Cluster
===============
Simple usage::
>>> from pyscf import gto, scf, cc
>>> mol = gto.M(atom='H 0 0 0; H 0 0 1')
>>> mf = scf.RHF(mol).run()
>>> cc.CCSD(mf).run()
:func:`cc.CCSD` returns an instance of CCSD class. Followings are parameters
to control CCSD calculation.
verbose : in... | apache-2.0 | Python |
6d7ebdceaea896dde86a278f1df6cfc998f0896a | Remove unnecessary print statements. | DerWeh/pyplot | pyplot.py | pyplot.py | #!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
"""Module to bundle plotting scripts
`activate-global-python-argcomplete` must be run to enable auto completion """
import argparse
import argcomplete
import plotter
def parse_arguments():
"""Argument Parser, providing available scripts"""
parser = argparse.Argum... | #!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
"""Module to bundle plotting scripts
`activate-global-python-argcomplete` must be run to enable auto completion """
import argparse
import argcomplete
import plotter
def parse_arguments():
"""Argument Parser, providing available scripts"""
parser = argparse.Argum... | mit | Python |
4bf81b58b47937d04b8a3975a01cfbd110757c97 | Annotate zerver/views/webhooks/zendesk.py. | dawran6/zulip,reyha/zulip,showell/zulip,tommyip/zulip,sonali0901/zulip,jrowan/zulip,zacps/zulip,souravbadami/zulip,verma-varsha/zulip,paxapy/zulip,umkay/zulip,jackrzhang/zulip,cosmicAsymmetry/zulip,dattatreya303/zulip,aakash-cr7/zulip,SmartPeople/zulip,rht/zulip,Diptanshu8/zulip,JPJPJPOPOP/zulip,arpith/zulip,j831/zulip... | zerver/views/webhooks/zendesk.py | zerver/views/webhooks/zendesk.py | # Webhooks for external integrations.
from __future__ import absolute_import
from zerver.models import get_client, UserProfile
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success
from zerver.decorator import authenticated_rest_api_view, REQ, has_request_variables
from django.h... | # Webhooks for external integrations.
from __future__ import absolute_import
from zerver.models import get_client
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success
from zerver.decorator import authenticated_rest_api_view, REQ, has_request_variables
def truncate(string, leng... | apache-2.0 | Python |
e9467251acfdbceb26c158636d3befe4428ed88b | Update dates passed in python3 | unt-libraries/coda,unt-libraries/coda,unt-libraries/coda,unt-libraries/coda | coda/coda_replication/factories.py | coda/coda_replication/factories.py | """
Coda Replication Model factories for test fixtures.
"""
from datetime import datetime
import factory
from factory import fuzzy
from . import models
class QueueEntryFactory(factory.django.DjangoModelFactory):
ark = factory.Sequence(lambda n: 'ark:/00001/id{0}'.format(n))
bytes = fuzzy.FuzzyInteger(100000... | """
Coda Replication Model factories for test fixtures.
"""
from datetime import datetime
import factory
from factory import fuzzy
from . import models
class QueueEntryFactory(factory.django.DjangoModelFactory):
ark = factory.Sequence(lambda n: 'ark:/00001/id{0}'.format(n))
bytes = fuzzy.FuzzyInteger(100000... | bsd-3-clause | Python |
b72bea3f6970a095864ec564008f5542dc88eeca | Test symmetry of equality, even with vector-likes | ppb/ppb-vector,ppb/ppb-vector | tests/test_vector2_equality.py | tests/test_vector2_equality.py | from hypothesis import assume, given
from ppb_vector import Vector2
from utils import vectors, vector_likes
@given(x=vectors())
def test_equal_self(x: Vector2):
assert x == x
@given(x=vectors(), y=vectors())
def test_equal_symmetric(x: Vector2, y):
assert (x == y) == (y == x)
for y_like in vector_likes(y):
... | from hypothesis import assume, given
from ppb_vector import Vector2
from utils import vectors
@given(x=vectors())
def test_equal_self(x: Vector2):
assert x == x
@given(x=vectors())
def test_non_zero_equal(x: Vector2):
assume(x != (0, 0))
assert x != 1.1 * x
assert x != -x
@given(x=vectors(), y=vectors())
de... | artistic-2.0 | Python |
b5fe71191bc7c39996d526132720a22c3967b1cf | Fix post schema for latest marshmallow release | josuemontano/pyramid-angularjs-starter,josuemontano/pyramid-angularjs-starter,josuemontano/pyramid-angularjs-starter,josuemontano/API-platform,josuemontano/api-starter,josuemontano/API-platform,josuemontano/api-starter,josuemontano/api-starter,josuemontano/API-platform,josuemontano/API-platform | canopus/schema/core.py | canopus/schema/core.py | from marshmallow import Schema, fields, post_load
from ..models import Post
class PostSchema(Schema):
__model__ = Post
id = fields.Integer()
title = fields.String()
body = fields.String()
is_published = fields.Boolean()
class Meta:
ordered = True
@post_load
def make_object(... | from marshmallow import Schema, fields
from ..models.core import Post
class PostSchema(Schema):
id = fields.Integer()
title = fields.String()
body = fields.String()
is_published = fields.Boolean()
def make_object(self, data):
return Post(**data)
| mit | Python |
ddde5dfff8a0046407db7c3331c7727134138847 | Change of address | romanschejbal/tempreader | reader.py | reader.py | import os
import time
import requests
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
temp_sensor = '/sys/bus/w1/devices/28-000005d8be69/w1_slave'
def temp_raw():
f = open(temp_sensor, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = temp_raw()
while li... | import os
import time
import requests
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
temp_sensor = '/sys/bus/w1/devices/28-000005d8be69/w1_slave'
def temp_raw():
f = open(temp_sensor, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = temp_raw()
while li... | mit | Python |
69ad70e692a21ac05574f5e61b78ff69da1a9cf1 | add serializer for your finances | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | cla_backend/apps/legalaid/serializers.py | cla_backend/apps/legalaid/serializers.py | from rest_framework import serializers
from core.serializers import UUIDSerializer
from .models import Category, EligibilityCheck, Property, Finance, \
PersonalDetails, Case
class CategorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Category
fields = ('id', 'name',... | from rest_framework import serializers
from core.serializers import UUIDSerializer
from .models import Category, EligibilityCheck, Property, Finance, \
PersonalDetails, Case
class CategorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Category
fields = ('id', 'name',... | mit | Python |
7c2c4afde6abb9e00b6c09e7897cd0438fc3a236 | Remove key 'active' since is deprecated and is an alias for 'auto_install' | scigghia/l10n-italy,hurrinico/l10n-italy,abstract-open-solutions/l10n-italy | l10n_it_ddt/__openerp__.py | l10n_it_ddt/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Abstract (http://www.abstract.it)
# @author Davide Corio <davide.corio@abstract.it>
# Copyright (C) 2014 Agile Business Group (http://www.agilebg.com)
#
# This program is free softwa... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Abstract (http://www.abstract.it)
# @author Davide Corio <davide.corio@abstract.it>
# Copyright (C) 2014 Agile Business Group (http://www.agilebg.com)
#
# This program is free softwa... | agpl-3.0 | Python |
1de568877a63d07d27c624db57d1ebfd7cb45a6f | Add more tests in descriptors/tests/test_params.py | tkf/compapp | compapp/descriptors/tests/test_params.py | compapp/descriptors/tests/test_params.py | import pytest
from ...core import Parametric
from .. import Dict, List, Or, Link
def test_dict_with_default():
class MyApp(Parametric):
x = Dict(default=dict(y=dict(z=1)))
assert MyApp.paramnames() == ['x']
x0 = MyApp.defaultparams()['x']
x1 = MyApp().params()['x']
assert x0 is not x1
... | from ...core import Parametric
from .. import Dict, List
def test_dict_wo_default():
class MyApp(Parametric):
x = Dict()
assert MyApp.paramnames() == ['x']
def test_list_wo_default():
class MyApp(Parametric):
x = List()
assert MyApp.paramnames() == ['x']
| bsd-2-clause | Python |
a6176d89e1daa3b986b2ad8b00c070c84398bfd6 | Rewrite this so it's something other people might want to use. | gsnedders/presto-testo-converters | convert_xpath.py | convert_xpath.py | import argparse
import os
import json
import sys
from lxml import etree
tests = {}
def process_file(name, out_dir):
tree = etree.parse(name)
xpath = tree.xpath("//xsl:when/@test",
namespaces={"xsl": "http://www.w3.org/1999/XSL/Transform"})
test_xml = tree.xpath("/xsl:stylesheet/xsl... | import os
import json
import sys
from lxml import etree
tests = {}
def process_file(name):
tree = etree.parse(name)
xpath = tree.xpath("//xsl:when/@test",
namespaces={"xsl": "http://www.w3.org/1999/XSL/Transform"})
test_xml = tree.xpath("/xsl:stylesheet/xsl:template/xsl:if[@test='f... | bsd-2-clause | Python |
6e422c98bf9c7dab4ad60c038c54ab01fcbb6dfe | Change theme to pelican-foundation | kfr2/kfr2.github.com,kfr2/kfr2.github.com | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
SITENAME = u'Kevin Richardson'
AUTHOR = u'Kevin Richardson'
TAGLINE = u'explorer & tinkerer'
SITEURL = 'http://localhost:8000'
FEED_DOMAIN = SITEURL
FEED_ATOM = 'feeds/all.atom.xml'
FEED_RSS = 'feeds/all.rss'
TIMEZONE = 'America/... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
SITENAME = u'Kevin Richardson'
AUTHOR = u'Kevin Richardson'
TAGLINE = u'explorer & tinkerer'
SITEURL = 'http://localhost:8000'
FEED_DOMAIN = SITEURL
FEED_ATOM = 'feeds/all.atom.xml'
FEED_RSS = 'feeds/all.rss'
TIMEZONE = 'America/... | mit | Python |
ee43983b8c7a345be8553cdd92871ae82d72f751 | support raw commands in config | jtperreault/tenyks,kyleterry/tenyks,jtperreault/tenyks,kyleterry/tenyks | tenyks/commandmapping.py | tenyks/commandmapping.py | class CommandNotFound(KeyError):
pass
class Command(object):
template = None
def __init__(self, command_string):
if command_string.startswith('/'):
command_string = command_string.lstrip('/')
self.command_string = command_string
self.parts = command_string.split()
... | class CommandNotFound(KeyError):
pass
class Command(object):
template = None
def __init__(self, command_string):
if command_string.startswith('/'):
command_string = command_string.lstrip('/')
self.command_string = command_string
self.parts = command_string.split()
... | mit | Python |
b3028843fc9f799d3fe1f52fbd64bb843dcd6f75 | Use photologue as default url | TuinfeesT/PicAxe | picaxe/urls.py | picaxe/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.sites.models import Site
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'picaxe.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
... | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.sites.models import Site
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'picaxe.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
... | mit | Python |
2ff24a21eee1bfb01873362dbf1172f2ca305327 | Update task_4_11.py | Mariaanisimova/pythonintask | BITs/2014/Kozlov_A_D/task_4_11.py | BITs/2014/Kozlov_A_D/task_4_11.py | #Задача 4. Вариант 11.
#Напишите программу, которая выводит имя, под которым скрывается Йоханнес Бруфельдт. Дополнительно необходимо вывести область интересов указанной личности, место рождения, годы рождения и смерти (если человек умер), вычислить возраст на данный момент (или момент смерти). Для хранения всех необхо... | #Задача 4. Вариант 11.
#Напишите программу, которая выводит имя, под которым скрывается Йоханнес Бруфельдт. Дополнительно необходимо вывести область интересов указанной личности, место рождения, годы рождения и смерти (если человек умер), вычислить возраст на данный момент (или момент смерти). Для хранения всех необхо... | apache-2.0 | Python |
b9d388cad54ed53d2ddb6741c725c4c453719a56 | Fix @r_hmmm a little. | nsiregar/reddit2telegram,Fillll/reddit2telegram,nsiregar/reddit2telegram,Fillll/reddit2telegram | channels/r_hmmm/app.py | channels/r_hmmm/app.py | # encoding:utf-8
from utils import get_url
subreddit = 'hmmm'
t_channel = '@r_hmmm'
NSFW_EMOJI = u'\U0001F51E'
def send_post(submission, r2t):
what, url, ext = get_url(submission)
title = submission.title
link = submission.shortlink
text = '{}\n{}'.format(title, link)
if what not in ('img'):... | #encoding:utf-8
from utils import get_url, download_file
subreddit = ‘hmmm’
t_channel = ‘@r_hmmm’
NSFW_EMOJI = u'\U0001F51E'
def send_post(submission, r2t):
what, url, ext = get_url(submission)
title = submission.title
link = submission.shortlink
text = '{}\n{}'.format(title, link)
if what not... | mit | Python |
942dc9ef00f4138d382b33b3835114df44a85af7 | Refactor codes, correct space complexity & revise comments | bowen0701/algorithms_data_structures | lc0763_partition_labels.py | lc0763_partition_labels.py | """Leetcode 763. Partition Labels
Medium
URL: https://leetcode.com/problems/partition-labels/submissions/
A string S of lowercase letters is given. We want to partition this string into
as many parts as possible so that each letter appears in at most one part,
and return a list of integers representing the size of th... | """Leetcode 763. Partition Labels
Medium
URL: https://leetcode.com/problems/partition-labels/submissions/
A string S of lowercase letters is given. We want to partition this string into
as many parts as possible so that each letter appears in at most one part,
and return a list of integers representing the size of th... | bsd-2-clause | Python |
bbf6bb83dfabd467b12d180d4d95e7acae273d23 | update test | culqi/culqi-python | culqi_py/test.py | culqi_py/test.py | import unittest ,json, uuid
from culqi import Culqi
culqi = Culqi("pk_test_vzMuTHoueOMlgUPj","sk_test_UTCQSGcXW8bCyU59")
class TestStringMethods(unittest.TestCase):
culqi = Culqi("pk_test_vzMuTHoueOMlgUPj","sk_test_UTCQSGcXW8bCyU59")
def token(self):
token = json.loads(culqi.createToken(
... | import unittest ,json, uuid
from culqi import Culqi
culqi = Culqi("pk_test_vzMuTHoueOMlgUPj","sk_test_UTCQSGcXW8bCyU59")
class TestStringMethods(unittest.TestCase):
culqi = Culqi("pk_test_vzMuTHoueOMlgUPj","sk_test_UTCQSGcXW8bCyU59")
def token(self):
token = json.loads(culqi.createToken(
... | mit | Python |
bd8657c4a49b1d8ced4d7e4c62519f6feb51c91a | fix pep8 | mupi/tecsaladeaula,mupi/timtec,virgilio/timtec,mupi/timtec,GustavoVS/timtec,hacklabr/timtec,mupi/tecsaladeaula,AllanNozomu/tecsaladeaula,AllanNozomu/tecsaladeaula,AllanNozomu/tecsaladeaula,GustavoVS/timtec,mupi/timtec,virgilio/timtec,virgilio/timtec,virgilio/timtec,GustavoVS/timtec,GustavoVS/timtec,hacklabr/timtec,mupi... | core/management/commands/find_by_city.py | core/management/commands/find_by_city.py | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
User = get_user_model()
class Command(BaseCommand):
args = ''
help = 'Remove all student related data'
def handle(self, *args, **options):
cities = []
for city in ... | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from core.models import StudentProgress, ProfessorMessage, CourseStudent, CourseProfessor
from forum.models import Question, QuestionVote, Answer, AnswerVote
import activities
User = get_user_mod... | agpl-3.0 | Python |
acd85500b15eeaa0fd7a44a4124dd80ce51a0093 | Allow slugs to be passed to the update_repos command to specify one project. | hach-que/readthedocs.org,wanghaven/readthedocs.org,attakei/readthedocs-oauth,sils1297/readthedocs.org,SteveViss/readthedocs.org,raven47git/readthedocs.org,royalwang/readthedocs.org,techtonik/readthedocs.org,clarkperkins/readthedocs.org,VishvajitP/readthedocs.org,attakei/readthedocs-oauth,davidfischer/readthedocs.org,su... | core/management/commands/update_repos.py | core/management/commands/update_repos.py | from django.core.management.base import BaseCommand
from projects import tasks
from projects.models import Project
class Command(BaseCommand):
def handle(self, *args, **kwargs):
if not len(args):
tasks.update_docs_pull()
else:
for slug in args:
p = Project.o... | from django.core.management.base import BaseCommand
from projects import tasks
class Command(BaseCommand):
def handle(self, *args, **kwargs):
tasks.update_docs_pull()
| mit | Python |
5cc5d8ad12c9ad88341de415aa54484e22643c93 | Change the custom_commands to context property | csm-aut/csm,smjurcak/csm,csm-aut/csm,kstaniek/csm,smjurcak/csm,csm-aut/csm,kstaniek/csm,csm-aut/csm,kstaniek/csm,smjurcak/csm,kstaniek/csm,smjurcak/csm | csmserver/horizon/plugins/cmd_capture.py | csmserver/horizon/plugins/cmd_capture.py | # =============================================================================
# cmd_capture
#
# Copyright (c) 2016, Cisco Systems
# All rights reserved.
#
# # Author: Klaudiusz Staniek
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following con... | # =============================================================================
# cmd_capture
#
# Copyright (c) 2016, Cisco Systems
# All rights reserved.
#
# # Author: Klaudiusz Staniek
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following con... | apache-2.0 | Python |
9756d271400608e8f7b8bfa80957e726f54c4b4b | Remove comments | fnatalucci/NSAEQGRPFortinetVerify | check_fortinet_vuln.py | check_fortinet_vuln.py | #!/usr/bin/env python2.7
import sys, getopt, os.path, os, requests
#verifico se esiste il file EGBL.config
def usage():
print ""
print "######## Fortinet NSA checking tool ############"
print "# Author by Fabio Natalucci #############"
print "# Twitter @fabionatalucci #############"
print "# Webs... | #!/usr/bin/env python2.7
import sys, getopt, os.path, os, requests
#verifico se esiste il file EGBL.config
def usage():
print ""
print "######## Fortinet NSA checking tool ############"
print "######## Author by Fabio Natalucci #############"
print "# with collaboration of NSA and Equation Group #"
print "# Th... | mit | Python |
8bd1387084763c8dbf862bf2a3f2f082a046a889 | Work around pip issue on debian | thusoy/grunt-pylint,thusoy/grunt-pylint,thusoy/grunt-pylint | postinstall.py | postinstall.py | #!/usr/bin/env python
import subprocess
import sys
# Versions here must match what is bundled with the package (see package.json)
packages = [
'astroid-1.6.6.tar.gz',
'backports.functools_lru_cache-1.5.tar.gz',
'configparser-3.7.4.tar.gz',
'isort-4.3.17.tar.gz',
'lazy-object-proxy-1.3.1.tar.gz',
... | #!/usr/bin/env python
import subprocess
import sys
# Versions here must match what is bundled with the package (see package.json)
packages = [
'astroid-1.6.6.tar.gz',
'backports.functools_lru_cache-1.5.tar.gz',
'configparser-3.7.4.tar.gz',
'isort-4.3.17.tar.gz',
'lazy-object-proxy-1.3.1.tar.gz',
... | mit | Python |
346a56fdf3a60c545408ae1f23ae678d9e933f06 | add args parsing | Storj/downstream-node,Storj/downstream-node | runapp.py | runapp.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
# Runs the development server of the downstream_node app.
# Not for production use.
from downstream_node.startup import app, db
def initdb(sys=None):
db.create_all()
def eval_args(args):
if args.initdb:
initdb()
else:
app.r... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Runs the development server of the downstream_node app.
# Not for production use.
from downstream_node.startup import app
def main():
app.run(debug=True)
if __name__ == '__main__':
main()
| mit | Python |
bdadfdcb85e3b3392f3c01ed0609034df63c4d99 | Add test for zeroth element None in PeriodicTable | langner/cclib,ATenderholt/cclib,cclib/cclib,berquist/cclib,langner/cclib,cclib/cclib,ATenderholt/cclib,berquist/cclib,cclib/cclib,berquist/cclib,langner/cclib | test/parser/testutils.py | test/parser/testutils.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2018, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Unit tests for parser utils module."""
import unittest
import cclib
class convertorTest(unittest.TestCase):
de... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2018, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Unit tests for parser utils module."""
import unittest
import cclib
class convertorTest(unittest.TestCase):
de... | bsd-3-clause | Python |
a57b175ef686a7854f9dfbce1281c1e9f4107278 | update new file | zpiman/golemScripts | script.py | script.py | from subprocess import call
import urllib
import xml.etree.ElementTree as ET
import time, math
TELNET = "telnet 192.168.2.241 10001"
time_delay = 0.3
time_step = 0.001
#res = Device("192.168.2.243:10001")
#print res.get_outputs_state("192.168.2.243:10001")
Ion = "echo '*B1OS1H'|" + TELNET
Ioff = "echo '*B1OS1L'|" + ... | from subprocess import call
import urllib
import xml.etree.ElementTree as ET
import time, math
TELNET = "telnet 192.168.2.243 10001"
time_delay = 0.3
time_step = 0.001
#res = Device("192.168.2.243:10001")
#print res.get_outputs_state("192.168.2.243:10001")
Ion = "echo '*B1OS1H'|" + TELNET
Ioff = "echo '*B1OS1L'|" + ... | mit | Python |
f5480b47b67c667ea02fc8798a33ea7905ca31f4 | use the constant | dmd/clack | scroll.py | scroll.py | #!/usr/bin/env python2.7
import os, sys
from glob import glob
import requests
import numpy
from clack import HEIGHT, WIDTH, CLACK_URL, blank_screen, read_font, clack_post
import time
HEIGHT, WIDTH = WIDTH, HEIGHT # we're going the other way
def banner(message, fontname='banner'):
font = read_font(fontname)
... | #!/usr/bin/env python2.7
import os, sys
from glob import glob
import requests
import numpy
from clack import HEIGHT, WIDTH, CLACK_URL, blank_screen, read_font, clack_post
import time
HEIGHT, WIDTH = WIDTH, HEIGHT # we're going the other way
def banner(message, fontname='banner'):
font = read_font(fontname)
... | apache-2.0 | Python |
8ee293385b9ca8971f07edd063a85d89642877c8 | Fix middleware settings for django > 1.10 | byashimov/django-controlcenter,byashimov/django-controlcenter,byashimov/django-controlcenter | test_project/settings.py | test_project/settings.py | SECRET_KEY = 'test'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'controlcenter',
)
MIDDLEWARE_CLASSES = (
'django.contr... | SECRET_KEY = 'test'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'controlcenter',
)
MIDDLEWARE_CLASSES = (
'django.contr... | bsd-3-clause | Python |
ebe87da332e58f4ea8b46ecf3f8fd75494091e48 | Clean tests | Phylliade/ikpy | tests/ikpy/test_chain.py | tests/ikpy/test_chain.py | import unittest
import numpy as np
import sys
from ikpy import chain
from ikpy import plot_utils
import params
plot = params.interactive
class TestChain(unittest.TestCase):
def setUp(self):
if plot:
self.ax = plot_utils.init_3d_figure()
self.chain1 = chain.Chain.from_urdf_file(params.... | import unittest
import numpy as np
import sys
from ikpy import chain
from ikpy import plot_utils
import params
plot = params.interactive
class TestChain(unittest.TestCase):
def test_chain(self):
a = chain.Chain.from_urdf_file(params.resources_path + "/poppy_torso.URDF", base_elements=["base", "abs_z", "s... | apache-2.0 | Python |
ef3d86e368b2dc7a8360f6e28fae3fc44141906c | fix sympy.zeros() call for sympy 0.7.6 | BubuLK/sfepy,rc/sfepy,RexFuzzle/sfepy,lokik/sfepy,sfepy/sfepy,rc/sfepy,vlukes/sfepy,rc/sfepy,lokik/sfepy,RexFuzzle/sfepy,sfepy/sfepy,RexFuzzle/sfepy,vlukes/sfepy,RexFuzzle/sfepy,BubuLK/sfepy,lokik/sfepy,vlukes/sfepy,lokik/sfepy,BubuLK/sfepy,sfepy/sfepy | tests/sympy_operators.py | tests/sympy_operators.py | import sympy as sp
from sympy import sin, cos, sympify, lambdify, Symbol
from numpy import arange, zeros
dim = 3
def set_dim(dim):
globals()['dim'] = dim
def default_space_variables(variables):
from sympy.abc import x, y, z
if variables is None:
variables = [x, y, z][:dim]
return variables
... | import sympy as sp
from sympy import sin, cos, sympify, lambdify, Symbol
from numpy import arange, zeros
dim = 3
def set_dim(dim):
globals()['dim'] = dim
def default_space_variables(variables):
from sympy.abc import x, y, z
if variables is None:
variables = [x, y, z][:dim]
return variables
... | bsd-3-clause | Python |
1d853fbaa70cda9ed5caabec7f78393c7d4b9fb0 | Improve usefulness of pep8/jsonschema test descriptions | caleb531/youversion-suggest,caleb531/youversion-suggest | tests/test_compliance.py | tests/test_compliance.py | #!/usr/bin/env python
import nose.tools as nose
import glob
import os.path
import json
import jsonschema
import pep8
def test_pep8():
file_paths = glob.iglob('*/*.py')
for file_path in file_paths:
style_guide = pep8.StyleGuide(quiet=True)
total_errors = style_guide.input_file(file_path)
... | #!/usr/bin/env python
import nose.tools as nose
import glob
import json
import jsonschema
import pep8
def test_pep8():
'''all Python files should comply with PEP 8'''
files = glob.iglob('*/*.py')
for file in files:
style_guide = pep8.StyleGuide(quiet=True)
total_errors = style_guide.input... | mit | Python |
fb3d80ebac6de449908737e254b273d9eafff349 | Add more Python tests | gasman/wagtaildraftail,springload/wagtaildraftail,springload/wagtaildraftail,gasman/wagtaildraftail,gasman/wagtaildraftail,springload/wagtaildraftail,gasman/wagtaildraftail,springload/wagtaildraftail | tests/test_decorators.py | tests/test_decorators.py | from __future__ import absolute_import, unicode_literals
import unittest
from draftjs_exporter.constants import BLOCK_TYPES
from draftjs_exporter.dom import DOM
from wagtaildraftail.decorators import BR, HR, Icon
class TestIcon(unittest.TestCase):
def test_render(self):
self.assertEqual(DOM.render(DOM.c... | from __future__ import absolute_import, unicode_literals
import unittest
from draftjs_exporter.dom import DOM
from wagtaildraftail.decorators import HR, Icon
class TestIcon(unittest.TestCase):
def test_render(self):
self.assertEqual(DOM.render(DOM.create_element(Icon, {'name': 'rocket'})), '<svg class="... | mit | Python |
c28fabb4a95b66a3a15e08f3af52f35a2190470d | Check the bitcoin address | sbuss/bitmerchant,mflaxman/bitmerchant | tests/test_key_vector.py | tests/test_key_vector.py | import json
from unittest import TestCase
from bitmerchant.network import BitcoinMainNet
from bitmerchant.wallet.keys import PrivateKey
from bitmerchant.wallet.keys import PublicKey
class TestKeys(TestCase):
def test_keys(self):
with open("tests/keys_test_vector.json", 'r') as f:
vectors = j... | import json
from unittest import TestCase
from bitmerchant.network import BitcoinMainNet
from bitmerchant.wallet.keys import PrivateKey
from bitmerchant.wallet.keys import PublicKey
class TestKeys(TestCase):
def test_keys(self):
with open("tests/keys_test_vector.json", 'r') as f:
vectors = j... | mit | Python |
4d2d6a90055cc636d788d03d1033e8feeb0191e0 | test for lm.__contains__ with test.arpa | sfischer13/python-arpa,sfischer13/python-arpa | tests/test_model_base.py | tests/test_model_base.py | import pytest
import arpa
from arpa.models.base import ARPAModel
from arpa.models.simple import ARPAModelSimple
from test_arpa import TEST_ARPA
def test_manual_log_p_unk():
lm = arpa.loadf(TEST_ARPA)[0]
assert lm.log_p("UnladenSwallow") == -1.995635
def test_manual_p():
lm = arpa.loadf(TEST_ARPA)[0]
... | import pytest
import arpa
from arpa.models.base import ARPAModel
from arpa.models.simple import ARPAModelSimple
from test_arpa import TEST_ARPA
def test_manual_log_p_unk():
lm = arpa.loadf(TEST_ARPA)[0]
assert lm.log_p("UnladenSwallow") == -1.995635
def test_manual_p():
lm = arpa.loadf(TEST_ARPA)[0]
... | mit | Python |
063492dca29fec11e52f3d576b49bb4dbec83efa | Use new functions | RazerM/pg_grant,RazerM/pg_grant | tests/test_round_trip.py | tests/test_round_trip.py | from functools import partial
import pytest
from plumbum.cmd import pg_dump
from pg_grant import parse_acl_item, PgObjectType
from pg_grant.query import (
get_all_function_acls, get_all_sequence_acls, get_all_table_acls,
get_all_type_acls)
pytestmark = pytest.mark.nocontainer
def _priv_acls(conn, acls, ty... | from functools import partial
import pytest
from plumbum.cmd import pg_dump
from pg_grant import parse_acl_item, PgObjectType
from pg_grant.query import (
get_all_function_acls, get_all_sequence_acls, get_all_table_acls,
get_all_type_acls)
from pg_grant.sql import Grant, Revoke
pytestmark = pytest.mark.noco... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.