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
import MySQLdb as mysql
from flask import Flask, request, render_template
import json
app = Flask(__name__)
con = mysql.connect(user="root", passwd="redhat", db="jiangkun")
con.autocommit(True)
cur = con.cursor()
@app.route('/')
def index():
return render_template("index.html")
@app.route('/list'... | seerjk/reboot06 | 09/homework08/flask_web.py | Python | mit | 768 |
from .mixins import (CaseMixin, VariantMixin)
from .plugin import GeminiPlugin | robinandeer/puzzle | puzzle/plugins/gemini/__init__.py | Python | mit | 78 |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 16:31:33 2015
@author: Rick Berg, University of Washington, School of Oceanography
!!!!!!!!!!Need to add in way to deal with upper boundary condition, saving output,
input process. Is this following the sediment package rather than depth?
Script for modeling reaction... | rickdberg/mgmodel | ratedownanalytic.py | Python | mit | 19,209 |
import tft_ir_api as IR
var_u = IR.RealVE("u", 0, (-100.0 - 0.0000001), (100.0 + 0.0000001))
var_v = IR.RealVE("v", 1, (20.0 - 0.000000001), (20000.0 + 0.000000001))
var_T = IR.RealVE("T", 2, (-30.0 - 0.000001), (50.0 + 0.000001))
t1 = IR.BE("+", 4, IR.FConst(331.4), IR.BE("*", 3, IR.FConst(0.6), var_T))
t... | soarlab/FPTuner | examples/primitives/doppler-1.py | Python | mit | 477 |
from django.core.management import call_command
from django.test.utils import override_settings
from bulbs.special_coverage.models import SpecialCoverage
from bulbs.utils.methods import today_as_utc_datetime
from bulbs.utils.test import BaseIndexableTestCase
class SpecialCoverageCommandTests(BaseIndexableTestCase):
... | theonion/django-bulbs | tests/special_coverage/test_spec_cov_commands.py | Python | mit | 2,296 |
from __future__ import unicode_literals
from django.apps import AppConfig
class PaypalConfig(AppConfig):
name = 'paypal'
| linkingcharities/linkingcharities | Linking_Charities/payment/apps.py | Python | mit | 128 |
from RaspiBot import Methods, sleep
# represents btn color and action on press in a state
class Btn:
def __init__(self, red, green, nextid = None):
self.red = red
self.green = green
self.next = nextid
# represents one menu state with message, button and own action
class State:
de... | alex-Symbroson/BotScript | BotScript/res/calibrate.py | Python | mit | 4,128 |
from sense_hat import SenseHat
import pygame
from pygame.locals import *
from time import sleep
pygame.init()
pygame.display.set_mode((1,1))
sense = SenseHat()
loop = True
i = 0
while i < 25:
i += 1
while loop == True:
for event in pygame.event.get():
if event.type == KEYDOWN:
... | geomapping/raspi-python | Schleifenwechsel.py | Python | mit | 643 |
from sqlalchemy import Column, Integer, String
from gradedash.database import Base
class Student(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True)
first_name = Column(String(45))
last_name = Column(String(45))
email = Column(String(128))
| corntoole/gradedash-backend-py | gradedash/models.py | Python | mit | 268 |
#!/usr/bin/python
# email_url.py
# emails the video URL to the presenters
from email_ab import email_ab
class email_url(email_ab):
ready_state = 7
subject_template = "[{{ep.show.name}}] Video up: {{ep.name}}"
body_body = """
The video of your talk is posted:
{{url}}
{% if ep.state == 7 %}
Look... | yoe/veyepar | dj/scripts/email_url.py | Python | mit | 1,390 |
"""airports.py provides an example Steno3D project of airports"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from .base import BaseExample, exampleproperty
from ..point import Mesh0D, Point
fr... | 3ptscience/steno3dpy | steno3d/examples/airports.py | Python | mit | 3,650 |
from . import myModule | aammd/python-package-example | myPackage/__init__.py | Python | mit | 22 |
def branch(str):
print("branch function: ", str)
| dcminnix/cs3240-labdemo | branch.py | Python | mit | 53 |
registry = set()
def register(active=True):
def decorate(func):
print('running register(active=%s)->decorate(%s)' % (active, func))
if active:
registry.add(func)
else:
registry.discard(func)
return func
return decorate
@register(active=False... | stephenl6705/fluentPy | registration_param.py | Python | mit | 451 |
"""
:mod:`zsl.db.helpers.sorter`
----------------------------
"""
from __future__ import unicode_literals
from builtins import object, zip
from sqlalchemy import asc, desc
DEFAULT_SORT_ORDER = 'ASC' # If changed, look at the condition in apply_sorter if self.get_order() == "DESC":.
class Sorter(object):
"""
... | AtteqCom/zsl | src/zsl/db/helpers/sorter.py | Python | mit | 3,601 |
import logging
logger = logging.getLogger(__name__)
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, keep=True, *args, **kwargs):
logger.debug("Handle singleton instance for %s with arg... | sahlinet/fastapp | fastapp/plugins/singleton.py | Python | mit | 1,074 |
"""
Definition of models.
"""
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
# python manage.py makemigrations app
progress = models.IntegerField(default=0)
progress_v1 = models.IntegerField(default=0)
progress_v2 = models.IntegerField(default=0)
progress_v3 = mod... | 0909023/Dev6B_English_Website | DjangoWebProject1/DjangoWebProject1/app/models.py | Python | mit | 1,227 |
"""
Ethernet (TCP/IP protocol stack)
"""
from binascii import unhexlify
from construct import *
from construct.protocols.layer3.ipv4 import IpAddressAdapter
from ethernet import MacAddressAdapter
def HwAddress(name):
return IfThenElse(name, lambda ctx: ctx.hardware_type == "ETHERNET",
MacAddressAdapter(... | gkonstantyno/construct | construct/protocols/layer2/arp.py | Python | mit | 2,137 |
import logging
from utils import common
from utils.lyric_base import LyricBase
site_class = 'UtaNet'
site_index = 'uta_net'
site_keyword = 'uta-net'
site_url = 'http://www.uta-net.com/'
test_url = 'http://www.uta-net.com/song/138139/'
test_expect_length = 1089
# current url format
# 'http://www.uta-net.com/song/13813... | franklai/lyric-get | lyric_engine/modules/uta_net.py | Python | mit | 3,585 |
from setuptools import setup
license = open('LICENSE.txt').read()
setup(
name='iloveck101',
version='0.5.2',
author='tzangms',
author_email='tzangms@gmail.com',
packages=['iloveck101'],
url='https://github.com/tzangms/iloveck101',
license=license,
description='Download images from ck10... | tzangms/iloveck101 | setup.py | Python | mit | 662 |
"""
The wrapper for Postgres through SQLAchemy
__author__ = "Alex Xiao <http://www.alexxiao.me/>"
__date__ = "2018-11-03"
__version__ = "0.1"
Version:
0.1 (03/11/2018 AX) : init
"""
from urllib.parse import quote_plus
from sqlalchemy import create_engine, text
import pandas
from ax.log import ge... | axxiao/toby | ax/wrapper/sqlalchemy.py | Python | mit | 1,716 |
from kivy.config import Config
from kivy.config import ConfigParser
import pentai.base.logger as log
import os
def config_instance():
return _config
def create_config_instance(ini_file, user_path):
global _config
ini_path = os.path.join(user_path, ini_file)
if not ini_file in os.listdir(user_path):... | cropleyb/pentai | pentai/gui/config.py | Python | mit | 737 |
#!/usr/bin/env python
import os
import numpy as np
import math
import fnmatch
from my_spectrogram import my_specgram
from collections import OrderedDict
from scipy.io import wavfile
import matplotlib.pylab as plt
from pylab import rcParams
from sklearn.model_selection import train_test_split
rcParams['figure.figsize']... | nick-monto/SpeechRecog_CNN | create_spectrograms_16k.py | Python | mit | 6,802 |
from selenium.common.exceptions import NoSuchElementException
from .base import FunctionalTest, login_test_user_with_browser
class EditPostTest(FunctionalTest):
@login_test_user_with_browser
def test_modify_post(self):
self.browser.get(self.live_server_url)
self.move_to_default_board()
... | cjh5414/kboard | kboard/functional_test/test_post_edit.py | Python | mit | 4,015 |
"""
Optimal power flow based on branch power flow modelling
Additional case33 is added to the test cases
Note: The proposed method has been verified
@author: Tianyang Zhao
@email: zhaoty@ntu.edu.sg
"""
from Two_stage_stochastic_optimization.power_flow_modelling import case33
from pypower import runopf
from gurobip... | Matrixeigs/Optimization | Two_stage_stochastic_optimization/optimal_power_flows/opf_branch_power.py | Python | mit | 4,744 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
admin.autodiscover()
urlpatterns = patterns('',
# Home Page -- Replace as you prefer
url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
url(r'^admin/do... | bung87/django-html5-boilerplate | project_name/urls/base.py | Python | mit | 417 |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'crashlog.views.home', name='home'),
# url(r'^crashlog/', include('crashlog.foo.urls')),
... | creativepsyco/crashlogger | crashlog/urls.py | Python | mit | 562 |
import os
import webbrowser
def get_index_path():
path = os.path.join(os.path.dirname(__file__), 'poolhub_app', 'dist', 'index.html')
return path
def launch_index_page():
path = get_index_path()
webbrowser.open('file://' + path)
| tsarpaul/poolhub | poolhub/frontend/utils.py | Python | mit | 250 |
import cherrypy
from cherrypy._cpcompat import ntou
from cherrypy.test import helper
class ETagTest(helper.CPWebCase):
@staticmethod
def setup_server():
class Root:
@cherrypy.expose
def resource(self):
return "Oh wah ta goo Siam."
@cherrypy.expose... | heytcass/homeassistant-config | deps/cherrypy/test/test_etags.py | Python | mit | 3,093 |
from unittest import mock
from django.urls import reverse
from .mixins import APIEndpointMixin
@mock.patch('readthedocs.projects.tasks.update_docs_task', mock.MagicMock())
class BuildsEndpointTests(APIEndpointMixin):
def test_projects_builds_list(self):
self.client.credentials(HTTP_AUTHORIZATION=f'Toke... | rtfd/readthedocs.org | readthedocs/api/v3/tests/test_builds.py | Python | mit | 2,045 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'PriorityManager.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
Mai... | asconz/SystematicPrioritization | application/views/gen/ui_MainView.py | Python | mit | 26,434 |
# encoding: UTF-8
from ctaBase import *
from ctaTemplate import CtaTemplate
import talib
import numpy as np
import math
import copy
from datetime import datetime
########################################################################
class Tmm3Strategy(CtaTemplate):
className = 'Tmm3Strategy'
author = ... | mumuwoyou/vnpy-dev | vn.trader/ctaStrategy/strategy/strategyTmm3.py | Python | mit | 19,435 |
import numpy as np
from sklearn.datasets import load_boston
(x, y) = load_boston(True)
ss_total = ((y - y.mean()) ** 2).sum()
def evaluate(p):
return 1 - ((np.inner(x, p[:-1]) + p[-1] - y) ** 2).sum() / ss_total
iter_count = 10000
pop_size = 100
child_size = 30
params_len = 14
tau = 1.0 / np.sqrt(2.0 * params_... | yukoba/EvolutionStrategyLinearModel | src/test4.py | Python | mit | 1,726 |
import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db.models import permalink
from django.contrib.auth.models import User
from tagging.fields import TagField
from src.basic.places import Place
class Event(models.Model):
"""Event model"""
title = m... | hittu123/ruhive | src/basic/events/models.py | Python | mit | 1,838 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from gaebusiness.gaeutil import SaveCommand, ModelSearchCommand
from gaeforms.ndb.form import ModelForm
from gaegraph.business_base import UpdateNode
from course_app.model import Course
class CourseForm(ModelForm):
"""
Form used ... | gamunax/pyhtongamunax | backend/apps/course_app/commands.py | Python | mit | 1,665 |
<<<<<<< HEAD
<<<<<<< HEAD
# Test properties of bool promised by PEP 285
import unittest
from test import support
import os
class BoolTest(unittest.TestCase):
def test_subclass(self):
try:
class C(bool):
pass
except TypeError:
pass
else:
... | ArcherSys/ArcherSys | Lib/test/test_bool.py | Python | mit | 36,233 |
# Scrapy settings for analytics_counter project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'analytics_counter'
SPIDER_MODULES = ['analytics_counter.spiders']... | ikeikeikeike/analytics-counter | analytics_counter/analytics_counter/settings.py | Python | mit | 1,032 |
import os
import re
import sublime
import sublime_plugin
class ExpandTabsOnLoad(sublime_plugin.EventListener):
# Run ST's 'expand_tabs' command when opening a file,
# only if there are any tab characters in the file
def on_load(self, view):
expand_tabs = view.settings().get("expand_tabs_on_load", ... | markashleybell/ExpandTabsOnLoad | ExpandTabsOnLoad.py | Python | mit | 630 |
#######################################################################
# This file is part of redminelib.
#
# Copyright (C) 2011 Will Kahn-Greene
#
# redminelib is distributed under the MIT license. See the file
# COPYING for distribution details.
######################################################################... | willkg/redminelib | redminelib/tests/test716.py | Python | mit | 1,444 |
# Keras imports
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.wrappers import TimeDistributed
from keras.layers.wrappers import Bidirectional
from keras.layers.core import Dropout
from keras.regularizers import... | pandeydivesh15/NER-using-Deep-Learning | Task 3: Hindi data/NER_model.py | Python | mit | 3,179 |
"""
bc125csv - Channel import and export tool for the Uniden BC125AT, UBC125XLT
and UBC126AT.
Copyright (c) 2020, fdev.nl. All rights reserved.
Released under the MIT license.
Uniden and Bearcat are registered trademarks of Uniden America Corporation.
This application and its author are not affiliated with or endors... | fdev/bc125csv | bc125csv/__init__.py | Python | mit | 548 |
# -*- coding: utf-8 -*-
from django.http import HttpResponse
import json
def rest_api(view_func):
def json_view(request, *args, **kwargs):
request.json_data = {}
if request.method == 'POST':
try:
request.json_data = json.loads(request.body)
except ValueErro... | Instanssi/Instanssi.org | Instanssi/common/rest.py | Python | mit | 677 |
"""
Django settings for monews project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... | Osmose/monews | monews/settings/base.py | Python | mit | 1,911 |
"""
atlas.instance_operations
~~~~
Commands that run on servers to deploy instances.
Instance methods:
Create - Local - All symlinks are in place, DB exists, NFS mount is attached
Update - Local and Update code or configuration;
Delete - Local - Remove instance symlinks, delete settings fil... | CuBoulder/atlas | atlas/instance_operations.py | Python | mit | 24,722 |
# -*- coding: utf-8 -*-
"""Easy network discovery & messaging
Aimed at a classrom or club situation, networkzero makes it simpler to
have several machines or several processes on one machine discovering
each other and talking across a network. Typical examples would include:
* Sending commands to a robot
* Sending sc... | tjguk/networkzero | networkzero/__init__.py | Python | mit | 1,846 |
from timeit import default_timer
from psychopy import core, event, visual
from psychopy.visual.rect import Rect
from toon.anim.easing import (ELASTIC_IN_OUT, SMOOTHERSTEP, SMOOTHSTEP,
EXPONENTIAL_OUT, LINEAR)
from toon.anim.interpolators import SELECT, LERP
from toon.anim import Track
fr... | aforren1/toon | demos/animation.py | Python | mit | 2,742 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# aggregate.py
#
# Copyright 2013 tusharmakkar08 <tusharmakkar08@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 Software Foundation; either vers... | tusharmakkar08/SQL_PARSER | aggregate.py | Python | mit | 3,641 |
"""
json_io.py
Functions related to reading/writing/mapping json
"""
import json
import ijson
from re import sub
from datetime import datetime
from os import listdir, SEEK_END
from sys import exc_info, stdout
from random import choice, randrange
from nlp import feature
TWEET_LINK_RE = "https://t.co/(\w)+"
TWEET_HAND... | TheWeiTheTruthAndTheLight/senior-design | src/json_io.py | Python | mit | 7,324 |
from pythonthegathering import ManaPool, spell
pool = ManaPool()
@spell('WBB')
def boop(x):
print(x)
pool.tap('plains').tap('swamp').tap('swamp')
boop('boop', mana_pool=pool, mana_pay={'W': 1, 'B': 2})
| linky00/pythonthegathering | test.py | Python | mit | 209 |
import copy
pattern_raw_digits = [
[' _ ',
'| |',
'|_|'],
[' ',
' |',
' |'],
[' _ ',
' _|',
'|_ '],
[' _ ',
' _|',
' _|'],
[' ',
'|_|',
' |'],
[' _ ',
'|_ ',
' _|'],
[' _ ',
'|_ ',
'|_|'],
[' _ ',
' |',
' |'],
[' _ ',
'|_|',
'|_|'],
[' ... | brunorijsman/coding-katas | bank-ocr-python/bank-ocr.py | Python | mit | 3,837 |
from .Edge import Edge
from .Vertex import Vertex
class Graph(object):
def __init__(self, V, E, tau=set()):
if isinstance(V, Vertex):
V = set([V])
elif not isinstance(V, set):
V = set(V)
if isinstance(E, Edge):
E = set([E])
elif not isinstanc... | char-lie/patterns_recognition | classes/graph/Graph.py | Python | mit | 6,045 |
'''The four adjacent digits in the 1000-digit number that have the greatest product
are 9 x 9 x 8 x 9 = 5832
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896... | kluge-iitk/Project-Euler | 8.py | Python | mit | 2,546 |
# !/usr/bin/python
# -*- coding: utf-8 -*-
class Reporter:
@classmethod
def from_identifier(cls, identifier):
clazz = TYPES.get(identifier, None)
return clazz() if clazz else None
def report(self, all_files, modified_files):
pass
class JSONReporter(Reporter):
def report(sel... | barbosa/clorox | clorox/reporter.py | Python | mit | 551 |
import numpy as np
def voc_ap(rec, prec, use_07_metric=False):
""" ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
Adopted from https://github.com/rbgirshick/py-faster-rcnn/blob/master/li... | xdshang/VidVRD-helper | evaluation/common.py | Python | mit | 3,685 |
### hierarchical_clustering.py
#Copyright 2005-2012 J. David Gladstone Institutes, San Francisco California
#Author Nathan Salomonis - nsalomonis@gmail.com
#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 ... | ActiveState/code | recipes/Python/578175_Hierarchical_Clustering_Heatmap/recipe-578175.py | Python | mit | 18,918 |
__version__ = '1.2.0'
from .oss_authorizers import OssAuthorizer
from .oss_file_operation import OssFileOperation
from .oss_fs import OssFS
from .oss_fs_impl import OssFsImpl
| aliyun/oss-ftp | ossftp/__init__.py | Python | mit | 176 |
import random
import copy
from Tkinter import *
def init():
printInstructions()
canvas.data.isGameOver = False
board = []
for x in xrange(canvas.data.rows):
board.append(["blue"]*canvas.data.cols)
canvas.data.emptyColor = "blue"
canvas.data.tetrisBoard = board
tetrisPieceColors = ... | torablien/PythonFun | Tetris/Basic Tetris.py | Python | mit | 8,322 |
import functools
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from django.db.models.loading import get_app
def safe(view):
"""Marks a view as safe to be called"""
@functools.wraps(view)
def wrapper(*args, **kwargs... | LucianU/django-failclose | failclose/utils.py | Python | mit | 2,530 |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import struct
import array
import os
def pack_neg(ID):
type = 0
id = ID
data = struct.pack('>II', type, id)
return data
def unpack_neg(data):
type,id = struct.unpack('>II', data)
return (type,id)
print "negotiation", unpack_neg(pack_neg(16))
d... | edderick/E0_Python | pystruct.py | Python | mit | 1,485 |
from CGATReport.Tracker import *
from cpgReport import *
##########################################################################
class IntervalsSummary(cpgTracker):
"""Summary stats of intervals called by the peak finder. """
mPattern = "_macs_intervals$"
def __call__(self, track, slice=None):
... | CGATOxford/CGATPipelines | CGATPipelines/pipeline_docs/pipeline_cpg/trackers/macs_intervals.py | Python | mit | 5,417 |
import json
import numpy as np
from scipy.integrate import odeint
from ..utils import model_eval, NumpyEncoder
def sens_value(sol, par, delta_x, delta_y):
if sol != 0 and delta_x != 0:
return par / sol * (delta_y) / (2 * delta_x)
else:
return float('Inf')
def find_sensitivity(funcs, y0, t, par... | Rhymmor/pharmac | src/solver-server/pkg/algorithms/identifiability/sensitivity.py | Python | mit | 1,544 |
from collections.abc import Iterable
from TM1py.Services import CellService
from TM1py.Services import ElementService
from TM1py.Utils import require_pandas
try:
import pandas as pd
_has_pandas = True
except ImportError:
_has_pandas = False
class PowerBiService:
def __init__(self, tm1_rest):
... | OLAPLINE/TM1py | TM1py/Services/PowerBiService.py | Python | mit | 6,310 |
'''
LintCode: http://www.lintcode.com/zh-cn/problem/find-minimum-in-rotated-sorted-array-ii/
160. 寻找旋转排序数组中的最小值 II
假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。
你需要找到其中最小的元素。
数组中可能存在重复的元素。
样例:
给出[4,4,5,6,7,0,1,2] 返回 0
'''
# 跟 findMin I 类似
# 因为可能存在重复的元素,所以在判断 num[left] >= num[mid] 之后
# 需要判断 left - mi... | happylindz/algorithms-tutorial | lintcode/FindMin/findMinII.py | Python | mit | 1,448 |
#!/usr/bin/env python3
"""
The 8-Queens Problem as dynamic programming.
https://en.wikipedia.org/wiki/Eight_queens_puzzle
"""
class QueenSolver:
def __init__(self, numqueens, boardsize):
# Cast and validate
self.numqueens = int(numqueens)
self.boardsize = int(boardsize)
assert self... | jnez71/demos | methods/dynpro_queens.py | Python | mit | 2,894 |
from django.urls import include, re_path
from .. import views
management_urls = [
re_path(r'^$', views.ManagementHome.as_view(), name='picker-manage'),
re_path(r'^game/(\d+)/$', views.ManageGame.as_view(), name='picker-manage-game'),
re_path(r'^(?P<season>\d{4})/', include([
re_path(r'^$', views.Ma... | dakrauth/picker | picker/urls/picks.py | Python | mit | 1,495 |
# -*- coding: utf-8 -*-
__author__ = 'Juho Vepsäläinen'
__version__ = '0.7.5-dev'
| bebraw/speccer | speccer/__init__.py | Python | mit | 86 |
import glob, os
import pysrt
from gensim import corpora, models, similarities
from collections import defaultdict
from pprint import pprint
import nltk.tokenize
from stop_words import get_stop_words
from nltk.stem.porter import PorterStemmer
import csv
tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
p_stemmer = Por... | kevinwang/moca | createcorpus_textretrieval.py | Python | mit | 3,070 |
class BinaryOperator:
def __init__(self, left, right):
self.left = left
self.right = right
def __str__(self):
return '%s(%s, %s)' % (self.__class__.__name__, self.left, self.right)
def toCalchas(self, op):
return '(%s%s%s)' % (self.left.toCalchas(), op, self.right.toCalchas... | iScienceLuvr/PPP-CAS | ppp_cas/mathematicaTree.py | Python | mit | 6,347 |
class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
"""
MAX_INT = 2 ** 31 - 1
if not nums or len(nums) == 0:
return 0
i = j = n_sum = 0
min_len = MAX_INT
while j < ... | ChuanleiGuo/AlgorithmsPlayground | LeetCodeSolutions/python/209_Minimum_Size_Subarray_Sum.py | Python | mit | 564 |
#!/usr/bin/env python
"""Ripple ledger extractor.
Grapple extracts the ledger from rippled via websocket. It starts at the
current ledger index, and walks backwards until it reaches the genesis ledger.
The genesis ledger index is set by default to 152370.
If you have previously run Grapple, data will only be collect... | tinybike/grapple | grapple/grapple.py | Python | mit | 24,929 |
from aiohttp.web import View, HTTPFound
def http_found(func):
async def wrapped(self, *args, **kwargs):
await func(self, *args, **kwargs)
return HTTPFound(self.request.rel_url)
return wrapped
class CoreView(View):
sensor = None
def __init__(self, *args, **kwargs):
super()._... | insolite/alarme | alarme/extras/sensor/web/views/core.py | Python | mit | 386 |
try:
from django.contrib.auth.tests.utils import skipIfCustomUser
except ImportError:
def skipIfCustomUser(wrapped):
return wrapped
| maroux/django-oauth2-provider | provider/compat/__init__.py | Python | mit | 148 |
#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
主程序入口
@author:alex
@date:15-2-13
@time:上午11:44
@contact:alexliyu2012@gmail.com
"""
__author__ = 'alex'
import sys
import os
import ConfigParser
import uuid
from subprocess import Popen, PIPE
from utils.heartbeat import HeartBeatManager
from utils.tools import *
... | alexliyu/CDMSYSTEM | firewall.py | Python | mit | 1,273 |
import os
import os.path
import random
import recipe_generator
import subprocess
import shutil
#Comparing all recipes, which uses the fewest ingredients? ...kinda hacky
def fewest_ingredients(path):
""" Takes a path and returns the recipe txt file with the fewest ingredients
in the tree specified by that p... | ScriptingBeyondCS/CS-35 | week_0_to_2/tree_analysis/recipe_analysis_examples.py | Python | mit | 4,728 |
import sys
import copy
import psutil
import os
from PyQt5.QtWidgets import QWidget, QTabWidget
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtWid... | JohnKendrick/PDielec | PDielec/GUI/NoteBook.py | Python | mit | 21,778 |
from pysam.utils import PysamDispatcher
# samtools command line options to export in python
SAMTOOLS_DISPATCH = {
# samtools 'documented' commands
"view": ("view", None),
"sort": ("sort", None),
"mpileup": ("mpileup", None),
"depth": ("depth", None),
"faidx": ("faidx", None),
"fqidx": ("fqi... | pysam-developers/pysam | pysam/samtools.py | Python | mit | 1,671 |
"""
--- Day 25: The Halting Problem ---
Following the twisty passageways deeper and deeper into the CPU, you finally reach the core of the computer. Here, in the expansive central chamber, you find a grand apparatus that fills the entire room, suspended nanometers above your head.
You had always imagined CPUs to be ... | bbglab/adventofcode | 2017/iker/day25.py | Python | mit | 7,429 |
import _plotly_utils.basevalidators
class DurationValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="duration", parent_name="layout.slider.transition", **kwargs
):
super(DurationValidator, self).__init__(
plotly_name=plotly_name,
p... | plotly/python-api | packages/python/plotly/plotly/validators/layout/slider/transition/_duration.py | Python | mit | 518 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-01 16:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('starwarspwa', '0002_subscription'),
]
operations = [
migrations.RemoveField(
... | jedijulia/starwarspwa | starwarspwa/migrations/0003_auto_20160901_1650.py | Python | mit | 955 |
# check for specific mention of fMRI-related terms
# to filter out non-fMRI papers
def filter_fMRI_terms(pmids,fmri_terms=['fMRI','functional MRI',
'functional magnetic resonance'],usemesh=False):
""" return pmids that include fMRI-related terms
in MESH keywords or abstract or title"""... | jokedurnez/RequiredEffectSize | SampleSize/filter_fMRI_terms.py | Python | mit | 831 |
import os
from flask import Flask, url_for, send_from_directory, flash, get_flashed_messages, session, request, render_template, redirect
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from configure_database import Base, F5Device, AFMStat, StatValue
engine = create_engine('sqlite:///F5AF... | pdawson1983/Python-F5-AFM-App | F5AFMApp.py | Python | mit | 2,130 |
class resonance():
"""
This class represents a resonance.
"""
def __init__(self,cR=1.0,wR=[],w0=1.,r0=.5,phase=0.):
self.wR=wR
self.cR=cR
self.w0=w0
self.r0=r0
self.phase=phase
def toString(self):
"""
Returns a string of the resonance data mem... | bdell/pyPWA | pythonPWA/dataTypes/resonance.py | Python | mit | 464 |
from unittest.mock import Mock
import pandas as pd
import pytest
import pytz
from qstrader.alpha_model.single_signal import SingleSignalAlphaModel
@pytest.mark.parametrize(
'signal,expected_signals',
[
(0.75, {'EQ:SPY': 0.75, 'EQ:AGG': 0.75, 'EQ:GLD': 0.75}),
(-0.25, {'EQ:SPY': -0.25, 'EQ:AG... | mhallsmoore/qstrader | tests/unit/alpha_model/test_single_signal.py | Python | mit | 814 |
import medic
from maya import OpenMaya
class FaceAssigned(medic.PyTester):
def __init__(self):
super(FaceAssigned, self).__init__()
def Name(self):
return "FaceAssigned"
def Description(self):
return "Face assigned mesh(s)"
def Match(self, node):
return node.object()... | sol-ansano-kim/medic | plugins/Tester/faceAssigned.py | Python | mit | 1,666 |
#!/usr/bin/env python
import unittest
from os.path import realpath
from path_tools import create_filepath
class TestCreateFilepath(unittest.TestCase):
def test_identity(self):
original_filepath = realpath('E:/GoPro/2018-04-18/GH010926.MP4')
dest_filepath = create_filepath(original_filepath)
... | jujumo/gpsbip-configurator | source/task/path_tools_test.py | Python | mit | 2,315 |
from django.db import models
from django.shortcuts import resolve_url as r
from eventex.subscriptions.validators import validate_cpf
class Subscription(models.Model):
name = models.CharField('nome', max_length=100)
cpf = models.CharField('CPF', max_length=11, validators=[validate_cpf])
email = models.Emai... | rg3915/wttd2 | eventex/subscriptions/models.py | Python | mit | 808 |
import os
import socket
import atexit
import re
from setuptools.extern.six.moves import urllib, http_client, map
import pkg_resources
from pkg_resources import ResolutionError, ExtractionError
try:
import ssl
except ImportError:
ssl = None
__all__ = [
'VerifyingHTTPSHandler', 'find_ca_bundle', 'is_avail... | AustinRoy7/Pomodoro-timer | venv/Lib/site-packages/setuptools/ssl_support.py | Python | mit | 8,130 |
import pypsa
#NB: this test doesn't work for other cases because transformer tap
#ratio and phase angle not supported for lpf
from pypower.api import ppoption, runpf, case30 as case
from pypower.ppver import ppver
from distutils.version import StrictVersion
pypower_version = StrictVersion(ppver()['Version'])
import... | PyPSA/PyPSA | test/test_lpf_against_pypower.py | Python | mit | 2,335 |
import _plotly_utils.basevalidators
class ValueminusValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="valueminus", parent_name="bar.error_x", **kwargs):
super(ValueminusValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_nam... | plotly/plotly.py | packages/python/plotly/plotly/validators/bar/error_x/_valueminus.py | Python | mit | 447 |
from __future__ import (absolute_import, division, print_function)
from collections import OrderedDict
import numpy as np
import os
import pickle
from qtpy.QtWidgets import QDialog, QTreeWidgetItem, QTableWidgetItem, QMenu, QFileDialog, QApplication
from addie.utilities import load_ui
from qtpy import QtCore, QtGui
... | neutrons/FastGR | addie/processing/mantid/master_table/table_tree_handler.py | Python | mit | 66,023 |
import bpy
from math import sin, cos, pi
TAU = 2*pi
import utils
# Create a function for the u, v surface parameterization from r0 and r1
def torusSurface(r0, r1):
def surface(u, v):
point = ((r0 + r1*cos(TAU*v))*cos(TAU*u), \
(r0 + r1*cos(TAU*v))*sin(TAU*u), \
r1*sin(TA... | njanakiev/blender-scripting | scripts/parametric_torus.py | Python | mit | 2,009 |
#-*- coding: utf-8 -*-
import sys
from abc import ABCMeta, abstractmethod
from src.shell.std import Std
class ICommand(Std):
"""
Interface for a scat command
"""
def __init__(self, verbose=2):
self.__verbose = verbose
return
def stdout(self, msg, crlf=True):
if self... | Frky/scat | src/shell/command/i_command.py | Python | mit | 968 |
"""NIAGADSOFINQUERY API application.
simplePostwithPython.py get -n <titlename> -i <individualnum> -s <snpnum> -f <tfampath> -p <tpedpath> -a <apitoken>
Usage:
simplePostwithPython.py get -n <titlename> -i <individualnum> -s <snpnum> -f <tfampath> -p <tpedpath> -a <apitoken>
simplePostwithPython.py (-h | --help)... | light940929/niagadsofinquery | testexample/simplePostwithPython.py | Python | mit | 3,247 |
# -*- coding: utf-8 -*-
"""
Test Script for debugging DHS TAXII Connection.
"""
import sys
import argparse
import requests
import datetime
import random
from dateutil.tz import tzutc
import libtaxii.messages_11 as taxii_messages
from libtaxii.messages_11 import SubscriptionInformation
from libtaxii.messages_11 import C... | stkyle/serengeti | serengeti/taxii-client.py | Python | mit | 5,591 |
class SharpIrDistanceSensor(object):
def __init__(self, spi_interface, pin_id):
self.spi_interface = spi_interface
self.pin_id = pin_id
def _voltageToMeters(self, voltage):
return 67.84 / (voltage - 3) - 0.04
def readDistance(self):
'''Returns distance in meters.'''
... | asydorchuk/robotics | python/robotics/sensors/sharp_ir_distance_sensor.py | Python | mit | 443 |
import model_loader
from keras.utils import plot_model
model_names = ['ResNet50', 'VGG19']
stages = ['5', 'final']
for model_name in model_names:
for stage in stages:
full_model = model_loader.load_full_model(model_name, random_weights=False, no_cats=2, weight_decay=0, activation='softmax')
tail_model = model_lo... | bbenligiray/keras_models | test.py | Python | mit | 801 |
from django.conf import settings
PAGINATED_PER_PAGE = getattr(settings, 'PAGINATED_PER_PAGE', 10)
PAGINATED_NEXT_TEXT = getattr(
settings, 'PAGINATED_NEXT_TEXT', '»'
)
PAGINATED_PREV_TEXT = getattr(
settings, 'PAGINATED_PREV_TEXT', '«'
)
PAGINATED_LEADING_PAGE_RANGE_DISPLAYED = getattr(
settin... | simas/django-paginated | paginated/settings.py | Python | mit | 943 |
# -*- coding: utf-8 -*-
#!/usr/bin/python
# Author: Tania M. Molina
# UY - 2017
# MIT License
import math
import numpy as np
import pandas as pd
from scipy import stats
from scipy.stats import norm
import scipy.stats as stats
import scipy.stats as st
import matplotlib
import matplotlib.pyplot as plt
import re
import sc... | lastralab/Statistics | Specialization/Personal/Rtopy.py | Python | mit | 484 |
# -*- coding: utf-8 -*-
# The base for SQL wrappers to implement.
class sqltype:
""" pysqlw.sqltype is a parent class to the meta-wrappers
provided by pysqlw. This allows for simple integration
into the pysqlw meta-wrapper family.
"""
def __init__(self, **kwargs):
""" Check that a... | sysr-q/pysqlw | pysqlw/sqltype.py | Python | mit | 1,490 |
# -*- coding: utf-8 -*-
__all__ = ['AddDialog']
import pygtk
pygtk.require('2.0')
import gtk
import gconf
import datetime
import locale
import gobject
from lib import utils
from lib import common
from lib import scheduler
from lib.bill import Bill
from lib.actions import Actions
from lib.utils import create_pixbuf
f... | google-code/billreminder | src/gui/adddialog.py | Python | mit | 20,237 |