text stringlengths 3.07k 22.1k |
|---|
"""Transform a roidb into a trainable roidb by adding a bunch of metadata."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import lib.datasets
import numpy as np
from lib.model.utils.config import cfg
from lib.datasets.factory import get_imdb
import PIL
i... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021 The HERA Collaboration
# Licensed under the MIT License
"""Utilities for dealing with maps."""
import warnings
import numpy as np
import matplotlib.pyplot as plt
import healpy
from .util import field_to_healpix
from .data import PATH
map_options = ["gsm", "roman", "ngrs... |
#!/usr/bin/env python
#
# spyne - Copyright (C) Spyne contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later ve... |
# coding=utf-8
from robot.libraries.BuiltIn import BuiltIn
from datetime import datetime, timedelta
import dateutil.parser
import pytz
import urllib
import shutil
import os
TZ = pytz.timezone('Europe/Kiev')
def adapt_data(data):
data['data']['items'][0]['unit']['name'] = get_unit_name(data['da... |
import os
import sys
import glob
import argparse
import utility
import re
import string
from decimal import *
CONFIG = {}
"""
Initialise all file headers to the data stored within the config file.
"""
def initHeaders():
global accession_number
accession_number = CONFIG['accession_number']
global authors
... |
# Copyright 2021 Huawei Technologies Co., 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-2.0
#
# Unless required by applicable law or agreed to... |
import pickle
from sqlalchemy import MetaData, Table
from sqlalchemy.dialects.mysql import insert
from selenium import webdriver
from weibo.Connect_mysql import Connect
import re
import time
import random
import pymysql
import datetime
def getinfo(conn, driver, uid, table):
time.sleep(2)
driver.get('https://w... |
from countries_plus.models import Country
from decimal import Decimal as D
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.core.exceptions import FieldError
from django.db import models
from django.db.models import Sum
from django.utils.crypto import get_random_string
from phonenumber_f... |
"""
Simple script to show a countdown in OBS
Starts and stops a timer countdown
Implemented by writing the countdown value twice per second in file timer.txt
To use the timer countdown, create a TXT (GDI+) source and configure it to get its text from the file timer.txt
in OBS assets.
Action Points:
to do: add script... |
import asyncio
import discord as discordpy
import re
from django.conf import settings
from django.contrib.auth.models import User as AuthUser
from django.db import models
from django.db.models import signals
from django.dispatch import receiver
from django.urls import reverse
from django.utils import timezone
from furl... |
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# <NAME>
# Copyright 2021 Keeper Security Inc.
# Contact: <EMAIL>
#
import argparse
import base64
import datetime
import logging
import os
from urllib.parse import urlparse, urlunparse
from .base i... |
"""
Created on Oct. 19, 2020
@author: Heng-Sheng (Hanson) Chang
"""
import os, sys
import numpy as np
from numba import njit, jit
from elastica._linalg import _batch_matvec, _batch_cross, _batch_norm, _batch_matrix_transpose
from elastica._calculus import quadrature_kernel, difference_kernel
from elastica.external... |
import json
import logging
import signal
import requests
import boto3
import os
import traceback
import sys
import subprocess
import re
import uuid
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)
def check_call(args):
proc = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subproce... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import threading
import time
import sys
# from random import *
import struct
import argparse
import re
from urllib.request import Request, urlopen # Python 3
import queue as Queue
__author__ = "TheSpeedX"
__version__ = "2.0"
banner = """
███████╗ ██████╗ ███... |
#
# XDMC
# Copyright (C) <NAME> (email <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 3 of the License, or
# (at your option) any later versi... |
from datetime import timedelta
from django.conf import settings
from django_statsd.clients import statsd
from google.cloud import bigquery
from olympia.constants.applications import ANDROID, FIREFOX
# This is the mapping between the AMO usage stats `sources` and the BigQuery
# columns.
AMO_TO_BQ_DAU_COLUMN_MAPPING =... |
#!/usr/bin/env python
import argparse
import subprocess
import os
from pathlib import Path
import tempfile
import shutil
import configparser
import datetime
import logging
import re
from collections import defaultdict
logger = logging.getLogger()
sh = logging.StreamHandler()
logger.addHandler(sh)
template_warning = '... |
# -*- coding: utf-8 -*-
import os,sys,time,hashlib,json
from kcweb import config
from kcweb.utill import redis
from kcweb.utill.db.mysql import mysql
import time,hashlib
def md5(strs):
"""md5加密"""
if not strs:
return strs
m = hashlib.md5()
b = strs.encode(encoding='utf-8')
m.update(b)
r... |
# Copyright (c) 2019 Intel 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
# -*- coding: utf-8 -*-
#
# Copyright 2018-2020 Data61, CSIRO
#
# 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... |
#!/usr/bin/env python
'''
Title: correct_sam_format.py
Date: 20180730
Author: <NAME>
Description:
Fix the FLAG and CIGAR values in a paired-end SAM file generated by erne-bs5.
Specifically, correct the custom bisulfite strand information in the FLAG and
remove any zero-length elements present in the CIGAR string. I... |
import torch
import math
'''
REDISTRIBUTION
'''
def momentum_redistribution(masking, name, weight, mask):
"""Calculates momentum redistribution statistics.
Args:
masking Masking class with state about current
layers and the entire sparse network.
name ... |
import os
from pprint import pprint
import numpy as np
import pandas as pd
from script.data_handler.Base.BaseDataset import BaseDataset, path_join
from script.data_handler.Base.BaseDatasetPack import BaseDatasetPack
from script.data_handler.Base.Base_df_transformer import Base_df_transformer
from script.util... |
import json
import tempfile
import zipfile
import os
import boto3
from utils.aws_utils import file_to_dict
from utils.logging_utils import get_logger
code_pipeline = boto3.client('codepipeline')
logger = get_logger()
class PipelineUserParameters:
def __init__(self, job_data, lambda_ctx):
"""Decodes the ... |
from typing import Iterator, Optional, Sequence, Tuple
from collections import deque, namedtuple
from pprint import pprint
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data.dataset import IterableDataset
from anim... |
# -*- coding: utf-8 -*-
# @Time : 2021-12-08 7:59 a.m.
# @Author : <NAME>
# @FileName: CIoctDICOM.py
# @Software: PyCharm
"""this script performs the following
(1). read .oct file into a numpy array
(2). geometrically correct the distorted view coordinates
(3). export the .oct volume into the DICOM format
(4). sav... |
#!/usr/bin/python
'''This module contains the underlying model of the game itself. It depends heavily on the board and rules modules. Games are currently limited to two players only.
There are four major stages to the game, represented by module level constants:
`game.GAME_HANDICAP`
The current player must place h... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
import json
import logging
import os
from typing import List
import click
import numpy as np
import tensorflow as tf
from sklearn.metrics import cohen_kappa_score, precision_recall_fscore_support, accuracy_score
from discopy.components.component import Component
from discopy.utils import init_logger
from discopy_data... |
import warnings
import numpy as np
warnings.simplefilter('always', UserWarning)
# ----------------------------------------------------------------------------------------------------------------------------------------------------
# Generate Stimulus
# -----------------------------------------------------------------... |
import argparse
import sys
import logging
import os
import csv
class ReadItem:
def __init__(self, sequence):
self.Sequence = sequence
self.TotalCount = 0
self.SampleMap = {}
class AnnotationItem:
def __init__(self, sequence, category):
self.Sequence = sequence
self.TotalCount = 0
self.Cate... |
import os
import json
from data.train_data_loader import DataSet as train_dataset
from data.test_data_loader import DataSet as test_dataset
from opts import parse_opts
def check_data_list_function(video_list_path, dataset_type_list):
train_dataset_count = dict()
for dataset_type in dataset_type_list:
... |
from typing import Any, Type, Union
import numpy as np
import pytest
import segyio.tools
from segyio import SegyFile, TraceSortingFormat
from tiledb.segy.structured import Index, LabelIndexer, StructuredSegy
from .conftest import (
assert_equal_arrays,
iter_slices,
parametrize_segys,
stringify_keys,
... |
# Copyright 1999-2022 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-2.0
#
# Unless required by applicable law or a... |
#####################################################################################
##-----------------------------------------------------------------------------------
## This Python program will automate the APS to SQLDW code migration tasks.
## The program will use exact pattern matching t... |
# -*- coding: utf-8 -*-
from scipy.special import betaln, beta as betafn, logsumexp
import numpy as np
def predictRecall(prior, tnow, exact=False):
"""Expected recall probability now, given a prior distribution on it. 🍏
`prior` is a tuple representing the prior distribution on recall probability
after a spec... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 6 15:08:25 2021
@author: ccamargo
"""
import pandas as pd
import xarray as xr
import numpy as np
#%% find closest points of our TG, make sure that they are water
def harvedist(lats,lons,qlats,qlons):
# https://www.movable-type.co.uk/scripts/l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Imports
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object
import sys
import os
import argparse
import io
from lxml import etree
import process_includes
#
# Globals and constants
... |
'''
Test MNIST classifications with JAX and Haiku
'''
import haiku as hk
import jax
import numpy as np
import jax.numpy as jnp
import optax
import tensorflow as tf
import tensorflow_datasets as tfds #stable
from typing import Mapping, Tuple, NamedTuple
import pickle
#locals
import filenames
import preprocess
import ne... |
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of sou... |
from collections import namedtuple
import torch
import math
from .defs import NONLINEARITIES, TimeDerivative, StepPrediction
RELU_LEAK = 0.2
BASE_CHANS = 64
class UNetBlock(torch.nn.Module):
def __init__(self, in_chans, out_chans, transposed=False, bn=True, relu=True, size=4, pad=1):
super().__init__()
... |
"""
Tests that require Metagov to be running.
Run with `INTEGRATION=1 python manage.py test`
"""
import os
import unittest
import integrations.metagov.api as MetagovAPI
from django.conf import settings
from django.contrib.auth.models import Permission
from django.test import Client, LiveServerTestCase, TestCase
from d... |
import base64
import fcntl
import json
import logging
import psycopg2
import socket
import time
import dateutil
import datetime
import pytz
from patroni.exceptions import PostgresConnectionException
from patroni.utils import Retry, RetryFailedError
from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServe... |
#!@PYTHON@ -tt
#
# Fence agent for Intel AMT (WS) based on code from the openstack/ironic project:
# https://github.com/openstack/ironic/blob/master/ironic/drivers/modules/amt/power.py
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.... |
# basics
import re
import os
import numpy as np
import pandas as pd
import pytz
from datetime import datetime
from collections import Counter
# Specify the timezone of Hong Kong
# No time difference between Shanghai and Hong Kong
time_zone_hk = pytz.timezone('Asia/Shanghai')
# For instance, if we want to compare the ... |
"""Module for performing optimization over the stiefel manifold."""
import numpy as np
from scipy import linalg as linalg
import neuropy.temp as tmp
def optimize(ObjFn):
"""Perform optimization over the Stiefel manifold."""
# Parameters
max_iter = 1000
max_ls_iter = 500 # Maximum number of line sea... |
import csv
import os
import pickle
import re
import emoji
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import MinMaxScaler
from textblob import TextBlob
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from emotion.EmojiEmotionFeature i... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__doc__ = """
Implementation of a SAX parser for the AST defined in the
mathml.termparser module.
Usage examples:
(remember to run 'from mathml import mathdom, xmlterm, termparser' first!)
* Building a MathDOM document from a boolean expression in infix notation:
>>> from m... |
from typing import List
import datetime
import itertools
from dateutil.relativedelta import relativedelta
import numpy as np
import marshmallow as ma
from paramtools.typing import ValueObject
from paramtools import utils
class ValidationError(ma.ValidationError):
def __init__(self, *args, level=None, **kwargs):... |
import sys
sys.path.append('..')
from common.gfxutil import CEllipse
from kivy.graphics.instructions import InstructionGroup
from kivy.graphics import Color, Line, PushMatrix, PopMatrix
from kivy.clock import Clock as kivyClock
from kivy.core.image import Image
from math import exp
from .test_constants import *
fr... |
from numpy import ones, diag, matrix, ndarray, zeros, absolute, mean,var, linalg, prod, sqrt
import numpy as np
import warnings
from SparseSC.optimizers.cd_line_search import cdl_search
warnings.filterwarnings('ignore')
def ct_v_matrix(X,
Y,
LAMBDA = 0,
treated_units = N... |
from collections import Counter, defaultdict
import datetime
from datetime import date, timedelta
from math import ceil
from os import path
from typing import List
import reportlab.rl_config
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.gr... |
# -*- coding: utf-8 -*-
#
"""
I/O for MED/Salome, cf.
<http://docs.salome-platform.org/latest/dev/MEDCoupling/med-file.html>.
.. moduleauthor:: <NAME> <<EMAIL>>
<NAME> <<EMAIL>>
"""
import numpy
from .mesh import Mesh
# https://bitbucket.org/code_aster/codeaster-src/src/default/catalo/cataelem/Com... |
from django.core.serializers.json import DjangoJSONEncoder
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from django.contrib.postgres.aggregates import ArrayAgg... |
import logging
import pathlib
import re
import subprocess
import types
from . import configuration
from . import qemu
from . import utils
from . import ssh
from . import static
from typing import (
cast,
Any,
Sequence,
Callable,
List,
Optional,
Type,
Tuple,
Union,
)
def combine_c... |
"""
Description: This library contains all the functions/classes for: Agents.
Please refer to each of the functions/classes for a full description of what they do.
Functions ([first,second] "first bool" notes the implemented functions "second bool" notes the implemented documentation):
name:[True,F... |
# -*- coding: utf-8 -*-
# Copyright 2018 ICON Foundation
#
# 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 ... |
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# -*- coding: UTF-8 -*-
# SPDX-License-Identifier: MIT
from __future__ import print_function, unicode_literals
import re
import socket
from pymta.exceptions import SMTPViolationError
from pymta.session import SMTPSession
from pymta.statemachine import StateMachine
from pymta.compat import queue, basestring
__all__ ... |
import os, logging
import os.path
import datetime
import zlib
from enum import Enum
from hashlib import md5, sha1
from datetime import datetime
from sys import getsizeof
def get_size(obj: object, seen=None):
"""Recursively finds size of objects"""
size = getsizeof(obj)
if seen is None:
seen = set(... |
# implementation of DQN with experience replay and target networks to play Atari breakout
import gym
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from gym.core import ObservationWrapper
from gym.spaces import Box
import cv2
import gym
from framebuffer import FrameBuffer
from replay_buffer imp... |
from radiomics.featureextractor import RadiomicsFeatureExtractor
import SimpleITK as sitk
from itertools import combinations
import numpy as np
from dicom_to_cnn.tools.pre_processing.threshold_mask import *
"""Tools to extract metrics from PET/MASK using pyradiomics
"""
def get_center_of_mass(mask_path:str, thres... |
################################################################################
# COPYRIGHT(c) 2018 STMicroelectronics #
# #
# Redistribution and use in source and binary forms, with or without ... |
from collections import defaultdict
from copy import copy
from discord.ext import commands
from discord.utils import find, get
from .. import const, exceptions
import asyncio
import discord
import gettext
import logging
import traceback
logger = logging.getLogger('taalbot.cogs.onboarding')
nt = gettext.NullTransla... |
# -*- coding: utf-8 -*-
"""
Center for Research on Media, Technology, and Health
University of Pittsburgh
Author: colditzjb
Version: 2017-09-23
Python version: 2.7 (tested) & 3.5+ (preferred)
Required Python packages:
twython: https://github.com/ryanmcgrath/twython
& requests_oauthlib: http://github.com/request... |
import os
import argparse
from deep_ed_PyTorch import utils
from deep_ed_PyTorch.data_gen.indexes import YagoCrosswikisWiki
from deep_ed_PyTorch.entities.ent_name2id_freq import EntNameID
class GenTestTrain(object):
def __init__(self, args):
self.args = args
self.ctxt_len = 100
self.num_c... |
import logging
import argparse
import torch
import torch.nn.functional as F
import numpy as np
from transformers import GPT2Tokenizer, GPT2LMHeadModel, AdamW, WarmupLinearSchedule
from tqdm import tqdm, trange
import utils.utilities as U
# import utils.bleu as bleu
logging.basicConfig(format='%(asctime)s - %(levelna... |
""" Module for preparing the data for the churn prediction model with text.
Run in CLI example:
'python preprocess.py --test-size 0.33'
"""
import os
import sys
import json
import yaml
import joblib
import logging
import argparse
import numpy as np
import pandas as pd
from pathlib import Path
from matplotlib i... |
"""便利関数"""
import numpy as np
from math import pi, sin, cos, tan
### 超基本の関数 ###
def rotate(theta):
"""回転行列
入力:回転角theta
出力:二次の回転行列
"""
return np.array([[cos(theta), -sin(theta)],
[sin(theta), cos(theta)]], dtype = np.float32)
def sigmoid(multi, coeff, x_offset, y_offset, x):
... |
"""
Utility Functions that can be used for Kaggle and other ML uses
Includes all stable utility functions.
Reference for kaggle API: https://github.com/Kaggle/kaggle-api
"""
import configparser
import datetime as dt
import json
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import ... |
# coding: utf-8
from sqlalchemy import BINARY, Column, Index, Integer, String, Table, VARBINARY
from sqlalchemy import String, Unicode, ForeignKey
from sqlalchemy.orm import relationship, backref
from dbdatetime import dbdatetime
from sqlalchemy.dialects.mysql.base import LONGBLOB
from sqlalchemy.ext.declarative import... |
from __future__ import generators, print_function
import numpy as np
from random import shuffle
from scipy.io import loadmat
import functools
import Queue
#from multiprocessing import Process, Queue, Manager, Pool
import threading
import time
from collections import defaultdict
def async_prefetch_wrapper(iterable, b... |
from jsub.manager.error import JobvarListNotSetupError
import copy
import re
def _jobvar_name_map(jobvar_single, name_map):
jobvar_new = {}
for k, v in jobvar_single.items():
if k in name_map:
jobvar_new[name_map[k]] = v
else:
jobvar_new[k] = v
return jobvar_new
'''
This splitter generates subjob paramet... |
from flask import Flask, jsonify, render_template, request, Response, session, url_for
import json
import time
import emails
import user_db
import stone_db
import move_validation
import captures
with open("config.json") as f:
cfg = json.load(f)
app = Flask(__name__)
app.secret_key = cfg["secret key"]
@app.rou... |
# Create your views here.
import datetime
import os
from django.contrib.auth.decorators import user_passes_test
from django.contrib.markup.templatetags.markup import markdown
from django.contrib import messages
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.forms.formset... |
import pygame
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')
black = (0,0,0)
white = (255,255,255)
clock = pygame.time.Clock()
crashed = False
carImg_right = pygame.image.load('/Users/vladislavde... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 23 13:20:54 2021
@author: Nicolas
"""
import cv2 as cv
import csv
import os, os.path, time
import numpy as np
import matplotlib.pyplot as plt
from os import path
import math
import imutils
import pandas as pd
method_array = {}
method_array['rotation'] = True
method_arra... |
__author__ = 'hofmann'
__version__ = '0.0.6'
import os
import io
import time
import datetime
from scripts.Validator.validator import Validator
import gzip
import bz2
import zipfile
from scripts.parallel import TaskThread, runThreadParallel
class Compress(Validator):
"""Reading and writing compressed files"""
... |
import discord
from discord.ext import commands
import requests
import json
import asyncio
import typing
# Importa a função predicate do mod blacklist, que retorna True ou False, usado como decorator
from cogs._blacklist import is_blacklisted
class Wikipedia(commands.Cog):
def __init__(self, bot):
self.b... |
import os
import numpy as np
import pickle as pkl
import h5py
import networkx as nx
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import sys
import tensorflow as tf
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.a... |
import pytest
from opsy.inventory.models import Host, Group, Zone, HostGroupMapping
from opsy.exceptions import DuplicateError
def test_zone_model(test_inventory_bootstrap):
"""Test Zone to make sure it works correctly."""
# Test to make sure deleting a zone nukes all assets in that zone
west_zone = Zone.... |
# ParchmentMC
# Produces Parchment (mappings) and Blackstone (metadata)
# https://github.com/ParchmentMC/
import json
import os
import subprocess
import zipfile
from typing import Dict, Tuple, Any, Set
from util import mapping_downloader, utils
from util.mappings import Mappings
MethodInheritanceTree = Dict[Tuple[st... |
from functools import wraps
import magma as m
from magma.bitutils import seq2int
from mantle import And, NAnd, Or, NOr, XOr, NXOr, LSL, LSR, Not, Invert, UDiv, SDiv, UMod, SMod, Mul
from mantle import ASR
from mantle import EQ, NE, ULT, ULE, UGT, UGE, SLT, SLE, SGT, SGE
from mantle import Mux
from .arith import Add, S... |
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
import tensorflow as tf
import keras.backend as K
from keras.utils import to_categorical
from keras import metrics
from keras.models import Model, load_model
from keras.layers import Input, BatchNormalizat... |
from collections import defaultdict
import csv
import ast
import argparse
class Graph:
'''
The code for this class is based on geeksforgeeks.com
'''
def __init__(self,vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self, u, v, w):
self.graph[... |
"""Class to control openMVS behaviour."""
from pathlib import Path
import subprocess
from . import utils
class OpenMVSControllerError(RuntimeError):
"""Generic openMVS error."""
pass
class OpenMVSController():
"""Controls behaviour of openMVS data processing."""
def __init__(self, res_dir, ext_lo... |
import os
from dotenv import load_dotenv
from sqlalchemy import create_engine
import math
import numpy as np
import pandas as pd
from scipy.signal import iirnotch, filtfilt
from scipy.io.matlab import savemat
# parameters
SUBJECT_ID = 'S08'
FREQ_TYPE = 'C'
VERBOSE = True # if True, prints some output to screen
# run... |
import os
from glob import glob
from toil_lib.tools import get_mean_insert_size
from toil_lib.files import tarball_files
from toil.lib.docker import dockerCall
def run_mutect(job, normal_bam, normal_bai, tumor_bam, tumor_bai, ref, ref_dict, fai, cosmic, dbsnp):
"""
Calls MuTect to perform variant analysis
... |
# PIG / Python Version
from random import randint
from math import pi, sin, cos
from Tk2050 import *
RUN={
'MAX_FRAMES' : 64*64*10,
'FRAME_SPEED' : 400,
'COUNT' : 0,
'RUNNING' : 1,
}
SET_MEMORY = 50
SET={
'a' : {
'NUMBER' : 5,
'RADIUS' : 10,
'VELOCITY' : 2,
'MEMO... |
import string
import sys
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Set, Union
import click
import geopandas as gpd
import numpy as np
import pandas as pd
import pygeos
from bs4 import BeautifulSoup
from keplergl_cli import Visualize
from shapely.geometry import MultiPolygon, Polygon, ... |
import random
from os import system
from time import sleep
cards_value = {
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'J': 10,
'Q': 10,
'K': 10,
'A': [1, 11]
}
class Deck:
def __init__(self):
self.cards = ['2','3','4','5',... |
#!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation;
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the... |
# coding=utf-8
"""
PyTorch BERT model.
Slightly modified from https://github.com/codertimo/BERT-pytorch
"""
import torch.nn as nn
import torch.nn.functional as F
import torch
import math
from allennlp.modules.token_embedders.token_embedder import TokenEmbedder
from allennlp.data import Vocabulary
from allennlp.commo... |
"""prodigal.py: a module with functions to call genes with Prodigal,
count codon usage, calculate centered log ratio and isometric log ration
transformations and return values as a CSV."""
import subprocess
import os
import logging
import csv
import yaml
import numpy as np
# import scipy.linalg
import scipy
f... |
#!/usr/bin/env python
"""
Get information from cp2k output files, such as coordinates and final QMMM energy.
Given a template data or pdb file, it will make new files with the xyz coordinates from the cp2k output file
"""
from __future__ import print_function
import argparse
import os
import re
import sys
import numpy... |
"""
All code fragments that are embedded in the API conversion document for the auto_ivc feature
are tested here.
"""
import unittest
import numpy as np
import openmdao.api as om
from openmdao.core.tests.test_distribcomp import DistribNoncontiguousComp
from openmdao.test_suite.components.unit_conv import TgtCompC, Tg... |
from antelope_core.implementations import BackgroundImplementation, CoreConfigureImplementation
from antelope import ExteriorFlow, check_direction, comp_dir
from antelope_core.exchanges import ExchangeValue # these should be ExchangeRefs?
from antelope_core.contexts import Context
from .flat_background import FlatBac... |
import math
import os
from hacktools import common, nitro
import constants
def readIMGData(f, paloff, tileoff, mapoff):
paloffs = []
if paloff > 0:
f.seek(paloff)
paln = f.readUInt()
for i in range(paln):
paloffs.append(paloff + f.readUInt() * 4)
paloff... |
"""
Handler for hiding implementation details of data storage for a crafted object
behind an abstraction layer
"""
from evennia_extensions.object_extensions.item_data_handler import ItemDataHandler
def get_storage_prop(attr_name, default=None):
"""Helper function to create a property with closures of the given va... |
# Copyright 2018 <NAME>
# Licensed under the MIT license
"""
Async-compatible version of itertools standard library functions.
These functions build on top of the async builtins components,
enabling use of both standard iterables and async iterables, without
needing to use if/else clauses or awkward logic. Standard ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.