content stringlengths 5 1.05M |
|---|
from datetime import datetime, timedelta
birthday = input('When is your birthday (dd/mm/yyyy)? ')
birthday_date = datetime.strptime(birthday, '%d/%m/%Y')
print('Birthday ' = str(birthday_date))
one_day = timedelta(days=1)
birthday_eve = birthday_date - one_day
print("Day before birthday " + str(birthday_eve)) |
r1 = float(input('comprimento da reta 1: '))
r2 = float(input('Comprimento da reta 2: '))
r3 = float(input('Comprimento da reta 3: '))
if r1 < (r2+r3) and r2 < (r1+r3) and r3 < (r1+r2):
print('Sim, é possível formar um triângulo!')
else:
print('Não, não é possível formar um triângulo!')
|
# -*- coding: utf-8 -*-
# 获取引擎服务端API的模块
import server.extraServerApi as serverApi
# 获取引擎服务端System的基类,System都要继承于ServerSystem来调用相关函数
ServerSystem = serverApi.GetServerSystemCls()
# 在modMain中注册的Server System类
class TutorialServerSystem(ServerSystem):
# ServerSystem的初始化函数
def __init__(self, namespace, systemNam... |
from inheritance_exercise.zoo.project.reptile import Reptile
class Lizard(Reptile):
pass |
import glob
import os
import sys
import librosa
import librosa.core
import librosa.feature
import numpy
def select_dirs(dataset_path):
"""
return :
dirs : list [ str ]
load base directory list of data
"""
print("load_directory <- data")
dir_path = os.path.abspath(data... |
import logging
from typing import Set
from discord import Intents
import pathlib
from .patches import SnekBot
logger = logging.getLogger(__name__)
commands_available = """```py
def commands():
return {
sentdebot.member_count(): 'get member count',
sentdebot.community_report(): 'get some stats on ... |
from __future__ import print_function
from uuid import uuid4
from time import time
from simplejson import dumps as serialize_json, loads as deserialize_json
from twisted.internet import reactor, ssl
from twisted.web.client import Agent, BrowserLikeRedirectAgent, readBody
from twisted.web.http_headers import Headers
fr... |
from sqlfaker.column import Column
class PrimaryKey(Column):
"""This column class represents primary key objects of a table.
This class is used to setup a new column that is used as an identifier
in a table. It is a sub class of Column and inherits most of its
attributes.
:param column_name:... |
"""
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
Follow up:
Wh... |
from django.views.decorators.cache import never_cache
from django.views.generic import TemplateView
from rest_framework import viewsets
from .models import AdaptationAction
from .serializers import AdaptationActionSerializer
index_view = never_cache(TemplateView.as_view(template_name="index.html"))
class Adaptation... |
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
import os
from app import app, server
from apps import anmeldung, spanen, lackieren, montage, commonmodules
server.secret_key = os.environ.get('SECRET_KEY',... |
import socket
from test_log import *
from ast import literal_eval
class ServerMainPult:
'''
Класс описывающий систему бекенд- пульта
log - флаг логирования
log cmd - флаг вывода логов с cmd
host - хост на котором будет крутиться сервер
port- порт для подключения
motorpowervalue=1 - пр... |
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense, Dropout, Concatenate, Flatten, Embedding
from tensorflow.keras.regularizers import l2
from cin import CIN
class xDeepFM(Model):
def __init__(self,
feat_dense_num=0,
feat_sparse... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
from piazza_api.piazza import Piazza
__version__ = "0.11.0"
|
import tensorrt as trt
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
import ctypes
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_char_p
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
class PythonEntropyCalibrator(trt.IInt8EntropyCalibrator):
... |
from django.utils import timezone
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.shortcuts import render
from .models import ToDoList
# Create your views here.
class ToDoListListView(ListView):
model = ToDoList
paginate_by = 10 # if pagination i... |
"""
This file will show you how to quantize your network with PPQ
You should prepare your model and calibration dataset as follow:
~/working/model.onnx <-- your model
~/working/data/*.npy <-- your dataset
if you are using caffe model:
~/working/model.caffemdoel <-- your m... |
#!/usr/bin/env python3
import sys
import random
from lib import *
seed(sys.argv[-1])
n = int(sys.argv[1])
m = int(sys.argv[2])
graph = random_connected_undirected_graph_uniform(n, m)
output_graph(n, with_random_weights(graph))
|
from typing import Callable, Union
from warnings import warn
import numpy as np
from specc.analysis.converter import Converter, DEFAULT_CONVERTER
from specc.data.validators import validate_compatible_array, validate_compatible_signals, validate_sample_rate, \
validate_samples
from specc.fourier import fourier_1d,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pony.orm import db_session, select, get
from models.models import Tracker, Project
@db_session
def list_project():
"""
List All Projects
:return:[{
'id': string,
'name': string,
'issue_tracker': {
'tracker_name': str... |
""" glider plotting utilities
"""
import numpy as np
from geometry.quaternion import Quaternion
from geodesy.conversions import enu_to_ned
class Glider3D:
""" 3-D glider
"""
def __init__(self, scale_factor=1):
""" Constructor
Arguments:
scale_factor: wingspan is default 1 unit,... |
import requests
from fabric.api import local
def update():
local('rm -rf fonts/')
local('rm katex.min.css')
local('rm katex.min.js')
local('rm -rf contrib/')
latest_version = requests.get('https://api.github.com/repos/Khan/KaTex/releases/latest').json()['tag_name']
local('wget https://github.co... |
from ..classes import PersonWroteReview, ReviewOfProduct, IsGoldenFlag
import random
from ..meta_classes import DataSetProperties
from ..experiment_1.simple_data_set import SimpleDataSet
from ..utils import DatasetWriter
from graph_io import QueryParams, CypherQuery
from tqdm import tqdm
def run(client, data_set_pro... |
# -*- coding: utf-8 -*-
import unittest
import logging
from tornado.ioloop import IOLoop
from tornado.testing import AsyncTestCase, gen_test
from http2 import SimpleAsyncHTTP2Client
log = logging.getLogger('http2_test_client')
class TestSimpleAsyncHTTP2Client(AsyncTestCase):
def setUp(self):
self.io_l... |
"""
Unit tests for the rotations module
"""
import numpy as np
from . import rotations
def test_quaternion_from_euler():
"""
Tests if the function 'quaternion_from_euler' works for a zero rotation.
"""
assert np.allclose(np.array([1, 0, 0, 0], dtype=float),
rotations.quaterni... |
import pandas as pd
def getPlayerHist(pid,df):
tk1='player1'
tk2='player2'
other = [x for x in list(df.columns) if not("_" in x)]
ext = list(set([y.split('_')[1] for y in [x for x in list(df.columns) if ("_" in x)]]))
pid_df = df[(df[tk1+'_'+ext[0]]==pid)]
pid_df.winner_id=(pid_df["winner_i... |
import numpy as np
from ai.go.go_player import GoPlayer
class RandomPlayer(GoPlayer):
def play(self, color, history, move_history, current_move, mask):
size = history[0].shape[0]
policy = np.random.uniform(size=(size, size))
policy = np.minimum(policy, mask)
point = np.unr... |
#! /usr/bin/env python3
"""
####################################################################
####################################################################
####################################################################
#################### GreenPonik_OneWire_DS18B20 ####################
###############... |
# -*- coding: utf-8 -*-
import random
import torch
from torch.autograd import Variable
import setting
from buildVocab import variableFromSentence, readVocab
def evaluate(nlVocab, codeVocab, encoder, decoder, sentence, max_length=setting.SENTENCE_MAX_LENGTH):
input_variable = variableFromSentence(codeVocab, sen... |
import json
import re
import csv
import math
port = 5655
boltzmann = 1.23 * math.pow(10, -23)
avogadro = 6.02*math.pow(10, 23)
planck = 6.626*math.pow(10, -34)
K = 1.2025 * math.pow(10, -4)
ddd = 3.45 * math.pow(10, -11)
periodic_table = {}
preset_compound_data = {}
class Element:
def __init__(self, name="", small=""... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('gui', '0001_initial'),
('vms', '0001_initial'),
('auth', '0006_require_contenttypes_0002'),
... |
import requests
r = requests.request('GET','http://192.168.1.2/AutomatedDrone/sample.php').json()
print(r)
print(r['A'])
|
from django.test.testcases import SimpleTestCase
from custom.ewsghana.handlers.helpers.formatter import EWSFormatter
class TestFormatter(SimpleTestCase):
def test_parser1(self):
self.assertEqual(EWSFormatter().format('lf10.0mc20.0'), 'lf 10.0 mc 20.0')
self.assertEqual(EWSFormatter().format('LF1... |
from django.shortcuts import render, get_object_or_404
from .models import Pet
def home(request):
pets = Pet.objects.all()
return render(request, 'adoptions/home.html', {'pets':pets})
def pet_detail(request, id):
pet = get_object_or_404(Pet, pk=id)
return render(request, 'adoptions/pet_detail.html'... |
from .delete_command import delete |
from flask import Flask, request, jsonify
from flask_restful import Resource
from middleware import checkAuth
class ResumeInfo(Resource):
path = '/resume'
data = {
"name":
"Erik Dietrich",
"contactDetails": [
{
"label": "email",
"info": "eri... |
"""Defines the GoGettr client module. Most of the useful functionality is
inside PublicClient."""
from gogettr.public import PublicClient # noqa: F401
|
import logging
# class ContextFilter(logging.Filter):
# def __init__(self, trim_amount):
# self.trim_amount = trim_amount
# def filter(self, record):
# import traceback
# record.stack = ''.join(
# str(row) for row in traceback.format_stack()[:-self.trim_amount]
# )
... |
#
# @lc app=leetcode id=218 lang=python3
#
# [218] The Skyline Problem
#
# https://leetcode.com/problems/the-skyline-problem/description/
#
# algorithms
# Hard (38.53%)
# Likes: 3715
# Dislikes: 193
# Total Accepted: 202.6K
# Total Submissions: 525.5K
# Testcase Example: '[[2,9,10],[3,7,15],[5,12,12],[15,20,10],... |
import os
from hesiod import __version__
conf_file = "docs/source/conf.py"
with open(conf_file) as f:
lines = f.readlines()
release_prefix = "release = "
with open("docs/source/conf.py", "wt") as f:
for line in lines:
if not release_prefix in line:
f.write(line)
f.write(f'{release_pre... |
"""
{This script tests given values of the Zu and Mandelbaum hybrid quenching model
parameters to see how the resulting SMF for blue and red model galaxies
as well as spread in velocity difference of galaxies around red and blue
centrals compares to that of data}
"""
# Libs
from cosmo_utils.utils import work_path... |
from pandac.PandaModules import Point3, VBase3
objectStruct = {'Objects': {'1128540775.81jubutler': {'Type': 'Region','Name': 'pvpCTLw00','Objects': {'1128540801.88jubutler': {'Type': 'Island','File': 'pvpTestIslev2','Hpr': VBase3(0.0, 0.0, 0.0),'Objects': {'1128541283.64jubutler': {'Type': 'LOD Sphere','Hpr': Point3(0... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : route.py
@Time : 2020/11/27 11:06:13
@Author : SHILIU
@Version : 2.0
'''
# here put the import lib
import json as js
from random import choice, random, uniform
import os
import csv
import datetime
import requests
# Todos
'''
1.国外的城市目前全用的是各国首都,可... |
from helpers import (
TemporaryShowyourworkRepository,
ShowyourworkRepositoryActions,
)
from showyourwork import overleaf, exceptions
from showyourwork.config import edit_yaml
from showyourwork.logging import get_logger
from showyourwork.subproc import get_stdout
import time
class TestOverleaf(
TemporaryS... |
# Copyright 2015-2016 Canonical Ltd.
#
# This file is part of the Leadership Layer for Juju.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the h... |
import unittest
from .format_hints import vertica_format_hints
from records_mover.records.pandas import pandas_to_csv_options
from records_mover.records.processing_instructions import ProcessingInstructions
from records_mover.records.records_format import DelimitedRecordsFormat
class TestPandasToCsvOptionsVertica(uni... |
from scipy import stats
import redis
import json
import time
client = redis.StrictRedis(host='localhost', port=6379, password='4e81415c6c5c961f6ac62a9a4cf8df3e8c54375ed1cf6e09595c06e7e076fe5b3084301b82eb8319ce17068b1fac1db41c95804886d9980d084ac9e36dcfa438')
while(True):
dataString = client.get('BUFFER')
data =... |
#!/usr/bin/env python3
from datetime import datetime
import glob
import json
import os
import sys
import subprocess
DATA_DIR = "./data-cache"
FILE_PATTERN = "*.timeline"
PREPROC_FILE = "preproc.json"
files = glob.glob(os.path.join(DATA_DIR, FILE_PATTERN))
print(len(files))
recs = []
cnt = len(files)
cur = 0
for ... |
class Solution:
@staticmethod
def naive(arr):
return sorted(arr,key=lambda x:(bin(x).count("1"),x))
|
"""Company - MODELS
"""
from sqlalchemy import Column, String, PickleType, Text
from app.models.base import Base
class WebRequest(Base):
__tablename__ = 'web_requests'
uri = Column(Text(), nullable=False)
data = Column(PickleType())
ip = Column(String(50))
def __init__(self, _id=None):
... |
import itertools
import argparse
import glob
import cv2
import pickle
from sklearn.neighbors.kd_tree import KDTree
import numpy as np
import os
from bagofvisualwords import BagOfVisualWords
from VLADlib.VLAD import *
from VLADlib.Descriptors import *
import faiss
def get_query(groundtruth_dir):
image_dir = 'datase... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Jiao Lin
# California Institute of Technology
# (C) 2007 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
#!/usr/bin/python
import re,sys,redis,json,getopt,random,urllib2
import time,uuid
MPH=1.60934
WAKEINTERVAL=3
alreadyPicked=[]
liveScheds=[]
maps=[]
segMaps=[]
projectDir=""
segmentsDir="segments/"
foundSch=False
conf={}
#scheduleFile=""
redisDB=0
try:
opts, args = getopt.getopt(sys.argv[1:], "h:m", ["help", "insta... |
from r2p2_model import R2P2
from absl import app, flags
from glob import glob
import json
import numpy as np
import os
import torch
import tqdm
flags.DEFINE_string('r2p2_train_data', '', 'Path to r2p2 training data.')
flags.DEFINE_string('r2p2_val_data', '', 'Path to r2p2 validation data.')
device = 'cuda'
FLAGS = f... |
# -*- coding: iso-8859-1 -*-
# -*- mode: python -*-
|
import argparse
import mysql.connector
from collections import Counter
import csv
import json
if __name__ == '__main__':
parser = argparse.ArgumentParser('Run some cleanup routines to remove dead annotations')
parser.add_argument('--db',required=True,type=str,help='JSON with database settings')
args = parser.pars... |
from django.core.exceptions import ValidationError
from functools import partial
from cyder.base.tests import ModelTestMixin
from cyder.cydhcp.constants import STATIC
from cyder.cydhcp.interface.static_intr.models import StaticInterface
from cyder.cydhcp.network.models import Network
from cyder.core.system.models impo... |
from scipy import ndimage
from PIL import Image
import numpy as np
import pylab as pl
def image_in_image(image_material, image_canvas):
"""
四隅をできるだけ同次座標tpに近づけるアフィン変換を使って
image1をimage2に埋め込む.
"""
#: アフィン変換を適用
image_alpha = (ndimage.affine_transform(
image_material, [[1, 1], [1, 1... |
'''
Created on May 21, 2012
@author: kristof
'''
import os
import math
from reportlab.pdfgen import canvas
from reportlab.lib import colors
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib... |
import nextcord, datetime, time
from nextcord.ext import commands
start_time = time.time()
class Uptime(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def uptime(self, ctx):
current_time = time.time()
difference = int(round(current_t... |
def primeNumber(number):
if number == 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
def run():
prime = 0
primes = []
j = 1
while prime < 10001:
for i in range(j, j+1):
if primeNumber(j):
... |
import unittest
from knaspack import (
knaspack,
)
class TestKnaspack(unittest.TestCase):
def test_knaspack(self):
weights = [2, 3, 4]
values = [2, 4, 7]
size = 5
actual_result = knaspack(weights, values, size)
expected_result = [0, 0, 1]
self.assertEqual(actua... |
from test_url import *
|
from __future__ import print_function, division
import numpy as np, astropy.io.fits as pyfits
import matplotlib.pyplot as plt
import os,sys
import psf_marginalise as pm
import scipy.ndimage as nd
def choose_psfs(tgt_cubes,cal_cubes,save_dir):
"""Choose the target and PSF images to use and save images in same file.
... |
import yaml
with open('../sensors.yaml', 'r') as f:
mydict = yaml.load(f.read())
f.close()
# print(mydict['sensor'][0]['state_topic'])
print len(mydict)
# print len(mydict['sensor'])
|
'''OpenGL extension EXT.draw_instanced
This module customises the behaviour of the
OpenGL.raw.GLES2.EXT.draw_instanced to provide a more
Python-friendly API
Overview (from the spec)
This extension provides the means to render multiple instances of
an object with a single draw call, and an "instance ID" variable... |
#coding: utf-8
"""
Образцы разборов для дорожки "Морфология" сделаны С.Ковалем
в соответствии с согласованным на конференции Диалог-2010 инвентарем
признаков.
В образцах на следующих листах используются три вида условных обозначений:
* знак '|' - соединяет два варианта описания данного разбора
(в частности, привед... |
import PIL
import sys
img = PIL.Image.open('img.jpg')
exif_data = img._getexif()
def saveOutputAsJson(output, fileName):
json_data = json.dumps(output, sort_keys=True, indent=4, separators=(',', ': '))
with open(fileName, "w") as text_file:
text_file.write(json_data)
if __name__ == '__main__':
databaseName =... |
import requests
import time
import tqdm
import json
import sqlite3
import numpy
import math
import hashlib
sql_InsertDetailInfo = '''insert into %s(houseId,houseCode,title,appid,source,imgSrc,layoutImgSrc,imgSrcUri,layoutImgSrcUri,roomNum,square,buildingArea,buildYear,isNew,ctime,mtime,orientation,floorStat,totalFloor... |
"""Script for computing the results for the specified project"""
from pathlib import Path
import argparse
import project_gen as pg
def main(project_dir: Path, n_procs: int = 4):
# Run Hazard, Disagg, UHS and GMS
pg.gen_psha_project_data(project_dir, n_procs=n_procs)
pg.gen_gms_project_data(project_dir, n... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.db import migrations
from django.db import models
import lizard_auth_server.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
mig... |
import json
import sys, os
from modules.api.util import auth
sys.path.insert(0, "./modules/api")
from util import *
try:
last_info = sys.argv[1]
except IndexError:
print("Please provide last image info file path.")
exit(1)
with open(os.path.join("uploaded", last_info)) as f:
try:
data = json... |
from lightning_model import NuWave
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
from omegaconf import OmegaConf as OC
import os
import argparse
import datetime
from glob import glob
import torch
from tqdm import tqdm
from scipy.io.wavfile import write as swrite
def test(... |
import copy
import cv2
import torch
import numpy as np
from PIL import Image
from scipy import ndimage as ndimg
from cfglib.config import config as cfg
from util.misc import find_bottom, find_long_edges, split_edge_seqence, \
vector_sin, get_sample_point
def pil_load_img(path):
image = Image.open(path)
im... |
import shell
import os
from ownLogging import *
from dataclasses import dataclass
from typing import *
import yaml
import utils
def getFromDicts(dicts, k, conv=lambda x: x, default=None, fail=True):
if type(dicts) is not list:
dicts = [dicts]
val = None
for d in dicts:
if k in d:
... |
from .base import CastorClient
|
__all__ = ['readbot']
from readbot import * |
#!/usr/bin/env python
# encoding:utf-8
"""
Author : Yuanqing Mei
Date : 2021/8/4
Time: 20:06
File: precision_table_plot.py
HomePage : http://github.com/yuanqingmei
Email : dg1533019@smail.nju.edu.cn
compute the avg std max min values and draw the box plot of precision and recall.
"""
import time
def precision_table_... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
@s-gupta, @amurali and @dgandhi
Run the following to start camera and ar tracker:
roslaunch robot_calibration calibration.launch
"""
impor... |
"""Manages rendering templates"""
import os
from enum import Enum
from jinja2 import Environment, FileSystemLoader
_TEMPLATES_DIRECTORY = 'templates'
class CDALTemplate(Enum):
C_TYPES_HEADER = 1
C_TYPES_SOURCE = 2
ACCESSOR_HEADER = 3
ACCESSOR_SOURCE = 4
def environment_create():
"""Creates an ... |
from unittest import TestCase
import pandas as pd
from scripts.utils import train_binary, Bounds, Support
class TestTrain(TestCase):
"""Tests train from utils.py"""
def test_train(self):
"""Test with numeric and nominal features"""
training_set = pd.DataFrame({"A": ["low", "low", "high", "l... |
"""Unit test package for pypackage."""
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.signal import find_peaks
data = pd.read_excel (r'..\Flex Sensor\FlexSensorWalkingData.xlsx')
#data = pd.read_excel (r'f:\MSC Courses\Master Thesis BIBA\flex sensor feet data test1.xlsx')
df = pd.DataFrame(data, columns= ['Analog value']... |
"""
Comparing two trees by MP3
--------------------------
This example shows how to compare/measure two inferred genotype data (trees).
"""
import scphylo as scp
# sphinx_gallery_thumbnail_path = "_static/thumbnails/mp3.png"
# %%
# First, we load two binary test single-cell genotype data.
grnd = scp.io.read(
sc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020, Wenbin Fei, Email: wenbinfei@gmail.com
# All rights reserved.
"""
Have fun with PowpwerPoint files
=================================
todo: the strange thinng is when the powerpoint is open.
but when run the smae code on the shell, it works.
"""
im... |
"""Cast tensors in a functional fashion.
Users can use this module to cast `step` outputs to desired type or
to lower precision in order to save memory (though it shouldn't be needed.)
"""
import abc
import torch
from ._base import Operation
def _docstring(klass) -> str:
klass.__doc__ = """Cast `torch.Tensor... |
"""
@File : setup.py.py
@Contact : panrs@venpoo.com
@Modify Time
------------
2020/7/14 16:24
------------
@Model Name: 安装命令:python setup.py install
"""
from setuptools import find_packages, setup
PACKAGE = 'algorithm_mic_sdk'
with open("README.rst", "r", encoding='UTF-8') as fh:
long_description = fh.r... |
import os
import PIL
import xml.etree.ElementTree as ET
from torch.utils.data import Dataset
from .constants import *
class ImageNetValDataset(Dataset):
def __init__(self, root_dir, label_dir, synset_filepath, max_num=None, transform=None):
"""
Args:
root_dir (string): Directory with ... |
# Predicting Cognitive Impairment by Kiran K.
# www.github.com/kkphd/mmse
import Step_1_MMSE_Data_Cleaning
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns
import pprint
analysis_results = Step_1_MMSE_Data_Cleaning.run_analysis()
# Perform explora... |
#!/usr/bin/env python
"""Test the file transfer mechanism."""
import os
from grr.client.client_actions import standard
from grr.lib import action_mocks
from grr.lib import aff4
from grr.lib import flags
from grr.lib import test_lib
from grr.lib import utils
from grr.lib.flows.general import transfer
from grr.lib.rd... |
import unittest
import os
import pickle
from mof_tda import MOF_TDA_PATH
from mof_tda.narrow_mof_dataset import get_lowest_volumes
class VolumeTest(unittest.TestCase):
def test_volume(self):
# TODO: duplicate code, refactor/delete
filepath = []
with open(os.path.join(MOF_TDA_PATH, 'allMOF... |
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Processor for Parquet files."""
import logging
import prestodb
import pyarrow.parquet as pq
from dateutil.relativedelta import relativedelta
from django.conf import settings
from prestodb.exceptions import PrestoExternalError
from prestodb.exce... |
import discord as nextcord
from discord.ext import commands
admins = [878726683195240468,685180177419993102,899722893603274793]
class Root(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def view_guilds(self,ctx):
if ctx.author.id in admins:
... |
__all__ = ["jsonReader", "pseudoSlam", "util"] |
"""TapMap: A generator for keyboard heatmap images."""
from codecs import open
from os import path
from setuptools import find_packages, setup
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as file:
long_description = file.read()
setup(
name='tapmap',... |
# coding: utf-8
"""
SCORM Cloud Rest API
REST API used for SCORM Cloud integrations. # noqa: E501
OpenAPI spec version: 2.0
Contact: systems@rusticisoftware.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
... |
import os
import pickle
import numpy as np
import pprint
from .base import Routine
class OutputRoutine(Routine):
"""A base routine that has output functionality"""
def __init__(self, output_dir):
Routine.__init__(self)
self._output_dir = output_dir
def initialize(self):
if not os... |
from __future__ import print_function
from pgmagick import gminfo as info
libinfo = info()
print(libinfo.version)
print(libinfo.library)
|
import sys
from argparse import ArgumentParser
from pathlib import Path
from typing import Iterator, List, NamedTuple, NoReturn, TextIO
import flake8_codes
from ._config import Config
from ._ini import INI
def normalize(name: str) -> str:
return name.replace('-', '_').lower()
RED = '\033[91m'
GREEN = '\033[92... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.