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 |
|---|---|---|---|---|---|
#
# Solution to Project Euler problem 52
# Philippe Legault
#
# https://github.com/Bathlamos/Project-Euler-Solutions
import itertools
def compute():
c = 1
while True:
lists = [digits(c * n) for n in range(1, 7)]
if len(set(lists)) == 1: # Check that all elements are equal
return c
c += 1
def digits(n)... | Bathlamos/Project-Euler-Solutions | solutions/p052.py | Python | mit | 451 |
# -*- coding: utf-8 -*-
"""Module providing views for the site navigation root"""
from Acquisition import aq_inner
from Products.Five.browser import BrowserView
from Products.ZCatalog.interfaces import ICatalogBrain
from plone import api
from plone.app.contentlisting.interfaces import IContentListing
from plone.app.con... | a25kk/dpf | src/dpf.sitecontent/dpf/sitecontent/browser/frontpage.py | Python | mit | 3,589 |
import string
import csv
import os
from abaqusConstants import *
from part import *
from material import *
from section import *
from assembly import *
from load import *
from mesh import *
from visualization import *
def importEBSD(inpFileName):
while True:
fileName, file_extension = os.path.splitext... | DorianDepriester/mtex2abaqus | MTEX2abaqus/AbaqusImport.py | Python | mit | 2,602 |
# Laser Generator Library
# Part of the Glitch_Heaven Project
# Copyright 2015-2016 Penaz <penazarea@altervista.org>
import pygame
from os.path import join as pjoin
def generate(size, vertical=False, image=None):
if image is None:
graphics = pygame.image.load(pjoin("resources", "sprites", "laser.png")).c... | Penaz91/Glitch_Heaven | Game/libs/lasergen.py | Python | mit | 1,000 |
#!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from __future__ import unicode_literals
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst'), 'rb').read().decode('utf-8')
except IOError:
README = ''... | keelerm84/powerline | setup.py | Python | mit | 931 |
default_app_config = 'shoottikala.apps.ShoottikalaAppConfig'
| conikuvat/shoottikala | shoottikala/__init__.py | Python | mit | 61 |
"""
Clone server Model Six
"""
import random
import time
import zmq
from clone import Clone
SUBTREE = "/client/"
def main():
# Create and connect clone
clone = Clone()
clone.subtree = SUBTREE
clone.connect("tcp://localhost", 5556)
clone.connect("tcp://localhost", 5566)
try:
while ... | soscpd/bee | root/tests/zguide/examples/Python/clonecli6.py | Python | mit | 638 |
# -*- coding: utf-8 -*-
#
# TensorFlow-World documentation build configuration file, created by
# sphinx-quickstart on Wed Jun 28 22:26:19 2017.
#
# 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 fi... | astorfi/TensorFlow-World | docs/conf.py | Python | mit | 5,320 |
#!/usr/bin/env python
"""
<Program Name>
test_formats.py
<Author>
Vladimir Diaz <vladimir.v.diaz@gmail.com>
<Started>
January 2017 (modified from TUF's original formats.py)
<Copyright>
See LICENSE for licensing information.
<Purpose>
Unit test for 'formats.py'
"""
# Help with Python 3 compatibility, whe... | vladimir-v-diaz/securesystemslib | tests/test_formats.py | Python | mit | 15,792 |
# -*- coding: utf-8 -*-
# @Author: Yue Wu <me@blaulan.com>
# @Date: 2020-02-29 17:49:05
# @Last Modified By: Yue Wu <me@blaulan.com>
# @Last Modified Time: 2020-03-02 22:06:26
from prompt_toolkit import PromptSession
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.validation import ... | blaulan/alfred-beancount | commandline.py | Python | mit | 2,565 |
# -*- coding: utf-8 -*-
import sqlalchemy.ext.declarative
from sqlalchemy import types
from sqlalchemy.dialects import postgresql
import uuid
class Base(object):
pass
#:
Base = sqlalchemy.ext.declarative.declarative_base(cls=Base)
class GUID(types.TypeDecorator):
"""Platform-independent GUID type.
Use... | smartstudy/midauth | midauth/models/base.py | Python | mit | 1,286 |
import unittest
import json
import re
from base64 import b64encode
from flask import url_for
from app import create_app, db
from app.models import User, Role
class APITestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
se... | Qumeric/instabattle | tests/test_api.py | Python | mit | 5,128 |
from .blueprint import bp
from .submission import *
| SpeedProg/eve-inc-waitlist | waitlist/blueprints/xup/__init__.py | Python | mit | 52 |
import hashlib
import os
import threading
from Queue import Queue
import requests
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from konfig import Konfig
konf ... | jpf/ftp-to-s3 | server.py | Python | mit | 3,319 |
# -*- coding: utf-8 -*-
from protoLib.getStuff import getDjangoModel
from protoExt.utils.utilsWeb import JsonError , doReturn
from . import validateRequest
import json
from django.contrib.admin.sites import site
from protoExt.utils.utilsBase import traceError
def protoExecuteAction(request):
""" Ejecuta una ... | DarioGT/docker-carra | src/protoExt/views/protoActionAction.py | Python | mit | 3,186 |
from django.conf.urls import url
from DjangoTaskManager.task import views
urlpatterns = [
url(r'^$', views.all_tasks, name='all_tasks'),
url(r'^add/$', views.add, name='task_add'),
url(r'^mark-done/(?P<task_id>[\w+:-]+)/$',
views.mark_done, name='task_mark_done'),
url(r'^edit/(?P<task_id>[\w+:... | MaxwellCoriell/DjangoTaskManager | DjangoTaskManager/task/urls.py | Python | mit | 544 |
import unittest
from uvio.loop import Loop
from uvio.idle import Idle
from uvio.handle import Handle
class Test(unittest.TestCase):
def test_init(self):
loop = Loop.create()
called = False
def callback():
print("callback called!")
nonlocal called
cal... | srossross/uvio | uvio/tests/test_idle.py | Python | mit | 720 |
import sys, os
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
from common.layers import *
from common.gradient import numerical_gradient
from collections import OrderedDict
class TwoLayerNet:
def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
# 重みの初期化
self... | nobukatsu/deep-learning-from-scratch | ch05/two_layer_net.py | Python | mit | 2,635 |
import catalog.runner
from catalog.models import *
class Runner(catalog.runner.Runner):
name = 'Axoft'
alias = 'axoft'
url = {'start': 'http://axoft.ru/',
'login': 'http://axoft.ru/',
'vendors': 'http://axoft.ru/vendors/',
'prefix': 'http://axoft.ru'}
word =... | anodos-ru/catalog | updaters/axoft.py | Python | mit | 9,080 |
# coding: UTF-8
#
# user_conf.py
#
# スマート電力量メーター ユーザ設定
#
# Copyright(C) 2016 pi@blue-black.ink
#
SEM_ROUTEB_ID = '00000000000000000000000000000000'
SEM_PASSWORD = 'XXXXXXXXXXXX'
SEM_INTERVAL = 20 # 瞬時電力取得間隔[s]
SEM_DURATION = 6 # アクティブスキャンduration (通常は変更の必要なし)
SOCK_UDP = '192.168.0.255' # UDPソケットIPアドレス
S... | bokunimowakaru/Wi-SUN_EnergyMeter | user_conf.py | Python | mit | 486 |
import pysam
from readtagger.pysamtools_view import view
INPUT = 'tagged_dm6.bam'
def test_pysamtoolsview(datadir_copy, tmpdir): # noqa: D103
input_bam = str(datadir_copy[INPUT])
output_bam = tmpdir.join('out.bam').strpath
region = '3R:8121625-8121731'
view(input_bam=input_bam, output_bam=output_ba... | bardin-lab/readtagger | tests/test_pysamtools_view.py | Python | mit | 404 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-10-27 22:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mentoring', '0011_auto_20161027_1653'),
]
operations = [
migrations.AlterField... | TomWerner/AlumniMentoring | mentoring/migrations/0012_auto_20161027_1700.py | Python | mit | 5,231 |
#JOHN CONWAY'S GAME OF LIFE
import RPi.GPIO as GPIO
import time
import random
import serial
import string
from plotter import mybuffer
MAXGENERATIONS = 4000
DISPLAY = True
gamecount = 0
maxgenfold = ''
def toggledisplay(pin):
global DISPLAY
p.turnondisplay()
p.loadcustomchars(fullblock=False)
DISPLAY = not DI... | tachijuan/python | myscripts/foldgame.py | Python | mit | 3,016 |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from azure.core.exceptions import ServiceRequestError
from azure.identity._internal.msal_client import MsalClient
import pytest
from helpers import mock, mock_response... | Azure/azure-sdk-for-python | sdk/identity/azure-identity/tests/test_msal_client.py | Python | mit | 1,769 |
import ssadata
# how many boys names are also girls names?
# implementation details:
# find all names in the boys data set that are
# also keys in the girls data set.
num_shared_names = 0
for name in ssadata.boys:
if name in ssadata.girls:
num_shared_names = num_shared_names + 1
print(str(num_shared_... | guyrt/teaching | 2017/Com597I/babynames/problem8.py | Python | mit | 607 |
from __future__ import absolute_import
import json, math
from .schema import SolrResponse, SolrResult
class SunburntJSONEncoder(json.JSONEncoder):
def encode(self, o):
if isinstance(o, SolrResponse):
return self.encode(list(o))
return super(SunburntJSONEncoder, self).encode(o)
... | rlskoeser/sunburnt | sunburnt/json.py | Python | mit | 1,190 |
'''
Created on June 09, 2014
@author: sscepano
'''
# This one serves for the starting point
import logging
import traceback
import multiprocessing
#####################################################
# imports distributor
#####################################################
from distribute import task_manager as D... | sanja7s/CI_urban_rural | CI_urban_rural/__main__.py | Python | mit | 1,723 |
# Copyright 2004-2017 Tom Rothamel <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, m... | kfcpaladin/sze-the-game | renpy/gl/glblacklist.py | Python | mit | 1,846 |
# -*- coding: utf-8 -*-
"""Base module for unittesting."""
from plone.app.testing import applyProfile
from plone.app.testing import FunctionalTesting
from plone.app.testing import IntegrationTesting
from plone.app.testing import login
from plone.app.testing import PLONE_FIXTURE
from plone.app.testing import PloneSandb... | a25kk/newe | src/newe.sitecontent/newe/sitecontent/testing.py | Python | mit | 1,963 |
import praw, argparse, sys, json, re, os, time, traceback
from peewee import *
from logins import *
from var_dicts import *
user_agent = "StunfiskHelperBot v0.1.1 by /u/0ffkilter"
reddit = praw.Reddit(user_agent=user_agent)
reddit.login(bot_name, bot_password)
c_db = MySQLDatabase(database='stunbot', host='localhos... | 0ffkilter/StunfiskBot | StunfiskBot.py | Python | mit | 15,210 |
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
# Map PageElement constructor arguments to webdriver locator enums
_LOCATOR_MAP = {'css': By.CSS_SELECTOR,
'id_': By.ID,
'name': By.NAME,
'xpath': By.XPATH,
... | julietalucia/page-objects | page_objects/__init__.py | Python | mit | 4,653 |
from algorithms.sorting.bubblesort import bubble_sort
def test_bubble_sort_small(array_ints_small, assert_sorted):
assert_sorted(array_ints_small, bubble_sort)
def test_bubble_sort_large(array_ints_large, assert_sorted):
assert_sorted(array_ints_large[:800], bubble_sort)
| dieb/algorithms.py | tests/sorting/test_bubblesort.py | Python | mit | 283 |
import config
import novaclient.client
#import novaclient.v1_1.client
nova = novaclient.client.Client(
2,
config.USERNAME,
config.PASSWORD,
project_id=config.TENANT_ID,
auth_url=config.AUTH_URL,
insecure=True,
http_log_debug=True,
)
#print nova.verify_cert
nova.set_management_url('https:/... | ewiger/hobbit | sagecase.py | Python | mit | 388 |
import logging
from flask import Flask
from honeybadger.contrib import FlaskHoneybadger
from blueprint import simple_page
logger = logging.getLogger(__name__)
app = Flask(__name__)
app.config['HONEYBADGER_ENVIRONMENT'] = 'honeybadger-example'
app.config['HONEYBADGER_API_KEY'] = '<your key>'
app.config['HONEYBADGER_... | honeybadger-io/honeybadger-python | examples/flask-blueprint/app.py | Python | mit | 454 |
import numpy as np
import matplotlib.pyplot as plt
npoint = 100
dec = 3
x = np.linspace(0,1,npoint)
a = dec * np.linspace(0,1,npoint/2)
b = dec * np.linspace(1,0,npoint/2)
delta = np.concatenate((a,b))
delta1 = dec * np.linspace(0,1,npoint)
delta2 = dec * np.ones(npoint)
plt.figure()
plt.plot(x, delta2)
plt.figu... | Aircollition/Aircollition | Python scripts/theta.py | Python | mit | 378 |
import io
import logging
import os
import re
log = logging.getLogger(__name__)
class file2(io.TextIOWrapper):
"""
Provides tools useful for navigating through and finding data
in the output files
"""
def __init__(self, name, mode='r', *args, **kwargs):
# super().__init__(*args, **kwargs)... | talipovm/terse | terse/Tools/file2.py | Python | mit | 5,523 |
# -*- coding: utf-8 -*-
"""
Helper functions used in views.
"""
import csv
import xml
import urllib2
import time
import threading
from json import dumps
from functools import wraps
from datetime import datetime
from lxml import etree
from flask import Response
import logging
log = logging.getLogger(__name__) # pylin... | stxnext-kindergarten/presence-analyzer-jjanuzik | src/presence_analyzer/utils.py | Python | mit | 5,272 |
import websocket
import thread
import time
import cv2
from StringIO import StringIO
import base64
from PIL import Image
import numpy as np
import time
def on_message(ws, message):
img = base64.b64decode(message)
print img
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
... | TE-ToshiakiTanaka/stve | project/col/client.py | Python | mit | 829 |
# Copyright © 2016 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, p... | jwilk/anorack | lib/articles.py | Python | mit | 1,632 |
# various converters between country codes and names
# including the possibility to look up the continent
# a country belongs to.
#
# source: ISO 3166 and
# http://en.wikipedia.org/wiki/List_of_countries_by_continent_(data_file)
import data
import types
def ccn_to_ccn(code):
"""Normalize the numeric country code... | jamesporter/InternationalTrade | countryutils/transformations.py | Python | mit | 7,163 |
from .endpoint import Endpoint
from .exceptions import MissingRequiredFieldError
from .. import ViewItem, PaginationItem
import logging
logger = logging.getLogger('tableau.endpoint.views')
class Views(Endpoint):
@property
def baseurl(self):
return "{0}/sites/{1}".format(self.parent_srv.baseurl, self.... | Talvalin/server-client-python | tableauserverclient/server/endpoint/views_endpoint.py | Python | mit | 1,391 |
from yapsy.IPlugin import IPlugin
from scanner.util import check_call
class FallbackScsv(IPlugin):
def description(self):
return "TLS_FALLBACK_SCSV"
def check(self, url, host_info):
host_info[self.description()] = None
if host_info["ssl checked"].get():
return None
... | kotnik/scanner | scanner/checks/fallback_scsv.py | Python | mit | 713 |
# Create your views here.
from danibraz.bolsa.models import PlanoDeContas
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
import xlrd
# def simple_upload(request):
# if request.method == 'POST' and request.FILE... | CoutinhoElias/danibraz | danibraz/bolsa/views.py | Python | mit | 5,742 |
from .. import Provider as CurrencyProvider
class Provider(CurrencyProvider):
# Format: (code, name)
currencies = (
("AED", "Dírham de los Emiratos Árabes Unidos"),
("AFN", "Afghaní"),
("ALL", "Lek albanés"),
("AMD", "Dram armenio"),
("ANG", "Florín de las Antillas Hola... | joke2k/faker | faker/providers/currency/es_ES/__init__.py | Python | mit | 6,293 |
import flask
import MemeRepo.db as db
import MemeRepo.funcs as fnc
from MemeRepo.config import config
def handle(code, uri):
result = db.get_file(uri)
if result == None:
return flask.render_template("error.html", msg="That file does not exist", code="400"), 400
else:
if result['ow... | carcinogoy/MemeRepo | MemeRepo/delete.py | Python | mit | 517 |
from wsgiref.handlers import CGIHandler
from wwag import app
CGIHandler().run(app)
| zhoutong/wwag | serve.py | Python | mit | 83 |
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
Development script of the ChemEnv utility to get the explicit permutations for coordination environments identified
with the separation plane algorithms (typically with coordination numbers >= 6)
"""
import itertools
impo... | materialsproject/pymatgen | dev_scripts/chemenv/explicit_permutations_plane_algorithm.py | Python | mit | 5,857 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2018-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Contributed Marshmallow fields."""
from __future__ import absolute_import, print_... | inveniosoftware/invenio-records-rest | invenio_records_rest/schemas/fields/marshmallow_contrib.py | Python | mit | 4,465 |
"This module creates the file githash.h with git hash."
import subprocess
RESULT = subprocess.run(["git", "describe", "--tags"],
stdout=subprocess.PIPE)
s = RESULT.stdout.decode("utf-8")
with open("githash.h", "w") as f:
s = """#ifndef SHG_GIT_HASH
#define SHG_GIT_HASH "{}"
#endif""".forma... | shgalus/shg | githash.py | Python | mit | 349 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Pasos para transformar proy a geod/proy/GK y exportar a DXF
from geod_proy import *
from toDXF import *
#
# 1) Configurar Proyecciones usadas
#
# 1.1) Proyección Mercator Transversal cualquiera.
lat_orig = gms2gyf(-33,52)
merid_c = gms2gyf(-61,14)
pserapio = config_p... | quijot/agrimpy-package | agrimpy/test.py | Python | mit | 1,621 |
import datetime
from django.conf import settings
from django import template
from django.core.cache import cache
from online_status.status import CACHE_USERS, CACHE_PREFIX_ANONYM_USER, TIME_OFFLINE, ONLY_LOGGED_USERS, status_for_user
from django.contrib.sessions.models import Session
register = template.Library(... | codefisher/codefisher_apps | online_status/templatetags/online_status_tags.py | Python | mit | 2,065 |
import json
from collections import OrderedDict
import openpyxl
from openpyxl.styles import Border, Side, Alignment, Font, NamedStyle
from openpyxl.utils.cell import get_column_letter
from directions.models import IstochnikiFinansirovaniya
from doctor_call.models import DoctorCall
from hospitals.tfoms_hospital import... | moodpulse/l2 | statistic/structure_sheet.py | Python | mit | 67,638 |
from .settings import Settings
from .logger import Logger
from .detection_result_recorder import DetectionResultRecorder
from .color_operations import ColorOperations
from .target_analyzer import TargetAnalyzer
from .background_color_nullifier import BackgroundColorNullifier
from .target_detectors import TargetDetector... | FlintHill/SUAS-Competition | UpdatedImageProcessing/UpdatedImageProcessing/TargetDetection/__init__.py | Python | mit | 668 |
import uuid
from google.appengine.api import memcache
class CollectionCache:
def __init__(self, timeout=480, hash=None):
self.contents = [];
if hash:
self.contents = memcache.get(hash)
self.timeout = timeout
def add(self, item):
hash = uuid.uuid1().hex
mem... | rmoskal/e-springpad | collection_cache.py | Python | mit | 845 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from csv import DictReader, DictWriter
from datetime import datetime
from os import environ
from sys import argv
from time import sleep
import requests
from requests_oauthlib import OAuth1
from urlparse import parse_qs
# (command, argument, input, output) = argv[1:]
# ... | geraldarthur/PrismJr | twitter.py | Python | mit | 5,815 |
import asyncio
import logging
from aiozk import exc, WatchEvent, Deadline
from .sequential import SequentialRecipe
log = logging.getLogger(__name__)
class DoubleBarrier(SequentialRecipe):
ZNODE_LABEL = 'worker'
def __init__(self, base_path, min_participants):
super().__init__(base_path)
se... | tipsi/aiozk | aiozk/recipes/double_barrier.py | Python | mit | 2,390 |
#!/usr/bin/env python
"""
BeginDate:20071001
CurrentRevisionDate:20071001
Development Version : net 001
Release Version: pre-release
Author(s): Mishtu Banerjee
Contact: mishtu@harmeny.com
Copyright: The Authors
License: Distributed under MIT License
[http://opensource.org/licenses/mit-license.html]
... | MishtuBanerjee/xaya | xaya/xayanet.py | Python | mit | 22,529 |
"""
Created on 16 May 2017
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
Note: time shall always be stored as UTC, then localized on retrieval.
"""
from scs_core.data.rtc_datetime import RTCDatetime
from scs_host.bus.i2c import I2C
from scs_host.lock.lock import Lock
# -------------------------------... | south-coast-science/scs_dfe_eng | src/scs_dfe/time/ds1338.py | Python | mit | 5,825 |
import numpy as np
from ..utils import check_random_state
class ChainWorld(object):
def __init__(self, left_length, left_reward, right_length, right_reward, on_chain_reward, p_return_to_start, random_state=None):
self.left_length = left_length
self.left_reward = left_reward
self.right_lengt... | dustinvtran/bayesrl | bayesrl/environments/chainworld.py | Python | mit | 1,441 |
from __future__ import print_function
from .SceneClass import Scene
from ..backends.base_backend import DrawingData
class ScenesManager(object):
def __init__(self):
self._scenes = {}
self._models = None
self.sounds = None
self._engine = None
self.currentSceneID = ""
... | jr-garcia/Engendro3D | e3d/scene_management/ScenesManagerClass.py | Python | mit | 2,253 |
# coding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
import logging
import os
import os.path
import re
from .command import exec_cmd
__author__ = 'Ingo Heimbach'
__email__ = 'i.heimbach@fz-juelich.de'
de... | IngoHeimbach/shallow-appify | shallow_appify/plugins/util/libpatch.py | Python | mit | 2,668 |
"""
WSGI config for keyformproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANG... | mostateresnet/keyformproject | keyformproject/wsgi.py | Python | mit | 405 |
from fontTools.misc import transform
from fontParts.base import normalizers
from fontParts.base.errors import FontPartsError
from fontParts.base.base import (
BaseObject,
TransformationMixin,
InterpolationMixin,
PointPositionMixin,
SelectionMixin,
IdentifierMixin,
dynamicProperty,
refere... | robofab-developers/fontParts | Lib/fontParts/base/component.py | Python | mit | 11,222 |
import _plotly_utils.basevalidators
class MaxpointsValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="maxpoints", parent_name="histogram.stream", **kwargs
):
super(MaxpointsValidator, self).__init__(
plotly_name=plotly_name,
parent... | plotly/python-api | packages/python/plotly/plotly/validators/histogram/stream/_maxpoints.py | Python | mit | 550 |
#!/usr/bin/python
from pymongo import MongoClient
client = MongoClient()
db=client.exampledatabase
collect1 = db.queries
for document in collect1.find():
print document | Tsiems/mobile-sensing-apps | tornado_bare/mongodb_example.py | Python | mit | 174 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
import random
from mla.base import add_intercept
class BasicRegression:
def __init__(self, method="sgd", eta=0.01, penalty='None', gamma=0.01,
tolerance=0.0001, max_iters=10000):
... | qianlv/MachineLearningAlgorithm | mla/LinearModel.py | Python | mit | 3,742 |
from inspect import currentframe, getfile
from itertools import product
from random import sample
import os
import math
import numpy as np
from stripstream.utils import flatten
from utils import set_base_conf, Pose, box_body, get_name, set_manipulator_conf, mirror_arm_config, open_gripper, close_gripper, top_grasps,... | caelan/stripstream | robotics/openrave/problems.py | Python | mit | 6,418 |
class ConfigError(Exception):
"""
Base class for all exceptions raised by *configmanager* that user may be able to recover from.
"""
pass
class NotFound(ConfigError):
"""
Section or item with the requested name or path is not found
in the section it is being requested from.
.. attribu... | jbasko/configmanager | configmanager/exceptions.py | Python | mit | 1,324 |
"""Hello message tests."""
from pyof.v0x01.symmetric.hello import Hello
from tests.unit.test_struct import TestStruct
class TestHello(TestStruct):
"""Hello message tests (also those in :class:`.TestDump`)."""
@classmethod
def setUpClass(cls):
"""Configure raw file and its object in parent class (... | kytos/python-openflow | tests/unit/v0x01/test_symmetric/test_hello.py | Python | mit | 506 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | Azure/azure-sdk-for-python | sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/aio/operations/_diagnostic_settings_operations.py | Python | mit | 12,838 |
class intSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each integer in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty set of integers"""
self.vals = []
def __str__(self):
"""Returns... | pparacch/PlayingWithPython | computationAndProgrammingUsingPython/src/classesAndObjects/week6_L11_part05.py | Python | mit | 1,393 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""""""
import inspect
import colony
from colony.entities.attributes import Age
__title__ = "GameTime"
__author__ = "DeflatedPickle"
__version__ = "1.1.1"
class GameTime(object):
def __init__(self, parent):
self.parent = parent
self._time = colony.... | DeflatedPickle/Colony | gametime.py | Python | mit | 2,265 |
import uuid
import xbmc
import xbmcaddon
settings = {}
addon = xbmcaddon.Addon()
settings['debug'] = addon.getSetting('debug') == "true"
settings['powersave_minutes'] = int(addon.getSetting('powersave_minutes'))
settings['version'] = addon.getAddonInfo('version')
settings['uuid'] = ... | devshans/script.service.hdmipowersave | resources/lib/settings.py | Python | mit | 415 |
from django import forms
from seednetwork.forms import SeedNetworkBaseForm
from seedlibrary.models import Event
GRAIN_CHOICES = (
('-','-'),
('amaranth','Amaranth'),
('barley', 'Barley'),
('buckwheat', 'Buckwheat'),
('corn', 'Corn'),
# ('kaniwa', 'Kaniwa'),
('mil... | RockinRobin/seednetwork | seedlibrary/forms.py | Python | mit | 6,875 |
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from pyramid_sqlalchemy import Session
from ..forms.news import NewsAddForm, NewsForm
from ..models.news import NewsModel
@view_config(route_name='news', renderer='templates/news.jinja2')
def news_view(request):
news = Session.query(... | fosstp/fosstp | fosstp/views/news.py | Python | mit | 2,170 |
import random
from plugin import Plugin
class Flatter(Plugin):
def help_text(self, bot):
return bot.translate("flatter_help")
def on_msg(self, bot, user_nick, host, channel, message):
if message.lower().startswith(bot.translate("flatter_cmd")):
if len(message.split()) >= 2:
if bot.getlanguage... | k4cg/Rezeptionistin | plugins/flatter.py | Python | mit | 687 |
import _plotly_utils.basevalidators
class LineValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="line", parent_name="scatter3d.marker", **kwargs):
super(LineValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/scatter3d/marker/_line.py | Python | mit | 5,005 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 26 23:44:04 2015
@author: willy
"""
import random
import hashlib
import argparse
import shutil, os, time
def write_a_file(destination, character, size=1):
"""
Create random file with specifyed size (in GBytes)
and copy them to "destina... | willyrv/microSDcheck | microSDcheck.py | Python | mit | 3,837 |
from contextlib import redirect_stderr
from io import StringIO
from pathlib import Path
from bernard.actors import (
AutomodDomainWatcher,
AutomodUserWatcher,
Banner,
Modmailer,
Notifier,
Nuker,
ToolboxNoteAdder,
)
from bernard.loader import load_yaml_config
from .helper import BJOTest
c... | leviroth/bernard | test/test_system.py | Python | mit | 2,784 |
# edge detection and colorspaces, includes laplacian and sobel filters that are tuned to the pink whiffle ball
import cv2
import numpy as np
def nothing(x):
pass
cap = cv2.VideoCapture(0)
cv2.namedWindow('frame1')
kernel = np.ones((5,5),np.uint8)
# create trackbars for color change, tuned to pink whiffle ball
#... | FRC900/2016VisionCode | preseason_edge_detection/edge_detection.py | Python | mit | 1,892 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-19 06:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('condensed_urls', '0001_initial'),
]
operations = [
migrations.AddField(
... | ezarowny/url-condenser | url_condenser/condensed_urls/migrations/0002_condensedurl_visited_count.py | Python | mit | 456 |
import logging
import gym
import numpy as np
from universe import spaces
from universe import vectorized
from universe.wrappers.gym_core import gym_core_action_space
logger = logging.getLogger(__name__)
def slither_vnc(space=False, left=False, right=False):
return [spaces.KeyEvent.by_name('space', down=space),
... | openai/universe | universe/wrappers/experimental/action_space.py | Python | mit | 6,525 |
from map import Map
import networkx as nx
import matplotlib.pyplot as plt
import random
import numpy as np
from scipy.spatial import Delaunay
pts = np.array([[random.random(), random.random()] for i in range(10)])
delTri = Delaunay(pts)
print(delTri.vertices)
G = Map(40, 3, 2, 10, 10, 5, 0)
#pos_dict = {G.map.nodes()... | Favidavid/graphwars | graphwars/test_map.py | Python | mit | 420 |
import os
import requests
if __name__ == "__main__":
session = requests.Session()
data = {"email": "admin@knex.com", "password": "admin"}
session.post("http://localhost:5000/api/users/login", data=data)
for file in os.listdir("."):
if file.endswith(".json"):
text = open(file, "r")... | Drakulix/knex | evalData/testdata_insertion.py | Python | mit | 897 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio module for common role based access control."""
from __future__ import ab... | tiborsimko/invenio-access | invenio_access/ext.py | Python | mit | 6,195 |
from audio_pipeline.util import Tag
import re
from audio_pipeline.util import Exceptions
class BaseTag(Tag.Tag):
def extract(self):
super().extract()
if self._value is not None:
self._value = self._value[0]
def set(self, value=Tag.CurrentTag):
if value is not Tag.CurrentT... | hidat/audio_pipeline | audio_pipeline/util/format/Vorbis.py | Python | mit | 6,254 |
"""
Alternative convolution implementations for Theano
"""
import numpy as np
import theano
import theano.tensor as T
## 1D convolutions
def conv1d_sc(input, filters, image_shape=None, filter_shape=None, border_mode='valid', subsample=(1,)):
"""
using conv2d with a single input channel
"""
if borde... | diogo149/Lasagne | lasagne/theano_extensions/conv.py | Python | mit | 8,695 |
#!/usr/bin/python2.7
from PySide.QtCore import *
from PySide.QtGui import *
from PySide import *
import sys
import monitor
from monitorthread import MonitorThread
from monitordata import MonitorData
class HMStandardItemModel( QStandardItemModel ):
monitor_data = None
values = None
previous_values = None
... | gary-pickens/HouseMonitor | housemonitor/qt/hm.py | Python | mit | 5,321 |
#!/usr/bin/env python
def add(a, b):
print("ADDING %d + %d" %(a, b))
return a + b
def subtract(a, b):
print("SUBTRACTING %d - %d" %(a, b))
return a - b
def multiply(a, b):
print("MULTIPLYING %d * %d" %(a, b))
return a * b
def devide(a, b):
print("DEVIDING %d / %d" %(a, b))
return a /... | davvi/Hardway3 | ex21.py | Python | mit | 741 |
#!/usr/bin/env python
from nose.tools import assert_equal, assert_less_equal, assert_greater_equal
from slcli.sl_cli import travel, trip2str, main
from datetime import datetime, timedelta
import sys
import re
from io import StringIO
from argparse import Namespace
def assert_matches(string, pattern, single_char, line... | Sebelino/SL-CLI | slcli/test/test_cli.py | Python | mit | 12,105 |
# !env python3
import sys
import pytest
if "-c" in sys.argv:
sys.argv.remove("-c")
args = ['--cov-config', '.coveragerc',
'--cov-report', 'html',
'--cov-report', 'term-missing',
'--cov',
'.']
else:
args = []
args.append('--tb=native')
sys.argv.extend(args)
... | skk/eche | runtests.py | Python | mit | 417 |
from sqlalchemy import create_engine, distinct, func, desc
from sqlalchemy.orm import sessionmaker
from geoalchemy2 import functions as geo_func
from datetime import datetime, timedelta
import config
from base import Base
from schema import Tweet, Hashtag, Picture, Division
import codecs, json
class Database:
def ... | alexurquhart/webgis | app/database.py | Python | mit | 7,684 |
import json, requests, os, sys, util, load_messages, shutil, simulate
# Load the list of groups the user is a member of
print("Loading user group information")
groups = util.get_rest('groups', params={"per_page": 100})
if groups is None:
print("Unable to load user's group information")
sys.exit(1)
sim_ids = m... | Narbulus/GroupmeSimulator | setup.py | Python | mit | 2,067 |
import unittest
from geopar.triangle_class import Triangle
from geopar.triangulated_figure_class import TriangulatedFigure
from geopar.angle_class import Angle
__author__ = 'ebraude'
# URL1: https://docs.google.com/presentation/d/1nddxo9JPaoxz-Colod8qd6Yuj_k7LXhBfO3JlVSYXrE/edit?usp=sharing
class TestTriangulatedFi... | satbekmyrza/geopar | tests/test_triangulated_figure.py | Python | mit | 5,876 |
from threading import local
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern, ResolverMatch
from django.utils.encoding import smart_str
from django.utils import lru_cache
from urlmiddleware.base import MiddlewareResolver404
from urlmiddlewa... | leTel/django-urlmiddleware | urlmiddleware/urlresolvers.py | Python | mit | 3,234 |
import time
import numpy as np
from keras import backend as K
from music_tagger_cnn import MusicTaggerCNN
from music_tagger_crnn import MusicTaggerCRNN
import audio_processor as ap
import pdb
def librosa_exists():
try:
__import__('librosa')
except ImportError:
return False
else:
re... | keunwoochoi/music-auto_tagging-keras | example_feat_extract.py | Python | mit | 1,936 |
#gets COUNT tweets from user's timeline
import os
import tweepy
import cPickle as pickle
from config import Config
#constants
COUNT = 200
#tweepy configuration
keys = file('config.cfg')
cfg = Config(keys)
consumer_key= cfg.consumer_key
consumer_secret= cfg.consumer_secret
access_token= cfg.access_token
access_toke... | dnr2/fml-twitter | tweets.py | Python | mit | 1,301 |
# Query Github public timeline using Bigquery and display top new repositories
# Modified from sources
## https://developers.google.com/bigquery/bigquery-api-quickstart#completecode
## https://gist.github.com/igrigorik/f8742314320e0a4b1a89
import httplib2
import pprint
import sys
import time
import json
import logging... | harishvc/tools | bigquery-github/TopGithubRepos.py | Python | mit | 4,367 |
from sympy.core import pi, oo, symbols, Function, Rational
from sympy.functions import exp, log, sqrt, erf, erfc, gamma, loggamma
# from sympy import ccode
from oclcode import oclcode
x, y, z = symbols('x,y,z')
i = symbols('i', integer=True)
def asserteq(a, b):
if a != b:
raise AssertionError("%s != %s"... | hunse/codify | codify/test_oclcode.py | Python | mit | 1,803 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | Azure/azure-sdk-for-python | sdk/keyvault/azure-mgmt-keyvault/azure/mgmt/keyvault/v2020_04_01_preview/operations/_private_link_resources_operations.py | Python | mit | 4,897 |