code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
#!/usr/bin/env python
# encoding: utf-8
from ImageFusion import ImageFusion
from PIL import Image
import numpy as np
import pylab as plt
import pywt
class FusionDWB(ImageFusion):
""" Image Fusion based wavelet """
def __init__(self, imageNames = None, zt=2, ap=2, mp=0):
self._imageNames = imageNames... | nan86150/ImageFusion | src/main/fusion_dwb.py | Python | mit | 2,018 |
import re
class ibeon:
def remSpaces(data):
return data.replace(" ", "")
def remNumbers(data):
return ''.join([x for x in data if not x.isdigit()])
def remSymbols(data):
return re.sub('[^\w]', '', data)
def onlyNumbers(data):
return re.sub('[^0-9]', '', data)
def onlyAlp... | Aroliant/iBeon | python/ibeon.py | Python | mit | 901 |
from templates import OutputProcessor
import hashlib
from pprint import pprint
class Hashes(OutputProcessor):
def process(self, filename, name, data):
filedata = open(filename).read()
result = {'malware': name}
result['md5'] = hashlib.md5(filedata).hexdigest()
result['sha256'] = hashlib.sha256(filedata).hexdi... | maldroid/maldrolyzer | processing/hashes.py | Python | mit | 490 |
from os import environ
AWS_ACCESS_KEY_ID = environ["AWS_ACCESS_KEY_ID"]
AWS_SECRET_ACCESS_KEY = environ["AWS_SECRET_ACCESS_KEY"]
BUCKET_NAME = "22board-captchas"
AWS_ROOT_URL = "https://s3-eu-west-1.amazonaws.com/{}/".format(BUCKET_NAME)
| volnt/22board | app/config.py | Python | mit | 240 |
with open("dictionary.txt", "r") as one_gram_f:
with open("old_dictionary.txt", "r") as internet_list_f:
with open("intersecting_words.txt", "w") as intersecting_words_f:
one_grams = one_gram_f.readlines()
internet_words = internet_list_f.readlines()
for word in one_grams... | ctlewitt/Invisible-Keyboard | find_intersecting_words.py | Python | mit | 417 |
"""phial's custom errors."""
class ArgumentValidationError(Exception):
"""Exception indicating argument validation has failed."""
pass
class ArgumentTypeValidationError(ArgumentValidationError):
"""Exception indicating argument type validation has failed."""
pass
| sedders123/phial | phial/errors.py | Python | mit | 286 |
from django.db import models
from django.utils.translation import ugettext_lazy as _, ugettext_lazy
from django_countries import countries
from django_countries.fields import CountryField
COUNTRIES = [(ugettext_lazy(name), code) for (name, code) in list(countries)]
class Company(models.Model):
# Company credenti... | samupl/simpleERP | apps/contacts/models.py | Python | mit | 6,028 |
import re
with open('England.txt') as f:
data = f.read()
pat = re.compile(r"\{\{基礎情報 (.*?)\n\}\}", re.S)
baseInfo = '\n'.join(pat.findall(data))
print(baseInfo)
pat = re.compile(r"\|(.*?) = (.*)")
Info = pat.findall(baseInfo)
dic = {key: cont for key, cont in Info}
# print(dic)
| knuu/nlp100 | chap03/25.py | Python | mit | 328 |
#!/usr/bin/env python3
import collections # OrderedDict
import sys # exit
from pass_utils import UNOPS, BINOPS, expand
from expression_walker import walk
def lift_consts(exp, inputs, assigns, consts=None, hashed=dict()):
""" Extracts constant values from an expression """
# Note about hashed: This argum... | soarlab/FPTuner | src/parser/pass_lift_consts.py | Python | mit | 6,823 |
import base64
import hashlib
import json
import os
import bcrypt
from sqlalchemy.orm.exc import NoResultFound
from server_global import db
class Admin(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False, unique=True)
password = db.Column(db.String... | glennyonemitsu/MarkupHiveServer | src/model/admin.py | Python | mit | 506 |
from __future__ import unicode_literals
from django.apps import AppConfig
class AnnonceConfig(AppConfig):
name = 'annonce'
| firasbenmakhlouf/JobLookup | annonce/apps.py | Python | mit | 130 |
import unittest
from ctypes import *
import _ctypes_test
class Callbacks(unittest.TestCase):
functype = CFUNCTYPE
## def tearDown(self):
## import gc
## gc.collect()
def callback(self, *args):
self.got_args = args
return args[-1]
def check_type(self, typ, ... | ktan2020/legacy-automation | win/Lib/ctypes/test/test_callbacks.py | Python | mit | 8,245 |
from os import walk
files = []
for (dirpath, dirnames, filenames) in walk('./data/'):
files.extend(filenames)
break
data = []
OFratio = None
for file in files:
t = []
with open('./data/' + file) as f:
for i, line in enumerate(f):
if i in [15, 24, 25, 29, 31, 34, 39]:
... | ferram4/ProcEngines | GameData/ProcEngines/PropellantMixtures/config_parser.py | Python | mit | 928 |
import mdpopups
import sublime
import sublime_plugin
import webbrowser
import os
from html import escape
from .code_actions import actions_manager, run_code_action_or_command
from .code_actions import CodeActionOrCommand
from .core.configurations import is_supported_syntax
from .core.popups import popups
from .core.pro... | tomv564/LSP | plugin/hover.py | Python | mit | 11,187 |
"""
PyCSP implementation of the CSP Core functionality (Channels, Processes, PAR, ALT).
Copyright (c) 2009 John Markus Bjoerndalen <jmb@cs.uit.no>,
Brian Vinter <vinter@nbi.dk>, Rune M. Friborg <rune.m.friborg@gmail.com>.
See LICENSE.txt for licensing details (MIT License).
Versions available: parallel, greenl... | runefriborg/pycsp | pycsp/__init__.py | Python | mit | 664 |
from flask.ext.migrate import MigrateCommand
from flask.ext.script import Manager
from flask.ext.script.commands import ShowUrls, Clean
from commands.testcase_command import TestCommand
from flask_learn import create_app
manager = Manager(create_app)
manager.add_option("-c", "--config", dest='config',
... | KotiyaSenya/FlaskLearn | manage.py | Python | mit | 605 |
#import fast_rcnn
| Zardinality/TF_Deformable_Net | lib/__init__.py | Python | mit | 18 |
# game_rpg_simulation.py written by Duncan Murray 30/3/2015
import os
import random
def main():
"""
Prototype to see how an RPG simulation might be used
in the AIKIF framework.
The idea is to build a simple character and run a simulation
to see how it succeeds in a random world against another... | acutesoftware/virtual-AI-simulator | vais/z_prototypes/game_rpg_simulation1.py | Python | mit | 3,330 |
m = [2]
for i in range(int(input())-1):
m.append(int(3*m[i]/2))
print(sum(m)) | vipmunot/HackerRank | Algorithms/Viral Advertising.py | Python | mit | 81 |
"""{-
Copyright (c) 2009 Pauli Henrikki Rikula
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, publish, di... | tuturto/pyherc | src/pyherc/ai/pathfinding.py | Python | mit | 6,004 |
from django.apps import AppConfig
class PagesConfig(AppConfig):
name = 'precision.pages'
verbose_name = "Pages"
| FreeCodeCampRoma/precision_school-management | precision/pages/apps.py | Python | mit | 122 |
'''
Problem:
Find the kth smallest element in a bst without using static/global variables.
'''
def find(node, k, items=0):
# Base case.
if not node:
return items, None
# Decode the node.
left, value, right = node
# Check left.
index, result = find(left, k, items)
# Exit early.
... | RishiRamraj/interviews | solutions/algorithms/bst.py | Python | mit | 667 |
from __future__ import print_function
import os
import time
import subprocess
from colorama import Fore, Style
from watchdog.events import (
FileSystemEventHandler, FileModifiedEvent, FileCreatedEvent,
FileMovedEvent, FileDeletedEvent)
from watchdog.observers import Observer
from watchdog.observers.polling im... | ColtonProvias/pytest-watch | pytest_watch/watcher.py | Python | mit | 6,256 |
import time
import thread
import pygame
import input
from menu.menuitems import create_menu_items
from screenfactory import create_screen
from server import interface
from helpers import *
os.chdir(os.path.dirname(os.path.realpath(__file__)))
S = Settings()
S.load()
class Menu(object):
def __init__(self, scree... | derblub/pixelpi | menu.py | Python | mit | 6,460 |
from typing import Optional
import sphinx.util.logging
from ..base import PythonMapperBase
LOGGER = sphinx.util.logging.getLogger(__name__)
class PythonPythonMapper(PythonMapperBase):
"""A base class for all types of representations of Python objects.
:var name: The name given to this object.
:vartyp... | rtfd/sphinx-autoapi | autoapi/mappers/python/objects.py | Python | mit | 9,679 |
"""User administration API"""
from flask import request, jsonify, Blueprint
from flask_login import current_user
from emcit.models import User
from emcit.resources import UserAdministrationResource
from emcit.util import required_access, api_error, validate
from emcit.schemas import user_schema
user_api = Blueprint('u... | civiclee/Hack4Cause2017 | src/snack-overflow/emcit/emcit/api/user.py | Python | mit | 1,756 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
(r'^hello-django', 'demosite.views.hello'),
)
| tamasgal/django-tornado | demosite/demosite/urls.py | Python | mit | 164 |
import os.path
import urllib.parse
import requests
import rfc6266
import settings
import utilities
from markdown import Extension
from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE
class ImageDownloadPattern(ImagePattern):
def handleMatch(self, match):
el = super(ImageDownloadPattern, self)... | Tigge/trello-to-web | markdown_imaged.py | Python | mit | 1,141 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from flask import json
from collections import OrderedDict
#from event import RayEvents
from app import msg_event
import models
import utils
import six
class Message(object):
def __init__(self, msg_content=None, msg_title='Messages from System', msg_... | rtx3/Microburst | ray/messager.py | Python | mit | 6,218 |
import os
import sys
import threading
import boto3
import requests
import json
import logging
from boto3.s3.transfer import TransferConfig, ProgressCallbackInvoker
from s3transfer.utils import OSUtils
from botocore.exceptions import ClientError
from boto3.exceptions import RetriesExceededError, S3UploadFailedError
fro... | huaili-cid/metagen_cli | metagen/api/upload.py | Python | mit | 4,807 |
#!/usr/bin/env python
import json
DEBUG = False
import sys
import tweepy
import time
#consumer_key = 'HcMP89vDDumRhHeQBYbE3Asnp'
#consumer_secret = 'kcXfsNyBl7tan1u2DgV7E10MpsVxhbwTjmbjp3YL9XfDdMJiYt'
#access_key = '67882386-IXbLKaQEtTbZF9yotuLTjgitqjwBkouIstmlW4ecG'
#access_secret = 'SyVrXlIDkidYr3JlNiTQ8tjZ973gIKy... | gtrdp/twitter-clustering | crawling/crawl.py | Python | mit | 1,795 |
from twisted.internet.threads import deferToThread
import scrapy.statscollectors
import statsd
import six
class StatsDStatsCollector(scrapy.statscollectors.MemoryStatsCollector):
"""
Send all the stats to the statsd server in a thread. This is to ensure
the UDP packet which is sent doesn't hold up the main... | vinayan3/scrapy-statsd | scrapy_statsd/statscollectors.py | Python | mit | 2,853 |
from flask import Flask, render_template, redirect, url_for, request, session, flash, jsonify, g
import sqlite3 as sql
import os
import random
import json
from flask_sqlalchemy import SQLAlchemy
import ast #To change string list to a python list
import collections #To conte duplicate in iventory list using Count... | sylverspace/craft_game | app.py | Python | mit | 10,026 |
from ..config import GlobalConfig, LocalConfig
from kao_command.args import FlagArg
class ProjectArg(FlagArg):
""" Represents an CLI Argument that specifies a Project """
def __init__(self, *, help):
""" Initialize the Arg """
FlagArg.__init__(self, '-p', '--project', action="store... | cloew/TogglDriver | toggl_driver/args/project_arg.py | Python | mit | 547 |
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import yaml
import numpy as np
import numpy.random as n... | adityaarun1/faster_rcnn_pytorch | faster_rcnn/rpn_msr/proposal_target_layer.py | Python | mit | 10,606 |
# Django settings for reviewboard project.
from __future__ import unicode_literals
import os
import re
import sys
import djblets
from django.core.urlresolvers import reverse
# Can't import django.utils.translation yet
_ = lambda s: s
DEBUG = True
ADMINS = (
('Example Joe', 'admin@example.com')
)
MANAGERS =... | 1tush/reviewboard | reviewboard/settings.py | Python | mit | 12,734 |
import sys, numpy as np, hashlib, copy, cPickle, ctypes, os, os.path as osp
from collections import defaultdict,namedtuple
import __builtin__
import traceback
import cgt
from . import utils
# ================================================================
# Datatypes
# ================================================... | nebw/cgt | cgt/core.py | Python | mit | 122,515 |
from .base import BaseReader
try:
from boto3 import resource
from botocore.exceptions import ClientError
except ImportError: # pragma: no cover
raise ImportError(
'To use "s3" dynamic settings reader\n'
'you need to install simple-settings with s3 dependency:\n'
'pip install simple... | drgarcia1986/simple-settings | simple_settings/dynamic_settings/s3_reader.py | Python | mit | 1,740 |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, "Replica set status")
| cflq3/getcms | plugins/mongodb_dbs.py | Python | mit | 138 |
from demo import app
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
| runozo/leaflet-adv-demo | run.py | Python | mit | 89 |
# -*- coding: utf-8 -*-
#
# SelfTest/Util/test_number.py: Self-test for parts of the Crypto.Util.number module
#
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# th... | nparley/mylatitude | lib/Crypto/SelfTest/Util/test_number.py | Python | mit | 12,862 |
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
import scrapy
import os
# IN the special case of the wto disputes, we need to get the list of all disputes, so we run this script preliminarily:
execfile("./fetchjson.py")
# Now we build the scraper:
# Fir... | trcook/wto_python_scrape | wto_scraper.py | Python | mit | 1,127 |
import sys
from numpy import *
from scipy import signal
import scipy.io.wavfile
from matplotlib import pyplot
import sklearn.decomposition
def main():
# First load the audio data, the audio data on this example is obtained from http://www.ism.ac.jp/~shiro/research/blindsep.html
rate, source = scipy.io.wavfile.re... | nareshshah139/CocktailPartyAlgorithm1 | CocktailPartyAlgorithm.py | Python | mit | 2,277 |
import os
from ..helper import freq_to_mel
from ..praat import PraatAnalysisFunction
class PraatMfccFunction(PraatAnalysisFunction):
def __init__(self, praat_path=None, window_length=0.025, time_step=0.01, max_frequency=7800,
num_coefficients=13):
script_dir = os.path.dirname(os.path.ab... | mmcauliffe/python-acoustic-similarity | conch/analysis/mfcc/praat.py | Python | mit | 586 |
# Ill attempt to research and see the practicality of making a pid tuner
# possibly hard coding and using error
# or maybe using tensor flow
# but just an idea at the moment
| purduerov/XX-Core | rov/movement/controls/PID_Tuner.py | Python | mit | 174 |
import os
import shutil
import unittest
import pytest
from pyontutils import obo_io as oio
from .common import temp_path
obo_test_string = """format-version: 1.2
ontology: uberon/core
subsetdef: cumbo "CUMBO"
treat-xrefs-as-has-subclass: EV
import: http://purl.obolibrary.org/obo/uberon/chebi_import.owl
treat-xrefs-as-... | tgbugs/pyontutils | test/test_oboio.py | Python | mit | 6,002 |
from __future__ import print_function
import sys
import win32com.client
import pywintypes
import pythoncom
import numpy as np
import subprocess as sp
import concurrent.futures
import atexit
import json
import zmq
import os
from six.moves import range
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..')... | acq4/acq4 | acq4/util/igorpro.py | Python | mit | 10,366 |
import zipfile
import os
import xml.etree.ElementTree as etree
import re
import copy
class ODTPage:
def __init__(self, name, odt=None, pagename='page', indexname='index'):
self.pagename = pagename
self.indexname = indexname
if odt is None:
self.odt = ODT(name, pagename=pagename)... | jroivas/odt-html5 | odt.py | Python | mit | 23,990 |
"""DeeCluster: provides a namespace for a set of DeeDatabases"""
__version__ = "0.1"
__author__ = "Greg Gaughan"
__copyright__ = "Copyright (C) 2007 Greg Gaughan"
__license__ = "MIT" #see Licence.txt for licence information
from Dee import Relation, Tuple
from DeeDatabase import Database
class Cluster(dict):... | ggaughan/dee | DeeCluster.py | Python | mit | 1,475 |
from zope.component import getUtility, getMultiAdapter
from plone.portlets.interfaces import IPortletType
from plone.portlets.interfaces import IPortletManager
from plone.portlets.interfaces import IPortletAssignment
from plone.portlets.interfaces import IPortletDataProvider
from plone.portlets.interfaces import IPort... | vwc/agita | src/vwcollective.simplecontact/vwcollective/simplecontact/tests/test_contactsportlet.py | Python | mit | 3,908 |
from proteus import *
from dambreak_Ubbink_medium import *
from ls_consrv_p import *
timeIntegrator = ForwardIntegrator
timeIntegration = NoIntegration
femSpaces = {0:basis}
subgridError = None
massLumping = False
numericalFluxType = DoNothing
conservativeFlux = None
shockCapturing = None
fullNewton... | erdc-cm/air-water-vv | 3d/dambreak_Ubbink/dambreak_Ubbink_medium/ls_consrv_n.py | Python | mit | 982 |
import numpy
def iterate(Z):
# find number of neighbours that each square has
N = numpy.zeros(Z.shape)
N[1:, 1:] += Z[:-1, :-1]
N[1:, :-1] += Z[:-1, 1:]
N[:-1, 1:] += Z[1:, :-1]
N[:-1, :-1] += Z[1:, 1:]
N[:-1, :] += Z[1:, :]
N[1:, :] += Z[:-1, :]
N[:, :-1] += Z[:, 1:]
N[:, 1:] +... | mdda/Reverse-GoL | benchmark/speed_numpy.py | Python | mit | 1,447 |
import unittest
import plotly.graph_objs as go
import weplot as wp
class FigureHolderTest(unittest.TestCase):
def test_can_update_layout(self):
fh = wp.FigureHolder(go.Figure())
layout = fh.figure.layout
self.assertIsNone(layout.barmode)
self.assertIsNone(layout.title)
... | arraystream/simpleplotly | tests/test_figure.py | Python | mit | 1,366 |
from Framework.Resposta import Resposta
from Models.Sala.Sala import Sala as ModelSala
class RespostaListar(Resposta):
def __init__(self,salas):
self.corpo = []
for sala in salas:
self.corpo.append(ModelSala(sala))
| AEDA-Solutions/matweb | backend/Models/Sala/RespostaListar.py | Python | mit | 224 |
from contextlib import closing
from flask import current_app
from summer.app import create_app
from summer.db.connect import connect_db
def init_db():
app = create_app('product')
_context = app.app_context()
_context.push()
with closing(connect_db()) as db:
with open('./summer/schema.sql', mo... | zhongql/summer | tool/initdb.py | Python | mit | 448 |
import _plotly_utils.basevalidators
class ColorscaleValidator(_plotly_utils.basevalidators.ColorscaleValidator):
def __init__(
self, plotly_name="colorscale", parent_name="layout.coloraxis", **kwargs
):
super(ColorscaleValidator, self).__init__(
plotly_name=plotly_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/layout/coloraxis/_colorscale.py | Python | mit | 560 |
'''import datetime
daytime.MINYEAR = 1901
daytime.MAXYEAR = 2000
print(daytime.MAXYEAR)'''
import calendar
count = 0
year = 1901
endYear = 2001
month = 12
for x in range (year, endYear):
for y in range (1, month+1):
if calendar.weekday(x,y,1) == calendar.SUNDAY:
count = count+1
print("Count: " + str(c... | DarrenBellew/CloudCompDT228-3 | Lab3/CountingSundays.py | Python | mit | 328 |
import ANN
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
data = load_digits()
input = data.data
target = data.target
numLayers = 5
iterations = 20000
#input = [[0,0],[0,1],[1,0],[1,1]]
#target = [0,1,1,0]
nn1 = ANN.FNN(numLayers, input, target, eta=0.05 )
e = nn1.train(iterations)
achi... | AbstractGeek/rusmalai-ncbs | packages/examples/test_data.py | Python | mit | 768 |
#!/usr/bin/env python
# -*- coding:utf-8 -*
import dbm
import codecs
db = dbm.open('./vocabulary', 'r')
vDict = db.keys()
vList = sorted(vDict)
print len(vList)
with codecs.open('vocabulary.list', 'w') as f:
f.write('\n'.join(vList))
| caspartse/python-translate | data/db2list.py | Python | mit | 241 |
#!/usr/bin/env python
import os, sys, re, csv
######################################## ##### ########################################
######################################## Order ########################################
######################################## ##### ########################################
def arg... | relic7/prodimages | python/dload_orcl-mysql-server_imgs_byPOorStyleList.py | Python | mit | 5,989 |
#!/usr/bin/env python
##################################################################
# AUTHOR: Miguel A. Ibarra-Arellano (miguelib@ufl.edu)
#
# DESCRIPTION: Pairwise and mean standarized euclidean comparisons
##################################################################
import os
import logging
import argpars... | secimTools/SECIMTools | src/scripts/standardized_euclidean_distance.py | Python | mit | 20,242 |
from sqlalchemy import BigInteger, Column, String
from tornado.gen import coroutine
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
from tornado_sqlalchemy import (
SessionMixin,
as_future,
set_max_workers,
SQLAlchemy,
)
db = SQLAlchemy()
set_max_workers(10)
c... | siddhantgoel/tornado-sqlalchemy | examples/multiple_databases.py | Python | mit | 2,508 |
import openpnm as op
from numpy.testing import assert_allclose
class TransientAdvectionDiffusionTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[4, 3, 1], spacing=1.0)
self.geo = op.geometry.GenericGeometry(network=self.net,
pores=self... | PMEAL/OpenPNM | tests/unit/algorithms/TransientAdvectionDiffusionTest.py | Python | mit | 2,595 |
import urllib.request, urllib.parse, urllib.error
import datetime
import lxml.html
import tweepy
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.http import HttpResponseForbidde... | samuelclay/NewsBlur | apps/oauth/views.py | Python | mit | 31,341 |
# https://leetcode.com/problems/ugly-number-ii/
import heapq
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
def addToHeap(heap, dictionary, key):
if key in dictionary:
dictionary[key] += 1
else:
... | young-geng/leet_code | problems/264_ugly-number-ii/main.py | Python | mit | 767 |
"""Sensor platform for nodered."""
import json
import logging
import voluptuous as vol
from homeassistant.components.websocket_api import event_message
from homeassistant.const import (
CONF_ENTITY_ID,
CONF_ICON,
CONF_ID,
CONF_STATE,
CONF_TYPE,
EVENT_STATE_CHANGED,
)
from homeassistant.core im... | shortbloke/home_assistant_config | custom_components/nodered/switch.py | Python | mit | 7,962 |
# finally found how to change the backlight color
# https://diyodemag.com/projects/playing_with_raspberry_pi_pico_review_project
import machine
import utime
sda = machine.Pin(0)
scl = machine.Pin(1)
i2c = machine.I2C(0, sda=sda, scl=scl, freq=400000)
utime.sleep(1)
i2c.writeto(114, '\x7C') # | enter settings mode
i2c.... | mirontoli/tolle-rasp | pico/009_serlcd_rgb.py | Python | mit | 628 |
from cms import sitemaps
from cms.apps.pages.models import ContentBase
from cms.models import HtmlField, PageBase
from django.db import models
from historylinks import shortcuts as historylinks
class Faqs(ContentBase):
classifier = 'apps'
urlconf = '{{ project_name }}.apps.faqs.urls'
per_page = models.P... | onespacemedia/cms-faqs | apps/faqs/models.py | Python | mit | 1,520 |
#!/usr/bin/env python3
from anormbookmarker.test.test_enviroment import *
with self_contained_session(CONFIG.database_timestamp) as session:
BASE.metadata.create_all(session.bind)
buffalo = Word.construct(session=session, word='Buffalo')
session.commit()
buffalo_swap = Word.construct(session=session,... | jakeogh/anormbookmarker | anormbookmarker/test/tests/Word/end_letters_swapped.py | Python | mit | 939 |
#!/usr/bin/python
##############################################
###Python template
###Author: Elizabeth Lee
###Date: 6/9/13
###Function:
#### 1) create scatter of OR by zipcode vs. urban metro RUCC avg 2013
###Import data: zipcode_bysseas_cl.csv
###Command Line: python
############################################... | eclee25/flu-SDI-exploratory-age | scripts/OR_urbanmetro_v6-7-13.py | Python | mit | 11,462 |
from OpenGLCffi.GL import params
@params(api='gl', prms=['minX', 'minY', 'minZ', 'minW', 'maxX', 'maxY', 'maxZ', 'maxW'])
def glPrimitiveBoundingBoxARB(minX, minY, minZ, minW, maxX, maxY, maxZ, maxW):
pass
| cydenix/OpenGLCffi | OpenGLCffi/GL/EXT/ARB/ES3_2_compatibility.py | Python | mit | 209 |
from .base import MarathonObject, MarathonResource
class MarathonDeployment(MarathonResource):
"""Marathon Application resource.
See: https://mesosphere.github.io/marathon/docs/rest-api.html#deployments
https://mesosphere.github.io/marathon/docs/generated/api.html#v2_deployments_get
:param lis... | drewrobb/marathon-python | marathon/models/deployment.py | Python | mit | 3,907 |
# -*- coding: utf-8 -
#
# This file is part of offset. See the NOTICE for more information.
from offset import run, maintask
from offset.time import Ticker, SECOND
@maintask
def main():
ticker = Ticker(0.1 * SECOND)
for i in range(3):
print(ticker.c.recv())
ticker.stop()
run()
| benoitc/offset | examples/demo_ticker.py | Python | mit | 302 |
import sys
from collections import defaultdict, OrderedDict
import toml
from wurst.core.models import IssueType, Priority, Status, Transition
def sift(iterable, predicate):
"""
Sift an iterable into two lists, those which pass the predicate and those who don't.
:param iterable:
:param predicate:
... | kcsry/wurst | wurst/core/utils/schema_import.py | Python | mit | 3,317 |
import _plotly_utils.basevalidators
class CliponaxisValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(self, plotly_name="cliponaxis", parent_name="funnel", **kwargs):
super(CliponaxisValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/funnel/_cliponaxis.py | Python | mit | 450 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 13 20:55:28 2017
@author: moamin
"""
import os, sys, time, gzip, math
import numpy as np,csv, json, re
#from gensim.models import Word2Vec
import matplotlib.pyplot as plt
#from sets import Set
from representations.sequentialembedding import Sequen... | ruhulsbu/WEAT4TwitterGroups | histwords/gender_bias_plot.py | Python | mit | 5,322 |
#----------------------------------------------------------------------------
# Name: masked.ipaddrctrl.py
# Authors: Will Sadkin
# Email: wsadkin@nameconnector.com
# Created: 02/11/2003
# Copyright: (c) 2003 by Will Sadkin, 2003
# RCS-ID: $Id$
# License: wxWidgets license
... | ktan2020/legacy-automation | win/Lib/site-packages/wx-3.0-msw/wx/lib/masked/ipaddrctrl.py | Python | mit | 8,362 |
import base64
from asyncio import coroutine
from .base import Base
class Target(Base):
unary = False
@coroutine
def __call__(self, text, encoding='utf-8'):
return base64.b64decode(text).decode(encoding)
| Answeror/torabot | torabot/lang/targets/base64_decode.py | Python | mit | 227 |
"""Helper to provide extensibility for pickle/cPickle.
This is only useful to add pickle support for extension types defined in
C, not for instances of user-defined classes.
"""
from types import ClassType as _ClassType
__all__ = ["pickle","constructor"]
dispatch_table = {}
safe_constructors = {}
def pickle(ob_typ... | MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.2/Lib/copy_reg.py | Python | mit | 1,861 |
# This script only works for OCLC UDEV reports created after December 31, 2015
import csv
import datetime
import re
import requests
import sys
import time
from lxml import html
user_date = raw_input('Enter report month and year (mm/yyyy) or year only (yyyy): ')
if len(user_date) == 7: # For running a report for a si... | vmdowney/oclc-udev | oclc_udev.py | Python | mit | 7,800 |
import contextlib
import sqlalchemy as sa
from sqlalchemy import and_
from sqlalchemy import between
from sqlalchemy import bindparam
from sqlalchemy import Boolean
from sqlalchemy import cast
from sqlalchemy import collate
from sqlalchemy import column
from sqlalchemy import desc
from sqlalchemy import distinct
from ... | wujuguang/sqlalchemy | test/orm/test_query.py | Python | mit | 183,302 |
#!/usr/bin/env python3
import random
import unittest
import numpy as np
import cereal.messaging as messaging
from common.params import Params
from selfdrive.locationd.calibrationd import Calibrator
class TestCalibrationd(unittest.TestCase):
def test_read_saved_params(self):
msg = messaging.new_message('liveC... | commaai/openpilot | selfdrive/locationd/test/test_calibrationd.py | Python | mit | 739 |
#!/usr/bin/env python
'''
Run this script to update all the copyright headers of files
that were changed this year.
For example:
// Copyright (c) 2009-2012 The Presidentielcoin Core developers
it will change it to
// Copyright (c) 2009-2015 The Presidentielcoin Core developers
'''
import os
import time
import re
y... | presidentielcoin/presidentielcoin | contrib/devtools/fix-copyright-headers.py | Python | mit | 1,400 |
# https://oj.leetcode.com/problems/4sum/
# Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
#
# Note:
# Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a <= b <= ... | lijunxyz/leetcode_practice | 4_sum_medium/Solution2.py | Python | mit | 2,496 |
from contextlib import contextmanager
from datetime import datetime, timedelta
from queue import Queue
from typing import IO, TYPE_CHECKING, Dict, Generator, List, Optional, Set, Tuple, Union
import sys
import timeit
import simpy
from desmod.config import ConfigDict
from desmod.timescale import TimeValue, parse_time,... | SanDisk-Open-Source/desmod | desmod/progress.py | Python | mit | 12,418 |
import sys
vi = sys.version_info
if vi < (3, 5):
raise RuntimeError('httptools require Python 3.5 or greater')
else:
import os.path
import pathlib
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as build_ext
CFLAGS = ['-O2']
ROOT = pathlib.Path(__file_... | MagicStack/httptools | setup.py | Python | mit | 7,252 |
from .base import *
DEBUG = True
db_url = 'sqlite:///{}'.format(os.path.join(BASE_DIR, 'test.sqlite3'))
default_db = dj_database_url.config(default=db_url, conn_max_age=None)
DATABASES['default'].update(default_db)
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
EMAIL_BACKEND = 'django.c... | citiufpe/citi-webplate | project_name/settings/test.py | Python | mit | 360 |
# coding: utf-8
def test_string_set_bang(doctest):
"""
! (define str (substring "hello world" 0 5))
! (string-set! str 0 #\\x)
> str
"xello"
> (immutable? str)
#f
"""
def test_substring(doctest):
"""
> (substring "Apple" 1 3)
"pp"
> (substring "Apple" 1)
"pple"
... | vishesh/pycket | pycket/test/test_string.py | Python | mit | 8,374 |
import urllib
import requests
class Config(object):
""" Config object for Slack """
API_PATHS = { "auth.test" : "auth.test",
"oauth.access" : "oauth.access",
# CHANNELS
"channels.archive" : "channels.archive",
"channels.create" : "channels.create",
"channels.history" : "channels... | nikhs/slack-analytics | slackwrapper.py | Python | mit | 10,543 |
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Softwa... | kpkhxlgy0/SublimeText3 | Packages/SublimeCodeIntel/SublimeCodeIntel.py | Python | mit | 49,980 |
#!/usr/bin/python
import sys
import getopt
import urllib2
import json
from bs4 import BeautifulSoup
import re
import json
colors = {'W': 'White', 'U': 'Blue', 'B': 'Black', 'R': 'Red', 'G': 'Green'}
colorless = "Colorless"
multicolored = "Multicolored"
def extract_cmc_and_color(cost):
pieces = re.findall(r'[\dWU... | matthewbhall/pack-generator | Scripts/card-scraper.py | Python | mit | 3,428 |
#!/usr/bin/env python
import sys, os, arcpy
class GenericToolsBatchConvertRastersASCIIMXE(object):
"""This class has the methods you need to define
to use your code as an ArcGIS Python Tool."""
def __init__(self):
"""Define the tool (tool name is the name of the class)."""
se... | marbiouk/dsmtools | Tools/GenericToolsBatchConvertRastersASCIIMXE.py | Python | mit | 4,814 |
"""
gaussian.py: Classes for Gaussian estimation
"""
from __future__ import division
from __future__ import print_function
import numpy as np
from vampyre.common.utils import get_var_shape, repeat_axes, repeat_sum
from vampyre.common.utils import VpException
from vampyre.estim.base import BaseEst
class GaussEst(Base... | GAMPTeam/vampyre | vampyre/estim/gaussian.py | Python | mit | 6,954 |
import pandas as pd
class Status:
Instance = None
@classmethod
def add(cls, message, red = False, verbosity = 1):
cls.get().add_message(message, red, verbosity)
@classmethod
def initialize_status(cls, status_method, verbosity = 1):
# Note: verbosity must be pa... | clembou/PCWG | pcwg/core/status.py | Python | mit | 1,242 |
# -*- coding: utf-8 -*-
"""
Created on Mon May 2 16:41:42 2016
This downloads xml metadata files from a text list
It reads the start, end, and corresponding data file name.
It writes this data out to a CSV
If passed a command line argument, a test will be performed on the first
16 files
@author: Keith
"""
import c... | karoraw1/GLM_Wrapper | bin/GEO_MetaData.py | Python | mit | 1,659 |
from django.contrib import admin
from library.models import Author, Book, Genre, Review
admin.site.register(Author)
admin.site.register(Book)
admin.site.register(Genre)
admin.site.register(Review)
| Nocks/ReadBooks | library/admin.py | Python | mit | 199 |
from distutils.core import setup
import py2exe
setup(console=[
'../src/mouseup.py',
'../src/mousedown.py',
'../src/mouseclick.py',
'../src/mousemove.py',
'../src/keyboarddown.py',
'../src/keyboardkey.py',
'../src/keyboardtype.py',
'../src/keyboarddown.py',
'../src/keyboardup.py',
]) | nawarian/PHPBot | ext/pyautogui/bin/setup.py | Python | mit | 320 |
# coding: utf8
from __future__ import print_function
import json
import os
import pyprind
from stst import utils
from stst import config
class Feature(object):
def __init__(self,
load=True,
dimension=None,
**kwargs):
self.load = load
self.featu... | rgtjf/Semantic-Texual-Similarity-Toolkits | stst/modules/features.py | Python | mit | 5,022 |
"""Databases and datasets used in common tests"""
import yaml
YAML_LOADER = yaml.FullLoader
A_B_REGULAR_SOLUTION_TDB = """
ELEMENT A ALPHA 0.0 0.0 0.0 !
ELEMENT B ALPHA 0.0 0.0 0.0 !
TYPE_DEFINITION % SEQ *!
PHASE ALPHA % 1 1 !
CONSTITUENT ALPHA : A B : !
$ Default the lattice stability and regular solution para... | PhasesResearchLab/ESPEI | tests/testing_data.py | Python | mit | 49,302 |
import boto3
import collections
import datetime
import time
import sys
import botocore
ec2_client = boto3.client('ec2',region_name='ap-southeast-2')
ec2_resource = boto3.resource('ec2',region_name='ap-southeast-2')
sns = boto3.client('sns')
images_all = ec2_resource.images.filter(Owners=["self"])
today_fmt = (datetime... | RexChenjq/AWS-Image-Backup | purge latest.py | Python | mit | 2,667 |