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/python3
#Filename: expression.py
length = 5
breadth = 2
area = length * breadth
print('Area is', area)
print('Perimeter is', 2 * (length + breadth))
| louistin/thinkstation | a_byte_of_python/unit_4_5_6_basic/expression.py | Python | mit | 161 |
def StringIntersect(str1,str2):
intr = []
for i in str1:
if i in str2 and i not in intr:
intr.append(i)
d = {}
for i in intr:
d[i] = min(str1.count(i),str2.count(i))
output = []
for i in d.keys():
output.append(i*d[i])
output.sort()
return ''.join(output)
def CountBit(num):
... | smenon8/AlgDataStruct_practice | practice_problems/StringIntersection.py | Python | mit | 702 |
from .base import configure_app, create_app
import re
find_urls = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
class MailTemplatesAuthControllerTests(object):
def setup(self):
self.app = create_app(self.app_config, True)
class TestMailTemplatesAuthControll... | axant/tgapp-mailtemplates | tests/test_controller_auth.py | Python | mit | 626 |
# -*- coding: utf-8 -*-
"""Startup utilities"""
import os
import sys
from functools import partial
import paste.script.command
import werkzeug.script
etc = partial(os.path.join, 'parts', 'etc')
DEPLOY_INI = etc('deploy.ini')
DEPLOY_CFG = etc('deploy.cfg')
DEBUG_INI = etc('debug.ini')
DEBUG_CFG = etc('debug.cfg')
_... | aadamski/presence-analyzer-aadamski | src/presence_analyzer/script.py | Python | mit | 3,701 |
"""Compute McCabe's Cyclomatic Metric.
This routine computes McCabe's Cyclomatic metric for the whole file.
"""
from metricbase import MetricBase
mccabe_keywords = [
'assert',
'break',
'continue',
'elif',
'else',
'for',
'if',
'while']
class McCabeMetric(MetricBase):
"""Comp... | GadgetSteve/metrics | metrics/mccabe.py | Python | mit | 1,278 |
import colorname
import glob
import os
import re
import numpy
from loadseg import AbstractSegmentation
from scipy.io import loadmat
from scipy.misc import imread
from collections import namedtuple
class AdeSegmentation(AbstractSegmentation):
def __init__(self, directory=None, version=None):
# Default to v... | bonyuta0204/NetDissec | src/adeseg.py | Python | mit | 5,296 |
__author__ = 'yusaira-khan'
import unittest
import un_iife_ize.un_iife_ize as un_iife_ize
class CheckVar(unittest.TestCase):
def test_simple(self):
statement = [('var hello,world=5;', 0)]
exp = [('hello=undefined,world=5;', 0)]
v = un_iife_ize.Var(statement)
v.extract_all()
... | yusaira-khan/un-iife-ize | tests/vars.py | Python | mit | 2,836 |
# -*- coding: utf-8 -*-
"""
InformationMachineAPILib.Models.GetNutrientsWrapper
"""
from InformationMachineAPILib.APIHelper import APIHelper
from InformationMachineAPILib.Models.NutrientInfo import NutrientInfo
from InformationMachineAPILib.Models.MetaBase import MetaBase
class GetNutrientsWrapper(object):
... | information-machine/information-machine-api-python | InformationMachineAPILib/Models/GetNutrientsWrapper.py | Python | mit | 2,942 |
"""Depth-First Search is a search strategy where, starting at the root of a
tree of nodes to explore, the first child node encountered is explored
continually until a leaf node is reached, whereupon the parent of the leaf node
will have it's next child explored, effectively giving priority to nodes
farthest from the ro... | PhilipCastiglione/learning-machines | uninformed_search/algorithms/dfs.py | Python | mit | 4,778 |
from django.conf.urls import url
from .views import *
urlpatterns = [
url(r'^(?P<command>[A-Za-z0-9]+)$',
view=IndexView.as_view(), name='index'),
url(r'^$', view=IndexView.as_view(), name='index'),
url(r'^add/$',view=DeviceAddView.as_view(), name='add'),
url(r'^(?P<device_id>[0-9]+)/remove/$'... | MikaelSchultz/dofiloop-sentinel | sentinel/device/urls.py | Python | mit | 1,788 |
from __future__ import division, print_function
import numpy as np
import numpy.random as ra
import scipy.interpolate as sci
from ..utils import assign_value_if_none
def simulate_times(lc, use_spline=False, bin_time=None):
"""
Assign (simulate) photon arrival times to event list, using the
acceptance-reje... | evandromr/stingray | stingray/simulator/base.py | Python | mit | 2,875 |
from typing import Optional, Iterable, Iterator, List
import itertools
import os.path
from pydev_docker import models
from pydev_docker import utils
class ContainerOptions:
"""
Options for running a docker container
"""
DEFAULT_PYPATH_DIR = "/pypath"
DEFAULT_SRC_DIR = "/src"
def __init__(sel... | Rastii/pydev_docker | pydev_docker/options.py | Python | mit | 4,867 |
# -*- coding: iso-8859-15 -*-
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
#
# Copyright (c) 2015 Tom Kralidis
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files... | ocefpaf/pycsw | setup.py | Python | mit | 5,698 |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from compas.artists import Artist
class GHArtist(Artist):
"""Base class for all GH artists.
"""
def __init__(self, **kwargs):
super(GHArtist, self).__init__(**kwargs)
| compas-dev/compas | src/compas_ghpython/artists/artist.py | Python | mit | 300 |
from enum import Enum
class ImageAlignType(Enum):
"""Image alignment"""
Default = 1
Left = 2
Right = 3
Center = 4
| jablonskim/jupyweave | jupyweave/settings/align_types.py | Python | mit | 137 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import getopt
import sys
import math
options, _ = getopt.getopt(sys.argv[1:], '', ['file='])
filename = 'Ugb_uH72d0I_8_17_memView_27K.npy'
dpi = 150
fig_size = (2560 / dpi, 1440 / dpi)
for opt in options:
if opt[0] == '--file':
... | HimariO/VideoSum | tasks/video/Visualize/MemoryView.py | Python | mit | 2,318 |
#Short module amiright
def main(message):
return [["purgeText", int(message.content.split(' ', 1)[1])]]
| ubidiscordbot/ubi | src/lib/modules/clear.py | Python | mit | 108 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-13 01:06
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('redditpoller', '0020_auto_20170311_1503'),
]
operation... | ericleepa/watcherforreddit | redditpoller/migrations/0021_auto_20170312_2106.py | Python | mit | 708 |
from __future__ import print_function
import os
from setuptools import setup
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# Setup
# 1. zip_safe needs to be False since we need access to templates
setup(
name="TimeVis",
v... | gaoce/TimeVis | setup.py | Python | mit | 1,191 |
# -*- coding: utf-8 -*-
"""
|oauth1| Providers
--------------------
Providers which implement the |oauth1|_ protocol.
.. autosummary::
OAuth1
Bitbucket
Flickr
Meetup
Plurk
Twitter
Tumblr
UbuntuOne
Vimeo
Xero
Xing
Yahoo
"""
import abc
import binascii
import datetime
i... | jasco/authomatic | authomatic/providers/oauth1.py | Python | mit | 38,859 |
#!/Users/patron/Desktop/maps/django-project/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| abzaloid/maps | django-project/bin/django-admin.py | Python | mit | 161 |
# 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.
# --------------------------------------------------------------------... | Azure/azure-sdk-for-python | sdk/storage/azure-storage-blob/samples/blob_samples_common_async.py | Python | mit | 9,540 |
# 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/healthbot/azure-mgmt-healthbot/azure/mgmt/healthbot/__init__.py | Python | mit | 680 |
from scoring_engine.config_loader import ConfigLoader
config = ConfigLoader()
| pwnbus/scoring_engine | scoring_engine/config.py | Python | mit | 80 |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HMM9_if_IsolatedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HMM9_if_IsolatedLHS.
"""
# Flag this instance as c... | levilucio/SyVOLT | UMLRT2Kiltera_MM/Properties/from_thesis/HMM9_if_IsolatedLHS.py | Python | mit | 2,478 |
#!/usr/bin/env python
import argparse
import json
import sys
import os
import requests
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
parser = argparse.ArgumentParser()
parser.add_argument('repo', help='GitHub organization and repository')
parser.add_argument('bucket', help... | flywheel-io/exchange | bin/validate-storage.py | Python | mit | 2,078 |
from OpenGLCffi.GLES3 import params
@params(api='gles3', prms=['pname', 'param'])
def glConservativeRasterParameteriNV(pname, param):
pass
| cydenix/OpenGLCffi | OpenGLCffi/GLES3/EXT/NV/conservative_raster_pre_snap_triangles.py | Python | mit | 142 |
from urls_base import Urls
from slugify import slugify
from settings import ASSET_TAG
urls = Urls()
urls.add('index', '/')
urls.add('projects', '/projects/')
urls.add('blog', '/blog/')
urls.add('404.html', '/404.html')
urls.add('post', '/post/{slug}.html',
format_func=lambda **kwargs: dict(slug=slugify(kwar... | plumdog/myhome | urls.py | Python | mit | 620 |
import zipfile
import imghdr
from django import forms
from .models import Image, ImageBatchUpload, Album
class AlbumAdminForm(forms.ModelForm):
class Meta:
model = Album
fields = '__all__'
def clean(self):
cleaned_data = self.cleaned_data
if cleaned_data.get('authorized_u... | dsimandl/teamsurmandl | gallery/forms.py | Python | mit | 1,431 |
from twisted.internet.defer import Deferred, DeferredQueue, succeed
from collections import defaultdict
class DeferredPriorityQueue(DeferredQueue):
def __init__(self):
DeferredQueue.__init__(self, None, None)
self.pending = defaultdict(list)
def put(self, priority, obj):
if self.waiti... | ryansb/netHUD | nethud/dpqueue.py | Python | mit | 927 |
import numpy as np
from sklearn import preprocessing
import sklearn.cluster as cl
from latools.helpers.stat_fns import nominal_values
class classifier(object):
def __init__(self, analytes, sort_by=0):
"""
Object to fit then apply a classifier.
Parameters
----------
analyte... | oscarbranson/latools | latools/filtering/classifier_obj.py | Python | mit | 8,422 |
from django.conf.urls import patterns, include, url
from django.views.generic.base import RedirectView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'core.views.home', name='home'),
url(r'^morsel/create/$', 'core... | tsaylor/remember-forever | remember_forever/urls.py | Python | mit | 1,038 |
from . import ast as A
from . import runtime
from . import scope as S
from . import static
from . import token as K
from . import types as T
from contextlib import contextmanager
from llvmlite import binding
from llvmlite import ir
from os.path import isdir, isfile
from os.path import join
import os.path
import re
nam... | philipdexter/rain | rain/module.py | Python | mit | 12,253 |
from setuptools import setup
setup(
name="tyoi.OAuth2",
version="0.2.1",
author="Ryan Horn",
author_email="ryan.horn.web@gmail.com",
description=("Implements the client side of the OAuth 2 protocol"),
keywords="oauth oauth2 auth authentication",
url="https://github.com/ryanhorn/tyoiOAuth2",... | ryanhorn/tyoiOAuth2 | setup.py | Python | mit | 463 |
from setuptools import setup
setup(
name='PrintNodeApi',
version='0.2.0',
description="Python Client for PrintNode's API",
author='printnode',
author_email='support@printnode.com',
packages=['printnodeapi'],
install_requires=['requests','future'])
| PrintNode/PrintNode-Python | setup.py | Python | mit | 278 |
import re
import html
# The regular string.split() only takes a max number of splits,
# but it won't unpack if there aren't enough values.
# This function ensures that we always get the wanted
# number of returned values, even if the string doesn't include
# as many splits values as we want, simply by filling in extra... | Tigge/platinumshrimp | utils/str_utils.py | Python | mit | 1,370 |
from src.greedy_algorithms import find_ample_city
from src.greedy_algorithms import find_majority_element
from src.greedy_algorithms import GasCity
from src.greedy_algorithms import three_sum
from src.greedy_algorithms import trapped_water
from src.greedy_algorithms import two_sum
class TestTwoSum(object):
"""
... | jakubtuchol/epi | test/test_greedy_algorithms.py | Python | mit | 2,161 |
"""The following code is (c) sliceofcode 2017."""
"""Source: https://github.com/sliceofcode/dogbot/blob/master/dog/core/ext/exec.py """
"""
Handy exec (eval, debug) cog. Allows you to run code on the bot during runtime. This cog
is a combination of the exec commands of other bot authors:
Credit:
- Rapptz (Danny)
... | xshotD/lolbot | cogs/eval.py | Python | mit | 4,708 |
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
class Solution:
def connect(self, root: 'Node') -> 'Node':
curr = ro... | jiadaizhao/LeetCode | 0101-0200/0116-Populating Next Right Pointers in Each Node/0116-Populating Next Right Pointers in Each Node.py | Python | mit | 612 |
import ast
import base64
import itertools
from functools import lru_cache
import cpapilib
from flask import session
from app import app
OBJECTS_DICTIONARY = None
@lru_cache(maxsize=5000)
def uid_name(uid_obj):
for obj in OBJECTS_DICTIONARY:
if uid_obj == obj['uid']:
return obj['name']
... | themadhatterz/cpapi | app/checkpoint.py | Python | mit | 6,936 |
from io_processing.result_interpreter.abst_result_interpreter import AbstractInterpreter, \
InterpreterOptions
from io_processing.surveillance_handler import CheckpointHandler
from tools.general import RefList, General as G
from enum import Enum
import logging
class CheckpointInterpreter(AbstractInterpreter):
... | PhilippMundhenk/IVNS | ECUSimulation/io_processing/result_interpreter/checkpoint_interpreter.py | Python | mit | 29,278 |
from Tkinter import *
import os
import tkMessageBox
class syndelcnsl:
def show(self,mainfrm):
#-----------------------------------------This is mainframe--------------------------------------------
syndelfrm=Frame(mainfrm,relief=SOLID,borderwidth=1,bg="white")
txtfont=("FreeSerif", 11,"bold")
fnt=("Fre... | d4rkl0rd3r3b05/Firewall | Firewall/syndelcnsl.py | Python | mit | 5,853 |
import requests
__url = 'http://www.baidu.com/s?wd=' # 搜索请求网址
def page(word):
r = requests.get(__url + word)
if r.status_code == 200: # 请求错误(不是200)处理
return r.text
else:
print(r.status_code)
return False
| JianmingXia/StudyTest | KnowledgeQuizTool/MillionHeroes/baiduSearch/get.py | Python | mit | 277 |
'''
Created on Feb 28, 2013
@author: Santiago Diaz M - salchoman@gmail.com
'''
from core.plugs import fuzzdb_plugin
from core.utils.wsresponse_object import wsResponse
from core.data import logger
from core.Singleton import Singleton
import sys
import inspect
import threading
import Queue
import gtk
class PluginMan... | salcho/antares | core/PluginManager.py | Python | mit | 5,590 |
# -*- coding: utf-8 -*-
import abc
import tensorflow as tf
from inferbeddings.models import embeddings
import sys
class BaseModel(metaclass=abc.ABCMeta):
def __init__(self, entity_embeddings=None, predicate_embeddings=None, similarity_function=None,
reuse_variables=False, *args, **kwargs):
... | uclmr/inferbeddings | inferbeddings/models/base.py | Python | mit | 7,187 |
from .consts import *
from .factory import SocketFactoryRegistry
from . import txzmq_impl
| cordis/pycloudia | pycloudia/channels/__init__.py | Python | mit | 90 |
from .hand import Hand, TakenCards
class Agent(object):
"""An Agent is a player in the game and may be controlled by a human or
by computer.
"""
def __init__(self, name):
self.name = name
self.hand = Hand()
self.taken_cards = TakenCards()
self.score = 0
def __str_... | reidlindsay/gostop | gostop/core/agent.py | Python | mit | 794 |
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def index():
# return 'hello flask'
# return '<input type="button" value="click me!!">'
# return '<input type="text">'
# return '<input type="password">'
# return '<input type="date">'
# return '<input type=... | seerjk/reboot06 | 06/flask_web.py | Python | mit | 1,609 |
''' This is the library for getting DotA2 insight information.
Problem:
there was no way to get dota internal data about heroes, their abilities...
in suitable for further work form.
Solution:
this library allows you to get access to all the data in the in-game files.
But information about single her... | gasabr/AtoD | atod/__init__.py | Python | mit | 806 |
from Utb import Utb
"""
astrae le utb di tipo provincia per postgres
"""
class ProvinciaPg(Utb):
def __init__(self,header="header",istat=-1):
Utb.__init__(self, header, 'pro', istat)
def getSelect(self):
query=" SELECT tc_istat_id FROM tc_istat JOIN province ON tc_istat.tc_provincia_id = province.tc_provinc... | arpho/mmasgis5 | mmasgis/ProvinciaPg.py | Python | mit | 558 |
# -*- coding: utf-8 -*-
'''
Created on 2014年7月23日
@author: fengzishiren
@mail: xiaoyaozi106@163.com
'''
import re
import MySQLdb
import os
import sys
from settings import *
__version__ = '0.1'
__date__ = '2014-07-23'
__updated__ = '2014-07-23'
FORMAT_ARGS = {'author': 'pysugar', 'date': __date__, 'version': __versio... | fengzishiren/pysugar | src/pysugar.py | Python | mit | 5,899 |
"""
Copyright (c) 2016, Jose Dolz .All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the f... | josedolz/SemiDenseNet | src/LiviaNet/generateNetwork.py | Python | mit | 8,290 |
class LiPo:
def __init__(self, voltage, current, cells, capacity):
self.voltage = voltage
self.current = current
self.cells = cells
self.capacity = capacity
def ChargePercentage(self):
v = self.voltage.GetVoltage() / self.cells
percent = 100 * (v - 3.7) / (4.2 - ... | curtisblack/R2D2 | LiPo.py | Python | mit | 745 |
import ConfigParser
from optparse import OptionParser
import subprocess, sys, os
if sys.platform == "win32":
import shutil
shutil.rmtree(os.path.join(os.getenv('APPDATA'),'Subversion','auth'), True)
cwd = os.getcwd()
def vararg_cb(option, opt_str, value, parser):
assert va... | ktan2020/legacy-automation | tools/fetch.py | Python | mit | 2,850 |
# -*- coding: utf-8 -*-
"""
ast
~~~
The `ast` module helps Python applications to process trees of the Python
abstract syntax grammar. The abstract syntax itself might change with
each Python release; this module helps to find out programmatically what
the current grammar looks like and allows... | MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.1/Lib/ast.py | Python | mit | 11,827 |
import numpy
import six
import theano
from numpy.testing import assert_allclose, assert_raises
from theano import tensor
from blocks.bricks import (Identity, Linear, Maxout, LinearMaxout, MLP, Tanh,
Sequence, Random)
from blocks.bricks.base import application, Brick, lazy, NoneAllocation
fro... | nke001/attention-lvcsr | libs/blocks/tests/bricks/test_bricks.py | Python | mit | 15,113 |
# Copyright (c) Jean-Paul Calderone
# See LICENSE file for details.
"""
Unit tests for L{OpenSSL.crypto}.
"""
from unittest import main
import os, re
from subprocess import PIPE, Popen
from datetime import datetime, timedelta
from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey, PKeyType
from OpenSSL.crypto i... | yasoob/PythonRSSReader | venv/lib/python2.7/dist-packages/OpenSSL/test/test_crypto.py | Python | mit | 104,799 |
from __future__ import unicode_literals
from django.test import TestCase
from wtl.wtlib.models import Library, LibraryVersion
from wtl.wtlib.tests.factories import (LibraryFactory, LibraryVersionFactory,
ProjectFactory)
class LibraryTestCase(TestCase):
def test_str(self):
... | elegion/djangodash2013 | wtl/wtlib/tests/models.py | Python | mit | 2,921 |
import weakref
import functools
import itertools
from mongoengine.common import _import_class
from mongoengine.errors import DoesNotExist, MultipleObjectsReturned
__all__ = ("BaseDict", "BaseList", "EmbeddedDocumentList")
class BaseDict(dict):
"""A special dict so we can watch any changes"""
_dereferenced =... | elephanter/mongoengine | mongoengine/base/datastructures.py | Python | mit | 15,294 |
from datetime import date, datetime, time, timedelta
from django.contrib import admin
from django.utils import timezone
from enrichmentmanager.models import Teacher, Student, EnrichmentOption, EnrichmentSlot, EnrichmentSignup, EmailSuppression
from simple_history.admin import SimpleHistoryAdmin
class EditableUntilLi... | rectory-school/rectory-apps | enrichmentmanager/admin.py | Python | mit | 4,641 |
import re
import Queue
import HTMLParser
import dateutil.parser as parser
class TwitterData:
#Twitter Datum properties
tweet_fields_list = ['id', 'user_id', 'in_reply_to_status_id', 'in_reply_to_user_id', 'favorited', 'retweeted', 'retweet_count', 'lang', 'created_at']
tweet_text_fields_list = ['tweet_id... | kuzeko/Twitter-Importer | twitter_helper/twitter_data.py | Python | mit | 8,560 |
"""myproject
"""
__author__ = 'myproject:author_name'
__email__ = 'myproject:author_email'
#----------------------------------------------------------------------
def hello_world(extend_hello=False):
"""prints hello world
:returns: None
:rtype: None
"""
print 'Hello World!{}'.format(' Beautiful ... | diszgaurav/projecture | projecture/projects/python/myproject/myproject/myproject.py | Python | mit | 353 |
import json
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth import logout
from django.contrib.auth import update_session_auth_hash
from rest_framework import status
from rest_framework import views
from rest_framework import viewsets
from rest_framework.permi... | KonichiwaKen/band-dashboard | authentication/views.py | Python | mit | 4,259 |
#!/usr/bin/env python
'''
Created on Feb 17, 2015
@author: norris
'''
import re, sys, os, argparse, glob, time, datetime, socket, random
from solvers import *
solveropts = getsolvers()
def readFeatures(dirname='anamod_features'):
files=glob.glob(dirname + '/*.anamod')
featuresre= re.compile(r'========([^=]+)=... | LighthouseHPC/lighthouse | sandbox/scripts/anamod2arff.py | Python | mit | 18,296 |
"""
This little helper takes Lebedev point and weight data from [1] and produces JSON files.
[1]
https://people.sc.fsu.edu/~jburkardt/datasets/sphere_lebedev_rule/sphere_lebedev_rule.html
"""
import os
import re
import numpy as np
def read(filename):
data = np.loadtxt(filename)
azimuthal_polar = data[:, :2]... | nschloe/quadpy | tools/lebedev/import_lebedev.py | Python | mit | 4,694 |
# Check dependencies
import PIL, PIL.Image, PIL.ImageTk
import aggdraw
import affine
import itertools
def grouper(iterable, n):
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=None, *args)
# Main class
class AggRenderer:
"""
This class is used to draw each feature with aggdra... | karimbahgat/PyAgg | __private__/temp_dev/rendererclass3orrevert.py | Python | mit | 12,788 |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Doriancoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet."""
from test_framework.test_framework import DoriancoinTestFramework
from test_fram... | doriancoins/doriancoin | test/functional/wallet_basic.py | Python | mit | 21,630 |
import argparse
import asyncio
import logging
import sys
from pyintesishome import IntesisHome, IntesisHomeLocal
from pyintesishome.const import (
DEVICE_AIRCONWITHME,
DEVICE_ANYWAIR,
DEVICE_INTESISHOME,
DEVICE_INTESISHOME_LOCAL,
)
_LOGGER = logging.getLogger("pyintesishome")
async def main(loop):
... | jnimmo/pyIntesisHome | examples/cli_example.py | Python | mit | 2,243 |
from django.db import models
from constituencies.models import Constituency
class Boundary(models.Model):
constituency = models.ForeignKey( Constituency )
boundary = models.TextField()
zoom = models.IntegerField()
north = models.FloatField()
south = models.FloatField()
east = models.FloatField(... | electionleaflets/electionleaflets | electionleaflets/apps/boundaries/models.py | Python | mit | 454 |
import _plotly_utils.basevalidators
class TickvalssrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name="tickvalssrc",
parent_name="scatter3d.marker.colorbar",
**kwargs
):
super(TickvalssrcValidator, self).__init__(
plotly_... | plotly/plotly.py | packages/python/plotly/plotly/validators/scatter3d/marker/colorbar/_tickvalssrc.py | Python | mit | 461 |
"""Tests."""
from typing import List
import pytest
from bs4 import element
@pytest.mark.sphinx("html", testroot="figure")
def test_figure(img_tags: List[element.Tag]):
"""Test."""
image = img_tags[0]
assert image.get("src") == "https://i.imgur.com/611EovQh.jpg"
assert image.get("alt") == "https://i.i... | Robpol86/sphinxcontrib-imgur | tests/unit_tests/test_rendered_figure.py | Python | mit | 1,528 |
from AsynMongo import Collection
| XianwuLin/AsynMongo | __init__.py | Python | mit | 33 |
# encoding: utf-8
# 为了 Python3 的兼容,如果你用的 Python2.7
from __future__ import print_function, division
import tensorflow as tf
print('Loaded TF version', tf.__version__, '\n\n')
# Tensor 在数学中是“张量”
# 标量,矢量/向量,张量
# 简单地理解
# 标量表示值
# 矢量表示位置(空间中的一个点)
# 张量表示整个空间
# 一维数组是矢量
# 多维数组是张量, 矩阵也是张量
# 4个重要的类型
# @Variable 计算图谱中的变量
# ... | karst87/ml | 01_openlibs/tensorflow/02_tfgirls/TensorFlow-and-DeepLearning-Tutorial-master/Season1/1-3/run.py | Python | mit | 3,407 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
import sys
import time
sqlite_file = '/var/db/BrightnessMonitor/db.sqlite'
table = 'data'
vartime = 'time'
vardata = 'data'
con = None
cur = None
def create():
'''
Creates database table 'data' with Integer values time and data
'''... | BrightnessMonitor/BrightnessMonitorClient | src/brightnessmonitorclient/raspberry/dbController.py | Python | mit | 2,396 |
import codecs
from setuptools import setup
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with codecs.open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='zenbu',
version='1.0.5',
descrip... | metakirby5/zenbu | setup.py | Python | mit | 1,288 |
import os
import sys
import golem
from golem.core import (utils, session, suite as suite_module, test,
settings_manager, test_directory)
from golem.core.project import Project, create_project
from golem.gui import gui_start
from golem.test_runner.execution_runner import ExecutionRunner
from gol... | lucianopuccio/golem | golem/cli/commands.py | Python | mit | 8,682 |
from PyQt4.QtCore import QAbstractListModel, QAbstractTableModel, QVariant, Qt, QModelIndex, SIGNAL, pyqtSignal, QDateTime, QString
from PyQt4.QtGui import QIcon, QPixmap, QImage, QBrush, QColor
from datetime import datetime
from exceptions import TypeError
class show(object):
''' A representation of a show '''
... | aleximplode/Show-Tracker | src/dataclasses.py | Python | mit | 23,821 |
""" Automatic file """
from app.logic.gitrepo.controllers.GitController import GitController
| imvu/bluesteel | app/logic/gitrepo/controllers/__init__.py | Python | mit | 94 |
# -*- coding: utf-8 -*-
"""
netease-dl.weapi
~~~~~~~~~~~~~~~~
This module provides a Crawler class to get NetEase Music API.
"""
import re
import hashlib
import os
import sys
import click
import requests
from requests.exceptions import RequestException, Timeout, ProxyError
from requests.exceptions import ConnectionE... | ziwenxie/netease-dl | netease/weapi.py | Python | mit | 14,637 |
from distutils.core import setup
setup(name='zencoder',
version='0.4',
description='Integration library for Zencoder',
author='Alex Schworer',
author_email='alex.schworer@gmail.com',
url='http://github.com/schworer/zencoder-py',
license="MIT License",
install_requires=['httpl... | torchbox/zencoder-py | setup.py | Python | mit | 363 |
from .clev import *
| infoscout/weighted-levenshtein | weighted_levenshtein/__init__.py | Python | mit | 20 |
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "congrefor.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
#from django.core.wsgi import get_wsgi_application
#from dj_static import Cling
#application = Cling(get_wsgi_application())
| renanalencar/congrefor | congrefor/wsgi.py | Python | mit | 296 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def Action(vim, *args, **kwargs):
'''This data object type defines the action initiated b... | xuru/pyvisdk | pyvisdk/do/action.py | Python | mit | 1,144 |
from keras.models import Sequential
from keras.utils import np_utils
from keras.layers.core import Dense
import pandas as pd
import numpy as np
NUM_PIXELS = 784
NUM_CLASSES = 10
def baseline_model():
model = Sequential()
model.add(Dense(NUM_PIXELS,
input_shape=(NUM_PIXELS,),
... | JohnCrickett/KaggleDigitRecognizer | simple_nn.py | Python | mit | 1,649 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright © 2012-2013 Martin Ueding <dev@martin-ueding.de>
import subprocess
__docformat__ = "restructuredtext en"
class Colorcodes(object):
"""
Provides ANSI terminal color codes which are gathered via the ``tput``
utility. That way, they are portable. If th... | martin-ueding/python-colorcodes | colorcodes.py | Python | mit | 1,674 |
#!/usr/local/bin/python
## wrapper script to download 100 photos from all the eitz synsets to a photos folder
import imagenet_datasets as id
eitz_synsets = id.get_list_of_eitz_synsets()
id.download_images_by_synset(eitz_synsets,num_per_synset=100) | judithfan/graphcomm | experiments/draw/python/download_all_eitz_synsets.py | Python | mit | 250 |
#-*- coding: utf-8 -*-
"""OAuth 2.0 Django Models"""
import time
from hashlib import sha512
from uuid import uuid4
from django.db import models
from django.contrib.auth.models import User
from .consts import CLIENT_KEY_LENGTH, CLIENT_SECRET_LENGTH
from .consts import SCOPE_LENGTH
from .consts import ACCESS_TOKEN_LE... | xrage/oauth2app-mongoDb | oauth2app/models.py | Python | mit | 5,945 |
"jho1_polarfits.py"
from builtins import zip
from builtins import range
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size':15})
def text_to_df(filename):
"parse XFOIL polars and concatente data in DataFrame"
lines = list(open(filename))
for i, l in enume... | convexengineering/gplibrary | gpkitmodels/GP/aircraft/wing/jho1polars/jho1_polarfits.py | Python | mit | 2,692 |
from django.contrib import admin
from models import Page, TPage, Content, TContent
class PageAdmin(admin.ModelAdmin):
exclude = ['posted']
#fields = ['posted', 'title']
list_display = ('title', 'posted', 'slug')
prepopulated_fields = {'slug': ('title',)}
class TPageAdmin(admin.ModelAdmin):
list_di... | vollov/isda.ca | isda_backend/page/admin.py | Python | mit | 962 |
import tables
import numpy as np
import json
import os
def single_db_microns_per_pixel(file_name):
#this is used in the single worm case, but it would be deprecated. I want to use this argument when I read the data from original additional files
with tables.File(file_name, 'r') as fid:
microns_per_pixe... | ljschumacher/tierpsy-tracker | tierpsy/helper/params/read_attrs.py | Python | mit | 7,845 |
# -*- coding: utf-8 -*-
from typing import Tuple
from asyncpg import Connection
from starlette.requests import Request
from starlette.responses import JSONResponse, RedirectResponse
from starlette.routing import Route
from qllr.app import App
from qllr.endpoints import Endpoint, HTTPEndpoint
from qllr.templating imp... | em92/pickup-rating | qllr/blueprints/player/__init__.py | Python | mit | 2,763 |
import tree_utils
import csv
def findDistructionDistance(num_files,epsilon):
#get number of nodes from file
for k in range(num_files):
with open("sprseq" + srt(k),"r") as seq:
newick_tree = seq.readline()
tree = newickToNestedLst(newick_tree)
number_nodes = countNod... | alejandro-mc/trees | findDistructionDistance.py | Python | mit | 1,007 |
"""
Simulation of Game of Life with pygame
Instructions:
Press ESC or F4 to quit the game
Press RETURN to restart the game
Press SPACE to stop or resume the game
Press "p" or "+" to zoom in
Press "m" or "-" to zoom out
Press one of the letter below to change the color of the alive cells:
- r: red
- b: blue
... | DavideTonin99/pygameoflife | main.py | Python | mit | 7,534 |
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016 Jonathan Labéjof <jonathan.labejof@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation fi... | b3j0f/schema | b3j0f/schema/base.py | Python | mit | 9,410 |
import os
import re
from conans.model import Generator
from conans.paths import BUILD_INFO_VISUAL_STUDIO
from conans.client.tools.files import VALID_LIB_EXTENSIONS
class VisualStudioGenerator(Generator):
template = '''<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.micro... | conan-io/conan | conans/client/generators/visualstudio.py | Python | mit | 5,803 |
""" A simple restful webservice to provide access to the wiki.db"""
import json
from bottle import Bottle, run, response, static_file, redirect
from dbfunctions import Wikidb
api = Bottle()
db = Wikidb()
@api.route('/static/<filepath:path>')
def static(filepath):
return static_file(filepath, root='./static')
@... | mtik00/bottle-wiki | wikiapi.py | Python | mit | 1,234 |
# -*- coding: utf-8 -*-
import sys
import os
import shutil
import psutil
import subprocess
import time
import numpy as np
import itertools
# from matplotlib import pyplot
from routeGen import routeGen
from sumoConfigGen import sumoConfigGen
from stripXML import stripXML
import multiprocessing as mp
from glob import glo... | cbrafter/TRB18_GPSVA | codes/mainCode/ParallelSpecialMac.py | Python | mit | 5,186 |
from strings_anagrams import are_anagrams
def test_funny_anagrams():
assert are_anagrams("the eyes", "they see")
assert are_anagrams("Allahu Akbar, Obama", "Aha bub, koala alarm")
assert are_anagrams("Donald Trump", "Damp Old Runt")
def test_same_is_anagram():
assert are_anagrams("foo", "Foo")
ass... | elli0ttB/problems | sorting/test_are_anagrams.py | Python | mit | 556 |
# -*- coding: utf-8 -*-
import pytest
from hamcrest import assert_that, equal_to, all_of, \
instance_of, has_property, calling, raises
from pikuli import Region, Location
from pikuli.common_exceptions import FailExit
X = 311
Y = 128
ID = 3
WIDTH = 303
HEIGHT = 201
FIND_TIMEOUT = 3.1
TITLE = 'New test region'
c... | pikuli-project/pikuli | test/test_region.py | Python | mit | 12,465 |
import tables
__author__ = 'Gyfis'
def generate_histogram(sequence, type=0):
table = tables.dna if type == 0 else tables.rna if type == 1 else tables.protein
hist = {c: 0 for c in table}
for c in sequence:
hist[c] += 1
return {c: hist[c] / float(len(sequence)) for c in hist}
| Gyfis/sequence-comparison | Modules/basic.py | Python | mit | 302 |