text stringlengths 3.07k 22.1k |
|---|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import defaultdict
import numpy as np
from scipy.ndimage.morphology import binary_dilation
from scipy.ndimage.interpolation import map_coordinates
from dipy.segment.clustering import QuickBun... |
import codecs
from models import *
from data_helper import load_text_target_label, load_w2v
import os
import pickle
import numpy as np
import pandas as pd
import argparse
#inaam
def load_sentences(k): # for reading a file line by line
valid_lines=[]
with open(k) as word_file: # take a file
valid_lines... |
#!/usr/bin/env python3
from argparse import ArgumentDefaultsHelpFormatter, FileType, ArgumentParser
import json
import sys
import matplotlib
matplotlib.use('Agg')
import pylab as plt # noqa
plt.rcParams.update({
'axes.grid': True,
})
def log(*a, **kw):
print(*a, **kw, file=sys.stderr)
def ptiles_from_inp... |
from unittest.mock import Mock
import pytest
from ..exc import FetchError
from ..provider.postgresql import Connection
from . import util
try:
import psycopg2
except ImportError:
psycopg2 = None
def setup_function(function):
util.setup_pg_db()
@pytest.mark.postgres
def test_conn_attr(pgdb, pgpooldb):... |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
import sys
import numpy as np
from numpy import genfromtxt
import tkinter as tk
from tkinter import filedialog
import os
import pandas as pd
import matplotlib.pyplot as plt
import scipy.signal as signal
from scipy import interpol... |
try:
from selenium import webdriver
from selenium.common.exceptions import WebDriverException, StaleElementReferenceException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from s... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 参考网站:https://www.jianshu.com/u/69f40328d4f0
import math
from PIL import Image,ImageDraw
import os
import cv2
import numpy as np
# 查找当前路径下所有的png文件
def walkFile(path):
for root, dirs, files in os.walk(path):
for f in files:
if f.endswith('.png') or f... |
# Crank-Nicholson (implicit) finite difference method for a wildfire model.
# Code written by <NAME>. Implicit finite difference method derived by <NAME>, <NAME>, <NAME>, and
# <NAME>. 2018-12-10
import numpy as np
from scipy import linalg as la
from matplotlib import pyplot as plt
from matplotlib import animation
fro... |
from random import randrange
import random
from Resources.field import Segment, Perimeter
class FruitSpawner():
def __init__(self, fruitType):
self.fruitType = []
self.fruitType.append(fruitType)
self.maxFruits = 1
self.maxSpawns = 0
self.totalFruits = 0
self.fruitRa... |
import numpy as np
import pytest
from matplotlib import pyplot as plt
from matchms import Spectrum
from .builder_Spectrum import SpectrumBuilder
def _assert_plots_ok(fig, n_plots, n_lines):
assert len(fig.axes) == n_plots
assert fig is not None
assert hasattr(fig, "axes")
assert isinstance(fig.axes, l... |
import numpy as np
from PIL import Image
from math import sqrt
from abc import ABC, abstractmethod
# handy utility functions for working with vectors (avoids numpy...)
class Utility:
@staticmethod
def add(x,y):
if len(x) != len(y):
raise Exception("Mismatched Vector Lengths")
return... |
import sqlite3
import pandas as pd # This is to print the sql database in a 'pretty' way.
import time # To get time for email text write up
##########################################################################################################################################
######################################... |
import numpy as np
from sklearn import metrics
from sklearn import calibration
import pandas as pd
import os
from scipy.optimize import brentq
from scipy.interpolate import interp1d
from scipy.optimize import minimize_scalar
def _compute_eer(y_true, y_score, average=None):
def _find_eer_intersection(false_pos_rat... |
"""
Fermi Rain Animation
Author: <NAME> (Fermi mods)
Original Author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from astropy.io import fits
import matplotlib as mpl
from astropy.time import Time
# 2017-01-01 00:00:00.000
metstart = 504921604.000
# 2... |
from Config._const import BRAIN
from Config._db import Database
import random, discord
from datetime import datetime, timezone
from calendar import monthrange
from Config._functions import is_whole
def HELP(PREFIX):
return {
"COOLDOWN": 1,
"MAIN": "The command for birthday registering and viewing",
"FORMAT": "(... |
#!/usr/bin/env python3
import json
import os
import pprint as pp
import random
import time
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from torch.utils.tensorboard.summary import hparams
from torch_geometric.data import DataLoader
from dataset import load_dataset, split_dataset
f... |
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
from torch import nn
from modules import Wavenet2D, Conv2D, ZeroConv2d
from torch.distributions.normal import Normal
from functions import *
#################################################################################
# experimental mdoel 1: shared parameters for each entire flow
class WaveFlowCoupling2D(nn.Modul... |
# coding=utf-8
# *** WARNING: this file was generated by test. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
from ._enums import *
__... |
import numpy as np
import paddle.fluid as fluid
from paddle.fluid.dygraph import to_variable
from paddle.fluid.dygraph import Conv2D
from paddle.fluid.dygraph import BatchNorm
from paddle.fluid.dygraph import Pool2D
from paddle.fluid.dygraph import Linear
model_path = {'ResNet18': './resnet18',
'ResNet34... |
"""
Very Deep Convolutional Networks for Large-Scale Visual Recognition.
Applying VGG 16-layers convolutional network to Oxford's 17 Category Flower
Dataset classification task.
References:
Very Deep Convolutional Networks for Large-Scale Image Recognition.
<NAME>, <NAME>. arXiv technical report, 2014.
Links:
... |
import logging
import simplejson
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_noop
from couchdbkit import RequestFailed
from dimagi.utils.decorators.memoized import memoized
from corehq.apps.api.es import CaseES
from corehq.apps.es import filters
from corehq.apps.e... |
import umap
from typing import Callable, Tuple
import torch
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from einops import rearrange
from torchvision.utils import make_grid
from scipy.stats import truncnorm
from scipy.stats import norm
from sklearn.manifold import TSNE
device = torch.device('c... |
import os
import re
import io
import yaml
import numpy as np
from scipy.io import loadmat
from scipy.io.matlab.mio5_params import mat_struct
# HACK: fix loading number in scientific notation
#
# https://stackoverflow.com/questions/30458977/yaml-loads-5e-6-as-string-and-not-a-number
#
# An apparent bug in python-yaml ... |
import logging
import math
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.http import Http404
from django.shortcuts import render, redirect
from django.urls import reverse, reverse_lazy
from django.utils.de... |
import torch
import rlkit.torch.pytorch_util as ptu
import numpy as np
def fetch_preprocessing(obs,
actions=None,
normalizer=None,
robot_dim=7, # CHANGE 10->7
object_dim=15,
goal_dim=3,
... |
# -*- coding: utf-8 -*-
import theano
import theano.tensor as T
import numpy as np
import pandas as pd
from collections import OrderedDict
INIT_RANGE = 0.01
def uniform(lb, ub, size):
"""
:param lb: lower bound
:param ub: upper bound
:param size: tensor shape
:return:
"""
return np.array... |
import argparse
import category_encoders as ce
import numpy as np
import re
import pandas as pd
from nltk.corpus import stopwords
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
from collections import Counter
from itertools import chain, combinations
from sklearn.feature_extraction.text import C... |
#!/usr/bin/env python3
import cv2
import time
import mediapipe as mp
from argparse import ArgumentParser
import rospy
from geometry_msgs.msg import Twist
def build_argparser():
parser = ArgumentParser()
parser.add_argument("-i", "--input", default=0, required= False, type=int,
help="vi... |
# coding: utf-8
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
# A module which holds test configuration information. This is intended to be a shared space where tests
# can figure out what kind of recording (via VCR) is being done and also so that they can take actions (e.g. waiting)
#... |
import pytest
from meetup_data_scraper.meetup_scraper.meetup_api_client.meetup_api_client import (
RateLimit,
MeetupApiClient,
)
from meetup_data_scraper.meetup_scraper.meetup_api_client.exceptions import (
HttpNoSuccess,
HttpNotFoundError,
HttpNotAccessibleError,
HttpNoXRateLimitHeader,
)
from ... |
"""Tests for distutils.unixccompiler."""
import os
import sys
import unittest
from test.support import run_unittest
from unittest.mock import patch
from .py38compat import EnvironmentVarGuard
from distutils import sysconfig
from distutils.errors import DistutilsPlatformError
from distutils.unixccompiler import UnixCC... |
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras import Model as M
from tensorflow.keras import Input as I
from tensorflow.keras.layers import Conv2D, Dense, Flatten
from utils.tf2_utils import get_device
from Nn.layers import ConvLayer
from Nn.activations import default_activation
... |
import ffmpeg
import json
import animation
# from ffmpy import FFmpeg
import tempfile
import urllib.request
import requests
from urllib.parse import urlparse
from tqdm import tqdm
import os
from dataclasses import dataclass
import re
import shutil
from time import sleep
import logging
import coloredlogs
formatter = "... |
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import time
from sortedcontainers import SortedList
from dateutil.parser import parse as dtparse
from pytimeparse import parse as tparse
from scipy import interpolate
class UserSortedList(object):
def __init__(self, iterable=None, key=None):
... |
# This program has been developed by students from the bachelor Computer Science at Utrecht University within the
# Software and Game project course
# ©Copyright Utrecht University Department of Information and Computing Sciences.
"""Django management commands for courses app."""
from django.contrib.auth.models import... |
import base64
import datetime
import gzip
import json
from io import BytesIO
from typing import Callable, Optional, Dict, Any, Union, List
import requests
from requests.models import Response
from .__version__ import __version__
def py3_b64encode(input_str: str) -> str:
input_bytes = input_str.encode('utf8')
... |
# Copyright (c) 2020 NVIDIA CORPORATION. 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 required by appli... |
import argparse
import binascii
import random
from typing import BinaryIO, List, Optional
from ledgerblue.comm import getDongle
from test_cmds_txs import *
CLA = 0xE0
BIP32_HARD_PREFIX = 0x80000000
application_token = random.randint(
1, 0xFFFFFFFE).to_bytes(4, 'big', signed=False)
ledger = getDongle()
cli = ar... |
#!/usr/bin/env python3
import argparse
import contextlib
import datetime
import os
import subprocess
import sys
import time
from config import load_config
from contract import pf_contracts, pf_thresholds, wrb
from threading import Timer
from web3 import Web3, exceptions
# Post a data request to the post_dr method of ... |
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import pycurl
from io import BytesIO
import certifi
from utils import *
from datetime import datetime
import json
import re
JS_ROW_END = "~"
JS_CELL_END = "¬"
JS_INDEX = "÷"
SHAREDINDEXES_SPORT_ID = "SA"
DCAPIPARTICIPANTINDEXES_TEAM_INFO = "PR"
DCAP... |
# -*- coding: utf-8 -*-
import pygame
import pygame.locals
from random import randrange
print("Módulos importados com sucesso")
try:
pygame.init()
print("Start")
except:
print("Start")
tamanho = 10
largura = 600
altura = 600
placar = 40
preto=(0,0,0)
vermelho = (227,47,34)
verde = (66,204,39)
branco = (2... |
# -*- coding: utf-8 -*-
# Copyright 2019 <NAME>. 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 required by... |
# -*- coding: utf-8 -*-
import re
from six import PY3
from clld.lib.bibtex import u_unescape
from clld.lib import latex
latex.register()
if PY3: # pragma: no cover
unicode = str
unichr = chr
# FIXME: resolve remaining code duplication with clld.lib.bibtex
RE_XML_ILLEGAL = re.compile(
u'([\u0000-\u0... |
#!/usr/bin/env python3
import argparse
# we keep track of total planning cost
total_planning_cost = [0.0]
total_path = [[]]
alpha = 8.0
lambda_ = 0.5
epsilon = 1.0 + (alpha*lambda_)/(1.0-lambda_)
def g_neighbors(v):
(x,y) = v
ns = []
for dx in (-1,0,1):
for dy in (-1,0,1):
if dx == dy == 0:
... |
""" Training script for CIFAR-10/100.
Reference:
https://github.com/bearpaw/pytorch-classification/blob/master/cifar.py
https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
from __future__ import print_function
import argparse
import os
import shutil
import time
import random
import c... |
# MegFlow is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2019-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KI... |
from bluepy.btle import DefaultDelegate, Peripheral, Scanner
import atexit
import sys
import warnings
import datetime
from bitstring import BitArray
import numpy as np
# TODO: Add aux data
# TODO: Reconnecting when dropped
SAMPLE_RATE = 200.0 # Hz
# service for communication, as per docs
BLE_SERVICE = "fe84"
# cha... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import os
import cv2
import torch
import numpy as np
from glob import glob
from tqdm import tqdm
from multiprocessing import Pool
from pysot.core.conf... |
# -*- coding: utf-8 -*-
import numpy as np
from pyfr.backends.base.generator import (BaseKernelGenerator,
BaseFunctionGenerator, funcsig)
from pyfr.util import ndrange
class CUDAKernelGenerator(BaseKernelGenerator):
_xidx, _yidx = '_x', '_y'
_xdim, _ydim = '_nx', '_... |
#!/usr/bin/env python3
# -*- coding: utf-8-*-
import sys
from datetime import datetime, timedelta
from collections import OrderedDict
""" Log Parser for Kart races """
class Pilot:
nowPrefix="2019-01-01" # this prefix will be fixed since class is declared
_all_pilots = {} # we need to track our instances. ... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Update the events database"""
import os
import re
import argparse
import time
import numpy as np
import pyyaks.logger
from Chandra.Time import DateTime
from ska_helpers.run_info import log_run_info
from kadi import __version__ # noqa
logger = None ... |
import numpy as np
import torch
PI = 3.14159
def encode_label(K, ry, dims, locs):
l, h, w = dims[0], dims[1], dims[2]
x, y, z = locs[0], locs[1], locs[2]
x_corners = [0, l, l, l, l, 0, 0, 0]
y_corners = [0, 0, h, h, 0, 0, h, h]
z_corners = [0, 0, 0, w, w, w, w, 0]
x_corners += - np.float32... |
"""Support for Ecobee binary sensors."""
from __future__ import annotations
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_OCCUPANCY,
# DEVICE_CLASS_DRYCONTACT,
DEVICE_CLASS_WINDOW,
BinarySensorEntity,
)
from homeassistant.helpers.entity import DeviceInfo
from .const import (
DO... |
# =================================================================
#
# Author: <NAME> <<EMAIL>>,
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# Copyright (c) 2020 <NAME>
# Copyright (c) 2020 <NAME>
# Copyright (c) 2022 <NAME>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy... |
import json
import os
import socket
import time
from typing import List
from typing import Tuple
import a_sync
import mock
import yaml
from behave import given
from behave import then
from behave import when
from itest_utils import clear_mesos_tools_cache
from requests import HTTPError
from paasta_tools import drain_... |
import unittest
from pymap.parsing import Params
from pymap.parsing.exceptions import NotParseable
from pymap.parsing.primitives import Nil, Number, Atom, String, QuotedString, \
LiteralString, List
from pymap.parsing.state import ParsingState, ParsingInterrupt, \
ExpectContinuation
class TestNil(unittest.T... |
import json
import numpy as np
from tools.mpii_coco_h36m import coco_h36m
import os
h36m_coco_order = [9, 11, 14, 12, 15, 13, 16, 4, 1, 5, 2, 6, 3]
coco_order = [0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
num_person = 2
num_joints = 17
img_3d = 100.
ratio_2d_3d = 500.
def load_json(file_path):
with open(file... |
from math import pi, radians, sin, cos, asin
import cadquery
import cqparts
from cqparts.params import *
from cqparts import constraint
from cqparts.constraint import Mate
from cqparts.utils import CoordSystem
from . import register
class _Ring(cqparts.Part):
# Basic shape
outer_radius = PositiveFloat(10,... |
# -*- coding: utf-8 -*-
"""
Utilities for generating static image and line plots of near-publishable quality
Created on Thu May 05 13:29:12 2016
@author: <NAME>, <NAME>
"""
from __future__ import division, print_function, absolute_import, unicode_literals
import os
import sys
from numbers import Number
import numpy a... |
#########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... |
# ********************************************************************************** #
# #
# Project: FastClassAI workbecnch #
# ... |
from __future__ import annotations
from array import array
from typing import (Any, List, TypeVar, Generic, Callable)
from ..fable_modules.fable_library.array import (take, append, concat as concat_1, last, head, skip)
from ..fable_modules.fable_library.list import (empty as empty_1, cons, FSharpList, is_empty, tai... |
# -*- coding: utf-8 -*-
# python std lib
import os
import sys
import json
# rediscluster imports
from rediscluster import RedisCluster
# 3rd party imports
import pytest
from distutils.version import StrictVersion
from mock import Mock
from redis import Redis
from redis.exceptions import ResponseError
# put our path... |
# import the necessary packages
from collections import OrderedDict
import subprocess
import numpy as np
import cv2
import os
# For dlib’s 68-point facial landmark detector:
FACIAL_LANDMARKS_68_IDXS = OrderedDict([
("mouth", (48, 68)),
("inner_mouth", (60, 68)),
("right_eyebrow", (17, 22)),
("left_eyebrow", (22, ... |
import mimetypes
from email import encoders, message_from_bytes
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
from smtplib import SMTP, SMTP_SSL, SMTPServerDisconnected
import m... |
"""
The Serial interface is a wrapper for the pyserial library.
"""
import labtronyx
import time
import os
import errno
import serial
import serial.tools.list_ports
from serial.serialutil import SerialException
class i_Serial(labtronyx.InterfaceBase):
"""
Serial Interface
Wraps PySerial.
"""
au... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models.fields import Field
from django.core import exceptions
from django.utils.functional import cached_property
from django.utils.text import capfirst
from collectionfield.converter import CollectionConverter
from collectionfield.valida... |
#!/usr/bin/env python3
# Copyright 2020 <NAME>
#
# 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 agree... |
from os import path
from sys import exit, version_info
from PIL import Image, ImageDraw, ImageFont
try:
from smbus import SMBus
except ImportError:
if version_info[0] < 3:
exit("This library requires python-smbus\nInstall with: sudo "
"apt-get install python-smbus")
elif version_info[... |
# @file model.py
# @brief the sample file that copied for new python file
# README: Simulation core related
# MODULE_ARCH:
# CLASS_ARCH:
# GLOBAL USAGE:
#standard
import logging
import random
import math
from datetime import datetime,timedelta
#extend
#library
import lib.globalclasses as gc
from lib.const import *
f... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import print_function
from __future__ import absolute_import
import sys
import traceback
import operator
import asyncio
import html
from operator import itemgetter
from functools import wraps as _wraps
from functools import partial
from six import string_types
impo... |
import pkg_resources
class Graph(dict):
"""A graph of egg dependencies.
The nodes of the graph represent distributions (sometimes informally
called 'packages' or 'eggs'). The edges represent dependencies.
After creating a graph you need to populate it. To collect information
about all installed ... |
"""
Holds all the configurations of the environmental variables for the whole project
"""
import os
import pickle
import yaml
from os import path, makedirs
from pprint import pprint
from collections import defaultdict
from bioflow.configs.configs_manager import compute_full_paths
from bioflow.configs.bioflow_home impo... |
#!/usr/bin/env python
'''
Seed_match.py:
Check seed matching between miRNA and TargetRNA
<Rules>
WC => Watson-Crick match
GU => G:U Wobble
-------------------------------
seed_length = 8
-------------------------------
8mer: p1-p8 WC match
8mer-1A: p1=A, p2-p8 WC match
7mer-m8: p2-p8 WC match
7mer-m1: p1... |
# -*- coding: utf-8 -*-
__author__ = 'Kay'
import datetime
import json
import os
import re
from math import log
# import linecache
import arrow
import numpy as np
import pandas as pd
'''
提取微博用户特征
'''
def str2datetime(s):
'''
字符串转datetime类
'''
return arrow.get(s)
def load_user_data(in_name):
'... |
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2011, <NAME> <<EMAIL>>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# License: MIT. See COPYING.MIT file in the milk distribution
'''
================
Tree Classifier
================
Decision tree based classifier
------------------------------
'''
from __future__... |
"""Request is the main business class that is the real top level object in the system
"""
from app import db
from app.exceptions import BusinessException
from sqlalchemy import Sequence
from marshmallow import Schema, fields, post_load
from datetime import datetime
import logging
# create sequence if not exists nr_seq... |
from collections import OrderedDict
import os
from mlcomp.contrib.search.grid import grid_cells
from mlcomp.db.core import Session
from mlcomp.db.enums import TaskType, DagType
from mlcomp.db.models import Report, Task, Dag, ReportTasks
from mlcomp.db.providers import TaskProvider, \
ReportProvider, \
ReportTa... |
# Copyright 2015 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... |
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import backref
#from flask import Flask
#db = SQLAlchemy
db = SQLAlchemy()
class Security(db.Model):
__tablename__ = 'securities'
id = db.Column(db.Integer,db.Sequence('securities_id_seq'),primary_key=True)
symbol = db.Colu... |
#!/usr/bin/python3
import sys
import unittest
import os
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(1, os.path.abspath(
os.path.join(script_dir, os.path.join('..', '..'))))
import pake
# Force the test to occur in the correct place
os.chdir(script_dir)
pk = pake.... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import unicode_literals
import logging
import multiprocessing
import os
import pymake.parser
import sys... |
# pylint: disable=protected-access,no-self-use
from datetime import datetime
from typing import List
from unittest import TestCase
from unittest.mock import MagicMock, PropertyMock, Mock
import pywikibot
from testfixtures import compare
from service.ws_re.scanner.tasks.wikidata.claims.claim_factory import ClaimFactor... |
# -*- coding: utf-8 -*-
import importlib
import logging
import os
import re
from datetime import datetime, timedelta
from django.conf import settings
from django.db import DatabaseError
from celery import chain, chord, group
from jobs.models import Job
from tasks.models import ExportRun, ExportTask
from .export_tas... |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
# Copyright © 2020 <NAME>
###############################################################################
# Imports
###############################################################################
from builtins import str
from collections import namedtuple
from ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Auxiliary(nn.Module):
def __init__(self, input_channels, n_classes):
super(Auxiliary, self).__init__()
self.Conv2 = nn.Conv2d(input_channels, 128, kernel_size=1)
self.FC1 = nn.Linear(2048, 1024)
self.FC2 = nn.... |
#!/usr/bin/env python
# coding: utf-8
"""
2020-09-16 MY
env: myGIS
From Sentinel-2 mosaics to analysis ready data with rasterstats. Indeces 'NDMI', 'NDTI' and 'NDVI'.
INPUTS:
/Users/myliheik/Documents/GISdata/satotutkimus/shpfiles
/Users/myliheik/Documents/GISdata/sentinel2/fromPTA/AOI2/mosaics/
binsize
OUTPUT:
tra... |
# PREPARE A CSV-FILE TO ENABLE AN STACKED PLOT FOR POSITIVE TESTS, HOSPITALIZATIONS AND DECEASED
# Hospitalizations and deceased are not lagged in time, the date of the result of the "desease onset", positieve test or notification is leading
# https://data.rivm.nl/geonetwork/srv/dut/catalog.search#/metadata/2c4357c8-76... |
# Copyright 2021 The HuggingFace Team. 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 required by app... |
# -*- coding: utf-8 -*-
"""
Pyramid views for Eucalyptus and AWS Roles
"""
from datetime import datetime
from dateutil import parser
import simplejson as json
from urllib import urlencode
from boto.exception import BotoServerError
from pyramid.httpexceptions import HTTPFound, HTTPNotFound
from pyramid.i18n import Tra... |
import socket
import struct
import netifaces
from HelperFuncs import ProtocolTypes, bytesToMac, bytesToIpv4, ProtocolTypesIP, bytesToIpv6
from Dns import DNS, DNSQR, DNSRR, QTYPES
from Ethernet import Ether
from Icmp import ICMP
from Ipv6 import IPv6
from Raw import Raw
from Arp import ARP
from Udp import UDP
from Tc... |
"""Portfolio View"""
__docformat__ = "numpy"
from typing import List
from datetime import datetime
from io import BytesIO
from os import path
import pandas as pd
from tabulate import tabulate
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
fro... |
#!/usr/bin/python3
#
# Copyright (C) 2013 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main script for running few shot training
Eg.
python ./Main.py --root_path ~/Data/NLP/few_shot_nlg/ --domain humans --gpt_model_name ../models/117M/ --output_path ~/Output/
"""
from SeqUnit import *
from DataLoader import DataLoader, Preprocessor
import model as model_g... |
#!/usr/bin/env python3
# Copyright 2021 <NAME>. 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 required by a... |
import math
import numpy as np
def is_in_voxel_bound(posx, posy):
is_in_bound = False
is_in_bound = posx > -0.125 and posx < 0.125 and posy > -0.25 and posy < -0.025
return is_in_bound
def get_voxel_len(voxel_type, twod_sep):
if voxel_type == '2d':
sep_x, sep_y = 0, 0
sep_x = 0.25 / t... |
import re
import sqlite3
import subprocess
import shutil
import os
import codecs
import datetime
import sys
class TskDbDiff(object):
"""Represents the differences between the gold and output databases.
Contains methods to compare two databases.
Attributes:
gold_artifacts:
autopsy_artifact... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import logging
import argparse
import numpy as np
# paddle
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle.io import DataLoader, BatchSampler, DistributedBatchSampler
from paddlenlp.transformers.bert.tokenizer impor... |
#!/usr/bin/python
# (c) Copyright 2015 Hewlett Packard Enterprise Development LP
# 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.