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 |
|---|---|---|---|---|---|
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Serial Port Protocol
"""
# system imports
import os, sys
# all of them require pyserial at the moment, so check that first
import serial
from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD
from serial import STOPBITS_ONE, STOP... | sorenh/cc | vendor/Twisted-10.0.0/twisted/internet/serialport.py | Python | apache-2.0 | 1,601 |
# Copyright (c) 2012 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.
"""A bare-bones test server for testing cloud policy support.
This implements a simple cloud policy test server that can be used to test
chrome's device... | aospx-kitkat/platform_external_chromium_org | chrome/browser/policy/test/policy_testserver.py | Python | bsd-3-clause | 35,010 |
# This code is supporting material for the book
# Building Machine Learning Systems with Python
# by Willi Richert and Luis Pedro Coelho
# published by PACKT Publishing
#
# It is made available under the MIT License
import sys
import os
import glob
import numpy as np
import scipy
import scipy.io.wavfile
from utils i... | kpespinosa/BuildingMachineLearningSystemsWithPython | ch09/fft.py | Python | mit | 3,673 |
"""Tests for cached authentication middleware."""
import unittest
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from mock import patch
from student.tests.factories import UserFactory
class CachedAuthMiddlewa... | synergeticsedx/deployment-wipro | openedx/core/djangoapps/cache_toolbox/tests/test_middleware.py | Python | agpl-3.0 | 1,973 |
# Copyright (c) 2012 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.
_API_UTIL_NAMESPACE = 'json_schema_compiler::util'
class UtilCCHelper(object):
"""A util class that generates code that uses
tools/json_schema_comp... | guorendong/iridium-browser-ubuntu | tools/json_schema_compiler/util_cc_helper.py | Python | bsd-3-clause | 1,498 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | bealdav/OpenUpgrade | addons/stock_account/wizard/__init__.py | Python | agpl-3.0 | 1,077 |
# Copyright 2009 Google Inc.
#
# 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 applicable law or agreed to in writing, ... | adam-pawluczuk/jaikuengine | common/messages.py | Python | apache-2.0 | 3,331 |
# coding: utf-8
"""
flask_wtf.csrf
~~~~~~~~~~~~~~
CSRF protection for Flask.
:copyright: (c) 2013 by Hsiaoming Yang.
"""
import os
import hmac
import hashlib
import time
from flask import Blueprint
from flask import current_app, session, request, abort
from werkzeug.security import safe_str_cmp
from ... | sunze/py_flask | venv/lib/python3.4/site-packages/flask_wtf/csrf.py | Python | mit | 7,823 |
#
# The Python Imaging Library
# $Id$
#
# bitmap distribution font (bdf) file parser
#
# history:
# 1996-05-16 fl created (as bdf2pil)
# 1997-08-25 fl converted to FontFile driver
# 2001-05-25 fl removed bogus __init__ call
# 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)
# 2003-04-22 fl ... | FreddieShoreditch/image_folder_organiser | venv/lib/python2.7/site-packages/PIL/BdfFontFile.py | Python | mit | 3,355 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | ovnicraft/openerp-restaurant | hr_evaluation/report/hr_evaluation_report.py | Python | agpl-3.0 | 4,676 |
'''
==================
RBF SVM parameters
==================
This example illustrates the effect of the parameters ``gamma`` and ``C`` of
the Radius Basis Function (RBF) kernel SVM.
Intuitively, the ``gamma`` parameter defines how far the influence of a single
training example reaches, with low values meaning 'far' a... | pv/scikit-learn | examples/svm/plot_rbf_parameters.py | Python | bsd-3-clause | 8,096 |
import os
from pprint import pprint
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.EXOSCALE)
driver = cls('api key', 'api secret key')
# Create a new key pair. Most providers will return generated private key in
# the response which can be acce... | dcorbacho/libcloud | docs/examples/compute/cloudstack/ssh_keypairs_management_exoscale.py | Python | apache-2.0 | 1,027 |
from ctypes import POINTER, c_char_p, c_int, c_size_t, c_ubyte
from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR, GEOSFuncFactory
from django.contrib.gis.geos.prototypes.errcheck import (
check_geom, check_minus_one, check_sized_string, check_string,
)
# This is the return type used by binary output (W... | sametmax/Django--an-app-at-a-time | ignore_this_directory/django/contrib/gis/geos/prototypes/geom.py | Python | mit | 3,565 |
# wireproto.py - generic wire protocol support functions
#
# Copyright 2005-2010 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
import urllib, tempfile, os, sys
from i18n import _
from node import b... | iaddict/mercurial.rb | vendor/mercurial/mercurial/wireproto.py | Python | mit | 22,044 |
"""Relay-Supplied Options"""
# pylint: disable=invalid-name,line-too-long
import pytest
import misc
import references
import srv_control
import srv_msg
@pytest.mark.v6
@pytest.mark.options
@pytest.mark.rsoo
def test_v6_options_rsoo_default_option():
misc.test_setup()
srv_control.config_srv_subnet('2001:db... | isc-projects/forge | tests/dhcpv6/options_validation/test_v6_rsoo.py | Python | isc | 7,036 |
"""Core views."""
from .admin import (
check_top_notifications, information, logs, logs_page, parameters,
viewsettings
)
from .auth import (
PasswordResetView, dologin, dologout, VerifySMSCodeView,
ResendSMSCodeView, TwoFactorCodeVerifyView
)
from .base import RootDispatchView
from .dashboard import Da... | modoboa/modoboa | modoboa/core/views/__init__.py | Python | isc | 801 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import wagtail.wagtailcore.fields
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('base', '0003_auto_20150122_2130'),
('home', '0003_homepagecarousel... | MidAtlanticPortal/marco-portal2 | marco/portal/home/migrations/0004_auto_20171118_0027.py | Python | isc | 872 |
#!/usr/local/bin/python3.7
# EASY-INSTALL-ENTRY-SCRIPT: 'jsonpath-rw==1.4.0','console_scripts','jsonpath.py'
__requires__ = 'jsonpath-rw==1.4.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(... | PaloAltoNetworks-BD/SplunkforPaloAltoNetworks | Splunk_TA_paloalto/bin/splunk_ta_paloalto/aob_py3/bin/jsonpath.py | Python | isc | 410 |
import sys
class PingdomEmailReport(object):
"""Class represening a pingdom email report
Attributes:
* id -- Subscription identifier
* name -- Subscription name
* checkid -- Check identifier for check subscriptions
* frequency -- Report frequency
* additionalemails --... | KennethWilke/PingdomLib | pingdomlib/reports.py | Python | isc | 3,335 |
import hashlib
import json
import os
import re
import string
import urllib.parse
from argparse import ArgumentParser
from collections import defaultdict
from contextlib import contextmanager
import psycopg2
import requests
from lacinizatar.lacinizatar import lacin
WIKIDATA_API_URL = 'https://www.wikidata.org/w/api.p... | opendataby/osm-streets | main.py | Python | mit | 33,614 |
# coding: utf-8
import os
from setuptools import setup
import urlify
setup(
name='urlify',
description='This library provides Django\'s urlify.js ' \
'functionality ported to Python.',
version=urlify.__version__,
license=urlify.__license__,
author=urlify.__author__,
url=urlify... | dreikanter/python-urlify | setup.py | Python | mit | 740 |
# coding=utf-8
"""
Collect metrics from postgresql
#### Dependencies
* psycopg2
"""
import diamond.collector
from diamond.collector import str_to_bool
try:
import psycopg2
import psycopg2.extras
psycopg2 # workaround for pyflakes issue #13
except ImportError:
psycopg2 = None
class PostgresqlCo... | datafiniti/Diamond | src/collectors/postgres/postgres.py | Python | mit | 15,406 |
from django.test.utils import override_settings
from django.urls import reverse
from rest_framework import status
from rest_framework import test
from waldur_core.core.tests.helpers import override_waldur_core_settings
from waldur_core.structure.images import dummy_image
from waldur_core.structure.models import Custom... | opennode/nodeconductor | waldur_core/structure/tests/test_upload.py | Python | mit | 2,935 |
raise NotImplementedError("ast is not yet implemented in Skulpt")
| ArcherSys/ArcherSys | skulpt/src/lib/ast.py | Python | mit | 66 |
"""This is a dummy module for the reflection test."""
from .reflection_test import ImportedClass # pylint: disable=unused-import
class DuplicateClass: # pylint: disable=missing-docstring
pass
| Cognexa/cxflow | cxflow/tests/utils/dummy_module.py | Python | mit | 200 |
#!/usr/bin/env python
# Copyright (c) 2014 The Flirtcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the listtransactions API
from test_framework import FlirtcoinTestFramework
from flirtcoinrpc.auth... | flirtcoin/flirtcoin | qa/rpc-tests/listtransactions.py | Python | mit | 4,725 |
#!/usr/bin/env python2.7
from common import *
from random import randint, choice
registers = {\
"a" : int("0000", 2),
"f" : int("0001", 2),
"b" : int("0010", 2),
"c" : int("0011", 2),
"d" : int("0100", 2),
"e" : int("0101", 2),
"h" : int("0110", 2),
"l" : int("0111", 2),
"af" : int("1000", 2),
"bc" : int("1001... | Wynjones1/gbvhdl | testing/tests/registers.py | Python | mit | 3,081 |
from spinn import util
from spinn.data.dual_arithmetic.base import FIXED_VOCABULARY
SENTENCE_PAIR_DATA = True
OUTPUTS = [True, False]
LABEL_MAP = {str(x): i for i, x in enumerate(OUTPUTS)}
def load_data(path, lowercase=None):
examples = []
with open(path) as f:
for pairID, line in enumerate(f):
... | nyu-mll/spinn | python/spinn/data/dual_arithmetic/load_eq_data.py | Python | mit | 1,053 |
"""
Django settings for picscope project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... | yeaske/picscope | picscope/settings.py | Python | mit | 1,978 |
#!/usr/bin/env python
#
#Copyright (C) 2011 by Venkata Pingali (pingali@gmail.com) & TCS
#
#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 ... | pingali/pyAadhaarAuth | AadhaarAuth/data.py | Python | mit | 24,954 |
#!/usr/bin/env python
# -*- coding: utf8 -*-
__author__ = "Laurent Faucheux <faucheux@centre-cired.fr>"
__all__ = ['cache']
class cache(object):
def __init__(self,*args,**kwargs):
""" Homemade cache class which aims at being inherited """
self._cache = {}
@c... | lfaucheux/PyENV | PyENV/tools.py | Python | mit | 585 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0022_bill_price_per_minute'),
]
operations = [
migrations.RemoveField(
model_name='widget',
... | vesellov/callfeed.net | mainapp/migrations/0023_auto_20150601_1935.py | Python | mit | 1,416 |
# code from: http://www.oschina.net/code/snippet_1245006_25187
# Collected by: Whale Chen
import urllib, urllib2
import json
class GeoCoding(object):
def __init__(self, key =' '):
# to set the return
#self.url_para = {'address':'', 'sensor': 'false', 'language': 'zh-CN'}
self.url_para ... | WhaleChen/OMOOC2py | 1sTry/mapData/getlatlng_s.py | Python | mit | 2,125 |
from __future__ import division
import nltk
import re
from load_utils import load_words, load_initial_ngrams, load_synonyms, load_anagrams, substring_words
from language_utils import semantic_similarity, legal_substrings, AnagramDict
FUNCTIONS = ['syn', 'null', 'sub', 'ana']
WORDS = load_words()
INITIAL_NGRAMS = loa... | rdeits/cryptics | Archive/solver.py | Python | mit | 4,697 |
from ga import Individual,GA
| lfzark/pygalib | pygalib/__init__.py | Python | mit | 32 |
def actual_power(a: int, b: int):
"""
Function using divide and conquer to calculate a^b.
It only works for integer a,b.
"""
if b == 0:
return 1
if (b % 2) == 0:
return actual_power(a, int(b / 2)) * actual_power(a, int(b / 2))
else:
return a * actual_power(a, int(b / ... | TheAlgorithms/Python | divide_and_conquer/power.py | Python | mit | 686 |
# -*- coding: utf-8 -*-
try:
import unittest2 as unittest
except ImportError:
import unittest
import os
from cnab240 import errors
from cnab240.bancos import santander
fro... | wpensar/cnab240 | tests/test_arquivo_santander.py | Python | mit | 1,601 |
#problem 59
def score(message):
total = 0
for c in message:
total += ord(c)
return total
def printMessage(array,key):
message = ''
for ascii in array:
message += chr(ascii)
if message.find("the") != -1 and message.find("this") != -1:
print message,key,score(message)
... | jhuang314/euler | p59.py | Python | mit | 895 |
from flask import Blueprint, request, send_file, jsonify
from app.mod_tools.api.helpers import *
import app.mod_tools.tools as tools
mod_tools = Blueprint("tools", __name__, url_prefix="/tools")
view_pool = {}
for module in getModule("./app/mod_tools/tools"):
functions = getFunctions(module)
for func... | vuquangtam/WebAPI-Flask | app/mod_tools/controllers.py | Python | mit | 694 |
import pytest
from ctx import Ctx
def test_lookup_error():
"""Should return LookupError if no attiibute or key is found"""
with pytest.raises(LookupError):
x = Ctx()
(x.no_key == 5)
with pytest.raises(LookupError):
x = Ctx()
(x['no_key'] == 5)
def test_attribute_error():... | figlief/ctx | test_ctx.py | Python | mit | 1,441 |
"""
views.py - (C) Copyright - 2017
This software is copyrighted to contributors listed in CONTRIBUTIONS.md.
SPDX-License-Identifier: MIT
Author(s) of this file:
J. Harding
Business logic for api endpoints.
"""
from django.db import models
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
fr... | jakeharding/repo-health | repo_health/gh_projects/views.py | Python | mit | 3,192 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'LogItem.serialized_data'
db.add_column('object_log_logitem', 'serialized_data', self.g... | osuosl/django_object_log | object_log/migrations/0002_version_0_6.py | Python | mit | 5,457 |
from . import fetcher, parser
from ..common import Params
def fetch(year, month, settings=None, post=None):
params = Params(year, month)
kwargs = {}
if settings is not None:
kwargs['settings'] = settings
if post is not None:
kwargs['post'] = post
return parser.parse(fetcher.fet... | playwhesmarter/playwhe | playwhe/client/__init__.py | Python | mit | 350 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is part of fake-painter, by Ilya Petrash
# and is licensed under the MIT license, under the terms listed within
# LICENSE which is included with the source of this package
__author__ = 'ipetrash'
from abstractinstrument import AbstractInstrument
from PySide... | gil9red/fake-painter | plugins/baseinstruments/eraserinstrument.py | Python | mit | 2,127 |
#!/usr/bin/env python3
import os
import subprocess
import sys
def get_group(group, local=False):
if local:
op = '-Q'
else:
op = '-S'
try:
with open(os.devnull, 'w') as f:
return set(
subprocess.check_output(
['pacman', op, '-qg', group],
stderr=f
).decode().... | botika/scripts | groupcheck.py | Python | mit | 671 |
import inspect
import json
import socket
import sys
import execnet
import logging
from remoto.process import check
class BaseConnection(object):
"""
Base class for Connection objects. Provides a generic interface to execnet
for setting up the connection
"""
executable = ''
remote_import_system... | ceph/remoto | remoto/backends/__init__.py | Python | mit | 11,113 |
import unittest
from worldengine.common import *
class TestCommon(unittest.TestCase):
def setUp(self):
pass
def test_get_and_set_verbose(self):
self.assertEqual(False, get_verbose(), "By default verbose should be set to False")
set_verbose(True)
self.assertEqual(True, get_ver... | ftomassetti/worldengine | tests/common_test.py | Python | mit | 3,211 |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
APP = ['RedditFunnies.py']
DATA_FILES = []
OPTIONS = {'argv_emulation': True,
'iconfile': '/Users/Kevin/PY/Reddit/Reddit.icns',
'packages': ['selenium']}
setup(
app=APP,
data_files=DATA_... | Sambalero/RedditFunnies | setup.py | Python | mit | 393 |
import socket, ssl
class PortScanner:
""" Finds open paths between this host and a specified host """
def __init__(self, target):
""" Initializes the port scanner with the specified target host"""
self.target_host = target
def run_scan(self):
""" Runs a scan against a collection... | dgarant/weasel | Weasel-Bot/weasel/bot/portscan.py | Python | mit | 959 |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 04 14:30:05 2017
@author: Mark
"""
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
# some import examples
#df = pd.read_sql_table('my_table', engine, columns = ['ColA', 'ColB'])
#df = pd.read_excel('my_dataset.xlsx'... | mr3bn/DAT210x | Module2/module2Notes.py | Python | mit | 2,684 |
"""
.. module:: nginx
:platform: Unix
:synopsis: A source module for nginx stats
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
import time
import datetime
from twisted.internet import defer
from zope.interface import implementer
from tensor.interfaces import ITensorSource
from tensor.objects import Sou... | calston/tensor | tensor/sources/nginx.py | Python | mit | 8,146 |
import todo.blueprints.admin_user as admin_user
import todo.blueprints.app_user as app_user
import todo.blueprints.jobs_api as jobs_api
import todo.blueprints.new_user as new_user
import todo.blueprints.pushes_api as pushes_api
import todo.blueprints.queues_api as queues_api
from datetime import timedelta
from flask i... | slackpad/hashtagtodo-open | todo/__init__.py | Python | mit | 782 |
import atexit
import ctypes
import os
import shutil
import subprocess
import tempfile
from taichi._lib import core as _ti_core
from taichi.lang import impl
from taichi.lang.exception import TaichiSyntaxError
from taichi.lang.expr import make_expr_group
from taichi.lang.util import get_clangpp
class SourceBuilder:
... | yuanming-hu/taichi | python/taichi/lang/source_builder.py | Python | mit | 5,824 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# written by Shotaro Fujimoto
# 2016-05-15
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from triangular import LatticeTriangular as LT
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import matplotlib.ani... | ssh0/growing-string | triangular_lattice/vicsek/vicsek_self-avoiding.py | Python | mit | 7,152 |
from collections import namedtuple
from datetime import datetime, time, timedelta
import pytz
from govuk_bank_holidays.bank_holidays import BankHolidays
from notifications_utils.countries.data import Postage
from notifications_utils.timezones import (
convert_utc_to_bst,
utc_string_to_aware_gmt_datetime,
)
L... | alphagov/notifications-utils | notifications_utils/letter_timings.py | Python | mit | 5,564 |
#!/usr/bin/env python
import os
from pylatex.utils import fix_filename
def test_no_dots():
fname = "aaa"
assert fix_filename(fname) == fname
def test_one_dot():
fname = "aa.a"
assert fix_filename(fname) == fname
def test_two_dots():
fname = "aa.a.a"
original_os_name = os.name
try:
... | JelteF/PyLaTeX | tests/test_utils_fix_filename.py | Python | mit | 1,367 |
from keystoneclient.v2_0 import client as keystoneClient
from keystoneauth1.identity import v2
from keystoneauth1 import session
from keystoneauth1 import exceptions
import easygui
import constants
class Keystone:
def __init__(self, user_name = None, password = None,
project_name = None , project... | RoyShulman/openstack-project | keystone_functions.py | Python | mit | 6,145 |
"""
Written by Jesse Evers
Completed on 05-03-2015
This program finds the nth Fibonacci number, assuming the
first two Fibonacci numbers are 0 and 1.
"""
def nthFib(num):
first = 0
second = 1
count = 2
if num == 1:
return first
elif num == 2:
return second
while count <= num:
nextNum = first + second
... | TheAtomicGoose/karan | solutions/numbers/nthFib.py | Python | mit | 416 |
# -*- coding: utf-8 -*-
import os
import codecs
import xlwt
##########################################################
def readKeysAndValuesFromeFilePath(path):
if path is None:
return
listKey = []
listValue = []
for string in codecs.open(path,'r','utf-8').readlines():
list = string.spl... | alexfeng/InternationalizationScript-iOS | InternationalScriptDemo/exportExcelDemoV2.0/exportToExcelv2.1.py | Python | mit | 2,319 |
import os
import logging
from colorlog import ColoredFormatter
import tornado
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import django
from django.core.management.base import BaseCommand
from django_websockets import settings
from django_websockets.app import get_app
logger = loggin... | samuelcolvin/django-websockets | django_websockets/management/commands/websockets.py | Python | mit | 2,670 |
import subprocess
@bot.message_handler(commands=['status'])
def bc_msg(message):
if message.from_user.id in ADMINS_IDS:
proc = subprocess.check_output("top -b |head -2 && free && df -l", shell=True)
bot.reply_to(message, proc)
else:
bot.send_message(message.chat.id, "You dont have permission.")
| WebShark025/TheZigZagProject | plugins/serverstatus.py | Python | mit | 316 |
import unittest
from utils import Lazy, EnhancedList, EnhancedDict
class LazyTest(unittest.TestCase):
def test_range(self):
lazy = Lazy(lambda: range(5))
for i, a in enumerate(lazy):
self.assertEqual(a, i)
self.assertEqual(len(lazy), 5)
def test_hash(self):
lazy... | rycus86/docker-pygen | tests/test_lazy.py | Python | mit | 956 |
from django.core.exceptions import ValidationError
from django.test import TestCase
from holonet.apps.utils.validators import domain_validator, local_validator
class DomainValidatorTestCase(TestCase):
def test_valdate(self):
self.assertRaises(ValidationError, domain_validator, 'invalid"#$email.com')
... | webkom/holonet | holonet/apps/utils/tests/test_validators.py | Python | mit | 576 |
import pathlib
import subprocess
import sys
import tempfile
import dhash
from selenium import webdriver
from wand.image import Image
image_directory = pathlib.Path("images")
# If the directory is open in explorer it won't be removed.
if not image_directory.exists():
image_directory.mkdir()
temp_directory = path... | orf/wordinserter | tests/comparison/generate_report.py | Python | mit | 4,078 |
"""
classes to model a parse tree that is a simplified equivalent to python's ast
"""
# Expression related
class Expr(object):
def __init__(self):
pass
def walk(self,walker):
walker.begin(self)
walker.end(self)
# Sub-classes of Expr
class AttributeLookup(Expr):
def __init_... | treeform/pystorm | parsetree.py | Python | mit | 16,555 |
from ooiui.core.app import app
from flask import request, render_template, Response, jsonify
from ooiui.config import SERVICES_URL
from werkzeug.exceptions import Unauthorized
import requests
import json
import urllib
def get_login():
token = request.cookies.get('ooiusertoken')
if not token:
response =... | lukecampbell/ooi-ui | ooiui/core/routes/common.py | Python | mit | 5,768 |
from handlers.douban import DBFavoriteHandler, DBLoginHandler, \
ValidCodeHandler, DBLogoutHandler
from handlers.home import HomeHandler
from handlers.player import AlbumHandler, ArtistHandler
from handlers.playlist import AddMyPlaylistHandler, ClonePlaylistHandler, \
CreateMyPlaylistHandler, PlaylistHandler, \... | listen1/listen1 | listen1/urls.py | Python | mit | 1,320 |
import sublime
def pkg_settings():
# NOTE: The sublime.load_settings(...) call has to be deferred to this function,
# rather than just being called immediately and assigning a module-level variable,
# because of: https://www.sublimetext.com/docs/3/api_reference.html#plugin_lifecycle
return sublime.loa... | psykzz/st3-gitblame | src/settings.py | Python | mit | 420 |
#_*_ coding: utf-8 _*_
import tensorflow as tf
a = tf.constant(2)
b = tf.constant(3)
with tf.Session() as sess:
print "-" * 60
print "a=2,b=3"
print "Addition with constants: %i" % sess.run(a+b)
print "Multiplication with constants: %i" % sess.run(a*b)
print "-" * 60
| JaeGyu/PythonEx_1 | 20160327_3.py | Python | mit | 276 |
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2014-2019 Digital Sapphire
#
# 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 ... | JMSwag/dsdev-utils | dsdev_utils/compat.py | Python | mit | 2,335 |
# -*- coding: utf-8 -*-
__author__ = 'Alex Bo'
__email__ = 'bosha@the-bosha.ru'
from torhandlers.base import ContextMixin, GenericHandler, TemplateResponseMixin
from torhandlers.exceptions import ImproperlyConfigured
class SuccessUrlMixin:
success_url = None
success_url_name = None
def get_success_url(s... | bosha/torhandlers | torhandlers/form.py | Python | mit | 3,137 |
# -*- coding: utf-8 -*-
import settings
import os
from geoconversions.LatLonConversions import geojson2WebMercator
# Convert the file
geojson2WebMercator(os.path.join(settings.DATAFOLDER, settings.ZIPCODE_FOLDER, settings.ZIPCODE_GEOJSON),
os.path.join(settings.DATAFOLDER, settings.ZIPCODE_FOLDER... | DawudH/scrapy_real-estate | plot/convert_zipcode_areas.py | Python | mit | 498 |
#-------------------------------------------------------------------------------
# Name: parse_xxcopy_logfile
# Purpose: A python script to parse statistics from xxcopy logfiles and
# write them to a .csv file.
#
# Part of https://github.com/maphew/Speed-test
#
# Author: Matt W... | maphew/Speed-test | stats/parse-log.py | Python | mit | 4,622 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from requests.exceptions import ConnectionError
import sys
import time
import math
import logging
sys.path.append('/home/workDir/hubi/auto-btc')
from Util import *
import HuobiService
latest_sell_order_id=None
latest_buy_order_id=None
lowe... | bupt075225/auto-btc | HuobiMain.py | Python | mit | 15,206 |
from datetime import *
date_str = "2016-08-30"
result = datetime.strptime('2011-07-07', "%Y-%m-%d")
# print(result)
if result < datetime.strptime("2016-09-01", "%Y-%m-%d"):
print('innner day')
else:
print('outter day') | SELO77/seloPython | 3.X/test.py | Python | mit | 226 |
from lib import test
class Test(test.Test):
@classmethod
def setUpClass(cls):
cls.nr = '06'
def test_1(self):
test_input = """eedadn
drvtee
eandsr
raavrd
atevrs
tsrnev
sdttsa
rasrtv
nssdts
ntnada
svetve
tesnvt
vntsnd
vrdear
dvrsen
enarar"""
self.execute_test(test_input)
se... | unstko/adventofcode2016 | 06/test.py | Python | mit | 442 |
#!/usr/bin/python
# Copyright 2012-2017, The Tor Project, Inc
# See LICENSE for licensing information
"""
ntor_ref.py
This module is a reference implementation for the "ntor" protocol
s proposed by Goldberg, Stebila, and Ustaoglu and as instantiated in
Tor Proposal 216.
It's meant to be used to validate Tor's ntor ... | mmcloughlin/pearl | etc/testdata/ntor_ref.py | Python | mit | 13,347 |
import sys
def template(templateLocation, fillings):
fileData = open(templateLocation, 'r').read()
count = 1
for fill in fillings:
fileData = fileData.replace('{{'+str(count)+'}}', fill)
count += 1
print fileData
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Argu... | siimeon/TemplateFiller | template.py | Python | mit | 480 |
from django.conf import settings
from django.conf.urls import include, url
from . import views
# Uncomment the next two lines to enable the admin:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^getobject/type/(?P<obj_type>[a-zA-Z]+)/tag/(?P<obj_tag>[a-zA-Z0-9_\-]+)/index/(?P<obj_index>[0-9]+)/?... | naelstrof/PugBot-Discord-Django | twitchstreams/urls.py | Python | mit | 1,106 |
from django.contrib.localflavor.us.forms import USZipCodeField
country_flavor = {
'US': USZipCodeField,
}
| fcurella/python_zipcodes | python_zipcodes/django_app/zipcodes/utils.py | Python | mit | 111 |
import _plotly_utils.basevalidators
class MirrorValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="mirror", parent_name="layout.scene.zaxis", **kwargs
):
super(MirrorValidator, self).__init__(
plotly_name=plotly_name,
parent_na... | plotly/plotly.py | packages/python/plotly/plotly/validators/layout/scene/zaxis/_mirror.py | Python | mit | 506 |
from pudzu.charts import *
# TODO: 10 downwards
df = pd.read_csv("datasets/flagsanimals.csv")
FONT = sans
fg, bg="black", "#EEEEEE"
default_img = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/No_flag.svg/1024px-No_flag.svg.png"
def process(d):
if not d: return None
description = get_non(d, 'des... | Udzu/pudzu | dataviz/flagsanimals.py | Python | mit | 1,893 |
#!/usr/bin/env python
import rospy
import numpy as np
from time import time, sleep
from datetime import datetime
import logging
from sensor_msgs.msg import LaserScan # Messages from Lidar System
import sys
logging.basicConfig(filename='control.log', format=50 * '=' +
'\n%(asctime)s %(message)s',... | NASLab/GroundROS | LidarLogger.py | Python | mit | 1,619 |
"""A module that answers hardcoded questions."""
from ppp_libmodule import HttpRequestHandler
from .requesthandler import RequestHandler
def app(environ, start_response):
"""Function called by the WSGI server."""
return HttpRequestHandler(environ, start_response, RequestHandler) \
.dispatch()
| ProjetPP/PPP-Oracle | ppp_oracle/__init__.py | Python | mit | 316 |
#!/usr/bin/env python
import socket
# Connect to an IPv4 address on port 5000
#host = '0.0.0.0'
host = '0.0.0.0'
port = 5012
sockaddr = (host, port)
# Create an IPv4 socket and connect
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
conn = sock.connect(sockaddr) | IPVL/Arun-SocketExample | client.py | Python | mit | 295 |
from django.conf import settings
from django.utils.module_loading import import_string
from rest_framework import serializers
from callback_request.models import CallbackRequest, CallEntry
from callback_schedule.models import CallbackManagerPhone, CallbackManagerSchedule
class CallbackSerializer(serializers.ModelSer... | steppenwolf-sro/callback-schedule | callback_request/serializers.py | Python | mit | 1,877 |
# program for broadcasting messages over channel; see
# http://asyncoro.sourceforge.net/tutorial.html for details.
import sys, random
import asyncoro
def seqsum(coro=None):
# compute sum of numbers received over channel
result = 0
while True:
msg = yield coro.receive()
if msg is None:
... | pgiri/asyncoro | examples/tut_channel.py | Python | mit | 1,318 |
import os
from datetime import date
from typing import List
import pytest
from invoices.models import Address, Invoice, Item, Sender
from invoices.xml.types import ProductSummary
from lxml import etree
@pytest.fixture
def sample_invoice_xml():
here = os.path.dirname(__file__)
parser = etree.XMLParser(remove... | patrick91/pycon | backend/invoices/tests/conftest.py | Python | mit | 2,524 |
"""
WSGI config for theaterwecker 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/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANG... | CodeforChemnitz/TheaterWecker | django/theaterwecker/wsgi.py | Python | mit | 404 |
## -*- coding: utf-8 -*-
# conf.py -- Sphinx configuration for PyLit
# =========================================
#
# Documentation build configuration file
#
# This file is execfile()d with the current directory set to its containing
# dir.
#
# The contents of this file are pickled, so don't put values in the nam... | tkarna/cofs | pylit/doc/conf.py | Python | mit | 7,538 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
urls = ['https://capturemrg.box.com/s/4ocv51zmv5wsb181nvej01awio1wm2qk',
'https://capturemrg.box.com/s/cyh1md18r4y6tv1j7isaqeu9quwe30qu',
'https://capturemrg.box.com/s/z2894tj1fdtyw4aix36h3zfxdowf7g3k',
'https://capturemrg.box.com/s/b7jgrvdrhx6g2z81... | relic7/prodimages | python/jbmodules/http_tools/auth/Box/boxapi_service.py | Python | mit | 6,197 |
# The contents of this file are subject to the Common Public Attribution
# License Version 1.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://code.reddit.com/LICENSE. The License is based on the Mozilla Public
# License Version 1.1, ... | h2oloopan/easymerge | EasyMerge/tests/reddit/r2/r2/controllers/policies.py | Python | mit | 4,163 |
import re
from django.conf import settings
# Capitalizes the first letter of a string.
capfirst = lambda x: x and x[0].upper() + x[1:]
def wrap(text, width):
"""
A word-wrap function that preserves existing line breaks and most spaces in
the text. Expects that existing line breaks are posix newlines.
... | jonaustin/advisoryscan | django/django/utils/text.py | Python | mit | 7,005 |
"""
Tests the subsets_exp module.
"""
import mock
import unittest
from .context import subsets_exp
from .context import config
from .context import runner
from .context import test_utils as tu
class Subsets_ExperimentTestCase(unittest.TestCase):
def setUp(self):
config_obj = tu.sample_config()
moc... | jjbrophy47/sn_spam | experiments/tests/test_subsets_exp.py | Python | mit | 3,319 |
import argparse
import json
import peggy
import pprint
import sys
parser = argparse.ArgumentParser(
description = 'Parse some input according to a Parsing Expression Grammar.'
)
parser.add_argument('grammar', type = lambda g: json.load(open(g)))
parser.add_argument('rule')
parser.add_argument('input', type = open,... | marmeladema/Peggy | peggy/__main__.py | Python | mit | 985 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bolt.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| blakecrosley/getboltapp.com | bolt/manage.py | Python | mit | 247 |
# 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/resources/azure-mgmt-msi/azure/mgmt/msi/aio/operations/_system_assigned_identities_operations.py | Python | mit | 4,293 |
"""Tests for etest.build."""
import click.testing
import etest.build as sut
def test_help() -> None:
"""Ensure etest-build --help exits successfully."""
runner = click.testing.CliRunner()
result = runner.invoke(sut.main, ["--help"])
assert result.exit_code == 0
| alunduil/etest | etest_test/build_test.py | Python | mit | 282 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*
# Homepage: https://github.org/rpuntaie/remdups
# License: See LICENSE file
# Authors:
# Roland Puntaier
# Changes:
# 2013-10-07: Version 1.0
# 2013-10-31: Version 1.1 (documentation changes/corrections)
# 2016-05-29: Version 1.2 (fails to install -> fix)
# 2018-01-24: ... | rpuntaie/remdups | remdups/remdups.py | Python | mit | 28,642 |
# Copyright (c) 2019 Pieter Wuille
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test-only secp256k1 elliptic curve implementation
WARNING: This code is slow, uses bad randomness, does not properly protect
keys, and is trivia... | thelazier/dash | test/functional/test_framework/key.py | Python | mit | 13,500 |