content stringlengths 5 1.05M |
|---|
from . import DEFAULT_PAGINATE_BY
from .compute import parameter_sweep
from .load import load_data_from
from .store import store_results_to
def do_everything(data_file, results_file, purge_integral_db_cache=False, paginate_by=DEFAULT_PAGINATE_BY):
beam_type_id, search_space, _, strip_data, materials, astiff_shape... |
# -*- coding: utf-8 -*-
import os
import numpy as np
import torch
import torch.optim as optim
from tensorboardX import SummaryWriter
from scipy import stats
from tqdm import tqdm
import argparse
from data.feat_16928_dataloader import AVADataset
from mlsp_wide_model import mlsp_model
from model.emd_loss_metric import... |
# -*- coding: utf-8 -*-
import pytest
from jsonschema.exceptions import ValidationError
from mock import Mock
from mock import patch
from bravado_core.swagger20_validator import required_validator
@pytest.fixture
def param_spec():
return {
'name': 'foo',
'in': 'query',
'required': True,
... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import unittest
import os
from django.test import LiveServerTestCase
from routes import models as mdl
from django.contrib.staticfiles.testing import StaticLiveServerTestCase, LiveServerTestCase
import socket
from routes.tests imp... |
from django_dzenlog.urls import create_patterns
from models import TextPost
urlpatterns = create_patterns(TextPost, '')
|
from terra_sdk.client.lcd import LCDClient
terra = LCDClient(chain_id="bombay-12", url="https://bombay-lcd.terra.dev")
print(
terra.distribution.validator_rewards(
"terravaloper1259cmu5zyklsdkmgstxhwqpe0utfe5hhyty0at"
)
)
|
from django.conf import settings
from simple_salesforce import Salesforce
from rest_framework import viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
from lims.permissions.permissions import IsInAdminGroupOrRO
from lims.shared.mixins import AuditTrailViewMixin
f... |
import os
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.request import url2pathname
import cgi
import mimetypes
import markdown
from markdown.extensions.toc import TocExtension
'''
ROPy Wiki
Written by Graham Sutherland (gsuberland)
Inspired by sqshr's mikiwiki - https://github.com/sqshr/miki... |
#!/usr/bin/python3
"""This is the pid controller, translated to python
"""
import time
import os
from sys import argv
try:
if argv[1] == '--info':
print("PID controller written in Python")
exit(0);
except IndexError:
print("Starting controller")
#========================================... |
#!/usr/bin/env python3
#
# Copyright (c) 2019 Miklos Vajna and contributors.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""The test_accept_language module covers the accept_language module."""
import unittest
import accept_language
class TestParseAcceptLan... |
from collections import deque
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# BFS (Accepted), O(n) time, O(n) space
def minDepth(self, root: TreeNo... |
import SessionState
import base64
import streamlit as st
import pyperclip
# The input stores the string that is in text_area
# The output stores the conversion with the input
# This storage is needed because textarea comes before the button
session_state = SessionState.get(input='', output='', key=0)
# Function use... |
import re
import hgtk
import json
cvTb = {}
for line in open('Korean.aff', 'r', encoding='utf-8').readlines():
match = re.match(r'^ICONV (.+) (.+)$', line)
if match:
cvTb[match.group(2)] = match.group(1)
lines = [line.strip() for line in open('test.txt', 'r', encoding='utf-8').readlines() if line]
... |
class Rectangle:
def __init__(self, height=1.0, width=1.0):
self._height: float = height
self._width: float = width
def set_height(self, height: float):
self._height = height
def set_width(self, width: float):
self._width = width
def area(self) -> float:
re... |
#!/usr/bin/env python3
import pytest
import time
import re
import py
@pytest.fixture
def issue49(cookie_factory, datafile):
p = datafile("Snakefile_issue49", "Snakefile")
cookie_factory()
d = py.path.local(p.dirname)
config = d.join("slurm").join("config.yaml")
lines = re.sub("restart-times: 3", "r... |
import pytest
from thefrick.rules.workon_doesnt_exists import match, get_new_command
from thefrick.types import Command
@pytest.fixture(autouse=True)
def envs(mocker):
return mocker.patch(
'thefrick.rules.workon_doesnt_exists._get_all_environments',
return_value=['thefrick', 'code_view'])
@pytes... |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.ops.MatMul import FullyConnected
from openvino.tools.mo.front.caffe.extractors.utils import weights_biases
from openvino.tools.mo.front.extractor import FrontExtractorOp
class InnerProductFrontExtractor(FrontExtr... |
from django.http import JsonResponse
from django.views.generic import TemplateView
__all__ = [
'JSONResponseMixin',
'JSONView'
]
class JSONResponseMixin:
def render_to_json_response(self, context, **kwargs):
resp = {
'response': self.get_data(context)
}
return JsonRes... |
from serversion.kubernetes import Kubernetes
from aiohttp import web
from aiohttp.abc import Request
# Path to ServiceAccount token
SERVICEACCOUNT = "/var/run/secrets/kubernetes.io/serviceaccount"
# Path to read this Pod's namespace
NAMESPACE = f"{SERVICEACCOUNT}/namespace"
class VersionsView(web.View):
def __... |
from flask import Blueprint
bp = Blueprint('api', __name__)
# 写在最后是为了防止循环导入,ping.py文件也会导入 bp
from app.api import ping, tokens, errors, roles, users, micropub, notifications, messages, \
tags, microcon, comments, recommend, cradle, ddls, microknos_cites, search
# from app.api import recommend |
class MyContext():
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.open_file = open(self.filename, self.mode)
return self.open_file
def __exit__(self, *args):
self.open_file.close()
files = []
for i in range(... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import logging
from dataclasses import dataclass
import kubernetes.client
from hikaru.model.rel_1_18.v1.v1 import (
Container,
EmptyDirVolumeSource,
EnvVar,
Job,
JobSpec,
ObjectMeta,
... |
from django.apps import AppConfig
class ProblemSolvingConfig(AppConfig):
name = 'problem_solving'
|
#!/usr/bin/env python3
# Author: Miguel Almeida
import time
import RPi.GPIO as GPIO
#Global Pin Variable
pin = None
def askPin():
validateInput = False
while not validateInput:
try:
a = int(input("Please tell me the pin the rain sensor is connected to: "))
validateInput = True
... |
from .plugin import KnowledgeBasePlugin
class Comments(KnowledgeBasePlugin, dict):
def __init__(self, kb):
super(Comments, self).__init__()
self._kb = kb
def copy(self):
o = Comments(self._kb)
o.update(self)
return o
KnowledgeBasePlugin.register_default('comments', ... |
from threading import Thread
import threading
import pickle
import timeit
def inputCHECK():
try:
value = int(input('Type value : '))
if value < 1:
raise ValueError
return value
except ValueError:
print('Digits bigger than one are accepted')
exit(0)
def sho... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from api import Endpoint
from base64 import b32decode, b64encode
import sys
if len(sys.argv) > 1:
url = sys.argv[1]
else:
url = 'http://localhost:5000'
e = Endpoint(url)
c = e.fetch_cookie()
with open('poc.cob') as f:
code = f.read()
print(c)
n = e.uploa... |
# -*- coding: utf-8 -*-
from vindauga.history_support.history_utils import initHistory, doneHistory
from vindauga.types.screen import Screen
from .program import Program
class Application(Program):
"""
The mother of all applications.
`Application` is a shell around `Program` and differs from it m... |
#!/usr/bin/env python3
from sys import argv
try:
t = str(argv[1])
except:
t = input()
if len(t) == 0:
print('Pass a string to encrypt')
exit()
def str_to_bin(letter: str) -> bin:
return bin(ord(str(letter)))
def encrypt() -> int:
hash_return = ''
for letter in t:
... |
"""
Tests the interfaces file -- which varies between py2 and py3
Particularly tests the 'meets' related functions
"""
import sys
import os
import unittest
import pdb
from . import dispatch_cases as cases
from . import support
from . import dispatcher
# Set correct directory for testing
FILE_DIR = support.normalize_p... |
# -*- coding: utf-8 -*-
from aiida.orm.data.int import Int
from aiida.work.launch import run
from aiida.work.workchain import WorkChain
class AddAndMultiplyWorkChain(WorkChain):
...
result = run(AddAndMultiplyWorkChain, a=Int(1), b=Int(2), c=Int(3)) |
# https://leetcode.com/problems/subsets-ii/
# Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
# Note: The solution set must not contain duplicate subsets.
# Example:
# Input: [1,2,2]
# Output:
# [
# [2],
# [1],
# [1,2,2],
# [2,2],
# [1,2],
# ... |
print(hello world)
def recv():
pass
|
# Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
"""This module contains various walkers to traverse the lazy map.
Utilities to walk only the leaves, modify them, insert an interator
above, materialzie all the lazy operators, print values and print types.
"""
import collections
from item impor... |
# -*- encoding: utf-8 -*-
from django.db import models
from image_cropping.fields import ImageRatioField, ImageCropField
from django.contrib.auth.models import User
from municipios.models import Municipio
class EstablishmentType(models.Model):
name_type = models.CharField(u'Tipo do Estabelecimento', null=False... |
from django.urls import path
from django.urls import re_path
from contacts.views import index
from contacts.views import ContactsList
from contacts.views import ContactsDetail
urlpatterns = [
path('', index, name='index'),
re_path('api/?$', ContactsList.as_view(), name='list'),
re_path('api/(?P<pk>[0-9]+)... |
# Generated by Django 3.2.12 on 2022-04-03 13:56
import blog.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_auto_20220328_1428'),
]
operations = [
migrations.CreateModel(
name='Category',
fie... |
from doublylinkedbase import _DoublyLinkedBase
class PositionalList(_DoublyLinkedBase):
"""A sequential container of elements allowing positional access."""
# nested Position class
class Position:
"""An abstraction representing the location of a single element."""
def __init__(self, conta... |
from typing import Callable, List, Optional, Tuple
import math
import torch
import torch.nn.functional as F
from torch.nn.modules import Module
import cvnn.functional as cF
Tensor = torch.Tensor
class _DropoutNd(Module):
__constants__ = ['p', 'inplace']
p: float
inplace: bool
def __init__(self, p: ... |
import arm.utils
def skin_pos(vert):
vert.add_include('compiled.glsl')
rpdat = arm.utils.get_rp()
if rpdat.arm_skin == 'GPU (Matrix)':
vert.add_include('std/skinning_mat.glsl')
vert.add_uniform('vec4 skinBones[skinMaxBones * 3]', link='_skinBones', included=True)
vert.write('mat4 ... |
#name: SeldonGetMetadataByDeploymentPy
#language: python
#input: string seldonHost
#input: string seldonOIDCServer
#input: string seldonClientID
#input: string seldonUser
#input: string seldonPassword
#input: string seldonNamespace
#input: string seldonDeployment
#output: string seldonModelMetadata
import seldon_deplo... |
from openbiolink.graph_creation.metadata_infile.onto.inMetaOntoDoIsA import InMetaOntoDoIsA
from openbiolink.graph_creation.metadata_infile.onto.inMetaOntoGoIsA import InMetaOntoGoIsA
from openbiolink.graph_creation.metadata_infile.onto.inMetaOntoGoPartOf import InMetaOntoGoPartOf
from openbiolink.graph_creation.metada... |
import csv
import datetime as dt
import json
from itertools import zip_longest
from django.apps import apps
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.utils.encoding import python_2_unicode_compatible
from django.utils imp... |
#!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2020-2022 EntySec
#
# 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... |
import os
import pytest
import numpy as np
import pandas as pd
from pandas.testing import assert_frame_equal
import nyaggle.feature_store as fs
from nyaggle.testing import get_temp_directory
def test_save_feature():
df = pd.DataFrame()
df['a'] = np.arange(100)
with get_temp_directory() as tmp:
... |
# Generated by Django 2.0.9 on 2018-12-11 07:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0009_auto_20181211_0708'),
]
operations = [
migrations.AddField(
model_name='studentmonthlyreport',
name=... |
def aumento(preco=0, taxa=0):
r = preco + (preco * taxa/100)
return r
def diminuir(preco=0, taxa=0):
r = preco - (preco * taxa/100)
return r
def dobro(preco=0):
r = preco * 2
return r
def metade(preco=0):
r = preco / 2
return r
def moeda(preço, moeda='R$'):
return f'{moeda}{p... |
"""This module contains the general information for ExtvmmKeyInst ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class ExtvmmKeyInstConsts:
pass
class ExtvmmKeyInst(ManagedObject):
"""This is ExtvmmKeyInst class."""
... |
import sys
import os
import re
from z3 import *
import random
import src.path_analyzer as pa
import time
from src.utils import writeSolutionToFile
path = "./wc_smt2s/"
def split_conditions(expr):
splitted = []
start = False
# hack : need to remove contantant delta1
# delta2 array constraints
pa... |
from pinax.blog.forms import FIELDS, AdminPostForm
from pinax.blog.models import Post
from taggit.forms import TagField
FIELDS.append("tags")
class AdminPostTagsForm(AdminPostForm):
tags = TagField(required=False)
class Meta:
model = Post
fields = FIELDS
|
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
from mathy_core.layout import TreeLayout, TreeMeasurement
from mathy_core.tree import BinaryTreeNode
from .search_tree import BinarySearchTree
def test_layout_tidier():
tree = BinarySearchTree(0)
for i in range(-10, 10):
tree.insert(i)
m: TreeMeasurement = TreeLayout().layout(tree)
assert m i... |
""" This module contain solvers for all kinds of equations:
- algebraic, use solve()
- recurrence, use rsolve()
- differential, use dsolve()
- transcendental, use tsolve()
- nonlinear (numerically), use nsolve()
(you will need a good starting point)
"""
from sympy.core.compatibility imp... |
import sys
import os
from typing import List
import math
from automates.program_analysis.for2py.format import *
from automates.program_analysis.for2py.arrays import *
from automates.program_analysis.for2py.static_save import *
from automates.program_analysis.for2py.strings import *
from automates.program_analysis.for2p... |
#!/bin/env python3
####################################################
# Plotting functionality for highlighting odd birth/death events
# Author/Copywrite - Timothy Tyree
# Date - 5/28/2020, 3:49pm
# University of Calif., San Diego
####################################################
import numpy as np, pandas as pd,... |
# -*- coding: utf-8 -*-
"""This is a custom local plugin to ad extra functionality to pybee site."""
# Standard library imports
from collections import OrderedDict
import sys
# Third party imports
from lektor.pluginsystem import Plugin
PY3 = sys.version_info[0] == 3
class PyConPlugin(Plugin):
name = 'PyCon Cu... |
import numpy as np
import matplotlib.pyplot as plt
### numerical model specifications and physical constants
def getPhysConstants():
physConst = {}
physConst['RE'] = 6371.0 # Earth's radius in km
physConst['sigSB'] = 5.6703*(10**-8) # Stefan-Boltzmann constant
physConst['KelToCel'] = 273... |
from pylint.interfaces import IRawChecker
import pycodestyle
import io
from contextlib import redirect_stdout
from pylint.checkers import BaseChecker
class PycodestyleChecker(BaseChecker):
__implements__ = IRawChecker
name = 'pep8_errors'
msgs = {'E9989': ('Found pep8 errors (and warnings)'
... |
# -*- coding: utf-8 -*-
'''
@author: kebo
@contact: kebo0912@outlook.com
@version: 1.0
@file: bert_tokenizer.py
@time: 2021/01/26 23:37:11
这一行开始写关于本文件的说明与解释
'''
import tensorflow as tf
from transformers import BertTokenizer
from cybo.data.tokenizers import Tokenizer
class TransformersBertTokenizer(BertTokenizer,... |
from __future__ import print_function
# Python 2 standard library imports
import argparse
import json
import logging
import os
import shutil
import sys
import threading
import uuid
# Oasis Api import
from oasislmf.api_client.client import OasisAPIClient
'''
Test utility for running a model analysis using the Oasis A... |
from app.intents.intent import Intent
import random
class ChitChat(Intent):
def handle(self):
return self._getRandomResponse()
def _getRandomResponse(self):
return random.choice(self._getResponses())
def _getResponses(self):
return [
'Hello, how are you?',
... |
# Copyright (c) 2017 Jared Crapo, K0TFU
import unittest
from netcontrol.operator import Operator
class OperatorTest(unittest.TestCase):
def test_operator_init(self):
op = Operator('N7RSC')
self.assertEqual('N7RSC', op.callsign)
op = Operator(callsign='K0TFU')
self.assertEqual('K0... |
# Copyright 2019 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, ... |
# $Id$
#
# Project: MapServer
# Purpose: xUnit style Python mapscript tests of Map "zooming"
# Author: Sean Gillies, sgillies@frii.com
#
# ===========================================================================
# Copyright (c) 2004, Sean Gillies
#
# Permission is hereby granted, free of charge, to any person o... |
"""
02-band-limited-oscs.py - Oscillators whose spectrum is kept under the Nyquist frequency.
This tutorial presents an object (misnamed LFO but it's too late
to change its name!) that implements various band-limited waveforms.
A band-limited signal is a signal that none of its partials exceeds
the nyquist frequency (... |
import sys
# import libraries
#General numeric and dataframes
import numpy as np
import pandas as pd
# Data base related
from sqlalchemy import create_engine
#Regex
import re
#Object serialization
import pickle
#Natural Language
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
... |
"""
vtelem - Test the websocket telemetry daemon's correctness.
"""
# built-in
import asyncio
import time
# third-party
import websockets
# module under test
from vtelem.channel.framer import build_dummy_frame
from vtelem.stream import queue_get
from vtelem.stream.writer import default_writer
from vtelem.daemon.webs... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from flier.models import BaseModel
class Topic(BaseModel):
BOUNCE = 0
COMPLAINT = 1
DELIVERY = 2
NOTIFICATION_TYPES = ['Bounce', 'Complaint', 'Delivery']
topic = models.IntegerField(
_('Topic'), choices... |
from pytest import raises
from secp256k1 import Secp256k1, FLAG_ALL, SECRET_KEY_SIZE
from secp256k1.key import SecretKey, PublicKey
def test_secret_key():
secp = Secp256k1(None, FLAG_ALL)
# (de)serialization
key_a = SecretKey.random(secp)
key_b = SecretKey.from_bytearray(secp, key_a.to_bytearray())
... |
import SimpleITK as sitk
img = sitk.Image(11,12,sitk.sitkUInt8)
# test writing the external third party libraries
sitk.WriteImage(img, "test.jpg")
sitk.WriteImage(img, "test.png")
sitk.WriteImage(img, "test.tiff")
print(sitk.Version())
|
from sqlalchemy import Column, Index, String, Text, func
from db import BaseModel
class Document(BaseModel):
text = Column(Text, nullable=False, default="", server_default="")
language = Column(String, nullable=False, default="en", server_default="en")
tsvector_text = func.to_tsvector(func.toregconfig(l... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import math
import numpy as np
import scipy as sp
import scipy.interpolate
import scipy.optimize
import swarmsim
import swarmui
import random
# PyOpenGL can be used to draw on the simulation... |
# 22.05 Problems
#
# 22.05/PSet07: Numerical Diffusion Theory Analysis
import multiprocessing as mp
import numpy as np
import diffusion
import materials
problems = np.empty(10, dtype=diffusion.Problem1D)
# Problem 0: Infinite homogeneous medium
problems[0] = diffusion.Problem1D(2, fuel=materials.fuel_016)
problems[0... |
from django import forms
class ContactForm(forms.Form):
fullname = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control font-shahab",
"placeholder": "اسم کامل شما(فارسی یا انگلیسی)",
}
),
label="اسم"
)
email... |
"""
Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).
"""
"""Question:
Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).
Hints:
Use "for" to iterate the tuple
Use tupl... |
#sci-kit method
import pandas as pd
import numpy as np
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
x_train = np.array(train['x'])
y_train = np.array(train['y'])
x_test = np.array(test['x'])
y_test = np.array(test['y'])
x_train = x_train.reshape(-1,1)
x_test = x_test.reshape(-1,1)
from sklearn.l... |
# -*- coding: utf-8 -*-
import json
import os
import logging
import re
from aliyunsdkcore import client
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkfnf.request.v20190315 import StartExecutionRequest
"""
param: event:... |
from django.shortcuts import render, HttpResponse
from django.views import View
# from django.core.paginator import Paginator
from article.models import *
from aboutsite.models import VisitDocument
from utils import getnow
# Create your views here.
class MainPage(View):
# 网站首页的访问记录
def __doc_for_first_vist_ma... |
from abc import ABC, abstractmethod
from typing import Any
class IManager(ABC):
"""
Interface for a manager object
"""
@abstractmethod
def manage(self) -> Any:
raise NotImplementedError
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = [
"ws4py>=0.5.1",
"soundfile>=0.9.0.post1",
"pyaudio>=0.2.11",
]
with open("README.md") as f:
readme = f.read()
with open("LICENSE") as f:
license = f.read()
tests_require = [
"nose2",
]
setup(
name="... |
# 842. Split Array into Fibonacci Sequence
class Solution:
def splitIntoFibonacci(self, S: str) -> List[int]:
for i in range(min(10, len(S))):
x = S[:i+1]
if x.startsWith('0'): break
a = int(x)
for j in range(i+1, min(10, len(S))):
... |
from PyQt5.QtWidgets import QWidget, QTabWidget
from PyQt5.Qt import QVBoxLayout
from model.mm_account_type_model import MMAccountTableModel
from .mm_account_type_widget import MMAccountTypeWidget
class MMMainWidget(QWidget):
def __init__(self, parent):
QWidget.__init__(self, parent)
self.setMin... |
"""
Author: Chris Lim
Date: 2/27/18
This module acts as a wrapper for the Twython module. It allows the user to
exceed the standard rate limit of the search call to the Twitter API by
rotating accounts when a specified account exceeds it's limit. If all accounts
timeout, it sleeps an application for 10 minutes before ... |
from typing import List
from iv.Binarytree.mytree import MyTree
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNo... |
from mcpi.minecraft import Minecraft
import time
mc = Minecraft.create()
air = 0
water = 9
while True:
pos = mc.player.getTilePos()
blockBelow = mc.getBlock(pos.x, pos.y - 1, pos.z)
if blockBelow != air and blockBelow != water:
mc.setBlock(pos.x, pos.y - 1, pos.z, 41)
|
from .io_helper import *
from .eval import *
from .train import * |
"""Test evaluation base."""
# pylint: disable=import-error,protected-access
from unittest.mock import patch
from supervisor.const import CoreState
from supervisor.coresys import CoreSys
from supervisor.resolution.checks.free_space import CheckFreeSpace
from supervisor.resolution.const import IssueType
async def test... |
from django.shortcuts import render, redirect
from django.urls import reverse
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Pager_Duty
from .forms import PagerDutyForm
from projects.models import Proj... |
import numpy as np
import scipy as sp
import numerical.numpytheano as nt
import numpytheano.varpool as vp
import matplotlib.pyplot as plt
def fit_main_frequency(x, w, a, p):
"""
Fits signal x with a sine with initial frequency w, ampliture a, phase p
:param x: [N, D] D channels of the signal
:param w:... |
import os
from .helper import is_file
def download_from_object_store(local, bucket_name, remote, transfer_manager):
local = os.path.abspath(local)
if not os.path.exists(local):
os.makedirs(local, exist_ok=True)
try:
if is_file(remote):
remote_filename = os.path.basename(remote... |
"""测试API"""
from typing import Any, Dict
import pytest
from flask import Flask
from flask.views import MethodView
from flask_smorest import Api, Blueprint
from flask_sqlalchemy import BaseQuery
from marshmallow import Schema
from smorest_sfs.extensions.api.decorators import paginate
from smorest_sfs.extensions.sqla i... |
#!/usr/bin/env python
from __future__ import print_function
from inspect import isfunction, ismethod, getcallargs
import rospy
import threading
from lifecycle_msgs.msg import lm_events
from lm_monitor.monitor import LmMonitor
class ListenerCbException(Exception):
"""
Thrown on invalid callback function
... |
from QASQL.qasql import Base
test_db_name = 'test_database'
first_record_id = 0
filter_db = Base(test_db_name, save_to_file=False)
filter_db.create('unique_id', 'name', "active", mode="override")
filter_db = filter_db
db = Base('dummy', save_to_file=False)
db.create('name', 'age', 'size')
db.insert(name='homer', age... |
from wagtail.admin.edit_handlers import FieldPanel, ObjectList, TabbedInterface
from wagtail.contrib.modeladmin.helpers import WagtailBackendSearchHandler
from wagtail.contrib.modeladmin.options import (
ModelAdmin, ModelAdminGroup, ThumbnailMixin, modeladmin_register)
from wagtail.contrib.modeladmin.views import C... |
# -*- coding: utf-8 -*-
# @Author: ZwEin
# @Date: 2016-07-21 11:12:02
# @Last Modified by: ZwEin
# @Last Modified time: 2016-07-22 11:07:01
"""
python dig_esdg.py -t "<USERNAME>:<PASSWORD>" -o <OUTPUT_FILE_PATH>
"""
import urllib3
import re
import sys
from elasticsearch import Elasticsearch
import json
import g... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import six
import sys
import json
import random as rnd
import argparse
import codecs
import re
from nltk.stem import WordNetLemmatizer
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer("english")
lemmer = WordNetLemmatizer()
def rea... |
from utils import *
BUFFER_SIZE = 1024
def _test_faust_soundfile(sample_seq, output_path, sound_choice=0):
engine = daw.RenderEngine(SAMPLE_RATE, BUFFER_SIZE)
faust_processor = engine.make_faust_processor("faust")
faust_processor.num_voices = 8
dsp_path = abspath("faust_dsp/soundfile.dsp")
reversed_audio = n... |
from datetime import datetime
from datetime import timedelta
import os
import re
import xlrd
import pandas as pd
from src.bsl_python.new_lab_book_loader import load_new_labbook
class LabBookLoader:
def __init__(self):
pass
def load_notebook_from_fileobj(self, fileobj):
information = {}
... |
"""
Task 5
@author: Alexandr Mazanik
"""
import time
import math
import turtle
turtle.shape('turtle')
turtle.speed(5)
a0 = 30 # длина стороны первого квадрата
delta_a = 30 # изменение длины стороны квадрата
n = 10
a = a0
for i in range(n):
for j in range(4):
turtle.forward(a)
t... |
# Generated by Django 2.2.12 on 2020-04-30 19:41
from django.db import migrations
CREATE_GWELLS_AQUIFER_VIEW_SQL = """
CREATE VIEW postgis_ftw.gwells_aquifer_view AS
SELECT
aquifer_id,
aquifer_name,
area,
geom
FROM aquifer;
"""
class Migration(migra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.