code stringlengths 1 199k |
|---|
from __future__ import unicode_literals
import frappe, os, re
from frappe.utils import touch_file, encode, cstr
def make_boilerplate(dest, app_name):
if not os.path.exists(dest):
print "Destination directory does not exist"
return
# app_name should be in snake_case
app_name = frappe.scrub(app_name)
hooks = frap... |
"""
This script adds a missing references section to pages.
It goes over multiple pages, searches for pages where <references />
is missing although a <ref> tag is present, and in that case adds a new
references section.
These command line parameters can be used to specify which pages to work on:
¶ms;
-xml ... |
import os
import module
from flask import Flask, render_template, request, session, redirect, url_for, send_from_directory
from werkzeug import secure_filename
from functools import wraps
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = set(['chessley']) # Change this to... |
"""
* Created by Synerty Pty Ltd
*
* This software is open source, the MIT license applies.
*
* Website : http://www.synerty.com
* Support : support@synerty.com
"""
RPC_PRIORITY = 10
DEFAULT_PRIORITY = 100 |
from collections.abc import Sequence
from numbers import Number
from . import Validator, Length, Range, Instance
from .compound import All
class Latitude(All):
"""Validate the given value as a number between -90 and +90 in decimal degrees, representing latitude."""
validators = [
Instance(Number),
Range(-90, 90... |
import _plotly_utils.basevalidators
class LegendrankValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="legendrank", parent_name="scatter", **kwargs):
super(LegendrankValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
from havocbot.common import catch_exceptions
from havocbot.plugin import HavocBotPlugin
import imp
import logging
import os
logger = logging.getLogger(__name__)
class StatefulPlugin:
def __init__(self, havocbot, name, path):
self.path = path
self.name = name
self.handler = None
self.... |
from django.core.management.base import BaseCommand
from stream_analysis.utils import cleanup
class Command(BaseCommand):
"""
Removes streaming data we no longer need.
"""
help = "Removes streaming data we no longer need."
def handle(self, *args, **options):
cleanup() |
"""
@author: Matthias Feys (matthiasfeys@gmail.com)
@date: %(date)
"""
import theano
class Layer(object):
def __init__(self,name, params=None):
self.name=name
self.input = input
self.params = []
if params!=None:
self.setParams(params=params.__dict__.get(name))
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def xavier_init(fan_in, fan_out, constant=1):
""" Xavier initialization of network weights"""
# https://stackoverflow.com/questions/33640581/how-to-do-xavier-initiali... |
"""Basic contact management functions.
Contacts are linked to monitors and are used to determine where to send
alerts for monitors.
Contacts are basic name/email/phone sets.
Contacts are only stored in the database and not in memory, they are loaded
from the database each time an alert is sent.
"""
from typing import D... |
from app import db
db.create_all() |
import os
import numpy as np
from cereal import car
from common.numpy_fast import clip, interp
from common.realtime import sec_since_boot
from selfdrive.swaglog import cloudlog
from selfdrive.config import Conversions as CV
from selfdrive.controls.lib.drive_helpers import create_event, EventTypes as ET, get_events
from... |
import os
import sys
import argparse
import pat3dem.star as p3s
def main():
progname = os.path.basename(sys.argv[0])
usage = progname + """ [options] <a star file>
Write two star files after screening by an item and a cutoff in the star file.
Write one star file after screening by a file containing blacklist/whitel... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
total = 0
def dfs(root, p, gp):
if root is None:
return
nonlocal total
... |
__author__ = 'xubinggui'
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print(self.score)
bart = Student('Bart Simpson', 59)
bart.print_score() |
import _plotly_utils.basevalidators
class UirevisionValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="uirevision", parent_name="heatmap", **kwargs):
super(UirevisionValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import time
class RecordAccumulator(object):
def __init__(self, buffer_class, config):
self.config = config
self.buffer_time_limit = config['buffer_time_limit']
self._buffer_class = buffer_class
self._reset_buffer()
def _reset_buffer(self):
self._buffer = self._buffer_cla... |
from pysnmp.entity.rfc3413.oneliner import cmdgen
import shlex
import subprocess
import re
import os
import sys
import smtplib
from devices.models import AP as AccessPoint
def snmpwalk(OIDs, controllers):
APs = dict()
cmdGen = cmdgen.CommandGenerator()
for key in OIDs:
for controller in controllers:... |
import json
from rest_framework.renderers import JSONRenderer
class CustomJSONRenderer(JSONRenderer):
charset = 'utf-8'
object_label = 'object'
pagination_object_label = 'objects'
pagination_count_label = 'count'
def render(self, data, media_type=None, renderer_context=None):
if data.get('re... |
"""Support for Melnor RainCloud sprinkler water timer."""
from __future__ import annotations
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_MONITORED_CONDITIONS
from homeassistant.core import HomeAssistant
import hom... |
from __future__ import absolute_import, division, print_function
import numpy as np
import matplotlib.pyplot as plt
from ..basics.map import Map
from .plotter import Plotter
from ..tools.logging import log
from ..tools import filesystem as fs
class MemoryPlotter(Plotter):
"""
This class ...
"""
def __in... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_propeller_demo.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
#... |
'''
A condition
'''
from base import Base
from compares import const
class ComparisonMixin(object):
'''
Compare two values with a comparison utility
to denote if a change has validated.
'''
def compare(self, a, b, ctype=None):
'''
compare 'a' against 'b' for a comparison of `ctype`
... |
import sys
import os
import shlex
from b3j0f.sync import __version__
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.pngmath',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
]
templates_path = ['_te... |
from google.appengine.api import mail
import json
import webapp2
class SendEmail(webapp2.RequestHandler):
def post(self):
to = self.request.get("to")
user_name = self.request.get("name")
user_address = self.request.get("email")
subject = self.request.get("subject")
body = sel... |
from django.shortcuts import render
from django.conf.urls import patterns, url
from django.core.urlresolvers import reverse_lazy
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
from edamame import base, utils, generic
from . import models
class SiteViews(base.View... |
import matplotlib.pyplot as plt
import numpy as np
from phuzzy.mpl import TruncNorm
def test_truncnorm():
alpha0 = [0, 2]
# alpha1 = [2]
p = TruncNorm(alpha0=alpha0, alpha1=None, number_of_alpha_levels=7)
print(p)
print(p.df)
print(p.df.values.tolist())
ref = [[0.0, 0.0, 2.0], [0.16666666666... |
import functools
from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transp... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, COIN
from io import BytesIO
def txFromHex(hexstring):
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(hexstring))
tx.deserialize(f)
return tx
class ListTran... |
from __future__ import (
unicode_literals,
absolute_import,
print_function,
division,
)
import aaf2
import traceback
import subprocess
import json
import os
import datetime
import sys
import tempfile
import shutil
import time
import fractions
from aaf2 import auid
from pprint import pprint
FFMPEG_EX... |
from helper import greeting
greeting("hello world...") |
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="color", parent_name="histogram2dcontour.textfont", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_nam... |
"""
Entry point to API application. This will be for running simple checks on the application
"""
from flask import jsonify, url_for, redirect, request
from flask_login import current_user
from . import home
from ..__meta__ import __version__, __project__, __copyright__
@home.route("")
@home.route("home")
@home.route("... |
import unittest
from usig_normalizador_amba.Callejero import Callejero
from usig_normalizador_amba.Partido import Partido
from usig_normalizador_amba.Calle import Calle
from tests.test_commons import cargarCallejeroEstatico
class CallejeroTestCase(unittest.TestCase):
p = Partido('jose_c_paz', 'José C. Paz', 'Partid... |
from huzzer.function_generator import generate_expression, generate_unary_expr
from huzzer.expressions import VariableExpression, FunctionExpression, BRANCH_EXPRESSIONS
from huzzer.namers import DefaultNamer
from huzzer import INT, BOOL
empty_variables = {
INT: [],
BOOL: []
}
def test_generate_unary_expr():
... |
"""
Created on Thu Apr 21 22:48:37 2016
@author: burger
"""
import numpy as np
from matplotlib import pyplot as plt
def sigma(x, a=1, b=0):
return 1/(1+np.exp(-(a*x+b)))
x = np.asarray([[0.0, .1], [0, 1], [.9, .05], [.9, .95]])
markers = 'v<>^'
a = .5*np.ones((2,))
proj = np.dot(x, a)
def trafo(x, y):
return si... |
"""Utility methods for flake8."""
import collections
import fnmatch as _fnmatch
import inspect
import io
import logging
import os
import platform
import re
import sys
import tokenize
from typing import Callable, Dict, Generator, List, Optional, Pattern
from typing import Sequence, Set, Tuple, Union
from flake8 import e... |
import unittest
"""
Test for the local and the web html page for table table generation
"""
class TestNET(unittest.TestCase):
def test_net(self):
pass
if __name__ == "__main__":
unittest.main() |
bind = '0.0.0.0:8000'
workers = 3
accesslog = '-'
errorlog = '-'
access_log_format = '{"request": "%(r)s", "http_status_code": "%(s)s", "http_request_url": "%(U)s", "http_query_string": "%(q)s", "http_verb": "%(m)s", "http_version": "%(H)s", "http_referer": "%(f)s", "x_forwarded_for": "%({x-forwarded-for}i)s", "remote_... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Team',
fields=[
('id', models.AutoField(auto_created=True... |
"""Hello World API implemented using Google Cloud Endpoints.
Defined here are the ProtoRPC messages needed to define Schemas for methods
as well as those methods defined in an API.
"""
import endpoints
from protorpc import messages, message_types, remote # TODO remove messages and message types when possible
from googl... |
__all__ = ['BaseConstructor', 'SafeConstructor', 'Constructor',
'ConstructorError']
from error import *
from nodes import *
import datetime
import binascii, re, sys, types
class ConstructorError(MarkedYAMLError):
pass
class BaseConstructor(object):
yaml_constructors = {}
yaml_multi_constructors = {}
... |
"""
WSGI config for Texas LAN Web project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... |
def unique_elems(data):
found_numbers = {}
for number in data:
if number not in found_numbers:
found_numbers[number] = number
else:
return False
return True |
from typing import Any, Collection, Dict, List, Optional, overload
from ..language import Node, OperationType
from ..pyutils import is_iterable
__all__ = ["ast_to_dict"]
@overload
def ast_to_dict(
node: Node, locations: bool = False, cache: Optional[Dict[Node, Any]] = None
) -> Dict:
...
@overload
def ast_to_di... |
import time
from socketio import packet
def test():
p = packet.Packet(packet.EVENT, 'hello')
start = time.time()
count = 0
while True:
p = packet.Packet(encoded_packet=p.encode())
count += 1
if time.time() - start >= 5:
break
return count
if __name__ == '__main__'... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
import re
import xmlrpc.client
from flexget import plugin
from flexget.event import event
from flexget.utils.template import RenderError
from flexget.plugin import... |
import unittest
import os
from latexbuild.utils import (
random_str_uuid,
random_name_filepath,
list_filepathes_with_predicate,
read_file,
recursive_apply,
)
PATH_FILE = os.path.abspath(__file__)
PATH_TEST = os.path.dirname(PATH_FILE)
class TestRandomStrUuid(unittest.Test... |
__author__ = 'oier'
import json
from flask import Flask, make_response
app = Flask(__name__)
import seaborn as sns
import numpy as np
import pandas as pd
import os
from datetime import datetime
import matplotlib.pyplot as plt
import sys
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import Fi... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"""Write your forwards methods here."""
# Replace all null values with blanks
orm.TweetChunk.obj... |
from typing import Dict, List, Optional, Union
from azure.core.exceptions import HttpResponseError
import msrest.serialization
from ._dev_spaces_management_client_enums import *
class ContainerHostMapping(msrest.serialization.Model):
"""Container host mapping object specifying the Container host resource ID and its... |
"""
.. module:: CreateProfileForm
:synopsis: A form for completing a user's profile.
.. moduleauthor:: Dan Schlosser <dan@schlosser.io>
"""
from flask.ext.wtf import Form
from wtforms import StringField, HiddenField
from wtforms.validators import URL, Email, Required
EMAIL_ERROR = 'Please provide a valid email addr... |
def createVocabList(dataSet):
vocabSet = set([])
for document in dataSet:
vocabSet = vocabSet | set(document)
return list(vocabSet)
def setOfWords2Vec(vocablist,inputset):
returnVec = [0] * len(vocablist)
for word in inputset:
if word in vocablist:
returnVec[vocablist.in... |
import unittest
class UnitParsingTest(unittest.TestCase):
def _assert_meters(self, tag_value, expected):
from vectordatasource.meta.function import mz_to_float_meters
parsed = mz_to_float_meters(tag_value)
if parsed is None and expected is not None:
self.fail("Failed to parse %r,... |
import glob
import os
import subprocess
'''
Convert 23andMe files to
PLINK format
'''
def twenty3_and_me_files():
"""Return the opensnp files that are 23 and me format"""
all_twenty3_and_me_files= glob.glob('../opensnp_datadump.current/*.23andme.txt')
fifteen_mb = 15 * 1000 * 1000
non_junk_files = [path for path in... |
import _plotly_utils.basevalidators
class NticksValidator(_plotly_utils.basevalidators.IntegerValidator):
def __init__(
self, plotly_name="nticks", parent_name="layout.ternary.baxis", **kwargs
):
super(NticksValidator, self).__init__(
plotly_name=plotly_name,
parent_name=... |
import unittest
import warnings
from collections import OrderedDict
import numpy as np
import numpy.testing as np_test
from pgmpy.extern.six.moves import range
from pgmpy.factors.discrete import DiscreteFactor
from pgmpy.factors.discrete import JointProbabilityDistribution as JPD
from pgmpy.factors import factor_divide... |
import sys
import tokenize
from functools import reduce
global_card = []
num_vars = 0
''' Calc Strides
'''
def calcStrides( scope ):
rev_scope = list( reversed( scope ) )
res = [ 1 ] + [ 0 ] * ( len( scope ) - 1 )
for idx in range( 1, len( rev_scope ) ):
res[ idx ] = res[ idx - 1 ] * global_card[ rev_scope[ idx - ... |
import unittest
import json
from api_health.verifier import Verifier
class JsonVerifier(unittest.TestCase):
def test_constructor_should_be_smart_about_params(self):
simple_json = u'{ "foo": "bar" }'
json_dict = json.loads(simple_json)
try:
v1 = Verifier(simple_json)
v... |
from props.graph_representation.word import Word,NO_INDEX, strip_punctuations
import cgi
from copy import deepcopy
from props.dependency_tree.definitions import time_prep, definite_label,\
adjectival_mod_dependencies
COPULA = "SAME AS" # the textual value of a copula node
PROP = "PROP" # the textu... |
"Assignment 5 - This defines a topology for running a firewall. It is not \
necessarily the topology that will be used for grading, so feel free to \
edit and create new topologies and share them."
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import CPULimitedHost, RemoteCont... |
from application import CONFIG, app
from .models import *
from flask import current_app, session
from flask.ext.login import login_user, logout_user, current_user
from flask.ext.principal import Principal, Identity, AnonymousIdentity, identity_changed, identity_loaded, RoleNeed
import bcrypt
import re
import sendgrid
i... |
"""
WSGI config for first_app 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.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "first_app.settings")
from django.core.w... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.ticker as ticker
r = mlab.csv2rec('data/imdb.csv')
r.sort()
r = r[-30:] # get the last 30 days
N = len(r)
ind = np.arange(N) # the evenly spaced plot indices
def format_date(x, pos=None):
thisind = np.clip(int(x+0.... |
from . import base_service
from .. import resources
from ..paginator import Paginator
from .. import errors
class MandatePdfsService(base_service.BaseService):
"""Service class that provides access to the mandate_pdfs
endpoints of the GoCardless Pro API.
"""
RESOURCE_CLASS = resources.MandatePdf
RES... |
"""
@file
@brief image et synthèse
"""
from .image_synthese_facette import Rectangle
from .image_synthese_base import Rayon, Couleur
from .image_synthese_sphere import Sphere
class RectangleImage(Rectangle):
"""définit un rectangle contenant un portrait"""
def __init__(self, a, b, c, d, nom_image, pygame, inver... |
"""
Performs recurrence analysis of paleoclimate proxy records.
This script provides analyses for this publication:
J.F. Donges, R.V. Donner, N. Marwan, S.F.M. Breitenbach, K. Rehfeld, and J. Kurths,
Nonlinear regime shifts in Holocene Asian monsoon variability: Potential impacts on cultural change and migratory patter... |
"""
http://coreygoldberg.blogspot.com/2013/01/python-matrix-in-your-terminal.html
Create "The Matrix" of binary numbers scrolling vertically in your terminal.
original code adapted from juancarlospaco:
- http://ubuntuforums.org/showpost.php?p=10306676
Inspired by the movie: The Matrix
- Corey Goldberg (2013)
Requir... |
from __future__ import division
import math
import numpy as np
from time import time
import sympy as sp
import mpmath as mp
from mpmath.ctx_mp_python import mpf
from scipy.misc import factorial
from scipy.special import gamma
precision = 53
mp.prec = precision
mp.pretty = True
def calculate_factorial_ratio(n, i):
# Th... |
"""Contains the :code:`Address` class, representing a collection of reverse
geocoding results. Primarily, this functions as a container for a set of
:code:`errorgeopy.Location` objects after a successful reverse geocode, and
exposes methods that operate on this set of results, including:
- de-duplication
- extracting t... |
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from core.base_processor import xBaseProcessor
from utilities.export_helper import xExportHelper
from utilities.file_utility import xFileUtility
from definitions.constant_data import xConstantData
class xProcessorPhp(xBaseProcessor... |
from __future__ import unicode_literals
import datetime
from frappe import _
import frappe
import frappe.database
import frappe.utils
from frappe.utils import cint, flt, get_datetime, datetime, date_diff, today
import frappe.utils.user
from frappe import conf
from frappe.sessions import Session, clear_sessions, delete_... |
from .ui import *
from .windows_views import * |
from collections import OrderedDict
import logging
import json
import re
import itertools
import sublime
import sublime_plugin
from ..lib import inhibit_word_completions
from .commandinfo import (
get_command_name,
get_builtin_command_meta_data,
get_builtin_commands,
iter_python_command_classes,
get... |
import re
from bs4 import BeautifulSoup
from nose.tools import assert_equal, assert_in, assert_true
import pages
import requests
APP_URL = 'https://www.github.com'
ADMIN_CREDENTIALS = {'username': 'admin@example.com', 'password': 'pk$321'}
ROOT_CREDENTIALS = {'username': 'root', 'password': '123456'}
API_URLS_MAP = {
... |
import numpy as np
import lxml.etree as ET
from ...dates import timedelta
from ...orbits import StateVector
from ...orbits.man import ImpulsiveMan, ContinuousMan
from ...utils import units
from ...frames.orient import G50, EME2000, GCRF, MOD, TEME, TOD, CIRF
from .cov import load_cov, dump_cov
from .commons import (
... |
"""Startup utilities"""
import os
import sys
from functools import partial
import paste.script.command
import werkzeug.script
etc = partial(os.path.join, 'parts', 'etc')
DEPLOY_INI = etc('deploy.ini')
DEPLOY_CFG = etc('deploy.cfg')
DEBUG_INI = etc('debug.ini')
DEBUG_CFG = etc('debug.cfg')
_buildout_path = __file__
for ... |
import time
def import_grid(file_to_open):
grid = []
print(file_to_open)
with open(file_to_open) as file:
for i, line in enumerate(file):
if i == 0:
iterations = int(line.split(" ")[0])
delay = float(line.split(" ")[1])
else:
gr... |
import pytest
from robustus.detail import perform_standard_test
def test_bullet_installation(tmpdir):
tmpdir.chdir()
bullet_versions = ['bc2']
for ver in bullet_versions:
bullet_files = ['lib/bullet-%s/lib/libBulletCollision.a' % ver,
'lib/bullet-%s/lib/libBulletDynamics.a' %... |
"""Instruction descriptions for the "SPIR-V Extended Instructions for GLSL"
version 1.00, revision 2.
"""
INST_FORMAT = {
1 : {
'name' : 'Round',
'operands' : ['Id'],
'has_side_effects' : False,
'is_commutative' : False
},
2 : {
'name' : 'RoundEven',
'operands... |
from unittest import TestCase
from dirty_validators.basic import (BaseValidator, EqualTo, NotEqualTo, StringNotContaining, Length, NumberRange,
Regexp, Email, IPAddress, MacAddress, URL, UUID, AnyOf, NoneOf,
IsEmpty, NotEmpty, NotEmptyString, IsNon... |
from models.sampler import DynamicBlockGibbsSampler
from models.distribution import DynamicBernoulli
from models.optimizer import DynamicSGD
from utils.utils import prepare_frames
from scipy import io as matio
from data.gwtaylor.path import *
import ipdb
import numpy as np
SIZE_BATCH = 10
EPOCHS = 100
SIZE_HIDDEN = 50
... |
import sys
import os, os.path
import shutil
from optparse import OptionParser
import cocos
from MultiLanguage import MultiLanguage
import cocos_project
import json
import re
from xml.dom import minidom
import project_compile
BUILD_CFIG_FILE="build-cfg.json"
class AndroidBuilder(object):
CFG_KEY_COPY_TO_ASSETS = "co... |
from __future__ import print_function
import sys
import math
import hyperopt
from hyperopt import fmin, tpe, hp
from hyperopt.mongoexp import MongoTrials
def get_space():
space = (hp.quniform('numTrees', 1, 10, 1),
hp.quniform('samplesPerImage', 10, 7500, 1),
hp.quniform('featureCount', 10... |
'''
Defines the base class of an electric potential grid.
'''
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
from numba import jit
sqc_x = (2., 'cm') # unit length for SquareCable
sqc_u = (10., 'V') # unit potential for SquareCable
edm_x = (10., 'mm') # unit length for Edm
edm_u = (2., 'kV... |
import ImageFont, ImageDraw, Image
FONT = "04B_03__.TTF"
font = ImageFont.truetype(FONT, 8)
glyphs = map(chr, range(ord(' '), ord('z')+1))
print """/*
* 8x8 variable-width binary font, AUTOMATICALLY GENERATED
* by fontgen.py from %s
*/
static const uint8_t font_data[] = {""" % FONT
for g in glyphs:
width, height... |
fastfood = ["momo", "roll", "chow", "pizza"]
print(fastfood)
print("\n")
print(fastfood.pop() + "\n")
print(fastfood) |
"""
Given an array nums, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning. It is guaranteed that such a parti... |
import re
from functools import reduce
from typing import Optional, Callable, Any, Type, Union
import wx # type: ignore
from gooey.gui import formatters, events
from gooey.gui.util import wx_util
from gooey.python_bindings.types import FormField
from gooey.util.functional import getin, ifPresent
from gooey.gui.validat... |
from ubluepy import Scanner, constants
def bytes_to_str(bytes):
string = ""
for b in bytes:
string += chr(b)
return string
def get_device_names(scan_entries):
dev_names = []
for e in scan_entries:
scan = e.getScanData()
if scan:
for s in scan:
if s[... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Feed.feed_type'
db.delete_column('syndication_feed', 'feed_type_id')
def backwards(self, orm):
# Adding f... |
r"""
PYTHONRC
========
Initialization script for the interactive Python interpreter. Its main purpose
is to enhance the overall user experience when working in such an environment
by adding some niceties to the standard console.
It also works with IPython and BPython, although its utility in that kind of
scenarios can ... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('talks', '0004_auto_20170326_1755'),
]
operations = [
migrations.AlterField(
model_name='talk',
name='fav_count',
fiel... |
"""
Django settings for blog project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
BASE_DIR = ... |
from axiom.test.historic.stubloader import StubbedTest
from xquotient.mail import MailTransferAgent
from axiom.userbase import LoginSystem
class MTAUpgraderTest(StubbedTest):
def testMTA2to3(self):
"""
Make sure MailTransferAgent upgraded OK and that its
"userbase" attribute refers to the st... |
from sys import stdout
from collections import defaultdict
from .parse import main, HTMLTag
def maybe_call(f, *args, **kwargs):
if callable(f):
return f(*args, **kwargs)
return f
class Compiler(object):
def __init__(self, stream):
self.stream = stream
self.blocks = []
self.de... |
"""
airPy is a flight controller based on pyboard and written in micropython.
The MIT License (MIT)
Copyright (c) 2016 Fabrizio Scimia, fabrizio.scimia@gmail.com
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 ... |
import datetime
import unittest2
import urlparse
from mock import Mock, ANY
import svb
from svb.six.moves.urllib import parse
from svb.test.helper import SvbUnitTestCase
VALID_API_METHODS = ('get', 'post', 'delete', 'patch')
class GMT1(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(hou... |
from django.test import TestCase
from django.contrib.auth.models import User
from dixit import settings
from dixit.game.models.game import Game
from dixit.game.models.player import Player
from dixit.game.models.round import Round, RoundStatus, Play
from dixit.game.models.card import Card
from dixit.game.exceptions impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.