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 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('client', '0002_auto_20150122_1116'),
]
operations = [
migrations.CreateModel(
name='Item',
fields=[
... | delete/estofadora | estofadora/item/migrations/0001_initial.py | Python | mit | 1,392 |
# Generated by Django 2.2.8 on 2020-01-07 22:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('grants', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='grant',
name='gender',
fie... | patrick91/pycon | backend/grants/migrations/0002_auto_20200107_2234.py | Python | mit | 682 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-01-04 09:13
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ligoj', '0005_auto_20170104_0858'),
]
operations = [
migrations.RemoveField(
... | Arlefreak/ApiArlefreak | ligoj/migrations/0006_remove_link_name.py | Python | mit | 386 |
import keyboard
print('Press esc to stop recording keys.')
recorded = keyboard.record(until='esc')
for r in recorded:
print(r.name, r.scan_code, r.event_type)
| butla/experiments | misc/keyboard_capture.py | Python | mit | 164 |
#!/usr/bin/env python -*- coding: utf-8 -*-
import random
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
__Author__ = "Riyaz Ahmad Bhat"
__Version__ = "1.0"
def dispersion (data, k):
if k == 1:
cluster_mean = np.mean(data, axis=0)
distances_from_mean = np.su... | riyazbhat/Prediction-Strength-and-Gap-Statistics-in-Python | gapStatistics.py | Python | mit | 2,651 |
"""
Set of helper functions for reading, writing and parsing information.
"""
import re
from datetime import datetime
date_formatting = '%d/%b/%Y:%H:%M:%S %z'
request_pattern = '(?P<ip>\S+).*\s' + \
'\[(?P<date>.+)\]\s*' + \
'\"(?P<request>.+)\"\s*' + \
'(?P<respo... | MariiaSurmenok/insight-data-challenge | src/io_utils.py | Python | mit | 2,295 |
# -*- coding: utf-8 -*-
""" OneLogin_Saml2_Logout_Response class
Copyright (c) 2014, OneLogin, Inc.
All rights reserved.
Logout Response class of OneLogin's Python Toolkit.
"""
from onelogin.saml2.utils import OneLogin_Saml2_Utils
from onelogin.saml2.xml_templates import OneLogin_Saml2_Templates
from onelogin.saml... | jkgneu12/python3-saml | src/onelogin/saml2/logout_response.py | Python | mit | 6,309 |
#Compound Machine
#Scoring Guidelines
#Version 1.2
#Stephanie Gu
#==========================================
import math
from math import *
import datetime
d= str(datetime.date.today())
print(d)
file = open('Compound_Machine'+d+'.txt','w')
print('2014 LA Regionals\n' + 'Compound Machines Cabinet Evaluations')
name = ... | kevinlee12/GAWHS-SciOly | Compound Machines.py | Python | mit | 2,798 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import division
import logging
import time
from quant.brokers import broker_factory
from quant.common import log
from .basicbot import BasicBot
class TriangleArbitrage(BasicBot):
"""
bch:
# python -m quant.cli -mKraken_BCH_EUR,Bitfinex_BCH_BT... | doubleDragon/QuantBot | quant/observers/t_kraken.py | Python | mit | 19,105 |
from django.core.paginator import Paginator, Page
from django.utils import six
from django.conf import settings
from elasticsearch_dsl.result import Response
class ElasticPaginator(Paginator):
"""Implementation of Django's Paginator that makes amends for
Elasticsearch DSL search object details. Pass a search... | devrand/declarations.com.ua | declarations_site/catalog/paginator.py | Python | mit | 3,085 |
# standard imports
from unittest import TestCase
# toolbox imports
from dltb.base.register import RegisterClass
class MockClass(metaclass=RegisterClass):
"""MockClass to test the :py:class:`RegisterClass`.
"""
class MockSubclass(MockClass):
"""Subclass of :py:class:`MockClass` to test
the :py:clas... | Petr-By/qtpyvis | dltb/base/tests/test_register.py | Python | mit | 1,283 |
from .. import Provider as LoremProvider
class Provider(LoremProvider):
# https://www.101languages.net/armenian/armenian-word-list
word_list = (
'ես',
'դու',
'նա',
'մենք',
'դուք',
'նրանք',
'այս',
'այն',
'այստեղ',
'այնտեղ',
... | danhuss/faker | faker/providers/lorem/hy_AM/__init__.py | Python | mit | 4,610 |
from asyncio import get_event_loop
from json import dumps, loads
from pathlib import Path
from sqlite3 import connect
from time import time
from typing import Dict, Optional, Union
from roboragi.logger import get_default_logger
from .abc import DataController
from .enums import Medium, Site
from .sqlite_utils import m... | MaT1g3R/Roboragi | roboragi/data_controller/sqlite_controller.py | Python | mit | 7,769 |
#! python3
from dateutil import parser as DateParse
import pytoml
from optparse import OptionParser
import random, re, sys, time, hashlib, base64
g_methods = dict()
def method(name):
def m(func):
def inner(a):
return func(a)
g_methods[name] = func
return inner
return ... | healerkx/PySQLKits | mysqlbatch/methods.py | Python | mit | 1,021 |
# The game is played on a rectangular grid with a given size. Some cells
# contain power nodes. The rest of the cells are empty.
# The goal is to find, when they exist, the horizontal and vertical neighbors
# of each node.
# To do this, you must find each (x1,y1) coordinates containing a node, and
# display th... | Pouf/CodingCompetition | CG/medium_there-is-no-spoon-episode-1.py | Python | mit | 1,055 |
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# Examples:
# url(r'^$', 'character_generator.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
]
| Daniel-and-Zach/character_generator | character_generator/urls.py | Python | mit | 267 |
# -*- coding: utf-8 -
#
# This file is part of offset. See the NOTICE for more information.
from collections import deque
import random
from .context import Context
from .exc import ChannelError
from ..util import six
from . import proc
class bomb(object):
def __init__(self, exp_type=None, exp_value=None, exp_t... | benoitc/offset | offset/core/chan.py | Python | mit | 10,774 |
#!/usr/bin/env python
import cPickle
import csv
import os
import re
import sys
TIME_RE = re.compile("^\d+:")
def minutes(time):
"""Convert a race time into minutes
given a time in the format hh:mm:ss, return the number of minutes"""
parts = [int(x) for x in time.split(':')]
return parts[0] * 60 + pa... | llimllib/bostonmarathon | makecsv.py | Python | mit | 1,186 |
import django
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("monitorings", "0001_initial"),
("alerts", "0001_initial"),
("contenttypes", "0002_remove_content_type_name"),
migrations.swappable_depen... | watchdogpolska/feder | feder/alerts/migrations/0002_auto_20151025_2345.py | Python | mit | 1,349 |
# -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# We cannot i... | qbbian/imread | docs/source/conf.py | Python | mit | 8,570 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-30 01:41
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('timetracker', '0008_auto_20170629_1616'),
]
operations = [
migrations.RenameField(
... | jantaylor/road-home-time-tracker | timetracker/migrations/0009_auto_20170629_1941.py | Python | mit | 725 |
import numpy as np
import numba
@numba.jit
def identity(x):
""" A no-op link function.
"""
return x
@numba.jit
def _identity_inverse(x):
return x
identity.inverse = _identity_inverse
@numba.jit
def logit(x):
""" A logit link function useful for going from probability units to log-odds units.
"... | slundberg/shap | shap/links.py | Python | mit | 443 |
from django.conf.urls import url
import issues.views as views
urlpatterns = [
url(r'^(?P<issue_id>\d+)$', views.issue_page, name="issues.views.issue_page"),
url(r'^get_or_create/(?P<task_id>\d+)/(?P<student_id>\d+)$', views.get_or_create,
name="issues.views.get_or_create"),
url(r'^upload/$', views... | znick/anytask | anytask/issues/urls.py | Python | mit | 425 |
#!/usr/bin/env python
"""Support library with useful utilities."""
import cPickle as pkl
import numpy as np
import os
import Image
from scipy.ndimage.filters import maximum_filter
from numpy.lib.stride_tricks import as_strided
__author__ = "Andrea Casini"
__copyright__ = "Copyright 2014"
__license__ = "MIT"
__versi... | bluesurfer/pyforest | pyforest/utils.py | Python | mit | 2,451 |
#!/usr/bin/env python3
import logging
from logging import error, warning, info, debug
import json
import re
import asyncore
import signal
from client import Client
from server import Server
from utils import recursive_round, clamp
from controls import VehicleControls
from state import VehicleState
from speed_control... | zwarren/morse-car-controller | control/main.py | Python | mit | 11,313 |
"""
Redis has no configuration options (yet), use it like this:
.. sourcecode:: yaml
deploy:
- redis
"""
from . import Package
def deploy(settings):
# redis dependency, no commands
return Package('redis'),
| davidhalter/depl | depl/deploy/redis.py | Python | mit | 230 |
import sys,os
mydir = os.path.dirname(sys.argv[0])
if len(mydir) == 0: mydir = "./"
template = open(mydir + '/htaccess-template','r').read()
issuers = list()
users = list()
if len(sys.argv) == 2:
if sys.argv[1] == '-':
input = sys.stdin
else:
input = open(sys.argv[1],'r')
elif len(sys.argv) ... | softcert/vsroom | contrib/certificate-based-authentication/vsr-populate-certficate-users.py | Python | mit | 1,519 |
'''
This is solution to problem https://www.hackerrank.com/challenges/battery
Status : Incomplete
'''
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
def load ():
data = np.loadtxt ("data/battery_train.txt", \
delimiter=",")
#print data
charged, ran = (data[... | ziiin/DS-py | HackerRank/battery.py | Python | mit | 1,005 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
from .logging import LOGGING # NOQA
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'this is not the actual secret key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = ... | iaga84/securities-analyzer | src/s_analyzer/settings/default.py | Python | mit | 2,738 |
from distutils.core import setup
setup(
name='phabulous',
version='0.1.3',
author='Will Larson',
author_email='lethain@gmail.com',
packages=['phabulous', 'phabulous.tests'],
url='http://pypi.python.org/pypi/phabulous/',
license='LICENSE.txt',
description='Pythonic abstraction for python... | lethain/phabulous | setup.py | Python | mit | 466 |
# MIT License
#
# Copyright (c) 2015-2021 Iakiv Kramarenko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modif... | yashaka/selene | selene/core/entity.py | Python | mit | 60,369 |
#!/usr/bin/env python3
import sqlite3
import hashlib
import random
import time
from datetime import datetime
class db_handler:
def __init__(self, name):
self.name = name
self.conn = self._get_db()
self.setup()
def _get_db(self):
return sqlite3.connect(self.name)
def setu... | BenDoan/livia-server | db_handler.py | Python | mit | 3,766 |
class GroupNotFoundException(Exception):
pass
class NoConnectionError(Exception):
pass
class RemoteCommandFailedError(Exception):
pass
class InvalidUnitError(Exception):
pass
class InvalidPluginError(Exception):
pass
| camerongray1515/Chaac | common/exceptions.py | Python | mit | 241 |
import json
import unittest
import app
class DownloaderTestCase(unittest.TestCase):
def setUp(self):
app.app.testing = True
self.app = app.app.test_client()
self.headers = {
"Authorization": "Basic VVNFUk5BTUU6UEFTU1dPUkQ=",
"Content-Type": "application/json"
... | P1-Ro/mini-remote-downloader | tests.py | Python | mit | 4,637 |
"""
Application specific layer
"""
import sqlite3
from . import domain, settings
class Link(domain.Link):
@property
def full_url(self):
url = self.url
if not url.startswith('http'):
url = 'http://' + url
return url
def connection_factory():
connection = sqlite3.con... | Afonasev/LinksCutter | backend/linkscutter/application.py | Python | mit | 2,703 |
from pycoin.coins.groestlcoin.hash import groestlHash
from pycoin.coins.groestlcoin.parse import GRSParseAPI
from pycoin.coins.groestlcoin.Block import Block as GrsBlock
from pycoin.coins.groestlcoin.Tx import Tx as GrsTx
from pycoin.encoding.b58 import b2a_base58
from pycoin.encoding.hexbytes import h2b
from pycoin.ne... | richardkiss/pycoin | pycoin/symbols/grs.py | Python | mit | 1,950 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import picamera
import os
import timebb
from PIL import Image, ImageDraw, ImageFont
def main():
"""
Displayes preview on PiTFT with PiCamera.add_overlay(). Displayed animation
is composed of two layers; One continuously displays the input from camer... | symunona/quadroscope | quadlib/test/overlaytest2.py | Python | mit | 2,361 |
from lxml import etree
from healthvaultlib.utils.xmlutils import XmlUtils
from healthvaultlib.itemtypes.healthrecorditem import HealthRecordItem
class PeakFlow(HealthRecordItem):
def __init__(self, thing_xml=None):
super(PeakFlow, self).__init__()
self.type_id = '5d8419af-90f0-4875-a370-0f881c18... | rajeevs1992/pyhealthvault | src/healthvaultlib/itemtypes/peakflow.py | Python | mit | 849 |
import multiprocessing
import sys
from bs4 import BeautifulSoup
import mechanize
import argparse
import urllib
import urllib2
import time
import MySQLdb
class WebSpider():
def __init__(self, webSite, depth, proxyhost, proxyuser, proxypassword, proxyport,proxysecure="http"):
try:
self.webSite = webSite
self.d... | coolhacks/python-hacks | examples/pyHacks/WebSpider.py | Python | mit | 9,026 |
from varappx.models.users import *
from varappx.common.utils import normpath, sha1sum
from varappx.handle_config import settings
import os, logging, time, datetime
from os.path import join
logger = logging.getLogger(__name__)
SQLITE_DB_PATH = settings.SQLITE_DB_PATH
TEST_PATH = join(normpath(SQLITE_DB_PATH), setting... | 444thLiao/VarappX-flask | varappx/common/db_utils.py | Python | mit | 5,680 |
import os
template_dir = os.path.dirname(__file__)
template_fn = 'multiqc_report.html'
| ewels/MultiQC_NGI | multiqc_ngi/templates/__init__.py | Python | mit | 88 |
from utils.property import cached_property,is_cached,delete_cache
from utils.dict import mget,merge
from giftwrap import JsonExchange
from sanetime import ntime
class Settings(object):
def __init__(self, hub, **kwargs):
super(Settings, self).__init__()
self.hub = hub
self.sm = self.domains... | prior/hapicake | cake/settings.py | Python | mit | 4,639 |
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
while (num>=10):
num = int(num/10) + (num %10)
return num
| tonylixu/leetcode | add-digits/solution1.py | Python | mit | 207 |
"""Tests for the template tags of the ``privacy`` app."""
from django.template import Context, Template
from django.test import TestCase
from ..templatetags.privacy_tags import is_access_allowed, get_privacy_setting
from .factories import PrivacyLevelFactory, PrivacySettingFactory
from test_app.factories import DummyP... | bitmazk/django-privacy | privacy/tests/tags_tests.py | Python | mit | 5,768 |
__author__ = "Christian Kongsgaard"
__license__ = 'MIT'
# -------------------------------------------------------------------------------------------------------------------- #
# IMPORTS
# Modules
import numpy as np
import os
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from s... | thp44/delphin_6_automation | delphin_6_automation/delphin_setup/archive/driving_rain_model.py | Python | mit | 7,950 |
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, 'index.html')
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the res... | mrclro/kbxrec | project/locations/views.py | Python | mit | 494 |
# -*- coding: utf-8 -*-
## ajax_views
import json
import os
import shutil
from pyramid.response import Response
from pyramid.request import Request
from pyramid.view import view_config
import uuid
import Image
from sqlalchemy.exc import DBAPIError
from sqlalchemy.orm import aliased
from pyramid.httpexceptions import ... | johncadigan/myenglishcloud | english/ajax_submissions.py | Python | mit | 15,904 |
"""
The Events module includes classes for each event that the system can process.
"""
from copy import copy
from node import DownNode
class Event(object):
"""
The Base Event Class. Includes shared behavior.
"""
def __init__(self, event_map):
self.event_map = copy(event_map)
self.even... | WesleyAC/raft | src/events.py | Python | mit | 7,460 |
from bin.hang import check_already_guessed
def test_check_guessed_true():
assert check_already_guessed('t', 'abcnotrymjkl')
print('OK!')
def test_checked_guessed_false():
assert not check_already_guessed('w', 'abcnotrymjkl')
print('OK!')
if __name__ == '__main__':
test_check_guessed_true()
... | DesmondPrice/Hang | tests/test.py | Python | mit | 350 |
import cPickle as pickle
import time
#print "_NOT_ Loading the graph..."
#t0 = time.time()
#nodes = pickle.load(open('main/family_tree_inference/plain_graph3.pckl', 'rb'))
#print "Loaded in {:.2f} seconds.".format(time.time() - t0)
def search_path(xref1, xref2):
try:
xref1 = int(xref1)
xref2 = int(xref2)
ex... | ekQ/ancestryai | main/family_tree_inference/path_search.py | Python | mit | 4,883 |
import re
from typing import Optional, Dict, Any, List, Tuple, Mapping
from .config.sums import SumType, SumTypeMetaclass
from .util import maybe_dotted
import logging
log = logging.getLogger(__name__)
# A replacement marker in a pattern must begin with an uppercase or
# lowercase ASCII letter or an underscore, and... | avanov/solo | solo/configurator/url.py | Python | mit | 4,928 |
from .spatial import (
Spatial,
Container,
Exitable,
Exit,
Invisible,
Enterable,
Carriable,
Stackable,
)
from .dark import Dark
from .emotive import Emotive
from .sticky import Sticky
from .important import Important
from .wandering import Wandering
from .meta import Meta, Admin
from .na... | vreon/figment | examples/theworldfoundry/theworldfoundry/components/__init__.py | Python | mit | 337 |
import serial, time
#import RPi.GPIO as GPIO
ledPin = 16
#time.sleep(2)
print("Setting the GPIO pin modes and configuration. Sleeping for 5.")
# set the mode of the GPIO output pins
#GPIO.setmode(GPIO.BCM)
# configure LED pin
#GPIO.setup(ledPin, GPIO.OUT)
# setting it LOW will trigger the pin
#GPIO.output(ledPin... | mitmuseumstudio/RoboticLightBallet | attic/OldCode/piCommunication.py | Python | mit | 1,128 |
# encoding: utf-8
d = {}
'''
打开文件把数据读入到字典里面用ip,url,返回值组成元组作为key。
先把所有key赋空值,发现key在字典里面就把value加1。直到循环完成
'''
with open('nginx.log','r') as f:
for line in f.readlines():
linelist = line.strip().split(' ')
dfile = linelist[0],linelist[6],linelist[8]
d.setdefault(dfile,0)
d[dfile] = d.s... | 51reboot/actual_09_homework | 03/jinderui/logtj2.py | Python | mit | 751 |
from django.core.management.base import BaseCommand, CommandError
from cc.util import HeaderedRow
from cc.models import *
from urllib.parse import unquote
from collections import Counter
import os, stat, csv
import json
class Command(BaseCommand):
"""Takes mturk repsonse CSV from [source], and loads into database... | arunchaganty/contextual-comparatives | applesoranges/cc/management/commands/eval_load.py | Python | mit | 2,239 |
import unittest
from predicthq.endpoints.v1.events.schemas import EventResultSet, CalendarResultSet, CountResultSet, ImpactResultSet
from tests import with_mock_client, with_mock_responses, with_client
class EventsTest(unittest.TestCase):
@with_mock_client()
def test_search_params_underscores(self, client):
... | predicthq/sdk-py | tests/endpoints/v1/test_events.py | Python | mit | 9,780 |
def Uniform(min_, max_):
return {
'type' : 'Uniform',
'min' : min_,
'max' : max_,
}
class JobTask:
#---------------------------------------------
config = {
'description' : 'Default Description of a job',
'task_type' : 'normal',
... | guanying/mrperf | scripts/job.py | Python | mit | 2,996 |
# coding=utf-8
"""
The MIT License
Copyright (c) 2013 Mustafa İlhan
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, modi... | mustilica/tt-history | src/csv_utils.py | Python | mit | 2,048 |
import crypto
from crypto import CryptoError
import unittest
class TestCrypto(unittest.TestCase):
def test_xor(self):
self.assertEqual("\x00", crypto.xor("\x00", "\x00"))
self.assertEqual("\x01", crypto.xor("\x00", "\x01"))
self.assertEqual("\x00", crypto.xor("\x01", "\x01"))
self.a... | mlsteele/one-time-chat | device/test_crypto.py | Python | mit | 2,725 |
import argparse
import json
from pathlib import Path
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("manifests", metavar="m", nargs="+", help="Manifests to verify")
args = parser.parse_args()
def main():
for manifest_path in tqdm(args.manifests):
with open(manifest_path, "r"... | SeanNaren/deepspeech.pytorch | data/verify_manifest.py | Python | mit | 770 |
#!/data/project/nullzerobot/python/bin/python
import wtforms.validators
from wtforms.validators import *
from wtforms.validators import ValidationError
from messages import msg
import re
##############################
class _Required(Required):
def __init__(self, *args, **kwargs):
if not kwargs.get('mess... | nullzero/wpcgi | wpcgi/package/p_form/p_validators.py | Python | mit | 1,995 |
import os
from lxml import html
import requests
import re
import time
#import config file
import config
#import log
from log import Log
#import common
from common import Common
#import json_manager
from json_manager import Json_Manager
log = Log()
com = Common()
jm = Json_Manager()
| Informationretrieval2016/furnito | furnito_crawler/__init__.py | Python | mit | 284 |
import setuptools
from kdn_pal.version import Version
setuptools.setup(name='kdn-pal',
version=Version('0.1.0').number,
description='The KDNuggets news reader',
long_description=open('README.md').read().strip(),
author='Oskar Jarczyk',
... | oskar-j/kdn-pal | setup.py | Python | mit | 667 |
from mamba import describe, context, before
from sure import expect
from doublex import *
from spec.object_mother import *
from mamba import reporter
from mamba.example import PendingExample
with describe(PendingExample) as _:
@before.each
def create_pending_example_and_reporter():
_.was_run = Fals... | jaimegildesagredo/mamba | spec/pending_example_spec.py | Python | mit | 742 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'TemplateAvaliacao.autor'
db.add_column('Avaliacao_templateavaliacao', 'autor', self.gf('dj... | arruda/amao | AMAO/apps/Avaliacao/migrations/0009_auto__add_field_templateavaliacao_autor.py | Python | mit | 7,591 |
import os
import six
from collections import defaultdict, OrderedDict
from geodata.address_expansions.address_dictionaries import address_phrase_dictionaries
from geodata.encoding import safe_decode, safe_encode
from geodata.i18n.unicode_paths import DATA_DIR
from geodata.text.normalize import normalized_tokens, norm... | openvenues/libpostal | scripts/geodata/address_expansions/gazetteers.py | Python | mit | 10,291 |
__version__ = '0.0.1'
__all__ = ['decorator', 'postgresql']
from . import *
| hfukada/py-decogres | decogres/__init__.py | Python | mit | 77 |
"""
WSGI config for remakery project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... | symroe/remakery | remakery/wsgi.py | Python | mit | 1,138 |
# Lesson 6
from random import randint
# Generates a random integer in the range of [0, 10] (inclusive)
r = randint(0, 10)
print(r)
| JonTheBurger/python_class | chapter 3/lessons/rand.py | Python | mit | 132 |
import pytest
from firedrake import *
import thetis.utility as utility
import numpy as np
@pytest.fixture(scope="module")
def mesh2d():
return UnitSquareMesh(5, 5)
@pytest.fixture(scope="module")
def mesh(mesh2d):
fs = utility.get_functionspace(mesh2d, 'CG', 1)
bathymetry_2d = Function(fs).assign(1.0)
... | tkarna/cofs | test/operations/test_operations_2d-3d.py | Python | mit | 6,979 |
API_DOCS = 'https://api.coala.io/en/latest'
USER_DOCS = 'https://docs.coala.io/en/latest'
MAX_MSG_LEN = 1000
MAX_LINES = 20
PRIVATE_CMDS = ['assign_cmd', 'create_issue_cmd', 'invite_cmd', 'mark_cmd',
'pr_stats', 'unassign_cmd', 'pitchfork', 'the_rules', 'wa',
'answer', 'lmgtfy', 'ghet... | coala/corobo | plugins/constants.py | Python | mit | 349 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
The MIT License
Copyright (c) 2010 Olle Johansson
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 ... | ollej/Twippy | src/plugins/Plugin.py | Python | mit | 5,739 |
"""Test cases for mupub.commands.check
"""
import os
from unittest import TestCase
from .tutils import PREFIX
import mupub
TEST_DATA = 'data'
class CheckTest(TestCase):
def test_basic_check(self):
"""Basic check command"""
basic = os.path.join(os.path.dirname(__file__),
... | MutopiaProject/mupub | mupub/tests/test_check.py | Python | mit | 645 |
import abjad
import collections
from abjad.tools import abctools
from abjad.tools import mathtools
from abjad.tools import rhythmmakertools
class MusicSpecifierSequence(abctools.AbjadValueObject):
r'''A music specifier sequence.
::
>>> sequence_a = consort.MusicSpecifierSequence(
... mus... | josiah-wolf-oberholtzer/consort | consort/tools/MusicSpecifierSequence.py | Python | mit | 5,595 |
##########################################################################
# #
# Use Case Script for NGC 5921 #
# #
# Converted by STM 2... | Astroua/casa-deploy | test_ngc5921_demo.py | Python | mit | 36,364 |
from .Deserializer import Deserializer
from .RateLimiter import RateLimiter
from .Handlers import (
DeprecationHandler,
DeserializerAdapter,
DictionaryDeserializer,
RateLimiterAdapter,
SanitationHandler,
ThrowOnErrorHandler,
TypeCorrectorHandler,
)
from .Handlers.RateLimit import BasicRate... | pseudonym117/Riot-Watcher | src/riotwatcher/TftWatcher.py | Python | mit | 2,663 |
import time
import amfast
import flex_messages as messaging
class Subscription(object):
def __init__(self, connection_id=None, client_id=None, topic=None):
self.connection_id = connection_id
self.client_id = client_id
self.topic = topic
class SubscriptionManager(object):
"""Receives a... | limscoder/amfast | amfast/remoting/subscription_manager.py | Python | mit | 8,907 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 31 16:58:52 2017
@author: marshals
"""
import os
from opconfig import opconfig
class opconfig2script(opconfig):
def __init__(self, *args, **kwargs):
super(opconfig2script, self).__init__(*args, **kwargs)
def opconfig2scrip... | cindy0123/duty-util01 | pyop4/opbase/opconfig2script.py | Python | mit | 3,478 |
from yahoo_finance import utils
from collections import OrderedDict
import json
def test_write_dict_to_csv():
entry1 = OrderedDict([('Field1','entry1-field1-value'), ('Field2','entry1-field2-value')])
entry2 = OrderedDict([('Field1','entry2-field1-value'), ('Field2','entry2-field2-value')])
test_dict = Ord... | howsunjow/YahooFinance | tests/test_utils.py | Python | mit | 1,293 |
#!/usr/bin/python3
import argparse
import datetime
import os
from subprocess import Popen, PIPE
def process_file(tldr_filename, manpage_filename):
tldr_dir, tldr_file = os.path.split(tldr_filename)
with open(tldr_filename) as inp:
data = inp.readlines()
# Extracting program name
_, ... | JIghtuse/manpages-tldr | tools/tldr_page_to_manpage.py | Python | mit | 2,238 |
"""
Brian T. Bailey
ITM 513 - MP4
MP4 Main Driver
"""
FTPHOST = 'glenellyn.rice.iit.edu'
FTPUSER = 'bbailey4'
FTPPSSWD = '@4clibri' | briantbailey/ITM-513 | mp4/src/mp4domain/ftpconfig.py | Python | mit | 132 |
"""Models for resources application."""
from django.db import models
from django.contrib.gis.db import models as geomodels
from django.urls import reverse
from utils.get_upload_filepath import (
get_event_organiser_upload_path,
get_event_sponsor_upload_path,
get_event_series_upload_path,
)
from autoslug i... | uccser/cs4teachers | dthm4kaiako/events/models.py | Python | mit | 8,057 |
'''Input arr is 2D. Make sure output is a slice of original array.
'''
from __future__ import division
import numpy as np
from functools import partial
from utils.array_handling import extend_true, skip_outside_frame_start_to_end
import pandas as pd
from collections import OrderedDict
def iterate_sites(func):
def... | braysia/covertrace | covertrace/ops_filter.py | Python | mit | 2,239 |
def hangman(string):
sofar = len(string)*["_"]
print(sofar)
i = 0
guess = input('Guess a letter')
while i < len(string):
if string[i] == guess:
print("Got one")
sofar[i] = guess
print(sofar)
guess = input('Guess again')
i = i + 1
hangman("hello")
| bensk/CS9 | Code Examples/Hangman.py | Python | mit | 271 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-07 02:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('master', '0002_auto_20160605_2201'),
]
operations = [
migrations.AlterField(... | j-windsor/thebeau | master/migrations/0003_auto_20160607_0252.py | Python | mit | 453 |
# 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 ... | rjschwei/azure-sdk-for-python | azure-mgmt-eventhub/azure/mgmt/eventhub/models/event_hub_management_client_enums.py | Python | mit | 1,527 |
__author__ = 'cook'
import time
from zones import *
thermo1 = '28-0000065bb6cd'
# The second entry in the value list should be the GPIO pin the zone is connected to
zones = {thermo1: ['whole house', 10]}
time_out = 30*60 # half an hour in seconds
zone = {}
# If there is an error reading the temperature send an err... | darwyncook/thermostat | thermostat.py | Python | mit | 779 |
# -*- coding: utf-8 -*-
#
import helpers
def plot():
from matplotlib import pyplot as pp
import numpy as np
fig = pp.figure()
an = np.linspace(0, 2*np.pi, 100)
pp.subplot(221)
pp.plot(3*np.cos(an), 3*np.sin(an))
pp.title('not equal, looks like ellipse', fontsize=10)
pp.subplot(222)... | danielhkl/matplotlib2tikz | test/test_subplot4x4.py | Python | mit | 959 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# A Solution to "Roman numerals" – Project Euler Problem No. 89
# by Florian Buetow
#
# Sourcecode: https://github.com/fbcom/project-euler
# Problem statement: https://projecteuler.net/problem=89
def load_roman_numerals(filename):
with open(filename) as f:
n... | fbcom/project-euler | 089_roman_numerals.py | Python | mit | 2,513 |
from django import forms
from admin_tools.dashboard.models import DashboardPreferences
class DashboardPreferencesForm(forms.ModelForm):
"""
This form allows the user to edit dashboard preferences. It doesn't show
the user field. It expects the user to be passed in from the view.
"""
def __init__... | noxan/django-admin-tools | admin_tools/dashboard/forms.py | Python | mit | 924 |
"""Module used to handle a API Server."""
import logging
import os
import sys
import warnings
import zipfile
from datetime import datetime
from urllib.error import HTTPError, URLError
from urllib.request import urlopen, urlretrieve
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from ... | renanrodrigo/kytos | kytos/core/api_server.py | Python | mit | 10,184 |
def PE_013():
f = open ('PE_013_input.txt', 'r')
length = 50
curr = length - 1
result = ""
numbers = []
# line[:-1] to get rid of \n
for line in f:
numbers.append(line[:-1])
carry = 0
for i in xrange(0, length):
for num in numbers:
# add one decimal pl... | NickDarling/ProjectEuler | PE_013.py | Python | mit | 524 |
"""AuditEvent: add data['draftId'] partial index
Revision ID: 1390
Revises: 1380
Create Date: 2019-08-06 10:24:00.359631
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1390'
down_revision = '1380'
def upgrade():
op.create_index(
'idx_audit_even... | alphagov/digitalmarketplace-api | migrations/versions/1390_auditevent_add_data_draftid_partial_index.py | Python | mit | 602 |
# -*- coding: utf-8 -*-
#download http://www.modelx.org/category/graphis-collection-2002-2016/
import urllib
import urllib.request
from lxml import etree
import re,os,time,random
import threading
def loadCategory(catpage,catname,header):
req = urllib.request.Request(catpage, headers=header)
html = urllib.reque... | machsix/personal-scripts | Scrapy/downloadgaphis.py | Python | mit | 4,145 |
"""
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: Fa... | franklingu/leetcode-solutions | questions/two-sum-iv-input-is-a-bst/Solution.py | Python | mit | 1,223 |
# copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of logilab-astng.
#
# logilab-astng is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as publis... | tlksio/tlksio | env/lib/python3.4/site-packages/logilab/astng/raw_building.py | Python | mit | 13,584 |
from flask import Flask, render_template, request, redirect
from werkzeug.utils import secure_filename
from genlist import classes
import os, sys, time
import signal
import requests
import socket
import requests
from PIL import Image
from io import BytesIO
from stepper import Stepper
from pin_control import PinControl
... | Roboartitsts/PiPaintingServer | app.py | Python | mit | 5,618 |
from django.config import settings
def debug(request):
return {
'DEBUG': settings.DEBUG
}
| WillsB3/Sim-Checklist | simchecklist/core/context_processors.py | Python | mit | 108 |
import re
# Matches strings of the form '## (##, ##):##, (##,##):##, (##, ##): ##'
# The first number is the total number of vertices,
# following that are pairs of ints representing edges, with each pair having a corresponding real-number weight.
graph_re = r"\d+\s+\(\d+,?\s*\d+\):\s*([-+]?(\d+(\.\d*)?|\.\d+))(,\s+\... | dwgill/SSSP-algorithm | src/graph.py | Python | mit | 4,324 |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
class Node(object):
''' Create node element with default previous pointer. '''
def __init__(self, value, next=None):
''' Previous pointer default to none. '''
self.val = value
self.next ... | constanthatz/data-structures | linked_list.py | Python | mit | 2,348 |