code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# David Art <david.madbox@gmail.com>
# Program Arcade Games With Python And Pygame - Build a Platformer
# http://programarcadegames.com
import pygame
import random
WIDTH = 640
HEIGHT = 480
class Platform (pygame.sprite.Sprite):
def __init__(self, width, he... | adcomp/super-fruit-pie | tuto/06_collect.py | Python | mit | 7,778 |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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... | rwl/PyCIM | CIM14/IEC61968/PaymentMetering/LineDetail.py | Python | mit | 2,482 |
# -*- coding: utf-8 -*-
"""nec_pd_sdk.py - High level functions for communicating via LAN or RS232 with NEC large-screen displays.
"""
#
#
# Copyright (C) 2016-18 NEC Display Solutions, Ltd
# written by Will Hollingworth <whollingworth at necdisplay.com>
# See LICENSE.rst for details.
# TODO == Helper Functions ==
# ... | NECDisplaySolutions/necpdsdk | nec_pd_sdk/nec_pd_sdk.py | Python | mit | 193,013 |
# -*- coding: utf-8 -*-
#
# 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
... | magnusgasslander/sqlalchemy-bigquery | sqlalchemy_bigquery/gcp/authorize/authorize.py | Python | mit | 3,503 |
import operator
from collections import Counter
from functools import reduce
from typing import Dict, Tuple
def add_dicts(*args: Tuple[Dict, ...]) -> Dict:
"""
Adds two or more dicts together. Common keys will have their values added.
For example::
>>> t1 = {'a':1, 'b':2}
>>> t2 = {'b':... | joke2k/faker | faker/utils/datasets.py | Python | mit | 535 |
import unittest
import flavio
from math import sqrt, pi
from flavio.physics.zdecays.gammazsm import Zobs, pb
from flavio.physics.zdecays.gammaz import GammaZ_NP
from flavio.physics.zdecays import smeftew
par = flavio.default_parameters.get_central_all()
class TestGammaZ(unittest.TestCase):
def test_obs_sm(self)... | flav-io/flavio | flavio/physics/zdecays/test_zdecays.py | Python | mit | 6,570 |
from __future__ import division, print_function
import autograd.numpy as np
import autograd.numpy.random as npr
from autograd.scipy.misc import logsumexp
from autograd.convenience_wrappers import value_and_grad as vgrad
from functools import partial
from os.path import join, dirname
import string
import sys
def EM(in... | barak/autograd | examples/hmm_em.py | Python | mit | 2,862 |
# -*- coding: utf-8 -*-
import numpy as np
def signal_to_class(data, n=2, normalize=True):
"""
Converts a list of signals to a n-dimensional list of classes [buy, .., sell].
Arguments
n (int): Number of classes.
normalize (bool): It normalizes to unity. False - the signal changes only the... | terentjew-alexey/market-analysis-system | mas_tools/classes.py | Python | mit | 5,267 |
#!/usr/bin/python
""" dicom_dao
Data Access Objects for persisting PyDicom DataSet objects.
Currently we support couchdb through the DicomCouch class.
Limitations:
- Private tags are discarded
TODO:
- Unit tests with multiple objects open at a time
- Unit tests with rtstruct objects
- Support for mongodb (mong... | mshunshin/SegNetCMR | pydicom/contrib/dicom_dao.py | Python | mit | 14,663 |
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from booking.models import *
class UserInline(admin.TabularInline):
model = User
class BookingAdmin(admin.ModelAdmin):
list_display = ('booker', 'book_type', 'status', ... | joeyjy/ayi-django | ms/booking/admin.py | Python | mit | 2,741 |
# Copyright (C) 2011 Philter Phactory Ltd.
#
# 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, publi... | philterphactory/prosthetic-runner | base_prosthetic.py | Python | mit | 3,132 |
import time
start = time.time()
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
f = fib()
for i in range(10000):
d = next(f)
if len(str(d)) == 1000:
print(i)
break
print("t = {:.5f} seg".format(time.time() - start))
# 4782
# t = 0.03068 seg
10... | floppp/programming_challenges | project_euler/001-050/25.py | Python | mit | 344 |
# -*- coding: utf-8 -*-
"""THIS DIRECTORY IS TO HOLD BOT SCRIPTS THAT NO LONGER ARE MAINTAINED."""
| PersianWikipedia/pywikibot-core | scripts/archive/__init__.py | Python | mit | 99 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from webargs.flaskparser import (parser, abort)
@parser.error_handler
def handler_request_parsing_error(e):
error({}, 400, errors=e.messages)
def error(params=None, code=422, message='不合法的请求', errors=None):
params['message'] = message
params['errcode'] = c... | alexcc4/flask_restful_backend | app/libs/error.py | Python | mit | 412 |
# -*- coding: utf-8 -*-
import os
import yaml
from six.moves import input
class Configure:
"""
msgiver configuration class
"""
CONF_FILE_PATH = os.path.join(os.environ.get("HOME"), ".msgiver.yml")
def __init__(self):
self.__conf = None
if os.path.exists(self.CONF_FILE_PATH):... | kitaro-tn/msgiver | msgiver/configure.py | Python | mit | 1,918 |
"""
WSGI config for weather_forecast project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJA... | elangaar/django-weather-forecast | weather_forecast/wsgi.py | Python | mit | 409 |
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.template.defaultfilters import slugify
from main.models import TeamMember
from django.db import models
import re
class Folder(models.Model):
name = models.CharField(max_length=20)
parent = models.ForeignKey('self',... | rit-sailing/website | files/models.py | Python | mit | 1,637 |
"""Common base class for Redis-based distributed worker systems.
This software is released under an MIT/X11 open source license.
Copyright 2012-2014 Diffeo, Inc.
"""
from __future__ import absolute_import
import logging
import socket
import redis
from rejester.exceptions import ProgrammerError
logger = logging.g... | diffeo/rejester | rejester/_redis.py | Python | mit | 2,666 |
# -*- coding: utf-8 -*-
import datetime
from babel.core import Locale
from sqlalchemy import func
from pyramid.view import view_config
from intranet3.utils.views import BaseView
from intranet3.models import User, PresenceEntry, Late, Absence, DBSession
from intranet3 import helpers as h
from intranet3.utils import ex... | stxnext/intranet-open | src/intranet3/intranet3/views/presence.py | Python | mit | 3,777 |
"""py.test plugin configuration."""
def pytest_addoption(parser):
"""Add options for filtering which file tests run.
This has to be done in the project root; py.test doesn't (and can't)
recursively look for conftest.py files until after it's parsed the command
line.
"""
parser.addoption('--inc... | ojengwa/pyScss | conftest.py | Python | mit | 684 |
from flask import abort, session
from noter import db
from models import Entry, User
from markdown2 import Markdown
def EntryGetById(entryid):
"""Retrieve entry by id"""
entry = Entry.query.filter_by(id=entryid).first()
return entry
def EntryGetByUserId(userid):
"""Retrieve entry by user id"""
ent... | miged/noter | noter/manager.py | Python | mit | 1,378 |
""" Views for the base application """
from django.shortcuts import render
from django.views.generic import DetailView
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
from django.http import Http404
from django.utils.translation import ugettext as... | michaelbrooks/uw-message-coding | message_coding/apps/base/views.py | Python | mit | 3,592 |
# It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
# 9 = 7 + 2x1^2
# 15 = 7 + 2x2^2
# 21 = 3 + 2x3^2
# 25 = 7 + 2x3^2
# 27 = 19 + 2x2^2
# 33 = 31 + 2x1^2
# It turns out that the conjecture was false.
# What is the smallest odd c... | ledbutter/ProjectEulerPython | Problem46.py | Python | mit | 1,921 |
import copy
import unittest
from pyrake.utils.datatypes import CaselessDict
__doctests__ = ['pyrake.utils.datatypes']
class CaselessDictTest(unittest.TestCase):
def test_init(self):
seq = {'red': 1, 'black': 3}
d = CaselessDict(seq)
self.assertEqual(d['red'], 1)
self.assertEqual(... | elkingtowa/pyrake | tests/test_utils_datatypes.py | Python | mit | 3,592 |
#!/usr/bin/env python
import os
import sys
import dotenv
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")
dotenv.read_dotenv('project/.env')
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| chiehtu/kissaten | manage.py | Python | mit | 311 |
"""
mixpandas.py
A library to request data from Mixpanel's Raw Data Export API
"""
import datetime
import hashlib
import urllib.request, urllib.parse, urllib.error
import time
try:
import json
except ImportError:
import simplejson as json
import pandas as pd
VERSION = '2.0' # Mixpanel API version
date_form... | jwass/mixpandas | mixpandas.py | Python | mit | 7,355 |
# -*- coding: utf-8 -*-
import re
import ipaddress
from unidecode import unidecode
class NetTest(object):
wildcards = [ipaddress.IPv4Interface(
unicode('0.0.0.0/{}'.format(x))).network.hostmask.exploded for x in range(0, 33)]
netmasks = [ipaddress.IPv4Interface(
unicode('255.255.255.255/{}'.... | heyglen/netobj | nettool/nettest.py | Python | mit | 14,175 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
usage: zerows [-h]
"""
__author__ = "Sebastian Łach"
__copyright__ = "Copyright 2015, Sebastian Łach"
__credits__ = ["Sebastian Łach", ]
__license__ = "MIT"
__version__ = "1.0"
__maintainer__ = "Sebastian Łach"
__email__ = "root@slach.eu"
from json import loads
fro... | sebastianlach/zerows | zerows/__init__.py | Python | mit | 2,638 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import random
import pytest
from marshmallow import Schema, fields, utils, MarshalResult, UnmarshalResult
from marshmallow.exceptions import MarshallingError
from marshmallow.compat import unicode, binary_type
from tests.base import * # noqa
random.seed(1... | jmcarp/marshmallow | tests/test_serializer.py | Python | mit | 35,818 |
#!/usr/bin/env python
# -*- coding: utf-8
import sys
import os
import os.path
import wx
from git import Repository
from MainWindow import *
def main():
# Parse arguments
repodir = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
# Show main window
try:
repo = Repository(repodir)
except ... | lez/stupidgit | stupidgit_gui/run.py | Python | mit | 492 |
def bold(s, isatty):
if isatty:
return "\x1B[1m" + s + "\x1B[0m"
return s
def italic(s, isatty):
if isatty:
return "\x1B[3m" + s + "\x1B[0m"
return s
| PolarPayne/scrycli | scrycli/utils.py | Python | mit | 184 |
from nltk import word_tokenize
class AnaphoraFinder:
def __init__(self):
self.f = ""
self.counter = 0
self.first_word = ""
self.b = False
#Path is inputted from AIPController
#Returns anaphora counter
def sendFile(self, path):
self.f = open(path)
... | benglard/Rhetorical-Analysis | AnaphoraFinder.py | Python | mit | 1,934 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-12-15 19:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('archive', '0001_initial'),
]
operations = [
migrations.AlterField(
... | WarwickAnimeSoc/aniMango | archive/migrations/0002_auto_20181215_1934.py | Python | mit | 1,365 |
#!/usr/bin/env python3
"""Project Euler - Problem 72 Module"""
from problem0069 import eulers_totient
# Smallest Distance if 7 & new_d have no common devisors
# 2: 1/2
# 3: 1/3 & 2/3
# 4: 1/4 (2/4) 3/4
# 5: 1/5 2/5 3/5 4/5
# 6: 1/6 (2/6) (3/6) (4/6) 5/6
# -> Nr of values for d == phi(d)
def problem72(limit):
"""... | rado0x54/project-euler | python/problem0072.py | Python | mit | 583 |
from django.apps import AppConfig
class FeaturesConfig(AppConfig):
name = 'features'
def ready(self):
import features.signals
| KDD-OpenSource/fexum | features/apps.py | Python | mit | 145 |
from modules.front_motor import FrontMotor
from modules.back_motor import BackMotor
from services.temperature_sensor import TemperatureSensor
modules = {}
def get_module(module_name, **data):
return modules[module_name](**data)
def register_module(module_name, cls):
modules[module_name] = cls
register_modul... | astagi/chickenfoot | chickenfoot/modules_register.py | Python | mit | 443 |
import django.dispatch
from django.contrib.sites.models import get_current_site
from django.core.mail import mail_managers
from django.core.urlresolvers import reverse
from django.template import loader, Context
from . import settings
form_submited = django.dispatch.Signal()
def notify_managers(sender, message, req... | satyrius/cmsplugin-feedback | cmsplugin_feedback/signals.py | Python | mit | 1,157 |
from django.contrib import admin
from dbservice.apps.utils import MEASUREMENT_UNIT_CHOICES
from . import models
admin.site.register(models.FixedValueMeterPort)
@admin.register(models.VirtualEnergyPort)
class VirtualPortEnergyAdmin(admin.ModelAdmin):
fields = ('name', 'consumption', 'current', 'voltage', 'power... | dbservice/dbservice | dbservice/apps/homes/admin.py | Python | mit | 1,248 |
from django.conf.urls import patterns, url
from .views import PlaylistList, PlaylistDetail, SongList, SongUpdate
urlpatterns = patterns('songs.views',
url(r'^playlists$', PlaylistList.as_view(), name='playlists_list'),
url(r'^playlists/(?P<playlist_pk>[0-9]+)/$', PlaylistDetail.as_view(),
name="playlist_detail")... | kburts/django-playlist | django_playlist/songs/urls.py | Python | mit | 465 |
from django.contrib.auth import logout
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import UserForm
def register(request):
... | swappsco/django-qa | test_project/core/views.py | Python | mit | 4,130 |
import pydpx_meta
# High level class DpxHeaderEx sample
#dpx = pydpx_meta.DpxHeaderEx("/root/V14_37_26_01_v001.0186.dpx")
dpx = pydpx_meta.DpxHeaderEx()
print(dpx.describe())
| plinecom/pydpx_meta | sample2_ex.py | Python | mit | 176 |
import utils
class Notifier(object):
def __init__(self, key='', type='slack'):
self.key = key
self.type = type
self.parameters = {
'icon' : ':space_invader:',
'username': 'Notifier Bot',
'channel' : 'general'
}
if self.key:
if... | tiaanwillemse/pythonNotifier | notifier.py | Python | mit | 2,262 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import random
from PyQt5.QtWidgets import QMainWindow, QFrame, QDesktopWidget, QApplication
from PyQt5.QtCore import Qt, QBasicTimer, pyqtSignal
from PyQt5.QtGui import QPainter, QColor
class Tetris(QMainWindow):
def __init__(self):
super().__init__()... | quchunguang/test | testpy3/pyqt5_tetris.py | Python | mit | 10,805 |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.absp... | ESG-USA/python-sample-project | setup.py | Python | mit | 4,015 |
# -*- coding: utf-8 -*-
"""Unit test package for qt-aider."""
| starofrainnight/rabird.pyside | tests/__init__.py | Python | mit | 63 |
from office365.entity import Entity
from office365.outlook.calendar.email_address import EmailAddress
class CalendarPermission(Entity):
"""
The permissions of a user with whom the calendar has been shared or delegated in an Outlook client.
Get, update, and delete of calendar permissions is supported on b... | vgrem/Office365-REST-Python-Client | office365/outlook/calendar/calendar_permission.py | Python | mit | 1,204 |
from nodetraq.tests import *
class TestPoolsController(TestController):
def test_index(self):
response = self.app.get(url(controller='pools', action='index'))
# Test response...
| seryl/Nodetraq | nodetraq/tests/functional/test_pools.py | Python | mit | 200 |
#!/usr/bin/env python
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
setup(name='moviepy',
version='0.2.1.6.9',
author='Zulko 2013',
description='Module for script-based video editing',
long_description=open('README.rst').read(),
license='LICENSE.txt',
... | ShaguptaS/moviepy | setup.py | Python | mit | 419 |
from unittest import TestCase
from plivo import plivoxml
from tests import PlivoXmlTestCase
class SayAsElementTest(TestCase, PlivoXmlTestCase):
def test_set_methods(self):
expected_response = '<Response><Speak><say-as format="application/ssml+xml" interpret-as="spell-out">' \
... | plivo/plivo-python | tests/xml/test_sayAsElement.py | Python | mit | 789 |
from authenticators.simple_authenticators import RandomAuthenticator, \
HeuristicAuthenticator, OracleAuthenticator, NeverSecondAuthenticator, \
AlwaysSecondAuthenticator
from simulator import parameters
from simulator.transaction_model import TransactionModel
from experiments import rewards
import numpy as np
... | lmzintgraf/MultiMAuS | experiments/run_multimaus.py | Python | mit | 2,970 |
# -*- coding: utf-8 -*-
def token(collection, token='token'):
return collection.find_and_modify({token: {'$exists': False}}, {'$set': {'token': True}})
def release(collection, token='token'):
return collection.update({token: True}, {'$set': {token: False}}, multi=True)
def garbage(collection, token='toke... | nextoa/comb | comb/mq/mongo.py | Python | mit | 480 |
from django.conf.urls.defaults import *
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = i18n_patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('cms.urls')),
)
if settings.DEBUG:
... | MagicSolutions/cmsplugin-carousel | example/example/urls.py | Python | mit | 582 |
from __future__ import absolute_import
from __future__ import unicode_literals
import pytest
from pre_commit_hooks.mixed_line_ending import main
@pytest.mark.parametrize(
('input_s', 'output'),
(
# mixed with majority of 'LF'
(b'foo\r\nbar\nbaz\n', b'foo\nbar\nbaz\n'),
# mixed with m... | Harwood/pre-commit-hooks | tests/mixed_line_ending_test.py | Python | mit | 3,733 |
from identifier import Result
MIDI_PATTERNS = [
'4D 54 68 64'
]
class MidiResolver:
def identify(self, stream):
return Result('MIDI')
def load(hound):
hound.add_matches(MIDI_PATTERNS, MidiResolver())
| Bindernews/TheHound | identifiers/midi_identifier.py | Python | mit | 211 |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module defines tools to generate and analyze phase diagrams.
"""
import re
import collections
import itertools
import math
import logging
from monty.json import MSONable, MontyDecoder
from functools ... | fraricci/pymatgen | pymatgen/analysis/phase_diagram.py | Python | mit | 84,602 |
"""
IndicoService Authentication Route
Creating and Maintaining Users
"""
from indico.utils.auth.auth_utils import auth, user_hash
from indico.utils.auth.facebook_utils import check_access_token
from indico.error import FacebookTokenError
from indico.utils import unpack, mongo_callback, type_check
from indico.routes.ha... | sihrc/tornado-boilerplate | indico/routes/auth.py | Python | mit | 1,532 |
from pysv.smtlib.synth import SynthesisConstr
from pysv.smtlib.synth import SynthesisConstrTestCases
from pysv.templates import *
from pysv.contract import *
from pysv import solvers
from pysv import smt_common
#
# Python ast package documentation: https://docs.python.org/2/library/ast.html
# Python _ast package doc... | iwob/pysv | pysv/smt_synthesis.py | Python | mit | 17,716 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-04-19 10:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0015_auto_20160408_1355'),
]
operations = [
migrations.AlterField(
... | hep7agon/city-feedback-hub | api/migrations/0016_service_code.py | Python | mit | 640 |
import dataclasses
from typing import Dict, Mapping, Optional, Tuple
import numpy as np
from stable_baselines3.common import vec_env
from imitation.data import types
class Buffer:
"""A FIFO ring buffer for NumPy arrays of a fixed shape and dtype.
Supports random sampling with replacement.
"""
capa... | humancompatibleai/imitation | src/imitation/data/buffer.py | Python | mit | 13,770 |
"""
Revision ID: 0212_remove_caseworking
Revises: 0211_email_branding_update
Create Date: 2018-07-31 18:00:20.457755
"""
from alembic import op
revision = '0212_remove_caseworking'
down_revision = '0211_email_branding_update'
PERMISSION_NAME = "caseworking"
def upgrade():
op.execute("delete from service_perm... | alphagov/notifications-api | migrations/versions/0212_remove_caseworking.py | Python | mit | 586 |
# Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""Basic message object for the email package object model."""
import re
import uu
import binascii
import warnings
from cStringIO import StringIO
# Intrapackage imports
from email import Utils
from email impor... | MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.4.3/Lib/email/Message.py | Python | mit | 31,201 |
"""
<Program>
dispatcher.py
<Started>
6 July 2009
<Author>
Justin Samuel
<Purpose>
XMLRPC handler for django.
Nothing in this file needs to be modified when adding/removing/changing
public xmlrpc methods. For that, see the views.py file in the same directory.
This xmlrpc dispatcher for django is modi... | sburnett/seattle | seattlegeni/website/xmlrpc/dispatcher.py | Python | mit | 2,429 |
import cherrypy
cherrypy.config.update({'server.socket_port': 9090})
cherrypy.config.update({'server.socket_host': '0.0.0.0'})
class Root(object):
@cherrypy.expose
def index(self):
return "Hello World! From Python"
if __name__ == '__main__':
cherrypy.quickstart(Root(), '/') | miketheprogrammer/dkxyz14 | hello-python/web.py | Python | mit | 296 |
from test_framework import generic_test
def get_height(cases: int, drops: int) -> int:
# TODO - you fill in here.
return 0
if __name__ == '__main__':
exit(
generic_test.generic_test_main('max_safe_height.py',
'max_safe_height.tsv', get_height))
| shobhitmishra/CodingProblems | epi_judge_python/max_safe_height.py | Python | mit | 308 |
import logging
from logging.config import dictConfig
def logger():
logging_config = dict(
version = 1,
formatters = {
'f': {'format':
'%(asctime)s %(levelname)-8s %(message)s'}
},
handlers = {
'h': {'class': 'logging.StreamHandler',
... | fruser/tagfind | tagfind/log_info.py | Python | mit | 633 |
from tkinter import *
from PIL import Image, ImageTk
from urllib.request import urlopen
from io import BytesIO
import mysql.connector as mysql
from MySQLdb import dbConnect
class StoreScreen(Toplevel):
def __init__(self):
Toplevel.__init__(self)
#frame = Frame(parent)
#frame.pack()
... | ACBL-Bridge/Bridge-Application | Home Files/storePage.py | Python | mit | 7,528 |
#!/usr/bin/env python
import numpy as np
import os
import shutil
import mss
import matplotlib
matplotlib.use('TkAgg')
from datetime import datetime
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigCanvas
from PIL import ImageTk, Image
import sys
PY3_OR_LATER... | kevinhughes27/TensorKart | record.py | Python | mit | 6,952 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Models.FeatureProcessing import *
from keras.models import Sequential
from keras.layers import Activation, Dense, LSTM
from keras.optimizers import Adam, SGD
import numpy as np
import abc
from ClassificationModule import ClassificationModule
class foldernameslstm(Cla... | Ichaelus/Github-Classifier | Application/Models/ClassificationModules/foldernameslstm.py | Python | mit | 3,635 |
# -*- coding:utf-8 -*-
import os
import sys
import sublime
import sublime_plugin
from .archiver import Archiver
from .settings import API_UPLOAD_URL
from .command import CommandWithStatus
sys.path.append(os.path.dirname(__file__))
import requests
class SublimeSyncUploadCommand(sublime_plugin.ApplicationCommand, Comm... | florianpaquet/sublime-sync | upload.py | Python | mit | 3,373 |
# Programmer friendly subprocess wrapper.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: March 2, 2020
# URL: https://executor.readthedocs.io
"""
Miscellaneous TCP networking functionality.
The functionality in this module originated in the :class:`executor.ssh.server`
module with the purpose of faci... | xolox/python-executor | executor/tcp.py | Python | mit | 6,803 |
from .nes import Nes
from .bus.devices.cartridge import CartridgeFactory
| Hexadorsimal/pynes | nes/__init__.py | Python | mit | 73 |
from random import choice
class Comparator:
def compare(self, clients, table):
return [choice(list(clients.keys()))]
| pRockrammer/DZcards | comparator.py | Python | mit | 130 |
from __future__ import absolute_import, print_function, unicode_literals
from compat_patcher_core import generic_patch_software, make_safe_patcher
@make_safe_patcher
def patch(settings=None):
"""Load every dependency, and apply registered fixers according to provided settings (or Django settings as a fallback)."... | pakal/django-compat-patcher | src/django_compat_patcher/__init__.py | Python | mit | 928 |
import SensorMonitor
class SensorFactory:
def __init__(self, sensor_cls, factory_if):
self.sensor_cls = sensor_cls
self.factory_if = factory_if
def create(self, **kwargs):
sensor_if = self.factory_if.create(**kwargs)
return self.sensor_cls(sensor_if)
class Sensor:
def __... | Nzbuu/SensorMonitor | SensorMonitor/sensor.py | Python | mit | 1,304 |
__author__ = "CHANN"
__email__ = "chann@chann.kr"
__version__ = "0.0.0"
import os
import sys
import re
from flask import Flask
from flask import render_template
from flask import url_for
from flask import redirect
from flask import request
from flask import flash
from flask_sqlalchemy import SQLAlchemy
from flask_log... | channprj/uptime-robot | app/__init__.py | Python | mit | 583 |
from abcmd import Command, Process
import pytest
@pytest.fixture()
def run_cmd(mocker):
return mocker.Mock(return_value=(0, "out", "err"))
def test_Command_init_arguments():
class MyCommand(Command):
def run(self):
pass
with pytest.raises(TypeError) as err:
MyCommand()
... | modulus-sa/abcmd | tests/test_abcmd.py | Python | mit | 5,599 |
import sys
import json
import webbrowser
# List similar commands so they end up in the same accordion
list_groups = [["usermove", "time", "otim"]]
groups = {}
for lg in list_groups:
for g in lg:
groups[g] = lg
white_piece_bitboards = [("White Pawn", "wp", "P"),
("White Knight","wn", "N"),
("White Bishop",... | tompko/Patrician | parse_log.py | Python | mit | 5,821 |
# Exercise 36: Designing and debugging
# No code
# Read: http://learnpythonthehardway.org/book/ex36.html
| pwittchen/learn-python-the-hard-way | exercises/exercise36.py | Python | mit | 105 |
#!/usr/bin/env python
from rgbmatrix import RGBMatrix
import time
rows = 32
chains = 2
parallel = 1
myMatrix = RGBMatrix(rows, chains, parallel)
myMatrix.Fill(255, 0, 0)
time.sleep(5)
myMatrix.Clear() | billthefighter/sunrise | hzeller-test.py | Python | mit | 201 |
import shopify
from test.test_helper import TestCase
class RefundTest(TestCase):
def setUp(self):
super(RefundTest, self).setUp()
self.fake("orders/450789469/refunds/509562969", method="GET", body=self.load_fixture("refund"))
def test_should_find_a_specific_refund(self):
refund = shop... | Shopify/shopify_python_api | test/refund_test.py | Python | mit | 1,089 |
# Generated by Django 3.0 on 2019-12-03 17:14
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_... | jbergantine/django-blog | django_blog/migrations/0001_initial.py | Python | mit | 2,509 |
prices = [2, 1, 2, 1, 2, 1]
total = 0
for i in xrange(1, len(prices), 2):
total += prices[i] - prices[i-1]
print total | quake0day/oj | ttt.py | Python | mit | 123 |
from datetime import datetime
from pretty_timedelta import pretty_timedelta
__author__ = 'gautam'
def pretty_time(datetime_value):
now = datetime.now()
delta = datetime_value - now
return pretty_timedelta(delta)
| gautamk/private-journal | util/custom_filters/pretty_time.py | Python | mit | 227 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-26 06:38
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pixelwars', '0011_auto_20170326_0935'),
]
operatio... | GenchoBG/HackTues3 | skeleton/pixelwars/migrations/0012_auto_20170326_0938.py | Python | mit | 2,133 |
"""This file contains code for use with "Think Bayes",
by Allen B. Downey, available from greenteapress.com
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
tb = imp.load_source('thinkbayes', '/home/chris/installations/python/ThinkBayes/thinkbayes.py')
from thinkbayes import ... | statwonk/thinkbayes | monty.py | Python | mit | 596 |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 05 17:10:34 2014
@author: Ning
"""
from util import *
from util.log import _logger
from feat.terms.term_categorize import term_category
import codecs
def parse(sentence):
for term in sentence.split():
yield term_category(term)
def tokenize():
r... | luanjunyi/cortana | feat/bow/tokenize.py | Python | mit | 834 |
from django.db import models
# Create your models here.
class Friend(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
friends = models.ManyToManyField('self', blank=True)
def full_name(self):
return self.first_name + " " + self.last_name
def __unicode__... | Nagasaki45/Friends-Mapper | friends/models.py | Python | mit | 353 |
# -*- coding: utf-8 -*-
class TrafficEntry:
def __init__(self, broadcast_count=0L, broadcast_bytes=0L, unicast_count=0L, unicast_bytes=0L):
self.broadcast_count = broadcast_count
self.broadcast_bytes = broadcast_bytes
self.unicast_count = unicast_count
self.unicast_bytes = ... | relman/sevpn-mgmt-py | SevpnMgmtPy/admin_api/traffic.py | Python | mit | 1,143 |
#!/usr/bin/python
#
# linearize.py: Construct a linear, no-fork, best version of the blockchain.
#
#
# Copyright (c) 2013 The SpeedCoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import json
import struct
im... | SureshMatsui/SpeedCoin | contrib/linearize/linearize.py | Python | mit | 3,357 |
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Copyright (c) 2013, Intel Corporation.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free ... | marcosbontempo/inatelos | poky-daisy/scripts/lib/mic/utils/oe/misc.py | Python | mit | 4,324 |
# Initialize web application and setup routing
from flask import Flask, request, session, render_template, send_from_directory
app = Flask(__name__) # Define the WSGI application object
# very first run will not have config.py
try: app.config.from_object('config')
except: pass
import os
import web.util.jinja # Initia... | unkyulee/elastic-cms | src/web/__init__.py | Python | mit | 2,565 |
# Given a linked list, remove the nth node from the end of list and return its head.
# For example,
# Given linked list: 1->2->3->4->5, and n = 2.
# After removing the second node from the end, the linked list becomes 1->2->3->5.
# Note:
# Given n will always be valid.
# Try to do this in one pass.
# Defin... | abawchen/leetcode | solutions/019_remove_nth_node_from_end_of_list.py | Python | mit | 1,751 |
from __future__ import division
from math import *
def calculate(expr_string):
math_list = ['math', 'acos', 'asin', 'atan', 'atan2', 'ceil',
'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod',
'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi',
'pow', 'radians', 'sin', 'si... | vtbassmatt/django-expression-fields | src/expression_fields/expr.py | Python | mit | 668 |
from __future__ import absolute_import, division, print_function
import _ast
from jaspyx.context.block import BlockContext
from jaspyx.visitor import BaseVisitor
class IfElse(BaseVisitor):
def visit_If(self, node, skip_indent=False):
if not skip_indent:
self.indent()
self.output('if(')... | ztane/jaspyx | jaspyx/visitor/if_else.py | Python | mit | 809 |
import datetime
import logging
from createsend import *
from mailsync.models.customfield import CustomField
class CampaignMonitor(object):
def __init__(self, apikey):
CreateSend.api_key = apikey
self.provider = CreateSend()
def get_list_custom_fields(self, listid):
custom_fields = []
try:
list_custom... | rebelact/mailsync-app | mailsync/api/campaignmonitor.py | Python | mit | 2,808 |
"""
Generates protein-ligand docked poses.
"""
import platform
import logging
import os
import tempfile
import tarfile
import numpy as np
from subprocess import call
from subprocess import check_output
from typing import List, Optional, Tuple, Union
from deepchem.dock.binding_pocket import BindingPocketFinder
from dee... | lilleswing/deepchem | deepchem/dock/pose_generation.py | Python | mit | 13,071 |
from .image_loader import Database_loader
from .image_loader import Test_loader
from .model import Model
from .baseline_histograms import train_classifier
from .construct_DB import construct_DB | NicoRahm/CGvsPhoto | CGvsPhoto/__init__.py | Python | mit | 193 |
class Solution:
def minCut(self, s: str) -> int:
cut = [0] * (len(s) + 1)
cut[0] = -1
ispal = []
for _ in range(len(s)):
ispal.append([False] * len(s))
for i in range(len(s)):
mincut = i
for j in range(i+1):
# if i ... | shobhitmishra/CodingProblems | LeetCode/Session3/mincut.py | Python | mit | 600 |
"""empty message
Revision ID: ace8d095a26b
Revises:
Create Date: 2017-10-01 20:39:54.984192
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ace8d095a26b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | danielSbastos/gistified | migrations/versions/ace8d095a26b_.py | Python | mit | 769 |
'''
Created on 30 Jun 2015
@author: @willu47
'''
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from SALib.sample.ff import sample, find_smallest, extend_bounds
from SALib.analyze.ff import analyze, interactions
def test_find_smallest():
'''
'''
num_vars = [1, 2, 3, 4, 5, 6, 7... | willu47/SALib | tests/test_ff.py | Python | mit | 6,285 |