code stringlengths 6 947k | repo_name stringlengths 5 100 | path stringlengths 4 226 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k |
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsDefaultValue.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
... | pblottiere/QGIS | tests/src/python/test_qgsdefaultvalue.py | Python | gpl-2.0 | 1,300 |
"""Tests for the HomematicIP Cloud component."""
| fbradyirl/home-assistant | tests/components/homematicip_cloud/__init__.py | Python | apache-2.0 | 49 |
# Copyright (c) 2015 Cloudbase Solutions.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | Stavitsky/neutron | neutron/common/eventlet_utils.py | Python | apache-2.0 | 1,112 |
# $Id: 201_ice_mismatch_1.py 2392 2008-12-22 18:54:58Z bennylp $
import inc_sip as sip
import inc_sdp as sdp
sdp = \
"""
v=0
o=- 0 0 IN IP4 127.0.0.1
s=pjmedia
c=IN IP4 127.0.0.1
t=0 0
m=audio 4000 RTP/AVP 0 101
a=ice-ufrag:1234
a=ice-pwd:5678
a=rtpmap:0 PCMU/8000
a=sendrecv
a=rtpmap:101 telephone-event/8000
a=fmtp:10... | lxki/pjsip | tests/pjsua/scripts-sendto/201_ice_mismatch_1.py | Python | gpl-2.0 | 650 |
# -*- test-case-name: twisted.conch.test.test_recvline -*-
# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.conch.recvline} and fixtures for testing related
functionality.
"""
import sys, os
from twisted.conch.insults import insults
from twisted.conch import r... | sorenh/cc | vendor/Twisted-10.0.0/twisted/conch/test/test_recvline.py | Python | apache-2.0 | 21,585 |
'''Unittests for idlelib/SearchDialogBase.py
Coverage: 99%. The only thing not covered is inconsequential --
testing skipping of suite when self.needwrapbutton is false.
'''
import unittest
from test.support import requires
from tkinter import Tk, Toplevel, Frame, Label, BooleanVar, StringVar
from idlelib import Sear... | FireWRT/OpenWrt-Firefly-Libraries | staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python3.4/idlelib/idle_test/test_searchdialogbase.py | Python | gpl-2.0 | 5,860 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ... | hryamzik/ansible | lib/ansible/modules/utilities/logic/import_tasks.py | Python | gpl-3.0 | 1,471 |
from django.forms import HiddenInput
from .base import WidgetTest
class HiddenInputTest(WidgetTest):
widget = HiddenInput()
def test_render(self):
self.check_html(self.widget, 'email', '', html='<input type="hidden" name="email" />')
def test_use_required_attribute(self):
# Always False... | edmorley/django | tests/forms_tests/widget_tests/test_hiddeninput.py | Python | bsd-3-clause | 603 |
#!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from copy import deepcopy
import unittest
from host_file_system_provider import HostFileSystemProvider
from host_file_system_iterator ... | s20121035/rk3288_android5.1_repo | external/chromium_org/chrome/common/extensions/docs/server2/host_file_system_iterator_test.py | Python | gpl-3.0 | 8,159 |
#
# Copyright (C) 2012-2013 The Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
import codecs
from collections import deque
import contextlib
import csv
from glob import iglob as std_iglob
import io
import json
import logging
import os
import py_compile
import re
import shutil
import socket
import... | piyush82/icclab-rcb-web | virtualenv/lib/python2.7/site-packages/pip/vendor/distlib/util.py | Python | apache-2.0 | 42,456 |
from functools import wraps
from urllib.parse import urlparse
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.exceptions import PermissionDenied
from django.shortcuts import resolve_url
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_... | sametmax/Django--an-app-at-a-time | ignore_this_directory/django/contrib/auth/decorators.py | Python | mit | 2,892 |
#!/usr/bin/env python
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies actions which are not depended on by other targets get executed.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('b... | ibc/MediaSoup | worker/deps/gyp/test/actions-bare/gyptest-bare.py | Python | isc | 558 |
#!/usr/bin/python
"""
requires tlslite - http://trevp.net/tlslite/
"""
import binascii
try:
from gdata.tlslite.utils import keyfactory
except ImportError:
from tlslite.tlslite.utils import keyfactory
try:
from gdata.tlslite.utils import cryptomath
except ImportError:
from tlslite.tlslite.utils import crypto... | boxed/CMi | web_frontend/gdata/oauth/rsa.py | Python | mit | 4,676 |
from __future__ import absolute_import, unicode_literals
from django.utils.encoding import force_str
from django.utils import six
from django.utils.six.moves import http_cookies
# Some versions of Python 2.7 and later won't need this encoding bug fix:
_cookie_encodes_correctly = http_cookies.SimpleCookie().value_enc... | edisonlz/fruit | web_project/base/site-packages/django/http/cookie.py | Python | apache-2.0 | 3,531 |
#! /usr/bin/env python
from __future__ import division, absolute_import, print_function
# System imports
from distutils.util import get_platform
import os
import sys
import unittest
# Import NumPy
import numpy as np
major, minor = [ int(d) for d in np.__version__.split(".")[:2] ]
if major == 0: BadListError = TypeE... | ddasilva/numpy | tools/swig/test/testFarray.py | Python | bsd-3-clause | 5,156 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | jmesteve/saas3 | openerp/addons/auth_crypt/__openerp__.py | Python | agpl-3.0 | 1,628 |
#!/usr/bin/env python
import re, string, sys, os, time, math
DEBUG = 0
(tp, exp) = ('compile', 'exec')
def parse(file):
f = open(file, 'r')
d = f.read()
# Cleanup weird stuff
d = re.sub(r',\d+:\d', '', d)
r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d)
test = {}
fname = ''
... | dslab-epfl/asap | utils/release/findRegressions-simple.py | Python | bsd-2-clause | 4,045 |
import os
import sys
import random
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(__file__, "../..")))
import base_test
repo_root = os.path.abspath(os.path.join(__file__, "../../.."))
sys.path.insert(1, os.path.join(repo_root, "tools", "webdriver"))
from webdriver import exceptions
class SendKeysTe... | youtube/cobalt | third_party/web_platform_tests/webdriver/user_input/sendkeys_test.py | Python | bsd-3-clause | 3,188 |
"""Core models."""
import re
from email.header import Header
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils.encoding import force_str, smart_bytes, smart_text
from django.utils.functional import cached_property
from django.utils.translation import ugett... | modoboa/modoboa | modoboa/core/models.py | Python | isc | 15,574 |
"""Admin API urls."""
from rest_framework import routers
from . import viewsets
router = routers.SimpleRouter()
router.register(r"domains", viewsets.DomainViewSet, basename="domain")
router.register(
r"domainaliases", viewsets.DomainAliasViewSet, basename="domain_alias")
router.register(r"accounts", viewsets.Acc... | modoboa/modoboa | modoboa/admin/api/v1/urls.py | Python | isc | 548 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
sipptam.conf.Schema
~~~~~~~~~~~~~~~~~~~
Contains a basic XML schema to parse the input configuration file.
:copyright: (c) 2013 by luismartingil.
:license: See LICENSE_FILE.
"""
import StringIO
schema = StringIO.StringIO('''\
<?xml version="1.0" enco... | halitalptekin/sipptam | src/sipptam/validate/Schema.py | Python | isc | 4,705 |
import wx
import os.path
class MainWindow( wx.Frame ):
def __init__( self, filename = '*.txt' ):
super( MainWindow, self ).__init__( None, size = ( 800,640 ) )
self.filename = filename
self.dirname = '.'
self.panel = wx.Panel( self, -1 )
self.CreateInteriorWindowComponents... | mpjoseca/ate | src/editor.py | Python | isc | 5,579 |
# -*- coding: utf-8 -*-
#
# sanpera documentation build configuration file, created by
# sphinx-quickstart2 on Sat May 12 21:24:07 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | eevee/sanpera | doc/conf.py | Python | isc | 7,742 |
from django.urls import reverse_lazy
from modoboa.lib.tests import ModoTestCase
class OpenAPITestCase(ModoTestCase):
openapi_schema_url = reverse_lazy('schema-v1-legacy')
def test_unauthorized(self):
self.client.logout()
response = self.client.get(self.openapi_schema_url)
self.asser... | modoboa/modoboa | modoboa/core/api/v1/tests.py | Python | isc | 699 |
"""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/je_os_segmentandintegrate_smartsigma_dropout.py | Python | mit | 12,565 |
# -*- coding: utf-8 -*-
# Given an unsorted integer array, find the first missing positive integer.
#
# For example,
# Given [1,2,0] return 3,
# and [3,4,-1,1] return 2.
# [1,3,4,2,5,8,9,7]
# Your algorithm should run in O(n) time and uses constant space.
# 根据题目来看, find the first minimum missing positive integer, 所以一定... | ddu7/PyLC | 041First Missing Positive.py | Python | mit | 1,058 |
# Copyright (c) 2014 by pyramid_decoy authors and contributors
# <see AUTHORS file>
#
# This module is part of pyramid_decoy and is released under
# the MIT License (MIT): http://opensource.org/licenses/MIT
"""Main decoy module."""
__version__ = "0.2.0"
SETTINGS_PREFIX = "decoy"
def includeme(configurator):
"""... | fizyk/pyramid_decoy | src/pyramid_decoy/__init__.py | Python | mit | 1,031 |
"""
Assumptions:
* Revisions appear ordered by page ASC, timestamp ASC, rev_id ASC
* The max(rev_id) and max(timestamp) of revisions represents the last revision
chronologically captured by the dump
"""
import logging
import traceback
from mw.xml_dump import Iterator, map, open_file
from ..errors import Revision... | halfak/Difference-Engine | diffengine/synchronizers/xml_dump.py | Python | mit | 5,555 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Zappa CLI
Deploy arbitrary Python programs as serverless Zappa applications.
"""
from __future__ import unicode_literals
from __future__ import division
import argcomplete
import argparse
import base64
import pkgutil
import botocore
import click
import collections... | parroyo/Zappa | zappa/cli.py | Python | mit | 87,982 |
# coding=utf-8
"""
Bridges calls made inside of a Python environment to the Cmd2 host app
while maintaining a reasonable degree of isolation between the two.
"""
import sys
from contextlib import (
redirect_stderr,
redirect_stdout,
)
from typing import (
IO,
TYPE_CHECKING,
Any,
List,
NamedT... | python-cmd2/cmd2 | cmd2/py_bridge.py | Python | mit | 4,605 |
"""Graphical user interface."""
import collections
import ctypes
import sdl2
import hienoi.renderer
from hienoi._common import GLProfile, GraphicsAPI, ParticleDisplay, UserData
from hienoi._vectors import Vector2i, Vector2f, Vector4f
class NavigationAction(object):
"""Enumerator for the current nagivation acti... | christophercrouzet/hienoi | hienoi/gui.py | Python | mit | 20,220 |
# coding: utf-8
from leancloud import Object
from leancloud import Query
from leancloud import LeanCloudError
from flask import Blueprint
from flask import request
from flask import redirect
from flask import url_for
from flask import render_template
import sys
sys.path.insert(0,'../')
from utils import JsonDict
import... | zhangw/leancloud_apperance_app | views/weibos.py | Python | mit | 1,920 |
from selenium.webdriver.support.select import Select
def get_selected_option(browser, css_selector):
# Takes a css selector for a <select> element and returns the value of
# the selected option
select = Select(browser.find_element_by_css_selector(css_selector))
return select.first_selected_option.get_a... | egineering-llc/egat_example_project | tests/test_helpers/selenium_helper.py | Python | mit | 338 |
#! python
# Python Serial Port Extension for Win32, Linux, BSD, Jython
# serial driver for win32
# see __init__.py
#
# (C) 2001-2015 Chris Liechti <cliechti@gmx.net>
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Initial patch to use ctypes by Giovanni Bajo <rasky@develer.com>
import ctypes
import time
from serial i... | martinohanlon/microbit-micropython | examples/mcfly/serial/serialwin32.py | Python | mit | 18,300 |
# -*- coding: utf-8 -*-
from IPython.core.display import Javascript, HTML, display_javascript, display_html
def setup_notebook():
# assign text/x-c++src MIME type to pybind11 cells
code = """
require(['notebook/js/codecell'], function(cc) {
cc.CodeCell.options_default.highlight_modes['magic_text/... | aldanor/ipybind | ipybind/notebook.py | Python | mit | 661 |
import os
import shutil
import tempfile
import numpy as np
import pytest
import torch
from spotlight.cross_validation import random_train_test_split
from spotlight.datasets import movielens
from spotlight.evaluation import mrr_score, sequence_mrr_score
from spotlight.evaluation import rmse_score
from spotlight.factor... | maciejkula/spotlight | tests/test_serialization.py | Python | mit | 3,374 |
import theano, theano.tensor as T
import numpy as np
import pandas as pd
import lasagne
"""
note: we are following the sklearn api for metrics/loss functions,
where the first arg for a function is y true, and second value is
y predicted. this is the opposite of the theano functions, so just
keep in mind.
"""
#copy ... | jonathanstrong/tmetrics | tmetrics/classification.py | Python | mit | 14,853 |
import os
import unittest
import numpy as np
from tfsnippet.examples.utils import MLResults
from tfsnippet.utils import TemporaryDirectory
def head_of_file(path, n):
with open(path, 'rb') as f:
return f.read(n)
class MLResultTestCase(unittest.TestCase):
def test_imwrite(self):
with Tempor... | korepwx/tfsnippet | tests/examples/utils/test_mlresult.py | Python | mit | 1,216 |
import logging
import requests
HUE_IP = '192.168.86.32'
HUE_USERNAME = '7KcxItfntdF0DuWV9t0GPMeToEBlvHTgqWNZqxu6'
logger = logging.getLogger('hue')
def getLights():
url = 'http://{0}/api/{1}/lights'.format(HUE_IP, HUE_USERNAME)
try:
r = requests.get(url)
except:
logger.error('Failed getting stat... | twotymz/lucy | hue/lights.py | Python | mit | 705 |
import re
import braintree
from braintree.address import Address
from braintree.error_result import ErrorResult
from braintree.exceptions.not_found_error import NotFoundError
from braintree.resource import Resource
from braintree.successful_result import SuccessfulResult
class AddressGateway(object):
def __init__(... | eldarion/braintree_python | braintree/address_gateway.py | Python | mit | 2,190 |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | kitaro-tn/msgiver | _docs/conf.py | Python | mit | 4,844 |
# -*- coding: utf-8 -*-
from anima.render.arnold import base85
import unittest
import struct
class Base85TestCase(unittest.TestCase):
"""tests the base85 module
"""
def setup(self):
"""setup the test
"""
pass
def test_arnold_b85_encode_is_working_properly(self):
"""t... | eoyilmaz/anima | tests/arnold/test_base85.py | Python | mit | 5,868 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-04-15 18:42
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | djstein/hci_final | hci/rockclimb/migrations/0001_initial.py | Python | mit | 1,801 |
#!/usr/bin/python
import os
import sys
import zlib
import time
import datetime
import base64
from socket import *
from impacket import ImpactPacket
""" Constants """
READ_BINARY = "rb"
WRITE_BINARY = "wb"
READ_FROM_SOCK = 7000
ICMP_HEADER_SIZE = 27
DATA_SEPARATOR = "::"
DATA_TERMINATOR = "\x12\x13\x... | ytisf/PyExfil | pyexfil/network/ICMP/icmp_exfiltration.py | Python | mit | 6,676 |
from django.http import StreamingHttpResponse, HttpResponseServerError
from download_service.zipbuilder import DDSZipBuilder, NotFoundException, NotSupportedException
from django.contrib.auth.decorators import login_required
from download_service.utils import make_client
from django.http import Http404
@login_require... | Duke-GCB/DukeDSHandoverService | download_service/views.py | Python | mit | 899 |
from celery.schedules import crontab
import djcelery
from django.conf.global_settings import EMAIL_BACKEND
import os, sys, logging
import subprocess
###############################
# MISC #
##############################
ROOT_PATH = os.path.dirname(__file__)
def to_absolute_path(path):
re... | jumoconnect/openjumo | jumodjango/settings.py | Python | mit | 8,951 |
# -*- coding:utf8 -*-
# File : tfutils.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 1/31/17
#
# This file is part of TensorArtist.
import re
import tensorflow as tf
class TArtGraphKeys:
PLACEHOLDERS = 'placeholders'
TART_VARIABLES = 'tart_variables'
INFERENCE_SUMMARIES = 'infer... | vacancy/TensorArtist | tartist/nn/tfutils.py | Python | mit | 2,691 |
import sys
import py, pytest
import _pytest.assertion as plugin
from _pytest.assertion import reinterpret, util
needsnewassert = pytest.mark.skipif("sys.version_info < (2,6)")
@pytest.fixture
def mock_config():
class Config(object):
verbose = False
def getoption(self, name):
if name =... | geraldoandradee/pytest | testing/test_assertion.py | Python | mit | 11,084 |
# -*- coding: utf-8 -*-
from tests import base
from app import pivocram
class PivocramConnetcTest(base.TestCase):
def setUp(self):
self.connect = pivocram.Connect('PIVOTAL_TEST_TOKEN')
def test_should_have_the_pivotal_api_url(self):
self.connect.PIVOTAL_URL.should.be.equal('https://www.pivota... | Maethorin/pivocram | tests/unit/test_pivocram.py | Python | mit | 8,498 |
"""
Django settings for TaskTracker project.
Generated by 'django-admin startproject' using Django 1.9.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import o... | polarkac/TaskTracker | TaskTracker/settings.py | Python | mit | 3,566 |
from typing import Dict, Any
from depccg.tree import Tree
from depccg.cat import Category
def _json_of_category(category: Category) -> Dict[str, Any]:
def rec(node):
if node.is_functor:
return {
'slash': node.slash,
'left': rec(node.left),
'righ... | masashi-y/depccg | depccg/printer/my_json.py | Python | mit | 1,555 |
"""
WSGI config for genoome project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` ... | jiivan/genoomy | genoome/genoome/wsgi.py | Python | mit | 1,563 |
#! python3
"""Remove CSV header
Removes the header from all CSV files in the current working directory.
Note:
Outputs to ``./headerRemoved`` directory.
"""
def main():
import csv, os
os.makedirs('headerRemoved', exist_ok=True)
# Loop through every file in the current working directory.
for cs... | JoseALermaIII/python-tutorials | pythontutorials/books/AutomateTheBoringStuff/Ch14/P3_removeCsvHeader.py | Python | mit | 1,125 |
# -*- coding: utf-8 -*-
from redmine import Redmine
from feedbacks import settings
from base import IBackend
class RedmineBackend(IBackend):
def __init__(self):
self.redmine = Redmine(settings.DJFEEDBACK_REDMINE_URL,
key=settings.DJFEEDBACK_REDMINE_KEY)
self.projec... | mpyatishev/djfeedback | feedbacks/backends/redmine_backend.py | Python | mit | 1,037 |
# -*- coding: UTF-8 -*-
from django.core.management.base import BaseCommand
from optparse import make_option
import daemon
import daemon.pidfile
from signal import SIGTSTP, SIGTERM, SIGABRT
import sys, os, subprocess
import time
from jukebox.jukebox_core import api
class Command(BaseCommand):
daemon = None
pr... | lociii/jukebox_mpg123 | jukebox_mpg123/management/commands/jukebox_mpg123.py | Python | mit | 3,441 |
# Przykladowy agent do zadania 'zagubiony Wumpus'. Agent porusza sie wezykiem.
import random
from action import Action
# nie zmieniac nazwy klasy
class Agent:
# nie zmieniac naglowka konstruktora, tutaj agent dostaje wszystkie informacje o srodowisku
def __init__(self, p, pj, pn, height, width, areaMap):
... | uHappyLogic/lost-wumpus | agents/snake_agent.py | Python | mit | 1,993 |
#!/usr/bin/python
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
import datetime
from participantCollection import ParticipantCollection
# Edit Me!
participantFileNames = ['../stayclean-2014-november/participants.txt',
'../stayclean-2014-december/partic... | foobarbazblarg/stayclean | stayclean-2016-august/update-google-chart.py | Python | mit | 5,485 |
import pretend
import pytest
from botocore.exceptions import ClientError
from configstore.backends.awsssm import AwsSsmBackend
def test_awsssm_init_bad_install(monkeypatch):
monkeypatch.setattr('configstore.backends.awsssm.boto3', None)
with pytest.raises(ImportError):
AwsSsmBackend()
def test_aw... | caravancoop/configstore | tests/test_awsssm.py | Python | mit | 3,127 |
import sys
import traceback
import unittest
import unittest.mock
import rail
class TestIdentity(unittest.TestCase):
def test_returns_input_value(self):
value = unittest.mock.Mock()
self.assertEqual(value, rail.identity(value))
class TestNot(unittest.TestCase):
def test_returns_inverse_for_b... | rob-earwaker/rail | test_rail.py | Python | mit | 23,712 |
"""
thisplace: Human-readable addresses for every 3x3m square on the earth's surface.
The simplest way to use this module are the `four_words` and `decode`
functions. For more see `WordHasher`.
"""
import random
import geohash
def get_words(fname):
lines = open(fname)
words = []
for word in lines:
... | Placeware/ThisPlace | thisplace.py | Python | mit | 8,967 |
#!/usr/bin/env python3
# vim: tw=76
import kxg
import random
import pyglet
LOWER_BOUND, UPPER_BOUND = 0, 5000
class World(kxg.World):
"""
Keep track of the secret number, the range of numbers that haven't been
eliminated yet, and the winner (if there is one).
"""
def __init__(self):
sup... | kxgames/kxg | demos/guess_my_number.py | Python | mit | 5,672 |
#!/usr/bin/env python3
# Copyright (C) 2017-2021 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except... | fametrano/BitcoinBlockchainTechnology | tests/test_hashes.py | Python | mit | 1,276 |
from django.conf.urls import include, url
from django.contrib import admin
from Poller import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='resu... | zzeleznick/zDjango | Poller/urls.py | Python | mit | 396 |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import os
import marshal
import cPickle
import array
class HuffmanNode(object):
recurPrint = False
def __init__(self, ch=None, fq=None, lnode=None, rnode=None, parent=None):
self.L = lnode
self.R = rnode
self.p = parent
self.c = ch
... | fepe55/RAMB0 | python/huffman2.py | Python | mit | 6,447 |
#!/usr/bin/env python
#
# Generate pnSeed[] from Pieter's DNS seeder
#
NSEEDS=600
import re
import sys
from subprocess import check_output
def main():
lines = sys.stdin.readlines()
ips = []
pattern = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):11000")
for line in lines:
m = patt... | prolifik/Furrycoin | contrib/seeds/makeseeds.py | Python | mit | 709 |
# Source:https://github.com/FastLED/FastLED/blob/master/examples/Fire2012WithPalette/Fire2012WithPalette.ino
from __future__ import division
import math
import random
from colour import Color
#import randomcolor
from PIL import Image, ImageChops, ImageDraw, ImageFont
from components import App
def hex... | mattgrogan/ledmatrix | ledmatrix/pattern/fire.py | Python | mit | 3,096 |
from django.db import models
from django.contrib.auth.models import User
class StockStatus(models.Model):
date = models.DateTimeField(auto_now_add=True)
price = models.FloatField()
change = models.FloatField()
volume = models.IntegerField()
average_daily_volume = models.IntegerField()
market_ca... | jwilson780/VirtualStockMarket | stockmarket/models.py | Python | mit | 2,038 |
# TODO WIP this is meant to find discrepencies between the stack templates that
# are deployed to CloudFormation and what is checked in, and do some other
# basic sanity checks on the stacks and their configurations
import boto3
import re
cloudformation = boto3.client("cloudformation")
stacks = cloudformation.descri... | PRX/Infrastructure | bin/continuity.py | Python | mit | 2,044 |
import numpy as np
from . import finiteelements as fe
from . import matrices
from math import cos
class Result:
def __init__(self):
pass
def __init__(self, freq, u1, u2, u3, mesh, geometry):
self.freq = freq
self.u1 = u1
self.u2 = u2
self.u3 = u3
self.mesh ... | tarashor/vibrations | py/fem/result.py | Python | mit | 2,014 |
""" Define a Check monad and corresponding functions.
"""
from functools import (reduce, partial)
class Check:
""" This super class is not really necessary but helps make the structure
clear.
data Check a = Pass a | Fail Message
"""
pass
class Pass(Check):
def __init__(self, value):... | kdungs/python-mcheck | mcheck/__init__.py | Python | mit | 1,840 |
"""
Revision ID: 0146_add_service_callback_api
Revises: 0145_add_notification_reply_to
Create Date: 2017-11-28 15:13:48.730554
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision = '0146_add_service_callback_api'
down_revision = '0145_add_notification_reply_to'
de... | alphagov/notifications-api | migrations/versions/0146_add_service_callback_api.py | Python | mit | 2,779 |
"""
Author: Maneesh Divana <mdaneeshd77@gmail.com>
Interpreter: Python 3.6.8
Quick Sort
Worst Case: O(n^2)
Average Case: O(nlog n)
Best Case: O(nlog n)
"""
from random import shuffle
def partition(arr: list, left: int, right: int) -> int:
"""Partitions the given array based on a pivot element,
then sorts the... | maneeshd/Algorithms-and-Data-Structures | algorithms/QuickSort.py | Python | mit | 1,581 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
import re
class AboutRegex(Koan):
"""
These koans are based on the Ben's book: Regular Expressions in 10 minutes.
I found this books very useful so I decided to write a koans in order to practice everything I had learned from i... | taw/python_koans | python3/koans/about_regex.py | Python | mit | 4,842 |
from django.db.models import CharField
DEFALT_PROTOCOLS = ('http', 'https', 'mailto', 'tel')
class HrefField(CharField):
def __init__(
self,
protocols=DEFALT_PROTOCOLS,
allow_paths=True,
allow_fragments=True,
allow_query_strings=True,
max_... | adamalton/django-href-field | hreffield/fields.py | Python | mit | 657 |
import json
from collections import OrderedDict
import numpy as np
import matplotlib.pyplot as plt
with open('data/EURUSD3600.json') as f:
data = json.loads(f.read())
data = OrderedDict(sorted(data.items()))
for i, v in data.iteritems():
print 'timestamp', i
print v['rate']
points = OrderedDict(sort... | Tjorriemorrie/trading | 04_oanda/viz.py | Python | mit | 463 |
'''
Created on Mar 28, 2016
@author: Ziv
'''
class MyClass(object):
'''
classdocs
'''
def __init__(self, params):
'''
Constructor
'''
import sys
import os
from getArgs import getParams
from parse import parse
__all__ = []
__version__ = 0.1
__date__ = '2015-05-24'
__... | ziv17/SRT-tools | srtFix/src/srtFix/processFile.py | Python | mit | 3,797 |
#!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Copyright (c) 2016 The Bitcoin Unlimited developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import *
from test_fram... | marlengit/BitcoinUnlimited | qa/rpc-tests/p2p-versionbits-warning.py | Python | mit | 6,299 |
from rest_framework import serializers
from rest_framework import pagination
from .models import Airport
class AirportSerializer(serializers.ModelSerializer):
read_only_fields = ('id','name','city','country','country_code','iata','icao')
class Meta:
model = Airport
class PaginationAirpor... | illing2005/django-airports-apis | airports/serializers.py | Python | mit | 433 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.nic.sn/status_registered
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import parse ... | huyphan/pyyawhois | test/record/parser/test_response_whois_nic_sn_status_registered.py | Python | mit | 3,849 |
# 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/v2018_03_01/aio/operations/_action_groups_operations.py | Python | mit | 24,867 |
from database import init_db
from flask import Flask
from flask_graphql import GraphQLView
from schema import schema
app = Flask(__name__)
app.debug = True
default_query = '''
{
allEmployees {
edges {
node {
id,
name,
department {
id,
name
},
rol... | yfilali/graphql-pynamodb | examples/flask_pynamodb/app.py | Python | mit | 552 |
from .features import Dictionary, RegexMatches, Stemmed, Stopwords
name = "dutch"
try:
import enchant
dictionary = enchant.Dict("nl")
except enchant.errors.DictNotFoundError:
raise ImportError("No enchant-compatible dictionary found for 'nl'. " +
"Consider installing 'myspell-nl'.")... | yafeunteun/wikipedia-spam-classifier | revscoring/revscoring/languages/dutch.py | Python | mit | 3,534 |
# -*- coding: utf-8 -*-
# Copyright 2015-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
from carepoint import Carepoint
from sqlalchemy import (Column,
Integer,
Boolean,
ForeignKey,
)
class FdbPem... | laslabs/Python-Carepoint | carepoint/models/cph/fdb_pem_mogc.py | Python | mit | 643 |
from .sanic import Sanic
from .blueprints import Blueprint
__version__ = '0.1.9'
__all__ = ['Sanic', 'Blueprint']
| hhstore/flask-annotated | sanic/sanic-0.1.9/sanic/__init__.py | Python | mit | 116 |
# code adapted from lasagne tutorial
# http://lasagne.readthedocs.org/en/latest/user/tutorial.html
import time
import os
from itertools import product
import numpy as np
from sklearn.cross_validation import KFold
import theano
from theano import tensor as T
import lasagne
from params import nnet_params_dict, feats_tra... | rafaelvalle/MDI | nnet_lasagne.py | Python | mit | 10,609 |
import os
import types
import binascii
from django.db import models
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import cached_property
try:
from django.utils.encoding import smart_text
except ImportError:
from django.utils.encoding impo... | gerhc/django-encrypted-fields | encrypted_fields/fields.py | Python | mit | 9,173 |
#-*- coding:utf8 -*-
def crawl_folder(folder):
import os
os_objects = []
seen = set([folder])
for os_object_name in os.listdir(folder):
full_path = os.path.normpath(os.path.join(folder, os_object_name))
if not full_path in seen:
os_objects.append((full_path, os_object_name... | mavlyutovrus/light_search | lib/utils.py | Python | mit | 1,167 |
import io
from pytest import fixture
class _FakeOutputFile(io.StringIO):
def close(self):
self.contents = self.getvalue()
super().close()
@fixture
def fake_output_file():
return _FakeOutputFile()
type_example_values = {
"none": (None,),
"callable": (lambda: None,),
"bool": (T... | nre/Doxhooks | tests/unit_tests/conftest.py | Python | mit | 1,575 |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.absp... | Perlkonig/sqrlserver-python | setup.py | Python | mit | 4,350 |
# -*- coding: utf-8 -*-
"""Regression tests."""
from __future__ import print_function
from __future__ import unicode_literals
from tabulate import tabulate, _text_type, _long_type, TableFormat, Line, DataRow
from common import assert_equal, assert_in, skip
def test_ansi_color_in_table_cells():
"Regression: ANSI... | astanin/python-tabulate | test/test_regression.py | Python | mit | 16,317 |
import json
with open("birthdays.json", "r") as damnJson:
birthDays = json.load(damnJson)
print("We know the birth days of: ")
for i in birthDays:
print(i)
print("\nWould you like to add or retrieve a birth day?")
lol = input().strip().lower()
if lol == "add":
person = input("Who's the lucky one? ")
date = input... | daniLOLZ/variaRoba | Python/34.py | Python | mit | 633 |
"""
Tests whether we can compute a consistent gradient of some functional
based on the forward model with respect to the bottom friction
via firedrake_adjoint.
Stephan Kramer 25-05-16
"""
import pytest
from thetis import *
from firedrake_adjoint import *
op2.init(log_level=INFO)
velocity_u = 2.0
def basic_setup():
... | tkarna/cofs | test_adjoint/test_swe_adjoint.py | Python | mit | 3,627 |
import codecs
import os
import re
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
here = os.path.abspath(os.path.dirname(__file__))
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test... | Ivoz/pip | setup.py | Python | mit | 2,816 |
from .context import CorpusContext
from .audio import AudioContext
from .importable import ImportContext
from .lexical import LexicalContext
from .pause import PauseContext
from .utterance import UtteranceContext
from .structured import StructuredContext
from .syllabic import SyllabicContext
from .spoken import Spoken... | samihuc/PolyglotDB | polyglotdb/corpus/__init__.py | Python | mit | 328 |
#!/usr/local/bin/python3
# STL imports
import datetime
import json
import logging
import pprint
# Package imports
import dateutil.parser
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (relationship, scoped_session, sessionmaker,
validate... | olety/FBD | fbd/storage.py | Python | mit | 19,799 |
from django.http import HttpResponse
from django.views.generic import TemplateView, DetailView
from django.views.generic.edit import FormView
from .forms import DonationForm
from .models import CardType
import json
class PagoView(FormView):
form_class = DonationForm
template_name = 'pago.html'
success_url... | FUNSEPA/fsp-paypal | pagos/views.py | Python | mit | 1,361 |
# -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from ade25.assetmanager.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of ade25.assetmanager into Plone."""
def setUp(self):
"""Custom shared utility setup ... | ade25/ade25.assetmanager | ade25/assetmanager/tests/test_setup.py | Python | mit | 1,209 |
#!/usr/bin/env python
# https://medium.com/@mshockwave/using-llvm-lit-out-of-tree-5cddada85a78
# To run lit-based test suite:
# cd xyz/qmlcore/test && ./lit.py -va .
from lit.main import main
import os
if __name__ == '__main__':
if not os.path.exists(".cache/core.Item"):
print("Note that first run may t... | pureqml/qmlcore | test/lit.py | Python | mit | 381 |
s = input().rstrip()
print(s[:4],s[4:])
| utgw/programming-contest | codefestival/2016/qualA/a.py | Python | mit | 40 |
import math
import unicodedata as uda
from binascii import unhexlify, hexlify
from torba.rpc.jsonrpc import RPCError
from torba.server.hash import hash_to_hex_str
from torba.server.session import ElectrumX
from torba.server import util
from lbry.schema.result import Outputs
from lbry.schema.url import URL
from lbry.w... | lbryio/lbry | lbry/lbry/wallet/server/session.py | Python | mit | 16,685 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.