text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python
"""An object that models the current state of the enclosure controller.
Information about various devices in the telescope enclosure.
Devices are broken up into categories, e.g. Fans, Lights.
Information about each category of devices is stored as follows:
model.catDict is a dictionary whose keys... |
#!/usr/bin/env python
"""
plot_SBOL_designs.py
Plot the design of DNA constructs using SBOL notation.
Usage:
------
python plot_SBOL_designs.py -params PARAM_FILENAME
-parts PART_FILENAME
-designs DESIGN_FILENAME
... |
# Code generated by lark_sdk_gen. DO NOT EDIT.
from pylark.lark_request import RawRequestReq, _new_method_option
from pylark import lark_type, lark_type_sheet, lark_type_approval
import attr
import typing
import io
@attr.s
class GetApprovalInstanceReq(object):
instance_code: str = attr.ib(
default="", me... |
#!/usr/bin/env python3
"""
Responsible for loading historical ASX prices and converting them into django model equivalents.
Not all data can be provided: fields which are missing are set to None. Historical prices are loaded
from google finance API using pandas_data_reader. This script is carefully written to not alter... |
"""Define Computational graph"""
import sympy as sp
from typing import List, Dict, Union
from copy import copy
from collections import defaultdict
import networkx as nx
import matplotlib.pyplot as plt
import math
from idrlnet.variable import Variables
from idrlnet.node import Node
from idrlnet.header import logger, DI... |
import torch
import argparse
import config
import logging
import os
from os.path import join
import json
from utils import io
from utils.io import Many2ManyDatasetWithAttributes
from model.seq2seq import Seq2SeqModel
from model.seq2seq_style_input import Seq2SeqModelStyleInput
from model.seq2seq_exact_length_input impo... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from numpy.testing import assert_almost_equal
from .metric import outer_cosine_similarity
class ContrastiveLoss(nn.Module):
"""
Contrastive loss
"Signature verification using a siamese time delay neural network", NIPS 1993
https:... |
import os
import math
import torch
import torch.nn as nn
import numpy as np
import torchvision.models as models
from torch.autograd import Variable
import torch.nn.functional as F
import operator
from collections import Counter
from transformers import TransfoXLConfig
from TransfoXLModel import TransfoXLModel
class ... |
#!/usr/bin/python
# Copyright: (c) 2019, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
mod... |
from __future__ import annotations
from heapq import heappop, heappush
from typing import Dict, List, Set, Tuple, Union
import itertools
from generation.structures import Point
from generation.maze import Maze, MazeCell
from generation.npc import Agent
from generation.direction import Direction
class Waypoint:
"""... |
import cmath
from itertools import zip_longest
from typing import List, Any
from scipy.special import ive, iv
import mpmath
import cmath as cm
import math as fm
import numpy as np
def pade_sqrt_coefs(n):
n_arr = np.arange(1, n+1)
a_n = 2 / (2*n + 1) * np.sin(n_arr * cm.pi / (2 * n + 1))**2
b_n = np.cos(n... |
__doc__ = """Symplectic time steppers and concepts for integrating the kinematic and dynamic equations of rod-like objects. """
import numpy as np
from elastica.timestepper._stepper_interface import (
_TimeStepper,
_LinearExponentialIntegratorMixin,
)
"""
Developer Note
--------------
For the reasons why we... |
import matplotlib
matplotlib.use('Agg')
import pyart
from netCDF4 import Dataset
import xarray
import numpy as np
from datetime import datetime, timedelta
from copy import deepcopy
import glob
import math
import dask.array as da
import time
import sys
import os
from scipy import interpolate, ndimage
from distributed im... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, bikbuk and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import json
import os
import math
import pytz
from datetime import datetime as dt
from frappe.utils import data
from frappe.utils.file_manager im... |
#!/usr/bin/env python3
import argparse
import configparser
import logging
import logging.handlers
import sys
import os.path
from time import sleep
from pv import FroniusIG
from pv import PVData
from pv import PVRestApi
from pv import PVSimulation
from pvmqtt import PVMqtt
from pvinflux import PVInflux
from pvmysql i... |
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Variable
import torch.utils.data
import torch.utils.data.distributed
import numpy as np
class View(nn.Module):
def __init__(self, size):
super(View, self).__init__()
self.size = size
def forward(... |
#-*- coding: utf-8 -*-
from .base import Base
from datetime import datetime
from django.core.validators import RegexValidator
from django.db import IntegrityError
from django.contrib.auth.models import User
from django.contrib.gis.db.models import CASCADE, DO_NOTHING
from django.contrib.gis.db.models import *
from pyt... |
import argparse
import collections
import datetime
import os
import pickle
import time
import ipdb
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from tensorboardX import SummaryWri... |
# Code for applying a pre-trained flow to a subset of the full CosmoDC2 catalog
# Smooths out unphysical discreteness in SFR and redshift
# If you don't have jax and pzflow installed, you need to run the following in a terminal:
# pip install pzflow
# pip install jax
import jax.numpy as np
import matplotlib.pyplot as... |
"""
Handlers for some basic commands including: /start, /list, /help.
Plus handlers for when user types in 'thank you' or a random message.
"""
import logging
from aiogram import types
from aiogram.utils.deep_linking import decode_payload
from aiogram.utils.emoji import emojize
from loader import dp, teams, users
fr... |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# coding: utf-8
# In[1]:
get_ipython().system('pip install numpy')
get_ipython().system('pip install h5py')
get_ipython().system('pip install pandas')
get_ipython().system('pip install afs2-datasource')
get_ipython().system('pip install nest_asyncio')
get_ipython().system('pip install networkx')
get_ipython().syste... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests related to data export of pppipam.AddressSpace."""
import ipaddress
import unittest
from pppipam.pppipam import AddressSpace
class AddressSpace_default_export_TestCase(unittest.TestCase):
"""Tests related to AddressSpace's data export."""
def setUp(s... |
import depthai
from depthai_helpers.calibration_utils import *
from depthai_helpers import utils
import argparse
from argparse import ArgumentParser
import time
import numpy as np
import os
from pathlib import Path
import shutil
import consts.resource_paths
import json
use_cv = True
try:
import cv2
except ImportEr... |
"""
Controle de cotas de disco. A ACME Inc., uma organização com mais de 1500 funcionários, está tendo problemas de espaço em disco no seu servidor de arquivos.
Para tentar resolver este problema, o Administrador de Rede precisa saber qual o espaço em disco ocupado pelas contas dos usuários, e identificar
os usuários ... |
import os
import numpy as np
import math
import torch
import torch.nn.functional as F
import glob
# Gaussian blur kernel
def get_gaussian_kernel(device="cpu"):
kernel = np.array([
[1, 4, 6, 4, 1],
[4, 16, 24, 16, 4],
[6, 24, 36, 24, 6],
[4, 16, 24, 16, 4],
[1, 4, 6, 4, 1]], ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 21 11:03:10 2020
@author: sergio.lordano
"""
import numpy as np
from scipy import ndimage
def read_shadow_beam(beam, x_column_index=1, y_column_index=3, nbins_x=100, nbins_y=100, nolost = 1, ref = 23, zeroPadding=0, gaussian_filter=0):
"""
... |
#!/usr/bin/env python3
"""
Plots jump rates against parameters.
Usage:
jump_rates.py -h | --help
jump_rates.py lambda [<index>] [options]
jump_rates.py theta [<index>] [options]
jump_rates.py check [options]
Options:
-h --help Show this screen.
--length=<val> Vertical v... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def series_segmentation(data, stepsize=1):
return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)
def sine(length, freq=0.04, coef=1.5, offset=0.0, noise_amp=0.05):
# timestamp = np.linspace(0, 10, length)
timestamp = np.ar... |
from itertools import count
from math import floor, isinf
from typing import Optional, Tuple
from ..constant.colors import *
from ..constant.main import (
DUNGEON_EXP, SKILL_EXP, SKILL_LIMITS, PET_EXP_DIFF, KILL_LEVELS,
)
from ..constant.util import Number
from .io import *
from .util import format_number, format... |
import sys
sys.path.append('../')
from assignment2.layers import softmax, cross_entropy_loss
import numpy as np
def l2_regularization(W, reg_strength):
'''
Computes L2 regularization loss on weights and its gradient
Arguments:
W, np array - weights
reg_strength - float value
Returns:
... |
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def df_is_null(df):
"""Checks if the data frame is null and returns a print statement if null."""
if df.shape[0... |
# Copyright (c) <NAME>
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from collections import OrderedDict
import itertools
import json
import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional
... |
# coding=utf-8
import os
import numpy as np
import matplotlib.pyplot as plt
from example.cbnu.utils import get_interval
from scipy.io import loadmat
from scipy.signal import find_peaks
from sklearn.cluster import k_means
import pandas as pd
import seaborn as sns
sns.set()
num_trials = 40
num_delays = 11
step_size_del... |
import numpy as np
from eb_gridmaker.utils import aux, physics, multiproc
from eb_gridmaker import dtb, config
from elisa import BinarySystem, settings, Observer
from elisa.base.error import LimbDarkeningError, AtmosphereError
def basic_param_eval(params, crit_potentials=None, omega1=None, omega2=None):
"""
... |
"""
base lightVolumes
"""
import math
import random
from PySide2 import QtGui, QtCore, QtWidgets
from PySide2.QtCore import QPoint
from PySide2.QtGui import QVector2D, QPen, QColor, QPainterPath
DEBUG = False
class Line:
def __init__(self, v0, v1):
self.v0 = v0
self.v1 = v1
def paint(self, ... |
from pygame import*
class GameSprite(sprite.Sprite):
def __init__(self, player_image, player_x, player_y, player_speed_y):
super().__init__()
self.image = transform.scale(image.load(player_image), (65, 115))
self.y_speed = player_speed_y
self.rect = self.image.get_rect()
... |
import datetime
import pytest
# from zconnect.testutils.factories import ModelBaseFactory
from zconnect.testutils.factories import (
BilledOrganizationFactory, BillFactory, BillGeneratorFactory, DeviceFactory,
DeviceSensorFactory, ProductFactory, TimeSeriesDataFactory)
from zconnect.testutils.util import week... |
# -*- coding: utf8 -*-
#
# Author: <NAME> <<EMAIL>>, <NAME>
#
# Support function of the NLP and spellchecker of the main application
# Function: Main controller of input restrictions - different methods for different game roles (guesser, describer)
import pandas as pd
import pickle
import nltk
import re
import string
... |
"""
Author: <NAME>
Organization: Phillips Lab, Institute of Ecology and Evolution,
University of Oregon
"""
import csv
import random
import datetime
import numpy as np
import pandas as pd
# import plotly.io as pio
import plotly.graph_objects as go
# pio.kaleido.scope.mathjax = None
from exp_mixture_mo... |
# -*- coding: utf-8; -*-
import sys
import numpy as np
import cv2
from PIL import Image
import data
import math
# 画像を表示する。
# キーを押すか、ウィンドウを閉じるまで待つ。
def show(image, debugFlag):
if not debugFlag:
return
title = 'image'
cv2.imshow(title, image)
while True:
if cv2.waitKey(100) != -1:
... |
"""
DNF plugin for getting the Python 3 porting status
Put this in your DNF plugin directory, then run:
$ dnf --enable=rawhide --enable=rawhide-source py3query -o fedora.json
This will give you a file "fedora.json" with information for portingdb.
"""
from __future__ import print_function
import operator
import... |
import serial
import sys
import time
import math
from SimpleHDLC import HDLC
from SimpleTCP import SimpleTCP
import logging
import json
import os
import asyncio
def commandLineTestStart():
# Get args passed from build/test script
try:
testname = ' '.join(sys.argv[1:2])
testLoops = int(' '.join(... |
from __future__ import print_function
from __future__ import division
from builtins import range
from past.utils import old_div
from future.utils import raise_
import os.path
import sys
from anuga.utilities.system_tools import get_pathname_from_package
from anuga.geometry.polygon_function import Polygon_function
from... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import random
import time
import tensorflow as tf
from sklearn import metrics
from sklearn.cross_validation import train_test_split
from tqdm import tqdm
from utils import *
# In[2]:
trainset = sklearn.datasets.load_files(container_path="data", encoding="... |
#
# compiler.py - Building new words/types for our language.
#
from typing import Dict, List, Tuple, Callable, Any, Optional, Sequence
from dataclasses import dataclass
from af_types import *
from af_types.af_any import op_swap, op_stack
def compilation_word_handler(c: AF_Continuation) -> bool:
#print("co... |
import numpy as np
from scipy import interpolate,linalg
def cumsummedian(a,weights=None):
"""
Compute the weighted median.
Returns the median of the array elements.
Parameters
----------
a : array_like, shape (n, )
Input array or object that can be converted to an array.
weights ... |
#!/usr/bin/env python3
# Common Localizations
# This file is released into the public domain.
# The localizations are licensed under the MIT License, from http://goo.gl/fhnw1t
__doc__ = """Common Localizations.
Creates localization files from the `Common Localization project <http://goo.gl/fhnw1t>`_.
Usage:
commonl... |
from image_geometry import PinholeCameraModel
import cv2
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image, PointField, CameraInfo
import numpy as np
import tf
import sensor_msgs.point_cloud2
import message_filters # to synchronize topic subscription
import rospy
from sensor_msgs.msg impo... |
import os
import argparse
import json
import html
import re
import sys
import boto3
import srt
import jaconv
from bs4 import BeautifulSoup
from count_chars import count_meaty_chars, remove_spaces_punctuation
# Subtitles will be chunked at gaps of this time or greater, even if they wouldn't otherwise need to
# be bec... |
import os
import re
def _get_docker_image_name(compiler: str, version):
OWNER = 'conanio'
version = str(version)
image_version = version.replace(".", "")
if compiler == "clang" and version == "7.0":
image_version = '7'
return "{}/{}{}".format(OWNER, compiler, image_version)
def _create... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 6 13:01:32 2019
@author: abibeka
Purpose: Compare VISSIM Volumes with collected volumes. Calc GEH
"""
#0.0 Housekeeping. Clear variable space
from IPython import get_ipython #run magic commands
ipython = get_ipython()
ipython.magic("reset -f")
ipython = get_ipython()
... |
import os
import numpy as np
import open3d as o3d
import glob
flip_transform = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]
def robust_kernel_fn(alpha, c):
if alpha == None:
# print('Binary truncation loss')
return lambda x: (np.abs(x) < c).astype(float)
if alpha == 2:
#... |
from django.shortcuts import render, redirect
from django import forms
from django.db.models import Q
from residents.models import Resident
from .forms import FormId, FormIdigent, FormScholar, FormBurial, FormBusiness, FormClearance
from .models import IDForm, IndigencyForm, ClearanceForm, ScholarshipForm,BusinessPermi... |
# This file is part of ranger, the console file manager.
# License: GNU GPL version 3, see the file "AUTHORS" for details.
CONTAINER_EXTENSIONS = ('7z', 'ace', 'ar', 'arc', 'bz', 'bz2', 'cab', 'cpio',
'cpt', 'deb', 'dgc', 'dmg', 'gz', 'iso', 'jar', 'msi', 'pkg', 'rar',
'shar', 'tar', 'tbz', 'tgz', 'xar', 'xpi'... |
from Agent import Agent
from Illustrator import Illustrator
import random
import numpy as np
from collections import defaultdict
class Gridworld(object):
def __init__(self,walls, treasure, snake_pit, whisky = None, size = 18, alfa=0.5, gamma = 1):
self.size = size
self.walls = walls
self.t... |
# Some general utilities that are used in multiple places
from contextlib import contextmanager
from enum import IntEnum
from functools import reduce
import math
import sys
import matplotlib.transforms as mtransforms
import numpy as np
from PySide2.QtCore import QObject, QSignalBlocker
from PySide2.QtWidgets import ... |
import copy
from filelock import FileLock
try:
import ujson as json
except ModuleNotFoundError:
import json
import torch.multiprocessing as mp
import numpy as np
import os
from pathlib import Path
from scipy import stats
import time
import torch
from torch import nn
from typing import *
from ...env import goos... |
"""
@author <NAME> (github.com/CorentinGoet)
"""
from pretty_printer_pkg.visitor import Visitor
class PrettyPrinter(Visitor):
"""
PrettyPrinter class based on the Visitor pattern.
The pretty printer visits the AST to print the given source code with the correct indentation and formatting.
"""
d... |
# Copyright 2021 The Petuum 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 applicabl... |
# Import package
import numpy as np
import tools
def setup():
class par: pass
# Demograhpics
par.T = 200
par.Tr = 200 # Retirement age, no retirement if TR=T
par.age_min = 25 # Only relevant for figures
# Preferences
par.rho = 2
par.beta = 0.96
# Income parameters
par.G = 1.0... |
"""
Copyright 2013 Rackspace
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
dist... |
import inspect
from typing import List, Dict, Tuple
import numpy as np
import pytorch_lightning as pl
import torch
from sklearn.metrics import mean_squared_error
from torch import nn
from torch.nn import functional as F
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch_geometric.data import Batch
from ... |
from sqlalchemy import desc
import time
from anchore_engine import db
import anchore_engine.db.db_catalog_image_docker
from anchore_engine.db import CatalogImage, CatalogImageDocker
from anchore_engine.subsys import logger
def add_record(input_image_record, session=None):
if not session:
session = db.Sess... |
from __future__ import print_function, unicode_literals
import datetime
import calendar
from flask import render_template, request, send_file, Response, url_for
from functools import wraps, partial
from weblab.core.web import weblab_api
from weblab.core.db import UsesQueryParams
def check_credentials(func):
@wraps... |
# Author: <NAME> <<EMAIL>>,
# License: ALv2
# Date created: 2016-11-25
import sys
sys.path.append("../code")
import pyplearnr as ppl
import pandas as pd
import itertools
import unittest
class AugmentedTestCase(unittest.TestCase):
"""
unittest.TestCase class with an extra helper method for comparing expec... |
import inspect
import re
from operator import attrgetter
import sphinx.ext.autodoc as autodoc
from docutils import nodes
from sphinx.domains.python import PythonDomain, PyObject, TypedField, GroupedField, l_, _
from sphinx.ext.autosummary import Autosummary, autosummary_table, ViewList, \
get_import_prefixes_from_e... |
# Copyright (c) 2021 <NAME>
# =======================================================================
# Distributed under the MIT License.
# (See accompanying file LICENSE or copy at
# http://opensource.org/licenses/MIT)
# =======================================================================
"""geometry things in... |
"""This script splits up the papers such that the datasets in train, dev, and test are disjoint.
Note: It assumes that the old splits and their file structure remain the same as before"""
import os
import json
from collections import defaultdict
import numpy as np
import random
def build_dataset_id_to_papers(old_t... |
import os
import glob
import argparse
import logging
import logging.config
import coloredlogs
import numpy as np
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from model import PoseNet
from dataset import H36M_Dataset
from evaluate import h36m_evaluate
config = {
"exp_root": "./log... |
import os
import json
import time
import hashlib
import argparse
import traceback
import logging
import web3
import eth_account
from eth import constants
from eth.chains.mainnet import MainnetChain
from eth.db.atomic import AtomicDB
from eth_utils import to_wei, encode_hex
from eth_utils import decode_hex, encode_hex
... |
"""
Solves the amplitude equations of Coupled Cluster Doubles
"""
import numpy as np
import sys
sys.path.append("../../project1/python/")
from fci import FCI
from fci import cartesian_product
from numpy import einsum
from itertools import product
from hfock import solve_hfock
def es(*args, **kwargs):
return ein... |
# -*- coding: utf-8 -*-
"""
Parse contacts evaluated by gmx hbonds
Usage:
md_davis contacts [options] (--file <.xpm>)
(--index <.ndx>)
(--structure <.pdb/.gro>)
(--group <string>)
md_davis contacts -h | --help
Options:
-f... |
from textwrap import dedent
import pytest
from parso import load_grammar
from parso import ParserSyntaxError
from parso.pgen2 import generate_grammar
from parso.python import tokenize
def _parse(code, version=None):
code = dedent(code) + "\n\n"
grammar = load_grammar(version=version)
return grammar.pars... |
# -*- coding: utf8 -*-
from __future__ import unicode_literals
import logging
from threading import Thread, Event
import time
import os
import subprocess
from tqdm import tqdm
import re
import signal
import shutil
from conf import Conf
from tools.workspace import Workspace
from tools.utils import extends, timeFormat... |
# ----------------------------------------------------------------------
# Copyright (C) 2013 <NAME> <<EMAIL>>
# Copyright (C) 2015 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published ... |
import sys
sys.path.append('../')
import unittest
from bayesian import Bayes, classify, classify_normal
class TestBayes(unittest.TestCase):
def test_empty_constructor(self):
with self.assertRaises(ValueError):
b = Bayes()
def test_list_constructor(self):
self.assertEqual(Bayes([]... |
import tensorflow as tf
import tensorflow.contrib.slim as slim
import common.utils as utils
import factory.losses_funcs as losses_funcs
import matting_nets.deeplab_v3plus as deeplab
from matting_nets import mmnet
from factory.base import CNNModel
from factory.matting_converter import ProbConverter
_available_nets = ... |
#!/usr/bin/env python
# Run an ultrasound session.
# This version works well with ultracomm 0.2.1-alpha.
import os, os.path, sys, subprocess, shutil
import win32api, win32con, win32file
from datetime import datetime
from dateutil.tz import tzlocal
import getopt
import random
#import ultratils.disk_streamer
import ti... |
#!/usr/bin/env python3
# Do machine learning depending mode train/test/eval
# Anyway, this work was inspired by a paper published in Nature Physics 2017;
# "Machine learning phases of matter" by <NAME> & <NAME>
# Nature Physics volume 13, pages 431–434 (2017)
# https://www.nature.com/articles/nphys4035
####... |
import numpy as np
import pandas as pd
from hyperopt import hp, fmin, tpe, STATUS_OK, STATUS_FAIL, Trials, space_eval
from acheron.workflows import supervised_model
def PHACs_next_top_model(trials):
"""
input: hyperopt trials object
returns the trained model with the lowest loss
"""
trials = [i f... |
# coding=utf-8
import tensorflow as tf
import numpy as np
import pickle
import random
import os
import matplotlib.pyplot as plt
# defines the size of the batch.
BATCH_SIZE = 100
# one channel in our grayscale images.
NUM_CHANNELS = 1
# The random seed that defines initialization.
SEED = 42223
IMAGE_SIZE = 48
NUM_LA... |
import jq
from copy import deepcopy
from haystack.document_store import ElasticsearchDocumentStore
from haystack.schema import BaseComponent, MultiLabel
from typing import List, Optional, Any # , Dict
from haystack.schema import Document
import numpy as np
import logging
from elasticsearch.exceptions import Reque... |
import numpy as np
import json
import copy
import re
import os
def capitalize(s:str) -> str:
"""
make first letter of s upper case
:param s: string
:return: s with first letter capitalized
"""
return s[0].upper()+s[1:]
def space_underscores(s):
"""
replace underscores with spaces
s... |
import os
import time
import numpy as np
import cv2
from PIL import Image
import glob
import logging
import pyrealsense2 as rs
from typing import Optional
class BaseCamera:
def run_threaded(self):
return self.frame
class CSICamera(BaseCamera):
'''
Camera for Jetson Nano IMX219 based camera
C... |
from sdautoencoder import SDAutoencoder, get_batch_generator, merge_generators, stopwatch, DEBUG
import tensorflow as tf
import numpy as np
# X_TRAIN_PATH = "../data/x_train_transformed_SAM_2.csv"
# Y_TRAIN_PATH = "../data/splits/OPYTrainSAM.csv"
# X_TEST_PATH = "../data/x_test_transformed_SAM_2.csv"
# Y_TEST_PATH = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# tesslightcurves.py - <NAME> (<EMAIL>) - Nov 2019
# License: MIT - see the LICENSE file for the full text.
'''
Useful tools for acquiring TESS light-curves. This module contains a number of
non-standard dependencies, including lightkurve, eleanor, and astroquery.
Light-... |
#!/usr/bin/env python3
import sys
import re
import copy
from pprint import pprint
INPUTS = ['d24-input.txt', 'd24-input-example.txt', 'd24-input-test.txt']
DEBUG = False
INPUT = INPUTS[2] if DEBUG else INPUTS[0]
section_re = re.compile('([\w\s]+):')
units_re = re.compile(r'(?P<count>\d+) units .* (?P<hp>\d+) hit poin... |
import csv
import os
import requests
import json
import os, shutil
import datetime
def show_account(url):
account = requests.get(url)
account_body = json.loads(account.text)
data = (account_body["response"])
account_info = data["accounts"][0]
print("Here is a summary of your spending in the account:... |
import flask_dance.contrib.google as google_dance
import flask_dance.contrib.azure as azure_dance
import flask_dance.contrib.github as github_dance
import flask_security
import logging
import flask
import flask_dance.consumer
import fra_back.app_init
import oauthlib.oauth2.rfc6749.errors
import fra_back.models
import f... |
import torch.nn as nn
class _BnReluConv(nn.Module):
def __init__(self, in_filters, nb_filters, fw, fh, subsample=1):
super(_BnReluConv, self).__init__()
self.model = nn.Sequential(
nn.BatchNorm2d(in_filters, eps=1e-3),
nn.LeakyReLU(0.2),
nn.Conv2d(
... |
import numpy as np
from sklearn.metrics.classification import accuracy_score
import argparse
import keras
from keras.layers.pooling import GlobalMaxPooling2D, GlobalAveragePooling2D, MaxPooling2D, AveragePooling2D
from keras.layers import Dense, Dropout, Conv2D, Flatten, Activation, BatchNormalization, Add
from k... |
from generator.actions import Actions
import random
import string
import struct
import StringIO
#define MAX_MSGS 5
#define MAX_RCPT 16
#define MAX_ADDR_LEN 32
#define MAX_DATA 512
#define MAX_USER_LEN 64
#define MAX_PASS_LEN 64
#define MAX_LINE 64
def random_word(max_size=10, min_size=2):
characters = string.lett... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Base class for activities. Activities have a parameters panel, handle events and
can make requests to the robot controller.
Author: tennessee
Created on: 2017-03-21
Copyright 2017, <NAME>.
"""
import logging
import sys
if sys.version_info[0] < 3:
import Tkinter a... |
import numpy as np
from numpy import linalg
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import SGD, lr_scheduler, Adam
from sklearn.base import ClassifierMixin
from utilize.test import evaluate_model
alpha = 0.0001
class MLP(nn.Module):
# MLP model with two hidden ... |
from sprites_env import *
from utility.json_config_uploader import *
from tkinter import *
import os
import codecs
import webbrowser
# TODO: Случайное перемещение монстров
class MainMenuWindow:
"""
Окно запуска программы.
С ним связаны следующие события:
- Начало игры, т.е. создание или загрузк... |
import time
import typing
from pathlib import Path
import mlflow
import mlflow.sklearn
import numpy
import numpy as np
import pandas as pd
from dagster import (Any, Bool, Enum, EnumValue, Field, Output,
OutputDefinition, PresetDefinition,
PythonObjectDagsterType, Selector, Str... |
#!/usr/bin/python3
import sys
import os
import argparse
import numpy as np
def get_candidates(bedgraph, cutoff=10, p=False):
result=[]
with open(bedgraph) as f:
stack=[]
for l in f.readlines():
pos = l.strip().split('\t')
if float(pos[2]) >= cutoff:
sta... |
# Skinny-128-384+ constant time Python Implementation
# Copyright 2020:
# <NAME> <<EMAIL>>
# This program 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 2 of the
# License, or (at... |
import sys
from math import sqrt, atan2, pi
import numpy as np
import imageio
import skimage.color as sk
import matplotlib.pyplot as plt
def canny_edge_detector(input_image):
input_pixels = input_image.load()
width = input_image.width
height = input_image.height
# Transform the image to grayscale
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.