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 |
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import itertools
import csv, codecs, cStringIO
def parse_date(date_str):
return datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S.%f")
def total_seconds(td):
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / float(10**6)
def ... | filipefigcorreia/asaanalyzer | asaanalyser/common/util.py | Python | mit | 2,824 |
'''
The kernel installer.
Run `python -m ai.backend.integration.jupyter.install` to use Backend.AI in your Jupyter notebooks.
'''
import argparse
import json
import os
import sys
import webbrowser
from jupyter_client.kernelspec import KernelSpecManager
from IPython.utils.tempdir import TemporaryDirectory
from .kerne... | lablup/sorna-jupyter-kernel | src/ai/backend/integration/jupyter/install.py | Python | mit | 4,036 |
#!/usr/bin/env python
# coding: utf-8
"""Generate ./pyui/config.py"""
import os
directory = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(directory, 'pyui', 'config.py')
if __name__ == "__main__":
s = '''\
#!/usr/bin/env python
# coding: utf-8
"""This python script file is generated automa... | niucheng/PYUI | config.py | Python | mit | 720 |
# coding: utf-8
"""
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification # noqa: E501
The version of the OpenAPI document: 1.1.2-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except Im... | cliffano/swaggy-jenkins | clients/python-legacy/generated/openapi_client/models/github_repositorypermissions.py | Python | mit | 5,737 |
from bashmu.distserver import DistServer
ds = DistServer('localhost',1708)
@ds.defer
def foo(n, s):
import time
print("Running", n, s)
time.sleep(n)
print("Done", n, s)
return s + 1
@ds.defer
def bar(n):
import time
print("Running",n)
time.sleep(n)
print("Done",n)
return n**... | Renmusxd/Bashmu | tests/testclient.py | Python | mit | 778 |
from rest_framework import serializers
from .fields import NestedHyperlinkedIdentityField, SecondaryKeyRelatedField
from .serializers import UserSerializer, NotebookSerializer, NoteSerializer, TaskSerializer
class UserLinksSerializer(serializers.Serializer):
self = NestedHyperlinkedIdentityField(view_name='user-... | vsemionov/boomerang | api/rest/links.py | Python | mit | 3,929 |
import re
import os
import hashlib
import shutil
import string
import oelite.fetch
import oelite.util
import local
import url
import git
import svn
FETCHERS = {
"file" : local.LocalFetcher,
"http" : url.UrlFetcher,
"https" : url.UrlFetcher,
"ftp" : url.UrlFetcher,
"git" : git.GitFetcher,
"svn"... | sknsean/core | lib/oelite/fetch/fetch.py | Python | mit | 13,075 |
from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, logout_user, login_required, \
current_user
from . import auth
from .. import db
from ..models import User
from ..email import send_email
from .forms import LoginForm, RegistrationForm, ChangePasswordForm,\
... | mikeyrichardson/kyburz | app/auth/views.py | Python | mit | 6,103 |
from django.db import models
import os
from django.core.files.storage import FileSystemStorage
storage = FileSystemStorage(location='/polls/media')
class Poll(models.Model):
name = models.CharField(max_length=30, null=True)
description = models.CharField(max_length=300, null=True)
category = models.CharField(max... | DenysGurin/projt1 | polls/models.py | Python | mit | 615 |
import _plotly_utils.basevalidators
class BarpolarValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="barpolar", parent_name="", **kwargs):
super(BarpolarValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/_barpolar.py | Python | mit | 10,554 |
import unittest
import nose.tools
import responses
import json
import os
from click.testing import CliRunner
from requests.exceptions import HTTPError
from test_helpers import *
from csa_client import constants
from csa_client import RequestHandler
from csa_client.command import *
class CommandTests(unittest.TestCase... | samueljackson92/CSAlumni-client | tests/command_test.py | Python | mit | 7,643 |
import math
import sys
from functools import reduce
import operator
from mule.InfoError import *
from mule.JobPlatformResources import *
from mule.JobParallelizationDimOptions import *
__all__ = ['JobParallelization']
def _prod(iterable):
return reduce(operator.mul, iterable, 1)
class JobParallelization(InfoEr... | schreiberx/sweet | mule/python/mule/JobParallelization.py | Python | mit | 10,391 |
import modules
from modules import *
def run():
print "Usage: spaceclone <command> <options>"
print ""
print "Commands:"
for module in modules.__all__:
print "%s\t\t%s" % (module, getattr(modules, module).__module_desc__)
| nzwulfin/spaceclone | src/spaceclone/usage.py | Python | mit | 249 |
from web3.utils.encoding import (
encode_hex,
)
from populus.migrations import (
String,
Address,
Migration,
Operation,
)
def test_migrations_store_receipts_on_completion(web3, MATH, chain):
registrar = chain.registrar
class MockOperation(Operation):
def execute(self, *args, **kwa... | euri10/populus | tests/migrations/test_migration_stores_receipt_values_in_registrar.py | Python | mit | 2,466 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import locale
import logging
import time
import datetime
from lib import ds18b20
INTERVALLE_ENTRE_2_RELEVES_EN_MINUTES=10
nbMaxTentatives = 3
FORMAT = '%(asctime)-15s:%(levelname)s:%(message)s'
logging.basicConfig(format=FORMAT,level=logging.DEBUG)
logging.info("Initialisati... | manuelsimon/domotique | releverTemperatures.py | Python | mit | 1,328 |
# coding=utf-8
# Global settings.
document_class = "ext" + "article" # Ext is for extsizes package.
font_size = "10pt" # Allowed: 8pt, 9pt, 10pt, 11pt, 12pt, 14pt, 17pt, 20pt
# Front page.
## Setting title to None also ignores authors and date.
title = "Dimensionality Reduction"
authors = None
date = None
abstract... | GMadorell/coursera-machine-learning | theory/08.02 - Dimensionality Reduction/metadata.py | Python | mit | 557 |
import sqlite3 as dbi
import sys
from copy import deepcopy
class Graph (object):
def __init__(self, foldername):
try:
self.db = dbi.connect(foldername)
self.cu=self.db.cursor()
#print 'success'
except:
#print 'failed'
sys.exit()
#retur... | cmfeng/CEE505 | HW6_GraphicUserInterface/files/Graph.py | Python | mit | 9,037 |
import numpy as np
from scipy.sparse import csc_matrix
import math
def pageRank(G, s = .85, maxerr = .001):
"""
Computes the pagerank for each of the n states.
Used in webpage ranking and text summarization using unweighted
or weighted transitions respectively.
Args
----------
G: matrix... | spininertia/graph-mining-rdbms | src/phase-3/src/misc/pagerank.py | Python | mit | 1,975 |
# vim: set ts=8 sw=4 tw=0 fileencoding=utf-8 filetype=python expandtab:
from __future__ import print_function, absolute_import, division, unicode_literals
from datetime import timedelta
import sys
import os
import stat
import time
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser... | bluec0re/python-sftpsync | sftp_sync/sync.py | Python | mit | 28,706 |
# coding: utf-8
from __future__ import print_function, unicode_literals
| asyncee/catpcha_extended | __init__.py | Python | mit | 75 |
from aiohttp import web
import asyncio
import os
import pystache
import functools
def Response(text):
return web.Response(body=text.encode('utf-8'))
def Json(obj):
json = str(obj)
return Response(json)
def render_template(template_name, root_path, request, data={}):
renderer = pystache.renderer.Re... | ViktorNova/aiostache | __init__.py | Python | mit | 4,038 |
import json
import requests
import sqlite3
import time
from Item import *
def run(url):
#url = http://services.runescape.com/m=itemdb_rs/api/catalogue/items.json?category=1&alpha=a&page=1
data = requests.get(url)
time.sleep(.01)
if(data.status_code == 404):
print('Item Doesnt Exist.')
return
r = requests.pos... | jb1361/RS3GEPredictionModel | src(old)/gatherData.py | Python | mit | 2,379 |
import os
def set_cuda_devices(device_list=[]):
"""Masks the CUDA visible devices.
Warning: Running this while another script is executed
might end up in the other script to crash.
Parameters
----------
device_list: list(int)
A list of of CUDA devices, such as [0,1].
... | bsautermeister/tensorlight | tensorlight/hardware.py | Python | mit | 833 |
# -*- coding: utf-8 -*-
"""This module contains pybooru object class."""
from __future__ import absolute_import,unicode_literals # get some features not yet in python 3
from .exceptions import PybooruError # get the exception call
from .resources import * # import the... | buzzbyte/pybooru | pybooru/pybooru.py | Python | mit | 33,500 |
import gtk.gdk
import time
while True:
for i in range(0,15):
time.sleep(.1)
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],s... | Brvno/CascadeTV | Test/test.py | Python | mit | 740 |
#!/usr/bin/env python
from string import ascii_uppercase
import caesar
LETTERS = ['etaoinshrdlcumwfgypbvkjxqz']
LETTERS = ['etaoinsh']
DIGRAPHS = ['ST','NG','TH','QU']
ciphertext = """LIVITCSWPIYVEWHEVSRIQMXLEYVEOIEWHRXEXIPFEMVEWHKVSTYLXZIXLIKIIXPIJVSZEYPERRGERIM
WQLMGLMXQERIWGPSRIHMXQEREKIETXMJTPRGEVEKEITREWHEXXLE... | mhearne-usgs/handcrypt | crack.py | Python | mit | 1,108 |
# =============================================================================
# FILE: deoplete_elm.py
# AUTHOR: Pawel Bogut
# =============================================================================
from .base import Base
from os import path
import re
import subprocess
import json
class Source(Base):
def... | pbogut/deoplete-elm | rplugin/python3/deoplete/sources/deoplete_elm.py | Python | mit | 2,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/network/azure-mgmt-network/azure/mgmt/network/aio/_network_management_client.py | Python | mit | 731,138 |
from __future__ import absolute_import, division, print_function
import os.path
import sys
from Cython.Build import cythonize
from Cython.Distutils import extension
from echomesh.base import Path
from echomesh.base import Platform
_DEBUG_FLAG = '--debug'
DEBUG = _DEBUG_FLAG in sys.argv
if DEBUG:
sys.argv.remov... | rec/echomesh | code/python/echomesh/build/BuildConfig.py | Python | mit | 2,875 |
""" Rumors script for x/84. """
# https://github.com/x84-extras/rumors
__author__ = u'haliphax <https://github.com/haliphax>'
# std imports
import collections
import os
# local
from x84.bbs import getsession, getterminal, DBProxy
from x84.bbs.ini import get_ini
from x84.bbs.output import echo
MYDIR = os.path.dirname... | x84-extras/rumors | rumors.py | Python | mit | 7,299 |
from random import randrange as rand
import pygame, sys
cell_size = 18
cols = 10
rows = 22
maxfps = 30
colors = [
(0, 0, 0 ),
(255, 85, 85),
(100, 200, 115),
(120, 108, 245),
(255, 140, 50 ),
(50, 120, 52 ),
(146, 202, 73 ),
(150, 161, 218 ),
(35, 35, 35)
]
tetris_shapes = [
[[1, 1, 1],
[0, 1, 0]],
... | saintdragon2/python-3-lecture-2015 | sinsojael_final/1st_presentation/5조/5wh.py | Python | mit | 6,784 |
"""Lea 128-bit cipher."""
import itertools
from arxpy.bitvector.core import Constant
from arxpy.bitvector.operation import RotateLeft as ROL
from arxpy.bitvector.operation import RotateRight as ROR
from arxpy.primitives.primitives import KeySchedule, Encryption, Cipher
class LeaKeySchedule(KeySchedule):
"""Key ... | ranea/ArxPy | arxpy/primitives/lea.py | Python | mit | 3,096 |
# -*- coding: utf-8 -*-
from distutils.core import setup
import py2exe
option = {
"compressed" : 1,
"optimize" : 2,
"bundle_files" : 1
}
setup(
options = {
"py2exe" : option
},
console = [
{ "script" : "main.py" }
],
zipfile = None
) | IBCCW/plen2__ble_motion_installer_python | make.py | Python | mit | 257 |
import sys, os
#sudo pip install prettytable
from prettytable import PrettyTable
sys.path.append(os.path.abspath("../login/"))
from azureADUserLogin import *
resource_client = azure_ad_user_login()
def list_resource_group(resource_group_name=""):
rgTable = PrettyTable(['Name','Location'])
if resource_group... | jiyongseong/AzureCommon | azure_resource_manager/python/resourceGroup/manage_resource_group.py | Python | mit | 1,672 |
import os
import shutil
import six
from tempfile import mkdtemp
from ..exceptions import UnknownMethod, ShellError
from .utils import ShellParser
from .image import Parser as TesseractParser
from distutils.spawn import find_executable
class Parser(ShellParser):
"""Extract text from pdf files using either the ``... | deanmalmgren/textract | textract/parsers/pdf_parser.py | Python | mit | 2,826 |
import argparse
import glob
import features
import cv2
import pickle
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--images", required = True,
help = "Path to the directory that contains the images representing model categories.")
ap.add_argument("-m", "--models", required = True,
help = "Path to locat... | jbest/digitization_tools | analyze/categorize.py | Python | mit | 1,699 |
# 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/desktopvirtualization/azure-mgmt-desktopvirtualization/azure/mgmt/desktopvirtualization/aio/operations/_applications_operations.py | Python | mit | 19,785 |
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, p... | wavycloud/pyboto3 | pyboto3/shield.py | Python | mit | 46,532 |
#!/usr/bin/python
# coding: utf-8
# waveform modification based on spectrum differencial
import json
import numpy as np
import sys
import sptk
from pylab import plot, show, legend
from scipy.io import wavfile
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Synthsis")... | r9y9/stav | diff_synthesis.py | Python | mit | 1,259 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cc', '0010_remove_numericdata_qualifiers'),
]
operations = [
migrations.AlterField(
model_name='numericexpressio... | arunchaganty/contextual-comparatives | applesoranges/cc/migrations/0011_auto_20160221_0120.py | Python | mit | 449 |
import unittest
from katas.kyu_7.finding_remainder_without_using_modulo import remainder
class RemainderTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(remainder(3, 2), 1)
def test_equals_2(self):
self.assertEqual(remainder(19, 2), 1)
def test_equals_3(self):
... | the-zebulan/CodeWars | tests/kyu_7_tests/test_finding_remainder_without_using_modulo.py | Python | mit | 512 |
"""
Test the ffi wrapper for libgroove
"""
from __future__ import absolute_import, unicode_literals
from groove._groove import ffi, lib
def setup_module(module):
lib.groove_init()
lib.groove_set_logging(32)
def teardown_module(module):
lib.groove_finish()
def test_channel_layouts():
# TODO: repla... | kalhartt/python-groove | tests/test_groove_ffi.py | Python | mit | 684 |
# -*- coding: utf-8 -*-
__author__ = 'peter'
from handlers.avatar import AvatarRequestHandler
class BotsHandler(AvatarRequestHandler):
def get(self):
pass
| motord/tardis | dashboard/bot.py | Python | mit | 170 |
import re
import copy
import os
import tempfile
import logging
import subprocess
import shlex
import time
from threading import Timer
from pycparser import parse_file, c_generator
from pycparser.c_ast import Break
_ENV_ORIG_SRC = 'MUTATE_ORIG_SRC'
_ENV_MODIFIED_SRC = 'MUTATE_MODIFIED_SRC'
def _node_to_str(node):
... | Juzley/Fawkes | mutate/mutator.py | Python | mit | 10,400 |
"""
Integration tests for singletask vector feature models.
"""
import os
import deepchem as dc
import numpy as np
from sklearn.ensemble import RandomForestRegressor
def test_singletask_sklearn_rf_ECFP_regression_API():
"""Test of singletask RF ECFP regression API."""
X = np.random.rand(100, 5)
y = np.random.ra... | lilleswing/deepchem | deepchem/models/tests/test_api.py | Python | mit | 5,338 |
"""
WSGI config for todo_lab 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.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETT... | pauloromeira/todo_lab | todo_lab/wsgi.py | Python | mit | 393 |
from django.shortcuts import render
from django.views.generic import View
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, JsonResponse
from django.utils import timezone
from .forms import PhotoForm, DeleteForm
from .mod... | andela-tadesanya/django-photo-application | django_photo/photo/views.py | Python | mit | 5,672 |
"""Review Board feature checkers."""
from __future__ import unicode_literals
from djblets.features.checkers import SiteConfigFeatureChecker
class RBFeatureChecker(SiteConfigFeatureChecker):
"""Feature checker that checks against a LocalSite's configuration.
Features can be enabled/disabled on a per-LocalSi... | brennie/reviewboard | reviewboard/features/checkers.py | Python | mit | 2,485 |
from numpy import array
from numpy import *
import knn
import matplotlib.pyplot as plot
datingMat, datingLabels = knn.readDataFile("../inaction/Ch02/datingTestSet2.txt")
fig = plot.figure()
ax = fig.add_subplot(111)
datingMat2 = {}
handles = []
distinctLabels = []
size = len(datingLabels)
for index in range(size):
... | lxzhu/ehow | src/testFirstPlot.py | Python | mit | 1,200 |
import bpy
import copy # オブジェクトをコピーするためのモジュールcopyをインポート
def move(box,l,stack,s,t): # 図形をコピーして移動する操作
box_2 =copy.deepcopy(box) # boxをbox_2にコピー
n=len(box_2)
for i in range(n):
for j in range(8):
box_2[i][j][s]+=l # s方向に l だけ移動
box_2[i][j][t]+=l # t方向に l ... | o-kei/design-computing-aij | ch2_5/blender04.py | Python | mit | 1,701 |
from maka.data.Field import String
from maka.data.Observation import Observation
from FieldTests import FieldTests, fieldTestClass
@fieldTestClass
class StringFieldTests(FieldTests):
fieldClass = String
validValue = 'bobo'
invalidValue = 0
defaultTypeName = 'string'
def te... | HaroldMills/Maka | test/StringFieldTests.py | Python | mit | 2,021 |
# 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-web/azure/mgmt/web/models/name_identifier.py | Python | mit | 825 |
#!/usr/bin/env python3
# Copyright (c) 2015-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test decoding scripts via decodescript RPC command."""
from test_framework.messages import CTransactio... | namecoin/namecore | test/functional/rpc_decodescript.py | Python | mit | 18,174 |
# -*- coding: utf-8 -*-
"""
Zipline bundle for Poloniex exchange
"""
import logging
from datetime import time, timedelta, datetime
from pytz import timezone
import numpy as np
import pandas as pd
from pandas.tseries.offsets import CustomBusinessDay
from zipline.utils.calendars import (
TradingCalendar, register_ca... | FlorianWilhelm/zipline-poloniex | zipline_poloniex/bundle.py | Python | mit | 6,718 |
import datetime
import numpy as np
from hyperopt import hp, fmin, tpe
import os
import sys
from sklearn.ensemble import RandomForestClassifier
sys.path.insert(0, os.getcwd())
import qml_workdir.classes.config
from qml.cv import QCV
from qml.models import QXgb, QXgb2, QNN1, QNN2
from qml_workdir.classes.models impor... | quantum13/mlbootcamp5 | qml_workdir/ensembling/level1_models_nn02.py | Python | mit | 1,653 |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
from django.apps import AppConfig
class Config(AppConfig):
name = 'useraccounts'
label = 'useraccounts'
verbose_name = "Accounts"
| glomium/elmnt.de | useraccounts/apps.py | Python | mit | 233 |
import contextlib
import io
import re
import os
import subprocess
import sys
import pexpect
import pytest
@pytest.fixture(scope='session')
def lldb_session(tmpdir_factory):
"""Starts LLDB in the background with Python as the target process.
LLDB is started via pexpect.spawn; bidirectional communication with... | malor/cpython-lldb | tests/conftest.py | Python | mit | 4,928 |
###ENUM CONSTANTS
XI_BINNING = 0
XI_SKIPPING = 1
# xiApi parameters
XI_PRM_DEVICE_NAME = "device_name" # Return device name
XI_PRM_DEVICE_TYPE = "device_type" # Return device type
XI_PRM_DEVICE_MODEL_ID = "device_model_id" # Re... | pupil-labs/pyximea | constants.py | Python | mit | 19,557 |
from django.conf import settings
from django.core.mail import send_mail
from django.shortcuts import render
# Create your views here.
from products.models import Product, ProductFeatured
from .forms import ContactForm, SignUpForm
from .models import SignUp
def home(request):
title = 'Sign Up Now'
featured_p... | loafbaker/django_ecommerce2 | newsletter/views.py | Python | mit | 2,151 |
# -*- coding: utf-8 -*-
import logging
from django import forms
from django.core.urlresolvers import reverse
from crispy_forms.bootstrap import FormActions, InlineCheckboxes
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Field, HTML, Layout, Submit
from .models import Mocker
logger = log... | paveu/api_mocker | apimocker/mocker/forms.py | Python | mit | 1,407 |
# -*- coding: utf-8 -*-
"""
Модели
"""
from django.db import models
from django.contrib.auth.models import User
from decimal import Decimal
# Create your models here.
class Booking(models.Model):
"""Модель заказа"""
class Meta:
"""
Права по-умолчанию обнулены.
Добавлено право на ... | bo858585/AbstractBooking | Booking/booking/models.py | Python | mit | 5,669 |
#--coding:utf8--
from BeautifulSoup import BeautifulSoup
import urllib2
start_url = 'http://bbs.tianya.cn/post-stocks-1062591-%s.shtml'
saved_file = "content.txt"
def spider(url, f):
r = urllib2.urlopen(url)
h = r.read()
txt = extract(h)
f.write(txt.encode('utf8'))
f.write('\r\n=================... | largetalk/tenbagger | gather/blog/fetch_tianya.py | Python | mit | 1,048 |
import sys
from importlib import import_module
sys.path.insert(0, ".") # Necessary for working in other modules
def import_from_path(path):
try:
module = import_module(path)
return module
except ImportError:
parts = path.split(".")
module_path = ".".join(parts[:-1])
a... | ToAruShiroiNeko/revscoring | revscoring/utilities/util.py | Python | mit | 717 |
import psycopg2
import datetime
from .db_controller import DbController
from logic import user
class Event:
def __init__(self, id_, title, description, photo, date, time, shortdescription):
self._id = id_
self.title = title
self.description = description
self.shortdescri... | lubchenko05/belka.system | belkaBot/logic/event.py | Python | mit | 3,392 |
"""Main initialization for the WeGovNow extension."""
VERSION = (3, 2, 1)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_wegovnow',
'WeGovNow',
display_admin=False,
superuser=False,
version=__version__
... | ExCiteS/geokey-wegovnow | geokey_wegovnow/__init__.py | Python | mit | 384 |
# -*- coding: utf8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import generators
from markdown.preprocessors import Preprocessor
from markdown.extensions import Extension
import re
class WorkSyntaxPreprocessor(Preprocessor):
de... | Lokky007/flask_testing_web | work_syntax_admin.py | Python | mit | 2,519 |
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('pollio.views',
url(r'^$', 'index'),
url(r'^initialize/$', 'initialize'),
url(r'^new_poll/$', 'new_poll'),
url(r'^request_poll/$', 'request_poll'),
url(r'^reque... | army-of-dumbledore/pennappsF13 | django/django_server/pollio/urls.py | Python | mit | 400 |
# encoding: UTF-8
"""
# Gender variable
#
# Copyright (c) 2015, Translation Exchange, Inc.
# 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 ... | translationexchange/tml-python | tml/rules/contexts/gender.py | Python | mit | 3,404 |
import asyncio
import unittest
from aiounittest import async_test
async def add(x, y):
await asyncio.sleep(0.1)
return x + y
class MyAsyncTestDecorator(unittest.TestCase):
@async_test
async def test_async_add(self):
ret = await add(5, 6)
self.assertEqual(ret, 11)
@unittest.expec... | kwarunek/aiounittest | tests/test_async_test.py | Python | mit | 899 |
from flask import render_template, flash, redirect, url_for, jsonify, session
from .forms import WebsiteForm
from . import main
from ..scraper import scraper
from datetime import datetime
@main.route('/', methods=['GET', 'POST'])
def index():
# Load Form
form = WebsiteForm()
# Scrape Function
def s... | znoland3/zachdemo | app/main/views.py | Python | mit | 1,428 |
#/usr/bin/env pypy
import subprocess
import tempfile
import argparse
import os
seqtk = "seqtk"
def parse_args():
"Pass command line arguments"
parser = argparse.ArgumentParser(description='Process input files')
#input files
parser.add_argument('-s','--sequences',
help='number of... | thomasvangurp/epiGBS | mapping_varcall/merge_pear.py | Python | mit | 8,665 |
# 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/containerregistry/azure-mgmt-containerregistry/azure/mgmt/containerregistry/v2019_04_01/operations/_runs_operations.py | Python | mit | 28,323 |
from ._base import FunctionBase
class Function(FunctionBase):
name = 'import'
doc = 'Imports arg[0] module as arg[1] name'
methods_subclass = {}
def do_import(self, tglobals, elocal, import_module, import_as):
text_mod = 'import %s as %s' % (import_module, import_as)
try:
e... | Bakterija/mmplayer | mmplayer/kivy_soil/terminal_widget/functions/import.py | Python | mit | 715 |
import unittest
from twisted.internet import defer
from arena.local_arena import LocalIOArena
class GameExampleTests(unittest.TestCase):
"""Tests of situations encountered in games that broke the bot"""
AIG_BOT = "pokeher/theaigame_bot.py"
def __run_test(self, actions):
with LocalIOArena(silent... | gnmerritt/poker | test/test_game_situations.py | Python | mit | 2,316 |
#!/usr/bin/env python
## path configuration
caffe_root = './caffe'
script_path = '.'
caffe_model = script_path + '/soccer_make_inference.prototxt'
caffe_weight = script_path + '/snapshot/superlatefusion_iter_last.caffemodel'
caffe_inference_weight = script_path + '/superlatefusion_inference.caffemodel'
### start gene... | xionluhnis/decnet-scripts | training/super_late_fusion/test.py | Python | mit | 1,383 |
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'manuelalvarez.views.home', name='home'),
# url(r'^manuelalvarez/', include('manuel... | manuel-alvarez/manuelalvarez | manuelalvarez/urls.py | Python | mit | 594 |
import sys
from copy import deepcopy
if sys.stdout.isatty():
RED_FONT_ESC = "\033[1;31m"
GREEN_FONT_ESC = "\033[1;32m"
DEFAULT_FONT_ESC = "\033[0;0m"
else:
RED_FONT_ESC = ""
GREEN_FONT_ESC = ""
DEFAULT_FONT_ESC = ""
class DictWrapper:
@classmethod
def from_dict(cls, source):
... | pkubik/setags | setags/utils.py | Python | mit | 595 |
from . import node
from . import visitor
| Sibert-Aerts/c2p | src/c2p/grammar/ast/__init__.py | Python | mit | 41 |
import os
from sys import exit
import pygame
import time
#import pywapi
import requests
import string
import logging
import datetime
import calendar
#import threading
import random
# *** Not to be used for commercial use without permission!
# if you want to buy the icons for commercial use please sen... | schnitzlein/weatherstation | WeatherScreen.py | Python | mit | 31,076 |
"""
In this module, the views of the recommender API are defined. According to
their definition, views are functions that take a web request and return a
web response. Therefore, they are the main entry points of the recommender
system. Moreover, they describe what the system is capable of and how the
system is accesse... | feibl/search-rex | search_rex/views.py | Python | mit | 10,635 |
"""
Handler for user Register: Inherits from Signup
Completes the registration of a user i.e. put()
of use details to ndb
"""
# [START imports]
from myapp.handlers.signup import SignUp
from myapp.models.user import *
from myapp.tools.hcookie import make_secure_val
# [END imports]
# [START Register]
class Register(Si... | cubiio/fsnd-blog | myapp/handlers/register.py | Python | mit | 1,200 |
"""Extension controller for working with extensions in the pod."""
from grow.common import extensions as common_extensions
from grow.extensions import core
from grow.extensions import hooks
from grow.extensions import hook_controller
class ExtensionController(object):
"""Controller for working with pod extensions... | grow/pygrow | grow/extensions/extension_controller.py | Python | mit | 2,425 |
from setuptools import setup, find_packages
from codecs import open
from os import path
#from wmtexe.commands.configure import Configure
#from wmtexe.commands.install import Install
_HERE = path.abspath(path.dirname(__file__))
def read(*names, **kwds):
return open(
path.join(_HERE, *names),
en... | bmi-forum/bmi-builder | setup.py | Python | mit | 1,248 |
import copy
import multiprocessing
import os
from pathlib import PurePath
import subprocess
import sys
import tempfile
from textwrap import dedent
import unittest
try:
from unittest.mock import MagicMock
except:
from mock import MagicMock
from green import cmdline
class TestFinalizer(unittest.TestCase):
... | CleanCut/green | green/test/test_integration.py | Python | mit | 1,664 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import glob
import csv
"""Grab the country-codes out of already existing txt-files which
contain the results of 'whois' and write them in a csv-file ordered
descending by occurance"""
# define an empty list to store the temporary results
country_list = []
# assuming that ev... | alex-gehrig/geoextractor | geoextractor.py | Python | mit | 1,803 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-07 15:11
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 = [
migrations... | HaroldMills/Vesper | vesper/django/app/migrations/0001_initial.py | Python | mit | 25,902 |
from unittest import mock
from git_code_debt.server.presentation.commit_delta import CommitDelta
def test_commit_delta_not_overriden():
overrides = {'OtherMetric'}
ret = CommitDelta.from_data('MyMetric', mock.sentinel.delta, overrides)
assert ret == CommitDelta('MyMetric', '', mock.sentinel.delta)
def ... | Yelp/git-code-debt | tests/server/presentation/commit_delta_test.py | Python | mit | 566 |
'''Sympy to numpy code generator.'''
from .metafun import getmaskarray
__all__ = ['getmaskarray']
| dimasad/sym2num | sym2num/__init__.py | Python | mit | 102 |
# -*- coding: utf-8 -*-
from django import forms
from apps.blog import models
class PostForm(forms.ModelForm):
class Meta:
model = models.Post
exclude = ['last_change']
| python-uni/tutorial-django | tutorial/apps/blog/forms.py | Python | mit | 191 |
class Solution(object):
def reverse(self, x):
MIN_INT32_VALUE = -(2 ** 31)
MAX_INT32_VALUE = 2 ** 31 - 1
# 去除符號
x, sign = abs(x), x < 0
# 數字顛倒
revx = 0
while x:
x, revx = x // 10, revx * 10 + x % 10
# 將符號補上
... | RevansChen/online-judge | LeetCode/Easy/7_reverse-integer/Python/solution1.py | Python | mit | 510 |
# -*- coding: utf-8 -*-
"""
Implementation of http://elementalselenium.com/tips/2-download-a-file
"""
import os
import time
import shutil
import tempfile
import unittest
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
class Download(unittest.TestCase):
def setUp(self):
... | tourdedave/elemental-selenium-tips | 02-download-a-file/python/download.py | Python | mit | 1,609 |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django import forms
from django.contrib.admin import widgets
from bookings.models import Booking
from providers.models import ProviderService
class CreateBookingForm(forms.ModelForm):
booked_for = forms.DateTimeField()
cl... | aniruddha-adhikary/bookit | bookit/bookings/forms.py | Python | mit | 1,507 |
# Unit testing framework
import unittest
import mock
# System under test
from chronicle import Messenger
# Standard modules
# External modules
# chronicle modules
from chronicle.messenger import MessengerAttributeError
class MessengerBaseTests(unittest.TestCase):
def setUp(self):
self.core_object = se... | nkashy1/chronicle | test/test_Messenger.py | Python | mit | 4,559 |
# -*- coding: latin-1 -*-
"""Heap queue algorithm (a.k.a. priority queue).
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
all k, counting elements from 0. For the sake of comparison,
non-existing elements are considered to be infinite. The interesting
property of a heap is that a[0] is always ... | Voluntarynet/BitmessageKit | BitmessageKit/Vendor/static-python/Lib/heapq.py | Python | mit | 18,299 |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class ValidationRequestTestCase... | twilio/twilio-python | tests/integration/api/v2010/account/test_validation_request.py | Python | mit | 1,584 |
#####################################################################
# #
# File: qbo.py #
# Developer: Justin Leto #
# #
# qbo class provides an interface from main csv iterator method #
# to handle qbo formatting, validations, and writing to file. #
# ... | Airbitz/airbitz-ofx | qbo.py | Python | mit | 7,851 |
import numpy as np
from numba import guvectorize
@guvectorize(['void(float64[:], intp[:], float64[:])'], '(n),()->(n)')
def move_mean(a, window_arr, out):
window_width = window_arr[0]
asum = 0.0
count = 0
for i in range(window_width):
asum += a[i]
count += 1
out[i] = asum / cou... | joseph-ai/aitoolkit | examples/numba_ex1.py | Python | mit | 527 |
from .base import BaseCommand
class TermvectorCommand(BaseCommand):
command_name = "elasticsearch:termvector"
def run_request(self, id=None):
if id is None:
self.show_input_panel("Document Id (option): ", "", self.run)
return
options = dict(
index=self.set... | KunihikoKido/sublime-elasticsearch-client | commands/termvector.py | Python | mit | 489 |
# Copyright 2017 Merkulov Alexey
#
# The MIT License
#
# 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, mer... | steelart/ask-navalny | django-backend/askp/models.py | Python | mit | 4,982 |
#!/usr/bin/python
# Copyright 2012, 2013 Andrew Lamoureux
#
# This file is a part of FunChess
#
# FunChess 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 3 of the License, or
# (at your option... | thompGIT/chesster | ChessLogic/ChessMove.py | Python | mit | 2,153 |