text
stringlengths
3.07k
12.6k
import os import sys import glog as log import json import pkg_resources import tempfile import struct import base64 import traceback import avro.schema from avro.datafile import DataFileReader, DataFileWriter from avro.io import DatumReader, DatumWriter, BinaryDecoder, BinaryEncoder from confluent_kafka.avro.cached_s...
import argparse try: from . import treedata_pb2 as proto from . import utils except (ValueError, ImportError): import treedata_pb2 as proto import utils import represent_ast as ra class Node: def __init__(self, id, label, position): self.id = id self.label = labe...
''' Funktioniert zur Zeit nur für Module ohne Parameter ''' def readFile(filename): f = open(filename, "r") content = f.read() f.close() return content def writeFile(filename, content): f = open(filename, "w") f.write(content) f.close() return def removeComments(text): # Removes Comme...
import time from signal import signal, SIGSEGV from types import MethodType try: import mathsat from pysmt.solvers.msat import MathSAT5Solver except ImportError: class MathSAT5Solver: pass try: from pysmt.solvers.z3 import Z3Solver except ImportError: class Z3Solver: pass from pys...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore", category=RuntimeWarning) def sigmoid(z): return 1 / (1 + np.exp(-z)) def cost(trainY, g): return np.sum(np.multiply(trainY, np.log(g))+np.multiply((1-trainY), np.log(1-g)))/trainY.shape[0...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: lenovo @file: SetCoverage.py @time: 2021/4/26 13:24 """ import pulp import random import time import matplotlib.pyplot as plt ''' 集合覆盖问题: • 输入: 有限集 X, X 的子集合族 F, X=∪𝑆∈𝐹 S • 输出: C⊆F, 满足 (1)X=∪𝑆∈𝐶 S (2)C 是满足条件(1)的最小集族, 即|C|最小. ''' # 生成实验数据 class generate(...
import abc import logging import time import warnings from enum import Enum from typing import Any from dateutil.parser import parse from great_expectations.core import ExpectationSuite, RunIdentifier from great_expectations.exceptions import GreatExpectationsError from ..data_asset import DataAsset from ..dataset i...
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from wtforms.fields import IntegerField, SelectField from wtforms.validators import DataRequired, Length, ...
# -*- coding: utf-8 -*- import os from subprocess import PIPE, STDOUT from mock import Mock import pytest from tests.utils import CorrectedCommand, Rule from theplease import const from theplease.exceptions import EmptyCommand from theplease.system import Path from theplease.types import Command class TestCorrectedC...
""" Initialize the application and import all the blueprints. This file will initialize all of the global variables used within the rest of the application. Anything needed for the app context will be done within the `create_app` function and returned back to the caller handler. """ from flask import current_app as ap...
#!/usr/bin/env python import os import argparse def get_cmd(task, sub_task, model_tag, gpu, data_num, bs, lr, source_length, target_length, patience, epoch, warmup, gpu_type, res_fn): cmd_str = 'bash exp_with_args.sh %s %s %s %d %d %d %d %d %d %d %d %d %s %s' % \ (task, sub_task, model_...
from view.modes import NormalMode, EditMode import curses import logging log = logging.getLogger("wfcli") class LateralCursor: def __init__(self): self._index = float("-Inf") self.allowed_offset = 0 def align_cursor(self, current_node): if self._index != self.in_line(current_node): ...
import os import sys from types import SimpleNamespace import torch import pytest import deepspeed from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus from common import distributed_test def setup_serial_env(): # Setup for a serial run os.environ['MASTER_ADDR'] = '127.0.0.1' os.envi...
""" Extracting automatically articles from the EB. The articles are stored in a ES file. The text is cleaned by using long-S and hyphen fixes. """ from defoe import query_utils from defoe.nlsArticles.query_utils import clean_headers_page_as_string, get_articles_eb, filter_terms_page from pyspark.sql import Row, S...
""" Base classes for other test cases to inherit from. """ from contextlib import contextmanager from django.contrib.auth import get_user_model from django.core import mail from django.http import HttpRequest from django.test import TestCase, override_settings from ..forms import RegistrationForm from .. import sign...
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
import rosgraph import rosparam import rospkg import rospy import rosservice from re import compile BLACK_LIST_PARAM = ['/rosdistro', '/rosversion', '/run_id'] BLACK_LIST_TOPIC = ["/tf", "/tf_static", "/rosout", "/clock"] BLACK_LIST_SERV = ["/set_logger_level", "/get_loggers"] BLACK_LIST_NODE = ["/rosout"] ACTION_FI...
import csv import itertools import os import multiprocessing import sys import numpy.random from typing import Tuple from matplotlib import pyplot as plt from tqdm import tqdm from pandas import DataFrame from cvrp.aco_cvrp_solver import AntColonyCVRPSolver from cvrp.augerat_loader import load_augerat_example from cv...
from __future__ import division import os.path as osp import cameramodels import numpy as np import numpy.ma as ma import PIL import scipy.io import torch from dense_fusion.datasets.ycb.ycb_utils import get_data_list from dense_fusion.datasets.ycb.ycb_utils import get_ycb_video_dataset from dense_fusion.datasets.ycb...
from .network import Network import tensorflow as tf class VisualContext(Network): """Visual context feature fusion.""" def _interpolate(self, xy1, xy2, points2): batch_size = tf.shape(xy1)[0] ndataset1 = tf.shape(xy1)[1] eps = 1e-6 dist_mat = tf.matmul(xy1, xy2, transpose_b...
#!/usr/bin/python2.4 # # Copyright (C) 2009 Google Inc. # # 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 l...
# -*- coding: utf-8 -*- from web.controllers.api import route_api from flask import request,jsonify,g from common.models.food.FoodCat import FoodCat from common.models.food.Food import Food from common.models.member.MemberCart import MemberCart from common.models.member.MemberComments import MemberComments from common...
""" Server recebe novas conexoes de usuarios a qualquer momento. Tambem fica responsavel pela parte do processamento de listar os usuarios ativos """ from constants import CMD_CHAT, CMD_LIST_USERS, CMD_QUIT, SERVER_NAME, SERVER_PORT import sys import socket import threading import select as s from datetime import date...
# Author: <NAME> <<EMAIL>> # # License: BSD 3 clause import time import numpy as np import numba from sklearn.utils.validation import check_is_fitted import scipy.sparse @numba.njit(parallel=True) def fast_knn_indices(X, n_neighbors): """A fast computation of knn indices. Parameters ---------- X: a...
""" stepdown.py - Produce a step-down schedule from a list of children. Copyright (c) 2021 by <NAME>, J.D. """ from datetime import datetime from dateutil.relativedelta import relativedelta from decimal import Decimal STEPDOWN_MONTH = 6 # Assume children graduate high shcool in June STEPDOWN_DAY = 30 # Last day bef...
#!/usr/bin/env python3 import os import sys import glob import jinja2 import codecs import markdown from bin.jinja_setup import setup_jinja from bin.markdown_jinja import MarkdownJinja from frontend.digital_land_frontend.filters import organisation_mapper from frontmatter import Frontmatter docs = "docs/" def re...
# coding=utf-8 # # Copyright 2015-2016 F5 Networks Inc. # # 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 la...
# ------------------------------------- # Execute at Collection Time # ------------------------------------- # Gets jinja templates and fills them # with data from table_config.yaml, then # generate tests with different configs # ------------------------------------- import csv import json import os from pathlib impo...
#!/usr/bin/env python # -*- coding: utf-8 -*- """This module contains a lightweight ontology to represent a performance in a MIDI-like format. A performance is defined at the highest level by a :class:`~partitura.performance.PerformedPart`. This object contains performed notes as well as continuous control parameters,...
# Copyright The OpenTelemetry Authors # # 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 ...
import re import requests import os import csv # Fukcije url_to_text, zapisi_csv in zapisi_v_csv so pobrane z repozitorija od predmeta Programiranje 1. STEVILO_STRANI = 166 mapa = 'zajeti_podatki' linki = 'linki.txt' nepremicnine_txt = 'nepremicnine.txt' nepremicnine_csv = 'nepremicnine.csv' vzorec_linka = r'<meta it...
import asyncio import json import logging import multiprocessing import time import contextlib from django.apps import AppConfig from django.conf import settings import glob from hfc.fabric import Client from hfc.fabric.peer import Peer from hfc.fabric.user import create_user from hfc.util.keyvaluestore import File...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
""" Receive signals from a keyboard and use it as a remote control. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/keyboard_remote/ """ # pylint: disable=import-error import threading import logging import os import time import voluptuous as vol import...
import os import json from typing import Optional import torch import numpy as np from tqdm import tqdm from sklearn import metrics from persia.ctx import TrainCtx, eval_ctx from persia.distributed import DDPOption from persia.embedding.optim import Adagrad from persia.embedding.data import PersiaBatch from persia....
import argparse import calendar import collections import gzip import inspect import json import os import re import subprocess import time import dateutil.parser # import bryo.utils.s3util SOURCE_FILE_FILTER = re.compile('^/nail/srv/') class CollectorFormatter(object): """ Abstract class for output format...
# 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, software # distributed under the...
import os import tempfile import time from collections import defaultdict import pytest from dagster import ( DagsterEventType, Output, OutputDefinition, PipelineRun, RetryRequested, execute_pipeline, execute_pipeline_iterator, lambda_solid, pipeline, reconstructable, reexec...
# -*- coding: utf-8 -*- # pylint: disable=missing-docstring ############################################################################## # # Copyright (c) 2011, <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"...
import clip import torch from PIL import Image from multiprocessing import cpu_count device = "cuda" if torch.cuda.is_available() else "cpu" use_jit = torch.cuda.is_available() and '1.7.1' in torch.__version__ class CLIPDataset(torch.utils.data.Dataset): def __init__(self, dataframe, preprocess): self.dat...
# -*- coding: utf-8 -*- #!/usr/bin/env python # # Copyright 2017-2020 BigML # # 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 requi...
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from contextlib import contextmanager import importlib.util import logging import os import shlex import subprocess as sp i...
import bs4 import csv import requests import re import time from selenium import webdriver from selenium.webdriver.firefox.options import Options class Steam: def __init__(self, driver): """Declare values needed for the class. Args: driver (class): Firefox webdriver """ ...
import ast import node import os import json import TF_horovod import Torch_run import TF_kung_fu import keras_kung_fu import TF_horovod import keras_horovod import re import numpy as np class DECIError(Exception): pass class LibraryError(DECIError): """This Exception is raised when an invalid library is u...
from collections import OrderedDict from conans.model.conanfile_interface import ConanFileInterface from conans.model.ref import ConanFileReference class Requirement(object): def __init__(self, ref, build=False, direct=True, test=False, visible=True): # By default this is a generic library requirement ...
import pytest import math from timeit import timeit import time from astropy import units as u from pocs.filterwheel.simulator import FilterWheel as SimFilterWheel from pocs.camera.simulator import Camera as SimCamera from pocs.utils import error @pytest.fixture(scope='module') def filterwheel(): sim_filterwhee...
# Copyright (c) 2012-2016 Seafile Ltd. """ A set of request processors that return dictionaries to be merged into a template context. Each function takes the request object as its only parameter and returns a dictionary to add to the context. These are referenced from the setting TEMPLATE_CONTEXT_PROCESSORS and used b...
#!/usr/bin/env python3 import lmfit import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button import numpy as np class VarSlider: def __init__(self, ax, valname, valmin, valmax, valinit = None, valstep = None, callback = None): self.ax = ax self.valname = valname ...
""" Minimum Spanning Tree Clustering """ import numpy as np from scipy import sparse from sklearn.neighbors import kneighbors_graph from sklearn.mixture import GMM try: from scipy.sparse.csgraph import \ minimum_spanning_tree, connected_components except: raise ValueError("scipy v0.11 or greater requi...
import pygame as pyg from pygame.locals import * import random, time from spritesheet.Sprites import * clock = pyg.time.Clock() FPS = 60 pyg.init() screen = pyg.display.set_mode([800, 600], RESIZABLE) mouse = pyg.transform.scale(pyg.image.load('./res/mouse/mouse_0.png'), (16, 16)) seletor = pyg.transfo...
import io import json import os from json import load, dump, JSONDecodeError from ctpbee.center import PositionModel from ctpbee.constant import TradeData, PositionData, Direction, Offset, Exchange class SinglePositionModel: def __init__(self, local_symbol): self.local_symbol = local_symbol # ...
"""Web API functions.""" import logging import struct import shutil from pathlib import Path from typing import Iterable, List import requests from dacite import from_dict from nozomi.data import Post from nozomi.exceptions import InvalidTagFormat, InvalidUrlFormat from nozomi.helpers import sanitize_tag, create_tag...
#!/usr/bin/python """ Reproduce the CAMB theta variable. """ import numpy as np import scipy.integrate import scipy.interpolate import pylab as P import copy C = 3e5 # km/s ################################################################################ def comoving_dist(a, cosmo): """ Comoving distance. Igno...
import math import torch.nn.functional as F import torch.nn as nn import torch.utils.model_zoo as model_zoo import torch import numpy as np from torch.utils import data from torchvision import transforms as T model_urls = { 'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth', 'vgg13': 'https://dow...
from __future__ import absolute_import, with_statement import os import logging import functools import hashlib from assetman.tools import get_shard_from_list, _utf8 from assetman.manifest import Manifest class AssetManager(object): """AssetManager attempts to provide easy-to-use asset management and compila...
import requests import datetime as dt bcb_urls = { 'IPCA-Serviços': 'https://api.bcb.gov.br/dados/serie/bcdata.sgs.10844/dados?formato=json', 'IPCA-Bens não-duráveis': 'https://api.bcb.gov.br/dados/serie/bcdata.sgs.10841/dados?formato=json', 'IPCA-Bens semi-duráveis': 'https://api.bcb.gov.br/dados/serie/bc...
import ecdsa import base64 from Crypto.Hash import keccak import chilkat import json # import sawtooth_rest_api.exceptions as errors # Unlock chilkat library chilkat.CkGlobal().UnlockBundle("Anything for 30-day trial") def generate_keys_pair(): """ :return: tuple of serialized secp256k1 elliptic curve privat...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use...
from flask import Flask, Response, request, jsonify, render_template import numpy as np import pickle #MPLD3 lets us make an html of a matplotlib plot: import matplotlib.pyplot as plt, mpld3 import seaborn as sns import pandas as pd #Mapping Specific imports: import json import requests from shapely.geometry import sh...
# Lint as: python2, python3 # Copyright 2019 The TensorFlow 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 # ...
import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler number_of_inputs = 63 number_of_outputs = 1 learning_rate=0.001 training_epochs=100 display_step=5 layer_1_nodes=50 layer_2_nodes=100 layer_3_nodes=50 def readData(): ...
import json import random import threading import os import io from subprocess import check_output from django.core.validators import MaxValueValidator, MinValueValidator from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.core.mail impor...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © 2017 bily Huazhong University of Science and Technology # # Distributed under terms of the MIT license. """ Inference Utilities """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import co...
from common import * from json import JSONEncoder __author__ = 'zadjii' class MyEncoder(JSONEncoder): def default(self, o): return o.__dict__ class CommandModel(object): """docstring for CommandModel""" def __init__(self, command=''): super(CommandModel, self).__init__() self.c...
#!/usr/bin/env python3 """Contains the code for ICAPAI'21 paper "Counterfactual Explanations for Multivariate Time Series" Authors: <NAME> (1), <NAME> (1), <NAME> (2), <NAME> (1) Affiliations: (1) Department of Electrical and Computer Engineering, Boston University (2) Sandia National Laboratories This wo...
import torch from torch import nn import functools from .block import upconv_block, Upsample #################### # UNet Generator #################### class UnetGenerator(nn.Module): """Create a Unet-based generator U-Net: Convolutional Networks for Biomedical Image Segmentation (Ronneberger et al., 2015)...
""" Module that contains the computer vision algorithms of project elegancc. """ import cv2 import time BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (127, 127, 127) class ImageFilter: """ Responsible for applying filtering algorithms on the images. """ def __init__(self): """ ...
"""Iteratively execute salmon until all transcripts with leave-one-out-ish until all transcripts meet expression criteria a nice addition (or option) would be to have the iteration continuously testing the gene group to see if it should be split apart more because of no linkage """ import argparse, sys, ...
import time from asciimatics.effects import Print from asciimatics.exceptions import ResizeScreenError from asciimatics.renderers import FigletText, StaticRenderer from asciimatics.scene import Scene from asciimatics.screen import Screen from .utils import * SLEEP_TIME = 0.005 TERMINAL_SIZE = (50, 20) game_fin = Fa...
import random import math import numpy as np import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from torch.nn.modules.distance import CosineSimilarity from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from model.attention import Attention from model.e...
""" Utility functions to make bedfiles. """ import os import re __docformat__ = "restructredtext en" # map eland_result.txt sense sense_map = {'F': '+', 'R': '-'} sense_color = {'F': '0,0,255', 'R': '255,255,0'} def create_bed_header(name, description): """ Produce the headerline for a bedfile """ #...
#!/usr/bin/env python import errno import os import pytest import sys # Import our local xcross. test_dir = os.path.dirname(os.path.realpath(__file__)) xcross_dir = os.path.dirname(test_dir) sys.path.insert(0, xcross_dir) import xcross os.environ['CROSS_TARGET'] = 'alpha-unknown-linux-gnu' os.environ['CROSS_WITH_PAC...
#!/usr/bin/env python3 # # Bootstraps pip if required and installs miniirc. # Note that this is not required if you already have and know how to use pip, # simply run 'pip install miniirc' instead. # # © 2020 by luk3yx. # import importlib.util, os, shutil, subprocess, sys, tempfile, urllib.request assert sys.versio...
''' NAGVAC is an alternative to cholesky decomposition and it uses the factor decomposition which is \Sigma = BB^T + C^2 where B is the factor loading matrix of size (d,f) for d << f the number of factors and C is a diagonal matrix. For more information, please see https://vbayeslab.github.io/VBLabDocs/tutorial/ffv...
import os class ChemevoModel: def __init__(self, filename, init_param=None): self.filename = filename self.initialize_model(**init_param) def initialize_model(self, radius=10., time_tot=12000., dt=30., imf='kroupa', mbins_low=0.1, mbins_high=100., ...
from flask import render_template, flash, redirect, url_for, session, g, request, Blueprint, jsonify from flask_login import login_required, login_user, logout_user, current_user from app import app, db, login_manager from ..forms import LoginForm, RegistrationForm, QuestionForm, AnswerForm, TagForm from .models import...
import datetime from urllib.parse import urljoin # Python 3 from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for, jsonify from werkzeug import secure_filename from app import app, db, utils from app.models import Uploads, User, Comment, Media, Country, Genre, MediaType, StoryTyp...
'''Utils.''' __author__ = 'healplease' import os import json import time import requests FT_APP_ICON = 0 FT_APP_VIDEO_AND_POSTER = 1 FT_APP_SCREENSHOT = 2 FT_RECOMMENDATION_VIDEO = 3 FT_RECOMMENDATION_IMAGE = 4 FT_APK_OR_RPK = 5 FT_PROXY_CERTIFICATE_OR_COPYRIGHT_IMAGE = 6 FT_CERTIFICATE_PDF = 7 FT...
""" Additional functions for PyGuitarPro. This function standardizes the way the tabs are written and handles cases where a tab is ergonomically impossible to play, e.g. when it demands more than two hands to hit all notes. The function handles the most commonly used notes: notation = { 35: Bass Drum 2 36: Ba...
""" The L System Refernece: 1. http://paulbourke.net/fractals/lsys/ Character Meaning F Move forward by line length drawing a line f Move forward by line length without drawing a line + Turn left by turning angle - Turn right by turning angle | Rev...
import torch import torch.nn as nn from torch.nn import functional as F from collections import OrderedDict from ..builder import BACKBONES class PyramidFeatures(nn.Module): ''' FPN pyramid layer ''' def __init__(self, C3_size, C4_size, C5_size, feature_size=256): super(PyramidFeatures, self)...
""" Created on Thu Oct 26 11:06:51 2017 @author: <NAME> - github.com/utkuozbulak """ from PIL import Image import numpy as np import torch class CamExtractor: """ Extracts cam features from the model """ def __init__(self, model, model_name, target_layer): self.model = model self.m...
import os import sys import nltk #nltk.download('punkt') from nltk.tokenize import word_tokenize from nltk.tokenize import RegexpTokenizer from nltk import * stemmer = PorterStemmer() def __termID(a): global termID termID = a def __docID(a): global docID docID=a def __offset(a): global offset offset=a def __t...
from bcar.car import Car import ipywidgets.widgets as widgets from ipywidgets import HBox, VBox, Button import time class BCar(): def __init__(self): self.car = Car() self.panel = ButtonGroup() self.m_steer = 0 self.m_gear = 0 self.press_count = 0 def play(self)...
import numpy as np import math import random from batchgenerators.transforms import AbstractTransform import sys sys.path.append(".") from kits19cnn.io.custom_augmentations import foreground_crop, center_crop, \ random_resized_crop class RandomResizedCropTransform(Abstra...
from typing import Counter class Node: '''' THis the class is responsiple to create the Nodes ''' def __init__(self, value=""): self.value = value self.next = None def __add__(self, other): return Node(self.value + other.value) # def __str__(self,value) -> str: # return value def...
# -*- coding: utf-8 -*- """ Default rules for the typing of constants. """ from __future__ import print_function, division, absolute_import import math import types import ctypes from functools import partial import numba.typesystem from numba.typesystem import itypesystem, numpy_support from numba import numbawrap...
""" Parse q-chem log files and created displaced structures using normal modes """ import numpy as np import glob import sys import cclib from cclib.parser import ccopen NAME = { 1: 'H' , 2: 'He' , 3: 'Li' , 4: 'Be' , 5: 'B' , 6: 'C' , 7: 'N' , 8: 'O' , 9: 'F' ,...
import io import os from urllib.parse import urlparse import requests import yaml from doozerlib.exceptions import DoozerFatalError from doozerlib.exectools import cmd_assert from doozerlib.logutil import getLogger from doozerlib.model import Missing from doozerlib.pushd import Dir from doozerlib.util import is_in_di...
import datetime import numpy as np import pandas as pd from sqlalchemy import sql def get_and_adjust_data(db_engine, station_id, start, end): """ Get data from the database in both the bike count format and the outage format, between the passed dates. If bike count data and outage data is available fo...
# Discord.py is smoooooooooooooosh!!!!! import discord from discord.ext import tasks, commands import asyncio from io import BytesIO import requests from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageOps import random class Event(commands.Cog): def __init__(self, technetium): self.bot = techne...
import datetime import logging import time from discord import activity from discord.utils import get from logging.handlers import RotatingFileHandler import discord from discord.ext import commands import util.gen_list as GenList from util.config import BotConfig from util.data.data_backup import DataBackups from ut...
import numpy as np from .harmonics import ut_E from .utilities import Bunch from ._time_conversion import _normalize_time def reconstruct(t, coef, epoch='python', verbose=True, constit=None, min_SNR=2, min_PE=0): """ Reconstruct a...
import torch from torch import nn import torch.nn.functional as F from models.attention import ChannelAttention, SpatialAttention class BasicConvBlock(nn.Module): def __init__(self, in_chans, out_chans, stride=1): super().__init__() self.layers = nn.Sequential( nn.Conv2d(in_chans, out...
from optimizer import optimizer_SGD, AdaGrad, NormGrad, SGD import numpy as np from functions import sigmoid, sigmoid_back, clip_grads class Loss: def __init__(self): self.Loss = None self.dout = None def forward(self, out, t): self.Loss = 1/2 * np.sum((out - t)**2) ...
# -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ Implementations of our 3D cameras. """ from __future__ import division import math import numpy as np from ..base import Camera from ...util import transforms, logger ...
import sqlite3 class Connection(): def __init__(self): self.connection = sqlite3.connect('results.db') self.cursor = self.connection.cursor() self.enable_foreign_keys() def close(self): self.connection.close() def commit(self): self.connection.commit() def ro...
import pytest import tempfile import pathlib import yaml import subprocess import os import textwrap import shutil import numpy as np import ase.io import torch from nequip.data import AtomicDataDict from test_train import ConstFactorModel, IdentityModel # noqa @pytest.fixture( scope="module", params=[ ...
# wpt-submissions.live is a public deployment of WPT, maintained in an external # repository. It automatically fetches and deploys all tags in the WPT # repository which match a certain pattern. This behavior is intended to be # used for pull requests so that reviewers can preview changes without running # the WPT serv...
# # ⚠ Warning # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT # LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA...