text stringlengths 3.07k 12.6k |
|---|
from django import forms
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpResponseNotFound
from django.urls import reverse
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.db.models impo... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import cv2
from keras.models import load_model
# In[2]:
framewidth = 640
frameheight = 480
brightness =100
threshold = 0.90
font = cv2.FONT_HERSHEY_SIMPLEX
# # setup the camers
# In[3]:
vid = cv2.VideoCapture(0)
if not vid.isOpened():
vid... |
# -*- coding: utf-8 -*-
"""
Created on 17-7-25
@author: hy_qiu
"""
import csv
import json
import multiprocessing.dummy as mt
import os
import re
import requests
from bs4 import BeautifulSoup
from util.wraps import retry
import src.util.mt
logger = util.loginit.get_logger()
sess = requests.session... |
from typing import Tuple, Union
from omnibus.log.logger import get_logger
from app.event_manager import error_handler, event_handler, leave_room, publish_event
from app.event_models import Error
from app.exception_handlers import handle_error
from app.game_state.game_state_exceptions import GameStateNotFound
from app... |
import os
import cv2
import json
class StarData():
def __init__(self, name="", content=[]):
self.name = name
self.content = content
def read_star(path):
coordinates = []
with open(path) as f:
x_index, y_index = 0, 0
while True:
line = f.readline()
... |
import sys
import petsc4py
petsc4py.init(sys.argv)
import numpy as np
from petsc4py import PETSc
from src import stokes_flow as sf
from src.myio import *
from src.geo import *
from src.objComposite import *
from matplotlib import pyplot as plt
def get_problem_kwargs(**main_kwargs):
problem_kwargs = get_solver_k... |
"""This module is responsible for finding contamination in assembled genomes
"""
# import pprint
# from Bio.Seq import Seq
import io
import sys
import subprocess
import re
from Bio import SeqIO
import argparse
import remoVecSec.removeUtils as rU
import pprint
from functools import reduce
def runContaminantPipe(genome... |
#!/usr/bin/env python3
''' routines to read/write the metadb '''
import copy
import logging
import os
import pathlib
import sys
import multiprocessing
import sqlite3
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from PySide2.QtCore import QStandardPaths ... |
from __future__ import annotations
from collections import namedtuple
import pathlib
import socket
from typing import Callable
from django.conf import settings
from django.contrib.admin.utils import NestedObjects
from django.db import router
from django.db import transaction
from django.db.models import (
Express... |
"""
Solution for day 20/12/2020
Created at 08:42:20 - 20/12/20
"""
import sys
sys.path.append("../aoc")
import math
from itertools import product
import numpy as np
from aoc import challenge_runner
from aoc.parser import get_lines
def solution1(inp):
"""Solves the first part of the challenge"""
inp = inp.s... |
#from workflow_automation import example
'''
Source:
- https://packaging.python.org/en/latest/tutorials/packaging-projects/
'''
# TO DO: --build option
import argparse
import shutil
import subprocess
from pathlib import Path
from typing import Optional
def main():
parser = argparse.ArgumentParser(descripti... |
import tensorflow as tf
class ResidualLayer(tf.keras.layers.Layer):
def __init__(self, channels):
super(ResidualLayer, self).__init__()
self.conv1 = tf.keras.layers.Conv2D(filters=channels, kernel_size=3, padding='same')
self.batch1 = tf.keras.layers.BatchNormalization()
self.conv2 ... |
from typing import List, cast, Dict
import numpy as np
from py_headless_daw.dto.waveform import Waveform
from py_headless_daw.project.content.audio_clip import AudioClip
from py_headless_daw.schema.clip_track_processing_strategy import ClipTrackProcessingStrategy
from py_headless_daw.schema.dto.time_interval import T... |
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler as SS
def create_new_features(df):
"""
Creates features for price differences:
high-low
close-open
"""
df['close-open'] = df['Adj_Close'] - df['Adj_Open']
df['high-low'] = df['Adj_High'] - df['Adj_Low']... |
import abc
import collections
from eth_utils import (
to_tuple,
)
from rlp.exceptions import (
ListSerializationError,
ObjectSerializationError,
ListDeserializationError,
ObjectDeserializationError,
)
from .lists import (
List,
)
class MetaBase:
fields = None
field_names = None
... |
import os
import json
import numpy as np
import matplotlib.pyplot as plt
def compute_iou(box_1, box_2):
'''
This function takes a pair of bounding boxes and returns intersection-over-
union (IoU) of two bounding boxes.
'''
inter = [0,0,0,0]
if box_1[0] >= box_2[0]:
inter[0] = box_2[0]
... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
import torch.nn.functional as F
from fairseq import utils
from . import FairseqCriterion, register_criterion
# c... |
import sys
if sys.version_info >= (3, 8):
from unittest.mock import AsyncMock
else:
from asynctest.mock import CoroutineMock as AsyncMock
from unittest.mock import Mock, call, sentinel
import pytest
from multidict import MultiDict
from jj.matchers import AttributeMatcher, ParamMatcher, RequestMatcher
from j... |
import functools
import logging
import pyproj
import yaml
from shapely.geometry import mapping, shape, Polygon, MultiPolygon
from shapely.ops import transform
from . import constants
from . import nominatim
from . import overpass
logger = logging.getLogger(__name__)
LOCAL_COORDINATES = pyproj.Proj(init=constants.... |
#!/usr/bin/env python3.6
# print("Jedi")
from locker import Passwords
from user import User
import random
"""
Users Details
"""
def create_user(fname, lname, password):
"""
Function to create a new user_list
"""
new_user = User(fname, lname, password)
return new_user
# Save users
def save_user... |
# -*- coding: utf-8 -*-
# main converter file, converts datasheet to Lektor format
import glob
import os
import json
import re
import datasheetparser
import htmlparser
import referenceparser
import symbolreplace
import flow
import alphaindexparser
import categories
countries = []
def get_countries():
countries_... |
from __future__ import absolute_import, division, print_function
from functools import partial
import hydra
import torch
from easydict import EasyDict as edict
from omegaconf import DictConfig, OmegaConf
from torch.utils.data import DataLoader
import kvt
import kvt.augmentation
from kvt.registry import (
DATASET... |
import os
import pygame
def load_image(filename):
image = os.path.join("assets", "images", filename)
if filename.endswith('.jpg'):
surface = pygame.image.load(image).convert()
else:
surface = pygame.image.load(image).convert_alpha()
return surface
class FILES(object):
score = os.... |
#!/usr/bin/python
# Copyright (c) 2016 <NAME>
# 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, publi... |
from bson import ObjectId
from .wrappers import MongoCollection
from .document import Document, DocumentSet
from .fields import BaseField
from ..errors import MissingFieldsException, CollectionException
class CollectionFields(list):
__data = dict()
def __init__(self, **kwargs):
super().__init__()
... |
# -*- coding: utf-8 -*-
# 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 annotations
import json
from datetime import datetime
from typing impo... |
# ====================================
# > Messaging and reporting utilities
# =================================
import textwrap
from collections import Counter
from datetime import datetime
from typing import Sequence, Tuple, cast
import rich
from rich.panel import Panel
from rich.progress import BarColumn, Progress... |
### This script is the testing file for regression DNN.
### Implementation assumptions in test_dnn:
## netType=1 (CNN), nRep=1, nClass=2, loss function = mse
## fThreeCameras=False, fClassifier=False
import sys
import os
ROOT_DIR = os.path.abspath("../")
print('PLATFORM_ROOT_DIR ', ROOT_DIR)
sys.path.insert... |
import numpy as np
import torch
import torch.nn as nn
from torch.distributions import Normal
import random
class DDPGDist():
def __init__(self, actions):
self.actions = actions
def log_prob(self, actions):
return torch.ones(actions.shape)
def sample(self):
return self.actions
class... |
import datetime
import vobject
from django import http
from django.shortcuts import get_object_or_404, render
from django.utils.timezone import utc
from django.utils import timezone
from django.core.cache import cache
from django.conf import settings
from django.db.models import Q
from django.core.urlresolvers import... |
import pandas as pd
import threading
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import argparse
import re
import os
import time
import random
import logging
'''
获取html原网页文本
参数:url,即要打开的网页链接
返回值:为html网页文本
'''
class Spider:
def __init__(self):
self.headers = {'user-agent': ... |
"""
Google API Client Library Page
https://developers.google.com/api-client-library/python/reference/pydoc
Python Quick Start Page
https://developers.google.com/drive/v3/web/quickstart/python
"""
import json
from os import path, makedirs
from warnings import warn, simplefilter, catch_warnings
import httplib2
from oau... |
import h5py
import numpy as np
import torch
from collections import defaultdict, namedtuple, Mapping
from glob import glob
from torch.utils.data import Dataset
import os
class Invertible:
def inv(self, y):
raise NotImplemented('Subclasses of Invertible must implement an inv method')
class DataTransform:
... |
import pymysql
import pandas as pd
# from sqlalchemy import create_engine
def boxing_money_year(engine):
# engine = create_engine('mysql+pymysql://root:hitse2018@172.16.17.32:3306/se')
sql = '''select boxing,year from boxing_month WHERE year in (2015,2016,2017,2018);'''
df = pd.read_sql_query(sql, engine)... |
import os
import json
import webbrowser
import SocketServer
import SimpleHTTPServer
from fabric.api import task
from fabric.api import execute
from fabric.api import local, lcd
from fabric.context_managers import settings
from fabric.context_managers import hide
from fabric.colors import red, green, yellow
os.envi... |
'''
uwsgi服务器脚本文件
'''
import json
import sys
from urllib import parse
import mysql.connector as connector
host = '127.0.0.1'
user = 'sjf'
passwd = '<PASSWORD>'
port = 3306
dbName = 'reader_hp'
dictTableName = 'wordDict'
wordRecTableName = "wordRecord"
sentenceRecTableName = "sentenceRecord"
debug = False
conn = No... |
import functools
import os
import sys
import click
import re
import logging
import mkdocs
from git import Git
from git import Repo
from mkdocs.commands import build
from mkdocs import config
# log = logging.getLogger('mkdocs.cli')
log = logging.getLogger(__name__)
config_file_help = "Provide a specific MkDocs config... |
import numpy as np
from machineLearningLibrary.activationFunctions import Sigmoid, Tanh
from machineLearningLibrary.costFunctions import LogCost
def initParams(n_x, n_h, n_y):
"""
Initialises the parameters of the NN based on the number of input,
output and hidden layers.
Params:
n_x - s... |
from hypothesis import given, example, note, assume, settings, HealthCheck
from hypothesis.strategies import (sampled_from, integers, booleans,
composite, data)
from unified_range import api
N = 20
# range was 0-19 but versions in ranges could be 20 which lead to value error
VERSION... |
# -*- coding:UTF-8 -*-
# Copyright (c) 2020 PaddlePaddle Authors. 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
#
# ... |
from decimal import Decimal
import json
import pytest
from django.core.exceptions import ImproperlyConfigured
from django.core.management import call_command
from . import app_parameter
from .models import Parameter
from .context_processors import add_global_parameter_context
@pytest.fixture
def params(db):
par... |
"""Defines tools in general dimension d=d."""
import numpy as np
from multipartite.tools import constants as const
## useful operations
def dag(A):
return 1.*np.conjugate(np.transpose(A))
def eigh(A):
vals, vecs = np.linalg.eigh(A)
vecs = np.transpose(vecs) ## so vecs[0] is an eigenvector
return 1.*vals, 1... |
import argparse
import sys
import re
import json
import requests
from models import auth
import pdb
import pprint
def create(config, args):
pp = pprint.PrettyPrinter()
url = config['url'] + "/api/session/"
data = {
"name": args['name'],
"description": args['description'],
"upstreamHo... |
import base64
import contextlib
import enum
import hashlib
import json
import re
from typing import Dict, List, Type
import attr
from pytuber.exceptions import NotFound
from pytuber.storage import Registry
from pytuber.utils import timestamp
class StrEnum(enum.Enum):
def __str__(self):
return self.value... |
#!/usr/bin/env python
import json
import random
import common.dff.integration.context as int_ctx
from datetime import datetime
from df_engine.core import Actor, Context
INTENT_RESPONSES_PATH = "scenario/data/intent_response_phrases.json"
with open(INTENT_RESPONSES_PATH, "r") as fp:
RESPONSES = json.load(fp)
d... |
# -*- coding: utf-8 -*-
'''
Created on Wed May 29 14:21:54 2019 by <NAME> - <EMAIL>
Calculates IoU scores of dataset per individual batch.
Arguments:
- labelNames: list of class names
- validClasses: list of valid class ids
- voidClass: class id of void class (class ignored for calculating metrics)... |
from typing import List, Optional
from datetime import datetime
from pydantic import BaseModel
from shopipy.resources.fulfillment.schemas import Fulfillments # type: ignore
from shopipy.resources.transactions.schemas import Transactions # type: ignore
from shopipy.resources.customers.schemas import Address, CustomerSho... |
from rank_bm25 import BM25L
from rank_bm25 import BM25Plus
from rank_bm25 import BM25Okapi
import os
import string
import json
import requests
import pandas as pd
import numpy as np
import nltk
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
from nltk.tokenize import word_tokenize
from nlt... |
import os
from datetime import datetime as dt
try:
with open('debug.log', 'r') as debugfile:
pass
except FileNotFoundError:
with open('debug.log', 'x') as debugfile:
debugfile.write(f'\n[{dt.now()}] debug.log file not found, creating in default directory.')
import time
VERSION = '1.1.2'
pr... |
from __future__ import unicode_literals
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.views.generic import ListView, UpdateView
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from django.shortcuts import get_object_or_404
from djan... |
class BoardError(StandardError):
pass
class tile:
"""This is the tile class.
tileType is a string designating the tile type.
health is how much health this tile is given
wallValues is a length 6 list designating
the type of walls around the tile.
This is the inde... |
"""
Newlove extension for clans.
Supports filtering for new planlove and ordering planlove by time.
"""
import json
from datetime import datetime
import os.path
import sys
import io
from clans.util import json_output, ISO8601_UTC_FMT
if sys.version_info < (3,):
str = unicode
# extension globals
lovelog = None... |
#------------------------------------------------------------------------------
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#------------------------------------------------------------------------------
import sys
from .qt.QtCore import Qt, Signal
from .qt.QtGui import QMainWindow
from .q_deferred_... |
# -*- coding: utf-8 -*-
"""
Created on January 23 2021
@author: <NAME>
"""
import unittest
import numpy as np
import ase
import ase.build
import sys
sys.path.insert(0, "../")
import pyTEMlib.graph_tools as graph
from pyTEMlib import crystal_tools
class TestUtilityFunctions(unittest.TestCase):
def test_circum_ce... |
#! /usr/bin/env python
import glob
import subprocess
import warnings
import time
import sys
import os
import numpy as np
from sklearn.exceptions import UndefinedMetricWarning
from sklearn.model_selection import cross_validate
from sklearn.svm import SVC
from sklearn.externals import joblib
from sklearn.decomposition ... |
import datetime
import re
import time
import networkx as nx
import pandas as pd
from settings import usersettings as settings
from utils.filehandling import read_file_in_dataframe
from settings import applicationsettings as glob
def getsubgraph(layerview, filternode=None, filtervalue=None):
"""
@param layervi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from random import randint
from django.db import models
class Strategy(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return "{}".format(
self.name
)
class Exchange(models.Model):
... |
import logging
from service import table_reader_service
from service.alma import alma_primo_service, alma_bib_service, alma_sru_service, alma_electronic_service
from service.table_reader_service import read_table, write_table
from utils import list_to_string
def collect_number_of_entries(project, table):
"""
... |
import os
import pickle
import zipfile
import torch
import torch.nn as nn
import torch.optim as optim
from .tensornet.data.dataset import Dataset
from .tensornet.models import mobilenet_v2, resnet_34
from .tensornet.models.optimizer import sgd
from .tensornet.data.cleaning import clean_data, split_data
from .tensorne... |
from ase.io import read, write
import numpy as np
import os
from copy import deepcopy
import pkg_resources
import json
from scipy.special import sph_harm
import warnings
database_path = 'tmp/database_Cu_761/'
#reference energy: adsorbate + clean surface
#adsorbate will be calculated by the numbers of atomic numer in At... |
from glob import glob
import pandas as pd
import sys
import ntpath
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from nltk.tokenize import RegexpTokenizer
from skimage.transform import resize
import os
import errno
checkpoint = '2018_10_23_14_55_12'
gen_dir = '../data/coco/gen_masks_%s/*'%... |
# Copyright 2014 Huawei Technologies Co. Ltd
#
# 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... |
#%%
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import matplotlib.cm as cm
from tqdm import trange, tqdm
from sklearn.metrics import adjusted_rand_score, f1_score
from argparse import ArgumentParser
from util.config_parser import ConfigParser... |
from torch import nn
import torch
import torch.nn.functional as F
# +
from torch import nn
from collections import OrderedDict
class Bottleneck(nn.Module):
def __init__(self,in_channel,out_channel,expansion,activation,stride=1,padding = 1):
super(Bottleneck, self).__init__()
self.stride=stride
... |
#
# General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall
# model for 1st, 2nd and 3rd generation solar cells.
# Copyright (C) 2008-2022 <NAME> r.c.i.mackenzie at googlemail.com
#
# https://www.gpvdm.com
#
# This program is free software; you can redistribute it and/or m... |
import numpy as np
def get_kaiserWindow(kHW):
kaiserWindow = np.zeros(kHW * kHW)
if kHW == 8:
kaiserWindow[0 + kHW * 0] = 0.1924
kaiserWindow[0 + kHW * 1] = 0.2989
kaiserWindow[0 + kHW * 2] = 0.3846
kaiserWindow[0 + kHW * 3] = 0.4325
kaiserWindow[1 + kHW * 0] = 0.2989
... |
#!/usr/bin/env python
"""
Classes for fiducial layout, intensity calculation and adding to an image.
"""
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
import shapely
import shapely.geometry
import shapely.ops
import mersim.base as base
import mersim.util as util
class FiducialImage(b... |
# -*- coding: utf-8 -*-
"""flake8chart: flake8 stats visualised
"""
import sys
import string
import itertools
import time
import pprint
import csv
try:
import click
import pygal
except ImportError as e:
print("error: {0}".format(e))
sys.exit(1)
if sys.version_info[0] == 3:
import functools
re... |
# xlcrypto_py/src/xlcrypto/hello_and_reply.py
"""
Implementation of the hello-and-reply protocol.
This allows a client to establish a secure conntection to a server
whose RSA public key the client knows.
"""
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
f... |
from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
import pytest
import pdb
from astropy import units as u
from astropy import constants as const
from linetools.spectralline import AbsLine
from linetools.analysis import voigt as lav
c_kms = const.c.to('km/s').value... |
# -*- mode:python; coding:utf-8; -*-
# A SCons tool to enable compilation of Haskell in SCons.
#
# Copyright © 2009, 2017 <NAME>
#
# 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 ... |
import logging
import re
from contextlib import suppress
from datetime import timedelta, datetime, timezone
from pathlib import Path
from tempfile import NamedTemporaryFile
from time import monotonic, sleep
from typing import Callable, Optional, List, cast, ClassVar, Pattern, Tuple, IO
from urllib.parse import urljoin
... |
import timm
import torch
import torch.nn.functional as F
from detectron2.layers import NaiveSyncBatchNorm, ShapeSpec
from detectron2.modeling import Backbone
from torch import nn
__all__ = ["BiFPN"]
class DepthwiseSeparableConv2d(nn.Sequential):
def __init__(
self,
in_channels,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
import platform
import signal
import time
import urllib.error
import urllib.parse
import urllib.request
from discord_webhook import DiscordWebhook, DiscordEmbed
from lxml import html
from pypeul import *
DISCORD_WH = "https://discordapp.com/api/webh... |
"""
Script to get word embeddings for Spike gene sequences
1. Read, Combine country CSVs
2. Filter spike protein
3. Load model; Get embeddings
4. Correct 0 indexing
5. Merge with full data df
"""
from datetime import datetime
import glob
import argparse
import numpy as np
import pandas as pd
from g... |
# -*- coding: utf-8 -*-
"""Functions for updating the search index."""
from __future__ import unicode_literals
from collections import namedtuple
import itertools
import logging
from memex._compat import xrange
import elasticsearch
from elasticsearch import helpers as es_helpers
from sqlalchemy.orm import subqueryloa... |
# import the necessary packages
from collections import deque
from imutils.video import VideoStream
import numpy as np
import argparse
import cv2
import imutils
import pandas as pd
import tkinter as tk
ap = argparse.ArgumentParser()
args = vars(ap.parse_args())
# Define the lower and upper boundaries of the "White" b... |
#!/usr/bin/env/python3
# -*- coding: UTF-8 -*-
""" Python based modular magic mirror application,
design your own modules or use the included ones!
Program and included modules are licensed under the
MIT license and are © <NAME> (2016). This
excludes existing third party libraries, other third
par... |
import pytest
from numpy import array, asarray, block, inf, nan, ones
from numpy.linalg import inv, pinv, svd
from numpy.testing import assert_allclose
from numpy_sugar.linalg import ddot
from glimix_core._util import check_covariates, check_economic_qs, check_outcome, hinv
from glimix_core._util.solve import heigvals... |
import os,re,glob
import numpy as np
from collections import defaultdict
import subprocess
import pandas as pd
RNA_dict = {'SRR3184279':'Pt1','SRR3184280':'Pt2','SRR3184281':'Pt4','SRR3184282':'Pt5','SRR3184283':'Pt6',
'SRR3184284': 'Pt7','SRR3184285':'Pt8','SRR3184286':'Pt9','SRR3184287':'Pt10','SRR318428... |
import copy
from collections import defaultdict
from inspect import isfunction
from typing import Any, Dict, Iterable, Tuple, Union
from uuid import uuid4
GenericAlias = type(Dict)
NoneType = type(None)
class SchemaMetaclass(type):
schemas = {}
@staticmethod
def _get_attr_from_bases(key, attrs, bases):
... |
import paginate
import requests
from bs4 import BeautifulSoup
from flask import request, url_for, render_template, jsonify, flash
from flask.views import MethodView
from flask_login import login_required
from paginate_sqlalchemy import SqlalchemyOrmWrapper
from sqlalchemy import desc
from nanumlectures.common import i... |
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Layer
from tensorflow.keras import Sequential
import tensorflow.keras.layers as nn
from einops import rearrange, repeat
from vit import ViT
from t2t import T2TViT
from efficient import ViT as EfficientViT
def exists(val):
... |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2020 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
""" Tools for working with EO3 metadata
"""
from types import SimpleNamespace
from affine import Affine
import toolz
from typing import Dict, An... |
'''
This script provides common functions used to help define optimal control
problems, as well as prototype classes to base new problems on.
'''
import numpy as np
from scipy.integrate import cumtrapz, solve_ivp
class config_prototype:
def __init__(self, N_states, t1, time_dependent):
'''Class defining p... |
# Copyright (c) 2021 The Toltec Contributors
# SPDX-License-Identifier: MIT
"""
Build the package repository.
"""
from datetime import datetime
import gzip
from enum import Enum, auto
import logging
import os
import textwrap
from typing import Dict, Iterable, List, Optional, Set
import requests
from .graphlib import T... |
#!/usr/bin/env python3
"""
RESOURCE MANAGEMENT - POLICIES MODULE
CIMI API calls
"""
__status__ = 'Production'
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__author__ = 'Universitat Politècnica de Catalunya'
from common.common import CPARAMS
from common.logs import LOG
import requests
import urllib3
urlli... |
import pytest
from ossify import grammar
from ossify.testutil import parse_string
# , parser_for
def check_raises(content):
with pytest.raises(SyntaxError) as e:
parse_string(content)
return str(e.value)
def test_empty_scope():
parse_string("a {}")
def test_leading_newline():
test_scope ... |
from collections import Set
import numpy as np
import random
from deap import creator
from .helperfunctions import validate
import sys
def arbitrary_matched_subgraph(ind1, ind2, toolbox):
c1 = create_arbitrary_matched_subgraph_offsprint(ind1, ind2, toolbox)
c2 = create_arbitrary_matched_subgraph_offsprint... |
#!/usr/bin/env python3
# +======================================================================+
# | |
# | File: matrix_multiply.py |
# | Author: <NAME> | N9763686 |
... |
# coding=UTF-8
# ex:ts=4:sw=4:et=on
# Copyright (c) 2013, <NAME>
# All rights reserved.
# Complete license can be found in the LICENSE file.
import logging
logger = logging.getLogger(__name__)
import re
from fractions import Fraction
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Gdk... |
import os
import numpy as np
from pathlib import Path
import json
from PIL import Image
def normalize(v):
'''
This function returns the normalized vector v
'''
norm = np.linalg.norm(v)
if norm ==0:
return v
return v/norm
def find_peaks(a, reach=10):
'''
This function returns ... |
# Copyright (c) 2021, 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... |
#!/usr/env python
import logging
import os
import sys
import subprocess
import codecs
_EXTERNAL_PROC_PARENT = None
_CONF_OBJ_DICT = {}
def get_conf(request):
global _CONF_OBJ_DICT
app_name = request.application
c = _CONF_OBJ_DICT.get(app_name)
if c is None:
from ConfigParser import SafeConfigPa... |
import collections
from util import *
import torch
import warnings
import copy
import random
import numpy as np
# [reference] https://github.com/matthiasplappert/keras-rl/blob/master/rl/memory.py
# This is to be understood as a transition: Given `current_state`, performing `ActionNoise`
# yields `reward` and results ... |
import re
from datetime import datetime, timedelta
import json
from flask import request, Response
from flask_restful import Resource, abort
from lxml import etree
from common import util
from common import objects
class Processes(Resource):
"""Lists processes (data update)."""
def get(self):
list_... |
from corehq.apps.accounting import generator
from corehq.apps.accounting.models import BillingAccount, DefaultProductPlan, SoftwarePlanEdition, Subscription
from corehq.apps.commtrack.models import CommtrackActionConfig
from corehq.apps.domain.models import Domain
from corehq.apps.locations.models import Location, SQLL... |
import os
import numpy as np
import pandas as pd
from argparse import ArgumentParser
from pprint import pprint
from tokenize import String
from typing import List, Dict
from utils.get_all_event import condition_option, get_all_events
from math import pi
from bokeh.io import show, output_file
from bokeh.models import C... |
import time
from typing import Optional, Union, Dict, Any, List
from algoliasearch.exceptions import AlgoliaUnreachableHostException, RequestException
from algoliasearch.http.hosts import Host
from algoliasearch.http.request_options import RequestOptions
from algoliasearch.configs import Config
from algoliasearch.http... |
import os
import tempfile
import unittest
from contextlib import closing
import mock
import numpy as np
import recordio
import tensorflow as tf
from elasticdl.proto import elasticdl_pb2
from elasticdl.python.common.constants import JobType
from elasticdl.python.master.embedding_service import EmbeddingService
from el... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.