code stringlengths 1 199k |
|---|
from django.urls import path
from . import views
urlpatterns = [
path('upload__/', views.upload__, name='lbattachment_upload__'),
path('delete__/', views.delete__, name='lbattachment_delete__'),
path('change_descn__/', views.change_descn__, name='lbattachment_change_descn__'),
path('download/', views.do... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from datetime import datetime
import inspect
import requests
import sys
from threading import Thread
import time
import traceback
import csv
from decimal import Decimal
fr... |
import os
try:
# Python 2.7
import ConfigParser as configparser
except ImportError:
# Python 3
import configparser
basedir = os.path.abspath(os.path.dirname(__file__))
def _get_bool_env_var(varname, default=None):
value = os.environ.get(varname, default)
if value is None:
return False
... |
from setuptools import find_packages, setup
from django_mailbox import __version__ as version_string
tests_require = [
'django',
'mock',
]
gmail_oauth2_require = [
'python-social-auth',
]
setup(
name='django-mailbox',
version=version_string,
url='http://github.com/coddingtonbear/django-mailbox/'... |
class pidpy(object):
ek_1 = 0.0 # e[k-1] = SP[k-1] - PV[k-1] = Tset_hlt[k-1] - Thlt[k-1]
ek_2 = 0.0 # e[k-2] = SP[k-2] - PV[k-2] = Tset_hlt[k-2] - Thlt[k-2]
xk_1 = 0.0 # PV[k-1] = Thlt[k-1]
xk_2 = 0.0 # PV[k-2] = Thlt[k-1]
yk_1 = 0.0 # y[k-1] = Gamma[k-1]
yk_2 = 0.0 # y[k-2] = Gamma[k-1]
... |
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for data in [b'Michael', b'Tracy', b'Sarah']:
# 发送数据:
s.sendto(data, ('127.0.0.1', 9999))
# 接收数据:
print(s.recv(1024).decode('utf-8'))
s.close() |
import io
import random
import picamera
def motion_detected():
# Randomly return True (like a fake motion detection routine)
return random.randint(0, 10) == 0
camera = picamera.PiCamera()
stream = picamera.PiCameraCircularIO(camera, seconds=20)
camera.start_recording(stream, format='h264')
count = 3
try:
wh... |
import gameowfication.__main__
if __name__ == "__main__":
gameowfication.__main__.main() |
import json
import urllib2
import datetime
from helpers import *
def ip_info(player):
data = json.load(urllib2.urlopen("http://ipinfo.io%s/json" % str(player.getAddress().getAddress())))
return data
def get_first_join(player):
first_join = int(player.getFirstPlayed())
dt = datetime.datetime.fromtimestamp(first_... |
from django.conf.urls import url
from django.views.generic import RedirectView
from . import views
from ext2020 import views as ext2020_views
urlpatterns = [
url(r'^schedule/$', views.ScheduleView.as_view(), name='events_schedule'),
url(r'^schedule/new/$', views.ScheduleCreateView.as_view()),
url(r'^talks/$... |
import sys
import os
from binascii import b2a_hex
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer... |
"""
:mod:`zsl.cache.id_helper`
--------------------------
.. moduleauthor:: Martin Babka
"""
from __future__ import unicode_literals
import abc
from builtins import object
import json
from future.utils import with_metaclass
from zsl.db.model.app_model import AppModel
from zsl.db.model.app_model_json_decoder import get_... |
"""
FINISHED, William Brynildsen
"""
from Bio import SeqIO
import sys, argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=
'')
parser.add_argument('-i', '--input', action='store', help='', type=argparse.FileType('r'), default = '-')
parser.add_argument('-c', '--classy', action='store',... |
from odoo import api, models
from odoo.addons.website.models.website import slugify
class SEOURL(models.AbstractModel):
_name = "website_seo_url"
_seo_url_field = "seo_url"
@api.model
def _check_seo_url(self, vals, record_id=0):
field = self._seo_url_field
vals = vals or {}
value... |
from math import pi
import torch
import time
import unittest
import gpytorch
from gpytorch.test.base_test_case import BaseTestCase
try:
import pyro
class ClusterGaussianLikelihood(gpytorch.likelihoods.Likelihood):
def __init__(self, num_tasks, num_clusters, name_prefix=str(time.time()), reparam=False):
... |
def request_page(page_to_request, site, config):
import GetAssets
import Request
from collections import ChainMap
from Config import PageDefaults
from Uri import UriBuilder
def do_request():
if page_config["method"] == "GET":
return Request.get_request(full_uri, site, config,... |
n = int(input().strip())
X = list(map(float, input().split()))
Y = list(map(float, input().split()))
Xs = sorted(X)
Ys = sorted(Y)
rx = [(Xs.index(k)+1) for k in X]
ry = [(Ys.index(l)+1) for l in Y]
sum = sum([ (rx[i] - ry[i]) ** 2 for i in range(n)])
r = 1- 6*sum / (n * ( n**2 -1 ))
print(round(r,3)) |
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = ['test_rotx.py']
self.test_suite = True
def run_tests(self):
#import here, cause outside... |
import redis
import json
import codecs
db = redis.Redis(host='localhost', port=6379, db=0)
with codecs.open('artist.json', 'r', 'utf_8') as json_data:
for line in json_data:
jsonData = json.loads(line)
if "name" in jsonData and "area" in jsonData:
db.set(jsonData["name"], jsonData["area"... |
from picamera.array import PiRGBArray
from gpiozero import MotionSensor
from twilio.rest import TwilioRestClient
from subprocess import call
import picamera
import numpy as np
import cv2
import time
face_cascade = cv2.CascadeClassifier(
'/home/pi/opencv-3.1.0/data/lbpcascades/lbpcascade_frontalface.xml')
MIN_FACE_C... |
"""
Django settings for core project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
BASE_DIR ... |
from string import Template
from datetime import date
bitcoinDir = "./";
inFile = bitcoinDir+"/share/qt/Info.plist"
outFile = "UnitedScryptCoin-Qt.app/Contents/Info.plist"
version = "unknown";
fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro"
for line in open(fileForGrabbingVersion):
lineArr = line.replac... |
__author__ = "Mari Wahl"
__copyright__ = "Copyright 2014"
__credits__ = ["Mari Wahl"]
__license__ = "GPL"
__version__ = "2.0"
__maintainer__ = "Mari Wahl"
__email__ = "marina.w4hl@gmail.com"
import numpy as np
import pylab as pl
from sklearn import neighbors, linear_model, svm, ensemble, naive_bayes, lda, qda, cross_va... |
BOT_NAME = 'Orienteering_Scraper'
SPIDER_MODULES = ['Orienteering_Scraper.spiders']
NEWSPIDER_MODULE = 'Orienteering_Scraper.spiders'
ITEM_PIPELINES = {
'scrapy.pipelines.images.ImagesPipeline': 1,
'Orienteering_Scraper.pipelines.MongoPipeline': 300
}
MONGO_DATABASE = 'Orienteering'
MONGO_URI = 'mongodb://local... |
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):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('asuntos', '0005_asunto_status'),
... |
def _sum_helper(given_list, start):
if start == len(given_list):
return 0
return given_list[start] + _sum_helper(given_list, start + 1)
def recursive_sum(given_list):
return _sum_helper(given_list, 0) |
"""Test Hebrew syllabification."""
from hebphonics.grammar import Parser
def test_empty():
"""syllabify an empty string"""
p = Parser()
assert [] == p.syllabify(p.parse(""))
def test_break_before_vowel():
"""syllable break before a vowel (syllable-before-vowel)"""
word = r"בָּרָא" # ba-ra
parts... |
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework.test import APIRequestFactory, force_authenticate
from rest_framework.viewsets import ModelViewSet
import permissions
from models import Whitelist
class IsStaffOrTargetUserTest(TestCase):
def setUp(self):
self.user = ... |
"""
[09/22/2014] Challenge #181 [Easy] Basic Equations
https://www.reddit.com/r/dailyprogrammer/comments/2h5b2k/09222014_challenge_181_easy_basic_equations/
Today, we'll be creating a simple calculator, that we may extend in later challenges. Assuming you have done basic
algebra, you may have seen equations in the form... |
import _plotly_utils.basevalidators
class DtickValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="dtick", parent_name="heatmap.colorbar", **kwargs):
super(DtickValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
"""Create Lagrange polynomials."""
import numpy
from scipy.special import comb
import numpoly
def lagrange(abscissas, graded=True, reverse=True, sort=None):
"""
Create Lagrange polynomial expansion.
Args:
abscissas (numpy.ndarray):
Sample points where the Lagrange polynomials shall be de... |
import sys
import os
import os.path as path
import subprocess as sp
import re
def run_test(test, check_tokens=True):
cmd = ['./build/install/svparse/bin/svparse', test]
pid = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
_, rawout = pid.communicate()
if pid.returncode != 0:
print rawout
return 1
if not check_t... |
n,m = list(map(int,input().split()))
print(1/n+(n-1)/n*(m-1)/(n*m-1)) |
from input import *
import numpy as np
from os import path
import skimage.io as skimgio
import PIL.Image
from PIL import Image
import imghdr
import random
import skimage as sk
import skimage.transform as sktf
from skimage.transform import SimilarityTransform
from skimage.transform import warp as skwarp
from img2d_utils... |
from ..plotting import *
import logging
import pytest
import os
logging.basicConfig(filename='test.log', level=logging.DEBUG)
wd = '../data'
out_dir = 'test_output'
slow = pytest.mark.skipif(
not pytest.config.getoption("--slow"),
reason="need --slow option to run"
)
if not os.path.exists(out_dir):
os.mkdir... |
"""Classes for creating a cover for an epub."""
import os
from xml.dom import minidom
import cv2
import numpy
import story_json as story_json_module
import util as util_module
import values as values_module
FONT_FACE = cv2.FONT_HERSHEY_COMPLEX
TITLE_FONT_SCALE = 3
AUTHOR_FONT_SCALE = 2
RATING_FONT_SCALE = 1
THICKNESS =... |
from .start_schema import StartSchema
from .brand_schema import BrandSchema
from .kind_schema import KindSchema
from .session_schema import SessionSchema
from .price_schema import PriceSchema
from .pricerange_schema import PriceRangeSchema
from .product_schema import ProductSchema
from .product_details_schema import Pr... |
import collections
from django.db import migrations, models
import django.db.models.deletion
import jsonfield.fields
import tests.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.C... |
import re
str1 = "An arbitrary string. Literal containing chars like: []{}!#$!@#!%ls813"
print " "
print str1
print " "
print "re.sub('[^A-Za-z0-9]+', '_', str1)"
print re.sub('[^A-Za-z0-9]+', '_', str1)
print " "
print "re.sub('[^A-Za-z0-9]', '_', str1)"
print re.sub('[^A-Za-z0-9]', '_', str1)
def replaceIt(str1):
... |
from django.apps import AppConfig
class PriceMonitorConfig(AppConfig):
name = 'price_monitor' |
"""Distutils setup script."""
import os
import setuptools
def _get_install_requires(fname):
return [req_line.strip() for req_line in open(fname)
if req_line.strip() and not req_line.startswith('#')]
def _get_version(fname):
import json
return json.load(open(fname, 'r'))['version']
def _get_long_... |
import os
import urllib
from google.appengine.ext import ndb
from webapp2_extras import sessions
from webapp2_extras import auth
from google.appengine.api import users
from models import User
import webapp2
import jinja2
TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), 'views')
jinja_environment = \
jinja2.En... |
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from ApplePie import *
from Utils import *
from ApplePieTk.subFrame.BaseFrame import *
class FrameExt(BaseFrame):
sVarExtList = []
sVarList = []
def __init__(self, parentFrame):
super().__init__(parentFrame)
s... |
"""
A minimal front end to the Docutils Publisher, producing HTML from PEP
(Python Enhancement Proposal) documents.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
description = ('Generates (X)HTML from reStructuredText-f... |
from bipy.log import setup_logging
from bipy.log import logger
from bipy.toolbox import macs
import sys
import yaml
import unittest
import os
from bcbio.utils import safe_makedir
STAGENAME = "macs"
class TestMacs(unittest.TestCase):
def setUp(self):
self.config_file = "test/macs/test_macs.yaml"
with... |
__author__ = 'study_sun'
import sys
import sqlite3
reload(sys)
sys.setdefaultencoding('utf-8')
from entity import IndexInfo, IndexConstituent
import os
import xlrd
from datetime import datetime
from spider_base.convenient import *
class IndexCollector(object):
DATABASE_TABLE_NAME = 'indexinfo'
DATABASE_NAME = '... |
from setuptools import setup
setup(
name='SLPP-23',
description='SLPP-23 is a simple lua-python data structures parser',
version='1.1',
author='Ilya Skriblovsky',
author_email='ilyaskriblovsky@gmail.com',
url='https://github.com/IlyaSkriblovsky/slpp-23',
license='https://github.com/IlyaSkrib... |
from __future__ import print_function
from __future__ import absolute_import
import wx
from matplotlib.backends.backend_wx import NavigationToolbar2Wx as NavigationToolbar
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
class GeneratedWireframe(wx.Fra... |
from .base import * # noqa
SECRET_KEY = ')#uqg@^y!&ei$l&l(*2ai3@+o8i+ju7vqryr6b+qtqq)na*#@='
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
STATIC_ROOT = 'static' |
from common.state import State
name = 'Finite difference method'
class Kinematics:
def __init__(self):
pass
def compute_new_state(self, state, acceleration, delta_time):
"Compute the forward kinematics with finite difference method."
new_state = State(state.ndim)
# Velocity (m/s)... |
import argparse
import vlc
import os
import mydb
instance = vlc.Instance()
mediaplayer = instance.media_player_new()
music_formats = ['.mp3','.flac','.mp4']
def init_parser():
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--path", help="Input music directory")
parser.add_argument("-u", "--up... |
import pprint
import json
from cgi import parse_qs, escape
html = """<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<link href='/static/synrc.css' type='text/css' rel='stylesheet'>
<link href='http://fonts.googleapis.com/css?family=Open+Sa... |
from unknown import Unknown
class CustomClass(object):
def keys(self):
return []
for key in Unknown().keys():
pass
for key in Unknown.keys():
pass
for key in dict.keys():
pass
for key in {}.values():
pass
for key in {}.key():
pass
for key in CustomClass().keys():
pass
[key for key in... |
from django.contrib import admin
from .models import Qualifier
@admin.register(Qualifier)
class QualifierAdmin(admin.ModelAdmin):
list_display = ('num', 'sub') |
import logging
from pyvisdk.exceptions import InvalidArgumentError
log = logging.getLogger(__name__)
def VmPortGroupProfile(vim, *args, **kwargs):
'''The VmPortGroupProfile data object represents the subprofile for a port group
that will be used by virtual machines. Use the policy list for access to
configu... |
s = raw_input("enter: ")
upper = 0
lower = 0
for i in s:
if i.isupper():
upper += 1
elif i.islower():
lower += 1
else:
pass
print "upper" , upper
print "lower" , lower |
"""
Support for interfacing to the Logitech SqueezeBox API.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.squeezebox/
"""
import logging
import telnetlib
import urllib.parse
import voluptuous as vol
from homeassistant.components.media_player... |
import os
from codecs import open
from os import path
from pathlib import Path
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
def read_requirements(path: str):
res = []
path =... |
"""
Wrapper for dbghelp.dll in ctypes.
"""
__revision__ = "$Id: dbghelp.py 1299 2013-12-20 09:30:55Z qvasimodo $"
from defines import *
from version import *
from kernel32 import *
_all = None
_all = set(vars().keys())
hdBase = 0
hdSym = 1
hdSrc = 2
UNDNAME_32_BIT_DECODE = 0x0800
UNDNAME_COMPLETE ... |
import tensorflow as tf
import time
batch_size = 128
epochs = 30
learning_rate = 0.1
momentum = 0.9
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape([x_train.shape[0], -1]).astype('float32') / 255
y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
x_test... |
from django.conf.urls import url
from .views import (BoxListView, BoxCreateView, BoxDeleteView, BoxSubmitView,
BoxCloseView)
urlpatterns = [
url(r'^$', BoxListView.as_view(), name="boxes_list"),
url(r'^create$', BoxCreateView.as_view(), name="boxes_create"),
url(r'^(?P<pk>[0-9]+)/delete$... |
class Calculator(object):
def __init__(self, nb1, nb2):
self.number1 = 0
self.number2 = 0
pass
def sum(self):
pass
def divide_sum_by(self, nb):
pass |
import json
import jinja2
from flask_debugtoolbar.panels import DebugPanel
from flask_debugtb_elasticsearch.utils import ThreadCollector
from elasticsearch.connection.base import Connection
collector = ThreadCollector()
old_log_request_success = Connection.log_request_success
_ = lambda x: x
def patched_log_request_suc... |
'''
Given a word, write a function that returns the first index and the last index of a character.
'''
def char_index(word, char):
return None if char not in word else [word.index(char), word.rindex(char)] |
from tkinter import *
class Application(Frame):
""" GUI application which can reveal the secret of longevity. """
def __init__(self, master):
""" Initialize the frame. """
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
... |
from __future__ import division
import hashlib
from hkdf import Hkdf
from .six import integer_types
from .util import (size_bits, size_bytes, unbiased_randrange,
bytes_to_number, number_to_bytes)
"""Interface specification for a Group.
A cyclic abelian group, in the mathematical sense, is a collectio... |
''' User's Twitter keys
Secret Twitter keys for the user that you want cozmo_reads_tweets.py to work with
To generate these you need to setup a Twitter account with developer keys:
1) Log into your Twitter account in your web browser (or create a new account if you prefer)
2) Go to https://apps.twitter.com/app... |
from .resource import Resource
class VirtualMachineExtension(Resource):
"""Describes a Virtual Machine Extension.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id
:vartype id: str
:ivar name: Resource name
:vartype name: str
:i... |
from django import forms
import itertools
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from .models import Episode, Program
class ProgramForm(forms.ModelForm):
class Meta:
model = Program
fields = (
'title',
'description',
... |
from logging import getLogger
import six
from django import template
from django.template.loader import get_template
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
from .filters import ChoicesFi... |
import argparse
from collections import defaultdict
import numpy
import pysam
def Parser():
the_parser = argparse.ArgumentParser()
the_parser.add_argument(
'--input', action="store", type=str, help="bam alignment file")
the_parser.add_argument(
'--minquery', type=int,
help="Minimum r... |
from cast.c_Parser import c_Parser
from cast.pp_Parser import pp_Parser
from cast.ParserCommon import Ast
from xtermcolor.ColorMap import XTermColorMap
class Token:
def __init__(self, id, resource, terminal_str, source_string, lineno, colno):
self.__dict__.update(locals())
def getString(self):
return self.s... |
from django.shortcuts import render
from django.template import loader
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from .forms import CustomUserChangeForm
@login_required()
def profile(request):
templa... |
'''
In this module, we find the kth smallest element in an array in O(n) time
'''
from quicksort import partition
def find_kth_smallest(alist, left,right, k):
if len(alist) == 1:
return alist[0]
pivot = partition(alist, left,right)
if k == pivot:
return alist[pivot]
if pivot > k:
return find_kth_smallest(ali... |
import sys
lines = open(sys.argv[1], 'r')
for line in lines:
line = line.replace('\n', '').replace('\r', '')
if len(line) > 0:
stack = []
result = True
for x in line:
if x == '(' or x == '[' or x == '{':
stack.append(x)
elif len(stack) == 0 or (sta... |
from __future__ import unicode_literals
from django.db.models import CharField
from accelerator_abstract.models.accelerator_model import AcceleratorModel
class BaseStartupRole(AcceleratorModel):
# Known Startup Roles
FINALIST = "Finalist"
ENTRANT = "Entrant"
FAST_TRACK = "Fast Track"
AIR = "Alum In ... |
import argparse
import javaproperties
import logging
import signal
import sys
from jog import JogFormatter
from kafka import KafkaConsumer
from prometheus_client import start_http_server
from prometheus_client.core import REGISTRY
from . import scheduler, collectors
from .fetch_jobs import setup_fetch_jobs
from .parsin... |
import re
import pytest
from mock import Mock, MagicMock
from mock import call, DEFAULT
REPR_PATTERN = r'''<Mock(?: name='(?P<name>.+)')? id='\d+'>'''
def mock_name(mock):
match = re.match(REPR_PATTERN, repr(mock))
return match.group('name')
def test_mock_and_magicmock():
assert issubclass(MagicMock, Mock)
... |
import sys, os
sys.path.insert(0, os.path.abspath('../../bt'))
sys.path.insert(0, os.path.abspath('_themes/klink'))
import klink
klink.convert_notebooks()
html_theme_path = ['_themes/klink']
html_theme = 'klink'
html_theme_options = {
'github': 'pmorissette/bt',
'analytics_id': 'UA-52308448-3'
}
extensions = ['... |
from django import forms
from users.models import LeaderUser
class LeaderForm(forms.Form):
username = forms.CharField(label='Username', max_length=8, min_length=8)
first_name = forms.CharField(label='First Name', max_length=30)
last_name = forms.CharField(label='Last Name', max_length=30)
email = forms.... |
from PyQt5 import QtCore, QtWidgets #, QtGui
class DatcomCASEEditerUi(object):
def setupUi(self, Dialog):
Dialog.setObjectName("DatcomCASEEditerUi")
#Dialog.resize(900, 500)
Dialog.setSizeGripEnabled(True)
self.horizontalLayout = QtWidgets.QHBoxLayout(Dialog)
self.horizontalL... |
import json
from textwrap import dedent
import hypothesis.strategies as st
from hypothesis import example, given
import pytest
def test_simple_run(tmpdir, runner):
runner.write_with_general(dedent('''
[pair my_pair]
a = "my_a"
b = "my_b"
collections = null
[storage my_a]
type = "filesystem"
... |
import os
import re
import logging
import unicodedata
from trovebox import Trovebox
from trovebox.errors import TroveboxError, TroveboxDuplicateError
from progressbar import ProgressBar, Percentage, Bar, ETA, FileTransferSpeed
SKIP_HIDDEN = True
def is_hidden(filename):
return (filename.startswith('.') and SKIP_HID... |
""" Tests for register allocation for common constructs
"""
import py
import re, sys, struct
from rpython.jit.metainterp.history import TargetToken, BasicFinalDescr,\
JitCellToken, BasicFailDescr, AbstractDescr
from rpython.jit.backend.llsupport.gc import GcLLDescription, GcLLDescr_boehm,\
GcLLDescr_framework... |
from __future__ import absolute_import
import numpy as np
from plotly import optional_imports
from plotly.tests.utils import is_num_list
from plotly.utils import get_by_path, node_generator
import copy
matplotlylib = optional_imports.get_module("plotly.matplotlylib")
if matplotlylib:
import matplotlib
# Force m... |
""" Downloads eBooks from Apress """
import requests
import os
import re
import bs4
import HTMLParser
import logging
VERSION = 1.0
class ApressDownloader(object):
""" Handles downloading eBooks you own from Apress.com """
def __init__(self, overwrite=False, parser='html.parser'):
self.request = requests... |
import sys
from pyswip.core import *
class PrologError(Exception):
pass
class NestedQueryError(PrologError):
"""
SWI-Prolog does not accept nested queries, that is, opening a query while
the previous one was not closed.
As this error may be somewhat difficult to debug in foreign code, it is
auto... |
from octopus.runtime import *
from octopus.sequence.util import Trigger
from twisted.internet import reactor
def fn ():
print "fn called"
return sequence(
log("fn called"),
set(v, False)
)
v = variable(False, "v", "v")
v2 = variable(False, "v", "v")
o1 = Trigger(v == True, fn)
o2 = Trigger(v2 == True, log("o2 tr... |
import msrest.serialization
class AccessPolicyEntry(msrest.serialization.Model):
"""An identity that have access to the key vault. All identities in the array must use the same tenant ID as the key vault's tenant ID.
All required parameters must be populated in order to send to Azure.
:param tenant_id: Requ... |
from flask import flash, jsonify, redirect, render_template, request, session
from itsdangerous import BadData, BadSignature
from markupsafe import Markup
from webargs import fields
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from indico.core import signals
from indico.core.auth import login_rate_li... |
import parsing.grammar
import parsing.lr_zero
import parsing.lalr_one
__all__ = ['grammar', 'lr_zero', 'lalr_one'] |
def load(n):
hof=[0, 1, 1]
for i in range(3,n+1):
hof.append(hof[i - hof[i-1]] + hof[i - hof[i-2]])
return hof
def hofstadter_Q(n):
hof = load(n)
return hof[n] |
from __future__ import absolute_import
import numpy as np
from pyti import catch_errors
from pyti.function_helper import fill_for_noncomputable_vals
from six.moves import range
def aroon_up(data, period):
"""
Aroon Up.
Formula:
AROONUP = (((PERIOD) - (PERIODS since PERIOD high)) / (PERIOD)) * 100
""... |
import requests
class Communicator:
def __init__(self, configuration):
self.configuration = configuration
self.api_infos = None
self.cookies = {}
self.authenticated = False
def __del__(self):
if self.authenticated:
self.logout()
def get_dl_task_list(self):... |
import ipLookup
if __name__ == '__main__':
ipList = {}
ip = '91.22.128.66'
ip = '85.164.178.87'
if ip not in ipList:
ipList.update({ip:ipLookup.ipLookup(ip)})
address = ipList[ip]
print(address) |
import os
from mushroom_rl.utils.preprocessors import MinMaxPreprocessor
from mushroom_rl.utils.callbacks import PlotDataset
import numpy as np
from mushroom_rl.algorithms.policy_search import REINFORCE
from mushroom_rl.approximators.parametric import LinearApproximator
from mushroom_rl.approximators.regressor import R... |
"""
*Perform a conesearch on a database table with existing HTMId columns pre-populated*
:Author:
David Young
"""
from __future__ import print_function
from __future__ import division
from future import standard_library
standard_library.install_aliases()
from builtins import zip
from builtins import str
from builti... |
import struct, binascii
from collections import namedtuple
from PIL import Image, ImageOps
Level = namedtuple('Level', ['char', 'density_abs', 'density', 'rank'])
class Font:
def __init__(self, img_file, dark=False, invert=False, normalize_r=0.3):
img = Image.open(img_file, 'r')
img = img.convert('L... |
import logging
import sys
import yaml
from svtplay_dl.service.cmore import Cmore
from svtplay_dl.utils.getmedia import get_media
from svtplay_dl.utils.getmedia import get_multiple_media
from svtplay_dl.utils.parser import parser
from svtplay_dl.utils.parser import parsertoconfig
from svtplay_dl.utils.parser import setu... |
"""
Launches the target process after setting a breakpoint at a convenient
entry point.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import shlex
import gdb
import pwndbg.commands
import pwndbg.el... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.