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 python3
# -*- coding: utf-8 -*-
#
# This file is part of my-weather-indicator
#
# Copyright (c) 2012 Lorenzo Carbonell Cerezo <a.k.a. atareao>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... | atareao/my-weather-indicator | src/machine_information.py | Python | mit | 1,943 |
#!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the stripecoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
... | stripecoin/stripecoin | share/qt/clean_mac_info_plist.py | Python | mit | 901 |
import socket
import os
import threading
import time
import zipfile
import threading
import myPacket as mp
def getParentDirectory(path):
path2 = path.split('/')
temp=''
for ph in path2:
if(len(ph)>4 and (ph[len(ph)-4:] == '.txt')):
break
temp = os.path.join(temp, ph)
... | misterlihao/network-programming-project | synchronizationRole.py | Python | mit | 3,395 |
####################################
# Sample Receiver Script
# [Usage]
# python receiver.py
# python receiver.py > data.csv
# [Data Format]
# id,time,x,y,z
# [Exaple]
# 1,118.533,-0.398,-0.199,-0.978
####################################
import sys
import os
import math
import time
import SocketServer
... | shivekkhurana/learning | python/scripts/user_input/receiver.py | Python | mit | 590 |
"""
Django settings for theoliveoilbakers project.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import sys
from os.path import abspath, dirname, join
from django... | theodesp/aspoonfulofhome | theoliveoilbakers/settings/base.py | Python | mit | 6,232 |
import os
import sys
import time
import posixpath
import threading
if sys.version > '3':
import urllib.parse
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
else:
import urllib
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPReque... | braceio/tags | tags/generator.py | Python | mit | 7,669 |
# -*- coding: utf-8 -*-
"""
module.name
~~~~~~~~~~~~~~~
Preamble...
"""
from __future__ import absolute_import, print_function, unicode_literals
import json
# TEST SETTINGS
import random
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
# Django replaces this, but it still wants it. *shrugs*
DATABASES = ... | alexhayes/django-async-test | django_async_test/tests/testapp/settings.py | Python | mit | 695 |
#!/usr/bin/env python
class Trouble:
def __init__(self, number):
self.number = number
def __str__(self):
return '<Trouble: {}>'.format(self.number)
class Support:
def __init__(self, name):
self.name = name
self.next = None
def set_next(self, next):
self.next... | kobtea/gof | chain_of_responsibility.py | Python | mit | 2,871 |
from Crypto.Cipher import AES
import base64
import hashlib
import math
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
# pseudo-random function
def PRF(key, plaintext):
keyHash = hashlib.sha256(key).hexdigest()
ptxtHash = hashlib.sha256(plaintext).hexdi... | izzygomez/cocoon | crypto/crypto.py | Python | mit | 4,136 |
#!/usr/bin/env python
import sys
import time
import zmq
import numpy as np
try:
import progressbar
except ImportError:
progressbar = None
try:
import pylepton
except ImportError:
print "Couldn't import pylepton, using Dummy data!"
Lepton = None
# importing packages in parent folders is voodoo
fr... | wonkoderverstaendige/raspi_lepton | server/lepton_server.py | Python | mit | 972 |
from ._topics import visualize_topics
from ._heatmap import visualize_heatmap
from ._barchart import visualize_barchart
from ._term_rank import visualize_term_rank
from ._hierarchy import visualize_hierarchy
from ._distribution import visualize_distribution
from ._topics_over_time import visualize_topics_over_time
from... | MaartenGr/BERTopic | bertopic/plotting/__init__.py | Python | mit | 616 |
# Django settings for temp project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {'ENGINE': 'django.db.backends.sqlite3'}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://do... | imposeren/django-messages-extends | test_settings.py | Python | mit | 4,967 |
"""Conversation objects."""
import asyncio
import datetime
import logging
from hangups import (parsers, event, user, conversation_event, exceptions,
hangouts_pb2)
logger = logging.getLogger(__name__)
CONVERSATIONS_PER_REQUEST = 100
MAX_CONVERSATION_PAGES = 100
async def build_user_conversatio... | tdryer/hangups | hangups/conversation.py | Python | mit | 46,809 |
##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2014
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - ... | laenderoliveira/exerclivropy | exercicios_resolvidos/capitulo 04/exercicio-04-04.py | Python | mit | 810 |
#SPDX-License-Identifier: MIT
import io
import os
import re
from setuptools import find_packages
from setuptools import setup
def read(filename):
filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io.open(filename, mode="r", encoding='utf-8') as fd:
return re.s... | OSSHealth/ghdata | workers/insight_worker/setup.py | Python | mit | 1,388 |
import _plotly_utils.basevalidators
class StartarrowsizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name="startarrowsize",
parent_name="layout.scene.annotation",
**kwargs
):
super(StartarrowsizeValidator, self).__init__(
... | plotly/python-api | packages/python/plotly/plotly/validators/layout/scene/annotation/_startarrowsize.py | Python | mit | 557 |
# encoding:utf-8
import logging
import maya.api.OpenMaya as om
# fast convenience tests on API objects
def isValidMObjectHandle(obj):
if isinstance(obj, om.MObjectHandle):
return obj.isValid() and obj.isAlive()
else:
return False
def isValidMObject(obj):
if isinstance(obj, om.MObject):
... | yes7rose/maya_utils | python/maya_utils/api_utils.py | Python | mit | 2,347 |
# coding: utf-8
""" Analyze the output from frequency mapping """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import os
# Third-party
import astropy.units as u
from astropy import log as logger
import matplotlib.pyplot as plt
import numpy as np
... | adrn/StreamMorphology | scripts/freqmap/analyze.py | Python | mit | 5,960 |
# -*- coding: utf-8 -*-
"""
Created on Wed May 04 22:38:40 2016
@author: Alex
"""
import numpy as np
class yic:
def __init__(self):
self.struct = np.array([[0],[0],[0]])
self.score = np.array([[0],[0],[0]])
self.fit = np.array([[0],[0],[0]])
return
def yic(sel... | FlaminMad/processControl | processControl/dev/yic.py | Python | mit | 563 |
# -*- coding: utf-8 -*-
"""
news_data.pipeline
~~~~~~~~~~~~~~~~~~
news_data processing pipeline package
:license: MIT, see LICENSE for more details.
""" | lbracken/news_data | pipeline/__init__.py | Python | mit | 175 |
import os
# Django settings for geonition project.
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True... | Mapita/mapita_ci | mapita/mapita_ci/settings_geojson_rest.py | Python | mit | 8,582 |
# -*- coding: utf-8 -*-
__all__ = ["mpd"]
| ggilestro/majordomo | actors/__init__.py | Python | mit | 42 |
import platform
import urllib
import subprocess
from progressbar import ProgressBar
class Downloader(object):
WINDOWS_DOWNLOAD_URL = "http://cache.lego.com/downloads/ldd2.0/installer/setupLDD-PC-4_3_8.exe"
MAC_DOWNLOAD_URL = "http://cache.lego.com/downloads/ldd2.0/installer/setupLDD-MAC-4_3_8.zip"
PB = N... | cbrentharris/bricklayer | bricklayer/utils/downloader.py | Python | mit | 951 |
### "imports"
from example.classes import Data
### "other-imports"
import csv
import json
from example.utils import tempdir
### "csv-subclass"
class Csv(Data):
"""
CSV type.
"""
aliases = ['csv']
def present(self):
with tempdir():
with open("dictionary.csv", "w") as f:
... | dexy/cashew | example/classes1.py | Python | mit | 748 |
from cached_property import cached_property
import sympy
from devito.ir.equations.algorithms import dimension_sort, lower_exprs
from devito.finite_differences.differentiable import diff2sympy
from devito.ir.support import (IterationSpace, DataSpace, Interval, IntervalGroup,
Stencil, dete... | opesci/devito | devito/ir/equations/equation.py | Python | mit | 9,325 |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root is None:
return None
left = self.invertTree(root.left)
... | jiadaizhao/LeetCode | 0201-0300/0226-Invert Binary Tree/0226-Invert Binary Tree.py | Python | mit | 430 |
import numpy as np
def add_vtarg_and_adv(seg, gamma, lam):
"""
Compute target value using TD(lambda) estimator, and advantage with GAE(lambda)
:param seg: (dict) the current segment of the trajectory (see traj_segment_generator return for more information)
:param gamma: (float) Discount factor
:p... | hill-a/stable-baselines | stable_baselines/trpo_mpi/utils.py | Python | mit | 1,008 |
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215)
import multiprocessing
assert multiprocessing
import re
from setuptools import setup, find_packages
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = 'activatable_mode... | wesleykendall/django-activatable-model | setup.py | Python | mit | 1,680 |
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy.special import expit
import numpy.linalg
from functions.function import Function
class DPP(Function):
def __init__(self, V, K=None):
self.V = V
if K is None:
self.K = np.eye(len(V))
... | net-titech/VidSum | src/packages/aistats-flid/code/functions/dpp.py | Python | mit | 2,448 |
# imports from solution
from utils import underestimate_edit_distance_fn_factory
# 3rd-party imports
from Queue import Queue, PriorityQueue
def shortest_path_bfs(word1, word2, neighbors_fn, queue=None):
visited_words = set()
start_state = ( word1, )
q = Queue() if queue is None else queue
q.put(star... | py-in-the-sky/challenges | intermediate_words_search_python/shortest_path_search.py | Python | mit | 1,749 |
import argparse
import csv
import glob
import logging
from logging.config import fileConfig
import os
import re
import sys
import xlrd
fileConfig('parsers/logging_config.ini')
logger = logging.getLogger()
reload(sys)
sys.setdefaultencoding('utf-8')
FILE_REGEX = "Demand|Budget at a glance|Receipt"
BUDGET_START_SLUG = "... | cbgaindia/parsers | state_budget/sikkim/sikkim_budget_csv_generator.py | Python | mit | 4,866 |
import ninjag
import os
from read_all import read_all
def test():
f_inputs = [
"input/in1_const.yaml",
"input/in1_rules.yaml",
"input/in1_tasks.yaml",
]
f_answer = "output/out1_combined.ninja"
f_solution = "solution/sol1.ninja"
cmd = " ".join(["ninjag", f_answer, *f_inp... | yuhangwang/ninjag-python | test/frontend/c/test_2.py | Python | mit | 443 |
#!/usr/bin/python3
import re
import sys
######## Global Variables
# Stacks
dictionary = []
execution = []
operand = []
# Sept 21, 2011 -- fixed the handling of }{ -- each brace should be a separate token
# A regular expression that matches postscript each different kind of postscript token
pattern = '/?[a-zA-Z][a-zA-... | vonderborch/CS355 | sps - working/sps.py | Python | mit | 9,305 |
import sublime
import sublime_plugin
import re
import subprocess
from array import *
from .giterCommandThread import CommandThread
from .commandBuilders import buildCommand
from .jsonDecoderBuilder import JsonDecoderBuilder
from .sbtBuildFileEditor import SbtBuildFileEditor
from .logger import LoggerFacade
from .utils ... | lgmerek/ScalaProjectGeneratorFacade | scalaProjectGeneratorFacade.py | Python | mit | 6,824 |
from pygame import *
from res import createImage, playSound
class Room():
def __init__(self, levelSize, spritePath):
self.level = Surface(levelSize)
self.levelRect = self.level.get_rect()
self.levelUnlocked = False
self.levelCleared = False
self.spike = crea... | aouerfelli/SuperDD-Python | res/Room.py | Python | mit | 8,839 |
from codecs import open
from ohoh import build_parser, DEFAULT_HOST, DEFAULT_PORT
from os import path
import os
import pytest
import sys
import time
@pytest.fixture
def parser():
return build_parser()
@pytest.fixture
def modfile(request, tmpdir):
def uninstall():
sys.path.remove(tmpdir.strpath)
s... | te-je/ohoh | tests/test_script.py | Python | mit | 3,667 |
# Sends GET to local server
# Author: schdub
#!/usr/bin/python
import socket
import sys
def GET(host, path, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.30)
s.connect((host, port))
s.send("GET %s HTTP/1.0\r\n" % (path))
total_data = []
while True:
data = s... | MrOnlineCoder/shockd | scripts/get.py | Python | mit | 523 |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Line(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scatter3d.marker"
_path_str = "scatter3d.marker.line"
_valid_props = {
"autocolorscale... | plotly/plotly.py | packages/python/plotly/plotly/graph_objs/scatter3d/marker/_line.py | Python | mit | 24,077 |
#!/usr/bin/env python3
# Copyright (c) 2018-2019 TurboCoin
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the scantxoutset rpc call."""
from test_framework.test_framework import TurbocoinTestFramework
from test_framework.u... | Phonemetra/TurboCoin | test/functional/rpc_scantxoutset.py | Python | mit | 12,820 |
from __future__ import unicode_literals
from django.db import models
from jsonfield import JSONField
SEVERITY_CHOICES = [('c', "critical"), ('w', "warning"), ('i', "info")]
class Event(models.Model):
description = models.TextField(max_length=500, default='')
severity = models.CharField(('severity'), choices=... | antipoachingmap/django-app | antipoaching/models.py | Python | mit | 909 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except:
from distutils.core import setup, find_packages
setup(
name = 'rpmquality',
version = '0.1',
description = 'Short description',
long_description = 'Long description',
keywords = 'some, ke... | hhorak/rpmquality | setup.py | Python | mit | 1,001 |
from PyQt4 import QtCore, QtGui
from BaseStudy import BaseStudy
class Jitter(BaseStudy):
def __init__(self):
super(Jitter, self).__init__()
self.setWindowTitle("Jitter Function")
widget = QtGui.QWidget()
self.vbox = QtGui.QVBoxLayout(widget) # General Box
self.hbox1 = Qt... | mattBrzezinski/Hydrogen | robot-controller/Study/Jitter.py | Python | mit | 3,906 |
from typing import Dict
from urllib.parse import urlparse
from testinfra.host import Host
from conftest import for_host_types, WebDriver
class TestMediaServer:
@for_host_types('pi')
def test_media_server(self, hostname: str, hosts: Dict[str, Host], addrs: Dict[str, str]) -> None:
# For now we just do ... | CallumCameron/pi-server | zz-vm-testing/test_05_media_server.py | Python | mit | 900 |
from django.contrib import admin
from blog.models import blogdata
# Register your models here.
class blogdataAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'date',)
list_display_links = ('id', 'title',)
admin.site.register(blogdata, blogdataAdmin)
| raryosu/djangoblog | raryosublog/blog/admin.py | Python | mit | 263 |
from django.shortcuts import render
from SharedFunctions.models import *
from Lights.models import *
def HandlePhoneRequest(request):
area = request.GET.get('area', 'None')
if area == 'None':
return PhoneHomePage(request)
elif area == 'lights':
if request.GET.get('room', 'None') != 'None':
if request.GET.get... | Tomcuzz/OctaHomeAutomation | Api/ciscophone.py | Python | mit | 3,020 |
from apiwrapper.endpoints.attachment_public import AttachmentPublic
from tests.endpoints.test_endpoint import EndpointTest
class AttachmentPublicTest(EndpointTest):
__base_endpoint_url = "/attachment-public/%s"
@property
def _base_endpoint(self):
return self.__base_endpoint_url % self.random_uuid... | PJUllrich/Complete-Bunq-API-Python-Wrapper | tests/endpoints/test_attachment_public.py | Python | mit | 1,221 |
from os import path
FREEZER_DESTINATION = path.abspath(path.join(path.dirname(__file__), '../dist'))
# The size the raw images will be resized to
IMAGE_WIDTH = 1000
# The JPEG quality used to save the new images
IMAGE_QUALITY = 70
| thusoy/robertblag | robert/config.py | Python | mit | 234 |
#!/usr/bin/env python3
import sys
def vadd(v1, v2):
return tuple(x + y for x, y in zip(v1, v2))
ALL_DIRS = [(y, x) for x in [-1,0,1] for y in [-1,0,1]]
def get_index(default, m, pos):
l = "".join([m.get(vadd(pos, d), default) for d in ALL_DIRS])
l = l.replace(".", "0").replace("#", "1")
idx = int(l... | msullivan/advent-of-code | 2021/20b.py | Python | mit | 1,368 |
import os
input_dir = "./convergence_inputs/"
output_dir = "./convergence_outputs/"
print("Removing input files")
os.system("rm -rf " + input_dir)
print("Removing output directories / files")
os.system("rm -rf " + output_dir)
| kramer314/1d-vd-test | convergence-tests/cleanup.py | Python | mit | 229 |
import os
from re import match, sub
from datetime import datetime
from pkg_resources import resource_listdir
from cmsis_svd.parser import SVDParser
from functools import reduce
def find_for_mcu(mcu):
mcu = mcu.lower()
vendors = resource_listdir("cmsis_svd", "data")
for vendor in vendors:
fnames = ... | KivApple/mcu-info-util | mcu_info_util/svd_utils.py | Python | mit | 6,803 |
import os
import re
import logging
from picrename.prnm import fileops
class DateStrError(Exception):
pass
def exif_to_datetimestr(exif_data_string):
"""
Extracts the date from an EXIF tag and reformats it
"""
dateregex = re.compile(r"""
(?P<year>\d\d\d\d): # match the year
... | huegli/automation | picrename/picrename/prnm/renops.py | Python | mit | 8,392 |
# -*- coding: utf-8 -*-
## \package custom
# MIT licensing
# See: LICENSE.txt
| AntumDeluge/desktop_recorder | source/custom/__init__.py | Python | mit | 80 |
"""
flask.ext.restless.search
~~~~~~~~~~~~~~~~~~~~~~~~~
Provides querying, searching, and function evaluation on SQLAlchemy models.
The most important functions in this module are the :func:`create_query`
and :func:`search` functions, which create a SQLAlchemy query object and
execute that que... | HellerCommaA/flask-angular | lib/python2.7/site-packages/flask_restless/search.py | Python | mit | 19,670 |
"""Custom keras layers
"""
# Coding: utf-8
# File name: custom_layer.py
# Created: 2016-07-24
# Description:
## v0.0: File created. MergeRowDot layer.
from __future__ import division
from __future__ import print_function
__author__ = "Hoang Nguyen"
__email__ = "hoangnt@ai.cs.titech.ac.jp"
from keras import backend a... | gear/motifwalk | research/src/mane/custom_layers.py | Python | mit | 1,273 |
"""
WSGI config for tele_giphy project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
# Standard Library
import os
# Django
from django.core.wsgi import get_wsgi_application
os.... | JessicaNgo/TeleGiphy | tele_giphy/tele_giphy/wsgi.py | Python | mit | 426 |
# 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 ... | lmazuel/azure-sdk-for-python | azure-mgmt-servicebus/azure/mgmt/servicebus/models/action.py | Python | mit | 1,703 |
#!/usr/bin/env python
import PID
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import spline
#P=2.0, I=0.0, D=1.0, Derivator=0, Integrator=0, Integrator_max=100, Integrator_min=-100, reference=0.0
def PID_test(P=2.0, I=0.0, D=1.0, reference=0.0):
pidx = PID.PID(P, I, D)
... | gunnarsnorri/rescueranger | scripts/PID_test.py | Python | mit | 1,596 |
#-*- coding: utf-8 -*-
import hashlib
import getpass
from pymongo import MongoClient
id = raw_input("등록할 아이디를 입력하세요: ")
pw = getpass.getpass("등록할 비밀번호를 입력하세요(입력하는 것은 보이지 않습니다): ")
client = MongoClient('localhost', 27017)
db = client.RnBCafe
member_collection = db.member
if member_collection.find_one({'id': id}) is N... | Prokuma/cafe-order-system | register.py | Python | mit | 598 |
"""
AppVeyor will at least have few Pythons around so there's no point of implementing a bootstrapper in PowerShell.
This is a port of https://github.com/pypa/python-packaging-user-guide/blob/master/source/code/install.ps1
with various fixes and improvements that just weren't feasible to implement in PowerShell.
"""
f... | ionelmc/virtualenv | .appveyor/appveyor-bootstrap.py | Python | mit | 3,284 |
from __future__ import (absolute_import, print_function, division)
import Cookie
import copy
import warnings
from email.utils import parsedate_tz, formatdate, mktime_tz
import time
from netlib import encoding
from netlib.http import status_codes, Headers, Request, Response, decoded
from netlib.tcp import Address
from ... | ikoz/mitmproxy | mitmproxy/models/http.py | Python | mit | 14,861 |
from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:9332")
else:
access = Ser... | karpelescoin/karpelescoin | contrib/bitrpc/bitrpc.py | Python | mit | 7,846 |
def get_mnemo_arg(l):
assert l.startswith(' ')
l = l.strip()
i = l.find(' ')
if i >= 0:
return (l[:i], l[i+1:].strip())
else:
return (l, None)
def get_func_names(lines):
names = set()
entry = None
for l in lines:
if l.startswith(' '):
mnemo, arg = get... | achille-fouilleul/meta-ii | from_asm.py | Python | mit | 582 |
# 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 ... | Azure/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/_configuration.py | Python | mit | 2,963 |
from django.core.management import call_command
from static_precompiler.management.commands.compilestatic import get_scanned_dirs
from static_precompiler.settings import STATIC_ROOT, ROOT, OUTPUT_DIR
import pytest
import os
def test_get_scanned_dirs():
assert get_scanned_dirs() == sorted([
os.path.join(o... | paera/django-static-precompiler | static_precompiler/tests/test_management.py | Python | mit | 1,188 |
import urlparse
from scrapy.spider import BaseSpider
from scrapy.selector import Selector
from scrapy.http import Request
from ..items import Car
# Add the model(s) below you want to search for
# e.g. MODELS = ['Outback']
MODELS = []
# Enter the domain name(s) here you have permission to retrieve data from
# e.g. DO... | JeffPaine/subaru_search | subaru/spiders/subaru_spider.py | Python | mit | 3,059 |
from model.u_net import get_unet_128, get_unet_256, get_unet_512, get_unet_1024, get_unet_1024_hq, get_unet_1024_heng
import cv2
### These parameters might be changed ###
input_size = 1024
max_epochs = 150
threshold = 0.49
downscale = cv2.INTER_CUBIC
upscale = cv2.INTER_AREA
### These parameters might be changed ###
... | sergeyshilin/Kaggle-Carvana-Image-Masking-Challenge | params.py | Python | mit | 749 |
# -*- coding: utf-8 -*-
"""
Test Cases para el cálculo de los perfiles de consumo de referencia para la estimación del reparto horario
del consumo eléctrico, con el fin de calcular el PVPC a aplicar al periodo considerado.
"""
from unittest import TestCase
import pandas as pd
class TestsPerfilesConsumo(TestCase):
... | azogue/esiosdata | tests/test_perfiles_consumo_pvpc.py | Python | mit | 2,973 |
""" General utilities. """
# Standard library
from collections.abc import Mapping
# Third-party
import numpy as np
__all__ = ['rolling_window', 'atleast_2d', 'assert_angles_allclose']
class ImmutableDict(Mapping):
@classmethod
def from_dict(cls, somedict):
return cls(**somedict)
def __init__(... | adrn/gala | gala/util.py | Python | mit | 4,794 |
#! /usr/bin/env python
"""
Get status and output of any command, capable of handling unicode.
"""
import subprocess
import codecs
from tempfiles import *
tmp = TempFiles()
def getstatusoutput(cmd):
logname = tmp.getTempFileName()
log = codecs.open(logname, mode="w", encoding="utf-8", errors="replace", buff... | ajaybhatia/archlinux-dotfiles | Scripts/pythonscripts/subprocess_extensions.py | Python | mit | 760 |
for f in AllFonts():
hasEdits = False
for name, members in f.groups.items():
groupHasEdits = False
new = []
for m in members:
if m[-1] == "'":
groupHasEdits = True
hasEdits = True
new.append(m[:-1])
else:
... | typemytype/RoboFontExamples | fontGroups/changeGroupSingleQuote.py | Python | mit | 514 |
from flask import Blueprint, request, jsonify, abort
from amiibo.amiibo import AmiiboHex, GameSeriesHex, CharacterHex, VariantHex, AmiiboTypeHex, AmiiboModelHex, AmiiboSeriesHex, Hex
from amiibo.manager import AmiiboManager
from amiibo.filterable import AmiiboCollection
amiiboApp = Blueprint("amiibo", __name__)
amii... | N3evin/AmiiboAPI | routes/amiibo.py | Python | mit | 5,303 |
import os
import sys
import numpy as np
import pandas as pd
import pandas.util.testing as pdt
import unittest
sys.path.insert(0, os.path.abspath("../../"))
from specdal.spectrum import Spectrum
from specdal.collection import Collection
class GroupByTests(unittest.TestCase):
def setUp(self):
# total 36 spe... | EnSpec/SpecDAL | specdal/tests/test_groupby.py | Python | mit | 1,667 |
# Copyright (c) 2013 Michael Bitzi
# Licensed under the MIT license http://opensource.org/licenses/MIT
import unittest
from unittest.mock import create_autospec, patch
from pwm.ffi.xcb import xcb
import pwm.bar
import pwm.workspaces
import pwm.windows
from pwm.config import config
import test.util as util
class Tes... | mibitzi/pwm | test/test_workspaces.py | Python | mit | 8,632 |
"""Errors
This module implements a set of standard HTTP Errors.
"""
import json
import traceback
try:
from html import escape
except ImportError:
from cgi import escape # Deprecated since version 3.2
try:
from urllib.parse import urljoin as _urljoin
except ImportError:
from urlparse import urljoin a... | nizox/circuits | circuits/web/errors.py | Python | mit | 7,638 |
import sys
sys.path.append('/Users/natj/projects/arcmancer/lib/')
import pyarcmancer as pyac
from img import Imgplane
from visualize_polar import Visualize
from lineprofile import *
import units
import numpy as np
import matplotlib as mpl
from pylab import *
import os
from matplotlib import cm
import scipy.interpol... | natj/bender | sweep.py | Python | mit | 8,380 |
"""create categories table
Revision ID: 26e3340ce799
Revises: 34a1034caa3b
Create Date: 2013-11-02 10:46:23.617628
"""
from alembic import op
import sqlalchemy as sa
import json
revision = '26e3340ce799'
down_revision = '34a1034caa3b'
# Load categories fixture file.
# TODO: create an abstraction for this.
with ope... | hackcyprus/jobber | schema/versions/26e3340ce799_create_categories_ta.py | Python | mit | 961 |
# -*- coding=utf-8 -*-
# author: zhihua.ye@spreadtrum.com
# define struct about vt call statistics
#
from lib.logConf import *
from helper.excelhelper import *
class Call:
def __init__(self):
self.time = dict()
self.time['start'] = None # incoming/outgoing
self.time['end'] =... | deevarvar/myLab | sprd/vowifi/mengine_parser/helper/call.py | Python | mit | 9,784 |
from worldengine.simulations.basic import *
import random
from worldengine.views.basic import color_prop
from PyQt4 import QtGui
class WatermapView(object):
def is_applicable(self, world):
return world.has_watermap()
def draw(self, world, canvas):
width = world.width
height = world.h... | ftomassetti/worldengine | worldengine/views/WatermapView.py | Python | mit | 880 |
#1/usr/bin/env python3
import setuptools
setuptools.setup(
name = 'rheedsim',
version = '0.1.0',
packages = ['rheedsim'],
entry_points = {
'console_scripts':[
'rheedsim = rheedsim.__main__:main'
]
},
)
| chanjr/rheedsim | src/setup.py | Python | mit | 305 |
"""ユーザー設定用モジュール."""
import os
DEBUG = True
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'app1',
'app2',
]
ROOT_URLCONF = 'project.urls'
WSGI_APPLICATION = [
# 'wsgiref.validate.validator',
'ngo.wsgi.RedirectApp',
'ngo.wsgi.WSGIHandle... | naritotakizawa/ngo | tests/project2/project/settings.py | Python | mit | 941 |
#!/usr/bin/env python
from setuptools import setup
setup(
name='mimerender',
version='0.6.0',
description='RESTful HTTP Content Negotiation for Flask, Bottle, web.py '
'and webapp2 (Google App Engine)',
author='Martin Blech',
author_email='martinblech@gmail.com',
url='https://github.co... | martinblech/mimerender | setup.py | Python | mit | 1,437 |
#Problem 1:
#Python provides a built-in function called len that returns the length of a string
#so the value of len('allen') is 5.
#Write a function named right_justify that takes a string named s as a parameter and prints
#the string with enough leading spaces so that the last letter of the string is in column 70
#o... | hollylemos/think-python | chapter-03/3.py | Python | mit | 1,541 |
# -*- coding: utf-8 -*-
"""Rich and structured data types."""
from verta._internal_utils import documentation
# import base class first to avoid circular import
from ._verta_data_type import _VertaDataType
from ._confusion_matrix import ConfusionMatrix
from ._discrete_histogram import DiscreteHistogram
from ._float_h... | mitdbg/modeldb | client/verta/verta/data_types/__init__.py | Python | mit | 747 |
#!/usr/bin/env python
# Exercise 32: Loops and Lists
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for... | Akagi201/learning-python | lpthw/ex32.py | Python | mit | 887 |
from concurrent import futures
import time
import grpc
import demo_pb2
import demo_pb2_grpc
_ONE_DAY_IN_SECOND = 60 * 60 * 24
class Greeter(demo_pb2_grpc.GreeterServicer):
def SayHello(self,request,context):
return demo_pb2.HelloReply(message='Hello, %s' % request.name)
def serve():
#grpc服务器
... | tencrance/cool-config | python3/grpc/greeter_server.py | Python | mit | 690 |
a, b, c, d = map(int, input().split())
print(a * 1728 + b * 144 + c * 12 + d)
| y-sira/atcoder | ddcc2017-qual/b.py | Python | mit | 79 |
import unittest
import flavio
from . import mw
from flavio.physics.zdecays.test_smeftew import ZeroDict
import wilson
par = flavio.default_parameters.get_central_all()
class TestMW(unittest.TestCase):
def test_mW_SM(self):
self.assertAlmostEqual(mw.mW_SM(par), 80.3779, delta=0.02)
def test_shifts_s... | flav-io/flavio | flavio/physics/wdecays/test_mW.py | Python | mit | 729 |
from django.db import models
from django.utils import timezone
# For teammate manager and modification of Django's base user auth system
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
# Manager class that instantiates the creation of a new teammate
# source (i think): http:/... | ethanperez/t4k-rms | riders/models.py | Python | mit | 4,366 |
# Copyright (c) 2011 AOL Inc. All Rights Reserved.
#
# 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, merg... | MapQuest/mapquest-osm-server | src/python/dbmgr/dbm_stats.py | Python | mit | 3,450 |
#! usr/bin/python3
# -*- coding: utf8 -*-
import datetime
from getpass import getpass
from flask_script import Command
from scripts.create_json import WriteConfigJson
from application import db, app
from application.flicket_admin.models.flicket_config import FlicketConfig
from application.flicket.models.flicket_mode... | evereux/flicket | setup.py | Python | mit | 10,056 |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Tests for Jinja2 filters."""
from __future__ import absolute_import, print_functi... | tiborsimko/invenio-formatter | tests/test_filters.py | Python | mit | 2,728 |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Contains the Document class representing an object / record
"""
_toc = ["webnotes.model.doc.Document"]
import webnotes
import webnotes.model.meta
import MySQLdb
from webnotes.utils impo... | gangadhar-kadam/sapphite_lib | webnotes/model/doc.py | Python | mit | 20,173 |
from __future__ import absolute_import
try:
import configparser
except:
import ConfigParser as configparser
class _NotSet(object):
pass
class ConfigException(Exception):
pass
class Config:
def __init__(self, conffile):
self.conffile = conffile
self.conf = configparser.ConfigP... | kostya0shift/SyncToGit | synctogit/Config.py | Python | mit | 1,728 |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from projects import views
urlpatterns = [
url(r'^$', views.MainPageView.as_view(), name='main'),
# Inlist
url(r'^inlist/$', views.InlistView.as_view(), name='inlist'),
url(r'^inlist/(?P<pk>[0-9]+)/delete/$', views.InlistItemDelete.as_view(),
... | XeryusTC/projman | projects/urls.py | Python | mit | 1,477 |
"""
This is an example automated test to help you learn Qxf2's framework
Our automated test will do the following action repeatedly to fill number of forms:
#Open Qxf2 selenium-tutorial-main page.
#Fill the example form
#Click on Click me! button and check if its working fine
"""
#The import statements impo... | qxf2/qxf2-page-object-model | tests/test_successive_form_creation.py | Python | mit | 6,309 |
"""Custom ``checkout`` app."""
from oscar.apps.checkout.app import CheckoutApplication
from oscar_custom.checkout import views
class OverriddenCheckoutApplication(CheckoutApplication):
# Specify new view for payment details
payment_details_view = views.PaymentDetailsView
application = OverriddenCheckoutApp... | bitmazk/django-oscar-asiapay | oscar_integration_example/checkout/app.py | Python | mit | 331 |
"""Add TagAlias table
Revision ID: 9a0f78ff57d6
Revises: d19881f4c045
Create Date: 2017-03-19 15:34:30.271997
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9a0f78ff57d6'
down_revision = 'd19881f4c045'
branch_labels = None
depends_on = None
def upgrade():
... | MJB47/Jokusoramame | migrations/versions/9a0f78ff57d6_add_tagalias_table.py | Python | mit | 1,126 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('mirrors', '0003_componentrevision_version'),
]
operations = [
migrations.AlterField(
model_name='componentrevisi... | motherjones/mirrors | mirrors/migrations/0004_auto_20140609_1943.py | Python | mit | 444 |
from .. import db
class ApiParameterLink(db.Model):
__tablename__ = 'api_parameter_link'
api_id = db.Column(db.Integer, db.ForeignKey('apis.id'), primary_key=True)
parameter_id = db.Column(db.Integer, db.ForeignKey('parameters.id'), primary_key=True)
parameter_description = db.Column(db.String(128))
... | hack4impact/legal-checkup | app/models/api.py | Python | mit | 2,549 |
import os
import ConfigParser
import Leap
from Leap import CircleGesture, SwipeGesture
class GestureListener(Leap.Listener):
def __init__(self):
super(GestureListener, self).__init__()
self.config = ConfigParser.ConfigParser()
self.gestures_stopped = {
"circleleft": 0,
... | dylian94/LeapGestureControl | GestureListener.py | Python | mit | 5,620 |