content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from datetime import datetime, timedelta
import pytest
from api.models.timetables import Timetable
from fastapi import status
from fastapi.testclient import TestClient
pytestmark = pytest.mark.asyncio
@pytest.fixture
def timetable2(timetable):
return Timetable(
id=1,
action="on",
start=d... | nilq/baby-python | python |
import enum
from typing import Optional
from sqlalchemy import (
BigInteger,
Boolean,
Column,
DateTime,
Enum,
Float,
ForeignKey,
ForeignKeyConstraint,
Index,
Integer,
String,
UnicodeText,
func
)
from sqlalchemy.orm import relationship
from .database import Base
UNK... | nilq/baby-python | python |
#!/usr/local/bin/python3
import os
import re
import sys
import argparse
import plistlib
import json
def modifyPbxproj():
data = ''
flag = False
end = False
with open(filePath, 'r') as file:
for line in file.readlines():
if not end:
find = line.find('3B02599D20F49A43001F9C82 /* Debug */')
... | nilq/baby-python | python |
# coding: utf-8
# # Dogs-vs-cats classification with ViT
#
# In this notebook, we'll finetune a [Vision Transformer]
# (https://arxiv.org/abs/2010.11929) (ViT) to classify images of dogs
# from images of cats using TensorFlow 2 / Keras and HuggingFace's
# [Transformers](https://github.com/huggingface/transformers).
#
... | nilq/baby-python | python |
#################################################################################
# Autor: Richard Alexander Cordova Herrera
# TRABAJO FIN DE MASTER
# CURSO 2019-2020
# MASTER EN INTERNET DE LAS COSAS
# FACULTAD DE INFORMATICA
# UNIVERSIDAD COMPLUTENSE DE MADRID
##################################################... | nilq/baby-python | python |
from django.apps import AppConfig
class TambahVaksinConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'tambah_vaksin'
| nilq/baby-python | python |
# Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values
# Splitting the dataset into the Training set and Test set
from... | nilq/baby-python | python |
"""Utilities relative to hunspell itself."""
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 19:39:10 2020
@author: esol
"""
from neqsim.thermo import fluid, addOilFractions, printFrame, dataFrame, fluidcreator,createfluid,createfluid2, TPflash, phaseenvelope
from neqsim.process import pump, clearProcess, stream, valve, separator, compressor, runProcess, view... | nilq/baby-python | python |
# Copyright 2018 Lawrence Kesteloot
#
# 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 agr... | nilq/baby-python | python |
def check():
import numpy as np
dataOK = np.loadtxt('nusselt_ref.out')
dataChk= np.loadtxt('data/post/wall/nusselt.out')
tol = 1e-6
nts = 10000
chk = (np.mean(dataOK[-nts:,2])-np.mean(dataChk[-nts:,2]))<tol
return chk
def test_answer():
assert check()
| nilq/baby-python | python |
import pytt
assert pytt.name == "pytt"
| nilq/baby-python | python |
from discord.ext import commands
import discord
import cogs
import random
import asyncio
import requests
from discord import File
import os
from datetime import datetime
import traceback
import tabula
import json
bot = commands.Bot(command_prefix='$')
class VipCog(commands.Cog):
def __init__(self,... | nilq/baby-python | python |
from collections import OrderedDict
from copy import deepcopy
from functools import partial
from ml_collections import ConfigDict
import numpy as np
import jax
import jax.numpy as jnp
import flax
import flax.linen as nn
from flax.training.train_state import TrainState
import optax
import distrax
from .jax_utils impo... | nilq/baby-python | python |
import sys
import os
from inspect import getmembers
from types import BuiltinFunctionType, BuiltinMethodType, MethodType, FunctionType
import zipfile
from util import isIronPython, isJython, getPlatform
cur_path = os.path.abspath(os.path.dirname(__file__))
distPaths = [os.path.join(cur_path, '../../../indigo/dist'), ... | nilq/baby-python | python |
import os
from .base import *
BASE_SITE_URL = 'https://rapidpivot.com'
AMQP_URL = 'amqp://guest:guest@localhost:5672//'
ALLOWED_HOSTS = ['rapidpivot.com']
ADMINS = (('Name', 'email@service.com'),)
DEBUG = False
TEMPLATE_DEBUG = False
# SSL/TLS Settings
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
... | nilq/baby-python | python |
from setuptools import find_packages, setup
import os
# load README.md as long_description
long_description = ''
if os.path.exists('README.md'):
with open('README.md', 'r') as f:
long_description = f.read()
setup(
name='XMCD Projection',
version='1.0.0',
packages=find_packages(include=['xmcd_... | nilq/baby-python | python |
from random import sample
from time import sleep
lista = []
print('\033[0;34m-'*30)
print(' \033[0;34mJOGOS DA MEGA SENA')
print('\033[0;34m-\033[m'*30)
j = int(input('Quantos jogos você deseja gerar? '))
print('SORTEANDO...')
for i in range(0, j):
ran = sorted(sample(range(1, 60), 6))
lista.append(ran[:])
... | nilq/baby-python | python |
from PyQt5.QtWidgets import QWidget, QMainWindow
from PyQt5.QtCore import Qt
import gi.repository
gi.require_version('Gdk', '3.0')
from gi.repository import Gdk
from utils import Rect
# from keyboard import Keybroad
# from button import Button
# moved inside classes to prevent cyclic import
# Window(parent, t... | nilq/baby-python | python |
# Generated by Django 3.1.5 on 2021-02-01 18:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rentalsapp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='tenants',
name='amou... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
def main():
from itertools import accumulate
n = int(input())
# 大きさを基準に昇順で並び替えておく
a = sorted(list(map(int, input().split())))
sum_a = list(accumulate([0] + a))
# 色は最大でN種類
ans = [False for _ in range(n)]
# 初期化:最も大きいモンスターは,確実に最後まで生き残る
ans[n - 1] ... | nilq/baby-python | python |
# Python code for 2D random walk.
import json
import sys
import random
import time
import math
import logging
import asyncio
from .DataAggregator import DataAggregator
from .PositioningTag import PositioningTag
from pywalkgen.walk_model import WalkAngleGenerator
from pywalkgen.pub_sub import PubSubAMQP
from pywalkgen... | nilq/baby-python | python |
from tkinter import*
from tkinter import messagebox
from PIL import ImageTk
import sqlite3
root=Tk()
root.geometry("1196x600")
root.title("Hotel Management System")
#bg=PhotoImage(file ="D:\Python\HotelManagement\Background.png")
#bglabel=Label(root,image=bg)
#bglabel.place(x=0,y=0)
backimage=PhotoImage("D:... | nilq/baby-python | python |
import os
import pytest
from cctbx import sgtbx, uctbx
from dxtbx.serialize import load
import dials.command_line.cosym as dials_cosym
from dials.algorithms.symmetry.cosym._generate_test_data import (
generate_experiments_reflections,
)
from dials.array_family import flex
from dials.util import Sorry
@pytest.m... | nilq/baby-python | python |
def print_section_header(header: str) -> None:
print(f"========================================================================")
print(f"=== {header} ")
def print_section_finish() -> None:
print(f"=== SUCCESS\n")
| nilq/baby-python | python |
names = []
posx = []
posy = []
caps = []
with open('sink_cap.txt') as f:
for line in f:
tokens = line.split()
names.append(tokens[0])
posx.append(float(tokens[1]))
posy.append(float(tokens[2]))
caps.append(float(tokens[3]))
minx = min(posx)
miny = min(posy)
maxx = max(posx)
maxy = max(posy)
#print(" -... | nilq/baby-python | python |
from block_model.controller.block_model import BlockModel
from drillhole.controller.composites import Composites
from geometry.controller.ellipsoid import Ellipsoid
from kriging.controller.search_ellipsoid import SearchEllipsoid
from kriging.controller.point_kriging import PointKriging
from variogram.controller.model i... | nilq/baby-python | python |
"""This module demonstrates usage of if-else statements, while loop and break."""
def calculate_grade(grade):
"""Function that calculates final grades based on points earned."""
if grade >= 90:
if grade == 100:
return 'A+'
return 'A'
if grade >= 80:
return 'B'
if gra... | nilq/baby-python | python |
from pinata.response import PinataResponse
from pinata.session import PinataAPISession
class PinataClient:
def __init__(self, session: PinataAPISession, api_namespace: str):
self.session = session
self._prefix = api_namespace
def _post(self, uri, *args, **kwargs) -> PinataResponse:
re... | nilq/baby-python | python |
import music_trees as mt
from music_trees.tree import MusicTree
from copy import deepcopy
import random
from tqdm import tqdm
NUM_TAXONOMIES = 10
NUM_SHUFFLES = 1000
output_dir = mt.ASSETS_DIR / 'taxonomies'
output_dir.mkdir(exist_ok=True)
target_tree = mt.utils.data.load_entry(
mt.ASSETS_DIR / 'taxonomies' / ... | nilq/baby-python | python |
from PIL import Image
import sys
im = Image.new("L", (256, 256))
c = 0
with open(sys.argv[1], "rb") as f:
f.read(8)
byte = f.read(1)
while c < 65536:
#print(c)
im.putpixel((c % 256, int(c / 256)), ord(byte))
byte = f.read(1)
c = c + 1
im.save("fog.png")
| nilq/baby-python | python |
from ..std.index import *
from .math3d import *
from .math2d import *
from ..df.blizzardj import bj_mapInitialPlayableArea
class TerrainGrid(Rectangle):
grids = []
_loc = None
def __init__(self,r,sampling=8):
Rectangle.__init__(self,GetRectMinX(r),GetRectMinY(r),GetRectMaxX(r),GetRectMaxY(r))
... | nilq/baby-python | python |
from collections.abc import Callable
def update( # <1>
probe: Callable[[], float], # <2>
display: Callable[[float], None] # <3>
) -> None:
temperature = probe()
# imagine lots of control code here
display(temperature)
def probe_ok() -> int: # <4>
return 42
def display_wrong(te... | nilq/baby-python | python |
# pylint: disable=invalid-name
# pylint: disable=too-many-locals
# pylint: disable=too-many-arguments
# pylint: disable=too-many-statements
# pylint: disable=unbalanced-tuple-unpacking
# pylint: disable=consider-using-f-string)
# pylint: disable=too-many-lines
"""
A module for finding M² values for a laser beam.
Full ... | nilq/baby-python | python |
'''
09.60 - Use the 8x8 LED Matrix with the max7219 driver using SPI
This sketch shows how to control the 8x8 LED Matrix to draw random pixels.
Components
----------
- ESP32
- One or more 8x8 LED matrix displays with the max7219 driver
- GND --> GND
- VCC --> 5V
- CS --> GPIO 5 (SPI SS)
... | nilq/baby-python | python |
#!/usr/bin/python
from setuptools import setup, find_packages
version = '0.9.4'
setup(name='workerpool',
version=version,
description="Module for distributing jobs to a pool of worker threads.",
long_description="""\
Performing tasks in many threads made fun!
This module facilitates distributing s... | nilq/baby-python | python |
"""
For more details, see the class documentation.
"""
from django.db.models import Q
from map_annotate_app.dto import CrimeDTO
from map_annotate_app.extras import Location
from map_annotate_app.models import Crime
class CrimeDAO:
"""
This class represents the data access layer for a crime record.
"""
... | nilq/baby-python | python |
"""
$url mediavitrina.ru
$type live
$region Russia
"""
import logging
import re
from urllib.parse import urlparse
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream.hls import HLSStream
from streamlink.utils.url import update_qsd
log = logging.getLog... | nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import sys
from socket import *
from time import strftime
import datetime
def main():
if len(sys.argv) < 4:
print("completion_logger_server.py <listen address> <listen port> <log file>")
exit(1)
host = sys.argv[1]
por... | nilq/baby-python | python |
#!/usr/bin/python
"""
python 1.5.2 lacks some networking routines. This module implements
them (as I don't want to drop 1.5.2 compatibility atm)
"""
# $Id: net.py,v 1.2 2001/11/19 00:47:49 ivo Exp $
from string import split
import socket, fcntl, FCNTL
def inet_aton(str):
"""
convert quated dot... | nilq/baby-python | python |
""" this is for pytest to import everything smoothly """
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
| nilq/baby-python | python |
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
store = {
'demo': 'this is important data!'
}
@app.get('/')
# Return all key-value pairs
def read_keys():
return store
@app.post('/')
# Create a new key-value pair
def create_key(key: str, value: str):
... | nilq/baby-python | python |
import pytest
import logging
import tempfile
from lindh import jsondb
# Logging
FORMAT = '%(asctime)s [%(threadName)s] %(filename)s +%(levelno)s ' + \
'%(funcName)s %(levelname)s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
@pytest.fixture(scope='function')
def db():
db = jsondb... | nilq/baby-python | python |
import sys
import os
from PIL import Image, ImageDraw
# Add scripts dir to python search path
sys.path.append(os.path.dirname(os.path.abspath(sys.argv[0])))
from maps_def import maps as MAPS
BORDERS = True
IDS = True
def bake_map(tiles, info):
size = tiles[0].size[0]
res = Image.new("RGB", (len(info[0]) * si... | nilq/baby-python | python |
#@+leo-ver=5-thin
#@+node:edream.110203113231.741: * @file ../plugins/add_directives.py
"""Allows users to define new @direcives."""
from leo.core import leoGlobals as g
directives = ("markup",) # A tuple with one string.
#@+others
#@+node:ekr.20070725103420: ** init
def init():
"""Return True if the plugin has... | nilq/baby-python | python |
# Microsoft API results index & search features generator
"""
Copyright 2016 Fabric S.P.A, Emmanuel Benazera, Alexandre Girard
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 copyrig... | nilq/baby-python | python |
"""
This module is used to interface with classical HPC queuing systems.
""" | nilq/baby-python | python |
from django.contrib import admin
from .models import SiteToCheck
@admin.register(SiteToCheck)
class SiteToCheckAdmin(admin.ModelAdmin):
list_display = ['url', 'last_status', 'last_response_time']
| nilq/baby-python | python |
# Based on https://github.com/petkaantonov/bluebird/blob/master/src/promise.js
from .compat import Queue
# https://docs.python.org/2/library/queue.html#Queue.Queue
LATE_QUEUE_CAPACITY = 0 # The queue size is infinite
NORMAL_QUEUE_CAPACITY = 0 # The queue size is infinite
class Async(object):
def __init__(sel... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
import os
import time
#
# Generate the master out.grid
# Create a 3M point file of lat/lons - and write to ASCII file called out.grd.
# This file will be used as input to ucvm_query for medium scale test for images
#
if not os.path.exists("out.grd"):
print("Creating grd.out file.")
... | nilq/baby-python | python |
import trcdproc.navigate.raw as nav
from trcdproc.core import H5File
def test_all_signal_dataset_paths_are_found(organized_faulty_data: H5File):
"""Ensures that all dataset paths are found
"""
dataset_paths_found = {path for path in nav.all_signal_dataset_paths(organized_faulty_data)}
all_paths = []
... | nilq/baby-python | python |
from nhlscrapi.games.events import EventType as ET, EventFactory as EF
from nhlscrapi.scrapr import descparser as dp
def __shot_type(**kwargs):
skater_ct = kwargs['skater_ct'] if 'skater_ct' in kwargs else 12
period = kwargs['period'] if 'period' in kwargs else 1
if period < 5:
return ET.Shot
# elif p... | nilq/baby-python | python |
from django import VERSION
if VERSION < (3, 2):
default_app_config = (
"rest_framework_simplejwt.token_blacklist.apps.TokenBlacklistConfig"
)
| nilq/baby-python | python |
# exercise/views.py
# Jake Malley
# 01/02/15
"""
Define all of the routes for the exercise blueprint.
"""
# Imports
from flask import flash, redirect, render_template, \
request, url_for, Blueprint, abort
from flask.ext.login import login_required, current_user
from forms import AddRunningForm, AddCy... | nilq/baby-python | python |
#!/usr/bin/env python
"""Tests for `magic_dot` package."""
import pytest
from collections import namedtuple
from magic_dot import MagicDot
from magic_dot import NOT_FOUND
from magic_dot.exceptions import NotFound
def test_can():
"""Test that dict key is accessible as a hash ."""
md = MagicDot({"num": 1})
... | nilq/baby-python | python |
message = 'This is submodule 1.'
def module_testing():
print(message) | nilq/baby-python | python |
# SISO program G.py
# This function is a placeholder for a generic computable function G.
# This particular choice of G returns the first character of the input
# string.
import utils
from utils import rf
def G(inString):
if len(inString) >= 1:
return inString[0]
else:
return ""
def testG()... | nilq/baby-python | python |
'''
LICENSE: MIT
https://github.com/keras-team/keras/blob/a07253d8269e1b750f0a64767cc9a07da8a3b7ea/LICENSE
実験メモ
Dropoutをなくしてみたが、あまりへんかなし
SGDにへんこうしたら、しゅうそくがすごくおそくなった
面白い。
試したいアイデアがあるので、
自前のactivation functionを書いてみる。
'''
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.mo... | nilq/baby-python | python |
from .tracebackturbo import *
| nilq/baby-python | python |
from __future__ import unicode_literals
import csv
import io
import json
import os
import string
from collections import OrderedDict
from unittest import TestCase
import pandas as pd
from backports.tempfile import TemporaryDirectory
from tempfile import NamedTemporaryFile
from hypothesis import (
given,
He... | nilq/baby-python | python |
#coding=utf-8
from datetime import datetime
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from aops.settings import INT_CHOICES, STATUS_CHOICES
from cmdb import signals
from cmdb.models.ip_record import IpRecord
from cmdb.models.physical_server import Phy... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
from unittest import TestCase
from simstring.measure.cosine import CosineMeasure
class TestCosine(TestCase):
measure = CosineMeasure()
def test_min_feature_size(self):
self.assertEqual(self.measure.min_feature_size(5, 1.0), 5)
self.assertEqual(self.measure.min_feature_s... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 15:28:07 2020
@author: ESOL
"""
# Import module
import jpype
# Enable Java imports
import jpype.imports
# Pull in types
from jpype.types import *
jpype.addClassPath('C:/Users/esol/OneDrive - Equinor/programming/neqsim/NeqSim.jar')
# Launch the JVM
#jpype.startJVM()
... | nilq/baby-python | python |
from fontbakery.callable import check
from fontbakery.callable import condition
from fontbakery.checkrunner import Section, PASS, FAIL, WARN
from fontbakery.fonts_profile import profile_factory
from tests.test_general import (
is_italic,
com_roboto_fonts_check_italic_angle,
com_roboto_fonts_check_fs_type,
... | nilq/baby-python | python |
import socket as sk
import sys
import threading
from PyQt4.QtCore import *
MAX_THREADS = 50
#def usage():
#print("\npyScan 0.1")
#print("usage: pyScan <host> [start port] [end port]")
class Scanner(threading.Thread):
def __init__(self, host, port):
threading.Thread.__init__(self)
# host an... | nilq/baby-python | python |
"""
Tyson Reimer
October 08th, 2020
"""
import os
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy.stats import norm
from umbms import get_proj_path, get_script_logger
from umbms.loadsave import load_pickle
##############################################################... | nilq/baby-python | python |
#encoding=utf-8
import sys
#encoding=utf-8
'''
SocialMiner
https://github.com/paulyang0125/SocialMiner
Copyright (c) 2015 Yao-Nien, Yang
Licensed under the MIT license.
'''
import re
from optparse import OptionParser
import nltk
#from nltk import *
import nltk.cluster
import nltk.cluster.kmeans
import nltk.cluster.... | nilq/baby-python | python |
#!/usr/bin/python
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Allow creation of uart/console interface via usb google serial endpoint."""
import argparse
import array
import exceptions
import os
... | nilq/baby-python | python |
import numpy as np
# general convolve framework
def convframe(input, weight, output=None, init=0,
mode='reflect', buffertype=None, keeptype=True, func=None):
if output is None:
output = np.zeros(input.shape, buffertype or input.dtype)
output[:] = input if init is None else init
buf = np... | nilq/baby-python | python |
import unittest
from user import User
class UserTest(unittest.TestCase):
"""
Test class that defines test cases for the contact class behaviours.
Args:
unittest.TestCase: Inherits the testCase class that helps in creating test cases
"""
def setUp(self):
"""
Set up method to ... | nilq/baby-python | python |
# Generated by Django 2.0.8 on 2018-08-12 16:09
from django.db import migrations, models
from django_add_default_value import AddDefaultValue
class Migration(migrations.Migration):
dependencies = [("dadv", "0001_initial")]
operations = [
migrations.CreateModel(
name="TestTextDefault",
... | nilq/baby-python | python |
import boto3
import json
from datetime import datetime, timedelta
from botocore.client import Config
def handler(event, context):
s3 = boto3.client('s3', config=Config(signature_version='s3v4'))
BUCKET_NAME = 'photostorage113550-dev';
s3_bucket_content = s3.list_objects(Bucket=BUCKET_NAME)['Contents']
contents... | nilq/baby-python | python |
import collections
import logging
import os
import time
import suds.xsd.doctor
import suds.client
from suds.plugin import MessagePlugin
from suds import WebFault
from . import base
logger = logging.getLogger(__name__)
# Suds has broken array marshaling. See these links:
# http://stackoverflow.com/questions/351981... | nilq/baby-python | python |
import os
import random
import sys, getopt
def getDesiredROMCount():
#Asks the user how many roms they want to select from, loops until it gets a valid input
asking = True
numFiles = 0
while asking:
try:
numFiles = int(input("Please enter the number of games you'd like randomly sel... | nilq/baby-python | python |
"""Auth namespace contains the class to manage authentication: Credentials.
It also includes the utility functions
:func:`cartoframes.auth.set_default_credentials` and
:func:`cartoframes.auth.get_default_credentials`."""
from __future__ import absolute_import
from .credentials import Credentials
from .defaults import ... | nilq/baby-python | python |
from telnetlib import Telnet
import os
import sys
import time
#1; E e geo eclip 2018-jan-01 00:00 2018-jan-02 00:00 1d
#ASTNAM=1 TABLE_TYPE= 'ELEMENTS e geo eclip START_TIME='2018-jan-01' STOP_TIME='2018-jan-02' STEP_SIZE='1 d'
tn=Telnet('horizons.jpl.nasa.gov', 6775)
#tn.set_debuglevel(10)
for i in range(30)... | nilq/baby-python | python |
# Copyright 2021 Google LLC. 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 applicable law or a... | nilq/baby-python | python |
from __future__ import division
import torch
import pytorch_warpctc
from ._warp_ctc import *
from .validators import validate_inputs
class CTCAutogradFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, activations, labels, lengths, label_lengths, take_average=True, blank=None):
use_cuda... | nilq/baby-python | python |
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 10
a = 1... | nilq/baby-python | python |
def fill_matrix(matrix, input_var, option=0):
for row in range(input_var[0]):
if option == 1:
row_input = [int(x) for x in input().split(" ")]
else:
row_input = [float(x) for x in input().split(" ")]
matrix.append(row_input)
return
def add_matrix(m... | nilq/baby-python | python |
from django.contrib.auth.models import User
from rest_framework import serializers
from ..models import Game
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'is_staff')
class GameSerializer(serializers.ModelSerializer):
creato... | nilq/baby-python | python |
extensions = ['sphinx.ext.autosectionlabel']
autosectionlabel_prefix_document = True
| nilq/baby-python | python |
from fastapi.testclient import TestClient
from main import app
from unittest import TestCase, mock
from persistence.repositories.question_template_repository_postgres import QuestionTemplateRepositoryPostgres
from infrastructure.db.question_template_schema import QuestionTemplate, QuestionTypeEnum
import json
import os... | nilq/baby-python | python |
# coding=utf-8
import time
import re
import zlib
import random
from gzip import GzipFile
from PIL import Image
# 兼容2.7和3.x
try:
from io import BytesIO as StringIO
except ImportError:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
'''
百度云引擎工具模块
'''
d... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Application: COMPOSE Framework - K-Nearest Neighbors Algorithm
File name: knn.py
Author: Martin Manuel Lopez
Creation: 10/20/2021
The University of Arizona
Department of Electrical and Computer Engineering
College of Engineering
"""
# MIT License
#
# ... | nilq/baby-python | python |
import csv
import logging
import os
import string
import numpy as np
import tensorflow as tf
from gensim.models import KeyedVectors
from sklearn.metrics.pairwise import cosine_similarity
from keyed_vectors_prediction_config import KeyedVectorsPredictionConfig
class KeyedVectorsFormatPredictor:
def __init__(sel... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
import banners
from constants import *
from scipy import stats
#%% Model parameters
n=1 # Number successes
p_cons = banners.DEFAULT_EVENT_RATES.fiveStarCons #* banners.DEFAULT_EVENT_RATES.fiveStarPriorityRate# Probability of success
primo_spend = 181
usd_spend = ... | nilq/baby-python | python |
"""Routing manager classes for tracking and inspecting routing records."""
import json
from typing import Sequence
from ...config.injection_context import InjectionContext
from ...error import BaseError
from ...messaging.util import time_now
from ...storage.base import BaseStorage, StorageRecord
from ...storage.error... | nilq/baby-python | python |
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField, DateField, SelectField
from wtforms.validators import DataRequired, Optional
from wotd.models import PartOfSpeech
class WordForm(FlaskForm):
word = StringField('Word', validators=[DataRequired()])
part_o_speech = Sele... | nilq/baby-python | python |
import re
import os
import argparse
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from dataloader import LOSO_sequence_generate
# Selected action units
AU_CODE = [1, 2, 4, 10, 12, 14, 15, 17, 25]
AU_DICT = {
number: idx
for idx, number in enumerate(AU_CODE)
}
def evaluate_adj(df, arg... | nilq/baby-python | python |
# Unit test _bayesian_search_skopt
# ==============================================================================
import pytest
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import Ridge
from skopt.space import Categorical, Real, Integer
from skopt... | nilq/baby-python | python |
import os
import sys
import logging
import csv
from py.hookandline.HookandlineFpcDB_model import database, TideStations, Sites
class SiteManager:
def __init__(self, app=None, db=None):
super().__init__()
self._logger = logging.getLogger(__name__)
self._app = app
self._db = db
... | nilq/baby-python | python |
#
# utilities.py
#
# (c) 2017 by Andreas Kraft
# License: BSD 3-Clause License. See the LICENSE file for further details.
#
# This module defines various internal utility functions for the library.
#
from lxml import etree as ET
import onem2mlib.constants as CON
import onem2mlib.utilities as UT
import onem2mlib.mcare... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: networking/v1alpha3/workload_entry.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 _messa... | nilq/baby-python | python |
from ..query.grammars import SQLiteGrammar
from .BaseConnection import BaseConnection
from ..schema.platforms import SQLitePlatform
from ..query.processors import SQLitePostProcessor
from ..exceptions import DriverNotFound, QueryException
class SQLiteConnection(BaseConnection):
"""SQLite Connection class."""
... | nilq/baby-python | python |
########## Script 1 ###################
import sys
from RK_IO_model import RK_IO_methods
from Generalized_RK_Framework import generalized_RK_framework
import pdb #for debugging
import numpy as np
import pyomo.environ as pyo
from pyomo.opt import SolverFactory
from pyomo.opt import SolverStatus,... | nilq/baby-python | python |
str2slice = "Just do it!"
print(str2slice[10]) # prints "!"
print(str2slice[5:7]) # prints "do"
print(str2slice[8:]) # prints "it!"
print(str2slice[:4]) # prints "Just"
print("Don't " + str2slice[5:]) # prints "Don't do it!"
| nilq/baby-python | python |
import abc
from typing import Any
from typing import Dict
from typing import Optional
from typing import Sequence
from optuna.distributions import BaseDistribution
from optuna.study import Study
from optuna.trial import FrozenTrial
from optuna.trial import TrialState
class BaseSampler(object, metaclass=abc.ABCMeta):... | nilq/baby-python | python |
from ledfx.effects.temporal import TemporalEffect
from ledfx.effects.gradient import GradientEffect
#from ledfx.color import COLORS, GRADIENTS
#from ledfx.effects import Effect
import voluptuous as vol
import numpy as np
import logging
class FadeEffect(TemporalEffect, GradientEffect):
"""
Fades through the col... | nilq/baby-python | python |
import numpy as np
from hand import Hand
from mulliganTester import MulliganTester
class BurnMullTester(MulliganTester):
hand_types = ["twolandCreature","goodhand","keepable"]
hand = Hand("decklists/burn.txt")
output_file_header = "burn"
land_value_list = ["Mountain", "Bloodstained Mire", "Inspiring V... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.