content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
[input]
project_dir
[output]
optimal hyperparameters, score each fold, avg, sd
<eval_func>.csv
"""
import argparse
import glob
import os
import pickle
import numpy as np
from sklearn.externals.joblib import Parallel, delayed
from Evaluation import ndcg
def eval_by_hy_parm(hy_parm_dir):
... |
import tkinter as tk
from config.config import CONFIG
import concurrent.futures
from controller import services
from services.IPInfoService import IPInfo
from beans.PacketBean import Packet
"""
This module for creating Graphical Interface and attaching handler for every events which occurs in ui
"""
def showappversio... |
# Copyright 2021 IBM Corporation
#
# 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 writi... |
import pandas as pd
import subprocess
import os
import csv
import json
from datetime import datetime
from os import walk
from dockerhub.downloader import Downloader
def select_tags(list_tags):
tags_ = []
for i in range(len(list_tags)):
if i==0 or i==(len(list_tags)-1) or i == round((len(list_tags)/2)... |
#!/usr/bin/env python
import argparse
import commands
from tableCmpSrc.genTopoOrder import *
from tableCmpSrc.tableNumCmp import *
def generateTest(directory, test_num):
"""Generating Topo Order Tests"""
for i in range(test_num):
ai = i+1
# Randomly generate topo order
l, topoOrder = genTopoOrder2()
# Writ... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
#!/usr/bin/env python
"""
A script that helps initiate a new python library.
Dependencies:
$ pip install requests
Usage: pylibcreator.py --path /path/to/foo_lib --token <github_personal_token>
Does the following tasks for you:
1) Initializes a new private git repository for foo_lib on github and clones that to /pa... |
import streamlit as st
import math
import plotly.graph_objects as go
def round_decimals_down(number: float, decimals: int = 2):
"""
Returns a value rounded down to a specific number of decimal places.
"""
if not isinstance(decimals, int):
raise TypeError("decimal places must be an integer")
... |
from aiogram.types import ReplyKeyboardRemove, \
ReplyKeyboardMarkup, KeyboardButton, \
InlineKeyboardMarkup, InlineKeyboardButton
from messages import MESSAGES, ROOMS, PETS_AND_FRIENDS
# Q&A Keyboard
Q_and_A_keyboard = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
q_and_exit_button = Keyb... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.http import HttpPostClientTransport
from tinyrpc import RPCClient
rpc_client = RPCClient(
JSONRPCProtocol(),
HttpPostClientTransport('http://127.0.0.1:5000/')
)
remote_server = rpc_clie... |
from flask import Flask
from celery_app import celery
from pymongo import MongoClient
#app
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(app.config)
# 添加蓝本
from celery_app.domainviews import domain_blueprint
from celery_app.ipviews import ipscan_blueprint
from celer... |
import filecmp
from itertools import combinations
from pathlib import Path
from typing import List
from src import settings
def handle_duplicates() -> List[Path]:
extensions = [".jpg"]
files = []
result = []
for file_ext in extensions:
for filepath in Path().glob("*" + file_ext... |
from pydantic import BaseSettings
from functools import lru_cache
class CdaSettings(BaseSettings):
cda_endpoint: str
cda_uid: str
cda_secret: str
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
@lru_cache()
def get_cda_settings():
return CdaSettings()
|
import os
class PlaylistLibrary(object):
def __init__(self, base_path):
self.__base_path = base_path
def add_album(self, album_info):
m3u_path = os.path.join(self.__base_path, '%s.m3u' % album_info.name)
m3u_file = open(m3u_path, 'wt')
m3u_file.write('# %s\n' % album_info.name... |
"""
Practical 9
Write a program to verify
ii) Eulers's Theorem
"""
import math
import time
import decimal
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
def phi(n):
count = 0
for i in range(0,n):
if(gcd(i,n)==1):
count = count + 1
return count
def eu... |
# Generated by Django 3.2.7 on 2021-11-10 19:48
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
import yamlfield.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(setti... |
from unittest import TestCase
from leetcodepy.surrounded_regions import *
solution1 = Solution1()
expected = [
['X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X'],
['X', 'O', 'X', 'X']
]
class TestSurroundedRegions(TestCase):
def test1(self):
board = [
['X', 'X'... |
import torch
import copy
import os
import operator
import re
import json
import numpy as np
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import default_collate
from torch.utils.data.sampler import BatchSampler, SequentialSampler, RandomSampler
from vilmedic.networks ... |
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import sys
import re
import os
from oscrypto import tls, errors as oscrypto_errors, version
from asn1crypto.util import OrderedDict
if sys.version_info < (3,):
from urlparse import urlparse
str_cls = unicode #... |
# ADD OLD DATES AND TIMES OF MESSAGES SO IT IS CHRONOLOGICAL, REPLACE REAL NAMES WITH FICTIONAL NAMES
def remove_white_lines(file):
stripped = open('chat_stripped.txt', 'w', encoding='utf-8')
with open(file, 'r', encoding='utf-8') as f:
for line in f:
if len(line) > 1:
... |
from django.contrib import admin
from .models import Service, Organisation
admin.site.register(Service)
admin.site.register(Organisation)
|
import numpy as np
from ..mixins import StrMixin
class Kernel(StrMixin):
def __init__(self, kernel: str = None, **kwargs):
self._name = kernel
self._kernel, self._kwargs = kernel, kwargs
def project(self, x1: np.ndarray, x2: np.ndarray) -> np.ndarray:
if self._kernel is None:
... |
from models.model import BaseModel
from keras.models import Model
from keras.layers import LSTM, Input, concatenate, LeakyReLU, Dense, Dropout, ReLU
from keras.activations import tanh
from keras.callbacks import EarlyStopping, ReduceLROnPlateau
from keras.losses import Huber
from metrics import Metrics
import numpy as... |
from typing import Optional
import torch
from fn import F
from torch import Tensor, zeros
from torch.nn import Parameter, LayerNorm, Linear, MultiheadAttention, GELU, Identity, ModuleList
from . import MLP, ResidualBlock
from ..neko_module import NekoModule
from ..layer import PositionalEmbedding, Concatenate
from ..... |
p1 = int(input('Primeiro termo: '))
p = p1
r = int(input('Razão: '))
while p1 < (p + r*10):
print(p1, '->', end=' ')
p1 += r
print('Fim') |
from .. import Globals
import PyFileIO as pf
def _ReadMET():
'''
Reads a data file containing the mission elapsed times (METs) at the
start of every date from 20080101 - 20150430.
Returns:
numpy.recarray
'''
fname = Globals.ModulePath + '__data/MessengerMET.dat'
dtype = [('Date','int32'),('ut','float32'),... |
from django import forms
from .models import *
class MovieForm(forms.ModelForm):
class Meta:
model = Movie
fields = ('title', 'creators', 'cast', 'description', 'genre', 'typ', 'seasons', 'release_date', 'image', 'video')
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
... |
import random
import math
import bisect
import numpy
class Instance:
def __init__(self, num_vars, num_clauses, k):
self.num_vars = num_vars
self.num_clauses = num_clauses
self.k = k
self.variables = range(1, num_vars+1)
self.clauses = {}
def generate(self):
rais... |
import flask_app
from credentials import API_KEY, API_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET
import tweepy
from selenium import webdriver
#from webdriver_manager.chrome import ChromeDriverManager
#from webdriver_manager.utils import ChromeType
def god() :
auth = tweepy.OAuthHandler(API_KEY, API_SECRET)
auth.set_... |
import numpy as np
import dynet as dy
from math import sqrt
from typing import List
import numbers
from xnmt import events, expression_seqs, param_collections, param_initializers
from xnmt.persistence import serializable_init, Serializable, bare, Ref
from xnmt.transducers import base as transducers
class MultiHeadAtt... |
""" Routines and Classes to get information about DHCP server
"""
import re
from ipaddress import IPv4Address, IPv6Address
from .config_reader import ConfigData
from .regex import MySystemRegex
def parse_dhcp_lease_file(dhcp_file=None):
"""
Open and parse DHCP Lease file
:param dhcp_file: Path of the DH... |
S ="パタトクカシーー"
print(S[::2]) |
#!/usr/bin/python3
import argparse
import getpass
import json
import select
import shlex
import socket
import sys
class Croaked(Exception): pass
class SocketClosed(Exception): pass
class Connection(object):
def __init__(self, host='localhost', port=0x6666, username=getpass.getuser(), playername=None):
sel... |
import numpy as onp
import jax.numpy as jnp
from jax import lax
from flax.optim import OptimizerDef
from flax import struct
#--------------------------------------------------------------------------------------------------
# UNCENTERED
@struct.dataclass
class _LaPropHyperParams:
learning_rate: onp.ndarray
be... |
class Solution:
def pivotIndex(self, nums) -> int:
total = sum(nums)
left = 0
right = total
for i, n in enumerate(nums):
if i > 0:
left = left + nums[i - 1]
right = right - nums[i]
if left == right:
return i
... |
'''
Newb Code Snippets:
https://stevepython.wordpress.com
77-Print Text On Webcam And Save Video
Tested on Window 7 and Linux Mint 19.1
On my Linux I had to make the font smaller (0.5)and change text position
(60,260) to be able see the text. Also the saved video would not play.
This could be all down to my setup th... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-14 22:27
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import pydoc.core.conf
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
... |
"""
https://github.com/FrederikSchorr/sign-language
Train a pre-trained I3D convolutional network to classify videos
"""
import os
import glob
import time
import sys
import numpy as np
import pandas as pd
import keras
from keras import backend as K
from datagenerator import VideoClasses, FramesGenerator
from model... |
from datetime import timedelta
from subparse import command
from .settings import asduration
default_report_interval = timedelta(seconds=5)
def generic_options(parser):
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('--profile', default='profile.yml')
@command('.tweet_stream... |
import sys
import re
from pathlib import Path
script_param_index = 0
if '--' in sys.argv: # debug mode
script_param_index = sys.argv.index('--') + 1
year_day_parser = re.compile(r'(\d+)(?:\\|/)(\d+)\.py$')
year, day = year_day_parser.search(sys.argv[script_param_index]).groups()
if (len(sys.argv) >= (script_param... |
from chibi.file.snippets import is_file
from tests.snippet.files import Test_with_files
class Test_is_file( Test_with_files ):
amount_of_files = 3
amount_of_dirs = 3
def test_root_should_be_a_false( self ):
self.assertFalse( is_file( self.root_dir ) )
def test_all_dirs_list_should_be_false( ... |
"""Collection of helper functions to handle the logic for the KME.
"""
import base64
import os
import numpy as np
from typing import List
from hashlib import shake_128
import uuid
def concat_keys(key_array: List[List[int]]) -> List[int]:
""" Helper function to concatenate keys.
The function will concatenate ... |
import requests
from twilio.rest import Client
import config
account_sid = config.twilio_account_sid
auth_token = config.twilio_auth_token
OWM_Endpoint = "https://api.openweathermap.org/data/2.5/onecall"
api_key = config.OWM_api_key
parameters = {
"lat": 41.14961,
"lon": -8.61099,
"exclude": "current,min... |
#!/usr/bin/python3
import numpy as np
import os
import matplotlib.pyplot as plt
import logging
import RGreedy
def eval(sr_info_res, G_res, PL, params):
'''
Evaluate the PDR and lifetime of the solution
Args:
sr_info_res: generated sensor/end device configuration
G_res: generated gateway placement
PL: path l... |
from distutils.core import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="HW_10", # Replace with your own username
version="0.1.0",
author="Olga",
author_email="Olga@example.com",
description="Creation of packages for projects HW8 and HW9",
long_descript... |
from .controllers import CoinbasePro, Kucoin, Local
class CryptoDockApi :
def __init__(self, Args) :
self.base = Args.API_HOST
self.port = Args.API_PORT
self.version = Args.API_VERSION
self.uri = "http://{}:{}/api/{}".format(self.base, self.port, self.version)
self.Local =... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import os
import argparse
import time
import sys
from f3.regex_counter import RegexCounter
from f3.filter_counter import FilterCounter
try:
from chardet.universaldetector import UniversalDetector
except ImportError:
print('WARNING: failed to load package "chard... |
import numpy as np
import pymc3 as pm
import theano
import arviz as az
from arviz.utils import Numba
from scipy.stats import mode
import theano.tensor as tt
Numba.disable_numba()
Numba.numba_flag
floatX = theano.config.floatX
# For creating toy data
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.m... |
#!/usr/bin/python
import os
import wx
import sys
#import shutil
import pyFileOps.file as fops
# developed by help of : https://wiki.wxpython.org/AnotherTutorial
class MyTextDropTarget(wx.TextDropTarget):
def __init__(self, object):
wx.TextDropTarget.__init__(self)
self.object = object
def o... |
"""create cases_per_county_and_day materialized view
Revision ID: a9ca657b90f5
Revises: f8791d49d830
Create Date: 2020-11-26 15:25:59.925681
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = 'a9ca657b90f5'
down_revision = 'f8791d49d830'
branch_labels = None
depends_on = None
def upgrad... |
from flask import Flask ,render_template ,request
app = Flask(__name__)
@app.route("/")
def website():
return render_template('03-cv-business.html')
@app.route("/read")
def about():
return render_template('letter.html')
@app.route("/cer11")
def form():
return render_template('certf11.html')
@app.route("/cer10")
def... |
#!/usr/bin/env python
from Bio import SeqIO
from threading import Thread
from glob import glob
from itsxcmd import ITSxCommandLine
from itsx import make_path, BinPacker
import os
import shutil
__author__ = 'mike knowles'
class ITSx(object):
def __init__(self, i, o, cpu, **kwargs):
from Queue import Queue... |
"""
January 19th 2020
Author T.Mizumoto
"""
#! python 3
# ver.x1.00
# SuperFigure.py - this program make a figure that be drown calculated the area and mesured point.
from stl import mesh
import numpy as np
import matplotlib.pyplot as plt
from rectselect import RectSelect
class SuperFigure(object):
... |
from django.utils.unittest.case import skipIf
from datetime import datetime
from django.test import TestCase
from django.contrib.auth.models import User
from transit_subsidy.models import TransitSubsidy,Mode,OfficeLocation
import StringIO
import csv
import json as simplejson
class TransportationSubsidyViewTest(TestCa... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
from __future__ import absolute_import
from __future__ import unicode_literals
import unittest
from copy import deepcopy
from junitparser import (
TestCase,
TestSuite,
Skipped,
Failure,
Error,
Attr,
JUnitXmlError,
JUnitXml,
... |
from neuroio import Client
def test_client_default_api_version():
neuroio = Client()
assert neuroio.api_version == 1
def test_client_api_version():
neuroio = Client(api_version=2)
assert neuroio.api_version == 2
def test_get_incorrect_attr():
neuroio = Client(api_version=1)
in_exception = ... |
import os.path as osp
import torch
import torch.nn.functional as F
from torch_geometric.datasets import LINKXDataset
from torch_geometric.nn import LINKX
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', 'LINKX')
dataset = LINKXD... |
{
'targets': [
{
'target_name': '<!(node -e \"require(\'./package.json\').binary.module_name\")',
'module_name': '<!(node -e \"require(\'./package.json\').binary.module_name\")',
'module_path': '<!(node -e \"require(\'./package.json\').binary.module_path\")',
'sources': [
'<!@(tools/genmoc.sh)',
'src/br... |
# @author: Michael Vorotyntsev
# @email: linkofwise@gmail.com
# @github: unaxfromsibiria
import signal
import socket
import time
import weakref
from threading import Thread
from .config import Configuration, LoggerWrapper
from .common import CommandBuilder
from .processing import CommandExecuter, WorkerStatusEnum
... |
from flask import Flask, jsonify, request
from flask_socketio import SocketIO, send
from flask_cors import CORS
from pymongo import MongoClient
from bson import json_util
import json
app = Flask(__name__)
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
#socket = SocketIO(app, cors_allowed_origins="*")
myclient... |
# uniform content loss + adaptive threshold + per_class_input + recursive G
# improvement upon cqf37
from __future__ import division
import os, scipy.io
import tensorflow.compat.v1 as tf
import tf_slim as slim
tf.disable_v2_behavior()
from d2s_numpy import depth_to_space
from PIL import Image
#import tensorflow.contrib... |
"""Predictors based on gammatone spectrograms"""
from pathlib import Path
import numpy as np
from eelbrain import *
from trftools.neural import edge_detector
DATA_ROOT = Path("~").expanduser() / 'Data' / 'Alice'
STIMULUS_DIR = DATA_ROOT / 'stimuli'
PREDICTOR_DIR = DATA_ROOT / 'predictors'
PREDICTOR_DIR.mkdir(exist_o... |
# python 3.7
"""Utility functions for visualizing results on html page."""
import base64
import os.path
import cv2
import numpy as np
__all__ = [
'get_grid_shape', 'get_blank_image', 'load_image', 'save_image',
'resize_image', 'add_text_to_image', 'fuse_images', 'HtmlPageVisualizer',
'VideoReader', 'Video... |
import sys
from skbuild import setup
setup(
name="pywasm3",
version="0.1",
description="Python 3 bindings for wasm3",
author='arrisde',
license="MIT",
packages=['pywasm3'],
install_requires=["cffi==1.14.0"]
)
|
"""This defines a basic set of data for our Star Wars Schema.
This data is hard coded for the sake of the demo, but you could imagine
fetching this data from a backend service rather than from hardcoded
JSON objects in a more complex demo.
"""
from typing import List, NamedTuple, Optional
class Ship(NamedTuple):
... |
# Generated by Django 2.2.7 on 2020-04-23 11:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Chat',
fields=[
('id', models... |
from django.http import request
import pandas as pd
import numpy as np
import json
import sklearn.neighbors
from polls.models import *
pd.set_option('chained_assignment',None)
pd.set_option('display.max_columns',100)
class DistanceH:
def distance_haversine(self, user_id):
# School Data
school_dat... |
import datetime
class Todo:
def __init__(self, task, category,
date_added=None, date_completed=None,
status=None, position=None):
self.task = task
self.category = category
self.date_added = date_added if date_added is not None else datetime.datetime.now()... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import logging
from fnmatch import fnmatch
import mutagen
from mutagen.easyid3 import EasyID3
import urchin.fs.default
import urchin.fs.json
import urchin.fs.plugin
import urchin.fs.mp3
MP3_GLOB = "*.mp3"
class Plugin(ur... |
# -*- coding: utf-8 -*-
"""
This is helper.py module
"""
class Helpers(object):
"""
Helper class
"""
def add_two(self, a, b):
"""
add two value
"""
return a + b
|
# coding=utf-8
class Processor(object):
"""
Processor base class
"""
name = None
parent = None
def __init__(self, name=None, parent=None):
self.name = name
self.parent = parent
@property
def info(self):
return self.name
def process(self, content, debug=Fa... |
# Read a VLC playlist in xspf format and shuffle it. Compared to
# using the "shuffle" mode, this has the advantage that it can be
# browsed in the playlist - you can see the next and previous, etc.
import xml.etree.ElementTree as ET
from urllib.parse import unquote, urlparse
import os
import sys
import random
files =... |
import stripe
from stripe.test.helper import StripeResourceTest
class TransferTest(StripeResourceTest):
def test_list_transfers(self):
stripe.Transfer.list()
self.requestor_mock.request.assert_called_with(
'get',
'/v1/transfers',
{}
)
def test_canc... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from apps.generic.models import GenericUUIDMixin
class Sms(GenericUUIDMixin):
phone = models.CharField(_("Phone"), max_length=64)
sms = models.TextField(_("Sms"))
def __str__(self):
return f"Sms {self.phone}: {s... |
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import pickle
with open('datas/champion_filter.pkl', 'rb') as f:
champion_datas = pickle.load(f)
palette_1 = sns.color_palette('hls',8)
palette_2 = sns.color_palette("Paired", 9)[1:]
def show_rateplot(df, criteria):
... |
import numpy as np
from torch.utils.data import Dataset
class DependentMaskContrastiveDataset(Dataset):
def __init__(self, data, Z):
self.data = data
self.Z = Z
assert data.shape[0] == Z.shape[0]
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
... |
import io
import pathlib
import hashlib
import pandas as pd
import requests
from bs4 import BeautifulSoup
from PIL import Image
from selenium import webdriver
def get_content_from_url(url):
driver = webdriver.Firefox() # add "executable_path=" if driver not in running directory
driver.get(url)
driver.exe... |
import numpy as np
import torch
from torch import tensor
import torchvision.transforms as transforms
from .base_model import BaseModel
from . import networks
from .patchnce import PatchNCELoss
import util.util as util
import cv2
import face_alignment as F
import os
from PIL import Image
class CUTModel(B... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trex.settings")
from django.core.management impor... |
# Generated by Django 3.0.8 on 2020-07-10 09:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("furport", "0009_event_google_map_location")]
operations = [
migrations.RemoveField(model_name="event", name="google_map_location"),
migrations.Ad... |
# noqa: E501 # verify-helper: PROBLEM https://onlinejudge.u-aizu.ac.jp/courses/library/7/DPL/5/DPL_5_B
from cpl.combinatronics.enumerator import Enumerator
def main() -> None:
n, k = map(int, input().split())
e = Enumerator(k, 1_000_000_007)
print(e.permutate(k, n))
if __name__ == "__main__":
main()... |
# This file is part of the Data Cleaning Library (openclean).
#
# Copyright (C) 2018-2021 New York University.
#
# openclean is released under the Revised BSD License. See file LICENSE for
# full license details.
"""Class that implements the DataframeMapper abstract class to perform groupby
operations on a pandas data... |
import plotly.express as px
import plotly.io as pio
import chart_studio.tools as tls
import plotly.graph_objects as go
from urllib.request import urlopen
import pandas as pd
import matplotlib.pyplot as plt
import os, sys
import json
import imageio
import glob
__author__ = 'Duy Cao'
__license__ = 'MIT'
__status__ = 're... |
import numpy as np
import os
import torch
import pandas as pd
from shutil import copyfile
source_root_url = "../../egs/dataset/Giant-MIDI"
data_root_url = "../../egs/dataset/giant_midis"
data_train_url = "../../egs/dataset/giant_midis/train"
data_vaild_url = "../../egs/dataset/giant_midis/vaild"
data_test_url = "../../... |
# Copyright 2021 JD.com, Inc., JD AI
"""
@author: Yehao Li
@contact: yehaoli.sysu@gmail.com
"""
import torch
from xmodaler.utils.registry import Registry
EVALUATION_REGISTRY = Registry("EVALUATION")
EVALUATION_REGISTRY.__doc__ = """
Registry for evaluation
"""
def build_evaluation(cfg, annfile, output_dir):
eval... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : BobAnkh
# @Github : https://github.com/BobAnkh
# @Date : 2020-12-09 19:33:29
# @LastEditTime : 2020-12-12 12:49:58
# @Description :
import cmd_control as cctl
import send
def get_location():
'''
获取当前位置
Returns:
list:... |
import json
import click
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import UniqueConstraint
from pgsync.base import create_database, pg_engine
from pgsync.helper import teardown
from pgsync.utils import get_config
Base = declarative_base()
class User(Base... |
# -*- coding:utf-8 -*-
from itertools import groupby
import io
from datetime import datetime
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.dates import DateFormatter
from matplotlib.figure import Figure
from matplotlib.ticker import MaxNLocator
import numpy as np
from dj... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from config import config
import math
#https://github.com/romulus0914/MixNet-Pytorch/blob/master/mixnet.py
class Attention(nn.Module):
def __init__(self, feature_dim, step_dim, bias=True, **kwargs):
... |
import core
import datetime
import logging
import time
import json
import os
import shutil
from core.helpers import Comparisons
from sqlalchemy import *
logging = logging.getLogger(__name__)
class SQL(object):
'''
All methods will return False on failure.
On success they will return the expected data or... |
import random
#Node
class Node:
def __init__(self,data):
self.data = data
self.next = None
self.random = None
#linked list
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.map = []
#add node
def addNode(self,data):
... |
#%%
# This notebook analyzes misc episode-level statistics; i.e. reproduces Fig A.1.
import numpy as np
import pandas as pd
import os
import os.path as osp
import json
import matplotlib.pyplot as plt
import seaborn as sns
import PIL.Image
import torch
from obj_consts import get_variant_labels, get_obj_label
from fp_fin... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""A module containing all the e2e model related benchmarks."""
from superbench.benchmarks.model_benchmarks.model_base import ModelBenchmark
from superbench.benchmarks.model_benchmarks.pytorch_bert import PytorchBERT
from superbench.benchmarks.m... |
# Copyright (c) 2018 NEC, Corp.
#
# 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... |
from Optimizacion.Instruccion import Instruccion
from Optimizacion.reporteOptimizacion import *
class Asignacion(Instruccion):
def __init__(self,id=None, valorizq=None,operador=None,valorder=None,linea=''):
self.valorder=valorder
self.valorizq=valorizq
self.operador=operador
self.id... |
from sqlalchemy import or_
from biz.ds.ds_eip import eip_sync_cmdb
from websdk.db_context import DBContext
from libs.base_handler import BaseHandler
from libs.pagination import pagination_util
from models.eip import FreeEip, model_to_dict
class EipHandler(BaseHandler):
@pagination_util
def get(self, *args, *... |
import datetime
import time
from typing import Any, Callable, Dict, Iterable, Optional, Tuple
import pendulum
import prefect
from prefect.client import Client
from prefect.core import Edge, Task
from prefect.engine.result import Result
from prefect.engine.runner import ENDRUN, call_state_handlers
from prefect.engine.... |
from metaprogramming.fido import Fido
class Anger(type):
def angry(cls):
print("{} is angry".format(type(cls())))
return True
def __call__(cls, *args, **kwargs):
this = type.__call__(cls, *args, **kwargs)
setattr(this, "angry", cls.angry)
return this
class AngryFido(Fi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from json import load, dump
from os.path import expanduser, join
from time import asctime
from html.parser import HTMLParser
class CorruptedFileError(Exception): pass
user_cfg_path = '/home/bunburya/webspace/cgi-bin/pisg/pum/users.cfg'
class AliasParser(HTMLParser):
... |
#!/home/student/anaconda3/envs/deepsort/bin/python
import os
import cv2
from cv_bridge import CvBridge
import time
import argparse
import torch
import warnings
import numpy as np
import sys
import rospy
from sensor_msgs.msg import Image
from sensor_msgs.msg import CameraInfo
import image_geometry
from geometry_msgs.msg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.