text stringlengths 2 999k |
|---|
"""Paint, for drawing shapes.
Exercises
1. Add a color.
2. Complete circle.
3. Complete rectangle.
4. Complete triangle.
5. Add width parameter.
"""
from turtle import *
from freegames import vector
def line(start, end):
"Draw line from start to end."
up()
goto(start.x, start.y)
down()
goto(end... |
import uuid
from datetime import datetime
class Sheet(object):
def __init__(self, db_client, s3_client, redis_client):
self._db_client = db_client
self._s3_client = s3_client
self._redis_client = redis_client
def get(self, user_id):
memoized = self._redis_client._get(user_id... |
import os
import numpy
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
# pylint: disable=redefined-outer-name
# pylint: disable=exec-used
def fetch_log_files(directory):
log_files = []
files = os.listdir(directory)
for f in files:
if os.path.splitext(f)[1] == '.txt':
... |
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... |
from functools import reduce
from operator import add
import re
import six
from werkzeug.datastructures import ImmutableOrderedMultiDict
EMAIL_REGEX = r'^[^@^\s]+@[^@^\.^\s]+(\.[^@^\.^\s]+)+$'
def get_validator(framework, content, answers):
"""
Retrieves a validator by slug contained in the framework diction... |
from __future__ import absolute_import
#
# Partnerbox E2
#
# $Id$
#
# Coded by Dr.Best (c) 2009
# Support: www.dreambox-tools.info
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either... |
import itertools
import os
import pickle
import numpy as np
import torch
import torch.nn.functional as F
def get_onehot(vec_len, pos):
v = np.zeros(vec_len)
v[pos] = 1
return v
def save_to_file(vals, folder='', file=''):
if not os.path.exists(folder):
os.makedirs(folder)
save_str = os.p... |
subset.groupby("road_type").size() # subset["road_type"].value_counts() |
# Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... |
'''
---------------------------
Licensing and Distribution
---------------------------
Program name: Pilgrim
Version : 2021.5
License : MIT/x11
Copyright (c) 2021, David Ferro Costas (david.ferro@usc.es) and
Antonio Fernandez Ramos (qf.ramos@usc.es)
Permission is hereby granted, free of charge, to any perso... |
class BootstrapInformation(object):
"""The BootstrapInformation class holds all information about the bootstrapping process.
The nature of the attributes of this class are rather diverse.
Tasks may set their own attributes on this class for later retrieval by another task.
Information that becomes invalid (e.g. a... |
import collections.abc
import warnings
from abc import abstractmethod
from collections import defaultdict
from datetime import datetime
from enum import Enum, EnumMeta
from textwrap import dedent
from typing import Any, Callable, Dict, Mapping, Optional, Set, Tuple, Union
from urllib.parse import urlencode
import ciso... |
import setuptools
description = "A simple idiot's guide api wrapper in python"
long_description = open("README.md").read()
version="1.2.0"
packages = ["idioticapi"]
setuptools.setup(
name="idioticapi",
version=version,
description=description,
long_description=long_description,
url="https://githu... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import sys
import traceback
from infra_libs import app
from infra_libs import event_mon
from infra_libs import ts_mon
from infra.tools.send_... |
import random
import time
import numpy as np
import torch
from transformers import AdamW, BertTokenizer, WarmupLinearSchedule
from common.constants import *
from common.evaluators.bert_evaluator import BertEvaluator
from common.trainers.bert_trainer import BertTrainer
from datasets.bert_processors.aapd_processor impo... |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2020 Apple Inc. All Rights Reserved.
#
import socket
import torch
import torch.distributed as dist
from utils import logger
def is_master(opts) -> bool:
node_rank = getattr(opts, "ddp.rank", 0)
return (node_rank == 0)
def distributed_init(op... |
# Copyright 2017, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
from dateutil import parser
from api.extensions import sql
from api.shows import models
from api.shows.services.wrapper import Wrapper
class ShowService(object):
def __init__(self, show_id):
self._show_id = show_id
def add_show(self):
x = Wrapper()
y = x.show(self._show_id)
... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/xurui/double_robot_project/src/scout_robot/tracer_ros/tracer_msgs/msg/TracerMotorState.msg;/home/xurui/double_robot_project/src/scout_robot/tracer_ros/tracer_msgs/msg/UartTracerMotorState.msg;/home/xurui/double_robot_project/src/scout_robot/trac... |
import re
from sublime import Region
class HTMLEditor:
def __init__(self, view):
self.new, self.edited, self.deleted = self._calculate(
old=self._readlines(view),
new=self._readregions(view)
)
def _calculate(self, old, new):
new_lines = []
edited = []
... |
import asyncio
import pytest
import json
import itertools
from typing import Union, List, Tuple
from botocore.exceptions import ReadTimeoutError
from botocore.utils import BadIMDSRequestError
from aiobotocore import utils
from aiobotocore._helpers import asynccontextmanager
# From class TestContainerMetadataFetcher... |
#Embedded file name: url_redirect.py
import re
import urlparse
import urllib
import time
if 0:
i11iIiiIii
def assign(service, arg):
if service != '''www''':
return
OO0o = urlparse.urlparse(arg)
Oo0Ooo = urlparse.parse_qsl(OO0o.query)
for O0O0OO0O0O0, iiiii in Oo0Ooo:
arg = arg.repla... |
from envs.g2048 import g2048
import time
import numpy as np
env = g2048()
obs = env.reset()
for i in range(10):
time.sleep(1.)
env.render()
obs, reward, done, _ = env.step(np.random.choice([0, 1, 2, 3]))
#for i in range(10):
# obs, reward, done, _ = env.step(0)
|
#!/usr/bin/env python
from __future__ import absolute_import
import unittest
from wagl import unittesting_tools as ut
class TestRandomPixelLocations(unittest.TestCase):
def test_non_2D(self):
"""
Test that specifying a non 2D tuple raises a TypeEror.
"""
dims = (3, 100, 100)
... |
"""
Appointment Excel Exporter.
Exports the current patient's appoitnments from the mongoDB database
"""
import sys
from os import chdir
from os.path import exists
from time import sleep
import numpy as np
from bson.objectid import ObjectId
from openpyxl import Workbook
from pymongo import MongoClient
chdir(sys.arg... |
"""Base class for all the objects in SymPy"""
from collections import defaultdict
from collections.abc import Mapping
from itertools import chain, zip_longest
from .assumptions import BasicMeta, ManagedProperties
from .cache import cacheit
from .sympify import _sympify, sympify, SympifyError
from .compatibility import... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Log'
db.create_table(u'eventlog_log', (
(u'id', self.gf('django.db.models.fields... |
# Note: The first part of this file can be modified in place, but the latter
# part is autogenerated by the boilerplate.py script.
"""
`matplotlib.pyplot` is a state-based interface to matplotlib. It provides
a MATLAB-like way of plotting.
pyplot is mainly intended for interactive plots and simple cases of
programmat... |
from unittest import TestCase
from flask.ext.acl import ACLManager
from flask.ext.login import LoginManager
from flask import Flask
class FlaskTestCase(TestCase):
def setUp(self):
self.flask = Flask('tests')
self.flask.config['SECRET_KEY'] = 'deadbeef'
self.authn = LoginManager(self.fla... |
#!/usr/bin/env python
##############################################################################
# Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompan... |
from django.contrib import admin
from django import forms
from taggit_labels.widgets import LabelWidget
from taggit.forms import TagField
from addressbook.models import *
class SocialInline(admin.TabularInline):
model = SocialNetwork
extra = 0
class WebsiteInline(admin.TabularInline):
model = Website
... |
# coding: utf-8
# # Keras tutorial - the Happy House
#
# Welcome to the first assignment of week 2. In this assignment, you will:
# 1. Learn to use Keras, a high-level neural networks API (programming framework), written in Python and capable of running on top of several lower-level frameworks including TensorFlow a... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
# TODO include https://github.com/blue-yonder/tsfresh
import matplotlib.pyplot as plt
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import mean_absolute_error, mean_squared_log_error
from scipy.optimize import minimize
from tqdm import tqdm
import statsmodels.tsa.api as smt
import statsmodels... |
# -*- coding: utf-8 -*-
r"""
Dirichlet characters
A :class:`DirichletCharacter` is the extension of a homomorphism
.. MATH::
(\ZZ/N\ZZ)^* \to R^*,
for some ring `R`, to the map `\ZZ/N\ZZ \to R` obtained by sending
those `x\in\ZZ/N\ZZ` with `\gcd(N,x)>1` to `0`.
EXAMPLES::
sage: G = DirichletGroup(35)
... |
import copy
from typing import Type
import pytest
from neuraxle.base import TrialStatus, synchroneous_flow_method
from neuraxle.metaopt.data.vanilla import (DEFAULT_CLIENT, DEFAULT_PROJECT,
RETRAIN_TRIAL_SPLIT_ID,
BaseDataclass, Clie... |
"""
WSGI config for plasma_link_django 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/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('D... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 9
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class FilepoolDefaultPolicyDefau... |
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
""" Tests for half-precision syntax quirks. """
import dace
import math
import numpy as np
import pytest
from dace.transformation.dataflow import MapFusion, Vectorization
from dace.transformation.optimizer import Optimizer
N = dace.symbol('N'... |
class RSG: pass |
import sys
import re
import py
from pypy.translator.translator import TranslationContext
from pypy.rpython.error import TyperError
from pypy.rpython.lltypesystem.lltype import *
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.rlist import *
from pypy.rpython.lltypesystem.rlist import ListRepr, FixedSizeL... |
# -*- coding: UTF-8 -*-
import os
import sys
import requests
from pprint import pprint
import time
import logging
import numpy as np
from binance.spot import Spot as Client
from decimal import Decimal
import json
from binance.error import ClientError
from key import *
from utils import *
from module import bots
log_fo... |
import glob
import optparse
import os.path
import subprocess
import sys
def main():
""" Repeatedly run GUI functional tests. """
parser = optparse.OptionParser()
parser.add_option('-t', '--trials', type='int', default=100,
help='# trials to attempt')
parser.add_option('-n', '--no... |
"""
Inits the summary bot. It starts a Reddit instance using PRAW, gets the latest posts
and filters those who have already been processed.
"""
import praw
import requests
import tldextract
import cloud
import config
import scraper
import summary
# We don't reply to posts which have a very small or ver... |
#!/usr/bin/env python
# Licensed under a 3-clause BSD style license, see LICENSE.
"""
Tests for the skhep.dataset.defs module.
"""
# -----------------------------------------------------------------------------
# Import statements
# -----------------------------------------------------------------------------
import p... |
#Distributed under the MIT licesnse.
#Copyright (c) 2015 Dave McCoy (dave.mccoy@cospandesign.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
#the Software without restriction, including without limitati... |
"""
:mod:`websockets.server` defines the WebSocket server APIs.
"""
import asyncio
import collections.abc
import email.utils
import functools
import http
import logging
import socket
import sys
import warnings
from types import TracebackType
from typing import (
Any,
Awaitable,
Callable,
Generator,
... |
"""
Licensed under the Unlicense License;
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://unlicense.org
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BAS... |
import unittest
from collections import namedtuple
from tests.harness import instrumentGooey
from gooey import GooeyParser
from gooey.tests import *
Case = namedtuple('Case', 'inputs initialExpected expectedAfterClearing')
class TestTextField(unittest.TestCase):
def makeParser(self, **kwargs):
parser = ... |
# import the basic python packages we need
import os
import sys
import tempfile
import pprint
import traceback
# disable python from generating a .pyc file
sys.dont_write_bytecode = True
# change me to the path of pytan if this script is not running from EXAMPLES/PYTAN_API
pytan_loc = "~/gh/pytan"
pytan_static_path =... |
from selenium import webdriver
from test_plus.test import TestCase
from selenium.webdriver.common.keys import Keys
from .data_for_test import visitor_urls, login_user_urls, admin_urls
from time import sleep
class NewVisitorTest(TestCase):
def setUp(self):
self.browser = webdriver.Chrome()
s... |
'''
Created on 17 Mar 2018
@author: julianporter
'''
from numbers import Number
def dot(v1,v2):
return sum([x*y for (x,y) in zip(v1,v2)])
def allLists(args):
return all([isinstance(x,list) for x in args])
def isList(x):
return isinstance(x,list)
def allNumbers(args):
return all([isinstance(x,Number... |
import sys, os
import matplotlib.pyplot as plt
import numpy as np
import utils
import subprocess
metro = [True, False]
points= 20
temps = np.linspace(0.2,3.0,num=points)
nspins = 50
j = 1.0
hs = [0.0, 0.02]
nblk = 100
nsteps = 10000
iter = 0
dbiter = 0
nrestarts = 5
total = len(metro)*len(temps)*len(hs)*nrestarts
uti... |
'''
@Description:common 公用组件
@Author:Zigar
@Date:2021/03/05 15:37:00
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from model.attention import SEModule, CBAM
from config.config import cfg
#---------------------------------------------------------------#
# Mish激活函数
#--------------------------... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: val.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import ... |
from datetime import datetime
from pprint import pprint, pformat
import requests
import scapy.all as scapy
from scapy2dict import to_dict
def get_filter(ip, protocol, port):
capture_filter = ""
if ip:
capture_filter += "host " + ip
if protocol:
if ip:
capture_filter += " and... |
import os
from seleniumbase import BaseCase
class ScreenshotTests(BaseCase):
def test_save_screenshot(self):
self.open("https://seleniumbase.io/demo_page")
# "./downloaded_files" is a special SeleniumBase folder for downloads
self.save_screenshot("demo_page.png", folder="./download... |
"""
Multi-dimensional Scaling (MDS)
"""
# author: Nelle Varoquaux <nelle.varoquaux@gmail.com>
# License: BSD
import numpy as np
from joblib import Parallel, delayed, effective_n_jobs
import warnings
from ..base import BaseEstimator
from ..metrics import euclidean_distances
from ..utils import check_random_state, ch... |
import os
import sys
import subprocess
import importlib.util as il
spec = il.spec_from_file_location("config", snakemake.params.config)
config = il.module_from_spec(spec)
sys.modules[spec.name] = config
spec.loader.exec_module(config)
sys.path.append(snakemake.config['args']['mcc_path'])
import scripts.mccutils as mccu... |
#!/usr/bin/env python3
## Author: Philip Larsson
#
# Check if there is any precipitation for specified hours forward (8 is default).
# Use this link to get correct latitude and longitude: http://opendata.smhi.se/apidocs/metfcst/demo_point.html
# Change using --latitude and --longitude to get correct geographic area. D... |
from abc import abstractmethod
import json
import sys
import datetime
import traceback
if sys.version_info[0] < 3:
from urllib import quote_plus
else:
from urllib.parse import quote_plus
import gevent
class Transport:
def __init__(self, session, connection):
self._session = session
self.... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 12, transform = "RelativeDifference", sigma = 0.0, exog_count = 0, ar_order = 0); |
from quart import g, render_template
from lnbits.decorators import check_user_exists, validate_uuids
from . import splitpayments_ext
@splitpayments_ext.route("/")
@validate_uuids(["usr"], required=True)
@check_user_exists()
async def index():
return await render_template("splitpayments/index.html", u... |
from random import randint
print('=-' * 15)
print('VAMOS JOGAR PAR OU IMPAR')
print('=-' * 15)
cont = 0
while True:
pc = randint(1, 10)
valor = int(input('Diga um valor: '))
escolha = str(input('Par ou Impar [P/I] ')).upper()
soma = pc + valor
print('--' * 15)
if soma % 2 == 0:
print(f'V... |
'''
given the string in the variable blah, program the necessary steps to print out the
day of the week in our given date
'''
blah = '21/03/2012'
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(
r"^~create-incoming-(?P<case_pk>\d+)$",
views.IncomingParcelPostCreateView.as_view(),
name="incoming-create",
),
url(
r"^incoming-(?P<pk>[\w-]+)$",
views.IncomingParcelPostDetailView.as_view(),... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
import torch
from torch.utils import data
from torch.utils.data import Dataset, DataLoader
import numpy as np
import functools
import librosa
import glob
import os
from tqdm import tqdm
import multiprocessing as mp
import json
from utils.augment import time_shift, resample, spec_augment
from audiomentations import Add... |
import pytest
import sys
import StringIO
from pypy.module.cpyext.state import State
from pypy.module.cpyext.pyobject import make_ref
from pypy.module.cpyext.test.test_api import BaseApiTest
from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
from rpython.rtyper.lltypesystem import rffi
class T... |
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import json
import logging
from django.db.models import Q, Avg, Count, Sum, Value, BooleanField, Case, When
from django.conf import settings
from ... |
from TikTokApi import TikTokApi
api = TikTokApi()
count = 1
for video in api.hashtag(name="funny").videos(count=count):
print(video)
user = api.user(username='rotififi')
print(user.as_dict)
for video in user.videos(count=count):
print(video)
|
#a=eval(input(">>"))
#b=eval(input(">>"))
a=10000
for i in range(5):
a=a*(1+0.05)
print(a)
|
from django.apps import AppConfig
class ViewcountConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'viewcount'
|
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitsend Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test logic for skipping signature validation on old blocks.
Test logic for skipping signature validati... |
def json_to_attrs(obj, json_res, types=(str, int, type(None), )):
for key, val in json_res.items():
if type(val) in types:
setattr(obj, key, val if type(val) is not str else val.strip()) |
#encoding=utf-8
chinese_non_stops = u'"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏'
chinese_stops = u"!?。。"
chinese_punctuations = chinese_non_stops + chinese_stops
# 判断一个unicode是否是汉字
def is_chinese(uchar):
if u'\u4e00' <= uchar <= u'\u9fff':
return True
else:
return False
# 判... |
# --------------
class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
# --------... |
#!/usr/bin/env python3
# Copyright (c) 2014-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.
"""Base class for RPC testing."""
import configparser
from enum import Enum
import logging
import argpars... |
from model_seq_cnn import *
from tqdm import trange
import torch
import numpy as np
import unittest
class TestSeqCNN(unittest.TestCase):
def test_shape_2d(self):
for i in trange(20, desc='test_shape_2d'):
in_C = np.random.randint(2, 4)
in_H = np.random.randint(30, 100)
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
###
from castor.config import CassandraKeyspace
from cassandra import InvalidRequest
import re
class Operation:
def add(stack):
x = stack.pop()
y = stack.pop()
return x+y
def minus(stack):
x = stack.pop()
y = stack.pop()
... |
def f():
global xx
xx = 1
f()
print(x<ref>x)
|
import numpy as np
from multiprocessing import cpu_count
from napari_plugin_engine import napari_hook_implementation
from pathlib import Path
from napari_czifile2.io import CZISceneFile
@napari_hook_implementation
def napari_get_reader(path):
if isinstance(path, list):
if any(Path(p).suffix.lower() != '... |
import argparse
import sys
import httplib2
from apiclient.discovery import build
from oauth2client import client
from oauth2client import file
from oauth2client import tools
def get_service(api_name, api_version, scope, client_secrets_path):
parser = argparse.ArgumentParser(
formatter_class=argparse.Raw... |
from dataclasses import dataclass
from typing import Tuple, Type
from lahja import BaseEvent, BaseRequestResponseEvent
from libp2p.peer.id import ID
@dataclass
class Libp2pPeersResponse(BaseEvent):
"""
libp2p_peers: Handshaked Peer IDs.
"""
result: Tuple[ID, ...]
class Libp2pPeersRequest(BaseReque... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from django import forms
from shortener.models import Shortener
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column, HTML
from crispy_forms.bootstrap import PrependedText
class ShortenerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().... |
"""
IP Routes
object abstractions for representing IP routes in VPP
"""
from vpp_object import VppObject
from socket import inet_pton, inet_ntop, AF_INET, AF_INET6
from vpp_ip import DpoProto, VppIpPrefix, INVALID_INDEX, VppIpAddressUnion, \
VppIpMPrefix
from ipaddress import ip_address, IPv4Network, IPv6Netw... |
"""
mfhyd module. Contains the ModflowHydclass. Note that the user can access
the ModflowHyd class as `flopy.modflow.ModflowHyd`.
Additional information for this MODFLOW package can be found at the `Online
MODFLOW Guide
<http://water.usgs.gov/ogw/modflow/MODFLOW-2005-Guide/hyd.htm>`_.
"""
import sys
impo... |
from .encoder import Encoder, EncHyperparameter
from .unary_encoder import UnaryEncoder, UEncHyperparameter
from .mean import MeanImputation, MeanHyperparameter
from .iterative_regression import IterativeRegressionImputation, IterativeRegressionHyperparameter
from .greedy import GreedyImputation, GreedyHyperparameter
... |
#!/usr/bin/python3
""" Review module for the HBNB project """
from models.base_model import BaseModel, Base
from sqlalchemy import Column, String, ForeignKey
class Review(BaseModel, Base):
""" Review classto store review information """
__tablename__ = "reviews"
place_id = Column(String(60), ForeignKey('p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `util.config`."""
import pytest
from mock import patch
from finances_at_home.finances_at_home import *
class TestLoadConfig:
"""Tests for `load_config`."""
def test_file_exists(self):
"""Check handling of file."""
pass
def tes... |
"""AnyNumberOf and OneOf."""
from typing import List, Optional, Tuple
from sqlfluff.core.parser.helpers import trim_non_code_segments
from sqlfluff.core.parser.match_result import MatchResult
from sqlfluff.core.parser.match_wrapper import match_wrapper
from sqlfluff.core.parser.match_logging import parse_match_loggin... |
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from goods.models import SKU
from users... |
#!/home/pi/server
# coding=utf-8
#使用超声波测距模块时,VCC接树莓派的5V,GND接树莓派GND。trig接树莓派38,echo接树莓派40.
#GPIO编码方式为BOARD!!
import RPi.GPIO as GPIO
import time
def t_stop():
GPIO.output(11,False)
GPIO.output(12,False)
GPIO.output(15,False)
GPIO.output(16,False)
def t_up():
GPIO.output(11,True)
GPIO.output(12... |
from datetime import datetime, timedelta
from timeit import default_timer
from adblockparser import AdblockRules
from adblockparser import AdblockRule
from carl import storage
all_options = {opt: True for opt in AdblockRule.BINARY_OPTIONS}
def load_rules():
fname = "easylist.txt"
with open(fname) as f:
... |
from sys import getrefcount
a = [1, 2, 3]
print(getrefcount(a))
b = [a, a, a]
print(getrefcount(a))
print(getrefcount(b)) |
from django.db import connections
from django.conf import settings
from baserow.core.exceptions import UserNotInGroupError
from baserow.core.utils import extract_allowed, set_allowed_attrs
from baserow.contrib.database.fields.models import TextField
from baserow.contrib.database.views.handler import ViewHandler
from b... |
from z3 import *
from maneuverRecomadEngine.exactsolvers.SMT_Solver_Z3_IntIntOr_ILP import Z3_Solver_Int_Parent_ILP
from maneuverRecomadEngine.exactsolvers.ManuverSolver_SB_ILP import ManuverSolver_SB_ILP
class Z3_SolverInt_SB_Enc_AllCombinationsOffers_ILP(Z3_Solver_Int_Parent_ILP, ManuverSolver_SB_ILP):
def _def... |
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
from collections import Counter
num_letters =[]
cont_2 = 0
cont_3 = 0
#with open("day2//input.txt") as f:
with open("input.txt") as f:
for line in f:
c = Counter(line)
num_letters = c.values()
if 2 in num_letters:
cont_2 += 1
if 3 in num_letters:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.