text stringlengths 3.07k 12.6k |
|---|
import argparse
class TreatAsError(object): pass
class Config(object):
def __init__(self, data=None, datatype=None, keyaliases=None, prefix=None):
self.__dict__['data'] = data or dict()
self.__dict__['datatype'] = datatype or dict()
self.__dict__['keyaliases'] = keyaliases or dict()
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 14 17:25:02 2021
@author: richa
"""
from __future__ import annotations
import json
import random
from dataclasses import dataclass
from typing import Callable, Iterable, List, Optional
@dataclass
class Model:
"""Neural network model comprised of layers."""
in... |
import pandas as pd
import numpy as np
from datetime import date
# Calcul le prix d'un joueur
def getPrice(age, intra_extra):
if intra_extra == 'INTRA':
if age <= 0:
return 0
elif age > 0 and age <= 6:
return 110
elif age > 6 and age <= 8:
... |
# -*- coding: utf-8 -*-
import httplib, urllib
import requests
import json
from flask import Flask, render_template, request, jsonify
# **********************************************
# *** Update or verify the following values. ***
# **********************************************
# Replace the accessKey string valu... |
# -*- coding: utf-8 -*-
import csv
import requests
import datetime
# key = 책 제목, value = 재고 수
book_stock_quantity_dict = {}
book_category_dict = {
"개발": "DEVELOP",
"경영": "MANAGEMENT",
"기획": "PLAN",
"마케팅": "MARKETING",
"자기계발": "SELF_IMPROVEMENT",
"자격증": "LICENSE",
"디자인": "DESIGN",
"소설":... |
from keras.models import Model
from keras.layers import Input, Dropout, Masking, Dense, Embedding
from keras.layers import Embedding
from keras.layers.core import Flatten, Reshape
from keras.layers import LSTM
from keras.layers.recurrent import SimpleRNN
from keras.layers import merge
from keras.layers.merge imp... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
import os, time, re, datetime, tempfile, subprocess, signal
import logging
import math, numpy
from influxdb import InfluxDBClient
PERF = None
DBCLIENT = InfluxDBClient("localhost", 8086, "root", "root", "cadvisor")
def handle_sigint(sig, frame):
global PERF
if (PERF !... |
# coding: utf-8
from datetime import datetime, timezone
import time
import hmac
import base64
import random
import json
import operator
import logging
import tornado
from tornado.gen import coroutine
from tornado.httpclient import AsyncHTTPClient
from tornado_opensearch import error
from tornado_opensearch import uti... |
'''Server for visualization.'''
#%%
from __future__ import (absolute_import, print_function, unicode_literals, division)
import json
import itertools
import numpy as np
from bokeh.layouts import column, gridplot
from bokeh.models import Button
from bokeh.palettes import Set1
from bokeh.plotting import figure, curdoc,... |
import six
from chainer.functions.array import reshape
from chainer.functions.array import split_axis
from chainer import link
from chainer.links.connection import convolution_2d as C
from chainer.links.connection import linear as L
from chainer.links.connection import lstm
from chainer.links.connection import gru
fro... |
import pynlpir
import re
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.svm import SVC, LinearSVC, libsvm, liblinear
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression
from random import shuffle
from nltk.probability import FreqDist, Cond... |
import datetime
import numpy as np
import pandas as pd
def get_ts_range(init_dt, end_dt, ts_range=900):
time_ranges = []
i = 0
while (init_dt+i*datetime.timedelta(seconds=ts_range)) <= end_dt:
time_ranges.append(init_dt+i*datetime.timedelta(seconds=ts_range))
i += 1
return time_ranges
... |
""" Sphinx role for static notebook """
from __future__ import print_function
import os
from os.path import (join as pjoin, relpath, splitext,
abspath, dirname, exists)
from datetime import datetime
from docutils import nodes, utils
from docutils.parsers.rst import directives
from docutils.parse... |
import scipy.stats.distributions as dist
import numpy as np
from astropy.coordinates import Distance
from sklearn.neighbors import NearestNeighbors
def bayes_ci(k, n, sigma=None):
'''
Calculate confidence interval using the binomial
distribution/bayesian methods described in Cameron et al. 2011
'''
... |
from datetime import (datetime,timedelta)
import webbrowser
#
from flask import (Flask, render_template, request, redirect, url_for, jsonify)
from data import (data_city_table, data_count, bar_base, map_base, mon_l)
#2 建立和配置Flask
flaskserver = Flask(__name__)
flaskserver.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedel... |
import matplotlib
# this needs to be called before importing wandb Graph
matplotlib.use("Agg")
from wandb import wandb_run
from wandb.summary import FileSummary
import pandas
import tensorflow as tf
import torch
import json
import glob
import os
import numpy as np
import tempfile
import plotly.graph_objs as go
import... |
from enum import Enum
from typing import Optional, List
CONFIG_VERSION = 1
class Droupouts(object):
def __init__(self, multiplier: float,
oute: float,
outi: float,
outh: float,
w: float,
out: float):
self.multiplier = mu... |
import pygame
import random
import time
#// initialise pygame and mixer
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.mixer.init()
pygame.init()
#// load sounds
kick_sound = pygame.mixer.Sound('sound/kick.wav')
snare_sound = pygame.mixer.Sound('sound/snare.wav')
openh_sound = pygame.mixer.Sound('sound... |
from .forms import NewProjectForm,ProfileForm,Votes
from django.contrib.auth.decorators import login_required
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse
from .models import Project,Profile,Ratings
from django.contrib.auth.models import User
# from django.http im... |
"""Module with abstract interface for sparsifiers."""
from abc import ABC, abstractmethod
import copy
import numpy as np
import torch
import torch.nn as nn
from torch.distributions.multinomial import Multinomial
class BaseSparsifier(ABC, nn.Module):
"""The basic interface for a sparsifier.
A sparsifier spar... |
import datetime
import logging
import typing
import pandas as pd
from atpy.data.ts_util import overlap_by_symbol
from pyevents.events import EventFilter
class DataReplay(object):
"""Replay data from multiple sources, sorted by time. Each source provides a dataframe."""
def __init__(self):
self._sou... |
import os
import pickle
import logging
import io
from typing import Callable
import chess.engine
import chess.pgn
import lichess_data_manager
import lichess_to_python_chess
import add_chess_analysis
DATA_FOLDER = 'data'
logger = logging.getLogger(__name__)
def get_games_from_lichess(userid, download):
return l... |
import random as rd
import logging as lg
participants=[]
def add_participants(x):
return participants.append(x)
def question_participant():
print("Another one more participant?")
return input()
def add_more_participants():
"""Function that asks if he want to add one more participant"""
try:
... |
import sys
import re
import pysam
import shutil
import os
import gzip
from multiprocessing import Pool
from optparse import OptionParser
from collections import Counter, defaultdict
from contextlib import contextmanager
opts = OptionParser()
usage = "usage: %prog [options] [inputs] Script to process aligned .bam fil... |
#!/usr/bin/env python3.7
# billboardgui.py
"""Utility module Lyric Scraper program."""
# stand lib
import json
from pathlib import Path
import re
import subprocess as sp
from time import sleep
from typing import Any, List, Set, Text, Tuple
# 3rd party
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
import ... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import plotly.express as px
import pandas as pd
import folium
# In[ ]:
def ParetoCurve(df_combined_output, current_hospitals):
fig = px.line(df_combined_output.sort_values(by=['km','number_of_hospitals']),
x='number_of_hospitals',y='%',color='km',
... |
#!/usr/bin/python3
from collections import namedtuple
import time
import usb.core
import usb.util
import os
from pathlib import Path
from sys import platform
if platform == 'win32':
import wmi
TARGET_CPU_TEMP = 70
MAX_TEMPERATURE_DELTA = 2
UPDATE_INTERVAL = 1
MIN_CPU_DUTY = 10
MAX_CPU_DUTY = 100
SYS_DUTY_DFL = 1... |
import random
from cv2 import magnitude
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from operation import apply_augment
from networks import get_model
from utils import PolicyHistory
from config import OPS_NAMES
default_config = {'sampling'... |
# Copyright (c) <NAME>, Indian Institute of Technlogy Kharagpur
# Copyright (c) Facebook, Inc. and its affiliates
import gym
from abc import ABC
import numpy as np
from rrl.encoder import Encoder, IdentityEncoder
from PIL import Image
import numpy as np
import torch
_mj_envs = {'pen-v0', 'hammer-v0', 'door-v0', 'relo... |
#!/usr/bin/pyth
#
# Authentic 2022 <NAME>, <EMAIL>
# <NAME>, <EMAIL>
import os
import sys
from Dash import PackageContext
from shutil import move
from datetime import datetime
from Dash.Utils import utils
class Test:
def __init__(self):
pass
class Jobs:
def __init_... |
#!/usr/bin/python
#
# ============================================================================
# Copyright (c) 2011 Marvell International, Ltd. All Rights Reserved
#
# Marvell Confidential
# ============================================================================
#
# Handy utility fu... |
"""
Report results of all test run that followed our project structure.
Plot Box plots for development set best performance on single metric.
From best on development set select the best and report results on test set.
"""
import os
import sys
import pprint
import pandas as pd
import numpy as np
from scipy import stat... |
# built in libraries
import os
import random
import hashlib
import math
# 3rd party libraries
try:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primit... |
from django.shortcuts import render
from django.views.generic import View
from library.models import Item, Stack, ItemComment
from library.forms import ItemCommentForm
from nonhumanuser import settings
import os
import mimetypes
from django.http import HttpResponse, HttpResponseRedirect
from wsgiref.util import FileWra... |
import datetime
from time import time
import numpy as np
import math
import os
def euler_to_rot_mat(yaw, pitch, roll):
Rz_yaw = np.array([
[np.cos(yaw), -np.sin(yaw), 0],
[np.sin(yaw), np.cos(yaw), 0],
[ 0, 0, 1]])
Ry_pitch = np.array([
[ np.cos(pitch), 0, n... |
# This file is part of the clacks framework.
#
# http://clacks-project.org
#
# Copyright:
# (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de
#
# License:
# GPL-2: http://www.gnu.org/licenses/gpl-2.0.html
#
# See the LICENSE file in the project's top-level directory for details.
"""
The configuration modul... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.distributions as dist
import numpy as np
from data.agent import BaseAgent
import pdb
class NetworkActorCritic(nn.Module):
def __init__(self, input_dims, output_dims, action_space,
lr, memory, ne... |
#
# Run multi-query script in BigQuery
#
import os
import sys
import getopt
import json
import datetime
# ----------------------------------------------------
# default config values
# To override default config values, copy the keys to be overriden to a json file,
# and indicate this file as --config parameter
# ---... |
from typing import List
import torch
from torch import nn
from torch.nn import functional as F
from mrbuilder.utils import get_params, remove_keys, is_single
import mrbuilder.builders.pytorch.utils as pu
class PyTorchBuilderLayer:
def __init__(self, config=None, connection=None):
self.connection = conne... |
"""#### Setup ###"""
import numpy
import matplotlib.pyplot as plt
import tensorflow as tf
import pandas as pd
from datetime import datetime
from sklearn.preprocessing import StandardScaler
import h5py
import numpy
import os
from sklearn.metrics import f1_score
from sklearn.metrics import precision_recall_fscore_suppo... |
#------------------------------
"""
:py:class:`NotificationLog` is intended to submit notification records in the log file
======================================================================================
Usage::
# Import
from psana.pyalgos.generic.NotificationLog import NotificationLog
nl = Notifi... |
import os
import pickle
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.utils
from torch.autograd import Variable
from model import gru
from data_loader import load_data
from opt import opt
# TODO - Make a file that will load the novel randomly or in order.
def trai... |
#!/usr/bin/env python3
# -*-coding:UTF8-*-#
import pandas as pd
from lxml import html
import pandas as pd
import time
import base64
import random
import requests
from fake_useragent import UserAgent
def createProxy():
'''proxy = {}
data = pd.read_csv('hidemy_proxy_https.csv')
ip_list = list(data.IP)
#p... |
import ipaddress
from django.core.exceptions import ValidationError
from django.db import models
from scionlab.defines import DEFAULT_LINK_BANDWIDTH, DEFAULT_LINK_MTU
from scionlab.models.core import Host, ISD, Link
from scionlab.models.user_as import UserAS
_MAX_IXP_LABEL_LEN = 255
_MAX_LEN_IP_SUBNET = 48
class I... |
"""
lambda-ses-forwarder.py by <NAME>, Version 1.1.
Python3 rewrite based on [aws_lambda_ses_forwarder_python3](https://github.com/tedder/aws_lambda_ses_forwarder_python3),
which was a port of the original node.js forwarder [aws-lambda-ses-forwarder](https://github.com/arithmetric/aws-lambda-ses-forwarder),
but re-wri... |
#!/usr/bin/env python
"""
Validate SVGs using the W3C nu validator.
The following arguments are supported:
-always Don't prompt to save changes.
¶ms;
"""
from functools import lru_cache
from typing import Any, FrozenSet, List
import mwparserfromhell
import pywikibot
import requests
from mwparserfromhe... |
# Copyright 2021 The Trieste Contributors
#
# 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... |
# coding:utf-8
import codecs
import os
import re
from os.path import getsize, splitext
import json
import shutil
luaDir = "tolua++"
snippetsDir = "snippets"
templatePath = "template.sublime-snippet"
completionTemplatePath = "template_completions.sublime-completions"
completionItemTemplatePath = "template_completions_i... |
import os
import numpy as np
from mathutils import Euler, Matrix, Vector
try:
import ruamel_yaml as yaml
except ModuleNotFoundError:
import ruamel.yaml as yaml
from lib.utils.inout_BOPformat import save_info
from lib.datasets.tless import inout
from lib.poses import utils
def create_gt_obj(index, list_id_obj,... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import atexit
import gzip
import os
import shutil
import sqlite3
import ubelt
# Set the default output dir to the XDG or System cache dir
# i.e. ~/.cache/fels $XDG_DATA_HOME/fels %APPDATA%/fels or ~/Library/Caches/fels
FELS_DEFAU... |
import pandas as pd
from pprint import pprint
ARQUIVO_DADOS = 'dados_oceans_status.csv'
ARQUIVO_DADOS = 'https://raw.githubusercontent.com/lucasHashi/coleta-dados-fundamentalistas/master/dados_oceans_status.csv'
def somar_posicoes(df_rank, list_indicadores):
linhas_posi = []
for tick, linha in df_rank.iterrow... |
from serial.threaded import Packetizer
import serial
import threading
import sys
class UArmLineReader(Packetizer):
"""
Read and write (Unicode) lines from/to serial port.
The encoding is applied.
"""
TERMINATOR = b'\r\n'
ENCODING = 'utf-8'
UNICODE_HANDLING = 'replace'
def __init__(sel... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import shlex
import sys
from invoke import run, task
from python_boilerplate.tasks.doc import *
from python_boilerplate.config import get_context
from python_boilerplate.tasks import util
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
'''
https://www.cnblogs.com/YongQiVisionIMAX/p/12630769.html
https://github.com/Andrew-Qibin/SPNet/blob/master/models/spnet.py
'''
class StripPooling(nn.Module):
def __init__(self, in_channels, pool_size, norm_layer, up_kwargs):
super(St... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import random
from nas_lib.utils.utils_data import gen_batch_idx
from nas_lib.utils.comm import get_spearmanr_coorlection, get_kendalltau_coorlection
import time
class MetaNeuralnetTorch(nn.Module):
def __init__(self, in_channel... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
MOT dataset with tracking training augmentations.
"""
import bisect
import copy
import csv
import os
import random
from pathlib import Path
import torch
from . import transforms as T
from .coco import CocoDetection, make_coco_transforms
from .... |
import tensorflow as tf
import os
import numpy as np
from tqdm import tqdm
import re
from easydict import EasyDict as edict
import sys
import cv2
import argparse
import sklearn.preprocessing
from IPython import embed
pca = False
output_name = 'fc1' if not pca else 'feature'
import torch
@torch.no_grad()
def main(ar... |
import argparse
import math
import os
import os.path as osp
from PIL import Image
class Element:
"""A data element of a row in a table."""
def __init__(self, htmlCode=''):
self.htmlCode = htmlCode
self.isHeader = False
self.drawBorderColor = ''
def imgToHTML(self, img_path, widt... |
import ubelt as ub
import pytest
def test_auto_dict():
auto = ub.AutoDict()
assert 0 not in auto
auto[0][10][100] = None
assert 0 in auto
assert isinstance(auto[0], ub.AutoDict)
def test_auto_dict_to_dict():
from ubelt.util_dict import AutoDict
auto = AutoDict()
auto[1] = 1
auto[... |
import torch
import torch.nn as nn
from beta_rec.models.torch_engine import ModelEngine
class LightGCN(torch.nn.Module):
"""Model initialisation, embedding generation and prediction of NGCF."""
def __init__(self, config, norm_adj):
"""Initialize LightGCN Class."""
super(LightGCN, self).__ini... |
from sample.scripts.transfer.utils import run_time
import torch
import pandas as pd
from anomalytransfer.transfer.data import KPI
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import logging
import anomalytransfer as at
import numpy as np
from glob import glob
from typing import Sequence, Tuple, Dict, Optional, ca... |
from amitools.vamos.machine import MockMemory
from amitools.vamos.mem import MemoryAlloc
from amitools.vamos.astructs import AmigaStruct, AmigaStructDef
from amitools.vamos.atypes import AmigaType, AmigaTypeDef, CString
@AmigaStructDef
class MyStruct(AmigaStruct):
_format = [
("WORD", "ms_Word"),
... |
import re
import sys
import shutil
import argparse
import subprocess
from pathlib import Path
from typing import List, Generator, Optional
import pytsk3
class NtfsFile(object):
def __init__(self, filetype: str, address: str, filename: str):
self.is_file = self.__is_file(filetype)
self.address = ad... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 20 16:50:55 2016
@author: Jeiel
"""
import decisiontree as dt
from random import sample
from random import uniform
from math import ceil
from statistics import mean
def holdout(data, pencentage = 2/3, featurenames = None, method = 'gini', adaboost... |
import copy
import os
from pprint import pprint
import warnings
import yaml
def load_config(path: str) -> dict:
"""
Load a config from a yaml file.
Args:
path: The path to the config file.
Returns:
The loaded config dictionary.
"""
with open(path, 'r') as f:
retur... |
import pygame, sys
from pygame.locals import *
import pygame.freetype
import time
class enigmaKeyboard:
def __init__(self, keys="ABCDEF"):
self.keys = keys
self.row1 = keys[:3]
self.row2 = keys[3:]
def add_key(self, letter, color, position_x=50, position_y=500):
self.letter = l... |
import logging
from pathlib import PurePath
from typing import List, Union
import pandas as pd
import numpy as np
from PIL import Image
from torch import from_numpy, Tensor
from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler, dataloader
import torchvision.transforms as T
# CheXpert pathologies on or... |
# @Author: <NAME>
# @Date: Tue, March 31st 2020, 12:36 am
# @Email: <EMAIL>
# @Filename: keras_models.py
'''
Model definitions for tensorflow.keras model architectures
'''
import pdb;pdb.set_trace();print(__file__)
import numpy as np
import os
import tensorflow as tf
# from pyleaves.utils import set_visible_gpus
... |
"""
Create simulated LDA documents
"""
# M: number of documents
# K: number of topics
# V: number of words in vocab
# N: number of words in all documents
# theta: topic distribution over documents (M by K)
# phi: word distribution over topics (V by K) (lambda)
import pickle
import typing
import os
import numpy as n... |
#import pygame
import numpy as np
from Obstacle import Obstacle
from Obstacle import Game
import matplotlib.pyplot as plot
from pygame.locals import *
import cv2
# define variables
bot_clearance = 5
# create pygame environment
screen_size = width, height = 400, 250
image = np.zeros((height, width, 3), np.uint8)
image... |
import json
import typing
from deprecation import deprecated
import cloudevents.exceptions as cloud_exceptions
from cloudevents.http.event import CloudEvent
from cloudevents.http.event_type import is_binary
from cloudevents.http.mappings import _marshaller_by_format, _obj_by_version
from cloudevents.http.util import ... |
import json
import os
import requests
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
from telegram import Update, Bot ,Message
from telegram import KeyboardButton,ReplyKeyboardMarkup
from PIL import Image
from functions import encrypt, decrypt
# import telebo... |
from model_definition import create_discriminator, create_generator
from keras.models import Model, load_model
from keras.layers import Input
from keras.optimizers import Adam
import pickle
import numpy as np
import os
from generation import generate_save_image_gallery
from csv_logging import log_to_csv, read_latest_lo... |
#!/usr/bin/python
""" topic_modeling
Trains a Topic Model (LDA w/ 20 components) on Tf-idf vectorized text data and
assigns the most probable topic to the Social Media Posts.
Author: datadonk23
Date: 13.11.19
"""
import os, logging, warnings
logging.basicConfig(level=logging.INFO)
warnings.filterwarnings("ignore", c... |
#Keras
from __future__ import print_function
from keras.layers.core import Activation
from keras.layers.core import Dense
from keras.layers.core import Dropout
from keras.models import Sequential
from keras.optimizers import Adam
#TensorFlow
import tensorflow as tf
#LSTM
from keras.layers.recurrent import LSTM
from k... |
"""
Find correlations between protected columns and non-protected columns.
"""
import pathlib
from typing import Callable, Dict, List, Optional, Tuple, Union
import pandas as pd
from ..metrics import correlation as cm
from ..sensitive import detection as dt
def find_sensitive_correlations(
df: pd.DataFrame,
... |
# ==============================================================================
# Copyright (C) 2018-2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
# ==============================================================================
import sys
import numpy
import cv2
from argparse import ArgumentParser
import g... |
# Copyright (c) 2018 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
from collections import defaultdict, namedtuple
import os
import ConfigParser
from chroma_agent.lib.shell import AgentShell
from chroma_agent.log import daemon_log
from... |
# -*- coding: utf-8 -*-
"""Experiments controller."""
import sys
from datetime import datetime
from os.path import join
from sqlalchemy.exc import InvalidRequestError, ProgrammingError
from werkzeug.exceptions import BadRequest, NotFound
from ..database import db_session
from ..models import Dependency, Experiment, T... |
from __future__ import division
import math
import re
import numpy as np
from scipy.integrate import ode
import warnings
warnings.filterwarnings("ignore")
def fcomp(x, t, alpha, mu, K, delta=0.0):
T, C = x
Ceff = C/(T+C+K)
return [alpha*T*Ceff-delta*T, -mu*C]
def fcompfull(x, t, alpha, mu, K, delta=0.... |
"""Functions and routines to read the stardust database and return what we want."""
from pathlib import Path
from typing import Tuple
import numpy as np
import pandas as pd
MODULE_PATH = Path(__file__).parent
class StarDust:
def __init__(self, fname: str = "PGD_SiC_2021-01-10.csv"):
"""Initialize the ... |
import base64
import hashlib
import hmac
from datetime import timedelta
from flask_unchained import Service, current_app, injectable
from itsdangerous import BadSignature, SignatureExpired
class SecurityUtilsService(Service):
"""
The security utils service. Mainly contains lower-level encryption/token handli... |
import json
import datetime
import tornado.web
from biothings.utils.ga import GAMixIn
from collections import OrderedDict
SUPPORT_MSGPACK = True
if SUPPORT_MSGPACK:
import msgpack
def msgpack_encode_datetime(obj):
if isinstance(obj, datetime.datetime):
return {'__datetime__': True, 'as_str... |
"""
Pikkujouluvekotin
~~~~~~~~~~~~~~~~~
A user interface to control Pikkujoulu widget lights,
written with Flask.
:copyright: (c) 2018 by <NAME>.
:license: MIT, see LICENSE for more details.
"""
import json
import os
import random
from flask import (Flask, Response, request, redirect, url_for, render_template, send... |
from classes.scraper import *
from classes.game import Game
from classes.poke import Poke
from classes.cheat import Cheat
from settings import *
from string import ascii_letters
import re
SANITIZE_DESC_CHARS = ['POKE', '->', ',', ':', '.',
'x=', 'x =', 'X=', 'X = ',
'n = '... |
#!/usr/bin/env python3
# %%
import numpy as np
from librosa import stft, amplitude_to_db, load, fft_frequencies
# note: librosa defaults to 22.050 Hz sample rate; adjust if needed!
# %%
dtmf_tones = [
('1', 697, 1209),
('2', 697, 1336),
('3', 697, 1477),
('A', 697, 1633),
('4', 770, 1209),
... |
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompan... |
import os
import csv
import argparse
import sklearn
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import cv2
CSV_FILE_NAME = 'driving_log.csv'
def get_dataset_names(base_url='data'):
'''
gets list of datasets in base_u... |
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from acceptance_quality.models import PullRequestQuality
from acceptance_quality.serializers import PullRequestQualitySerializer
from datetime import datetime, timezone, timedelta
from pull_request_me... |
# -*- coding: utf-8 -*-
import os
import re
import argparse
import xml.etree.ElementTree as ElementTree
from googletrans import Translator
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n'... |
"""
Unicycle Cat Module
"""
import logging
from math import radians
from typing import Optional, Tuple, List, Any
import pygame
import pymunk
from stuntcat import resources
from . import model
from .sprite import ShapeSprite
LOGGER = logging.getLogger(__name__)
class CatModel(model.UprightModel):
"""
Ca... |
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
import torch.backends.cudnn as cudnn
from torch import optim
from optparse import OptionParser
from torch.autograd import Variable
from myloss import dice_coeff
from utils import *
from mod... |
import math
from collections import namedtuple
from .errors import KaffeError
TensorShape = namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])
def get_filter_output_shape(i_h, i_w, params, round_func, do_dilation=False):
if do_dilation:
assert params.stride_h == 1 and params.stride... |
"""
PeeringDB configuration module.
This defines config schemas and related I/O.
"""
import logging
import os
import munge
from munge.util import recursive_update
from confu import schema as _schema, generator
from peeringdb.util import prompt
DEFAULT_CONFIG_DIR = "~/.peeringdb"
class ClientSchema(_schema.Schema... |
import os
import lightgbm as lgb
import neptune
from neptunecontrib.monitoring.lightgbm import neptune_monitor
from neptunecontrib.versioning.data import log_data_version
from neptunecontrib.api.utils import get_filepaths
from neptunecontrib.monitoring.reporting import send_binary_classification_report
from neptunecon... |
# Copyright (c) 2015 SONATA-NFV, Paderborn University
# 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 req... |
# -*- coding: utf-8 -*-
from aiida.common import aiidalogger
import celery
from aiida.common.exceptions import (
LockPresent, ModificationNotAllowed, InternalError)
from aiida.djsite.settings.settings import djcelery_tasks
#from celery.utils.log import get_task_logger
## I use the aiidalogger so that the logging i... |
# -*- coding: utf-8 -*-
# @Author : William
# @Project : TextGAN-william
# @FileName : text_process.py
# @Time : Created at 2019-05-14
# @Blog : http://zhiweil.ml/
# @Description :
# Copyrights (C) 2018. All Rights Reserved.
import nltk
import os
import torch
import config as cfg
de... |
"""Provide utilities to measure performance."""
from __future__ import division
import contextlib
import cProfile
import functools
import logging
import pstats
import time
from maya import cmds
__all__ = ["fps", "profile", "timing"]
LOG = logging.getLogger(__name__)
def fps(loop=5, mode="parallel", gpu=True, cach... |
# You need to install pyaudio to run this example
# pip install pyaudio
# When using a microphone, the AudioSource `input` parameter would be
# initialised as a queue. The pyaudio stream would be continuosly adding
# recordings to the queue, and the websocket client would be sending the
# recordings to the speech to t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.