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 |
|---|---|---|---|---|---|
"""Test flash_air_music.configuration functions/classes."""
import pytest
from flash_air_music import configuration, exceptions
from flash_air_music.__main__ import __doc__ as doc
def common_init(monkeypatch, tmpdir, skip_ffmpeg=False):
"""Perform common test setup.
:param monkeypatch: pytest fixture.
... | Robpol86/FlashAirMusic | tests/test_configuration.py | Python | mit | 12,904 |
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'clarityv2.accounts'
| Clarity-89/clarityv2 | src/clarityv2/accounts/apps.py | Python | mit | 101 |
"""Single slice vgg with normalised scale.
"""
import functools
import lasagne as nn
import numpy as np
import theano
import theano.tensor as T
import data_loader
import deep_learning_layers
import image_transform
import layers
import preprocess
import postprocess
import objectives
import theano_printer
import update... | 317070/kaggle-heart | configurations/j7_jeroen_ch.py | Python | mit | 10,276 |
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from __future__ import with_statement
import os
import sys
from datetime import datetime
# workaround on osx, disable kqueue
if sys.platform == "darwin":
os.environ['EVENT_NOKQUEUE'] = "... | samabhi/pstHealth | venv/lib/python2.7/site-packages/gunicorn/workers/ggevent.py | Python | mit | 3,735 |
#!/usr/bin/env python3
# Copyright (c) 2019-2020 The Bitcoin Unlimited developers
import asyncio
import time
from test_framework.util import assert_equal, assert_raises
from test_framework.test_framework import BitcoinTestFramework
from test_framework.loginit import logging
from test_framework.electrumutil import (Ele... | BitcoinUnlimited/BitcoinUnlimited | qa/rpc-tests/electrum_subscriptions.py | Python | mit | 7,420 |
""" Physics test sandbox for the space race game!
Alistair Reid 2015
"""
import matplotlib.pyplot as pl
import matplotlib as mpl
import numpy as np
from numpy.linalg import norm
from time import time, sleep
import os
def integrate(states, props, inp, walls, bounds, dt):
""" Implementing 4th order Runge-Kutta f... | lmccalman/spacerace | physics/engine.py | Python | mit | 10,367 |
"""
To build cx_Freeze executable:
python setup.py bdist_msi
"""
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need
# fine tuning.
buildOptions = dict(packages = [], excludes = [])
import PyQt5
from glob import glob
import sys, os
import os.path as osp
base = 'Wi... | cwebber314/pyqt_db | setup.py | Python | mit | 1,320 |
# -*- coding: utf-8 -*-
"""
plotting.py
Part of douglib. Used for general data plotting.
Created on Tue June 06 08:44:12 2014
@author: dthor
"""
# ---------------------------------------------------------------------------
### Imports
# ----------------------------------------------------------------------... | dougthor42/douglib | douglib/plotting.py | Python | mit | 1,474 |
# -*- coding: UTF-8 -*-
# import os
# import django
#
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "interface_platform.settings")
# django.setup()
from django.test import TestCase
from testdata import CreateTestData
from django.contrib.auth.models import User
from account.models import Account
from ..management.... | longmazhanfeng/interface_web | interface_platform/tests/qiye_itrunnertest.py | Python | mit | 1,838 |
from CGATReport.Tracker import *
from rrbsReport import *
class M3DSummaryTable(RrbsTracker):
# pattern = "^summary_table$"
def __call__(self, track, slice=None):
statement = '''
SELECT group1 as Group_1, group2 as Group_2,
total as Total, significant as Significant_Clusters
... | CGATOxford/CGATPipelines | CGATPipelines/pipeline_docs/pipeline_rrbs/trackers/M3D.py | Python | mit | 402 |
import cPickle as pickle
import numpy as np
import re
from math import log
from dic import Info
from config.config import config
from tools import tokenlize, comp_tuple, weights
class query_voc(object):
def __init__(self, tokens, dic):
self.tokens = tokens
self.dic = dic
class query_entry(objec... | Impavidity/SearchEngine | WebSite/engine/query.py | Python | mit | 3,939 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from pony.orm.core import Entity, SetInstance, Required, Optional
import suapp.orm
__all__ = ["to_json", "dumps"]
def to_json(object_to_serialize):
"""
Adding simple serialization for objects.
If standard json.dumps fails and it is a real ob... | schilduil/suapp | suapp/simple_json.py | Python | mit | 2,757 |
# GUI
# python for tkinter nature
from tkinter import *
class Application(Frame):
def __init__(self,master=None):
Frame.__init__(self,master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.helloLabel=Label(self,text='Hello World')
self.helloLabel.pack()
self.quitButton = Button(self,t... | CrazyBBer/Python-Learn-Sample | gui.py | Python | mit | 433 |
#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.
# pylint: disable-msg=C6310
"""WebRTC Demo
This module demonstrates the WebRTC API by implementing a simple video chat app.
"""
import datetime
import logging
import os
import random
import re
from google.appengine.api import channel
from goog... | jeromeetienne/webglmeeting0 | apprtc/apprtc.py | Python | mit | 6,313 |
from test_base import BaseTestCase
from search_rex.recommendations.data_model.case_based import\
InMemoryQueryDataModel
from search_rex.recommendations.data_model.case_based import\
PersistentQueryDataModel
from search_rex.recommendations.neighbourhood.case_based import\
ThresholdQueryNeighbourhood
from sea... | feibl/search-rex | tests/test_views_case_based.py | Python | mit | 6,795 |
#!/Tsan/bin/python
# -*- coding: utf-8 -*-
# Libraries To Use
from __future__ import division
from CloudQuant import MiniSimulator
import numpy as np
import pandas as pd
import pdb
import cvxopt as cv
from cvxopt import solvers
from datetime import datetime, date, time
import barraRiskModel as brm
impor... | kamiseko/factor-test | idiVol IN.py | Python | mit | 17,571 |
import os
import re
import sys
import logging
import json
from glob import iglob
from collections import defaultdict
import numpy as np
from settings import CACHE_DIR, REF_DIR
from utils import set_up_logging
from utils import mkdir_p
log = set_up_logging('describe', loglevel=logging.DEBUG)
def describe_dos(optio... | influence-usa/campaign-finance_state_PA | tasks/describe.py | Python | mit | 2,837 |
# this one is like your scripts with argv
def print_two(*args):
arg1,arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one arguments
def print_one(arg1):... | Cloudlie/pythonlearning | ex18.py | Python | mit | 514 |
'''@file main.py
this function is used to run distributed training on a local cluster'''
import os
import atexit
import subprocess
import tensorflow as tf
def local_cluster(expdir, class_type):
'''main function'''
#read the cluster file
clusterfile = os.path.join(expdir, 'cluster', 'cluster')
machin... | JeroenBosmans/nabu | nabu/distributed/local_cluster.py | Python | mit | 1,506 |
from __future__ import print_function
import argparse
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('/opt/ros/groovy/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.path.insert(0, os.path.jo... | robotics-silver-surfer/surfer-main | lab3/angPos_PID/build/catkin_generated/generate_cached_setup.py | Python | mit | 1,291 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import logging
import sys
from lfmconf.lfmconf import get_lastfm_conf
from lfmdb import lfmdb
from stats.stats import process_track, retrieve_total_plays_from_db, \
retrieve_total_json_tracks_from_db
from queries.inserts import get_query_insert_play
logg... | nicolasm/lastfm-export | import.py | Python | mit | 2,386 |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# # netCDF File Visualization Case Study
#
# I was asked by a colleague to visualize data contained within this [netCDF file](https://motherlode.ucar.edu/repository/entry/show/RAMADDA/Unidata/Staff/Julien+Chastang/netcdf-explore?entryid=c7239224-d3f... | rsignell-usgs/notebook | Siphon/casestudy.py | Python | mit | 10,318 |
#!/usr/bin/env python
# encoding: utf-8
"""
string-to-integer-atoi.py
Created by Shuailong on 2016-01-15.
https://leetcode.com/problems/string-to-integer-atoi/.
"""
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if len(str) < 1:
... | Shuailong/Leetcode | solutions/string-to-integer-atoi.py | Python | mit | 1,137 |
# -*- coding: utf-8 -*-
from datetime import datetime
__author__ = u"Tomas Holub"
__email__ = u"tomas.holub@olc.cz"
class Message(object):
u"""Basic class for Messages that goes into the Queue"""
MESSAGE_TYPE = u"basic"
STATUS_NEW = u"new"
STATUS_QUEUED = u"queued"
STATUS_DEQUEUED = u"dequeued... | HolubTom/Queue | pCore/module/queue/messages/Message.py | Python | mit | 1,342 |
#!/usr/bin/env python
import errno
import os
import platform
import sys
BASE_URL = os.getenv('LIBCHROMIUMCONTENT_MIRROR') or \
'https://s3.amazonaws.com/brave-laptop-binaries/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = os.getenv('LIBCHROMIUMCONTENT_COMMIT') or \
'd715734c03b0c892ea66695ae63fc0db9c3fc027'... | posix4e/electron | script/lib/config.py | Python | mit | 2,118 |
'''
pheno2plot.py - format and manipulate phenotype files
====================================================
:Author:
:Release: $Id$
:Date: |today|
:Tags: Python
Purpose
-------
.. Generate plots of phenotype data
Usage
-----
.. Example use case
Example::
python pheno2plot.py
Type::
python pheno2plot.p... | MikeDMorgan/gwas_pipeline | scripts/pheno2plot.py | Python | mit | 7,293 |
#!/usr/bin/env python
import jinja2
import os
import re
import shlex
import sys
import mkdocs.build
from mkdocs.build import build
from mkdocs.config import load_config
from urllib2 import urlopen
import subprocess
def line_containing(lines, text):
for i in range(len(lines)):
if text.lower() in lines[i].lower(... | mattn/ccat | Godeps/_workspace/src/sourcegraph.com/sourcegraph/srclib/docs/buildsite.py | Python | mit | 3,663 |
#!/usr/bin/python3
# Small script to validate a given IP address
import socket
import sys
def validate_ip(ip):
try:
socket.inet_pton(socket.AF_INET, ip)
return (True,"IPv4")
except socket.error:
try:
socket.inet_pton(socket.AF_INET6, ip)
return(True,"IPv6")
... | Tijndagamer/bin | validate_ip.py | Python | mit | 609 |
"""cairo_museum.py"""
from lib.stage import Stage
class CairoMuseum(Stage):
"""Cairo Museum stage"""
def desc(self):
"""Describe action"""
action = """
After getting the first replicant, you call some old friends and some of them
mentions something about a hippie woman that likes no jokes. ... | brunitto/python-runner | lib/stages/cairo_museum.py | Python | mit | 1,374 |
# encoding=utf8
import utils
import pickle
import zipfile
import os
from tqdm import tqdm
from pprint import pprint
# Globals
#[Special, Heavy, Primary]
bucketHashes = [2465295065,953998645,1498876634]
# Load in Manifest
print 'Loading Manifest...'
with open('manifest.pickle','rb') as f:
data = pickle.loads(f.rea... | linkian209/Destiny_RNN | create.py | Python | mit | 3,091 |
import webapp2, logging
from database import get_feed_source_by_name, store_feed_source, \
get_feed_source_by_url, change_feed_source_url
class AddHandler(webapp2.RequestHandler):
def post(self):
from database import FeedSource
name = self.request.get('name')
url = self.request.get('url')
frequency_... | phistuck/FrequentFeedScraper | add_handler.py | Python | mit | 1,694 |
'''
'''
from rest_framework import serializers
import models
class PluginSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Plugin
fields = ('id', 'name', )
class ScoredServiceSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models... | nuccdc/scoring_engine | scoring_engine/engine/serializers.py | Python | mit | 1,320 |
import numpy as np
from lie_learn.groups.SO3 import *
def test_change_parameterization():
def is_equal(R1, R2, p):
if p == 'Q':
# Quaternions are only defined up to a sign, so check each row, what sign we need
for i in range(R1.shape[0]):
if not (np.allclose(R1[i,... | AMLab-Amsterdam/lie_learn | lie_learn/groups/SO3_tests.py | Python | mit | 3,912 |
# Custom mapper sample for CodeMap plugin
# This script defines a mandatory `def generate(file)` and module attribute map_syntax:
# - `def generate(file)`
# The routine analyses the file content and produces the 'code map' representing the content structure.
# In this case it builds the list of sections (lines th... | oleg-shilo/sublime-codemap | custom_mappers/ts.py | Python | mit | 5,302 |
# -*- coding: utf-8 -*-
"""
The `Future()` object in **RedPipe** gives us the ability to make the pipeline
interface of redis-py look like the non-pipelined interface.
You call a command and get a response back.
Only the response is not the actual data.
It is an empty container called a `Future`.
There is a callback at... | 72squared/redpipe | redpipe/futures.py | Python | mit | 16,126 |
# choco/ui.py
# Copyright (C) 2006-2016 the Choco authors and contributors <see AUTHORS file>
#
# This module is part of Choco and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import re
import os
import posixpath
from choco import errors
from choco import util
from choco.ru... | whiteclover/Choco | choco/ui.py | Python | mit | 3,191 |
#!/usr/bin/env python
import subprocess
"""
A ssh based command dispatch system
"""
machines = ["10.0.1.40",
"10.0.1.50",
"10.0.1.51",
"10.0.1.60",
"10.0.1.80"]
cmd = "python /src/fingerprint.py"
for machine in machines:
subprocess.call("ssh root@%s %s" % (machine, cmd), shell=True)
| lluxury/P_U_S_A | 8_OS_Soup/code/dispatch1.py | Python | mit | 297 |
import itertools
class RuleCollection(object):
def __init__(self):
self.rules = {}
def add_rule(self, rule, level=0):
self.rules.setdefault(level, [])
self.rules[level].append(rule)
def apply(self, transaction, entry):
entries = [entry]
levels = list(self.rules.k... | pcapriotti/pledger | pledger/rule.py | Python | mit | 1,570 |
# Heads Up Texas Hold'em Challenge bot
# Based on the Heads Up Omaha Challange - Starter Bot by Jackie <jackie@starapple.nl>
# Last update: 22 May, 2014
# @author Chris Parlette <cparlette@gmail.com>
# @version 1.0
# @license MIT License (http://opensource.org/licenses/MIT)
class Pocket(object):
'''
... | brhoades/holdem-bot | poker/poker.py | Python | mit | 2,684 |
#!/usr/bin/env python
from setuptools import setup
setup(name='RQ-Cron',
version='1.0.2',
description='RQ Cron',
author='Andrii Kostenko',
author_email='andrey@kostenko.name',
packages=['rq_cron', 'rq_cron.scripts'],
install_requires=['rq>=0.3.5', 'croniter'],
entry_points=''... | Healthjoy/rq-cron | setup.py | Python | mit | 475 |
from nltk.tokenize import word_tokenize
from nltk.stem.snowball import EnglishStemmer
from nltk.corpus import stopwords
from collections import defaultdict
from search_backend.search_index import searchIndex
import operator
#from iRnWsLeo.search_backend.search_index import searchIndex
#from search_backend.create_index ... | Langhaarjoe/iRnWsLeo | search_backend/__init__.py | Python | mit | 1,949 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-25 18:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('transcript', '0025_transcriptphrasecorrectionvote_original_phrase'),
]
operations =... | WGBH/FixIt | mla_game/apps/transcript/migrations/0026_transcript_active.py | Python | mit | 486 |
"""Run commands in a new terminal window."""
from __future__ import annotations
import logging
import os
import shlex
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from tkinter import messagebox
from porcupine import get_main_window, utils
log = logging.getLogger(__name__)
_thi... | Akuli/editor | porcupine/plugins/run/terminal.py | Python | mit | 5,179 |
# -*- coding: utf8 -*-
import random
import re
from helga.plugins import match
def imgur(image):
"""
Returns an imgur link with a given hash
"""
return 'http://i.imgur.com/{0}.gif'.format(image)
RESPONSES = {
# Direct text responses
r'(gross|disgusting|eww)': (imgur('XEEI0Rn'),), # Dumb an... | shaunduncan/helga-oneliner | helga_oneliner.py | Python | mit | 8,137 |
""" Utilities """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Logging
# =======
import logging
import os, os.path
from colorlog import ColoredFormatter
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = ColoredFormatter(
"%(lo... | yuanchima/Activation-Visualization-Histogram | util.py | Python | mit | 1,077 |
#!/usr/bin/env python
import optparse
import sys
from kimpira.core import Runtime
from kimpira.version import get_version
def parse_args():
usage = "usage: %prog [options] <jobfile>"
p = optparse.OptionParser(usage)
p.add_option('-V', '--version', action='store_true', dest='show_version', default=False, ... | khattori/kimpira | kimpira/main.py | Python | mit | 745 |
#coding = utf-8
import sys
from File import File
from Execute import Execute
def test():
isKeep = True
dstFileName = None
argsLen = len(sys.argv)
if argsLen < 2:
sys.exit()
if argsLen >= 3:
if sys.argv[2].startswith('-nk'):
isKeep = False
if argsLen > 3:
dstFileName = sys.argv[3]
srcFile = Fi... | shallyan/AutoTest | Src/Tester.py | Python | mit | 459 |
#!/usr/bin/env python
'''
https://projecteuler.net/problem=20
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divi... | ArthurZey/toyproblems | projecteuler/0021_amicable_numbers.py | Python | mit | 1,028 |
from distutils.core import setup
import py2exe
setup(console=['daemon.py'])
| IngenuityEngine/daemon | setup.py | Python | mit | 77 |
import base64
import os
from django.test import Client as TC
import datetime
import logging
import pytz
from django.utils.module_loading import import_string
from api.directions.sql_func import direction_by_card, get_lab_podr, get_confirm_direction_patient_year, get_type_confirm_direction
from api.stationar.stationa... | moodpulse/l2 | integration_framework/views.py | Python | mit | 76,926 |
# Generated by Django 3.1.2 on 2020-11-10 11:51
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('emailtemplates', '0005_auto_20201110_1115'),
]
operations = [
migrations.AlterField(
model_name='em... | deployed/django-emailtemplates | emailtemplates/migrations/0006_auto_20201110_1151.py | Python | mit | 689 |
from collections import defaultdict, OrderedDict
from typing import Callable
class HookRegistry:
def __init__(self):
self.hooks = defaultdict(OrderedDict)
def register(self, name: str, func: Callable):
self.hooks[name][func] = True
def run_hook(self, name: str, *args, **kwargs):
... | fin/froide | froide/foirequest/hooks.py | Python | mit | 544 |
from setuptools import setup, find_packages
from os.path import dirname, join
import phone_iso3166
def readfile(filename):
with open(join(dirname(__file__), filename), 'r') as f:
return f.read()
setup(
name="phone-iso3166",
description="Phonenumber to ISO 3166-1 mapping",
install_requires=[
... | mehulsbhatt/phone-iso3166 | setup.py | Python | mit | 980 |
#!/usr/bin/python
import math
import numpy as np
class Gesture(object):
def __init__(self,name):
self.name=name
def getName(self):
return self.name
def set_palm(self,hand_center,hand_radius):
self.hand_center=hand_center
self.hand_radius=hand_radius
def set_finger_pos(s... | mahaveerverma/hand-gesture-recognition-opencv | GestureAPI.py | Python | mit | 3,579 |
from django.contrib import admin
from django import forms
from . import models
from nnmarkdown.form import MarkdownWidget
from nnscr.admin import site
class PageAdminForm(forms.ModelForm):
class Meta:
model = models.Page
exclude = ("slug",)
widgets = {
"text": MarkdownWidget
... | nnscr/nnscr.de | pages/admin.py | Python | mit | 430 |
from weight.weight_vector import WeightVector
from data.data_pool import DataPool
import os
from learner import logger
__version__ = '1.0.0'
class PerceptronLearnerBase:
name = "PerceptronLearnerBase"
def __init__(self, w_vector=None):
self.w_vector = {}
if w_vector is None:
re... | sfu-natlang/glm-parser | src/learner/perceptron_base.py | Python | mit | 6,218 |
# 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/v2015_04_01/operations/_autoscale_settings_operations.py | Python | mit | 22,225 |
"""
Template tags for reversion application.
"""
| oblalex/django-workflow | src/workflow/templatetags/__init__.py | Python | mit | 49 |
#!/usr/bin/env python
import sys
import json
import platform
from alertaclient.api import ApiClient
from alertaclient.alert import Alert
from alertaclient.heartbeat import Heartbeat
class Listener(object):
def wait(self):
data = sys.stdin.readline()
headers = dict([x.split(':') for x in data.sp... | msupino/alerta-contrib | integrations/supervisor/evlistener.py | Python | mit | 2,514 |
"""
Compiler objects for postgres data definition language.
"""
from sqlalchemy.sql.expression import Executable, ClauseElement
from sqlalchemy.ext.compiler import compiles
class CreateTableAs(Executable, ClauseElement):
def __init__(self, name, query):
self.name = name
self.query = query
@com... | portfoliome/pgawedge | pgawedge/ddl.py | Python | mit | 509 |
"""
Some common utilities.
"""
from turtle import Turtle
def turtle_subclass(name):
"""
Creates a subclass of Turtle with the given name.
"""
return type(name, (Turtle,), {})
def translate_methods(cls, translations):
"""
Creates aliases for method names.
"""
for method, aliases in tr... | wrwrwr/turtle-trans | turtletrans/translate.py | Python | mit | 444 |
#!/usr/bin/env python2
import sys
import json
import struct
import subprocess
import shlex
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
return json.loads(messag... | vayan/external-video | app/mpv.py | Python | mit | 487 |
# Copyright (c) 2012 Roberto Alsina y otros.
# 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, pub... | servalproject/nikola | nikola/plugins/template_mako.py | Python | mit | 3,347 |
# The MIT License (MIT)
#
# Copyright (c) 2018 Niklas Rosenstein
#
# 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,... | nr-plugins/c4ddev | lib/nr.types/src/nr/types/sumtype.py | Python | mit | 6,522 |
import json
import os
import ntpath
import datetime as dt
import pprint
import boto3
def get_config():
'''
Load the configuration from ./config.json
'''
with open('config.json', 'r') as config_file:
return json.load(config_file)
def get_new_files(config, max_age_in_hours=24):
'''
Get array of all files younge... | tzaffi/boto3play | encodeAndS3sync.py | Python | mit | 2,841 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division,absolute_import)
from .K2onSilicon import K2onSilicon
| danxhuber/k2epic | checkk2fov/__init__.py | Python | mit | 135 |
from rest_framework import routers
class NestedRouter(routers.DefaultRouter):
"""
Custom router which hides nested URLs as they cannot be reversed.
"""
def get_api_root_view(self):
"""
Return a view to use as the API root.
Ignores any URLs which do not reverse correctly.
... | kevin-brown/drf-nested-viewsets | rest_nested_viewsets/routers.py | Python | mit | 1,254 |
# 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/network/azure-mgmt-network/azure/mgmt/network/v2019_11_01/operations/_load_balancer_backend_address_pools_operations.py | Python | mit | 8,928 |
# -*- coding: utf-8 -*-
# Copyright 2015-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
import unittest
from sqlalchemy.schema import Table
from carepoint.tests.db.db import DatabaseTest
from carepoint.models.cph.fdb_gcn_seq import FdbGcnSeq
class TestModelsCphFdbGcnSeq(DatabaseTest):
d... | laslabs/Python-Carepoint | carepoint/tests/models/cph/test_fdb_gcn_seq.py | Python | mit | 465 |
# -*- coding: utf-8 -*-
import sys
#Éú³ÉºòÑ¡¼¯C1
#return£º×Öµäkey=item;value=item³öÏֵĴÎÊý
def getC1(srcdata):
c1 = {}
for transaction in srcdata:
for item in transaction:
key = frozenset(set([item])) #frozenset²Å¿ÉÒÔ×÷Ϊ×ÖµäµÄkey
#¼ÆÊýitem
if key in c1:
... | RayleighChen/Improve | Project/python/PyLDA-Apriori/m3.py | Python | mit | 2,169 |
# DarkCoder
def sum_of_series(first_term, common_diff, num_of_terms):
"""
Find the sum of n terms in an arithmetic progression.
>>> sum_of_series(1, 1, 10)
55.0
>>> sum_of_series(1, 10, 100)
49600.0
"""
sum = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff)
#... | TheAlgorithms/Python | maths/sum_of_arithmetic_series.py | Python | mit | 482 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('backend', '0006_auto_20141203_0021'),
]
operations = [
migrations.AlterField(
model_name='meeting',
... | euhackathon/commission-today-api | backend/backend/migrations/0007_auto_20141203_0934.py | Python | mit | 480 |
import json
from accelerator.models import CriterionOptionSpec
from impact.v1.views.utils import valid_keys_note
from impact.v1.helpers.validators import INVALID_INTEGER_ERROR
from impact.tests.api_test_case import APITestCase
from impact.tests.utils import assert_data_is_consistent_with_instance
from impact.tests.fac... | masschallenge/impact-api | web/impact/impact/tests/test_criterion_option_spec_list_view.py | Python | mit | 4,303 |
from PyQt4 import QtGui, QtCore
from shapely.geometry import Point
from shapely import affinity
from math import sqrt
import FlatCAMApp
from GUIElements import *
from FlatCAMObj import FlatCAMGerber, FlatCAMExcellon
class FlatCAMTool(QtGui.QWidget):
toolName = "FlatCAM Generic Tool"
def __init__(self, app,... | silasb/flatcam | FlatCAMTool.py | Python | mit | 8,497 |
import sublime
import sublime_plugin
import json
import os
import traceback
from threading import Thread
from subprocess import PIPE, Popen
dirtyFiles = []
pluginSettings = None
pluginProjectSettings = None
basicPluginProjectSettings = None
defaultPluginProjectSettings = None
pluginPath = None
userPath = None
upgradeC... | willrowe/sublime-sass-compile | SassCompile.py | Python | mit | 13,518 |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
# if you have postgres use this uri:
SQLALCHEMY_DATABASE_URI = "postgresql://rehub:rehub@localhost/rehub"
# if you want to use sqlite, use this one:
# SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'rehub.db')
SQLALCHEMY_MIGRATE_REPO = os... | xavitorne/mountain-rehub | config.py | Python | mit | 490 |
# Spreading Udaciousness
# One of our modest goals is to teach everyone in the world to program and
# understand computer science. To estimate how long this will take we have
# developed a (very flawed!) model:
# Everyone answering this question will convince a number, spread, (input to
# the model) of their friends ... | JoseALermaIII/python-tutorials | pythontutorials/Udacity/CS101/Lesson 23 - Problem Set/Q3-Spreading Udaciousness.py | Python | mit | 1,742 |
from django.contrib import admin
from metadata.models import *
# Register your models here.
admin.site.register(TanitJobsCategory)
admin.site.register(KeeJobsCategory)
| firasbenmakhlouf/JobLookup | metadata/admin.py | Python | mit | 169 |
class LinkedList():
def __init__(self, value=None):
self.value = value
self.before = None
self.behind = None
def __str__(self):
if self.value is not None:
return str(self.value)
else:
return 'None'
def init():
return LinkedList('HEAD')
de... | minfun/leetcode | notes/data_structure_linked_list.py | Python | mit | 2,160 |
import ChromaPy32 as Chroma # Import the Chroma Module
from time import sleep
Keypad = Chroma.Keypad() # Initialize a new Keypad Instance
RED = (255, 0, 0) # Initialize a new color by RGB (RED,GREEN,BLUE)
Keypad.setbyRow(2, RED) # sets the whole third row of the Keyboad-Grid to red
Keypad.applyGrid() # applies... | Vaypron/ChromaPy | Example Scripts/Keypad/3. setbyRow.py | Python | mit | 370 |
import os
from typing import Optional
import semver
from gitflow import _, version
from gitflow.common import Result
from gitflow.const import VersioningScheme
from gitflow.version import VersionConfig
def filter_sequence_number(version_config, prev_version, global_seq):
if version_config.versioning_scheme == V... | abacusresearch/gitflow | gitflow/procedures/scheme/scheme_procedures.py | Python | mit | 10,745 |
# -*- coding: utf8 -*-
from __future__ import print_function
from __future__ import absolute_import
from builtins import zip
from builtins import next
from builtins import range
import copy
import json
import os
import signal
import sys
from logging import StreamHandler
from uuid import uuid4
import click
import ether... | ethereum/pyethapp | pyethapp/app.py | Python | mit | 30,125 |
#!/usr/bin/env python
# coding: utf-8
import sys
import os
import time
import random
import string
import requests
import json
import re
import stat
import hashlib
import subprocess
#import sqlite3
from os.path import dirname
import zbxtg_settings
class Cache:
def __init__(self, database):
self.database ... | ableev/Zabbix-in-Telegram | zbxtg.py | Python | mit | 38,641 |
from datetime import datetime
from collections import defaultdict
from todo.models.calendar import Calendar
from todo.models.event import Event
from todo.models.stat import Stat
from todo.models.user import User
def rollup_users():
rollup = defaultdict(lambda: defaultdict(int))
for user in User.get_all():
... | slackpad/hashtagtodo-open | todo/stat_rollup.py | Python | mit | 1,528 |
import socket
import plugin
import ssl
import user
import os
class bot(object):
def __init__(self, server):
self.server = server
self.port = 6667
self.ssl = None
self.channels = []
self.connectedChannels = []
self.nick = 'default_nick'
self.realName = 'defau... | Th3l5D/lsbot | default.py | Python | mit | 5,164 |
import sys
import ceph_medic
import logging
from ceph_medic import runner, collector
from tambo import Transport
logger = logging.getLogger(__name__)
def as_list(string):
if not string:
return []
string = string.strip(',')
# split on commas
string = string.split(',')
# strip spaces
... | alfredodeza/ceph-doctor | ceph_medic/check.py | Python | mit | 2,944 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^login/$', views.login, name='login'),
url(r'^register/$', views.register, name='register'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^plaza/$', views.plaza, name='plaza')... | huaiping/pandora | membership/urls.py | Python | mit | 324 |
""" Functions related to writing to and retrieving from cache files
"""
import os
import numpy as np
from log_yatsm import logger
_image_ID_str = 'image_IDs'
def get_line_cache_name(dataset_config, n_images, row, nbands):
""" Returns cache filename for specified config and line number
Args:
dataset_... | jmorton/yatsm | yatsm/cache.py | Python | mit | 8,031 |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
import csv
from flask import flash, session
from indico.core.er... | mic4ael/indico | indico/util/roles.py | Python | mit | 3,193 |
# Definition for a point.
# class Point(object):
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution(object):
def maxPoints(self, points):
"""
:type points: List[Point]
:rtype: int
"""
lines = {}
n = len(points)
... | sogapalag/problems | leetcode/149.Max-Points-on-a-Line.py | Python | mit | 1,184 |
#!/bin/python
"""
Lisa just got a new math workbook. A workbook contains exercise problems, grouped into chapters.
There are nn chapters in Lisa's workbook, numbered from 11 to nn.
The ii-th chapter has titi problems, numbered from 11 to titi.
Each page can hold up to kk problems. There are no empty pages or unnecess... | codecakes/algorithms_monk | implementation/lisa_workbook_array_single_iter.py | Python | mit | 2,037 |
import os.path
from crepehat import SObject
class Kitchen(SObject):
sources = []
extensions = []
def __init__(self, sources, extensions=None):
if not hasattr(sources, "__iter__"):
sources = [sources]
self.sources = sources
if extensions and not hasattr(extensions, "_... | hyphyphyph/lascaux | crepehat/kitchen.py | Python | mit | 1,587 |
from django.apps import AppConfig
class GeoTweetsConfig(AppConfig):
name = 'geo_tweets'
| adoublebarrel/geo-tweet-exercise | server/assesment_site/geo_tweets/apps.py | Python | mit | 94 |
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
import pytest
from openpyxl.xml.functions import fromstring, tostring
from openpyxl.tests.helper import compare_xml
@pytest.fixture
def Reference():
from ..reference import Reference
return Reference
@pytest.fixture
def Worksheet():
... | cgimenop/Excel2Testlink | ExcelParser/lib/openpyxl/chart/tests/test_reference.py | Python | mit | 2,862 |
from repreader import RepReader
from operator import itemgetter
from displayer import Displayer
from optparse import OptionParser
import sys
usage = "Usage: %prog -u <USERNAME> -p <PASSWORD> -n <USERNUMBER TO DISPLAY>"
parser = OptionParser(usage)
parser.add_option(
"-u",
"--username",
dest="user",
he... | rbonick/care-tags_scripts | care_tags_repmeter/main.py | Python | mit | 1,036 |
#!/usr/bin/python
import time
import serial
import sys
import json
def ftdi232h_cmd(thePort, theBaud, theCommand):
ser = serial.Serial(
port=thePort, # /dev/ttyUSB0
baudrate=theBaud, # 9600
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
xonxoff=0, rtscts=0, dsrdtr=0,
... | stephaneAG/FT232H | ft232h__PythonCompanion_WIP_TESTER.py | Python | mit | 1,231 |
import time
import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
from sklearn.neural_network import MLPRegressor
from sklearn.ensemble import GradientBoostingRegressor
import matplotlib.pyplot as plt
from prepare.prepare_lin import PrepareDataLin
from p... | danielwpz/soybean | src/main.py | Python | mit | 3,856 |
class Solution:
# @param {integer[]} nums
# @return {boolean}
def containsDuplicate(self, nums):
return len(nums) != len(set(nums))
| zhyu/leetcode | algorithms/containsDuplicate/containsDuplicate.py | Python | mit | 153 |
from __future__ import unicode_literals
from . import exceptions
DEFAULT_HOST = 'http://api.acoustid.org/'
FORMATS = ('json', 'jsonp', 'xml')
META = (
'recordings', 'recordingids', 'releases', 'releaseids',
'releasegroups', 'releasegroupids', 'tracks', 'compress',
'usermeta', 'sources'
)
ERRORS = {
... | mattdennewitz/python-acoustid-api | acoustid_api/consts.py | Python | mit | 819 |
"""The template component."""
from __future__ import annotations
import asyncio
from collections.abc import Callable
import logging
from homeassistant import config as conf_util
from homeassistant.const import (
CONF_UNIQUE_ID,
EVENT_HOMEASSISTANT_START,
SERVICE_RELOAD,
)
from homeassistant.core import Co... | rohitranjan1991/home-assistant | homeassistant/components/template/__init__.py | Python | mit | 5,547 |