text stringlengths 3.07k 12.6k |
|---|
from enum import Enum
from typing import Dict, List, Optional
import typing
import pydantic
from karp import query_dsl # , resourcemgr
from karp.domain import errors
from karp.util import convert as util_convert
from karp.utility.container import arg_get
class Format(str, Enum):
json = "json"
csv = "csv"... |
import sys
import os
import io
import re
import gzip
import pickle as cPickle
import glob
import json
import numpy as np
def say(s, stream=sys.stdout):
stream.write(s)
stream.flush()
def read_ubuntu_threads(dir_name, lang_scores=None):
###################################################################... |
import requests
import json
import re
import logging
from typing import List, Dict, TypeVar, Any
T = TypeVar("T", str, List[str])
DEFAULT_USERS_URL = "https://gist.githubusercontent.com/benjambles/ea36b76bc5d8ff09a51def54f6ebd0cb/raw/ee1d0c16eaf373cccadd3d5604a1e0ea307b2ca0/users.json"
DEFAULT_VENUES_URL = "https://gi... |
import torch
import torch.utils.data as data
import os
import urllib.request
import zipfile
import json
from survae.data import TrainValidTestLoader, DATA_PATH
class Text8(TrainValidTestLoader):
def __init__(self, root=DATA_PATH, seq_len=256, download=True):
self.train = Text8Dataset(root, seq_len=seq_len... |
#!/usr/bin/python3
# Copyright 2021. FastyBird s.r.o.
#
# 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 re... |
import logging
import sdl2
import sdl2ui
import sdl2ui.joystick
import sdl2ui.mixins
DEFAULT_COUNTDOWN = 8
class JoystickCapture(sdl2ui.Component, sdl2ui.mixins.ImmutableMixin):
def init(self):
self.register_event_handler(
sdl2.SDL_JOYBUTTONDOWN, self.capture_button)
self.register_ev... |
from tenable.errors import *
from ..checker import check, single
import pytest, os
def test_roles_constructor_name_typeerror(sc):
with pytest.raises(TypeError):
sc.roles._constructor(name=1)
def test_roles_constructor_description_typeerror(sc):
with pytest.raises(TypeError):
sc.roles._construc... |
#!/usr/bin/env python3
from argparse import ArgumentParser
from exp2bytecode_fe import parse
from exp2bytecode_interp_state import state
from pprint import pprint
#####################################################################################
def get_tsx():
# compute the 'top of stack' index
return len(... |
"""Performs Logistic Regression to find the probability of occurrence of diseases"""
import sys
import os
import time
lib_path = os.path.abspath(os.path.join('../', 'lib'))
sys.path.append(lib_path)
import numpy as np
import pandas as pd
from icd9 import ICD9
from sklearn.externals import joblib
# Parameters
diag_t... |
from unittest import TestCase
from collections import Iterable
from util_funcs import unique, non_repeat, flatten
class TestUnique(TestCase):
def test_basic(self):
"""Test basic unique functionality"""
l = [1, 1, 7, 7, 3, 3, 4, 5, 6]
r = [1, 7, 3, 4, 5, 6]
self.assertEqual(unique(... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 7 13:26:59 2021
@author: huzongxiang
source code from tensorflow_graphics
"""
import numpy as np
import tensorflow as tf
from typing import Tuple
from .tensor import TensorLike
def _double_factorial_loop_body(n, result, two):
result = tf.where(tf.greater_equal(n, tw... |
import torch
import pandas as pd
from pathlib import Path
import logging
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
from imutils.paths import list_images
import cv2
from enum import IntEnum
from collections import namedtuple
import sys
_cur=Path(__file__).absolute().parent
sys... |
import discord
import asyncio
import json
from discord.ext import commands
class Moderation(commands.Cog, description='Commands for moderating the server.'):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print('moderation.py loaded')
... |
import argparse
import random
import numpy as np
import torch
from model_pytorch import LMModel, load_openai_pretrained_model
from text_utils import TextEncoder
encoded_words = []
def create_dictionary(encoder):
words = ['go', 'to', 'agent', 'red', 'green', 'blue', 'landmark',
'circle', 'triangle'... |
import time
import logging
import re
import os
logger = logging.getLogger(__name__)
class Device(object):
def __init__(self, privateKeyLocation=None,
publicKeyLocation=None,
serverPublicKeyLocation=None):
if privateKeyLocation is not None and publicKeyLocation is not ... |
# coding: utf-8
import logging
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.template.defaulttags import register
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.views import View, generic
from requests import codes
from... |
from torchreid.utils import FeatureExtractor
import torch
import os
import sys
import numpy as np
import cv2
from PIL import Image
import errno
import mmcv
def test_sanity():
features = extractor('/home/dmitriy.khvan/deep-person-reid/tmp/debug/dbg_orig_0.jpg')
print(features)
def extract_image_patch(image... |
# -*- encoding:utf-8 -*-
"""
* Copyright (C) 2017 OwnThink.
*
* Name : findword.py - 新词发现
* Author : Yener <<EMAIL>>
* Version : 0.01
* Description : 新词发现算法实现
special thanks to
http://www.matrix67.com/blog/archives/5044
https://github.com/zoulala/New_words_find
"""
import re
from math import l... |
"""Run training synthetic docker models"""
import argparse
import getpass
import json
import os
import random
import time
import docker
import synapseclient
def create_log_file(log_filename, log_text=None):
"""Create log file"""
with open(log_filename, 'w') as log_file:
if log_text is not None:
... |
"""
Auth server.
Provides endpoints:
* obtain access token;
* check authorization (validate access token);
"""
from flask import Flask, request, jsonify
from jose import jwt
import json
import logging
import os
import requests
from typing import Text
LOGLEVEL = os.getenv('LOGLEVEL', 'INFO').upper()
logging.... |
#!/usr/bin/env python3
from sys import exit, stderr, argv
from os import dup
from Feeder import Feeder
from Bar import Bar
from OptionUsageException import OptionUsageException
from getopt import gnu_getopt, GetoptError
from i3ipc import Connection
from apscheduler.schedulers.background import BackgroundScheduler
from... |
import utils
from database_con import *
import json
import psycopg2
def register(provide_username, provide_keyword, provide_name, phoneNum):
conn = psycopg2.connect(database=database, user=user, password=password, host=host, port=port)
cursor = conn.cursor()
truth_username = utils.base64decode(provide_us... |
import numpy as np
import pandas as pd
import pylab as plt
import cv2
import os
from sklearn.metrics import confusion_matrix
import mlxtend.plotting
from tqdm import tqdm
from IPython.display import clear_output
from keras.utils.np_utils import to_categorical
from keras.models import Model
from keras.callba... |
#!/usr/bin/env python3
# coding=utf-8
"""
Scraper for Morflot Ships Book.
Main data source (source system address): http://morflot.gov.ru/
Useful materials and resources:
- *(excel) http://morflot.gov.ru/deyatelnost/transportnaya_bezopasnost/reestryi/reestr_obyektov_i_transportnyih_sredstv/f3926.ht... |
from utils import *
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
import numpy as np
import torch
import matplotlib.pyplot as plt
def load_data(base_path="../data"):
""" Load the data in PyTorch Tensor.
:return:... |
import numpy as np
import tensorflow as tf
import random as rn
import re
import json
validation_split = .2
epochs = 50
DATA_COUNT = 10000
batch_size = 128
data_path = 'data/input.txt'
model_path = 'models/model.h5'
punctuation = ['!', '?', '.', ',']
sentinels = ['<BOS>', '<EOS>']
OOV_TOKEN = '<OOV>'
PAD_TOKEN = '<... |
import copy
import os
import gnupg
import json
import requests
from ..helper import fatal_error, info, ActionOnExit, error, warning
from ..config import AccountData
def configure_iam(account: AccountData):
configure_iam_policy(account)
configure_iam_saml(account)
dns_domain = account.domain
if dns_do... |
#Embedded file name: ACEStream\Core\dispersy\member.pyo
from __future__ import with_statement
from hashlib import sha1
from singleton import Parameterized1Singleton
from dispersydatabase import DispersyDatabase
from crypto import ec_from_private_bin, ec_from_public_bin, ec_to_public_bin, ec_signature_length, ec_verify,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-05-17
# @Author : <NAME> (<EMAIL>)
# @Link : https://www.shawnshan.com/
import argparse
import glob
import logging
import os
import sys
logging.getLogger('tensorflow').setLevel(logging.ERROR)
os.environ["KMP_AFFINITY"] = "noverbose"
os.environ['TF_CP... |
import random, heapq
# Assuming `online` is the set of users that is online, find a path to
# send `amount` coins from `frm` to `to` through `coins` where each
# step along the path is between users that have adjacent fragments.
# A transfer done in this way does not contribute to fragmentation.
def find_path(coins, f... |
__author__ = 'qchasserieau'
import itertools
import pandas as pd
from shapely import geometry as shapely_geometry
from syspy.skims import skims
from syspy.transitfeed import feed_links
def linestring_geometry(row):
return shapely_geometry.linestring.LineString([[row['x_origin'], row['y_origin']],
... |
# MIT License
#
# TFmini appears to be an eye safe laser ... asked for confirmation
# 120 mW @ 850 nm, class ?
# Sparkfun website says it is not a laser ... hence, no eye issues
#
from serial import Serial
import time
from collections import deque
import struct
class SerialBase:
def __init__(self, port):
... |
import json
from cascade.core.db import cursor
from cascade.core.log import getLoggers
from cascade.input_data.configuration import SettingsError
from cascade.input_data.configuration.form import Configuration
CODELOG, MATHLOG = getLoggers(__name__)
def load_settings(ec, meid=None, mvid=None, settings_file=None):
... |
import tensorflow as tf
from ..net import model_crf, model_softmax
from .location import locate, pair_vector
from collections import OrderedDict
import pickle
import os
import numpy as np
os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'
def annotate(text=None,
num_units=128,
num_layers=2,
... |
import text
import utils
import os
import sys
import writer
from slugify import slugify
from nltk import pos_tag
NOUN_THRESHOLD = 0.20
dir_name = os.path.dirname(os.path.realpath(__file__))
file_name = sys.argv[1] if len(sys.argv) > 1 else "texts/news/tech/001.txt"
file_path = os.path.normpath(os.path.join(dir_name,... |
# let's figure out some tests
import numpy as np
import os
import glob
import tempfile
from scipy.interpolate import RectBivariateSpline, interp1d
from hera_sim.interpolators import Tsky, Beam, Bandpass
from nose.tools import raises
def test_interpolator():
# make parameters for temporary npz file
freqs = np... |
#!/usr/bin/env python3
#
# Copyright 2018 <NAME> <<EMAIL>>
#
# 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, modif... |
# -*- coding: utf-8 -*-
"""
xParrotAPI Class Instance
***********************
>>> api = xParrotAPI() // Make sure to set the AIRTABLE_API_KEY environment variable.
>>> api.fetch(started())
[{'id': 'recMtGPR0nE6499eC', 'fields': {'Name': 'Mess with Flutter', 'Notes': 'How much effort is needed to make a list from a si... |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import argparse
import gzip
import pathlib
import shutil
import subprocess
import sys
from urllib import request
from xml.etree import ElementTree
import yaml
BASE_REPO_URL = "https://packagecloud.io/sensu/... |
from unittest import TestCase, expectedFailure
import re
import shutil
from typing import Any, TYPE_CHECKING
import integration_helpers as helpers
# This list should match test_fixed_sequence in mock_server.c
test_fixed_sequence = [0.0, 1.0, 0.5, -1.0, 280.0, -12.5, 16.3, 425.87, -100000.0, 0.001]
class FileLoadTest... |
"""
Utilities related to project directory.
"""
import datetime
import os
import subprocess
from multiprocessing.dummy import Pool, Process, Manager
from antlr4 import FileStream, CommonTokenStream
from antlr4.TokenStreamRewriter import TokenStreamRewriter
from joblib import Parallel, delayed
from gen.java.JavaLexer ... |
import os
import subprocess
import re
import tarfile
import modules.file as file
import modules.log as log
import modules.runner as runner
import modules.net as net
import modules.pack as pack
def run_task_build():
check_cmake()
# structure
root_dir = file.root_dir()
target_name = "android"
buil... |
import json
import threading
import time
from typing import Union, List, Set, Dict
import attr
from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager
class BinanceMarketDataMessage:
@staticmethod
def from_dict(data: dict, obj_type):
obj = obj_type()... |
import hashlib
import json
import pickle
from pathlib import Path
from time import sleep
from typing import Any, Dict, List, Set
import requests
from django.core.management.base import BaseCommand, CommandParser, CommandError
from tqdm import tqdm
from sok.models import Publication, PublicationReference, SemanticSc... |
import torch as th
from typing import Optional, Tuple
from tpp.utils import batch as bu
from tpp.utils.events import Events
from tpp.utils.utils import smallest_positive
from tpp.utils.index import take_2_by_2
from tpp.utils.history_bst import get_prev_times as get_prev_times_bst
def _get_rank(x: th.Tensor) -> int:... |
#!/usr/bin/env python
#
# Generated by generateDS.py.
# Python 2.7.14 (default, Sep 23 2017, 22:06:14) [GCC 7.2.0]
#
# Command line options:
# ('--no-dates', '')
# ('--no-versions', '')
# ('--member-specs', 'list')
# ('-f', '')
# ('-o', 'tests/ipo2_sup.py')
# ('-s', 'tests/ipo2_sub.py')
# ('--super', '... |
#
# Copyright (c) 2008 <NAME>
# Copyright (c) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this li... |
#!/usr/bin/env python3
from newengine import *
from random import randrange
"""creates visual mazes of any size"""
# -- PREFERENCES --
APP_NAME = "Programming Mazes"
MAZE_SIZE = (24, 16) # (W, H)
DELAY = 0.01
CELLWIDTH = 3
WALLWIDTH = 1
PIXEL_SIZE = (8, 8)
B_DRAW_STACK_TRACE = True
BT_DELAY = DELAY*.5
# -- CON... |
import argparse
import collections
import os
import pickle
import pytest
import re
import signal
import subprocess
import sys
import time
import numpy as np
import cntk as C
TIMEOUT_SECONDS = 300
NUM_WORKERS = 4
NUM_BATCHES = 10
BATCH_SIZE_PER_WORKER = 20
def mpiexec_execute(script, mpiexec_params, params, timeout_se... |
import streamlit as st
import numpy as np
import pandas as pd
from PIL import Image
from keras.models import load_model
import cv2
import time
#import keras model
eye_model_1 = load_model('sigmoid_final_cataract-90.h5')
eye_model_2 = load_model('accuracy-92size100x100_Threshold_0.56.h5')
st.set_page_config(page_tit... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""WAD file reader
"""
__version__ = '0.0.1'
__date__ = '2021-06-19'
__author__ = '<NAME>'
__all__ = ['WAD', 'WADEntry']
#######################################################################################
from collections import namedtuple
import io, os
from typ... |
import sys
import os
import rawpy
import json
import base64
from copy import copy
from contextlib import suppress
from flask import jsonify
from google.cloud import storage
from astropy.io import fits
PROJECT_ID = os.getenv('PROJECT_ID', 'panoptes-exp')
BUCKET_NAME = os.getenv('BUCKET_NAME', 'panoptes-incoming')
UPL... |
import logging
from utils import *
import os
import sys
import requests
import pandas as pd
from joblib import Parallel, delayed
RESULTS_DIR = "/med/pdbrepo/pdb_pubmed_pdfs"
PDFS_DIR = os.path.join(RESULTS_DIR, "pdfs")
ERRORS_FILE = os.path.join(RESULTS_DIR, "failed_pubmeds.csv")
def query_pdbj(sql, format, dest_fil... |
#
# ICRAR - International Centre for Radio Astronomy Research
# (c) UWA - The University of Western Australia
# Copyright by UWA (in the framework of the ICRAR)
# All rights reserved
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Filename: test_manager.py
# Project: api
# Author: <NAME>
# Created: Tuesday, 3rd November 2020 3:46:09 pm
# License: BSD 3-clause "New" or "Revised" License
# Copyright (c) 2020 <NAME>
# Last Modified: Tuesday, 3rd November 2020 3:46:09 pm
# Modified By: <NAME>
from... |
import logging
from typing import Any, Optional
import matplotlib
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pytorch_lightning as pl
import torch
import wandb
from power_perceiver.analysis.simple_callback import SimpleCallback
from power_perceiver.c... |
import os
import copy
import tensorflow as tf
import numpy as np
from tensorflow import layers, initializers
from collections import Iterable
def normalized_columns_initializer(std=1.0):
def _initializer(shape, dtype=None, partition_info=None):
out = np.random.randn(*shape).astype(np.float32)
... |
import os
import uuid
import boto3
from six.moves import configparser
from botocore.exceptions import ClientError
from .aws_util_exceptions import ProfileParsingError
from .aws_util_exceptions import RoleNotFoundError
from .aws_util_exceptions import AssumeRoleError
def get_aws_account_id(profile=None):
if profil... |
'''
Implementation of the TextRank algorithm
'''
import re
from string import punctuation
from math import log10
from scipy.sparse import csr_matrix
from scipy.linalg import eig
import numpy as np
from nltk.tokenize import sent_tokenize, RegexpTokenizer
from nltk.stem.snowball import EnglishStemmer
from nltk.corpus im... |
from PyQt5.QtWidgets import (
QTableWidget,
QAbstractItemView,
QHeaderView,
QTableWidgetItem,
QWidget,
QVBoxLayout,
QGroupBox,
QPushButton,
QCheckBox,
QMenu,
QAction,
)
from PyQt5.QtCore import Qt
from style import BG_COLOR
class SimpleFilterArtistsTable(QTableWidget):
... |
"""Line strings and related utilities
"""
from ctypes import c_double, cast, POINTER
from ctypes import ArgumentError
from shapely.geos import lgeos
from shapely.geometry.base import BaseGeometry
from shapely.geometry.proxy import CachingGeometryProxy
__all__ = ['LineString', 'asLineString']
class LineString(BaseG... |
from pathlib import Path
from typing import Iterable
from kyofu.metadata import Metadata
from kyofu.model import Song, Library
def parse_args():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--yes', '-y', action='store_true')
subparsers = parser.add_subparsers(re... |
from django.contrib.gis.gdal import SpatialReference, CoordTransform
# from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.geos import Point
from utility.geodesy import GeoPosition, SurfaceVector
# from django.contrib.gis.geos import LineString
# from geopy.distance import distance
# from shapely.g... |
import math
import os
from glob import glob
import tensorflow as tf
import pandas as pd
from tqdm import tqdm
NUM_PARALLEL_CALLS = 2
CYCLE_LENGTH = 16
BLOCK_LENGTH = 2
def bucket(buckets, batch_size):
return tf.data.experimental.bucket_by_sequence_length(
lambda source, target: source['seq_length'],
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from django.db import models, migrations
from chain.core.models import ScalarSensor
from chain.core.resources import influx_client
from django.utils.timezone import now
from datetime import datetime, timedelta
# from ... |
from ssdp_upnp.util import gen_logger, get_local_IP
import os
import socket
import re
import sys
import time
import threading
import miniupnpc
logger = gen_logger('upnp')
class Server(threading.Thread):
BCAST_IP = '172.16.58.3'
UPNP_PORT = 1900
IP = '0.0.0.0'
M_SEARCH_REQ_MATCH = "M-SEARCH"
... |
# ------------------------------------------------------------------------------
# CodeHawk C Analyzer
# Author: <NAME>
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2017-2020 Kestrel Technology LLC
#
# Permission is hereby granted, free of ch... |
"""Tests for the Compass helper functions.
Not all of Compass is implemented, and the arrangement of Compass functions
doesn't exactly match the arrangement in the original documentation.
Regardless, this is a good starting place:
http://compass-style.org/reference/compass/helpers/
Some functions appear to be undocu... |
import csv
import pickle
import time
import urllib
from datetime import datetime
import requests
from dateutil.parser import parser, parse
from constants import SAMPLE_MATCHES, SPECIFIC_MATCH_SAMPLE
PLAYER_HANDLES = [
'killacure24',
'clayschubiner',
'MarkMadness',
'socom1880',
'Rook',
'Arturi... |
import sys
import os
import shutil
import random
from multiprocessing import Process, Manager
import pandas as pd
from parse import *
from pyswip import Prolog
from commits import *
APP_NAME = "museuMonitor"
DAP = "dap(A,P,R,Infs,Time).".format(APP_NAME)
DAP_CR = "dapCR(A,NP,NR,Infs,Time).".format(APP_NAME)
INFR_FIL... |
# Copyright (c) 2019, Oracle and/or its affiliates.
# Copyright (C) 1996-2017 Python Software Foundation
#
# Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
from test.support import (TESTFN, run_unittest, import_module, unlink,
requires, _2G, _4G, gc_collect, cpython_only)
impo... |
from ..utility.expr_wrap_util import symbolic
from ..expr import BVV, BVS
from ..utility.models_util import get_arg_k
from ..sym_state import State
MAX_READ = 100
def read_handler(state: State, view):
fd = get_arg_k(state, 1, 4, view)
buf = get_arg_k(state, 2, state.arch.bits() // 8, view)
count = get_ar... |
import argparse
import cv2
import mxnet as mx
import numpy as np
from utils import face_preprocess
from utils.mtcnn_detector import MtcnnDetector
parser = argparse.ArgumentParser()
parser.add_argument('--image_size', default='112,112', help='models input size.')
parser.add_argument('--image', defa... |
"""utility functions for neuroimaging-specific applications."""
import logging
import numpy as np
import sana
from scipy.ndimage import affine_transform
#import nipy.modalities.fmri.hemodynamic_models as hrf
import nistats.hemodynamic_models as hrf
import nibabel as nib
logging.basicConfig(format="%(asctime)s %(filena... |
from typing import List
import torch
from torch import nn as nn
from mmcv.runner import force_fp32
from .furthest_point_sample import (furthest_point_sample,
furthest_point_sample_with_dist)
def calc_square_dist(point_feat_a, point_feat_b, norm=True):
"""Calculating square di... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from six.moves import xrange
# TODO
# - Proper tests of everything
# - be clearer about meaning of t_elapsed, t_ix and either (t)
# - Time Since Event is a ticking bomb. Needs better naming/... |
import yaml
import json
import os
import argparse
import getpass
from openpyxl import load_workbook
from gssacipkg import ACIobj, ACIconfig
def read_config_file(config_file):
"""Read an YAML config file
:param config_file: [description]
:type config_file: [type]
"""
if os.path.isfile(config_file... |
# -*- coding: utf-8 -*-
import os
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, Text, Boolean, String, ForeignKey, create_engine
from sqlalchemy.orm import sessionmaker, relationship
from flask_sqlalchemy import SQLAlchemy
import seed
engine = create_engine(os.enviro... |
from typing import Union, Optional, List
from qiskit import QuantumCircuit
from qiskit.providers import Backend
from qiskit.providers.aer import AerSimulator
from tomography.ansatz import AnsatzResults, get_ansatz
from tomography.cyclic_measurer import CyclicMeasurer
from utils.hamil_utils import TransverseIsingHamil... |
# import modules
try :
import os
import configparser
import time as tm
from datetime import *
import json
import prettytable
import easygui
import threading
except :
myassert( False, "Could not import some modules. Use \'pip install <module>\' to install them", True )
... |
import re
from django.db import models
from logging import getLogger
from api.exceptions import InvalidInput
logger = getLogger(__name__)
class DomainMetadata(models.Model):
"""
This table contains metadata for all domains.
CREATE TABLE public.domainmetadata (
id integer NOT NULL,
domai... |
import arrow
import asyncio
import discord
from discord.ext import commands
from math import ceil
class Guild(commands.Cog):
def __init__(self, bot: commands.Bot):
"""basic initalization of the guild cog"""
self.bot = bot
self.cache = self.bot.get_cog("Cache")
self.db = self.bot... |
# Copyright (c) 2019-2020, SPEAR3 authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
import asyncio
import pickle
from .spear3_api import within_spear3, \
_read_sext_value, _write_sext_value, \
_get_injection_state, _turn_off_injection, _turn_on_injection... |
import tensorflow as tf
import numpy as np
from configuration import Config
from core.anchor import Anchors
from core.efficientnet import get_efficient_net
from core.bifpn import BiFPN
from core.loss import FocalLoss
from core.prediction_net import BoxClassPredict
from utils.nms import NMS
class EfficientDet(tf.kera... |
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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
... |
#------------------------------------------------------------------------------#
# Funkcje pomocnicze dla skryptów realizujących zadania uczenia maszynowego
#
# author: <NAME>
# mail: <EMAIL>
# date: 25.08.2020
#------------------------------------------------------------------------------#
import numpy as np
from ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 24 10:08:14 2020
@author: dmattox
"""
import os, collections, glob, time
import numpy as np
import scipy.spatial
import Zernike
np.random.seed(27)
def getMol2Pnts(mol2FH):
''' Reads in the mol2 file specified by the argument and returns a li... |
######################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# SPDX-License-Identifier: MIT-0 #
######################################################################
import copy
import os
import json
i... |
'''
Copyright 2017 Recruit Institute of Technology
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... |
"""Custom Components componentstore."""
import os
import componentstore.functions.data as data
import componentstore.functions.manager as manager
from aiohttp import web
from aiohttp_basicauth import BasicAuthMiddleware
REASON = None
REDIS_HOST = None
REDIS_PORT = None
NO_CACHE = False
async def error_view(request... |
import random
import numpy as np
import pytest
import simpy
from numpy.testing import assert_array_equal
from estee.simulator import Worker
from estee.simulator.netmodels import compute_maxmin_flow, \
MaxMinFlowNetModel, SimpleNetModel
def test_maxmin_flow():
def mm_flow(send_capacities, recv_capacities, c... |
'''
Build reference file for images with data availability flags:
I: join to taxonomic reference
II: coerce missing higher level groups
III: add coerced higher level flag
III: join to metadata file
IV: add missing meta data flag
V: add ESDA exclusion flag
'''
# ... |
import urllib.request
import zipfile
import os
import warnings
from torch.utils.data import Dataset, DataLoader, random_split, Subset
from torchvision.transforms import RandomRotation, Normalize, Pad, Resize, ToTensor, Compose, InterpolationMode
import pytorch_lightning as pl
import numpy as np
from PIL import Imag... |
"""
Copyright (c) 2020 jcollinscastro
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, distribute,... |
"""Serilaizers for daatabase models."""
import logging
from django.forms.models import model_to_dict
from api.models import League, Player, PlayerStats, Season, Team, TeamStats
from rest_framework import serializers
logger = logging.getLogger(__name__)
def update_or_create(model, data, id_field):
try:
ob... |
"""
Define FastaRandomReader which accesses reads in FASTA
or ContigSet files randomly.
Note that a ContigSet can contain multiple FASTA files,
but can only contain FASTA files and filters in the
ContigSet will not be respected.
"""
from collections import namedtuple
import os.path as op
import logging
from pbcore.i... |
import os
from flask import Flask
from flask import request, render_template, redirect, url_for, flash, session
from flask.ext.pymongo import PyMongo
import pymongo
from datetime import datetime
from functools import wraps
app = Flask(__name__)
app.config['MONGO_HOST'] = 'localhost'
app.config['MONGO_PORT'] = 27017
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" template5 comes to complete the previous one
incorporating a file as a database ... """
from tkinter import *
from tkinter import messagebox
# initialize list to store contacts
the_list = []
# place all application methods below
def center(tk):
w = 700
h = ... |
from typing import Union
from fastapi import APIRouter, File, Security, UploadFile
from fastapi import HTTPException, status
from fastapi import Depends
from fastapi.security import APIKeyHeader
from configs import *
from main_processes.frontend.args import parse_args
from main_processes.frontend.utils import download... |
import asyncpg
import math
import uvloop
# from datetime import datetime
from sanic import Sanic
from sanic import response
loop = uvloop.new_event_loop()
app = Sanic()
app.debug = False
# Serve files from the static folder to the URL /static
app.static('/', './static')
async def initdb_pool():
dbdict = {"dat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.