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/env python
"""
prints, based on input:
current day
previous day
next day
barbour
29-Sep-2011
"""
import sys
import datetime
lsarg=len(sys.argv)
funcs={"previous":-1, "current":0, "next":1}
def yj2dt(y,jd):
return datetime.date... | ActiveState/code | recipes/Python/577883_Printing_current_next_or_previous/recipe-577883.py | Python | mit | 1,620 |
# Django settings for OpenEcho project.
import os.path
SITE_SRC_ROOT = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ora... | robneville73/OpenEcho | settings.py | Python | mit | 3,273 |
from api import create_app
app = create_app()
if __name__ == "__main__":
app.run(debug=True)
| open-city/school-admissions | runserver.py | Python | mit | 99 |
from flask import request, render_template
import web.util.tools as tools
import lib.es as es
def get(p):
if request.method == "POST":
# save configuration
set_all_conf(p['host'])
return tools.redirect(request.referrer)
# get list authentication plugins
p['login_modules'] = get_log... | unkyulee/elastic-cms | src/web/modules/admin/controllers/login_screen/control.py | Python | mit | 555 |
from six import add_metaclass
from .statsd_dep import StatsD
class ServiceBaseMeta(type):
"""Metaclass that adds the `_name` attribute to any `statsd_dep.StatsD`
object found in the attributes.
"""
def __new__(cls, name, bases, attrs):
for name, obj in attrs.items():
if isinsta... | thehardway15/nameko-statsd | nameko_statsd/bases.py | Python | mit | 517 |
# coding=utf-8
#
# Autocomplete feature for admin panel
#
import six
import operator
from six.moves import reduce
import django
from django.http import HttpResponse, HttpResponseNotFound
from django.conf import settings
from django.db import models
from django.db.models.query import QuerySet
from django.utils.encoding... | jpadilla/django-extensions | django_extensions/admin/__init__.py | Python | mit | 7,426 |
import json
import models
from test_api import StashboardTest
class PublicEventsTest(StashboardTest):
def setUp(self):
super(PublicEventsTest, self).setUp()
service = models.Service(name="Foo", slug="foo", description="Hello")
service.put()
def test_get(self):
response = self.... | guardian/stashboard | tests/test_rest_events.py | Python | mit | 6,728 |
# -*- coding: utf-8 -*-
"""
pygments.lexers._openedge_builtins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Builtin list for the OpenEdgeLexer.
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
OPENEDGEKEYWORDS = (
'ABSOLUTE',
'ABS',
... | tmm1/pygments.rb | vendor/pygments-main/pygments/lexers/_openedge_builtins.py | Python | mit | 48,362 |
"""Functions related to plotting maps. """
from collections import namedtuple
from matplotlib import pyplot as plt
_CartopyError = ImportError(
"You have to install `cartopy` to use functions located in `typhon.plots.maps`."
)
def worldmap(
lat,
lon,
var=None,
fig=None,
ax=None,
project... | atmtools/typhon | typhon/plots/maps.py | Python | mit | 5,317 |
# Copyright (C) 2016 Deloitte Argentina.
# This file is part of CodexGigas - https://github.com/codexgigassys/
# See the file 'LICENSE' for copying permission.
class Module():
def __init__(self, lib=None):
self.library = lib
if(lib is None):
self.already_initialized = False
el... | codexgigassys/codex-backend | src/Modules/Module.py | Python | mit | 508 |
from bayesnet.tensor.constant import Constant
from bayesnet.tensor.tensor import Tensor
from bayesnet.function import Function
class Negative(Function):
"""
element-wise negative
y = -x
"""
def forward(self, x):
x = self._convert2tensor(x)
self.x = x
if isinstance(self.x, ... | ctgk/BayesianNetwork | bayesnet/math/negative.py | Python | mit | 590 |
import os
from infrastructure import dotnetcore
def run(context):
solution_path = os.path.join(
context.sourcePath, '%s.sln' % context.settings.get('application_name'))
print 'Building %s' % solution_path
dotnetcore.build(solution_path)
| kunyo/pybuild | tasks/dotnet_build.py | Python | mit | 259 |
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
ipadr = get_ip_address('eth0') # '192.168.xx... | yasokada/python-151113-lineMonitor | toLearn/151125b.py | Python | mit | 340 |
from __future__ import print_function
from fabric.api import run
from fabric.api import env
from fabric.api import execute
from fabric.api import prompt
from fabric.api import put
from fabric.api import sudo
from fabric.utils import abort
from fabric.contrib.console import confirm
from fabric.contrib.project import upl... | sazlin/reTOracle | fabfile.py | Python | mit | 11,994 |
import utilities
from essentials import file_structure, save_file, load_file, confirm_values, pretty_values, value_relationships
import actions
import story
import atexit
import random
__ver__ = '0.01'
def game_init():
file_structure()
save_data = load_file()
save_data = confirm_values(save_data)
save... | shakna-israel/AColdWalk | AColdWalk.py | Python | mit | 2,791 |
import pytest
import settings
from jahia2wp import export
TEST_HOST = 'localhost'
TEST_SITE = 'dcsl'
SITE_URL_SPECIFIC = "https://{0}/{1}".format(TEST_HOST, TEST_SITE)
OPENSHIFT_ENV = 'test'
ENVIRONMENT = "local"
@pytest.fixture(scope="module")
def wp_exporter():
wp_exporter = export(
site="dcsl",
... | epfl-idevelop/jahia2wp | functional_tests/_test_exporter.py | Python | mit | 1,771 |
from __future__ import absolute_import, unicode_literals
import json
from django.conf import settings
from django.utils.encoding import force_text
from debug_toolbar.middleware import DebugToolbarMiddleware as DTM
class DebugToolbarMiddleware(DTM):
def process_response(self, request, response):
content... | zh012/djrest | djrest/patches/ddt.py | Python | mit | 929 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import datetime
import pytest
from owlmixin.util import load_yaml, dump_json, load_json
from jumeaux.addons.res2dict.xml import Executor
from jumeaux.models import Response, Res2DictAddOnPayload
NORMAL_BODY = """<?xml version="1.0"?>
<catalog>
<book id="bk001">
... | tadashi-aikawa/gemini | tests/addons/res2dict/test_xml.py | Python | mit | 3,737 |
#!/usr/bin/env python
from __future__ import division
import numpy as np
import modest
import logging
import scipy
import prior
import reg
import multiprocessing as mp
from slip import steps_and_ramps
from modest import funtime
logger = logging.getLogger(__name__)
def state_parser(Nst,Ns,Ds,Nv,Nx,Dx):
out = {}
o... | treverhines/PSGI | psgi/parameterized.py | Python | mit | 16,236 |
# create files
# WORKING/transactions-subset2-train.pickle
# WORKING/transactions-subset2-test.pickle
#
# The test data consists of a 10% random sample of all the data.
#
# Unlike the R version, the data are not stratified by sale month.
# import built-ins and libraries
import numpy as np
import pandas as pd
import pd... | rlowrance/re-local-linear | transactions-subset2-test.py | Python | mit | 3,987 |
import bsddb
from MenuCommand import *
class IncluiCommand(MenuCommand):
def __init__(self, op, objeto):
if op == 1:
self._nome = objeto.getNome()
self._cod = objeto.getCod()
if op == 2:
self._nome = objeto.getNome()
self._cod = objeto.getCod()
... | Mat-Bit/PRA-Trabalho_Final | IncluiCommand.py | Python | mit | 2,323 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.centralnic.com/no.com/status_available
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser... | huyphan/pyyawhois | test/record/parser/test_response_whois_centralnic_com_no_com_status_available.py | Python | mit | 2,051 |
from __future__ import print_function
import sys
import os
import time
import pyautogui
from pytribe import EyeTribe
import serial
# # # # #
# PREPARING CONNECTIONS
# Setting up usb serial connection
#ser = serial.Serial('/dev/cu.usbmodem1411', 9600) #mac
ser = serial.Serial('/COM3', 9600) #windows
# St... | luojxxx/handsfree | PyTribe-master/runHandsfree.py | Python | mit | 1,593 |
import logging
import os
from unittest import TestCase
from intent.igt.consts import ODIN_LANG_TAG, ODIN_JUDGMENT_ATTRIBUTE, ODIN_TRANS_TAG
from xigt.codecs import xigtxml
from intent.igt.rgxigt import RGCorpus, retrieve_normal_line, retrieve_lang_phrase_tier, retrieve_trans_phrase
from intent.interfaces.stanford_par... | rgeorgi/intent | intent/tests/parsetests.py | Python | mit | 6,373 |
'''
Created by auto_sdk on 2013.04.12
'''
from top.api.base import RestApi
class FenxiaoRefundGetRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.query_seller_refund = None
self.sub_order_id = None
def getapiname(self):
return 'taoba... | colaftc/webtool | top/api/rest/FenxiaoRefundGetRequest.py | Python | mit | 343 |
import _plotly_utils.basevalidators
class AValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="a", parent_name="carpet", **kwargs):
super(AValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwar... | plotly/python-api | packages/python/plotly/plotly/validators/carpet/_a.py | Python | mit | 425 |
def gcd(a, b):
while (a != 0):
a, b = b%a, a
return b
#print (gcd(12,15))
def findModInverse(a , m):
if gcd(a,m) != 1:
return None
u1,u2,u3 = 1, 0, a
v1,v2,v3 = 0, 1, m
while v3 != 0:
q = u3 // v3
u1 ,u2 , u3 ,v1 , v2, v3 = v1 , v2 , v3 , (u1 - q*v1), (u2 - q*v2), (u3 - q*v3)
ret... | AlMikFox3/Ciphers | AffineCipher/mathmeth.py | Python | mit | 361 |
# Begin: Python 2/3 compatibility header small
# Get Python 3 functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
from future.utils import raise_with_traceback, raise_from
# catch exception with: except Exception as e
from builtins import range, map, zip, filter
from i... | pikinder/nn-patterns | nn_patterns/utils/misc.py | Python | mit | 3,270 |
# B O O L E A N S
from sys import argv
_,a1 = argv
##if a1 is str:
x = 9
x = 5
x == 5
x != 5
not (x == 5)
#11 and 12 are saying the same thing
x <= 5
x is int
##even = x % 2 == 0
True = True or False
True = True or True
True = True and True
False = True and False
if x == 5:
print "B"
else:
print "A"
... | chrisortman/CIS-121 | k0459866/Lessons/ex11.py | Python | mit | 724 |
from django.conf.urls import *
from .views import UserViewSet
from rest_framework.routers import DefaultRouter
# [TODO] - needs to move these to user api directory
urlpatterns = [
url(r'^users/(?P<pk>[0-9]+)/relationships/$', UserViewSet.as_view({'get':'relationships'}), name="relationships"),
url(r'^users/(?P<pk... | masanorinyo/rest_django_api_boilerplate | api/v2/users/urls.py | Python | mit | 560 |
# File generated from our OpenAPI spec
from __future__ import absolute_import, division, print_function
from stripe.api_resources.abstract import SingletonAPIResource
class Balance(SingletonAPIResource):
OBJECT_NAME = "balance"
| stripe/stripe-python | stripe/api_resources/balance.py | Python | mit | 235 |
import pickle
class PickleStore(object):
def __init__(self):
self.__store = {}
def store_instance_count(self, in_type, count):
self.__store[in_type] = count
def get_instance_count(self, in_type):
if in_type in self.__store:
return self.__store[in_type]
else:
... | Weissger/TST.InstanceCounter | src/PickleStore/PickleStore.py | Python | mit | 547 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('parkkeeper', '0003_auto_20151103_1330'),
]
operations = [
migrations.CreateModel(
name='Credential',
... | telminov/django-park-keeper | parkkeeper/migrations/0004_auto_20151103_1726.py | Python | mit | 1,858 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='MemoryLog',
fields=[
('id', models.AutoField(se... | polarkac/PiMonitor | monitor/migrations/0001_initial.py | Python | mit | 1,506 |
#List of all apps and menu to open them
#copyright (c) 2015 Tyler Spadgenske
#GPL License
###############################
#To be packaged with stock TYOS
###############################
import sys, time
import pygame
class Run():
def __init__(self, fona):
#Stuff to follow app protocol
self.exit = ... | spadgenske/TYOS | apps/app-list/app-list.py | Python | mit | 2,493 |
# -*- coding: utf-8 -*-
from django.views import generic
from .models import Trip
# Create your views here.
class IndexView(generic.ListView):
template_name = 'trips/index.html'
context_object_name = 'latest_trip_list'
def get_queryset(self):
"""
Return the last five published questions (... | renanalencar/hermes | trips/views.py | Python | mit | 1,677 |
# 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-web/azure/mgmt/web/models/app_service_certificate.py | Python | mit | 2,845 |
def foo():
print "Goodbye, P1.foo!" | codeboardio/mantra | test/test_resources/python/py_several_files_folder/Root/p1/b.py | Python | mit | 36 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# A Hangman game programmed in Python 3.
#
# Copyright (c) 2013 K Kollmann <code∆k.kollmann·moe>
# License: http://opensource.org/licenses/MIT MIT
#
# You need to have Python 3.x installed to run this game.
# The game's objective is to guess a word, letter by letter.
# ... | kerstin/Hangman | hangman.py | Python | mit | 21,401 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "map_editor.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| tomaslu/map_editor | manage.py | Python | mit | 253 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function
from ._common import PokerEnum
class PokerRoom(PokerEnum):
STARS = 'PokerStars', 'STARS', 'PS'
FTP = 'Full Tilt Poker', 'FTP', 'FULL TILT'
PKR = 'PKR', 'PKR POKER'
class Currency(PokerEnum):
... | Seanmcn/poker | poker/constants.py | Python | mit | 2,063 |
#!/usr/bin/env python3
import csv
import os
import psycopg2
import sys
argv = sys.argv[1:]
user = os.environ['DB_USER']
password = os.environ['DB_PASSWORD']
conn = psycopg2.connect(dbname='iosr', user=user, password=password)
cursor = conn.cursor()
sql_template = 'INSERT INTO public.airports ("year", "week", "airp... | salceson/iosr-distributed-data-processing | scripts/import_airports.py | Python | mit | 751 |
'''
Plotting modules
'''
from halotools.sim_manager import CachedHaloCatalog
import os.path as path
from Corrfunc import _countpairs
from Corrfunc.utils import read_catalog
from halotools.empirical_models.factories.mock_helpers import three_dim_pos_bundle
from halotools.mock_observables.catalog_analysis_helpers import... | mjvakili/gambly | code/plot_occupation.py | Python | mit | 18,371 |
#!/usr/bin/env python
# Import some frameworks
import os
import time
import RPi.GPIO as GPIO
from datetime import datetime
d = datetime.now()
initYear = "%04d" % (d.year)
initMonth = "%02d" % (d.month)
initDate = "%02d" % (d.day)
initHour = "%02d" % (d.hour)
initMins = "%02d" % (d.minute)
# Define the location whe... | vcp-scoutlab/vcp-scoutlab.github.io | timelapse/appendix/zeitraffer.py | Python | mit | 1,818 |
"""A simple IRC bot for Twitch.
First things first, you need the Username and OAuth token of the account you
want to login with. Typically this would be for your bot, but you can login with
any Twitch account.
You can get your OAuth token from: http://twitchapps.com/tmi/
A standard bot would look like this:
use... | VoxelDavid/twitch-bot | twitchbot/bot.py | Python | mit | 4,141 |
import numpy as np
import scipy.stats as spts
from openpnm.utils import logging, Docorator
docstr = Docorator()
logger = logging.getLogger(__name__)
__all__ = [
'random',
'weibull',
'normal',
'generic_distribution',
'match_histogram',
]
@docstr.get_sections(base='models.misc.stats',
... | PMEAL/OpenPNM | openpnm/models/misc/statistical_distributions.py | Python | mit | 6,695 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_likelihood
----------------------------------
Tests of likelihood module
"""
import unittest
import numpy as np
import scipy.linalg as sl
from enterprise.pulsar import Pulsar
from enterprise.signals import gp_signals, parameter, selections, signal_base, utils... | nanograv/enterprise | tests/test_likelihood.py | Python | mit | 13,121 |
class Arco():
def __init__(self, origem, destino, valor):
self.valor = valor
self.vertices = (origem, destino)
def __hash__(self):
return hash(self.vertices + (self.valor,))
def __eq__(self, arco):
return (self.valor,) + self.vertices == (arco.valor,) + arco.vertices
... | Julianosantosb/dataStructure | grafoDijkistra.py | Python | mit | 13,491 |
from bge import logic
import mathutils as mt
from Player import Player, Animation
import nilutils as nl
import aud
class Shooting(nl.Component):
def __init__(self, gobj):
super().__init__(gobj)
#sound
self.device = aud.device()
sound = logic.expandPath("//sounds/yu_gun.ogg")
factory = aud.Factory(s... | Lucrecious/Aphtar-Yu | Yu.py | Python | mit | 1,160 |
'''
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another sol... | franklingu/leetcode-solutions | questions/maximum-subarray/Solution.py | Python | mit | 1,285 |
import re
SYMBOLS = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
def human2bytes(s):
"""
>>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824
"""
symbols = SYMBOLS
letter = s[-1:].strip().upper()
num = s[:-1]
assert re.match(r'\d+(\.\d+)?', num) is not None and lette... | fennm/pyVsphereInflux | lib/pyVsphereInflux/tools/humanreadable.py | Python | mit | 517 |
import pickle
from os import getcwd, path
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import HashingVectorizer, TfidfTransformer
__location__ = path.realpath(path.join(getcwd(), path.dirname(__file__)))
class Classifier():
"""
Multi... | publicscience/brain | app/brain/classifier.py | Python | mit | 2,366 |
# import_export_endorsements/controllers.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from import_export_batches.models import BatchManager
import wevote_functions.admin
from wevote_functions.functions import positive_value_exists
logger = wevote_functions.admin.get_logger(__name__)
def retrieve... | jainanisha90/WeVoteServer | import_export_endorsements/controllers.py | Python | mit | 1,509 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class InteractionsConfig(AppConfig):
name = 'apps.interactions'
def ready(self):
from actstream import registry
registry.register(*self.get_models())
| aldwyn/effigia | apps/interactions/apps.py | Python | mit | 276 |
# Copyright (c) 2012, Ryan Kelly.
# All rights reserved; available under the terms of the MIT License.
"""
playitagainsam.util: utility functions for interacting with terminals
======================================================================
"""
import os
import sys
import tty
import pty
import termios
impo... | rfk/playitagainsam | playitagainsam/util.py | Python | mit | 6,470 |
import argparse
from amber.amber16.cpptraj.command import exec_cpptraj
from utilities.path import which
from tempfile import mkstemp
import numpy
from pdb import set_trace as tr
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="""Obtain MSD(t) averaged over different chunks of the trajectory... | jmborr/confinedBSA | simulation/silica/cristobalite/confineBSA/poretop/yesbonds/wholesystem/diffusion_t0average.py | Python | mit | 2,748 |
import random
from datetime import datetime
from itertools import cycle
from functools import partial
import numpy as np
import tensorflow as tf
try:
from core.nn_trainer import train_policy_gradients
from core.nn import load_network, create_network
except ImportError:
# executing as __main__
import o... | giuliocatte/Gamer | connectfour/nn.py | Python | mit | 4,950 |
'''
In this lab we will create a program that can encrypt and decrypt strings
using a simple algorithm.
The algorithm we will use is the following:
* To encrypt a string, we reverse it and add 1 to the ASCII code for each
character. For example, if we take the word:
python
When we encrypt the word it becomes... | r-martin-/Code_College | PythonProgramming/encrypt.py | Python | mit | 3,327 |
from checker import *
| theopolis/friendly-heartbleed | friendlybleed/__init__.py | Python | mit | 22 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-08-08 16:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('agenda', '0014_auto_20180808_1758'),
]
operations = [
migrations.AlterField... | MilyMilo/sci-organizer | agenda/migrations/0015_auto_20180808_1804.py | Python | mit | 618 |
from .base_test import BaseTest, MockSendGridAPIClientRequest
import os
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
from StringIO import StringIO
except ImportError: # Python 3
from io import StringIO
import sendgrid
from sendgrid.client import SendGridAPIClient
from sen... | Khan/sendgrid-python | test/test_asm_global_suppressions.py | Python | mit | 1,896 |
from flask import abort, request
from inspect import getargspec
from bson.json_util import dumps
from bson.objectid import ObjectId
from good import Invalid
import sys
import time
import threading
def lexic_join(expressions):
*most, last = expressions
if most:
return ', '.join(str(e) for e in most) + '... | Daerdemandt/dota2league-tracker | dota2league-tracker/glue.py | Python | mit | 6,933 |
import networkx as nx
import EoN
import matplotlib.pyplot as plt
r'''This code demonstrates a change in parameters at time t1. To do this, it
will run to time t1 and then stop, and restart with the new parameters.
To demonstrate that stopping and restarting doesn't do anything weird, we first
run to time t0, stop, ... | springer-math/Mathematics-of-Epidemics-on-Networks | docs/examples/changing_parameters/SIS_change_tau.py | Python | mit | 3,017 |
from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse_lazy
from django.views.generic import CreateView, FormView, RedirectView, TemplateView
from .forms import RegistrationForm, LoginForm
from django.contrib.auth.models import User
... | pyladieshre/pyladies | accounts/views.py | Python | mit | 2,031 |
"""Calculate the square cube of a float number"""
__author__ = 'Nicola Moretto'
__license__ = "MIT"
def squareRootBisection(x, precision):
'''
Calculate the square root of a float number through bisection method with given precision
:param x: Float number
:param precision: Square root precision
:r... | nicola88/edx | MITx/6.00.1x/Week-2/Lecture-3/squareRootBisection.py | Python | mit | 671 |
class NoteModel(Query):
def __init__(self, db):
self.db = db
self.table_name = "note"
super(NoteModel, self).__init__() | yiyangyi/cc98-tornado | model/note.py | Python | mit | 147 |
# coding=utf-8
'''
Problem 46
20 June 2003
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 + 2×1^2
15 = 7 + 2×2^2
21 = 3 + 2×3^2
25 = 7 + 2×3 2
27 = 19 + 2×2^2
33 = 31 + 2×1^2
It turns out that the conjecture was false... | arturh85/projecteuler | python/src/problem046.py | Python | mit | 1,549 |
a = int(raw_input())
b = int(raw_input())
m = int(raw_input())
# a ** b
print (pow(a, b))
print (pow(a, b, m)) | ehouarn-perret/EhouarnPerret.Python.HackerRank | HackerRank/6 - Python/Introduction/6 - Power - Mod Power.py | Python | mit | 111 |
from typing import Dict
from hearthstone import enums
GameTagsDict = Dict[enums.GameTag, int]
| HearthSim/python-hearthstone | hearthstone/types.py | Python | mit | 97 |
import requests
from bs4 import BeautifulSoup
import urllib.parse
import backoff
import csv
import datetime
import dateutil.parser
import argparse
from typing import List, NewType, Tuple
AbsoluteUrl = NewType("AbsoluteUrl", str)
RelativeUrl = NewType("RelativeUrl", str)
IsoDateStr = NewType("IsoDateStr", str)
Path = ... | PaulKlinger/Enhance-GoodReads-Export | enhance_goodreads_export.py | Python | mit | 9,679 |
from unittest import skip
from selenium.common.exceptions import NoSuchElementException
from functional_tests.base import FunctionalTest
class AdminTest(FunctionalTest):
fixtures = ['accounts/fixtures/users.json', 'matches/fixtures/data.json']
@skip
def test_admin_can_add_matches(self):
# Alice... | asyler/betleague | functional_tests/test_admin.py | Python | mit | 1,781 |
"""gdsfactory simphony circuit simulation plugin"""
try:
from simphony.tools import freq2wl, wl2freq
except ImportError:
print("To install simphony plugin make sure you `pip install gdsfactory[full]`")
import gdsfactory.simulation.simphony.components as components
from gdsfactory.simulation.simphony.add_gc im... | gdsfactory/gdsfactory | gdsfactory/simulation/simphony/__init__.py | Python | mit | 1,197 |
#!/usr/bin/env python
from math import sqrt
import time
def factors(n):
return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(sqrt(n)) + 1) if n % i == 0)))
def main():
start_time = time.time()
counter = 0
TriangleNumber = 0
while True:
counter += 1
Triangle... | martinnj/ProjectEuler | python/problem12.py | Python | mit | 608 |
import climate
import theanets
import numpy as np
from sklearn.cross_validation import train_test_split
from os import path
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
import platform
from scipy.ndimage.filters import gaussian_filter
from mpl_toolkits.mplot3d import Axes3D
def load... | mwalton/artificial-olfaction | python/gsNN.py | Python | mit | 4,723 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-06-22 18:12
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sos', '0011_auto_20170620_2325'),
]
operations = [
migrations.RenameField(
... | sprintbiz/sos | sos/migrations/0012_auto_20170622_2012.py | Python | mit | 434 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from iip_processing_app import views
admin.autodiscover()
urlpatterns = [
url( r'^admin/', include(admin.site.urls) ),
u... | birkin/iip_processing_project | config/urls.py | Python | mit | 1,026 |
# abstractions for LED strip
import time
import colorsys
import random as Random
from neopixel import *
# LED strip configuration:
# LED_COUNT = 300 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
## LED_PIN = 10 # GPIO pin connected to the pi... | ethanacm/the_snake_lights | StrandMethods.py | Python | mit | 5,211 |
#---------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#---------------------------------------------------------------------... | BurtBiel/azure-cli | src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/mgmt_avail_set/lib/__init__.py | Python | mit | 840 |
"""
"""
import settings
from tornado.web import HTTPError
try:
from urllib import urlencode # py2
except ImportError:
from urllib.parse import urlencode # py3
def authenticated(method):
"""
12/02/14 @bwebb Pulled from Torando web.py to alter the behavior
of auth failure to redirect if REDIRECT... | gooftroop/Zeus | ef5/lib/handlers/__init__.py | Python | mit | 1,531 |
from elizabeth import Datetime, Personal, Text
from hashlib import pbkdf2_hmac
import binascii
import csv
import io
import random
class FakeEmail(object):
def __init__(self):
self.num_attachments = random.randint(0, 20)
def attachments(self):
for x in range(0, self.num_attachments):
... | wikkiewikkie/free-discovery | freediscovery/utils.py | Python | mit | 2,867 |
# Local config file
PORT = 8001
SECRET_KEY = 'DEVELOPMENT-KEY'
REDIS_QUEUE_KEY = 'hello-redis-tasks'
# Logging defaults
LOGGING = {
'version': 1,
'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } },
'loggers': { 'worker': { 'handlers': ['console'], 'level': 'DEBUG', } }
}
| vals/google_devnull | config.py | Python | mit | 319 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
"""
frappe.translate
~~~~~~~~~~~~~~~~
Translation tools for frappe
"""
import frappe, os, re, codecs, json
from frappe.utils.jinja import render_include
from frappe.utils im... | indictranstech/osmosis-frappe | frappe/translate.py | Python | mit | 22,878 |
def has_proper_prefix(s, prefix):
return len(s) > len(prefix) and s.startswith(prefix)
def repr_calling(args, kwargs):
"""
Reconstruct function calling code.
"""
li = []
li.extend(repr(a) for a in args)
li.extend('%s=%r' % (k, v) for k, v in kwargs.items())
return ', '.join(li)
def f... | xiaq/jadepy | jade/utils.py | Python | mit | 517 |
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import login as loginUser
from django.contrib.auth import logout as logoutUser
from urllib.request import urlopen
from urllib.parse import urlencode, parse_qs
import json
fr... | stlim0730/glide | user/views.py | Python | mit | 6,829 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_plugins_horizontal_rule', '0001_initial'),
]
operations = [
migrations.AlterModelTable(
name='horizontalr... | ic-labs/django-icekit | icekit/plugins/horizontal_rule/migrations/0002_auto_20160821_2140.py | Python | mit | 591 |
from __future__ import division
from future.utils import raise_from
import math
import time
from datetime import datetime
from operator import itemgetter
from pocket import (
Pocket,
PocketException,
PocketAutException
)
from progress.spinner import Spinner
from .config import Configs
from .exceptions i... | rakanalh/pocket-cli | pocket_cli/app.py | Python | mit | 5,875 |
# coding: utf-8
import inspect
import logging
from importlib import import_module
from typing import List
from django.apps import AppConfig
from django.core import checks
from modernrpc.conf import settings
from modernrpc.core import registry
logger = logging.getLogger(__name__)
@checks.register()
def check_settin... | alorence/django-modern-rpc | modernrpc/apps.py | Python | mit | 3,729 |
from .node import Document
from .builder import build
def shape(el, **kwargs):
el = wrap(el, **kwargs)
return el
def replace_element(e1, e2):
e1.tag = e2.tag
e1.clear()
e1.extend(e2)
class Wrap:
def __init__(self, *wrappers):
self.wrappers = {w.__name__.lower(): ... | fourpoints/addup | addup/reshaper.py | Python | mit | 3,048 |
"""
analysis/morlet.py
Time-frequency representation using Morlet wavelets
Original version written by Shane Lee (Brown University)
Modified by Sam Neymotin (NKI; added phase calculations, saving/passing in Morlet, specifying different
frequency steps and frequencies used for calculations (e.g. logarithmic freque... | thekerrlab/netpyne | netpyne/support/morlet.py | Python | mit | 4,477 |
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright (C) 2006 Fluendo, S.A. (www.fluendo.com).
# Copyright 2006, Frank Scholz <coherence@beebits.net>
from os.path import abspath
import urlparse
from urlparse import urlsplit
from coherence.extern.et import parse_xml as et_pars... | ligthyear/coherence-mirror | coherence/upnp/core/utils.py | Python | mit | 31,356 |
from templeplus.pymod import PythonModifier
from toee import *
import tpdp
import race_utils
###################################################
def GetConditionName():
return "Tiefling"
raceEnum = race_human + (3 << 5)
raceSpecModule = __import__('race096_tiefling')
###############################################... | GrognardsFromHell/TemplePlus | tpdatasrc/tpgamefiles/scr/tpModifiers/tiefling.py | Python | mit | 723 |
#!/bin/env python3
# -*- coding: utf-8 -*-
'''
Utility for mountain pass validation
Written by Andriy Danyleiko and Liudmyla Kislitsyna
Send bugs to andrii.danyleiko@gmail.com or by github https://github.com/DefteZ/westra2osm/
'''
import sys, argparse, codecs
import datetime
#import pygpx, gpxpy.gpx
import westra2osm... | DefteZ/westra2osm | pass_validator.py | Python | mit | 8,253 |
"""add detached D2 submission models
Revision ID: 4a1988f74a78
Revises: 4bf29ae16467
Create Date: 2017-01-20 11:40:50.782401
"""
# revision identifiers, used by Alembic.
revision = '4a1988f74a78'
down_revision = '4bf29ae16467'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
d... | fedspendingtransparency/data-act-broker-backend | dataactcore/migrations/versions/4a1988f74a78_add_detached_d2_submission_models.py | Python | cc0-1.0 | 7,389 |
import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'BIOMD0000000163.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
ret... | biomodels/BIOMD0000000163 | BIOMD0000000163/model.py | Python | cc0-1.0 | 427 |
#!/usr/bin/env python3
##################################################################
# This file is part of the POPE implementation. #
# Paper at https://eprint.iacr.org/2015/1106 #
# U.S. Government work product, in the public domain. #
# Written in 2015 by Daniel ... | dsroche/pope | test/nwbench-or.py | Python | cc0-1.0 | 4,630 |
import cv2
import numpy as np
import sys
def img_correlation(img, templ):
""" find most similar part to templ on img
returns upper left corner of templ in img and statistic
"""
rows, cols = img.shape
trows, tcols = templ.shape
row = col = None
mins = trows * tcols * 255**2 # max ... | OSGeoLabBp/tutorials | english/img_processing/code/img_corr.py | Python | cc0-1.0 | 878 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright notice
# ----------------
#
# Copyright (C) 2013-2014 Daniel Jung
# Contact: djungbremen@gmail.com
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Softwa... | proggy/columnize | __init__.py | Python | gpl-2.0 | 2,794 |
import sys
import usage
import utils
import xml.dom.minidom
import re
import resource
import cluster
from xml.dom.minidom import parseString
def status_cmd(argv):
if len(argv) == 0:
full_status()
sys.exit(0)
sub_cmd = argv.pop(0)
if (sub_cmd == "help"):
usage.status()
elif (sub... | jnpkrn/pcs | pcs/status.py | Python | gpl-2.0 | 5,073 |
# pylint: disable=redefined-outer-name
import itertools
from pathlib import Path
from typing import Callable, Tuple, cast
import astroid
import pytest
from astroid import AstroidBuildingError, nodes
import pylint.checkers.unicode
import pylint.interfaces
import pylint.testutils
from . import CODEC_AND_MSG, FakeNode
... | PyCQA/pylint | tests/checkers/unittest_unicode/unittest_bad_chars.py | Python | gpl-2.0 | 9,369 |
from __future__ import print_function
import numpy as np
def demo_gauss_sedel_method():
ITERATION_LIMIT = 1000
# initialize the matrix
A = np.array([[10., -1., 2., 0.],
[-1., 11., -1., 3.],
[2., -1., 10., -1.],
[0.0, 3., -1., 8.]])
# initialize the... | GraphProcessor/CommunityDetectionCodes | Algorithms/2014-Heat-Kernel/src_python/demo_files/yche_numerical_linear_algebra_exp.py | Python | gpl-2.0 | 2,192 |