content stringlengths 5 1.05M |
|---|
"""
Promotion API Service Test Suite
Test cases can be run with the following:
nosetests -v --with-spec --spec-color
coverage report -m
"""
import os
import logging
import unittest
from datetime import datetime
from unittest import TestCase
from flask_api import status # HTTP Status Codes
from service.models impo... |
#!/usr/bin/env python3
import sys
import math
data = [3, 1, 4, 1, 5]
data.sort()
mean = 0
sd = 0
med = 0;
for i in range(len(data)):
mean += data[i]
mean /= len(data)
for i in range(len(data)):
sd += ((mean - data[i]) ** 2)
if(len(data) % 2 == 0):
med = (data[len(data) // 2] + data[len(data) // 2 + 1]) / 2
else:
me... |
import pyapr
def opening(apr: pyapr.APR,
parts: (pyapr.ShortParticles, pyapr.FloatParticles),
binary: bool = False,
radius: int = 1,
inplace: bool = False):
if inplace:
# reference assignment
parts_copy = parts
else:
# copy input particl... |
import datetime
from typing import Dict, Optional, cast
import pytz
from ee.models.license import License, LicenseManager
from posthog.models import Organization
from posthog.test.base import APIBaseTest
class LicensedTestMixin:
"""
Test API using Django REST Framework test suite, for licensed PostHog (main... |
"""API Router is responsible for obtaining the connection values for each domain name.
This module obtains the IP, port and status of a microservice. Using the domain name,
it performs a Redis lookup by key value. The value is stored in Redis as JSON.
Typical usage example:
class OrdersMinosApiRouter(Min... |
#!/usr/bin/env python
###############################################################################
# Copyright (C) 2013-2014 by gempa GmbH
#
# Author: Stephan Herrnkind
# Email: herrnkind@gempa.de
###############################################################################
from __future__ import absolute_imp... |
from django.db import models
# Create your models here.
class Schema(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
class Code(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
active_instances = models.Posit... |
DEBUG = False
def merge(match_scheme, sum_match_scheme):
# print(match_scheme, sum_match_scheme)
for match_item, sum_match_item in zip(match_scheme, sum_match_scheme):
for node in match_item:
if node not in sum_match_item:
sum_match_item.append(node)
return sum... |
# -*- coding: utf-8 -*-
import numpy as np
from operator import add
from functools import reduce
def AUC(scores):
"""Area Under the Curve
params
------
scores :
np.ndarray, shape = (n_combination, 3)
Each 3d row consists of (idx, jdx, indicator).
If rank(idx|c) < rank(jdx|c), ... |
# ---------------
# Date: 10/06/2019
# Place: Biella/Torino/Ventimiglia
# Author: Vittorio Mazzia
# Project: Python in The Lab Project
# ---------------
# import some important libraries
import os
######################################################
# !! run this BEFORE importing TF or keras !!
# run code only on a ... |
'''
Find all anagrams in a list for a given lookup word
(can be a file)
'''
from __future__ import print_function
wordlist = ['abba',
'baba',
'caret',
'cater']
# Using a lookup table
def approach1(lookup):
d = {}
# O(n)
for w in wordlist:
# O(klogk)
w_s... |
from ModSecurity import ModSecurity
from ModSecurity import Rules
from ModSecurity import Transaction
modsec = ModSecurity()
print(modsec.whoAmI())
rules = Rules()
rules.loadFromUri("basic_rules.conf")
print(rules.getParserError())
transaction = Transaction(modsec, rules)
print(transaction.processURI("http://www.mo... |
#!/opt/local/bin/python
import argparse
import MySQLdb
import os, os.path
from HTMLParser import HTMLParser
import codecs
from nltk import RegexpTokenizer
from nltk.corpus import stopwords
__author__ = 'guglielmo'
"""
This script helps generating a Categorized corpus (like the Reuters NLTK corpus)
that can be used fo... |
from datetime import datetime
from model.Candle import Candle
from storage.KafkaStorage import KafkaStorage
import logging
log = logging.getLogger(__name__)
class CandleStorage(KafkaStorage):
def __init__(self, bootstrap_servers='localhost:9092'):
super(CandleStorage, self).__init__(bootstrap_servers=b... |
#!/usr/bin/env python
import sys
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy.interpolate import UnivariateSpline as interpolate
from settings import tableau20
from data import exo
m_nep = 0.0539531012
r_nep = 0.35219064
# Set dates for KOIs
# KOI -> 1609: 2011
# -> 2841: 2012
# ... |
from typing import Dict, List
from mlagents.trainers.env_manager import EnvironmentStep
from mlagents.trainers.simple_env_manager import SimpleEnvManager
from mlagents_envs.side_channel.float_properties_channel import FloatPropertiesChannel
from mlagents.trainers.action_info import ActionInfo
from animalai.envs.arena... |
"""Unit tests for Yandex.Weather custom integration."""
|
import datetime
import random
import string
from lona import LonaView
from lona_bootstrap_5 import show_alert
from pillowfort.response_formatter import ResponseFormatter
class Endpoint(LonaView):
URL = ''
ROUTE_NAME = ''
INTERACTIVE = False
VARIABLES = []
RESPONSE_FORMATTER = ResponseFormatter
... |
"""
Created on Dec 20, 2017
@author: nhan.nguyen
Verify that system returns 'True' when
checking a pairwise that exists in wallet.
"""
import pytest
import json
from indy import did, pairwise
from utilities import utils, common
from test_scripts.functional_tests.pairwise.pairwise_test_base \
import PairwiseTestB... |
# Copyright (c) 2016-present, Facebook, Inc.
#
# 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... |
# Copyright (c) 2017-2018 Martin Olejar
#
# SPDX-License-Identifier: BSD-3-Clause
# The BSD-3-Clause license for this file can be found in the LICENSE file included with this distribution
# or at https://spdx.org/licenses/BSD-3-Clause.html#licenseText
import os
class HotPlugBase:
def __init__(self):
pa... |
import circuits # import local file
from qiskit import transpile
from qiskit.providers.aer import StatevectorSimulator
from qiskit.visualization import plot_histogram
import itertools
import matplotlib.pyplot as plt
if __name__ == "__main__":
#circuit = circuits.no_overlap()
#circuit = circuits.no_1_1_2_tiles()
#c... |
# rename A.execute into A.calculate (Rename ⇧F6)
# Beware of not including wrong dynamic references!
# Add type annotation to run(a, b), try rename again (Rename ⇧F6)
class A:
def execute(self):
print('execute A')
class B:
def execute(self):
print('execute B')
def run(a, b):
a.execute()... |
#!/usr/bin/env python
"""
Faça um Programa que calcule a área de um quadrado, em seguida mostre o dobro desta área para o usuário.
"""
def float_or_int(number):
return int(number) if number.is_integer() else float(number)
def get_number(input_question):
numero = None
while not numero:
try:
... |
import time
import chess
import chess.pgn
import pickle
import sys
import numpy as np
import argparse
from .utils import Tic
def convert_games(source='',save_path='',start_name='chess',block_size=1000000,blocks=0,inter_map=None):
if source=='':
print('There is not source specified')
r... |
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class Stack:
def __init__(self, size):
self.head = None
self.size = size
self.length = 0
def __len__(self):
ret... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from design import views
urlpatterns = patterns('',
url(r'^search$', views.searchParts),
url(r'^get$', views.getParts),
url(r'^dashboard$', views.dashboardView),
url(r'^updateChain$', views.saveChain),
url(r'^newPr... |
"""
Helpers for tests.
"""
import itertools
import unittest
import numpy as np
import pandas as pd
import pandas.testing
from vlnm.normalizers.base import Normalizer
# There are issues wth pandas and pylint
# See https://github.com/PyCQA/pylint/issues/2198 for some discussion.
#
#
DataFrame = pd.DataFrame
Series = p... |
'''test for having the file checked .
if we request the channels from the file and there are no channels
and when you call the channels from file .. you specify which file to call from .(which list)
if the stream is already there then you dont want it to add the stream
and notify the user that it already exists.... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
"""Simple 1D & 2D plotting utilities package for "Synchrotron Radiation Workshop" (SRW).
``uti_plot`` currently wraps ``matplotlib``, but other backends are
planned. If no suitable backend is available, ``uti_plot_init`` sets
the backend to ``uti_plot_none`` so that the calling program is still
functional. This is ... |
# Generated by Django 3.0.7 on 2020-09-06 03:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('exams', '0015_remove_abilitytest_code'),
]
operations = [
migrations.AlterModelTable(
name='abilitytest',
table='AbilityTest... |
import argparse
import GeneTree
def subparser(subparsers):
desc = 'Create the matrice genes against strains file'
subparser = subparsers.add_parser('matrice', description=desc,
formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False
)
required = subparser.add_argument_group('re... |
from sub_units.bayes_model_implementations.moving_window_model import \
MovingWindowModel # want to make an instance of this class for each state / set of params
from sub_units.utils import run_everything as run_everything_imported # for plotting the report across all states
from sub_units.utils import Region
imp... |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class GameCollector(models.Model):
username = models.CharField(max_length=70)
Password1 = models.CharField(max_length=70)
Password2 = models.CharField(max_length=70)
da... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.burst_home, name='burst'),
path('sets/', views.burst_sets_view, name='burst_sets'),
path('sets/add/', views.burst_set_add, name='add_burst_set'),
path('sets/<int:burst_set_id>', views.burst_set_interfaces_view, name='burst_... |
"""
urlresolver XBMC Addon
Copyright (C) 2014 tknorris
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 version 3 of the License, or
(at your option) any later version.
... |
from django.conf.urls import url
from django.urls import include
from rest_framework.routers import DefaultRouter
from api.views.candidate import CandidateViewSet
from api.views.election import ElectionViewSet
from api.views.login import LoginView
from api.views.subelection import SubElectionViewSet
router = DefaultR... |
"""
For in em python
Iterando strings com for
Função range recebe três argumentos (star = a,stop, step=1)
"""
# texto = 'Python'
# for letra in texto:
# print( letra )
'''texto = 'Python'
for n,letra in enumerate(texto) :
print(n,letra) '''
# print("Escolha um número e veja a sua tabuada ")
# mult = int(input(... |
from pygame import *
from random import randint
from time import time as timer
#музло
mixer.init()
mixer.music.load('muzlo.mp3')
mixer.music.play()
#картинки
racket = 'racket.png'
ten_ball = 'tenis_ball.png'
#класс-родитель для других спрайтов
class GameSprite(sprite.Sprite):
#конструктор класса
... |
# 剑指 Offer 04:二维数组中的查找
# leetcode submit region begin(Prohibit modification and deletion)
from typing import List
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
i = len(matrix) - 1
j = 0
while i >= 0 and j < len(matrix[0]):
if matri... |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup
import urllib.request
import sys
impo... |
"""
ulmo.cuahsi.wof
~~~~~~~~~~~~~~~
`CUAHSI WaterOneFlow`_ web services
.. _CUAHSI WaterOneFlow: http://his.cuahsi.org/wofws.html
"""
from __future__ import absolute_import
from . import core
from .core import (get_sites, get_site_info, get_values, get_variable_info)
|
'''
Created on 07-May-2017
@author: Sathesh Rgs
'''
print("Program to print digits of a number")
try:
count=0
num=int(input("Enter a number.."))
while num > 0:
num=num//10
count += 1
print("Length is ",count)
except:
print("Enter a valid number") |
from utils.model_forward import forward
from sklearn.cluster import KMeans
class UpdateReps(object):
def __init__(self, every, dataset, batch_size=64):
self.every = every
self.dataset = dataset
self.batch_size = batch_size
def __call__(self, epoch, batch, step, model, dataloaders, los... |
n = 2020
cnt = 0
for i in range(2, n+1):
tmp = i
while tmp > 1:
if tmp % 10 == 2:
cnt += 1
tmp /= 10
print(cnt)
|
#!/usr/bin/env python
import argparse
from ansipants import ANSIDecoder, PALETTE_NAMES
parser = argparse.ArgumentParser(description="Convert ANSI art to HTML.")
parser.add_argument('filename')
parser.add_argument(
'--encoding', default='cp437',
help="Character encoding of input (default: cp437)"
)
parser.ad... |
#
# Copyright (c) 2019, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
#
from importlib import import_module
from django.conf import settings
from django.core.exceptions ... |
# Generated by Django 3.0.5 on 2021-08-02 14:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('quiz', '0007_course_attempt'),
]
operations = [
migrations.RemoveField(
model_name='course',
name='attempt',
),
... |
import numpy as np
import datetime as dt
import csv
from database import SQLite3Database
import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
fro... |
from .classic_actor_critic import *
from .deep_actor_critic import *
|
from django.db import models
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _
import uuid
import os
from InvoiceParser.settings import MEDIA_URL
# Create your models here.
UserModel=get_user_model()
def get_image_file_name(instance,filename):
ext=filename.spl... |
"""
Analyse the explicit projections calculated
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import griddata
directory = "D:/uni/tomography-calibration/solid-angle-calculation/"
sangles = np.load(direc... |
#!/usr/bin/python3
import RPi.GPIO as GPIO
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
from pubnub.callbacks import SubscribeCallback
pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'Your-Pubnub-Subscribe-Key-Here'
pnconfig.publish_key = 'Your-Pubnub-Publish-Key-Here'
pu... |
#
# Copyright 2008 Google Inc.
#
# 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 writ... |
import numpy as np
import cv2
class DensePoseEstimator(object):
def __init__(self):
pass
def estimate(self, depth_image, person_tracks, view_pose):
if depth_image is not None:
for p in person_tracks:
if p.is_located() and p.is_confirmed():
xmin ... |
# coding=utf-8
import io
import os
import re
from setuptools import setup
PACKAGE = 'moar'
def get_path(*args):
return os.path.join(os.path.dirname(__file__), *args)
def read_from(filepath):
with io.open(filepath, 'rt', encoding='utf8') as f:
return f.read()
def get_version():
data = read_fr... |
# python3 main.py -m ssd_mobilenet_v2_320x320_coco17_tpu-8/saved_model -l mscoco_label_map.pbtxt -t 0.5 -roi 0.5 -v example.mp4 -a
import cv2
import numpy as np
import argparse
import tensorflow as tf
import dlib
import imutils
import socket
import time
import base64
import requests
from object_detection.utils impor... |
from app import db, students
db.create_all()
test_rec = students(
'Marco Hemken',
'Los Angeles',
'123 Foobar Ave',
'12345'
)
db.session.add(test_rec)
db.session.commit()
|
import locale
import os
from pathlib import Path
import click
from tqdm import tqdm # type: ignore
from kaleidoscope.gallery import generate_gallery_ini, generate_album_ini
from kaleidoscope.generator import generate, DefaultListener
from kaleidoscope.reader import read_gallery
gallery_path = "."
@click.group()
@... |
'''
Praveen Manimaran
CIS 41A Spring 2020
Exercise I
'''
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def getArea(self):
return math.pi * math.pow(self.radius,2)
class Cylinder(Circle):
def __init__(self, radius, height):
super().__init__(rad... |
import os
import sys
from django_fakery.compat import HAS_GEOS
if hasattr(sys, "pypy_version_info"):
from psycopg2cffi import compat
compat.register()
DISABLE_SERVER_SIDE_CURSORS = False
if os.environ.get("PYTHON_VERSION", "").startswith("pypy"):
DISABLE_SERVER_SIDE_CURSORS = True
DEFAULT_AUTO_FIELD =... |
import time
from ....models.models import Speaker
from ....permissions.permissions import Permissions
from ....shared.exceptions import ActionException
from ....shared.patterns import Collection, FullQualifiedId
from ...generics.update import UpdateAction
from ...util.default_schema import DefaultSchema
from ...util.r... |
#!/usr/bin/env python
# @package nurbs
# Approximate a 3D curve with a B-Spline curve from either a set of data points or a set of control points
#
# If a set of data points is given, it generates a B-spline that either approximates the curve in the least square
# sense or interpolates the curve. It also computes the ... |
import datetime
import glob
import random
import pandas as pd
# Load modules
from psychopy import core, event, gui, sound, visual
|
"""Defines the class that handles ingest trigger rules"""
from __future__ import unicode_literals
import logging
from django.db import transaction
from data.data.data import Data
from data.data.json.data_v6 import convert_data_to_v6_json
from data.data.value import FileValue
from ingest.models import IngestEvent, Sc... |
"""Raspberry Pi Face Recognition Attendence System Configuration
import cv2
import glob
import os
import sys
import select
import config
import face
import Database_1
def is_letter_input(letter):
# Utility function to check if a specific character is available on stdin.
# Comparison is case insensitiv... |
from flask import Flask
from flask import request
from generate_conditional import conditional
app = Flask(__name__)
@app.route('/')
def hello_world():
input = request.args.get('input')
top_k = request.args.get('top_k', 100, int)
return conditional(raw_text_input=input, top_k=int(top_k))
@app.route('/ping... |
"""BC alias for previous msearch_daemon command name"""
import logging
from mjolnir.utilities.kafka_msearch_daemon import arg_parser, main
if __name__ == '__main__':
logging.basicConfig()
kwargs = dict(vars(arg_parser().parse_args()))
main(**kwargs)
|
#!/usr/bin/env python
###############################################################################
## Databrowse: An Extensible Data Management Platform ##
## Copyright (C) 2012-2016 Iowa State University Research Foundation, Inc. ##
## All rights reserved. ... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
from django import forms
from django.core.exceptions import ValidationError
class CustomForm(forms.Form):
error_css_class = 'is-invalid'
def clean(self):
cleaned_data = super(CustomForm, self).clean()
if 'password1' in self.changed_data and 'password2' in self.changed_data:
if cl... |
#models
import uuid
import django_tables2 as tables
import datetime
from django.db import models
from django.utils import timezone
from django.urls import reverse
#from django.utils.timesince import timesince
from django.utils.timezone import utc
from phonenumber_field.modelfields import PhoneNumberField
#from django... |
from Inheritance.class_Inheritance.project_zoo.reptile import Reptile
class Lizard(Reptile):
pass |
class Chess:
tag = 0
camp = 0
x = 0
y = 0
|
# Generated by Django 3.0.7 on 2020-07-17 06:28
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('problem', '0012_auto_20200716_1903'),
migrations.swappable_dependency(settings.AUTH... |
from __future__ import print_function
import logging
import sys
import os
import unittest
import torch
import torch_mlu.core.mlu_model as ct
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(cur_dir + "/../../")
logging.basicConfig(level=logging.DEBUG)
from common_utils import testinfo, TestCase # p... |
import requests
from bs4 import BeautifulSoup
import os
import re
import getpass
class Evaluation:
def toJson(self):
template = '{{"yr":{},"su":"{}","cr":"{}","sc":"{}","in":"{}","rc":{:.1f},"ri":{:.1f},"wl":{:.0f},"gr":"{}"}}'
return template.format(
self.year, self.subject, self.cours... |
"""
For this project we have multiple ice datasets. This script contains the helper functions for the notebook which is used to combine them to a new dataset:
Antarctic Ice Concentration (AIC)
"""
import numpy as np
import xarray as xr
import glob
from tqdm import tqdm
from pyproj import Proj, transform
def load_s... |
# Support for the Numato Opsis - The first HDMI2USB production board
from mibuild.generic_platform import *
from mibuild.xilinx import XilinxPlatform
from mibuild.openocd import OpenOCD
from mibuild.xilinx import UrJTAG
from mibuild.xilinx import iMPACT
_io = [
## FXO-HC536R - component U17
# 100MHz - CMOS C... |
#from scapy.all import *
class ASN1_object(object):
# Class migth be:
# UNIVERSAL (0)
# APPLICATION (1)
# PRIVATE (2)
# CONTEXT-SPECIFIC (3)
#class_number = 0
# Build-in types mighth by:
# Simple (0)
# Constructed (1)
#kind_of_type = 0
# Universal types are:
# Reserve... |
from dubhe_sdk.config import *
from dubhe_sdk.service.ADCkafka import *
from dubhe_sdk.service import context
from dubhe_sdk.service.service_prepare import *
from concurrent.futures import ThreadPoolExecutor
import socketserver
import sys
import importlib
import random
import typing
import inspect
import traceback
d... |
import os
import re
import emoji
import twitter
from dotenv import load_dotenv
from PIL import Image, ImageDraw, ImageFont
from font_fredoka_one import FredokaOne
PATH = os.path.dirname(os.path.abspath(__file__))
load_dotenv(PATH + '/../mclare.env')
# Set font
try:
ttf = ImageFont.truetype(os.getenv("DANK_MONO_IT... |
# for getting inputs passed to program
import sys
# for coercing bytestring<->python dict
from json import dumps, loads
# for retrieving/setting environment variables
from os import environ
# for encoding
from base64 import b64decode, b64encode
# for making request
import http.client
from dotenv import find_dotenv
# f... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtG... |
# Copyright 2018 Michael DeHaan LLC, <michael@michaeldehaan.net>
#
# 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 app... |
import logging
import sys
from contextvars import copy_context
from typing import Optional
import os
TRACE_ID_KEY = 'trace_id'
TEST_ENV = 'test'
DEFAULT_FORMAT_STR = '%(levelname)s:%(filename)s:%(lineno)d: %(message)s'
class KubricLogAdapter(logging.LoggerAdapter):
"""
This adapter checks for a trace_id in ... |
"""Tools to create profiles (i.e. 1D "slices" from 2D images)."""
import numpy as np
from astropy import units as u
from regions import CircleAnnulusSkyRegion, RectangleSkyRegion
from gammapy.datasets import Datasets, SpectrumDatasetOnOff
from gammapy.maps import MapAxis
from gammapy.modeling.models import PowerLawSpec... |
from functools import lru_cache
from dwave.cloud import Client
from dwave.cloud.exceptions import ConfigFileError
@lru_cache(maxsize=None)
def qpu_available():
"""Check whether QPU solver is available"""
try:
with Client.from_config() as client:
solver = client.get_solver(qpu=True)
exc... |
from __future__ import annotations
import os
import sys
import time
import discord
import psutil
from pgbot import common, embed_utils, utils
from pgbot.commands.base import CodeBlock, String, MentionableID
from pgbot.commands.user import UserCommand
from pgbot.commands.emsudo import EmsudoCommand
process = psutil.... |
""" Various configuration routines for musync.
"""
import logging
import time
import musync
ARCHIVE_TOP = 'http://www.mutopiaproject.org/ftp'
_MSG_FORMAT='%(asctime)s - %(name)s %(levelname)s - %(message)s'
_DATE_FORMAT='%Y-%m-%d %H:%M:%S'
class UTCFormatter(logging.Formatter):
converter = time.gmtime
LOGGING =... |
from flask import Blueprint
main = Blueprint("main", "pbxd.main")
v2 = Blueprint("v2", "pbxd.v2")
v3 = Blueprint("v3", "pbxd.v3")
|
# Generated by Django 3.1.2 on 2021-01-14 17:39
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('backend', '0042_seminar_similarities'),
]
operations = [
migrations.RemoveField(
model_name='seminar',
name='similarities',
... |
"""A custom turtle.Turtle.
Author: Henrik Abel Christensen
"""
import turtle
from typing import Tuple
class Tortoise(turtle.Turtle):
"""Custom Turtle class.
Parameters
----------
shape : str
visible : bool
"""
def __init__(self, shape: str = 'turtle', visible: bool = True) -> None:
... |
import numpy as np
from functions.global_settings import settings, us_in_1_second
from tkinter import filedialog
from datetime import date
ideal_speed_as_const = 1296000.0 / 86164.0
def get_data_from_correction_file(filepath):
print(f"Loaded correction data from {filepath}")
with open(filepath) as f:
... |
# Generated by Django 3.1.1 on 2020-09-08 04:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0002_auto_20200908_0405'),
]
operations = [
migrations.AlterField(
model_name='projects',
name='image',
... |
import unittest
from webob.compat import text_type
class text_Tests(unittest.TestCase):
def _callFUT(self, *arg, **kw):
from webob.compat import text_
return text_(*arg, **kw)
def test_binary(self):
result = self._callFUT(b'123')
self.assertTrue(isinstance(result, text_type))
... |
import requests
from bs4 import BeautifulSoup as bs
import csv
import pandas as pd
file = "Hotel-2.0.xlsx"
hotel_names = pd.ExcelFile(file)
df1 = hotel_names.parse('Sheet1')
hotel = []
hotel_amenities = []
hotel_room_types = []
hotel_nearby_hotels = []
hotel_nearby_restaurants = []
hotel_nearby_attracti... |
import AnalogShield as AS
import matplotlib.pyplot as plt
import numpy as np
import operator
import RigolInstruments as RI
import time
a = AS.AnalogShield("/dev/analog_shield", "D784216")
a.adc_calibrate(0, "/dev/multimeter")
# Connect to the multimeter
multimeter = RI.DM3058("/dev/multimeter")
actual_readings = []... |
# -*- coding: utf-8 -*-
import asyncio
import numpy as np
from poke_env.player.random_player import RandomPlayer
from poke_env.teambuilder.teambuilder import Teambuilder
class RandomTeamFromPool(Teambuilder):
def __init__(self, teams):
self.teams = [self.join_team(self.parse_showdown_team(team)) for team... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.