text stringlengths 3.07k 12.6k |
|---|
import time
from math import sin, cos, asin, pi
import pygame
from pygame.draw import *
from my_colors import *
pygame.init()
FPS = 60
SCREEN_X, SCREEN_Y = 1300, 600
GROUND_Y = 19 * SCREEN_Y // 20
screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y))
class Game:
def __init__(self):
self.pendulum = P... |
from enum import Enum
import pandas as pd
import numpy as np
# import data types
from pandas import DataFrame
from numpy import ndarray
from typing import List, Tuple, Optional
from pathlib import Path
from src.data.workout import Activity, Workout
from src.data.data import DataState
from src.config import RAW_BOOT_F... |
from PIL import Image, ImageDraw, ImageFont
from statistics import mean
import argparse, ffmpeg, os, subprocess, shutil
def get_info(original):
print("Getting video information...")
if '.mp4' not in original[-4:]:
print("The file specified is not a video.")
raise SystemExit
... |
# -*- coding: utf-8 -*-
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
import os
import numpy as np
from utils.UCF_utils import two_stream3_generator, two_stream18_generator
from models.two_stream import two_stream_model
from utils.OF_utils import stack_optical_flow
import cv2
import random
from scipy.misc import imresize
from keras.applications.imagenet_utils import preprocess_input
N_C... |
# ========================= eCAL LICENSE =================================
#
# Copyright (C) 2016 - 2019 Continental Corporation
#
# 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... |
#================================================================
#
# File name : RL-Bitcoin-trading-bot_1.py
# Author : PyLessons
# Created date: 2020-12-02
# Website : https://pylessons.com/
# GitHub : https://github.com/pythonlessons/RL-Bitcoin-trading-bot
# Description : Introduction to ... |
# Copyright 2018 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
#
# Unless required by applica... |
# -*- coding:utf-8 -*-
# author: Racle
# project: pointer-network
import os
import pyrouge
import logging
import numpy as np
import torch
from torch.autograd import Variable
import tensorflow as tf
import config
def get_encoder_variables(batch, use_cuda):
"创建encoder所需变量"
batch_size = len(batch.enc_lens)
... |
import calendar
from datetime import datetime, timedelta
import os
import re
from django.conf import settings
from django.core.management import BaseCommand, CommandError
from pysftp import Connection
try:
from urllib.parse import splitport
except ImportError:
from urllib import splitport
DEFAULT_PORT = 22
TI... |
"""Load ACS PUMS data from Census CSV files."""
import os
import random
import io
import requests
import zipfile
import numpy as np
import pandas as pd
state_list = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI',
'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI',
... |
import torch
import torch.nn as nn
class LossyYCbCr(nn.Module):
def forward(self, rgb: torch.Tensor):
return torch.cat([
# Y (B, 1, H, W)
0.299 * rgb[:, 0:1]
+ 0.587 * rgb[:, 1:2]
+ 0.114 * rgb[:, 2:3],
# Cb (B, 1, H, W)
-0.16875 * rg... |
#from mpi4py.futures import MPIPoolExecutor
from mpi4py import MPI
import argparse
from parser import parse_input
from merge_nodes import merge_field_nodes
from merge_nodes import merge_analysis_nodes
# based on https://github.com/jbornschein/mpi4py-examples/blob/master/09-task-pull.py
#x0, x1, w = -2.0, +2.0, ... |
"""Derive the license information and publish in docs."""
import functools
import json
import pathlib
import pkg_resources
import string
import subprocess # nosec
from typing import List, Tuple
__all__ = ['dependency_tree_console_text', 'direct_dependencies_table', 'indirect_dependencies_table']
ENCODING = 'utf-8'
T... |
# Copyright (c) Microsoft. All Rights Reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
# TODO: baselining (see json.py)
# TODO: Handle manager.agg_type (see json.py)
# TODO: Run pylint or any tool that detects Py2/Py3 differences.
import datetime
import j... |
# MIT License
#
# Copyright(c) 2017 Aalborg University
# <NAME>, June 2017
#
# 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... |
import csv
import numpy as np
import matplotlib.pyplot as plt
"""
This script first use the csv library to run through the weather data extracted by sql queries and
calculate the moving averages then visualize the data through matplotlib Library
"""
# all functions
# open csv and extract data
def extract_csv(filepa... |
# Autores:
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
import random, math
alturaCilindro = 1/2
ptosCircunfCilindro = 0
ptosCircunfCentro = 0
ptosCircunfInferior = 0
ptosCircunfSuperior = 0
ptosRuedaEsferica = 0
radioCircunfCilindro = 1/2
radioCircunfSuperior = 2
radioCircunfCentro = 4
radioCirunfInferior = 1
radioRuedaE... |
import torch
import torchvision
import numpy as np
from PIL import Image
from models.DeepLabV2_feat import DeeplabFeat
from datasets.cityscapes_Dataset import get_city_dataloader
from datasets.gta5_Dataset import get_gta5_dataloader
from datasets.synthia_Dataset import get_syn_dataloader
# class 19 colour map
label_co... |
from __future__ import division
import sys
import os
import numpy as np
from mpi4py import MPI
#=============================================================================
# Parallel & pretty printer
typemap = {
np.dtype('float64'): MPI.DOUBLE,
np.dtype('float32'): MPI.FLOAT,
np.dtype('int16'): MPI.SHO... |
import collections
import csv
import enum
import os
from typing import MutableMapping, Text, Tuple, Iterable, List
import pandas as pd
from absl import logging
from tapas_file_utils import (list_directory, make_directories)
from tapas_text_utils import (wtq_normalize)
_TABLE_DIR_NAME = 'table_csv' # Name that the t... |
# Copyright(C) 1999-2020 National Technology & Engineering Solutions
# of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
# NTESS, the U.S. Government retains certain rights in this software.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provide... |
from .utils.shared_array import SharedArray
from .utils.space_wrapper import SpaceWrapper
import multiprocessing as mp
import numpy as np
import traceback
import gym.vector
def compress_info(infos):
non_empty_infs = [(i, info) for i, info in enumerate(infos) if info]
return non_empty_infs
def decompress_inf... |
import os
import numpy as np
import pandas as pd
import argparse
import torch
from torch import nn, optim
from torch.nn import functional
from tqdm import tqdm
from VAE import *
'''
parser = argparse.ArgumentParser()
parser.add_argument('--batch-size', type=int, default=128, metavar='N',
help='in... |
import os
import sys
import subprocess
import logging
# --------------------------------------------------------------------------------------------------
# One time change.
# Dirctory structure of projects (change if you want different structure).
base_path = 'c:/csi/'
# for linux
#base_path = '/home/as... |
# PYthon
import logging
# pyATS
from pyats.utils.objects import find, R
# Unicon
from unicon.core.errors import SubCommandFailure
# iosxe traceroute
from genie.utils.timeout import Timeout
from genie.libs.parser.iosxe.traceroute import Traceroute
log = logging.getLogger(__name__)
def verify_traceroute_first_hop_a... |
"""
A simple simulator for learning to move a 2D point to a target location.
"""
from __future__ import print_function
import math
import sys
from random import random
import bonsai_ai
def debug(*args):
# To debug, change this to True
if False:
print(*args, file=sys.stderr)
def distance(p1, p2):
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms import ToTensor
import numpy as np
import cv2
from .matlab_cp2tform import get_similarity_transform_for_cv2
import pandas as pd
import os
import sys
from scipy.spatial.distance import cdist
from skimage.feature import local_b... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Helper functions to process image data.
@author: amagrabi
'''
import numpy as np
import os
import urllib
import glob
import validators
import magic
from PIL import Image
from mimetypes import guess_extension
import time
import shutil
import hashlib
import signal
... |
import navegador5 as nv
import navegador5.url_tool as nvurl
import navegador5.head as nvhead
import navegador5.body as nvbody
import navegador5.cookie
import navegador5.cookie.cookie as nvcookie
import navegador5.cookie.rfc6265 as nvrfc6265
import navegador5.jq as nvjq
import navegador5.js_random as nvjr
import naveg... |
#!/usr/bin/env python3
"""
Copyright 2019 Johns Hopkins University (Author: <NAME>)
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""
from __future__ import print_function
import os
import sys
import argparse
from collections import OrderedDict
from scipy.io import wavfile
from numpy import linalg a... |
from __future__ import annotations
import abc
import functools
import logging
import numbers
import os
from typing import Callable, Sequence
import dill
import numpy as np
import pandas as pd
import torch
import yaml
from yaml.representer import Representer
from meerkat.columns.abstract import AbstractColumn
from me... |
import torch
import torch.nn.functional as F
import torch.nn as nn
from modules.python.models.resnet import resnet18_custom
def reverse_onehot(one_hot_vector):
reversed_onehot = one_hot_vector.clone()
reversed_onehot[one_hot_vector == 0] = 1
reversed_onehot[one_hot_vector != 0] = 0
return reversed_one... |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision import datasets, models, transforms
import os
from torch.utils.data import dataloader, Dataset
from PIL import Image
from retrieval.DaiNet import *
def get_file_list(file_path_list, sort=True):
"""
... |
# Copyright (c) 2021 PyDefi Development Team.
# Distributed under the terms of the Modified BSD License.
import pytest
from chainfix import Fixb
from chainfix import Fixb32
from chainfix import Fixd
from chainfix import Fixd32
from chainfix import get_decimal_context, set_decimal_context
from chainfix import Ufixb
fr... |
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.mail import send_mail
from django.template import Template, Context
from django.utils import timezone
from html2text import html2text
from markdown import markdown
from chair_mail.context impor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# basic.py
# Data Culpa Validator Open Clients
#
# Copyright (c) 2020-2021 Data Culpa, Inc.
#
# 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... |
"""0-1 Knapsack Problem
Given weights and values of n "non-splittable" items, put these items in a
knapsack of capacity to get the maximum total value in the knapsack.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def _knapsack01_recur(val, wt, wt_... |
import tensorflow as tf
import networks.resnet50.resnet_v2 as resnet_v2
import networks.resnet50.params as config
slim = tf.contrib.slim
MEANS = [0.485, 0.456, 0.406]
STD = [0.229, 0.224, 0.225]
def model_fn(features, labels, mode, params):
"""Model function for CNN."""
# Subtracts the given means from ... |
import http.client
from datetime import datetime
import json
import pandas as pd
API = '<KEY>'
def str2time(strng):
return datetime.strptime(strng, '%H:%M:%S').time()
def str2date(strng):
return datetime.strptime(strng, '%Y-%m-%d').date()
def create_db_connection():
DB_USER = 'root'
DB_PASS = 'pas... |
import numpy as np
def init_weights(input_dim, output_dim):
return np.random.randn(input_dim, output_dim) #/ np.sqrt(input_dim)
class CrossEntropyLoss(object):
def loss(self, y, y_tar):
return np.mean(np.nan_to_num(-y_tar * np.log(y)), axis=1)
def loss_der(self, y, y_tar):
return np.nan_t... |
import wx
import cv2
import numpy as np
class VideoPanel(wx.Panel):
miniBuffer=None
updateTimer = None
callbacks={"onFrame": None}
frame_count=0
current_frame=0
state="play"
onUpdate=None
def __init__(self, parent):
super().__init__(parent, wx.ID_ANY, size=(320,200))
sel... |
# ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems 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.o... |
from itertools import chain
import pandas as pd
import pytz
from pandas_market_calendars.exchange_calendar_lse import LSEExchangeCalendar
def test_time_zone():
assert LSEExchangeCalendar().tz == pytz.timezone('Europe/London')
def test_2012_holidays():
# 2012/06/04 - Bank Holiday
# 2012/06/05 - Queen's... |
# Copyright (c) 2016, 2017, 2018, 2019 <NAME>.
#
# clgen 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 your option) any later version.
#
# clgen is distributed in th... |
from conftest import skipif_yask
import numpy as np
from devito import Grid, Function, TimeFunction
def test_basic_indexing():
"""
Tests packing/unpacking data in :class:`Function` objects.
"""
grid = Grid(shape=(16, 16, 16))
u = Function(name='yu3D', grid=grid, space_order=0)
# Test simple... |
"""
Migration script for tables related to dataset collections.
"""
import datetime
import logging
from sqlalchemy import (
Boolean,
Column,
DateTime,
ForeignKey,
Integer,
MetaData,
Table,
TEXT,
Unicode
)
from galaxy.model.custom_types import TrimmedString
from galaxy.model.migrat... |
import argparse
import configparser
import json
import os
import time
import uuid
from os.path import expanduser
from pathlib import Path
from typing import List
from vsw.dao import vsw_dao
import requests
from aries_cloudagent_vsw.commands import run_command
from vsw import utils
from vsw.commands import init,exit
fr... |
# ActivitySim
# See full license in LICENSE.txt.
import os.path
import logging
import pytest
import pandas as pd
from .. import tracing
from .. import inject
def close_handlers():
loggers = logging.Logger.manager.loggerDict
for name in loggers:
logger = logging.getLogger(name)
logger.handle... |
import io
from collections import OrderedDict
from functools import partial
import torch
import torch.distributed as dist
import torch.nn as nn
from inplace_abn import InPlaceABN, InPlaceABNSync, ABN
from seamseg.modules.misc import ActivatedAffine, ActivatedGroupNorm
from . import scheduler as lr_scheduler
NORM_LAY... |
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
def downsample(x, x_len, sample_rate, sample_style):
batch_size, timestep, feature_dim = x.shape
x_len = x_len // sample_rate
if sample_style == 'drop':
# Drop the unselected timesteps
... |
import torch
import cv2
import os
import numpy as np
from vision.ssd.mobilenet_v2_ssd_lite import create_mobilenetv2_ssd_lite, create_mobilenetv2_ssd_lite_predictor
from vision.utils.box_utils import get_iou_numpy
CLASS_NAMES_FILE = "models/voc-model-labels.txt"
MODEL_FILE = "models/mb2-ssd-lite-mp-0_686.pth"
VOC_PA... |
from __future__ import absolute_import
from .validator import *
class Field(object):
def __init__(self, source=None, required=False, many=False, default=None, allow_null=True):
self._source = source
self._data = None
self.data = None
self._many = many
self._errors = []
... |
from floem import *
pkt_size = 1024 #1024
class Request(Element):
def configure(self):
self.inp = Input(SizeT, "void*", "void*")
self.out = Output(SizeT, "void*", "void*")
def impl(self):
self.run_c(r'''
(size_t size, void* pkt, void* buff) = inp();
udp_message* m = (udp_message*) pkt... |
# Copyright 2011 OpenStack Foundation
# 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 requ... |
import qt
import numpy as np
import os
import shutil
import sys
import progressbar
from constants import *
def copy_script(once):
if once:
shutil.copy2('%s'%sys.argv[0],'%s/%s'%(data.get_filepath()[:-(len(data.get_filename())+1)],os.path.basename(sys.argv[0])))
fsv = qt.instruments.create('FSV', '... |
'''
Func: Get data of global-500
'''
import os
import json
from lxml import etree
import requests
import time
from get_url import get_url_global500
from company import Company
def get_data_load_file(data_json="data.json"):
company_list = []
company_json_list = []
if os.path.isfile(data_json):
try... |
#!/usr/bin/env python
import argparse
import copy
import logging
import sys
from BCBio import GFF
from Bio.SeqFeature import FeatureLocation
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
__author__ = "<NAME>"
__version__ = "0.4.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
def feat... |
import json
from pathlib import Path
from rlbot.matchconfig.loadout_config import LoadoutConfig, LoadoutPaintConfig
from rlbot.matchconfig.match_config import MatchConfig, ExtensionConfig, MutatorConfig, PlayerConfig, ScriptConfig
from rlbot.parsing.agent_config_parser import PARTICIPANT_CONFIGURATION_HEADER, PARTICIP... |
import numpy as np
from tkinter import *
import keyboard
def randdim(): # for giving random value of height and width
x = int(np.random.randint(5, 10, 1))
y = int(np.random.randint(25, 50, 1))
return x, y
l1 = [0, randdim()] # obstacle 1 [x coordinate,(dimensions)]
l2 ... |
from sklearn.metrics import coverage_error, accuracy_score
from sklearn.metrics import label_ranking_loss
from sklearn.metrics import label_ranking_average_precision_score
from sklearn.metrics import hamming_loss
from sklearn import metrics
from collections import Counter
import math
import numpy as np
def patk(predi... |
"""
Base module for handlers.
This module contains the base classes for implementing collectors, renderers, and the combination of the two: handlers.
It also provides two methods:
- `get_handler`, that will cache handlers into the `HANDLERS_CACHE` dictionary.
- `teardown`, that will teardown all the cached handlers,... |
import lungmap_utils.lungmap_sparql_queries as sparql_queries
from SPARQLWrapper import SPARQLWrapper, JSON
import os
import requests
import tempfile
import gzip
lungmap_sparql_server = "http://data.lungmap.net/sparql"
def get_probes():
sparql = SPARQLWrapper(lungmap_sparql_server)
sparql.setQuery(sparql_qu... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... |
# 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 torch
import torch.nn as nn
from fairseq import utils
from fairseq.models import register_model, register_model_architecture
from fairs... |
"""Author FredHappyface 2020.
Lib containing various image editing operations
"""
from __future__ import annotations
import glob
import os
import sys
from pathlib import Path
from layeredimage.io import (
LayeredImage,
exportFlatImage,
openLayerImage,
saveLayerImage,
)
from layeredimage.layeredimage import rende... |
# Copyright (c) 2021-2022, 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 ... |
import json
from django import forms
from django.core.files.base import ContentFile
from django.db import transaction
from django.db.models.fields.files import FieldFile
from django.utils.translation import gettext_lazy as _
from django_file_form.forms import FileFormMixin
from hypha.apply.stream_forms.fields import ... |
# This file manages the other files
# Number of bars to predict on
# Ex: If NUMBARS=4 use monday-thursday to predict friday
import pandas as pd
import time
NUMBARS = 10
TRAINBARLENGTH = 1000
TRAINSET = 'data/dataset.csv'
TESTSET = 'data/testSet.csv'
MODELS = 'data/models/'
LOGDIR = 'data/logs/'
STOCKDIR = '../Stock... |
"""
Copyright 2020 Pangea
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 os, sys, csv, json, argparse
import numpy as np
i... |
import csv
import cv2
import numpy as np
import ntpath
import time
import pickle
import sklearn
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Cropping2D, Convolution2D, Dropout
###########################... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdf as backend_pdf
# Local imports
from ising.utils.file_utils import projfile, eigenfile, load_sparse_csr
import ising.utils.operator_utils as ou
import is... |
from typing import Tuple
import base64
import io
import email
import json
import tempfile
import boto3
from botocore.exceptions import ClientError
from flask import Flask, jsonify, render_template
from config import Config
from users import (
get_config_for_user,
set_config_for_user,
renew_user_token,
... |
#!/usr/bin/env python3
import asyncio
import collections
from concurrent.futures import ProcessPoolExecutor
from contextlib import suppress
import copy
import datetime
import math
import numpy as np
import os
import random
import sys
import subprocess
import torch.multiprocessing as mp
import torch.distributed as dist... |
# Copyright 2018 DeepMind Technologies Limited.
#
# 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 ag... |
# Copyright 2016 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
#
# Unless required by applica... |
"""EnergyPlusVersion module handles finding idd paths and valid versions."""
import platform
import re
import warnings
from itertools import chain
from packaging.version import Version
from path import Path
from archetypal import settings
from archetypal.eplus_interface.exceptions import (
InvalidEnergyPlusVersi... |
#
# Copyright (c) 2019 <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ... |
import re
def le_assinatura():
'''A funcao le os valores dos tracos linguisticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos'''
print("Bem-vindo ao detector automático de COH-PIAH.")
print("Informe a assinatura típica de um aluno infectado:")
wal = float(input("Entre o ... |
import importlib
from typing import Callable
import hpman
import nevergrad as ng
import numpy as np
from hpman import L
class NgMethod(object):
"""
Get nevergrad parameter type from hpman.
"""
value = None # type: float
"""Elaborate value"""
hint = None # type: dict
"""Hints of the hy... |
#!/usr/bin/env python
"""
A generic odML parsing module.
Parses odML files and documents.
"""
import datetime
import json
import sys
import yaml
from os.path import basename
from . import xmlparser
from .dict_parser import DictWriter, DictReader
from ..info import FORMAT_VERSION
from .parser_utils import ParserExce... |
"""Helper methods for a Tetris game state"""
import random
from ._constants.template import PIECES, TEMPLATEHEIGHT, TEMPLATEWIDTH, BLANK
from ._constants.palette import PALETTE
from ._constants.dimensions import (
BOARDWIDTH,
BOARDHEIGHT,
BOXSIZE,
XMARGIN,
TOPMARGIN,
)
def level_and_fall_freq(
... |
'''
MODULE: main_ANN.py
@Author:
<NAME> [1,2]
[1]: Université Libre de Bruxelles, Aero-Thermo-Mechanics Laboratory, Bruxelles, Belgium
[2]: CRECK Modeling Lab, Department of Chemistry, Materials and Chemical Engineering, Politecnico di Milano
@Contacts:
<EMAIL>
@Additional notes:
This code is ... |
"""ASOS comparisons"""
import datetime
import calendar
import numpy as np
from matplotlib import cm
from pandas.io.sql import read_sql
from pyiem.plot.use_agg import plt
from pyiem.util import get_autoplot_context, get_dbconn
from pyiem.exceptions import NoDataFound
PDICT = {'low': 'Morning Low (midnight to 8 AM)',
... |
"""
data class for acquisitions.
"""
import numpy as np
import copy
from dataclasses import dataclass
from typing import Optional
from pulse_lib.segments.data_classes.data_generic import parent_data
@dataclass
class acquisition:
ref : Optional[str]
start: float
t_measure: float
threshold : Optional[f... |
import time
import numpy as np
import tools
import sys
import data
import tensorflow as tf
FLAGS = None
"""
This module scripts the procedure of running over episodes of training, validation and testing offline.
The data is collected from the data module.
"""
def run_episode(mode, sumvar, model, update_importance_w... |
"""Utils for metrics used in eval."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from layers import common_layers
class Metrics(object):
"""Available evaluation metrics."""
# Entries here should match the keys in METRICS_F... |
from argv.iterables import peekable
from argv.flags import parse_tokens
from argv.parsers.inferential import InferentialParser
class BooleanArgument(object):
# not much more than a named tuple
def __init__(self, names, default, boolean, positional):
# names is a list of strings, which can be anything ... |
# 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
#
# Unless required by applica... |
import argparse
import logging
import os
import gzip
import pickle
import re
from functools import partial
from multiprocessing.pool import Pool
from logrec.dataprep import parse_projects, path_to_non_eng_dicts, path_to_eng_dicts, PARSED_DIR
from logrec.dataprep.lang.dao import DAO
from logrec.dataprep.lang.langchecke... |
from pathlib import Path
import argparse
import asyncio
import contextlib
import functools
import importlib
import logging.config
import sys
import appdirs
from hat import util
from hat.gui import common
from hat.util import aio
from hat.util import json
import hat.event.client
import hat.event.common
import hat.gui.... |
# 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... |
# Authors <NAME> and <NAME>
# Version 1.0
# Date 05.2019
# import the necessary packages
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from pdf2image import convert_from_path
from PyPDF2 import PdfFileReader
from imutils import paths
import numpy as np ... |
import operator
import math
class Geo2(object):
pass
class Point2(Geo2):
def __init__(self, x, y):
self._x = x
self._y = y
def collides(self, geo2):
return geo2.collides_with_point2(self)
def touches(self, geo2):
return geo2.collides_with_point2(self, _touching=True)
def collides_with_point2(self... |
"""
Implements a network visualization in PyTorch.
WARNING: you SHOULD NOT use ".to()" or ".cuda()" in each implementation block.
"""
# import os
import torch
# import torchvision
# import torchvision.transforms as T
# import random
# import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from a4_hel... |
import numpy as np
import matplotlib.pyplot as plt
#Datos iniciales ===================
Data=np.loadtxt("ScalarGauss.txt")
nodos=np.loadtxt("MaximumNodeMap.txt")
n_nodos=len(np.where(nodos==1)[0])
n_side=int(Data.shape[0])
valor_max=0
valor_min=0 #Definiendo límites del barrido de watershed
cuenta_datos=n_side*n_side ... |
from oauth2client.file import Storage
import httplib2
import urllib
import json
from datetime import datetime, timedelta
# Your acount needs to be authorized for these requests. Get an API key and then an OAuth 2 client ID
# from console.developers.google.com, then use oauth2client to generate some credentials.
# inst... |
import argparse
import ipaddress
import logging
import os
import pathlib
import secrets
from typing import Collection, Optional
from async_service import background_trio_service, Service
from eth_keys import keys
from eth_utils import encode_hex, decode_hex
from alexandria._utils import sha256
from alexandria.abc imp... |
'''
classes.py
Module used in Snake Game 2
_Allen
'''
import pygame, random
from pygame.locals import *
# Gams speed
STARTING_FPS = 4
FPS_INCREMENT_FREQUENCY = 80
# Direction constants
DIRECTION_UP = 1
DIRECTON_DOWN = 2
DIRECTION_LEFT = 3
DIRECTION_RIGHT = 4
# World size
WORLD... |
import torch
import torch.nn as nn
from einops import rearrange
class InterlacedSparseSelfAttention(nn.Module):
def __init__(self, dim, P_h, P_w):
super().__init__()
self.Attention = Attention(dim=dim)
self.P_h = P_h
self.P_w = P_w
def forward(self, x):
# x:input features with shape [B, C, H, W]
# P_h,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.