text
stringlengths
3.07k
12.6k
''' Created on 2015/12/25 :author: hubo ''' from vlcp.event.runnable import RoutineContainer from vlcp.event.stream import Stream from vlcp.event.event import withIndices, Event from vlcp.event.core import PollEvent import socket @withIndices('channel', 'channelobj', 'ioerror', 'exitstatus') class ChannelExitEvent(Ev...
"""Mobile ViT Block module. - Author: <NAME> - Contact: <EMAIL> """ from typing import Tuple, Union import torch from einops import rearrange from torch import nn from kindle.modules.activation import Activation from kindle.modules.conv import Conv class PreNorm(nn.Module): """Pre-normalization layer.""" ...
import os import numpy as np import cv2 as cv def angle(x0, y0, x1, y1): from math import degrees, atan2 a = degrees( atan2(y1-y0, x1-x0) ) return a def coordinates(x0, y0, distance, angle): from math import radians, sin, cos x1 = x0 + cos(radians(angle)) * distance y1 = y0 + sin(radians(angle...
import logging import os from pathlib import Path import shutil import time from dash import __version__ as dashversion import dash_html_components as html from flask import request from flask import abort import dash_uploader.settings as settings from dash_uploader.upload import update_upload_api logger = logging.g...
#<NAME> #ICS3UO #Pygame #A player must "catch" as many blocks as possible within a 30 second time limit #Imports Libraries from python import pygame import random import time # Initialize Pygame pygame.init() # Initialize Variables timer = 0 #time tracker score = 0 #score tracker lost = False end = False soundpl...
import os import uuid from nixui.utils.logger import logger from nixui.utils import cache from nixui.options import syntax_tree, nix_eval from nixui.options.option_definition import OptionDefinition, Unresolvable def inject_expressions(module_path, option_expr_map): tree = syntax_tree.SyntaxTree(module_path) ...
"""J wave detection by Pino et al. (2015) <NAME>, <NAME>, and <NAME>, 'Noninvasive ambulatory measurement system of cardiac activity,' in Conf. Proc. IEEE Eng. Med. Biol. Soc., 2015, pp. 7622-7625 """ import numpy as np import scipy import scipy.ndimage import scipy.signal as sgnl import pandas as pd import pywt fro...
#!/usr/bin/env python # encoding: utf-8 # File : JetAlgos.py # Author : <NAME> # Contact : <EMAIL> # Date : 2018 Oct 30 # # Description : import uproot import itertools import numpy as np import ROOT import math def deltaPhi(x, y): dphi = x-y if dphi >= math.pi: dphi -= 2*math...
import os import shutil from copy import deepcopy import random import numpy as np import pandas as pd import torch from torch import optim from torch.optim.lr_scheduler import StepLR from tqdm import tqdm from transformers import AdamW, T5Tokenizer from nltk.tokenize import TweetTokenizer from modules.tokenization_ind...
#!/usr/bin/env python """igcollect - Logs This script is capable of scanning log files for a given regex for a message and then compare them by a given time format if they are within a given timeshift. Imagine for example you want to scan a log file every 15 minutes for errors and see how many errors occur and how ma...
"""This module holds the file I/O methods for rasters and bands.""" __all__ = [ 'set_properties', 'RasterSetReader', ] import xmltodict import numpy as np from PIL import Image import os import collections import properties from .raster import RasterSet, Band def set_properties(has_props_cls, input_dict, i...
""" Runs the main game. """ import pygame from tetris_board import TetrisBoard from tetris_piece import colors from tetris_controller import Controller # Initialize pygame pygame.init() # pylint: disable=no-member # Initialize the colors for the board BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (128, 128, 128) ...
import argparse from typing import Union from alto.utils import * def detect_workflow_source(workflow_string: str) -> str: """Detect if a workflow is from Dockerstore or Broad Methods Repository """ if workflow_string.find(':') >= 0: return 'Dockstore' return 'Broad Methods Repository' def...
# Copyright 2019 The OpenRadar 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 # Unless required by applicable law...
import sys import sqlite3 # connection = sqlite3.connect("C:/Users/michelle/PycharmProjects/GuideToPharmacology/Ligands.db", # check_same_thread=False) connection = sqlite3.connect("C:/Users/michelle/Documents/GitHub/scb-kp-dev/transformers/gtopdb/python-flask-server/data/GtoPdb.db", ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Topic modeling @author: ericyuan """ import pandas as pd # Other import re # Gensim import gensim # NLTK import nltk from nltk.corpus import stopwords nltk.download('stopwords') stop_words = stopwords.words('english') stop_words.extend(['from', 'subject', 're', 'edu...
import numpy as np import yaml from chainconsumer import ChainConsumer import pandas as pd import sys import argparse import os import logging def load_params(file): assert os.path.exists(file), f"Paramnames file {file} does not exist" names, labels = [], [] with open(file) as f: for line in f.rea...
# === Start Python 2/3 compatibility from __future__ import absolute_import, division, print_function, unicode_literals from future.builtins import * # noqa pylint: disable=W0401, W0614 from future.builtins.disabled import * # noqa pylint: disable=W0401, W0614 # === End Python 2/3 compatibility import pytest impo...
from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar from determined.common import schemas class UnionBaseMeta(schemas.SchemaBaseMeta): """ UnionBaseMeta raises an error if you forget to set the _union_key on a UnionBase. """ def __new__(cls: type, name: str, bases: Tuple, dct: dic...
import os from pathlib import Path import wandb from google.protobuf.json_format import MessageToDict, ParseDict from stable_baselines3.common.callbacks import BaseCallback from yacht import utils, Mode from yacht.config import Config from yacht.logger import Logger from yacht.utils import create_project_name from y...
#!/bin/env python # Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
import os import re import time import pickle import argparse import pandas as pd class message: time="" name="" qq="" content=[] def __init__(self): self.time,self.name,self.qq,self.content=("","","",[]) class messages: name="" msgs=[] user_qq_name={} def __init__(self, fi...
#!/usr/bin/env python """ Convert a graph between Pandas and OrientDB. """ # Copyright (c) 2015, <NAME> # All rights reserved. # Distributed under the terms of the BSD license: # http://www.opensource.org/licenses/bsd-license import copy import json import pandas as pd import pyorient.otypes from utils import _fin...
import numpy as np import rospy from kinect_robo.msg import ArmPose from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint CAMERA_ORIGIN = [0, -0.2, 3.14159, 1.25, 0, 0.1] # [r,p,y,x,y,z] (wrt world Frame) ## Definitions of Transformation Matrices def Rx(theta): rx = np.matrix([[1.0, 0.0,...
r""" Tools for working with ARPA format N-gram models Expects the ARPA format to have: - a \data\ header - counts of ngrams in the order that they are later listed - line breaks between \data\ and \n-grams: sections - \end\ E.G. ``` \data\ ngram 1=2 ngram 2=1 \1-grams: -1.0000 Hello -0.23 ...
import math class Cluster(object): """Cluster class The basic class of a cluster of seeds. Attributes: radius: The radius of a cluster of seeds """ def __init__(self, radius): self.radius = radius self.area = math.pi * radius * radius def get_radius(self): ret...
import os import functools from torchvision import datasets, transforms from torchvision.datasets.folder import default_loader from .abstract_dataset import AbstractLoader class ImageFolderLoader(AbstractLoader): """Simple pytorch image-folder loader.""" def __init__(self, path, batch_size, num_replicas=1, ...
import subprocess,time,sys,os,inspect,atexit,re import msgpack,mprpc class RubyObject(): session = None @staticmethod def cast(obj): if isinstance( obj, msgpack.ExtType ): assert obj.code == 40 rb_class, obj_id = msgpack.unpackb(obj.data, raw=False) return Ruby...
import traceback import datetime import logging import sqlite3 import sys import re from discord.ext import commands import ruamel.yaml as yaml import discord class HelperBodge(): def __init__(self, data): self.data = data def format(self, arg): return self.data.format(arg.replace('@', '@\u20...
class Link: """A linked list. >>> s = Link(1) >>> s.first 1 >>> s.rest is Link.empty True >>> s = Link(2, Link(3, Link(4))) >>> s.second 3 >>> s.first = 5 >>> s.second = 6 >>> s.rest.rest = Link.empty >>> s # Displays the contents o...
from pathlib import Path import pandas as pd from rich import box from rich.table import Table from remade import utils from remade.paths import storage_path_default #%% class Configs: def __init__( self, bam_files, ngsLCA, ngsLCA_command, storage_path=storage_path_defa...
"""Macros that define an sh_test target that is suitable for executing Bazel in \ an integration test.\ """ load("@bazel_skylib//lib:paths.bzl", "paths") load("@bazel_skylib//rules:select_file.bzl", "select_file") load(":integration_test_utils.bzl", "integration_test_utils") # This was lovingly inspired by # https://...
#!/usr/bin/env python # Copyright 2017 IIE, CAS. # Written by <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...
from skynet.full_node.block_store import BlockStore from skynet.util.ints import uint32, uint64 ################################################################## # Algo_rewards ################################################################## # 1 Skynet coin = 1,000,000,000,000 = 1 trillion synt. _synt_per_skynet =...
""" Images used in DR3 are now in different location on project/staging. This script finds these cases and updated the survey-ccds files with the new imagefilename """ import numpy as np import os from glob import glob import subprocess from astrometry.util.fits import fits_table, merge_tables def bashOutput(cmd): ...
import math from tqdm import tqdm from dataclasses import asdict import torch import torch.nn.functional as F from models.ts_ae.tsae import TSAE from models.encoders.schnet import SchNetEncoder from models.encoders.egnn import EGNNEncoder from utils.exp import TestLog from utils.models import X_to_dist from torch_geo...
# Listing_19-5.py # Copyright Warren & <NAME>, 2013 # Released under MIT license http://www.opensource.org/licenses/mit-license.php # Version $version ---------------------------- # PyPong with sounds and music import pygame, sys class MyBallClass(pygame.sprite.Sprite): def __init__(self, image_file, speed...
from torch.utils.data import Dataset # import joblib import numpy as np import torch from settings import segment_length, segment_slide import _pickle as pickle def load_file(filename): with open(filename,'rb') as f: data=pickle.load(f) return data def normalize(x, mean=[0.3, 0.6], std=[0.09, 0.13]):...
import numpy as np def make_mtl_file(material_name, save_folder): fout_mtl = open(save_folder / (material_name + ".mtl"), "w") fout_mtl.write("newmtl " + material_name + "\n") fout_mtl.write("Ns 96.078431\nKa 1.000000 1.000000 1.000000\nKd 0.640000 0.640000 0.640000\nKs 0.500000 0.500000 0.500000\nKe 0.0...
import asyncio from asyncio import Protocol, StreamReader, Event, Queue, AbstractEventLoop from threading import Thread from callblocker.core.modem import ModemType, SerialDeviceFactory from callblocker.core.modems import CX930xx from callblocker.core.service import AsyncioService, ServiceState, AsyncioEventLoop CX93...
import psycopg2.extras _user = "postgres" _password = "<PASSWORD>" _con = psycopg2.connect(host="localhost", database="esami", user=_user, password=_password) _con.set_session(autocommit=True) def get_cursor(): return _con.cursor(cursor_factory=psycopg2.extras.DictCursor) def create_tables(): with get_curso...
import netCDF4 from optimism.JaxConfig import * from optimism import Mesh from optimism import Interpolants exodusToNativeTri6NodeOrder = np.array([0, 3, 1, 5, 4, 2]) def read_exodus_mesh(fileName): with netCDF4.Dataset(fileName) as exData: coords = _read_coordinates(exData) conns, blocks = _rea...
import os import random import torch.nn as nn import torch import math import config from typing import Union,Tuple import pytorch_lightning as pl import copy class ConvNorm1d(nn.Module): def __init__(self,in_channels: int, out_channels: int, kernel_size: Union[int, Tuple[int]], stride: Union[int, ...
#!/usr/bin/python """ ================================================== HesBO - A Framework for Bayesian Optimization in Embedded Subspaces LINK: https://github.com/aminnayebi/HesBO @inproceedings{HeSBO19, author = {<NAME> and <NAME> and <NAME>}, title = {A Framework for Bayesian Opti...
# @author : <NAME> # github : https://github.com/hugosimony # creation date : 20/01/2021 # ------------------------------------------------------------------------------------------------------------- # imports from tkinter import * import threading import time import random from os import path # ------------------...
from __future__ import print_function import torch.utils.data as data import os import os.path import torch import numpy as np from plyfile import PlyData, PlyElement class ShapeNet_v0(data.Dataset): ''' able to select a list of classes, say 4, each with 1000 class_choices and ratio are list of clases and ...
# -*- coding: utf-8 -*- """ Author: <NAME> """ import numpy as np import matplotlib.pyplot as plt import scipy.signal as dsp def open_signal(file, sr): """ Open a txt file where the signal is Parameters: file: Address where the file is located sr: Sampling rate ...
#%% import os import time import json import numpy as np import math import matplotlib.pyplot as plt import gym from stable_baselines3.common.vec_env import DummyVecEnv, SubprocVecEnv from stable_baselines3.common.utils import set_random_seed from stable_baselines3 import PPO, A2C, TD3 from stable_baselines3.common.e...
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
import time import os from collections import defaultdict from cookielib import CookieJar from copy import deepcopy from deluge._libtorrent import lt import logging log = logging.getLogger(__name__) # Torrent tracker handler classes registry. TRACKER_HANDLERS = {} def register_tracker_handler(domain_name, handler...
import ast import json import os import time from pathlib import Path from typing import Optional import pandas as pd from gensim import corpora from gensim.models import LdaModel from txtai.embeddings import Embeddings def get_raw_data(datadir: str) -> Optional[pd.DataFrame]: return get_data(get_raw_data_path(d...
import numpy as np from KPI import KPI def calc(inp): return inp[:, 9] def gap(open_price, close_price, init_money): return 1.0 * (close_price / open_price - 1) * init_money def gap_colume(open_price, close_price, colume): return 1.0 * (close_price - open_price) * colume def RSI(data, paras, standard_da...
import urllib.parse from dataclasses import dataclass from typing import Tuple, Dict, Any, Callable, Optional from tarpn.crc import crc_b from tarpn.log import LoggingMixin from tarpn.network import L3Protocol, L3Address from tarpn.network.mesh import MeshAddress from tarpn.network.mesh.header import DatagramHeader, D...
# SPDX-FileCopyrightText: 2022 <NAME> # # SPDX-License-Identifier: MIT import json import time class SocketManager: def __init__(self, socketpool): self.socketpool = socketpool # configuration self._host = None self._port = None self._sslcontext = None self.reconn...
import asyncio import pandas as pd import aiohttp from time import mktime import mwparserfromhell as mw from datetime import datetime from lxml import html from mwclient import Site from .revision import Revision def get_users(metadata): """ Pull users, handles hidden user errors Parameters: met...
import torch from torch import nn from torch.nn import functional as F from torch.distributions import Normal class Encoder(nn.Module): """ Encoder to embed image observation (3, 64, 64) to vector (1024,) """ def __init__(self): super(Encoder, self).__init__() self.cv1 = nn.Conv2d(3, 3...
import base64 from rest_framework import status from django.contrib.auth.models import User from rest_framework.response import Response from django.core.files.base import ContentFile from django.utils.datetime_safe import datetime from rest_framework.authtoken.models import Token from rest_framework.permissions import...
import sys import os import json import re if sys.version_info[0] >= 3: unicode = str def is_bool(x, val=None): return isinstance(x, bool) and (val is None or x == val) def is_dict(x): return isinstance(x, dict) def is_list(x): return isinstance(x, list) def is_int(x, val=None): return (isinsta...
import torch from torch.nn import Conv2d, Linear, Module from torch.nn import functional as F # from functions.psroi_pooling.modules.psroi_pool import PSRoIPool # from functions.roi_align.modules.roi_align import RoIAlignMax # from functions.mmdet.roi_align.modules.roi_align import RoIAlign from utils.utils import norm...
""" In this example, we only have dots. The Size of the dots are the number of strains at each point and the color of the dots are the number of connnections to that dot. """ import os import sys import argparse import matplotlib.pyplot as plt # set the figure size. This should be in inches? plt.rcParams["figure.figs...
import os import geopandas as gpd import matplotlib.pyplot as plt import numpy as np import pandas as pd import pyro import seaborn as sns import torch from pyro.nn import PyroModule from torch import nn from pyro.distributions import Poisson, Binomial, Beta, Gamma import math import torch.distributions.constraints as...
# -*- coding: utf-8 -*- """ Created on Sat Sep 15 19:19:15 2018 @author: Developer """ from future.builtins import next import os import csv import re import logging import sys import argparse as ag import dedupe from unidecode import unidecode import traceback as tb import psutil as pu #import objgraph as og # ## ...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, <NAME> <<EMAIL>> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at you...
import os import random from .base import BaseDataset import numpy as np import sys import pdb def normalize(audio_data, re_factor=0.8): EPS = 1e-3 min_data = audio_data.min() audio_data -= min_data max_data = audio_data.max() audio_data /= max_data + EPS audio_data -= 0.5 audio_data *= 2 ...
import os import tempfile from warnings import warn from AnyQt import QtGui, QtCore, QtSvg from AnyQt.QtCore import QMimeData from AnyQt.QtWidgets import QGraphicsScene, QGraphicsView, QWidget, QApplication from Orange.data.io import FileFormat # Importing WebviewWidget can fail if neither QWebKit (old, deprecated) ...
# -*- coding: utf-8 -*- # # Copyright 2018 Spotify AB # # 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 a...
import sys import warnings warnings.filterwarnings("ignore") import pandas as pd from mgefinder import fastatools, cdhittools from Bio import SeqIO from snakemake import shell from collections import defaultdict import click from os.path import join, isfile from os import makedirs, rename from shutil import rmtree from...
import re TYPES = [ 'av(enue)?', 'r(ue)?', 'b(oulevar)?d', 'all[ée]es?', 'impasse', 'place', 'chemin', 'rocade', 'route', 'l[ôo]tissement', 'mont[ée]e', 'c[ôo]te', 'clos', 'champ', 'bois', 'taillis', 'boucle', 'passage', 'domaine', 'étang', 'etang', 'quai', 'desserte', 'pré', 'porte', 'square', 'mont',...
""" Plot demonstrating the integral as the area under a curve. Although this is a simple example, it demonstrates some important tweaks: * A simple line plot with custom color and line width. * A shaded region created using a Polygon patch. * A text label with mathtext rendering. * figtext calls to la...
""" Function to node transformer """ import ast import inspect from textwrap import dedent from uuid import uuid4 from lute.node.base import Constant, Node, NodeMeta def is_lambda(v) -> bool: """ Check for lambda. From https://stackoverflow.com/a/3655857 """ LAMBDA = lambda: 0 return isinstance...
''' description: Create a db entry for a VOEvent license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' import argparse import voeventparse as vp import pandas from pyAccess import dbase from pytz import timezone from pyAccess.FRBCat import * from pyAccess import utils def get_param(param_data, ma...
""" This module is used to test all function in Scripts/air_pollution/helpers.py """ import warnings import pandas as pd import numpy as np from ..scripts.air_pollution import helpers warnings.filterwarnings('ignore') PATH = r'air_pollution_death_rate_related/data/air_pollution/data_air_raw/daily_aqi_by_county_' L...
#!/usr/bin/env python from __future__ import print_function import math import numpy import matplotlib matplotlib.use("PDF") fig_size = [8.3,11.7] # din A4 params = {'backend': 'pdf', 'axes.labelsize': 10, 'text.fontsize': 10, 'legend.fontsize': 6, 'xtick.labelsize': 8, 'ytic...
# Copyright 2017 <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, softwa...
"""Defines a basic and primitive database interface. It is basically a thin wrapper on DB API 2.0.""" import logging from abc import ABC, abstractmethod from contextlib import contextmanager from dataclasses import dataclass from typing import List, Tuple from urllib.parse import parse_qs, urlparse from dinao.backend...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2019 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the ...
import sys import csv from itertools import * from bisect import * from operator import * from containers import * from collections import defaultdict def loadSnapshot(fn): snapshots = [] with open(fn, 'rb') as csvfile: snapshotRows = defaultdict(list) csvreader = csv.reader(csvfile) fo...
from .. utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperationTestCase, InplaceOperationTestCase class BytesTests(TranspileTestCase): def test_setattr(self): self.assertCodeExecution(""" x = b'hello, world' try: x.attr = 42 except Attrib...
from FT.weighted_tracts import save_ft, load_ft, nodes_by_index_mega, nodes_labels_mega, non_weighted_con_mat_mega, load_dwi_files, draw_con_mat from FT.all_subj import all_subj_folders, all_subj_names import numpy as np from dipy.tracking.streamline import values_from_volume import nibabel as nib import os def load_...
import random import os import itertools ###################################################################### posWins = [ [0,1,2] , [3,4,5] , [6,7,8] , [0,3,6] , [1,4,7] , [2,5,8] , [0,4,8] , [2,4,6] ] def loadFiles(): global wins, defeats if "wins.txt" in os.listdir(os.getcwd()) and "defeats.txt" in os.li...
import time, datetime import serial from thread import start_new_thread class FishFeederStatus: READY = 0 ERROR = 1 BUSY = 2 ROTATING = 3 DUMPING = 4 CALIBRATING = 5 @staticmethod def getMessage(status): if (status == FishFeederStatus.READY): return "Ready" if (status == FishFeederStatus.ERROR): re...
import os import tempfile import numpy as np from bgmol.util.importing import import_openmm _, unit, app = import_openmm() from ..systems.base import OpenMMSystem from ..util.pdbpatch import fixed_atom_names from torchvision.datasets.utils import download_url __all__ = ["ChignolinC22Implicit"] class ChignolinC22Impl...
from functools import reduce from operator import xor from string import hexdigits # yes I need to learn regex VALIDATIONS = { 'byr': lambda y: 1920 <= int(y) <= 2002, 'iyr': lambda y: 2010 <= int(y) <= 2020, 'eyr': lambda y: 2020 <= int(y) <= 2030, 'hgt': lambda h: 150 <= int(h[:-2]) <= 193 if...
import argparse import json import os import sys import timeit import numpy as np imports = """ import random from subprocess import call, PIPE import numpy as np import gtar """ generateRandom = """ position = np.random.uniform(-50, 50, size=({Nframes:}, {N:}, 3)).astype(np.float32) orientation = np.random.uniform(...
""" Advent of Code - Day 3: Toboggan Trajectory --- Part 1 --- With the toboggan login problems resolved, you set off toward the airport. While travel by toboggan might be easy, it's certainly not safe: there's very minimal steering and the area is covered in trees. You'll need to see which angles will take you nea...
from bs4 import BeautifulSoup import pandas as pd import re import requests from progress.bar import IncrementalBar from pathlib import Path import mwparserfromhell from .cache import HttpCache, DataCache from urllib.parse import urljoin, urlparse import argparse def to_fahrenheit_int(celsius): if celsius is None...
#!/usr/bin/env python import os import sys import unittest import contextlib from uuid import uuid4 from hashlib import md5 from unittest import mock from tempfile import TemporaryDirectory pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # noqa sys.path.insert(0, pkg_root) # noqa from json...
from baseline.utils import write_json from baseline.pytorch.torchy import * from baseline.pytorch.transformer import TransformerEncoderStack, subsequent_mask, MultiHeadedAttention from baseline.model import LanguageModel, register_model import torch.autograd import os class LanguageModelBase(nn.Module, LanguageModel)...
# Lint as: python3 # Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
"""Test setup.""" import sys import pathlib import tempfile from contextlib import contextmanager import os from unittest.mock import MagicMock import pytest import _repobee.constants import _repobee.config import _repobee.plugin import constants # mock the PyGithub github module sys.modules["github"] = MagicMock() ...
import inspect import os import re import time from pathlib import Path from types import FunctionType, ModuleType import click from gutt.parser import load_module_from_pyfile from gutt.template import populate_testclass, populate_testfunc from gutt.utils import ( blacking, collect_classes_and_functions, e...
from explainaboard.utils.analysis import ( reverse_dict, reverse_dict_discrete, find_key, ) from explainaboard.utils.py_utils import sort_dict def bucket_attribute_specified_bucket_value( dict_obj=None, bucket_number=4, bucket_setting=None ): if not dict_obj or len(dict_obj) == 0: return N...
import discord from discord.ext import commands from dotenv import load_dotenv import os import requests from bs4 import BeautifulSoup from races import * from classes import * from builds import build_search client = commands.Bot(command_prefix='!') load_dotenv() @client.command(name="race", hel...
from .GusherMap import GusherMap, BASKET_LABEL from .GusherNode import GusherNode, NEVER_FIND_FLAG, write_tree from copy import deepcopy def flag(findable): if findable: return "" else: return NEVER_FIND_FLAG def get_strat_greedy(gusher_map): """Build a decision tree for the gusher gushe...
#import numpy as np from numpy import sqrt, zeros, pi, arctan, asarray, arange, delete, sum, multiply, sin, cos def FT(k, exafs, rmin, rmax, dr): con = sqrt(2 / pi) nn = len(k) rx = zeros(int((rmax - rmin) / dr), float) exafs_re = zeros(nn, float) # exafs_im = zeros(nn, flo...
import netCDF4 as nc import numpy as np import gc import sys latdims = ['xt','xm','yt','ym'] skip = ['u0','v0','dn0'] class NCFile(object): def __init__(self,ifile,mode="r"): self.ncid = nc.Dataset(ifile,mode) def NcClose(self): self.ncid.close() class NcInput(NCFile,object): def __in...
import calendar from datetime import datetime from dateutil.relativedelta import relativedelta from lxml import etree as ElementTree from django.utils.translation import ugettext as _ from corehq import Domain from corehq.apps.commtrack.util import get_commtrack_location_id from corehq.apps.locations.models import Lo...
# -*- coding: utf-8 -*- """ Created on Thu Jan 9 12:59:26 2020 @author: Sean This model uses Tkinter to create a standard GUI. When you run the code, two windows should appear on your screen ('Figure 1' and 'Model'). In the top right of the 'Model' window, please select either 'Start the drunk model' (to...
import argparse import datetime import os import re import pkg_resources from jinja2 import Environment, PackageLoader, select_autoescape import openuxas_mde from openuxas_mde.lang.schema import UxasSchemaParser def camel_case_to_upper_case(s): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s) s1 = re.sub('([a-z0...
#!/home/zhihou/anaconda3/envs/tf/bin/python from __future__ import absolute_import from __future__ import division from __future__ import print_function from pickle import UnpicklingError import _init_paths import tensorflow as tf import numpy as np import argparse import pickle import json import ipdb import os fr...