text stringlengths 3.07k 22.1k |
|---|
"""
.. module:: _exchange
:platform: Unix, Windows
:synopsis: Helper functions for exchange module
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import math
from . import abstract, NURBS, multi, compatibility, utilities
# Initialize an empty __all__ for controlling imports
__all__ = []
def process_template(file... |
import sys
import os
from subprocess import *
from threading import Thread
if(sys.hexversion < 0x03000000):
import Queue
else:
import queue as Queue
#global parameters
fold = 5
c_begin, c_end, c_step = -5, 15, 2
g_begin, g_end, g_step = 3, -15, -2
nr_local_worker = 1
class WorkerStopToken: # used to notify the ... |
import os
import subprocess
import time
import yaml
import json
import re
import boto3
from config import DEFAULT_CFG as push_cfg
import shlex
from dotenv import load_dotenv
# create repository
def create_ecr_repo(cfg):
obj = {}
for service_name, service in cfg.services.items():
if "build" in servic... |
# Copyright (c) 2017 Cloudbase Solutions Srl
#
# 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 ... |
"""Do comparisons involving abstract values."""
from pytype import abstract
from pytype import abstract_utils
from pytype import class_mixin
from pytype import mixin
from pytype.pytd import slots
# Equality classes.
NUMERIC = frozenset({"builtins.bool", "builtins.int", "builtins.float",
"builtins... |
from robocorp_ls_core.unittest_tools.cases_fixture import CasesFixture
import weakref
from robocorp_ls_core.protocols import IConfigProvider
import os.path
import io
def test_resolve_interpreter_relocate_robot_root(
config_provider: IConfigProvider, rcc_conda_installed, datadir
) -> None:
from robocorp_code.p... |
"""Handlers for the app's external root, ``/ltdproxy/``."""
import posixpath
from typing import Optional, Union
from urllib.parse import urlencode, urlparse
import httpx
from authlib.integrations.starlette_client import OAuthError
from fastapi import APIRouter, Depends, HTTPException
from safir.dependencies.http_clie... |
# ---------------------------------------------------------------------
# Project "Track 3D-Objects Over Time"
# Copyright (C) 2020, Dr. <NAME> / Dr. <NAME>.
#
# Purpose of this file : Classes for sensor and measurement
#
# You should have received a copy of the Udacity license together with this program.
#
# https://w... |
"""ARRAY-BASED CONTAINERS
An array is an index-based collection of elements. An array is stored
contiguously in memory. As a result, arrays have better "cache" locality
compared to linked lists.
For some linked list-based counterparts, please see "linkedlist" module.
class | insertion | iterate | peek | removal
... |
# GUI for RePixelator v1.0.1
# Works on python 3.4 or higher
try:
import wx
from wx.adv import AboutDialogInfo, GenericAboutBox
except:
print('wxpython>=4.0.0 not installed. Type "pip install wxpython" to install')
exit()
try:
from .repixelator import rePixelateFile
from .repixelat... |
# -*- coding: utf-8 -*-
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
# Third-party
import numpy as np
import scipy.ndimage as ndimage
from astropy.io import fits
from astropy.convolution import Gaussian2DKernel
from astropy.utils.misc import isiterable
import sep
__all__ = [
'meas_back',
'detect_sources',
'make_seg_mask',
'make_obj_mask',
'elliptical_mask',
'ma... |
# Import functions and objects the microservice needs.
# - Flask is the top-level application. You implement the application by adding methods to it.
# - Response enables creating well-formed HTTP/REST responses.
# - requests enables accessing the elements of an incoming HTTP/REST request.
#
import json
# Setup and us... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import copy
from caffe2.proto import caffe2_pb2
from caffe2.python import core
import caffe2.python._import_c_extension as C
def rewrite_init_net_simple(net):
for o... |
#!/usr/bin/env python3
# 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 os
import unittest
import torch
import parlai.nn.lr_scheduler as lr_scheduler
import parlai.utils.testing as test... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import tensorflow as tf
import numpy as np
import os
from optparse import OptionParser
import logging
import subprocess
import scipy
import random
import sys
sys.path.append(os.path.join(os.getcwd(), 'utils'))
from pixrefer import PixReferNet
from voicepuppet.bfmnet.bfm... |
import math
import argparse
config: dict
feature_names: list
class ID3:
class Node:
def __init__(self, node_feature):
self.node_feature = node_feature
self.children = {}
def add_child(self, transition, child_node):
self.children[transition] = child_node
c... |
import pytest
from salamanca import cli
from salamanca.currency import Translator
from utils import assert_almost_equal
US_AUT_2010 = 0.7543089901059788 # changed recently in world bank dataset
CAN_US_2010 = 1.0301127351759798 # changed recently in world bank dataset
MER_PPP_AUT_2010 = 1.1155070936906801 # changed... |
import csv
import re
import sys
import xmltodict
lib_body = """EESchema-LIBRARY Version 2.3
#encoding utf-8
#
# %(description)s
#
DEF %(partname)s U 0 40 Y Y 1 F N
F0 "U" 0 0 60 H V C CNN
F1 "%(partname)s" %(labelX)d %(labelY)d 60 H V L CNN
F2 "" 0 0 60 H V C CNN
F3 "" 0 0 60 H V C CNN
$FPLIST
%(fplist)s$ENDFPLIST
DRA... |
from collections import OrderedDict
import numpy as np
from rlkit.envs.ant import AntEnv
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.core.serializable import Serializable
from rlkit.core import logger as default_logger
from rlkit.samplers.util import get_stat_in_paths
from rlkit.torch.tdm.e... |
"""
(C) Copyright 2019 IBM Corp.
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
... |
#
# Collective Knowledge (index of CK repositories)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: <NAME>
#
cfg={} # Will be updated by CK (meta description of this module)
work={} # Will be updated by CK (temporal data)
ck=None # Will be updated by CK (initia... |
import json
import subprocess
import hashlib
import os.path
import shlex
import gevent
from django.db import models
from django_mysql.models import JSONField, Model
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
f... |
#!/usr/bin/env python3
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script used to generate the tests definitions for Web App testing framework.
See the README.md file in this directory for more infor... |
#!/usr/bin/env python3
"""
@author: valengo
"""
from enum import Enum, unique
@unique
class Strings(Enum):
target = 'Path to file in which sequencing amplicons are listed'
region = 'Limit target definition to a given region. It should be in the form: chr1:10000-90000'
outdir = 'Output directory name'
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2018 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... |
import torch
import torch.nn as nn
import signatory
def stack(tensors, dim):
# Small efficiency boost in the common case that there's only one tensor to stack
if len(tensors) == 1:
return tensors[0].unsqueeze(dim)
else:
return torch.stack(tensors, dim)
def become_constant_trick(x, length... |
"""batemansolvers
Three solvers are enabled here to solve the Bateman equations:
(1) ODEINT solver
-----------------
Integrate a system of ordinary differential equations with RK45 adaptive time
mesh scheme
(2) EXPM solver
---------------
Compute the matrix exponential using Pade approximation
(3) CRAM solver
------... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 3 12:13:38 2020
@author: kookoo2052
Helper Functions
"""
#%% Astrometry query
def run_ast(outfile):
try_again = True
submission_id = None
while try_again:
try:
if not submission_id:
wcs_header =... |
from gym_combat.envs.Common.constants import *
from gym_combat.envs.DQN.DQN_constants import *
import os
import time
import random
from collections import deque
import tensorflow as tf
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Activation, Flatten
from... |
"""Update indexes to use new naming conventions
Revision ID: 03e98a49599c
Revises: c0fb4e374830
Create Date: 2020-07-07 13:06:06.204241
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "03e98a49599c"
down_revision = "<KEY>"
branch_labels = None
depends_on = None
def upgrade():
# ... |
"""
In this script we simulate triple evolution.
See papers:
http://arxiv.org/abs/1004.2506
and
http://arxiv.org/abs/1101.0399
"""
import numpy
import sys
# import time
from amuse.units import nbody_system, units
from amuse.units.quantities import AdaptingVectorQuantity
from amuse.datamodel import Particles
from amu... |
from lark import Lark
from lark import Transformer
import os
import sys
import time
from circuit import *
# verilog grammer
vlog_parser = Lark(r"""
netlist : module+
module : module_decl statement_list ENDMODULE
statement_list : statement+
?statement : statement SEMCOLON+ | always_decl | wire_decl |... |
import csv
import matplotlib.pyplot as plt
import numpy as np
import os
import tensorflow as tf
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('datafile',
'data/all.txt',
... |
################################################################################
# vector.py #
# basic vector classes #
# ... |
from itertools import islice
import shutil
import sys
import os
import glob
import numpy as np
import argparse
from msm_pele.AdaptivePELE.utilities import utilities
from msm_pele.AdaptivePELE.freeEnergies import cluster, extractCoords
from msm_pele.AdaptivePELE.analysis import splitTrajectory
import msm_pele.constants ... |
import argparse
import os
import uuid
from tqdm.auto import tqdm
import arrow
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data.dataset import random_split
from llp_vat.lib.llp import (BagMiniBatch, load_llp_datase... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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 ... |
import tempfile
import shutil
import os
import sys
import posixpath
from StringIO import StringIO
from django.test import TestCase
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management import call_command
from django.db.models.loading import load_app
from ... |
from ..CodeGenerator import CodeGenerator as Base
from spike.compiler.naming import *
SIZEOF_OBJ_PTR = 4
SIZEOF_CONTEXT_HEADER = 16*SIZEOF_OBJ_PTR
OFFSETOF_ARGUMENT_COUNT = 3*SIZEOF_OBJ_PTR
OFFSETOF_STACK_BASE = 14*SIZEOF_OBJ_PTR
# registers
eax = "%eax"
ebx = "%ebx"
ecx = "%ecx"
edx = "%edx"
esi = "%esi"
edi = ... |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2018-2020 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... |
from __future__ import print_function, division
from builtins import range, input
import numpy as np
import keras.backend as K
import matplotlib.pyplot as plt
import re
import tarfile
from keras.models import Model
from keras.layers import Dense, Embedding, Input, Lambda, Reshape, add, dot, Activation
from... |
# File: exp.py
# Author: raycp
# Date: 2019-05-20
# Description: exp for babyheap
from pwn import *
from pwn_debug.pwn_debug import *
from pwn_debug.IO_FILE_plus import *
pdbg=pwn_debug("babyheap")
pdbg.context.terminal=['tmux', 'splitw', '-h']
pdbg.local("./libc-2.23.so")
pdbg.debug("2.23")
pdbg.remote('172.16.31.1... |
# Lint as: python3
"""Transformer encoder implementation in JAX based on official TF model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import REDACTED
from __future__ import print_function
from typing import List
from absl import flags
from flax import nn
from flax.train... |
import socket
import threading
from tun import Tunnel
import argparse
from struct import *
from scapy.all import *
import os
from cipher import Cipher
from util import run
IS_SERVER = True
MTU = 1500
TUNNEL_ADDRESS = '10.10.0.1'
ENABLE_CRYPTO = True
# DEBUG Switch
ENABLE_LOG = False
class TCP:
def __init__(self... |
import os
import shutil
from abc import ABC
from typing import Dict, List
from appapy.common import shell
from appapy.common.cli import *
from appapy.common.constants import *
from appapy.common.env import get_home
from appapy.templating.args import Args
from appapy.templating.choices import ChoiceCollections
from app... |
import csv
import xlrd
import xlsxwriter
import re
import datetime
import common
import os
INPUT_FILE = "finance_old.xls"
OUTPUT_FILE = os.path.join(common.OUTPUT_FOLDER, 'financial_plans')
VARIABLES_FILE = 'sheet1.csv'
DATE_FILE = "finance_date.txt"
DIGITS_ROW_NUMBER = 6
STARTING_ROW = 7
SHEET_NUMBER = 1
DATE_RE = re... |
"""
Neural networks for semi-supervised variational autoencoder (VAE-SSL) model
The method implemented here is described in:
1. <NAME>, <NAME>, <NAME>, <NAME>, "Semi-supervised
source localization in reverberant environments," IEEE Access, Vol. 9, 2021.
DOI: 10.1109/ACCESS.2021.3087697
If you find this code usefult f... |
from __future__ import (absolute_import, division, print_function)
import base64
import io
import json
import math
import os
import struct
import tempfile
import zlib
from contextlib import contextmanager
import copy
import uuid
import collections
import numpy as np
from six import binary_type, text_type
from six.mo... |
import cv2
import numpy as np
from keras.models import load_model
from statistics import mode
from utils.datasets import get_labels
# from utils.inference import detect_faces
from utils.inference import draw_text
from utils.inference import draw_bounding_box
from utils.inference import apply_offsets
from utils.inferenc... |
"""resources.py."""
import functools
import html.parser
import re
import sys
import unicodedata
from typing import Any, Dict, Pattern
class HTMLTextExtractor(html.parser.HTMLParser):
"""Simple subclass of :class:`html.parser.HTMLParser`.
Collects data elements (non-tag, -comment, -pi, etc. elements)
fed... |
"""The Blueprint targets file format."""
import json
from dataclasses import asdict, dataclass, field as dc_field
from functools import lru_cache
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from foundation.geometry import BBox
from .extraction import Extraction, Field
from .instantiate i... |
from abbreviations import correct_abbreviations
from results_tools import sort_dict
def process_completed_rounds(soup,rounds_completed,par,output_dir):
'''
Go through the completed round scores and write to output files.
If rounds have already been written, check to verify the scores are still the same.
... |
# -*- coding: utf-8 -*-
from omodok_block import Block
from omodok_next_block import next_block
from omodok_wallet import Wallet,addressFn
from omodok_P2PKH import digitalSigFn,bin2hexOneFn,verifyFn
from urllib.parse import urlparse
from collections import OrderedDict as OD
import json
import time
import hashl... |
# coding: utf-8
from __future__ import division
import sys
import os
import codecs
from optparse import OptionParser
from utilities import *
import models
import yaml
import theano
import theano.tensor as T
import numpy as np
def restore_unsequenced_test_data(proscript_data, vocabulary_dict, leveler_dict, predict_func... |
from gui.creator import checkbox_fn_creator, train_fn_creator, write_bot_config, entry_int_fn_creator
from tkinter import StringVar, OptionMenu, Frame, Label, Entry, N, W
import webbrowser
def integer_entry_validate_cmd_creator(app, attr_name, def_value=0):
def validate_cmd(value, action_type):
if actio... |
"""
TODO intro and info here
Todo:
Implement img.close() and see the effects on memory :c
"""
# Python modules
import gc
import os
from datetime import datetime
# External modules
import PIL
from PIL import Image, ImageOps
from PyPDF2 import PdfFileMerger
# PyQt5 Gui components
from PyQt5 import QtWidgets
from Py... |
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
# Modifications:
# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Parser driver.
This provides a high-level interface to parse a file into a synta... |
import asyncio
import functools
import logging
import traceback
import typing
from starlette.websockets import WebSocket, WebSocketState
from starlette.status import WS_1001_GOING_AWAY
from . import serialize
from opentrons.protocol_api.execute import ExceptionInProtocolError
from concurrent.futures import ThreadPool... |
"""
Chatter command line entry point. All handling of the command line options and settings as well as basic application
startup configuration are contained within this module. As new commands become identified they should be plugged in
using the framework contained within this module.
"""
import anyconfig
import arg... |
import argparse
from pylab import *
import os
import audio_utilities
import Fftreader
from mpl_toolkits.axisartist.parasite_axes import HostAxes, ParasiteAxes
def getM_(mdir):
'''
to get M feature map
:param txtdir: str, lastm.txt, in 2K*T shape
:return: dimMeans(K-dim),frameMeans(T-dim)
'''
no... |
from nltk.classify import NaiveBayesClassifier, MaxentClassifier, SklearnClassifier
from sklearn import cross_validation
from sklearn.svm import LinearSVC, SVC
from nltk.corpus import stopwords
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import *
from nltk.tokenize import word_tokenize
# fro... |
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from transformers import BertTokenizer
from tqdm import tqdm
from bert_config import Config
from utils import clean_symbols, rm_stop_word
seed = 9999
np.random.seed(seed)
class DataPrecessForSentence(Dataset):
"""
对文本进行处理
""... |
import numpy as np
import scipy.stats
from collections import defaultdict
from typing import Tuple, Dict, Iterable
class ContiguousPMF:
'''
Implements a probability mass function for a discrete random variable whose realizations are
integers on the interval [0, ``max_value``], where ``max_value`` is an in... |
import os
import re
import hashlib
import boto3
from curried import curried
from future import Future
from common import Struct
class Item:
"""
A class that combines file paths, names, and hashes in a comparable way
"""
def __init__(self, file_path, file_name, file_hash = None):
self.file =... |
"""
Helper functions shared between the other modules
"""
import re
import json
import sys
import subprocess
import yaml
from . import errors
from os import getcwd
from pathlib import Path
def load_settings(file_path):
"""
Load a supported settings file
Checks the file suffix of file_path and calls the a... |
# -*- encoding: utf-8 -*-
"""
License: MIT
Copyright (c) 2019 - present AppSeed.us
"""
from __future__ import print_function
import base64
import mimetypes
import smtplib
from datetime import date
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipa... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pathlib import Path
import seaborn as sns
import plotly.express as px
from typing import List
import re
import patsy as pt
import pymc3 as pm
from sklearn import preprocessing
cols = sns.color_palette('colorblind')
# PROTEIN_DIRS = ['1fme', ... |
# -*- coding: utf-8 -*-
from tkinter import *
from tkinter import tix
from tkinter import font as tkFont
import MultiListbox as table
import sys
NAME = 0
SURNAME = 1
BIRTH_NUMBER = 2
STREET = 3
NUMBER = 4
CITY = 5
ZIP = 6
NOTE = 7
data = [
# Jméno, Příjmení, RČ, ulice, čp, město, PSČ, poz... |
# coding: utf-8
# Author: xiaoran
import math
class AdvCalculator(object):
def __init__(self):
self.priori_op = {
'+': {'+':-1, '-':-1, '*':-1, '/':-1, '√':-1, '(':1, ')':-1, '!':-1, '^':-1, 'ln':-1, 'log':-1, 'sin':-1, 'cos':-1, 'tan':-1, 'arcsin':-1, 'arccos':-1, 'arctan':-1},
'-... |
from manimlib.imports import *
import numpy as np
from vivek.vid_0003_selection_sort.sortable import Sortable
class Limb(VGroup):
def __init__(self, back, side, t, **kwargs):
super().__init__(**kwargs)
self.back = back
assert side in ['left', 'right']
assert t in ['arm', 'leg']
... |
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
class Student(Person):
def __init__(self, student_id, first_name, last_name, enroll_date):
Person.__init__(self, first_name, last_name)
self.student... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import namedtuple, OrderedDict, Iterable
def make_fixed_padding(kernel_size, rate=1):
"""Pads the input along the spatial dimensions independently of input size.
Pads the input such that if it was used in a convolution with '... |
# 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 Amazon.com, Inc. or its affiliates. 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
#
# Unl... |
#!/usr/bin/env python3
from sys import stderr, stdout, exit, argv
from os import environ
import os.path
from multilanguage import Env, Lang, TALcolors
problem=os.path.split(environ["TAL_META_DIR"])[-1]
args_list = [
('service',str),
]
ENV =Env(args_list)
TAc =TALcolors(ENV)
LANG=Lang(ENV, TAc, lambda fstring: ev... |
# coding:utf-8
import os
import gc
import yaml
import numpy as np
import pandas as pd
import tensorflow as tf
import keras.backend as k
from tqdm import tqdm
from tensorflow import set_random_seed
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import StratifiedKFold
from sc... |
import os
import re
from fabric.api import env, task, local, sudo, run, prompt
from fabric.colors import red, green, blue, yellow
from fabric.context_managers import cd, prefix
from fabric.contrib.files import exists
from fabric.utils import puts
# Studio
STUDIO_TOKEN = os.environ.get('STUDIO_TOKEN', None)
# GLOBA... |
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union
import json
class QuackClassMethod():
def __init__(self, method_name: str, params: List[str], ret: str):
self.method_name = method_name
self.params = params
self.ret = ret
class QuackClass():
def __init__(... |
#!/usr/bin/env python
"""
This script is used initialize the sample project with user-specific values
"""
# Imports ######################################################################
from __future__ import print_function
import os
import re
import sys
import time
import shutil
# Metadata #########################... |
import logging
import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
from scipy.ndimage.morphology import binary_fill_holes
from torch.nn.functional import one_hot
from seg_utils.utils import convert_binary_output_to_classes
DEBUG = True
def show_img(img, title=None, ax=None, show=True):
i... |
"""
Utilities and plugins for running tests with nose
Django-nose database context to run tests in two phases:
- Stage 1 runs all test that don't require DB access (test that don't inherit
from TransactionTestCase)
- Stage 2 runs all DB tests (test that do inherit from TransactionTestCase)
Adapted from testrunn... |
#!/usr/bin/python -u
#
# Author: <NAME> (<EMAIL>)
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
#
import datetime
import... |
# 程序使用Python3运行
# 示例文法G[E]:
# E→E+T | E-T | T
# T→T*F | T/F | F
# F→P^F | P
# P→(E) | i
# 用前需配置全局变量如下
# 拓广文法G[A],必须写开,不能带或
C = ['A→E', 'E→E+T', 'E→E-T', 'E→T', 'T→T*F', 'T→T/F', 'T→F', 'F→P^F', 'F→P', 'P→(E)', 'P→i']
# 非终结符,必须是一个字符不能写成类似E',不然转向SLR时会出错
Vn = ['A', 'E', 'T', 'F', 'P']
# 终结符,必须是一个字符,空字符写成ε
Vt = ['+', '-',... |
#!/usr/bin/env python
"""
obssim.py
Observation Simulator wrapper for webbPSF.
This package lets you easily script simulations of things more complicated than just a single point source.
"""
import os
import numbers
import numpy as np
import scipy.interpolate, scipy.ndimage
import matplotlib.pyplot as plt
i... |
r"""
Elation Sports Technologies LLC
22 Oct 2021
Force-Sensing Telescoping Pole
Calibration Processing Script
"""
import matplotlib.pyplot as plt
import numpy as np
import time,csv
import matplotlib.cm as cm
plt.close('all')
currTimeString = time.strftime('%d%b%Y_%I%M%p')
data_path = r'C:\Us... |
from typing import List, Dict
import collections
import dataclasses
import torch
import numpy as np
@dataclasses.dataclass
class node_param:
feat_level: int
offsets: List[int]
upsample: bool
_NODE_PARAMS = [
node_param(6, [3, 4], True),
node_param(5, [2, 5], True),
node_param(4, [1, 6], Tru... |
import re
from django.contrib.auth.hashers import check_password
from rest_framework import serializers
from common.models import (
User,
Org,
Comment,
Address,
Attachments,
Document,
APISettings,
Profile
)
from django.utils.http import urlsafe_base64_decode
from django.contrib.auth.toke... |
import random
def print_n_whitespaces(n: int):
print(" " * n, end="")
def print_n_newlines(n: int):
for _ in range(n):
print()
def print_feelers(n_feelers, is_player=True):
for _ in range(4):
print_n_whitespaces(10)
for _ in range(n_feelers):
print("A " if is_player... |
#!/usr/bin/python
import math
#Initialize list of occupied slices and recieve user input for material specifications
ocp_list=list()
print("---Sheet Material Slicer and Cost Calculator---")
ocp_xmat=float(input("What is the length of the material sheet? "));
ocp_ymat=float(input("What is the width of the material she... |
#!/usr/bin/env python
import codecs
import datetime
import decimal
import sys
try:
import json
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
import simplejson as json
import agate
import six
from csvkit.cli import CSVKitUtility, match_column_identifier
... |
import ceGame
import ceColor
import pygame
import random
import datetime
import urllib.request, urllib.error, urllib.parse
class Cell:
def __init__(self, ch=0, fg=0, bg=0, gfx=False, flash=False, double=False):
self.ch = ch
self.fg = fg
self.bg = bg
self.flash = flash
self.d... |
import argparse
import math
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
width = 500
height = 500
viewpoint = []
H = 0
scale = 2
points = []
polygons = []
window: GLint
def center_and_scale_model():
x = [point[0].value for point in points]
y = [point[1].value f... |
# !/usr/bin/env python
import numpy as np
import pandas as pd
from sklearn.preprocessing import scale, minmax_scale
def read_csv(filename, take_log):
""" Read TPM data of a dataset saved in csv format
Format of the csv:
first row: sample labels
second row: cell labels
third row: cluster labels from... |
from meerkat_hermes import app, logger
from flask import Response
from datetime import datetime, timedelta
import uuid
import boto3
import time
import json
import requests
def slack(channel, message, subject=''):
"""
Sends a notification to meerkat slack server. Channel is '#deploy' only if
in live deplo... |
"""
Requires neotermcolor
neotermcolor styles:
- logger:10 - debug log message
- logger:20 - info log message
- logger:30 - warning log message
- logger:40 - error log message
- logger:50 - critical log message
- logger:exception - exceptions, printed to stdout (w/o logging)
Keeping records in memory requires neotas... |
import itertools
import logging
from typing import NewType, Optional, Union, Dict, List, Tuple
import numpy as np
import pygame
from pygame.math import Vector2
from vgdl.core import VGDLSprite, Action, Resource
from vgdl.core import Color
from vgdl.tools import triPoints, unitVector
from .constants import *
from .phy... |
# vim: fdm=indent
'''
author: <NAME>
date: 12/06/17
content: FACS sorting related plumbing.
'''
# Modules
import os
import numpy as np
import pandas as pd
import xarray as xr
# Classes / functions
class FacsSample:
def __init__(self, mouse, tissue):
self.mouse = mouse
self.tissue = ti... |
import torch
import torch.nn as nn
from torch.optim import Adam
from torch.nn.utils import clip_grad_norm_
from torch.optim.lr_scheduler import ReduceLROnPlateau
from tqdm import tqdm
from time import time
from tensorboardX.writer import SummaryWriter
from datetime import datetime
from collections import defaultdict
... |
#!/usr/bin/env python3
"""
When studying distributed systems, it is usefull to play with concepts and create prototype applications.
This main runner aims in helping with the prototyping, so that an application can be created as a class
in ./classes/apps. This code contains the main runner that will run in each node.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.