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 |
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
"""Stdout, stderr and argv support for unicode."""
##############################################
# Support for unicode in windows cmd.exe
# Posted on Stack Overflow [1], available under CC-BY-SA 3.0 [2]
#
# Question: "Windows cmd encoding change causes Python crash" [3] by Alex [4],
# Answered... | icyflame/batman | pywikibot/userinterfaces/win32_unicode.py | Python | mit | 12,438 |
""" A collection of input methods that aren't necessarily buttons """
from rcfc.server import register_post_with_state, register_post_with_input
from rcfc.groups import convertGroup
class DIRECTIONAL:
LEFT = "left"
RIGHT = "right"
def slider(text, getter, input_range=(0, 100), group=None):
min_value, m... | pviafore/rcfc | rcfc/input_methods.py | Python | mit | 1,204 |
from mock import MagicMock, patch
import pytest
from adbpy.adb import Adb
from adbpy import Target, AdbError
@pytest.fixture
def adb():
adb = Adb(())
adb.socket = MagicMock()
return adb
def test_get_transport():
assert Adb._get_transport(Target.ANY) == "host:transport-any"
assert Adb._get_transp... | noahgoldman/adbpy | tests/test_adb.py | Python | mit | 2,479 |
"""
Grab screen data from OMERO based on Screen ID
"""
import csv
import multiprocessing
import progressbar
import signal
import sys
import time
import requests
import json
from argparse import ArgumentParser
import omeroidr.connect as connect
from omeroidr.data import Data
parser = ArgumentParser(prog='OMERO screen ... | zegami/omero-idr-fetch | fetch_omero_data.py | Python | mit | 3,129 |
def f(x=2):
return x
lis = [1]
dic = {
"x": 2
}
f(1) # call_function
f(*lis) # call_function_var
f(**dic) # call_function_kw
f(*[], **dic) # call_function_var_kw
class C(object): # call_function
def __enter__(self):
x = 1
return x
def __exit__(self, *args, **kwargs):
... | gems-uff/noworkflow | tests/test_disasm.py | Python | mit | 831 |
"""Constant definitions for testing purposes."""
from bddbot.config import TEST_COMMAND
BANK_PATH_1 = "banks/first.bank"
BANK_PATH_2 = "banks/second.bank"
FEATURE_PATH_1 = BANK_PATH_1.replace("bank", "feature")
FEATURE_PATH_2 = BANK_PATH_2.replace("bank", "feature")
(HOST, PORT) = ("bank_server", 0xBDD)
CLIENT = "cli... | nivbend/bdd_bot | bddbot/test/constants.py | Python | mit | 367 |
import config
def execute(parser, bot, user, args):
if not parser.checkPerms(bot, user, "owner"):
return
reload(config)
bot.addressUser(user, "Got it, reloaded my config.")
def requiredPerm():
return "owner"
def canUseByWhisper():
return True
| Dabomstew/goldenrod | commands/reloadconfig.py | Python | mit | 297 |
from datetime import datetime
import pygame
from pygame.mixer import Sound
from ui import colours
from ui.widgets.background import LcarsBackgroundImage, LcarsImage
from ui.widgets.gifimage import LcarsGifImage
from ui.widgets.lcars_widgets import LcarsText, LcarsButton, LcarsBlockHuge, LcarsBlockLarge, LcarsBlockSmal... | psychomugs/lcars_probe | app/screens/mainOriginal.py | Python | mit | 4,771 |
import _plotly_utils.basevalidators
class BordercolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="bordercolor", parent_name="ohlc.hoverlabel", **kwargs
):
super(BordercolorValidator, self).__init__(
plotly_name=plotly_name,
pa... | plotly/python-api | packages/python/plotly/plotly/validators/ohlc/hoverlabel/_bordercolor.py | Python | mit | 526 |
# _________________________________________________________________________
#
# PyUtilib: A Python utility library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the BSD License.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains ... | evandrix/Splat | code/demo/pyutilib.math-3.3/setup.py | Python | mit | 1,569 |
import numpy as np # モジュールnumpyを読み込み
import matplotlib.pyplot as plt # モジュールmatplotlibのpylab関数を読み込み
def bernstein(t, n, i): # bernstein基底関数の定義
cn, ci, cni = 1.0, 1.0, 1.0
for k in range(2, n, 1):
cn = cn * k
for k in range(1, i, 1):
if i == 1:
break
ci = ci * k
f... | o-kei/design-computing-aij | ch3_2/bezier_2D.py | Python | mit | 1,190 |
import pytest
import logging
from pageobject import PageObject
from pageobject.pageobjectbase import PageObjectBase
from pageobject.locator import Locator
from .fixtures import mock_po_base
from selenium.webdriver import Remote as RemoteWebDriver
def test_dunder_repr_returns_correct_string(monkeypatch, mock_po_base):... | lukas-linhart/pageobject | tests/unit/test_pageobjectbase.py | Python | mit | 6,421 |
import json
import os
import time
import redis
# initialize redis connection for local and CF deployment
def connect_redis_db(redis_service_name = 'p-redis'):
if os.environ.get('VCAP_SERVICES') is None: # running locally
DB_HOST = 'localhost'
DB_PORT = 6379
DB_PW = ''
REDIS_DB = 1
... | lwalstad-pivotal/unified-demonstration-sentiment_01 | gen-tweet-stats/helper_functions.py | Python | mit | 1,012 |
from __future__ import division
import datetime
import pytz
from app.models import Patch
def get_match_patch(match_date):
utc = pytz.UTC
#pylint: disable=no-value-for-parameter
match_date = utc.localize(datetime.datetime.fromtimestamp(match_date))
for patch in Patch.objects.all().order_by('-start_dat... | lucashanke/houseofdota | app/util/match_util.py | Python | mit | 2,180 |
from hype.cloud.cloudprovider import CloudProvider
from boto import ec2
class AmazonEC2(CloudProvider):
def __init__(self, cfg):
CloudProvider.__init__(self, cfg)
self.conn = ec2.connect_to_region(str(self.cfg["region"]),
aws_access_key_id=str(self.cfg["access-key-id"]),
aws_secret_access_key=st... | mdwint/hype | hype/cloud/amazon.py | Python | mit | 1,420 |
from discord.ext import commands
from datetime import datetime
from bs4 import BeautifulSoup
import discord
import re
class VisWax:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True, aliases=['wax'],
description='Shows the combination of runes needed f... | duke605/RunePy | commands/viswax.py | Python | mit | 2,553 |
import logging
import os
from pip._internal.utils.subprocess import runner_with_spinner_message
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import List, Optional
from pip._vendor.pep517.wrappers import Pep517HookCaller
logger = logging.getLogger(__name__)
d... | nataddrho/DigiCue-USB | Python3/src/venv/Lib/site-packages/pip/_internal/operations/build/wheel.py | Python | mit | 1,458 |
import numpy as np
from quadracheer.recursion import recursive_quad,\
gll_nodes, modified_vandermonde, modified_moments
from quadracheer.rl135 import rl1
from quadracheer.map import map_pts_wts, map_singular_pt,\
map_distance_to_interval, map_weights_by_inv_power
def test_small_order_recursive_... | tbenthompson/quadracheer | tests/test_rl_quad.py | Python | mit | 4,531 |
# noinspection PyUnresolvedReferences
from cosmical_realistic import cosmical
import scipy.signal
import numpy as np
def cosmicImage(exptime=1800.0, size=2048, rate=5.0, gradient=False, diffusion=False, buffer_size=100):
"""Generate a cosmic ray image, using Al Levine's fast C code."""
# if a gradient is set... | TESScience/SPyFFI | Cosmics.py | Python | mit | 1,397 |
import os
import sys
from pathlib import Path
from setuptools import setup
from setuptools import find_packages
from setuptools.command.test import test as TestCommand
here = Path(os.path.abspath(os.path.dirname(__file__)))
with here.joinpath('README.rst').open() as f:
README = f.read()
with here.joinpath('req... | avanov/assignment | setup.py | Python | mit | 2,111 |
from __future__ import print_function
from pylab import *
import numpy as np
import cv2
import sys
def main(filenames):
for filename in filenames:
print("Processing %s" % filename)
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Using opencv
cv2.imshow('image %dx%d' % (... | Elucidation/ChessboardDetect | base_imgload.py | Python | mit | 538 |
"""Time series plot."""
import datetime
import pytz
import psycopg2.extras
import numpy as np
import pandas as pd
from pyiem.plot import figure_axes
from pyiem.util import get_autoplot_context, get_sqlalchemy_conn, get_dbconn
from pyiem.exceptions import NoDataFound
MDICT = dict(
[
("tmpf", "Air Temperatu... | akrherz/iem | htdocs/plotting/auto/scripts/p18.py | Python | mit | 7,957 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division
import math
from datetime import datetime
from random import randint
from furl import furl
from delorean import Delorean
def create_quota_headers(qpd=None, qps=None, reset=datetime.now()):
qpd_allotted, qpd_current = qpd if qpd else (10000... | Administrate/surveymonkey | surveymonkey/tests/mocks/utils.py | Python | mit | 3,642 |
# TODO: Logging
import contextlib
import json
import logging
import weakref
from python2.client.codec import ClientCodec
from python2.client.exceptions import Py2Error
from python2.client.object import Py2Object
SPECIAL_EXCEPTION_TYPES = {t.__name__: t for t in (StopIteration, TypeError)}
logger = logging.getLogge... | nickgaya/python2 | python2/client/client.py | Python | mit | 2,862 |
#!/usr/bin/env python3
import json
with open("day12-input.txt") as f:
day12_input = f.read()
day12_input_json = json.loads(day12_input)
def is_int(token):
return isinstance(token, int)
def is_list(token):
return isinstance(token, list)
def is_dict(token):
return isinstance(token, dict)
def p... | Lajnold/adventofcode2015 | day12.py | Python | mit | 1,136 |
# Unit tests for p24.py
# IMPORTS
from S24 import Item
import unittest
# main
class ItemTests(unittest.TestCase):
def test_empty_constructor(self):
item = Item()
self.assertEqual("", item.get_name())
self.assertEqual(0.0, item.get_price())
def test_constructor_with_name(self):
... | futurepr0n/Books-solutions | Python-For-Everyone-Horstmann/Chapter9-Objects-and-Classes/test_24.py | Python | mit | 718 |
#!/usr/bin/env python2
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import hashlib
import sys
import os
from random import SystemRandom
import base64
import hmac
if len(s... | cryptoprojects/ultimateonlinecash | share/rpcuser/rpcuser.py | Python | mit | 1,125 |
from buffalo import utils
from recipeManager import RecipeManager
from nose.tools import with_setup
import pygame
def init():
utils.init()
def teardown():
utils.end = True
pygame.quit()
@with_setup(init,teardown)
def test_manager():
RecipeManager.loadRecipes()
assert len(RecipeManager.RECIPES) > 0
| benjamincongdon/adept | test_recipe.py | Python | mit | 308 |
import concurrent.futures
from copy import deepcopy
from .SimulationResult import SimulationResult
class BatchSimulator:
def __init__(self, game, logger, count=1000, batch_size=5):
self._game = game
self._max = count
self._batch_size = batch_size
self._batches = self._max//self._ba... | djscheuf/Machikoro-Simulator | MachikoroSimulator/MachikoroSimulator/Simulator/BatchSimulator.py | Python | mit | 1,597 |
#!/usr/bin/env python
# encoding: utf-8
import glob
import os
import subprocess
cwd = os.getcwd()
'''
Convert 23andMe files to
PLINK format
'''
def twenty3_and_me_files():
"""Return the opensnp files that are 23 and me format"""
all_twenty3_and_me_files= glob.glob('../opensnp_datadump.current/*.23andme.txt')
fi... | gedankenstuecke/opensnp-fun | 01_analyse.py | Python | mit | 2,478 |
from iliasCorrector import db
def _split_ident(ident):
data = ident.split('_')
matr = int(data[-1])
last = data[0]
first = ' '.join(data[1:-2])
return first, last, matr
class Exercise(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True)
p... | simonsmiley/iliasCorrector | iliasCorrector/models.py | Python | mit | 2,030 |
class WTPBaseObject(object):
pass
class WTPResultObject(WTPBaseObject):
def _populate(self, instance, **kwargs):
self.api_instance = instance
for args in kwargs.items():
setattr(self, args[0], args[1])
return self
class APIResponse(WTPBaseObject):
"""
This the ... | Dolphman/WeThePeople | wethepeople/objects.py | Python | mit | 2,094 |
from sklearn.linear_model.base import BaseEstimator, LinearClassifierMixin
import sklearn
import numpy as np
from copy import deepcopy
from utils import roc_auc_score_reversed
import tt
import logging
class TTRegression(BaseEstimator, LinearClassifierMixin):
"""This class alows to optimize functions of the foll... | Bihaqo/exp-machines | src/TTRegression.py | Python | mit | 13,433 |
import unittest
import datetime
import uuid
import sys
import json
import sys, os, os.path
root_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..')
if root_directory not in sys.path:
sys.path.append(root_directory)
from applicationinsights.channel.contracts import *
from ... | Microsoft/ApplicationInsights-Python | tests/applicationinsights_tests/channel_tests/contracts_tests/TestMessageData.py | Python | mit | 2,310 |
import pickledb
import re
import yaml
from datetime import *
_ignoreUsage = "Sorry, I don't understand. The correct usage is '!ignore <-me | @user> [minutes]'."
_dmsUsage = "Sorry, I dom't understand. The correct usage is '!dms <-enable | -disable>'."
with open("./conf.yaml") as conf:
config = yaml.load(conf, Loa... | ibanner56/OtherDave | otherdave/commands/ignore.py | Python | mit | 2,051 |
import numpy as np
from PyQt5.QtWidgets import (QWidget, QProgressBar, QLabel, QCheckBox,
QPushButton, QSpinBox, QVBoxLayout, QFormLayout)
from .matplotlib import QMatplotlib
from qtgui.utils import QObserver
from tools.train import Training, TrainingController
from dltb.network import Ne... | Petr-By/qtpyvis | qtgui/widgets/training.py | Python | mit | 6,290 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-02-17 10:06
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('basicviz', '0049_auto_20170216_2228'),
... | sdrogers/ms2ldaviz | ms2ldaviz/decomposition/migrations/0001_initial.py | Python | mit | 4,500 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""DataPlatform module for the management of multimodal mechanical datasets.
The `samples` module provides a base class `SampleData` implementing a generic
data model and data paltform API, allowing to define by inheritance specific
data platform classes for specific mech... | heprom/pymicro | pymicro/core/samples.py | Python | mit | 218,980 |
# -*- coding: utf-8 -*-
# db_config
env = {
'redis': {
'host': '172.18.19.218',
'port': 6379,
'db': [0, 1, 2, 3, 4, 5],
},
'mongo': {
'host': '172.18.19.219',
'port': 27017,
'db': 'crs'
},
# 'mysql':{
# 'user': 'admin',
# ... | Svolcano/python_exercise | dianhua/setting/env_dev.py | Python | mit | 888 |
# def custom_range(end):
# i = 0
# z = "How generator works!!??"
# while i < end:
# yield i #coroutine : 진입점이 여러개인 함수
# print('custom_range.i :%s'%i)
# i += 1
# yield z
# gen = custom_range(5)
# for i in gen:
# print(i, end=',')
# list(gen)
# print(next(gen))
# def s... | SELO77/seloPython | 3.X/ex/asyncIOex.py | Python | mit | 5,486 |
#!/usr/bin/env python3
# coding: utf-8
####################################################################################
### Copyright (C) 2015-2019 by ABLIFE
####################################################################################
###################################################################... | ablifedev/ABLIRC | ABLIRC/bin/public/circos_plot.py | Python | mit | 9,818 |
"""
Django settings for paypal_demo project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build pa... | pizzapanther/Getting-Paid-With-Python | paypal_demo/paypal_demo/settings.py | Python | mit | 2,758 |
#!/usr/bin/env python
import imp
import os
PluginFolder = "./plugins"
MainModule = "__init__"
def getPlugins():
"""
List the plugins located in the plugins folder.
"""
plugins = []
pluginList = os.listdir(PluginFolder)
for pluginName in pluginList:
location = os.path.join(PluginFolde... | Nitr4x/whichCDN | utils/loader.py | Python | mit | 828 |
'''
Created on 22 sept. 2015
@author: arxit
'''
import os
from qgis.core import *
from PyQt4.QtCore import QCoreApplication
import PagLuxembourg.main
class StylizeProject(object):
'''
Main class for the layers stylize widget
'''
def __init__(self):
'''
Constructor
'''
... | Geoportail-Luxembourg/qgis-pag-plugin | widgets/stylize/stylize.py | Python | mit | 2,046 |
from django.test.testcases import TestCase
from mock import patch, Mock
from imfp.subscriptions.models import Subscription
__all__ = ['CreateSubscriptionTestCase', 'RemoveSubscriptionTestCase']
class SubscriptionOperationsTestBase(TestCase):
def setUp(self):
self.mock_event = Mock(id=1)
self.mo... | akoskaaa/imfp | imfp/subscriptions/tests/test_models.py | Python | mit | 1,766 |
# coding=utf-8
# !/usr/bin/env python
import sys
try:
from setuptools import setup
except ImportError:
sys.stderr.write('using distutils\n')
from distutils.core import setup
with open('requirements.txt') as f:
required = f.read().splitlines()
required = [ req.split('#egg=')[1] if '#' in req else r... | project-capo/amber-python-drivers | setup.py | Python | mit | 2,925 |
# coding: utf-8
# file generated by setuptools_scm
# don't change, don't track in version control
version = '6.2.5'
version_tuple = (6, 2, 5)
| pexip/os-pytest | src/_pytest/_version.py | Python | mit | 142 |
"""
lamvery
----
Yet another deploy tool for AWS Lambda in the virtualenv environment.
"""
__version__ = '0.0.1'
| marcy-terui/lamvery | tests/__init__.py | Python | mit | 113 |
#!/usr/bin/env python3
class WordAddress(int):
# Retrieves all consecutive words for the given word address (including
# itself)
def get_consecutive_words(self, num_words_per_block):
offset = self % num_words_per_block
return [(self - offset + i) for i in range(num_words_per_block)]
| caleb531/cache-simulator | cachesimulator/word_addr.py | Python | mit | 316 |
import imp
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
migration = SQLALCHEMY_MIGRATE_REPO + '/versions/%03d_migration.py' % (api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) + 1)
tmp_module = imp.new_modul... | polosate/get_subscribes | db_migrate.py | Python | mit | 828 |
import os
import py
import pytest
import numpy as np
import openpnm as op
from openpnm.models.misc import from_neighbor_pores
@pytest.mark.skip(reason="'netgen' is only available on conda")
class STLTest:
def setup_class(self):
np.random.seed(10)
self.net = op.network.Cubic(shape=[2, 2, 2])
... | PMEAL/OpenPNM | tests/unit/io/STLTest.py | Python | mit | 1,388 |
import argparse
from pdnssync.database import Database
from pdnssync.parse import Parser
from pdnssync.error import get_warn, get_err
parser = Parser()
def validate():
domains = parser.get_domains()
for d in sorted(domains):
domains[d].validate(domains)
def sync(db):
all_db_domains = db.get_dom... | Quiphius/pdns-sync | pdnssync/main.py | Python | mit | 2,853 |
#! /usr/bin/python
# Filename : draw.py
# A python program for drawing 1d result
import matplotlib.pyplot as plt
import numpy as np
data = np.loadtxt('output.txt')
x = data[:,0]
h = data[:,1]
q = data[:,2]
plt.figure(figsize=(8,4))
plt.plot(x,h,color='blue',linewidth=2)
plt.xlabel('x(m)')
plt.ylabel('h(m)')
plt.ti... | xiaxilin/fvm_swes_1d | plot.py | Python | mit | 529 |
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name="color",
parent_name="bar.marker.colorbar.title.font",
**kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly... | plotly/plotly.py | packages/python/plotly/plotly/validators/bar/marker/colorbar/title/font/_color.py | Python | mit | 455 |
"""
Support for Speedtest.net based on speedtest-cli.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.speedtest/
"""
import logging
import re
import sys
from subprocess import check_output, CalledProcessError
import homeassistant.util.dt as dt_uti... | devdelay/home-assistant | homeassistant/components/sensor/speedtest.py | Python | mit | 4,705 |
import pygame
import math
import os
import sys
import struct
from Util import BinaryReader, Camera
from BoTWHeightmap import Heightmap, Config
bgcolor = (0, 0, 0)
size = [1024, 768]
camera = Camera(size)
camera.SetLodLevel(32.0)
# Initialize pygame
pygame.init()
screen = pygame.display.set_mode(size)
# Run a loo... | simply-jos/birth-of-the-toolkit | REScripts/TSCBViewer/viewer.py | Python | mit | 2,829 |
"""
This is the file to store all user-definable magic constants.
Of course, all these values are supposed to be got from some
decent config file, something like ~/.habiter. Somewhen I'll
do that. Nevertheless, current file could be the source of
the default settings.
"""
try:
from .secret import USER_ID, API_KEY... | moskupols/habiter | habiter/settings.py | Python | mit | 1,683 |
"""
Copyright (C) 2012 Alan J Lockett
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, distribute,... | hypernicon/pyec | pyec/distribution/boltzmann/sample.py | Python | mit | 29,509 |
# -*- coding: utf-8 -*-
from lutefiskdemo.settings import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
SITE_ID = 1
MAINTENANCE_MODE = 'DEVELOPMENT'
EMAIL_PORT = 1025
INSTALLED_APPS += (
'debug_toolbar',
)
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
INTERNAL_IPS = (
... | rentalita/django-lutefiskdemo | src/python/lutefiskdemo/development.py | Python | mit | 475 |
<<<<<<< HEAD
<<<<<<< HEAD
# -*- coding: utf-8 -*-
"""Tests for distutils.archive_util."""
import unittest
import os
import sys
import tarfile
from os.path import splitdrive
import warnings
from distutils import archive_util
from distutils.archive_util import (check_archive_formats, make_tarball,
... | ArcherSys/ArcherSys | Lib/distutils/tests/test_archive_util.py | Python | mit | 35,333 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
def gray2rgb(data):
return np.array(Image.fromarray(data, 'L').convert('RGB'))
# ITU-R 601-2 luma transform:
# L = R * 299/1000 + G * 587/1000 + B * 114/1000
def rgb2gray(data):
return np.array(Image.fromarray(data, 'RGB').conv... | gdsglgf/tutorials | python/pillow/image_converter.py | Python | mit | 896 |
from core import views
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken import views as authtoken_views
router = DefaultRouter()
router.register(r'category', views.CategoryViewSet)
router.register(r'provider', views.ProviderViewSet)
router.regist... | FZambia/reborn | server/core/urls.py | Python | mit | 739 |
import sys
def render(node, strict=False):
"""Recipe to render a given FST node.
The FST is composed of branch nodes which are either lists or dicts
and of leaf nodes which are strings. Branch nodes can have other
list, dict or leaf nodes as childs.
To render a string, simply output it. To rende... | cbonoz/codehealth | dependencies/baron/render.py | Python | mit | 34,151 |
try:
from account.decorators import login_required
except ImportError:
from django.contrib.auth.decorators import login_required # noqa
try:
from account.mixins import LoginRequiredMixin
except ImportError:
from django.contrib.auth.mixins import LoginRequiredMixin # noqa
| pinax/pinax-forums | pinax/forums/compat.py | Python | mit | 292 |
import unittest
from rasterio import features
from shapely import wkt
class TestRasterize(unittest.TestCase):
def test_first(self):
size = 20
first = "POLYGON(({0} {0}, {0} -{0}, -{0} -{0}, -{0} {0}, {0} {0}))".format(size)
geo_interfaces = [wkt.loads(first).__geo_interface__]
ras... | reinvantveer/Topology-Learning | model/topoml_util/test_rasterization.py | Python | mit | 429 |
import socket
import os
server_address = '/tmp/uds_socket'
# Unlink the socket if it already exists
try:
os.unlink(server_address)
except OSError:
if os.path.exists(server_address):
raise
# Create a socket
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
except socket.error:
prin... | egenerat/REST-API | uds/server.py | Python | mit | 539 |
"""
Package for managing a ranked ladder, which is a special kind of ongoing League.
Package Requirements
--------------------
botbase
match
user
Dependencies
------------
cmd_ladder
botbase/
commandtype
ladder/
ratingsdb
match/
cmd_match
matchinfo
user/
userl... | incnone/necrobot | necrobot/ladder/__init__.py | Python | mit | 678 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ndim.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| jsalva/ndim | ndim/manage.py | Python | mit | 247 |
import tempfile
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import xlrd
from networkx.algorithms import bipartite as bi
from networkx.algorithms import centrality
from itertools import product
from collections import defaultdict
import pandas as pd
import datetime
from gat.core.sna import ... | css-lucas/GAT | gat/core/sna/updateSNA.py | Python | mit | 35,903 |
"""
PSET-4
Word Game Part 9: You and your Computer
"""
PROMPT_STR = "Enter n to deal a new hand, r to replay the last hand, or e to end game: "
NO_REPL_AVAIL_STR = "You have not played a hand yet. Please play a new hand first!"
INVALID_CMD = "Invalid command."
CHOOSE_PLAYER_STR = "Enter u to have yourself play, c to h... | CptDemocracy/Python | MITx-6.00.1x-EDX-Introduction-to-Computer-Science/Week-4/PSET-4/game.py | Python | mit | 2,366 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-02-12 06:08
from __future__ import unicode_literals
from django.db import migrations
import fossevents.users.models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_user_is_moderator'),
]
operations = [
m... | fossevents/fossevents.in | fossevents/users/migrations/0005_auto_20170212_1138.py | Python | mit | 504 |
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of th... | d9w/6858-android-intents | analyzer/androguard/core/bytecodes/dvm.py | Python | mit | 232,587 |
#!/usr/bin/env python3
version = '0.1.2'
| jad-b/garden | garden_test/testfile.py | Python | mit | 42 |
import Image
import os
import math
import argparse
# Set the root directory
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
HTML_DIR = os.path.join(BASE_DIR, 'diced_images')
def dice(image_path, out_name, out_ext, outdir, slices):
img = Image.open(image_path) # Load image
imgdir = os.path.join(outdir, ... | skolsuper/imagedicer | imagedicer.py | Python | mit | 3,913 |
# file:///C|/project/lifeanddeath/lifeanddeath.fla.stage.py
# max_depth = 9
{
'currentLabel': 'setup',
'cursor_mc': {
'currentLabel': 'none',
'act_mc': {
'currentLabel': 'none',
}, # act_mc
'extra_stone_mc': {
'currentLabel': '_0',
}, #... | ethankennerly/hotel-vs-gozilla | lifeanddeath.fla.stage.py | Python | mit | 433,306 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This provides a base SensuHandler class that can be used for writing
python-based Sensu handlers.
'''
from __future__ import print_function
import argparse
import os
import sys
import json
import requests
try:
from urlparse import urlparse
except ImportError:
f... | sensu/sensu-plugin-python | sensu_plugin/handler.py | Python | mit | 9,342 |
from django.contrib import admin
from manager.models import Package, Build, Artifact
class PackageAdmin(admin.ModelAdmin):
list_display = ('id', 'name')
admin.site.register(Package, PackageAdmin)
class BuildAdmin(admin.ModelAdmin):
list_display = ('id', 'package', 'version', 'date', 'status')
admin.sit... | colajam93/aurpackager | manager/admin.py | Python | mit | 483 |
import abc
import json
import flask
class ApiBase(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def add_feature(self, feature_name, distribution, **kwargs):
return
@abc.abstractmethod
def remove_feature(self, feature_name, **kwargs):
return
@abc.abstractmethod
... | diogo149/simbo | simbo/base/api.py | Python | mit | 1,542 |
'''
This module extracts all of the comments and comment threads from the forum of
a given course. Using NLTK, all of the comments and comment threads will be
parsed into a list of words which will be then used to create a word cloud
using http://www.wordle.net/create
Usage:
python forum_body_extraction_for_word_... | McGillX/edx_data_research | edx_data_research/reporting/basic/forum_body_extraction_for_word_cloud.py | Python | mit | 1,989 |
from enum import Enum
class LogLevel(Enum):
"""Represent different log levels by their verbose codes."""
TRACE = 'TRC'
DEBUG = 'DBG'
INFO = 'INF'
WARNING = 'WRN'
WARN = 'WRN'
ERROR = 'ERR'
FATAL = 'FTL'
UNKNOWN = 'UKN'
class LogLevelInt(Enum):
"""Represent different log leve... | jmluy/xpython | exercises/concept/log-levels/.meta/exemplar.py | Python | mit | 1,610 |
import subprocess
import os
defaultUser = 'root'
defaultSudoGroup = 'sudo'
try: #master
git_root_path = subprocess\
.Popen(["git", 'rev-parse', '--show-toplevel'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\
.communicate()[0].rstrip() + '/'
except Exception as e:
#slave
... | hero78119/account-management-deploy-system | src/conf/projConst.py | Python | mit | 2,609 |
'''
Vibrator
=======
The :class:`Vibrator` provides access to public methods to use vibrator of your
device.
.. note::
On Android your app needs the VIBRATE permission to
access the vibrator.
Simple Examples
---------------
To vibrate your device::
>>> from crisscross import vibrator
>>> time=2
... | bhaveshAn/crisscross | crisscross/facades/vibrator.py | Python | mit | 2,155 |
class Error(Exception):
"""Generic errors."""
def __init__(self, msg: str) -> None:
Exception.__init__(self)
self.msg = msg
def __str__(self):
return self.msg
class ConfigError(Error):
"""Config related errors."""
pass
class RuntimeError(Error):
"""Generic runtime errors."""
pass
| urosjarc/maestro | maestro/core/exc.py | Python | mit | 301 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | Azure/azure-sdk-for-python | sdk/containerservice/azure-mgmt-containerservice/azure/mgmt/containerservice/v2022_01_01/operations/_agent_pools_operations.py | Python | mit | 40,397 |
a = raw_input("Yakin ? (y/t) : ")
list = ["y","Y"]
if a in list :
print "baiklah"
elif a in ["t","T"]:
print "Sayang Sekali"
else:
print "Liat Pilihan OON" | Jufianto/LearnPython | fistLearn/konsidi.py | Python | mit | 165 |
import httplib2
import os
import mimetypes
import time
from apiclient import discovery, errors
from googleapiclient.http import MediaFileUpload
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
try:
import argparse
flags = argparse.ArgumentParser(parents=[too... | dsloop/FranERP | app/google_drive_api.py | Python | mit | 3,922 |
import re
from functools import partial
from os.path import (join as pjoin, basename, normpath, sep)
from subprocess import CalledProcessError
from gtest.util import (
prepare_working_directory, prepare_compiled_grammar,
debug, info, warning, error, red, green, yellow,
check_exist, make_keypath, dir_is_pr... | goodmami/gtest | gtest/coverage.py | Python | mit | 6,114 |
'''
Created on Sep 28, 2013
@author: justin
'''
class databaseConstants():
'''
Holds the metadata behind the database creation
'''
_connDict = {
'DBType':'mysql',
'DBUsername':'root',
'DBPassword':'Ginger*12',
'DBNAme':'SportsStatistics',
'DBServer':'local... | JJarczyk12/Sports-Statistical-Scraper | SportsStatistics/model/databaseConstants.py | Python | mit | 2,575 |
# coding: utf-8
import json
import functools
import tornado.web
from tornado.log import app_log
from tornado.util import import_object
from .base import Base
from tt.model.user import User
def load_model(func):
"""注入一个Model参数给函数."""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
... | yunlzheng/tomatodo | tt/handle/backbone.py | Python | mit | 3,975 |
# ==============================================================================
# Copyright 2019 - Philip Paquette
#
# NOTICE: 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 rest... | diplomacy/research | diplomacy_research/models/policy/token_based/v004_language_model/tests/test_model.py | Python | mit | 4,186 |
import random
import collections
from itertools import *
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(islice(iterable, n))
def tabulate(function, start=0):
"Return function(0), function(1), ..."
return map(function, count(start))
def consume(iterator, n):
"Advance the ite... | ztenma/Swap | itertoolsExt.py | Python | mit | 5,830 |
# Lesson 3
# If arguments n3 or later aren't provided by the caller, they'll use a default value instead
def add(n1, n2, n3=0, n4=0, n5=0, n6=0): # (We'll learn a better way to do something like this later)
return n1 + n2 + n3 + n4 + n5 + n6
print(add(1, 2, 3, 4))
# We can explicitly fulfil arguments out of ... | JonTheBurger/python_class | chapter 3/lessons/default_arguments.py | Python | mit | 383 |
from __future__ import absolute_import
import logging
import re
from pyramid.settings import aslist
from . import request_log
log = logging.getLogger(__name__)
def includeme(config):
settings = config.registry.settings
config.scan('pyramid_request_log.request_log')
if 'pyramid_request_log.pattern' i... | MoiTux/pyramid-request-log | pyramid_request_log/config.py | Python | mit | 1,497 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-01-02 18:22
from __future__ import unicode_literals
import django.contrib.auth.models
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependenc... | Nikola-K/django-template | users/migrations/0001_initial.py | Python | mit | 3,082 |
"""Generate JSON files with dbnames per project
Just generates for wikipedias for now"""
from urllib2 import urlopen
import unicodecsv as csv
import json
def get_dbnames(wiki_class):
"""Return dbnames for all wikis in a particular wiki_class, such as 'wikipedias'"""
URL = "https://wikistats.wmflabs.org/api.p... | yuvipanda/edit-stats | dmz/generate_dbnames.py | Python | mit | 821 |
"""Add model for snapshots of ExperimentThings
Revision ID: a0f4fda7588f
Revises: ae72c799d321
Create Date: 2016-11-26 22:05:26.728790
"""
# revision identifiers, used by Alembic.
revision = 'a0f4fda7588f'
down_revision = 'ae72c799d321'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy... | c4fcm/CivilServant | alembic/versions/a0f4fda7588f_add_model_for_snapshots_of_.py | Python | mit | 4,337 |
#!/usr/bin/env python
'''
CSV to JSON Converter
Created by Anurag Banerjee.
Copyright 2016. All rights reserved.
USAGE `python csv-to-json.py <CSV FILE>`
Use I/O Redirection for creating resulting files.
`python csv-to-json.py sample.csv > sample.json`
'''
from codecs import open
import json
import sys
def showIn... | anuragbanerjee/HandyTools | csv-to-json.py | Python | mit | 1,300 |
from . import base
from .base import action
class Graph(base.Container):
template = 'spaces/graph.html'
@classmethod
def implementations(cls):
return (cls, )
@action
def create_node(self, **kwargs):
return kwargs
@action
def update_node(self, **kwargs):
return kw... | alviproject/alvi | alvi/containers/graph.py | Python | mit | 468 |
# -*- coding: utf-8 -*-
"""Base module for unittesting."""
from plone.app.testing import applyProfile
from plone.app.testing import FunctionalTesting
from plone.app.testing import IntegrationTesting
from plone.app.testing import login
from plone.app.testing import PLONE_FIXTURE
from plone.app.testing import PloneSandb... | a25kk/mitr | src/mitr.sitetheme/mitr/sitetheme/testing.py | Python | mit | 1,948 |
''' Initiation procedure for the auth module
Yields:
- Initiates the Login Manager
'''
# ---------------------------------------------------------------------------
# Imports
# ---------------------------------------------------------------------------
from flask_login import LoginManager
from .. import app
# --... | jtannas/NOA | app/mod_auth/__init__.py | Python | mit | 613 |