content stringlengths 5 1.05M |
|---|
import numpy as np
import json
import AllData as ad
def get_speed_data(data_d, speed, ordered_params):
# convert speed to string (key)
speed = str(speed);
assert(speed in data_d);
speed_data = data_d[speed]["out_norm"];
num_params = len(ordered_params);
num_trials = len(speed_data["0"]);
... |
""" inherits common methods """
from .base import BaseModel
class Categorymodel(BaseModel):
"""
Category Model has saved data
"""
def __init__(self):
self.category = []
self.products = []
def get_categories(self):
"""
get all categories
"""
... |
initcode_orig =[1,12,2,3,1,1,2,3,1,3,4,3,1,5,0,3,2,9,1,19,1,19,6,23,2,6,23,27,2,27,9,31,1,5,31,35,1,35,10,39,2,39,9,43,1,5,43,
47,2,47,10,51,1,51,6,55,1,5,55,59,2,6,59,63,2,63,6,67,1,5,67,71,1,71,9,75,2,75,10,79,1,79,5,83,1,10,83,87,1,
5,87,91,2,13,91,95,1,95,10,99,2,99,13,103,1,103,5,107,1,107,13... |
import pygame
class Component:
def __init__(self, position, size):
self.position = position
self.size = size
def is_clicked(self, event):
mouse = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONUP:
if (
self.position[0] < mouse[0] < self.p... |
#!/usr/bin/env python3
# Script to remove files older than three months
# Import serious stuff
import os
import shutil
import argparse
from datetime import datetime
import pdb
# Generate list of files to be deleted
def generate_list(start_path, oldfile_age):
# List of files to be removed
remove_list = []
... |
import unittest
import vimdoc
from vimdoc.block import Block
from vimdoc import error
from vimdoc import module
class TestVimModule(unittest.TestCase):
def test_section(self):
plugin = module.VimPlugin('myplugin')
main_module = module.Module('myplugin', plugin)
intro = Block(vimdoc.SECTION)
intro.L... |
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.template import loader
from django.urls import reverse_lazy
@login_req... |
# pylint:disable=import-outside-toplevel
"""Registry of custom Gym environments."""
import importlib
import gym
from .utils import wrap_if_needed
def filtered_gym_env_ids():
"""
Return environment ids in Gym registry for which all dependencies are installed.
"""
specs = set(gym.envs.registry.all())
... |
### sorting
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
return sorted(A, key=lambda x: x % 2)
### two pass
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
return [i for i in A if not i % 2] + [i for i in A if i % 2]
|
import os.path
import random
import ConfigFile
initialized = False
dists = {}
class Distribution:
def __init__(self, probs):
self.probabilities = [min(max(p, 0), 1) for p in probs]
if ((not self.probabilities) or (self.probabilities[-1] >= 1)):
self.probabilities.append(0)
def getCount(self):
count = 0
... |
#!/usr/bin/env python3
from wx_explore.common.models import (
Source,
SourceField,
Location,
Timezone,
)
from wx_explore.common import metrics
from wx_explore.common.db_utils import get_or_create
from wx_explore.web.core import db
sources = [
Source(
short_name='hrrr',
name='HRRR ... |
import argparse
import sys
from configparser import ConfigParser
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.session import Session
class OracleDBManager(object):
def __init__(
self,
connection_string: str
) -> None... |
from time import sleep
from selenium import webdriver
from subprocess import Popen
URL = 'http://www.specialeffect.org.uk/gameblast'
def write_to_text_file(file_name='', amount_to_write=''):
print('Writing to text file: {}'.format(file_name))
with open(file_name, 'w') as file:
file.write(amount_to_wr... |
#
# @lc app=leetcode id=1365 lang=python3
#
# [1365] How Many Numbers Are Smaller Than the Current Number
#
# @lc code=start
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
result = []
for index, number in enumerate(nums):
temp = [y for y in [x for i, ... |
#!/usr/bin/env python
import codecs
import csv
import datetime
import getpass
import optparse
import pymysql
import sys
parser = optparse.OptionParser(
'./load_antolin_db.py [-d <dbname>] [-u user] [-p password] csv-file')
parser.add_option('-d', '--database', dest='database', default='spils',
h... |
import torch
from torch_geometric.nn import ARMAConv
def test_arma_conv():
in_channels, out_channels = (16, 32)
num_stacks, num_layers = 8, 4
edge_index = torch.tensor([[0, 0, 0, 1, 2, 3], [1, 2, 3, 0, 0, 0]])
num_nodes = edge_index.max().item() + 1
edge_weight = torch.rand(edge_index.size(1))
... |
import unittest
from unittest.mock import MagicMock
import shutil
import glob
import os
import os.path
import logging
from PIL import Image
from Psd2Png import Psd2Png
class TestPsd2PngBase(unittest.TestCase):
#テスト実行の都度、過去に生成したフォルダを削除します。
def setUp(self):
self.logger = logging.getLogger("TEST")
... |
import serial #requires python-serial to be installed on system
import time
arduino_location = '/dev/ttyACM0'
arduino_port = 9600
arduino = serial.Serial(arduino_location, arduino_port)
def get_temp():
raw = arduino.readline()
return float(raw.decode())
def turn_relay_on():
arduino.write('1'.encode... |
# Generated by Django 2.1.7 on 2019-03-20 08:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('examples', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='basicfields',
name='float_field',
... |
from __future__ import unicode_literals
import re
from .util import (
extract_user_from_cookies,
FileProgress,
options,
parse_date,
sql_filter,
TableSizeProgressBar,
)
from .sources import get_requests_from_db
@options([], requires_db=True)
def action_load_requestlog(args, config, db, wdb):
... |
import numpy as np
from gpucsl.pc.pc import GaussianPC
from gpucsl.pc.helpers import correlation_matrix_of
from gpucsl.pc.kernel_management import Kernels
from tests.equality import check_graph_equality, graph_equality_isomorphic
from .fixtures.input_data import Fixture, input_data
import pytest
import networkx as nx
f... |
from prepare_mesh_lib.file_reader2 import FileReader
def main():
print('-' * 25)
print('Put full filename to parse mesh from:')
filename = input() # Файл, который надо распарсить. Полное имя.
# mesh_dir = input()
mesh_dir = 'prepared_meshes' # Папка где будут лежать готовые сетки.
# raw_mesh... |
# encoding: utf-8
from miniworld.model.singletons.Singletons import singletons
from miniworld.model.spatial.MovementPattern.ReplayMovementPattern import ReplayMovementPattern
__author__ = "Patrick Lampe"
__email__ = "uni at lampep.de"
class ReplayNode():
def __init__(self, node_id):
self.crnt_movement_p... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains functions and classes related with meta system
"""
import copy
import pprint
import logging
import traceback
import maya.cmds
from tpDcc.dccs.maya.core import common, attribute as attr_utils, name as name_utils, shape as shape_utils
logger = l... |
from pk_classifier.bootstrap import split_train_val_test
FEATURES_SAMPLE = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
LABELS_SAMPLE = {'label': [0, 1, 0, 1, 0, 1, 0, 1, 0, 1], 'pmid': [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]}
def test_split_train_val_test():
x_train, x_dev, x_test, y_train, y_dev, \
y_test, pmids_train,... |
from core import Asset
from core import GridBot
from datetime import datetime
from core import grid_bot_optimization
def test_answer():
# "btc-usd_2021-01-01_2021-03-31.csv"
# a1 = Asset("BTC-USD.csv")
a1 = Asset("btc-usd_2021-01-01_2021-03-31.csv")
assets = [a1]
best = grid_bot_optimizati... |
import base64
import datetime
import io
import os
from os import listdir
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import ntpath
import csv
import pandas as pd
# from extra import find_pfds_csv
from pfd import... |
"""
Name: Reissner-Nordstrom Electro-Vacuum
References:
- Reissner, Ann. Phys., v50, p106, (1916)
- Stephani (13.21) p158
Coordinates: Spherical
Symmetry: Spherical
"""
from sympy import diag, sin, symbols
coords = symbols("t r theta phi", real=True)
variables = symbols("M Q", constant=True)
functions = ()
t, ... |
from django.apps import AppConfig
class StagedoorConfig(AppConfig):
name = "stagedoor"
|
from pyoperant.errors import * |
#!/usr/bin/env python
import logging, logging.config
import numpy as np
import yaml
import cv2
import os
from operator import attrgetter, itemgetter
from collections import namedtuple
# The FLANN Index enums aren't exposed in the OpenCV Python bindings. We create
# our own in accordance with:
# https://github.com/It... |
data = (
'Ku ', # 0x00
'Ke ', # 0x01
'Tang ', # 0x02
'Kun ', # 0x03
'Ni ', # 0x04
'Jian ', # 0x05
'Dui ', # 0x06
'Jin ', # 0x07
'Gang ', # 0x08
'Yu ', # 0x09
'E ', # 0x0a
'Peng ', # 0x0b
'Gu ', # 0x0c
'Tu ', # 0x0d
'Leng ', # 0x0e
'[?] ', # 0x0f
'Ya ', # 0x10
'Qian ', ... |
import numpy as np
from scipy.integrate import odeint
from sgp4.api import Satrec
from astropy.time import Time
import astropy
from astropy import units as u
from astropy.coordinates import EarthLocation, ITRS, FK5, CartesianDifferential, CartesianRepresentation
if float(astropy.__version__[0:3]) > 4.1:
from astr... |
#!/usr/bin/env python3
import argparse
import os
import re
import sys
from typing import IO, List, Optional
from colors import COLORS, Style
from system_info import get_system_info
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--hide-logo", action="store_true")
parser.add_argumen... |
# Copyright 2017 gRPC 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 writing... |
# ##################################################################################################
# Copyright (c) 2020. HuiiBuh #
# This file (test_auth_flows.py) is part of AsyncSpotify which is released under MIT. #
# You are not al... |
'''
Configure Seaborn through a RC file, similarly to how Matplotlib does it.
To load the configuration from the RC file, simply import this package after
seaborn:
>>> import seaborn as sns
>>> import seaborn_rc
To reload the rc:
>>> seaborn_rc.load()
The RC file used is the first found in the following list:
- `$... |
# Copyright 2017 Covata Limited or its affiliates
#
# 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... |
import asyncio
import datetime
from nonebot import get_driver, logger, on_command, require
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message
from nonebot.params import CommandArg
from nonebot.permission import SUPERUSER
from utils.config_util import SubManager, SubList
from utils.utils import get_diff... |
# Pandas Data Operation
import pandas as pd
import numpy as np
def make_df(cols, ind):
"""Quickly make a DataFrame"""
data = {c: [str(c) + str(i) for i in ind]
for c in cols}
return pd.DataFrame(data, ind)
def concatenation():
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
print(... |
import tokenize
import token
from StringIO import StringIO
def fixLazyJsonWithComments (in_text):
""" Same as fixLazyJson but removing comments as well
"""
result = []
tokengen = tokenize.generate_tokens(StringIO(in_text).readline)
sline_comment = False
mline_comment = False
last_token = ''
for toki... |
# Generated by Django 3.2.1 on 2021-05-20 21:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Acct',
fields=[
... |
# ---------------------------------------------------------------
# visual_spatial.py
# Set-up time: 2020/4/28 下午8:46
# Copyright (c) 2020 ICT
# Licensed under The MIT License [see LICENSE for details]
# Written by Kenneth-Wong (Wenbin-Wang) @ VIPL.ICT
# Contact: wenbin.wang@vipl.ict.ac.cn [OR] nkwangwenbin@gmail... |
def DitBonjour():
print("Bonjour")
def DivBy2(x):
return x/2
|
import random
from os import path
from tempfile import TemporaryDirectory
import numpy as np
import torch
from deepsnap.batch import Batch
from deepsnap.dataset import GraphDataset
from graphgym.config import assert_cfg, cfg
from graphgym.model_builder import create_model
from graphgym.utils.device import auto_select_... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Ramon van der Winkel.
# All rights reserved.
# Licensed under BSD-3-Clause-Clear. See LICENSE file for details.
from django.test import TestCase
from Functie.models import maak_functie
from NhbStructuur.models import NhbRegio, NhbVereniging
from Sporter.models import Sp... |
from common.mongo.bson_c import json_util
from model import merchant
merchants = merchant.populates(filter={'support': {'$nin': [None, '']}},
projection={'_id': 1, 'name': 1, 'sname': 1, 'support': 1},
sort=[('_id', 1)],
skip=... |
from random import randint
def key(_arg):
"""
Returns a random integer in [0, 2**64)
Outgoing correlation between original and sorted < 1%
Also have tried:
* `hash(arg)` 17% correlation
* `id(arg)` 98% correlation
"""
return randint(0, 2 ** 64 - 1)
|
# Generated by Django 3.0.5 on 2020-06-06 23:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('trainings', '0004_auto_20200601_2052'),
]
operations = [
migrations.DeleteModel(
name='NetworkBayesianRatingConfiguration',
),
... |
"""Include single scripts with doc string, code, and image
Use case
--------
There is an "examples" directory in the root of a repository,
e.g. 'include_doc_code_img_path = "../examples"' in conf.py
(default). An example is a file ("an_example.py") that consists
of a doc string at the beginning of the file, the exampl... |
from setuptools import setup
from setuptools import find_packages
setup(name='gcncc',
version='0.2',
description='Graph Convolutional Network for Clustering and Classification',
author='Omar Maddouri',
author_email='omar.maddouri@gmail.com',
url='https://github.com/omarmaddouri',
... |
from .metrics import precision_at_k, dcg_score_at_k, ndcg_score_at_k
# These are not required
del metrics
|
import logging
import os
import sys
PROJECT_ROOT = os.path.abspath(os.path.split(os.path.split(__file__)[0])[0])
logging.disable(logging.CRITICAL)
ROOT_URLCONF = 'urls'
STATIC_URL = '/static/'
STATIC_ROOT = '%s/staticserve' % PROJECT_ROOT
STATICFILES_DIRS = (
('global', '%s/static' % PROJECT_ROOT),
)
UPLOADS_DIR... |
from django.shortcuts import render
# Create your views here.
from django.views.decorators.cache import cache_page
from services.blog.blog_service import BlogService
from services.blog.category_service import CategoryService
# @cache_page(300)
def index(request):
"""
首页-
:param request:
:return:
... |
from unittest import TestCase
from .problem_6_18_spiral_ordering import *
class TestSolution(TestCase):
def testTopPrinting(self):
self.assertEqual([1, 2, 3], print_top([[1, 2, 3]], 0, 0, 3))
def testBottomPrinting(self):
self.assertEqual([3, 2, 1], print_bottom([[1, 2, 3]], 0, 0, 3))
de... |
"""
@author: Deniz Altinbuken, Emin Gun Sirer
@note: Queue proxy
@copyright: See LICENSE
"""
from concoord.clientproxy import ClientProxy
class Queue:
def __init__(self, bootstrap, timeout=60, debug=False, token=None):
self.proxy = ClientProxy(bootstrap, timeout, debug, token)
def __concoordinit__(self... |
from selenium import webdriver
from bs4 import BeautifulSoup
import re
from tmdbv3api import TMDb, TV, Season, Movie
from module.api_key import MY_API_KEY
tmdb = TMDb()
tmdb.api_key = MY_API_KEY
debug=0
def get_ep_list(id, season):
"""Return a dictionary of episodes list from MovieDb, return None if not found"""
... |
# Copyright (C) [2021] by Cambricon, Inc.
#
# 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 use, copy, modify, merge, publish... |
# Copyright 2020 MONAI Consortium
# 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... |
from PyQt5.QtWidgets import QDialog
from UI.Layouts.EvolutionParametersDialog import Ui_EvolutionParametersDialog
class EvolutionParametersDialog(QDialog):
def __init__(self, parent = None):
QDialog.__init__(self, parent)
self.ui = Ui_EvolutionParametersDialog()
self.ui.setupUi(self)
... |
from datasets.decorators import OrderDataset
from datasets.utils import FullDatasetBase
from torchvision.datasets import cifar
from torchvision import transforms
from torch.utils.data import Dataset
from torch.utils.data.dataset import Subset
class CIFAR100(FullDatasetBase):
mean = (0.5071, 0.4865, 0.4409)
st... |
# coding: utf-8
import os
DEFAULT_TEMPLATE = os.environ.get("DEFAULT_TEMPLATE")
if not DEFAULT_TEMPLATE:
DEFAULT_TEMPLATE = '''{"id": $count, "ts": "$ts"}'''
|
"""Data model and functions for Tapis profiles
"""
from tapis_cli.commands.taccapis.v2 import SERVICE_VERSION
from tapis_cli.commands.taccapis import TapisModel
from tapis_cli.display import Verbosity
from tapis_cli.search import argtype, argmod
__all__ = ['Profile', 'API_NAME', 'SERVICE_VERSION']
API_NAME = 'profile... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 19 19:05:05 2022
@author: Alexander Southan
"""
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from pyRandomWalk import random_walk
# Define the box for the random walks
limits = {'r': 0.75, 'x_c': 0.5, 'y_c': 0.5}
# Genera... |
# -*- coding: utf-8 -*-
"""
Useful utility decorators.
"""
class renamed:
"""Decorator to mark functions are renamed and will be removed some later
```
@pg.renamed(newname, '1.2')
def oldname(args, kwargs):
pass
```
"""
def __init__(self, newFunc, removed=''):
self.newFunc... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from mailing.utils import html_to_text
class HtmlToTextTestCase(TestCase):
def test_no_html(self):
html = "Ceci est du HTML sans balises"
text = "Ceci est du HTML sans balises"
self.assertEqual(html_to_text(html), text)
def te... |
import streamlit as st
# SETTING PAGE CONFIG TO WIDE MODE
#st.set_page_config(layout="wide")
#lottie_book = load_lottieurl('https://assets4.lottiefiles.com/temp/lf20_aKAfIn.json')
def load_page(df_metadata_complete):
###Streamlit app
row1_spacer1, row1_1, row1_spacer2 = st.beta_columns((0.01, 3.2, 0.01))
... |
# Angold4 20200613
import Complexity
def normal_power(x, n):
"""Complexity: O(n)"""
if n == 0:
return 1
else:
return x * normal_power(x, n-1)
def power(x, n):
"""Complexity: O(log n)"""
if n == 0:
return 1
else:
partial = power(x, n // 2)
result = par... |
from flask import Flask, render_template, Response
import datetime
from Camera import VideoCamera
app = Flask(__name__)
@app.route("/")
def index():
now = datetime.datetime.now()
timeString = now.strftime('%I:%M:%S')
templateData = {
'title' : 'KittyTalk',
'time': timeString,
}
return ren... |
# -*- coding: utf-8 -*-
from urllib2 import urlopen
import urllib
import json
import base64
class BaiduRest:
def __init__(self, cu_id, api_key, api_secert):
# token认证的url
self.token_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
... |
#!/usr/bin/env python
"""
"""
from .bpsf_keys import *
from .h5_file_ops import * |
x = input("player A: ")
y = input("player B: ")
def game(x,y):
if x==y:
print ("It is a tie")
elif x=="paper" and y=="rock":
print ("A won")
elif x=="paper" and y=="scissors":
print("B won")
elif x=="rock" and y=="paper":
print ("B won")
elif x=="rock" and y=="sciss... |
import logging
from stocks import tsx
from stocks.tsx import TSX
logging.basicConfig(
filename="logs.log",
filemode="w",
level=logging.INFO,
format="{asctime} {levelname:<8} {message}",
style='{'
)
# Date range for historical data download
start_date = "2015-01-01"
end_date = "2020-12-31"
loggi... |
# Copyright L.P.Klyne 2013
# Licenced under 3 clause BSD licence
import sys, logging , time , os , thread
import unittest
from EventHandlers.tests.DummyRouter import *
from EventHandlers.hvac_components import *
from EventLib.Event import *
from MiscLib.DomHelpers import *
from EventHandlers.EventRouterLoad import ... |
# Generated by Django 3.1.3 on 2020-11-30 14:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='product',
name='available',
... |
"""
@author: Rossi
@time: 2021-01-26
"""
import json
import re
from Broca.utils import find_class, list_class
from Broca.task_engine.slot import Slot
from .event import UserUttered, BotUttered
from .skill import ConfirmSkill, FormSkill, ListenSkill, OptionSkill, Skill, UndoSkill, DeactivateFormSkill
class Agent:
... |
from pyknow import *
class Counter(Fact):
counter_normal=Field(int, default=0)
counter=Field(int, default=0)
class Result(Fact):
pass
class Input(Fact):
pass
class Output(Fact):
def retrieve(self):
return self.as_dict()
class State(Fact):
pass
class ExpertSystem(KnowledgeEngi... |
import numpy
from keras import backend as K
import keras
import time
from keras.datasets import mnist
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.models impor... |
import json
import uuid
from flask import jsonify, request
from flask_classy import FlaskView
from app.exceptions.exceptions import DomainError
from app.service.domain.service import Service as Service_Domain
from app.service.database.service import Service as Service_DB
from utils.celery.celery import start_search... |
from assembler import Assembler
class Section:
header = 0
length = 0
name = ""
type = ""
def __init__(self,header,length,name,type):
self.header = header
self.length = length
self.name = name
self.type = type
class Section_table:
header = 0
num = 0
module... |
import asyncio
from datetime import datetime, timedelta
version = None
async def get_cmd_output(cmd, do_strip=True):
proc = await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE)
stdout, _ = await proc.communicate()
output = stdout.decode('utf-8')
if do_strip:
return outpu... |
# -*- coding: utf-8 -*-
import glob
import os
import re
from zhon.hanzi import punctuation
if __name__ == "__main__":
output_path = "jieba1.txt"
fout = open(output_path, 'wb')
dic = {}
input_dir = "/Volumes/MyDisk/studio/ai/Tacotron/data_thchs30/"
trn_files = glob.glob(os.path.join(input_dir,... |
#What's Your Name
#https://www.hackerrank.com/challenges/whats-your-name/problem
def print_full_name(a, b):
print("Hello {} {}! You just delved into python.".format(a, b))
|
import json
from phonepiece.config import phonepiece_config
from phonepiece.inventory import read_inventory
from phonepiece.grapheme import read_grapheme
from phonepiece.unit import read_unit
import numpy as np
def rec_read_cart_tree(tree_dict):
node = Node(None)
if tree_dict['left_set'] is not None:
... |
import numpy as np
import math
def shortestLRTime():
henry = float(input('Henry: '))
Count = float(input('Count of resistors: '))
ohms = float(input('ohms: '))
final = (henry/ohms)
final = final / Count
print(final)
shortestLRTime() |
# Initialize!
|
class Solution:
def solve(self, n):
facts = [prod(range(1,i+1)) for i in range(1,13)]
def solve(n, right_bound):
if n == 0: return True
right_bound = min(right_bound, bisect_right(facts,n))
return any(n - facts[i] >= 0 and solve(n-facts[i], i) for i in range(righ... |
n = int(input())
h = [int(x) for x in input().split()]
if n == 2 and h[0] == h[1]:
pico = 0
else:
pico = 1
for i in range(1, n-1):
if not ((h[i] < h[i-1] and h[i] < h[i+1]) or (h[i] > h[i-1] and h[i] > h[i+1])):
pico = 0
break
print(pico) |
# Python
#
# This module implements the Main Markdown class.
#
# This file is part of mdutils. https://github.com/didix21/mdutils
#
# MIT License: (C) 2018 Dídac Coll
"""Module **mdutils**
The available features are:
* Create Headers, Til 6 sub-levels.
* Auto generate a table of contents.
* C... |
"""
unittest for Astronomy
"""
import unittest
import Astronomy.formats
class testDatesTimes(unittest.TestCase):
def test_dms_delimited_angle_to_rads(self):
self.assertEqual(Astronomy.formats.dms_delimited_angle_to_rads('''19d14'33.801860"'''),
0.33584886884199222)
def test_hms_delim... |
# %%
from enum import Enum, Flag, auto
from pandas.core.frame import DataFrame
class Band(Enum):
R = 'R'
G = 'g'
class AlertType(Flag):
cand = auto()
ulim = auto()
llim = auto()
# %%
# extract a band.
def extract_info(lightcurve: DataFrame, band: Band, alertType: AlertType):
'''
@retu... |
import numpy as np
from sklearn import model_selection, metrics
from .containers import Data
from .querystrategies import QueryStrategy, SimpleMargin
'''
>>> from sklearn.svm import NuSVC
>>> clf = NuSVC(nu= 0.46, probability=True)
>>> qs = LeastConfidence(model_change=False)
>>> learner = ActiveLearningModel(clf, qs... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import connection, models, migrations
import cityhallmonitor.models
def add_text_tsvector_index(apps, schema_editor):
MatterAttachment = apps.get_model('cityhallmonitor', 'MatterAttachment')
db_table = MatterAttachment._meta.db_ta... |
# You are given two strings, str_1 and str_2, where str_2 is generated by randomly shuffling str_1 and then adding one letter at a random position.
# Write a function that returns the letter that was added to str_2.
# Examples:
# csFindAddedLetter(str_1 = "bcde", str_2 = "bcdef") -> "f"
# csFindAddedLetter(str_1 = "... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Created on May 15, 2019
@author: Robert BASOMINGERA
@Ajou University
This project is developed and tested with Python3.5 using pycharm on an Ubuntu 16.04 LTS machine
'''
from keras.applications.vgg19 import VGG19
# from keras.applications.vgg19 import decode_predicti... |
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import detail_route
from rest_framework import status
from rest_framework.decorators import de... |
from SOC.models import BTW
import numpy as np
import pytest
def test_boundary_shape():
sim = BTW(10)
assert sim.values.shape == (12, 12)
assert sim.L_with_boundary == 12
def test_run():
sim = BTW(10)
sim.run(10)
def test_deterministic_result():
b = BTW(5, save_every = 1)
... |
from DateTime import DateTime
class Flight:
def __init__(self, id, source, destination, departure_time, airfare, number_of_seats_available):
self.iD = id
self.source = source
self.destination = destination
self.departure_time = departure_time
self.airfare = airfare
s... |
from amuse.community import *
from amuse.test.amusetest import TestWithMPI
from .interface import vaderInterface
from .interface import vader
class vaderInterfaceTests(TestWithMPI):
def test1(self):
instance = vader()
instance.initialize_code()
instance.initialize_keplerian_grid(128, ... |
import cv2
import numpy as np
#image_path
img_path= r"C:\Users\evan\Documents\GitHub\OCR-Project\sample.jpg"
#read image
img_raw = cv2.imread(img_path)
#select ROIs function
ROIs = cv2.selectROIs("Select Rois",img_raw)
#print rectangle points of selected roi
print(ROIs)
#Crop selected roi ffrom raw image
#counte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.