text stringlengths 3.07k 22.1k |
|---|
"""
Generate the src/_ufuncs.c file to turn the scalar C functions
into numpy ufuncs. Also writes ufuncs.list as a record of the
ufunc names.
"""
from pathlib import Path
import sys
import shutil
from c_header_parser import (get_simple_sig_dict,
get_complex_scalar_dict_by_nargs_nreturns)... |
#!/usr/bin/env python
import os
import datetime
import rospy
import numpy as np
import scipy
import pdb
import sys
import time
import matplotlib.pyplot as plt
import pickle
import sys
from segway_sim.msg import highLevelBelief
sys.path.append(sys.path[0]+'/pyFun')
print("sys.path: ", sys.path)
from segway_sim.msg i... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
import numpy as np
from torch.autograd import Variable
torch.set_default_tensor_type('torch.cuda.FloatTensor')
class MultiCrossEntropyLoss(nn.Module):
def __init__(self, size_average=True, ignore_index=-500):
super(... |
from gurobipy import Model, GRB, quicksum
import networkx as nx
def create_model(G, terminals, root=None, weight='weight', warmstart=[], lower_bound=None):
r""" Create an ILP for the minimum Steiner tree problem in graphs.
This formulation enforces a cycle in the solution if it is not connected.
Cycles a... |
"""moudle for 2D image datasets.
Todo:
* Add more datasets (CIFAR-100, ImageNet etc.)
"""
import logging
import pathlib
from dataclasses import dataclass
from typing import Final, Optional, Tuple
import pytorch_lightning as pl
import torch
import torchvision
from omegaconf import MISSING
from torch.utils.data imp... |
import numpy as np
import nibabel as ni
from scipy.io import loadmat
import os
from nitime.timeseries import TimeSeries
from mvpa_itab.conn.connectivity import z_fisher, glm, get_bold_signals
from mvpa_itab.conn.operations import flatten_matrix
import logging
from mvpa_itab.io.connectivity import load_matrices
from mv... |
from . import QUOTES, COMMON_SEPARATORS, DEFAULT_WAIT, \
MAX_ERROR_PRINTOUT, MAX_DISPLAY_COLS
# =================================================
# Automatically Reading Structured Arrays
# =================================================
# Return the type of a string (try converting to int and float)
... |
'''Transformer model defination
'''
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
class TokenEmbedding(layers.Layer):
'''Positinal embedding layer define for ASR'''
def __init__(self, num_vocab=1000, maxlen=100, num_hid=64):
super().__init__()
self.em... |
from owlready2 import *
"""
author: <EMAIL>
using Owlready2 to manipulate the ontology
README
- I created a python vrit env for this: $ pew new --python=python3 owlready2
- installed owlready2 in my ws: $ pip install Owlready2
- Make sure you are working in the Virtual environment: $ pew workon owlready2
- run this s... |
import itertools
import random
import numpy as np
class Operation:
"""
Abstract base class for all types of operations that may be put into a pipeline.
"""
def __init__(self):
"""
Create the Operation.
args member contains the arguments that were used while creating the opera... |
"""Interpolates between two latent vectors using pretrained network pickle."""
import os
import re
from typing import List, Optional
import click
import imageio
import dnnlib
import numpy as np
import pandas as pd
import PIL.Image
import torch
import copy
import legacy
from scipy.stats import multivariate_normal
#-... |
#!/usr/bin/env python
# encoding: utf-8
"""
train_reuters_rnn.py
~~~~~~~~~~~~~~~~~~~~
Train RNN for topic labelling on reuters dataset using keras
"""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__created__ = "2018-05-29"
__copyright__ = "Copyright 2018 Will Davey"
__license__ = "MIT https://opensource.org/licenses/M... |
import torch
import numpy as np
from obj_geo_utils.obj_utils import OBJ_REPS_PARSE
#*******************************************************************************
Track_running_stats = 1
class DIM_PARSE:
IMAGE_SIZE = 512
POINTS_NUM = 9
POINTS_DIM = POINTS_NUM * 2 * 2
# StrPointsHead.cal_test_score()
LINE_CL... |
import numpy as np
import time
import gym
import pandas as pd
from rl_lib.utils.utils import running_average
from rl_lib.agents.q_learning import QLearningAgent
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
plt.style.use("bmh")
################### VARIABLES ###################
class Mountain... |
from django.conf import settings
from django.contrib.auth import get_user_model, authenticate
from django.conf import settings
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from rest_framework.serializers import (
CharField,
EmailField,
ModelSerializer,
Validati... |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, ... |
"""
.. module:: beamngcommon
:platform: Windows
:synopsis: Module containing common functions used across various BeamNGpy
modules.
.. moduleauthor:: <NAME> <<EMAIL>>
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import logging
import json
import os
import warnings
import numpy as np
from functools i... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Distributed under terms of the MIT license.
from torch.utils.data.sampler import SubsetRandomSampler
import numpy as np
import torch
import cPickle as pickle
from .features import Features
import config
UNK_IDX = 0
EOS_IDX = 2
class Dataset(torch... |
'''
Based on code from <NAME>
fcn.berkeleyvision.org
'''
from ba import BA_ROOT
import ba.utils
import caffe
import numpy as np
from PIL import Image
import random
import scipy.misc
import yaml
class TextListLayer(caffe.Layer):
def setup(self, bottom, top):
params = eval(self.param_str)
se... |
import logging
from copy import deepcopy
from warnings import warn
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from interpret.glassbox import ExplainableBoostingClassifier, LogisticRegression
from tqdm import tqdm
class ClusterExplainer():
def __init__(self, ... |
from __future__ import division, print_function, absolute_import
import tensorflow as tf
from preprocessing import inception_preprocessing
from tensorflow.contrib import slim
from autoencoders import ae_factory
from collections import defaultdict
from autoencoders.optimizers.ae_sdc_1.sgd_v2 import GradientDescentOptim... |
#!/usr/bin/env python3
import os
import sys
import time
from PyQt5.QtCore import QTimer, Qt, QEvent, pyqtSignal, QThread, QObject, QRect
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, QWidget, QComboBox, QScrollArea
from PyQt5.QtWidgets import QHBo... |
import numpy as np
import tensorflow as tf
from tensorflow_probability import distributions as tfd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import matplotlib
matplotlib.use('Agg') # needed when running from commandline
import matplotlib.pyplot as plt
import cycler
import u... |
#!/usr/bin/env python3
from _run import *
from systemsettings import *
from datasets import *
import numpy as np
import pickle
import time
import subprocess
import os
import sys
TUM_RGB_FR1 = [TUM_RGB_FR1_DESK, TUM_RGB_FR1_ROOM, TUM_RGB_FR1_PLANT]
TUM_RGB_FR2 = []
TUM_RGB_FR3 = [TUM_RGB_FR3_DESK]
ICL = [ICL_NUIM_LIV... |
import argparse
import copy
import os
import numpy as np
from tqdm import tqdm
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel
from .sampled_trainer import (
SampledTrainer,
ClusterGCNTrainer,
NeighborSamplingTrainer,
... |
import shm
from shm.watchers import watcher
from mission.framework.task import Task
from mission.framework.targeting import PIDLoop
from mission.framework.combinators import (
Sequential,
Concurrent,
MasterConcurrent,
Retry,
Conditional,
Defer,
)
from mission.framework.movement import (
Dept... |
"""
各ディレクトリ毎にスクリプトを実行、copyを行う
やること
各ディレクトリ:ある問題のあるmetricのあるmethodでクラスタリングされた1つのクラスター。
分類された問題の一覧がある
それぞれのディレクトリに対して以下の処理を行う
1. ファイル名をリストにする
2. miningscripts/CodeForceCrawler/resultから、SourceMonitorのメトリクス値を読みこんでくる
3. pandaのライブラリに読み込んでくる
4. クラスタリングを実行。fclusterでクラスターのラベリング。
5. 再コピー。
4, 5はリファクタリ... |
import sys
import time
# TODO:マルチセルポリシーに対応する
file_name = sys.argv[1]
disable_policy_output = sys.argv[2]
start = time.time()
value_name_key = ['set', 'policy', 'id', 'policy_id', 'name', 'value_name', 'from', 'src_zone', 'to',
'dst_zone', 'src_ip', 'dst_ip', 'protocol', 'nat', 'src', 'dst', 'ip', '... |
#!/usr/bin/env python
"""
Helper functions for windowing singal and noise in a trace.
"""
import os
from importlib import import_module
import pkg_resources
import yaml
import numpy as np
import pandas as pd
from openquake.hazardlib.gsim.base import SitesContext
from openquake.hazardlib.gsim.base import RuptureContex... |
from cdislogging import get_logger
import flask
import json
import requests
from pidgin.errors import *
from pidgin.constants import *
app = flask.Flask(__name__)
app_info = {
"swagger": "2.0",
"info": {
"title": "Pidgin OpenAPI Specification",
"description": "A core metadata API for CDIS Ge... |
import gc
from typing import Union
from unicodedata import normalize
import numpy as np
from ..parallel.batch import batch_process
from ..utils import import_tqdm
from .utils import scaled_linspace
tqdm = import_tqdm()
def generate_cone(
vertex,
base_points,
n,
normalizer,
method,
reversed_c... |
#!/usr/bin/env python
#Seperates candidate loci by cluster and annotates them with genewise
import subprocess
import os
import tempfile
from HAPpy import genome_fork as genome
from HAPpy import toolbox_for_HAP
import threading
import time
def thammerin_for_parse_loci(hmm_file,hmm_dir,thammerin_path,candi... |
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import io
import os
import pickle
import itertools
from sklearn.metrics import confusion_matrix
import seaborn as sn
import pandas as pd
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
def plot_training_result(dict_res, s... |
import sys, os
argv = sys.argv
if len(argv) != 3:
sys.exit()
file = "data/programs/" + str(argv[2])
mode = str(argv[1])
if not (mode == "new" or mode == "open"):
sys.exit()
if mode == "open":
try:
if not os.path.isfile(file):
sys.exit()
except:
sys.exit()
else:
try:
... |
print(f"Loading {__file__}...")
from ophyd import EpicsMotor, EpicsSignal, EpicsSignalRO
from ophyd import Device
from ophyd import Component as Cpt
from ophyd import PVPositionerPC
from nslsii.devices import TwoButtonShutter
# Setup photon shutters
shut_fe = TwoButtonShutter("XF:05ID-PPS{Sh:WB}", name="shut_fe")
s... |
#<NAME>
#<EMAIL>
#UBC Microbiology - Haney Lab
import os
from Bio import SeqIO
import numpy as np
### Attempting to re-implement InParanoid algorithm
# def get_seqs(fastafile):
# count = 0
# seqdict = {}
# seqarr = []
# for s in SeqIO.parse(open(fastafile,'r'),'fasta'):
# count += 1
# seqdict[s.id] = count
... |
import argparse
import logging
from collections import defaultdict
from overrides import overrides
from typing import Dict, List
from sacrerouge.commands import RootSubcommand
from sacrerouge.common import Params
from sacrerouge.common.logging import prepare_global_logging
from sacrerouge.common.util import import_mod... |
import pandas as pd
from io import open
#2021/06/16 eapuertoc: Si no se pone un alias no es necesario el "as json"
import json
import re
import numpy as np
import pickle
import os
def __open_osm(osm_file):
"""Read an OSM file and save contents in a list
Parameters:
-----------
osm_file -- File wi... |
import numpy as np
from math import pi
from cdtea import event
import math
"""
a coordinate function is one that takes in a spacetime and outputs a dictionairy with node indices as keys and coordinate tuples as values.
"""
# utility functions
# finds the minimum angular distance beween two given angles
def angular_s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
## @file ostap/trees/funcs.py
# Module with helper base classes ...
# @author <NAME> <EMAIL>
# @date 2011-06-07
# ===========================================================================... |
"""Visualizing various regions in a list of scores. E.g. adding colored regions
corresponding to percentiles to a timeline of outlier scores"""
import numpy as np
import matplotlib.pyplot as plt
# The code bellow is intended to add some visual interpretation to outliers scores display on a timeline
# See: https://w... |
import pandas as pd
from multiprocessing import Pool, RawArray, cpu_count
from portfolio_methods import PortfolioMethods
import numpy as np
import copy
from decorators import timeit
from sklearn.linear_model import LinearRegression
import numpy.random as npr
import json
import datetime as dt
from portfolio import PM, P... |
import discord
import asyncio
import logging
from discord.ext import commands
# self-created modules below
import lib.embedCreation as embedCreation #contains functions for creating an embed
import lib.tekkenFinder as tekkenFinder #contains functions for finding character and move details
# Get token from local dir... |
from enum import Enum
GENERIC_JSON_RPC_EXCEPTIONS = {
-32700: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.",
-32601: "Method not found",
-32602: "Problem parsing the parameters, or a mandatory parameter was not found",
-32603: "Internal JSON-RP... |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import asyncio
import logging
from collections import defaultdict
from typing import Any, DefaultDict, Dict, List, Tuple
import aiohttp
from terragraph_thrift.Topology.ttypes import NodeType
from tglib.clients import APIServiceClient
from ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 11:20:41 2020
@author: worklab
"""
import torch
import numpy as np
import time
import random
import _pickle as pickle
random.seed = 0
from detrac_files.detrac_tracking_dataset import Track_Dataset
from torch_kf import Torch_KF
from torch.utils... |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and rel... |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on December 12, 2021
"""
import arff
import numpy as np
import os
from os.path import join
from scipy import sparse
from stpredictions.models.DIOKR.utils import project_root
# bibtex
# files (sparse): Train and test sets along with their union and the XML he... |
import copy
from collections import deque
import query_collections.query_structs
from .exceptions import InvalidQueryException, EmptyQueryException, InvalidFilterException
class NodeType:
"""
Current implemented query node types.
BASIC_MEMBER: A key of a component is expected
WILD_CARD: Any value of ... |
from iotcommon import IotUDPHandler
from iotcommon import UdpPacket
import datetime
import iotcommon
import SocketServer
import binascii
import logging
import time
import threading
import os
import socket
import ssl
import sys
import json
class IotSession:
TYPE_UDP = 'udp'
TYPE_SSL = 'ssl'
def __init__(sel... |
import heapq
class Cell(object):
def __init__(self, x, y, reachable):
"""Initialize new cell.
@param reachable is cell reachable? not a wall?
@param x cell x coordinate
@param y cell y coordinate
@param g cost to move from the starting cell to this cell.
@... |
# coding=utf-8
import logging
import datetime
import re
from collections import defaultdict, OrderedDict
from copy import copy
import requests
from .models import Route, DataProviderUrl,\
DataProviderTypes as p_types, RouteTypes, Point, Platform, Directions, RoutePoint, RouteWeekDimension, GeoDirections, \
... |
# Copyright (c) 2016 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Read upper air data from remote archives."""
from io import BytesIO
import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
i... |
from Box2D import *
from typing import List
from settings import get_boxcar_constant
import math
import numpy as np
def rotate_floor_tile(coords: List[b2Vec2], center: b2Vec2, angle: float) -> List[b2Vec2]:
"""
Rotate a given floor tile by some number of degrees.
"""
rads = angle * math.pi ... |
import dash_core_components as dcc
import dash_html_components as html
import dash_table as dt
from os import environ
from monty.serialization import loadfn
# noinspection PyUnresolvedReferences
import propnet.symbols
from propnet.core.registry import Registry
from propnet.web.layouts_plot import scalar_symbols
fro... |
from abc import ABC
from textwrap import wrap
from PIL import Image, ImageDraw, ImageOps
from PIL import ImageFont
class MemeFormat(ABC):
def __init__(self, logger) -> None:
super().__init__()
self.logger = logger
class ImpactFormat(MemeFormat):
POSITION_TOP = "TOP"
POSITION_BOTTOM = "... |
import os
import pickle
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
from matplotlib import font_manager as fm, rcParams
import numpy as np, scipy.stats as st
import glob
import os
import csv
import shutil
import random
# Say, "the default sans-serif font is COMIC SANS"
m... |
import aiohttp
import asyncio
import typing
import logging
import os
from typing import Any
from dataclasses import dataclass
from aiohttp import WSMessage, WSMsgType, ClientConnectionError
from ..codes import OpCodes
from ..helpers import dumps_data, load_data, JSONDecodeError
__all__ = ["WebsocketShard", "AutoSha... |
import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Function, Variable
from torch.nn.parameter import Parameter
try:
from spatial_correlation_sampler import spatial_correlation_sample
except Impor... |
#!/usr/bin/python
import argparse, sys, os, gzip, random
from shutil import rmtree
from multiprocessing import cpu_count, Pool
from tempfile import mkdtemp, gettempdir
from Bio.Format.GPD import GPDStream, GPD
from Bio.Stream import LocusStream
from Bio.Structure import TranscriptGroup
def main(args):
#do our input... |
'''
The main model for classifying relationships between source and target entities.
'''
import string
import numpy as np
import tensorflow as tf
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn import metrics
from tensorflow.keras import Model
from tensorflow.keras.backend impo... |
##
## nw_rtparse
##
## <NAME>
## Last modified: 2013-05-01
##
## Python script for parsing NWChem real-time TDDFT output for various
## time-dependent quantities (e.g., dipole moment, electric field, etc)
##
## nw_rtparse --help
##
##
import sys
from optparse import OptionParser
from signal import signal, SIGPIPE, SIG... |
import json
from os.path import join
import numpy as np
import torch
from torch.utils.data import Dataset
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.text import text
from keras.preprocessing.sequence import pad_sequences
from utils import data_utils
from utils import settings
class Proc... |
import global_types
from common import *
def create_subscr_cb_reg_method_definitions(file_we, data):
ret = ""
for service_name in data["services"]:
if "signal" in data["services"][service_name]:
for signal_name in data["services"][service_name]["signal"]:
signal_info = data[... |
import scipy
from glob import glob
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import cv2
from utils import *
from os import listdir
from os.path import isfile, join, isdir
class AU2Emotion():
#https://imotions.com/blog/facial-action-coding-system/
def __init__(se... |
# -*- coding: utf-8 -*-
import enum
from collections import Iterable
from elb import ELBSet, RuleSet, UpStream, UARule, BackendRule, PathRule
from sqlalchemy import Index
from werkzeug.utils import cached_property
from citadel.config import ELB_BACKEND_NAME_DELIMITER
from citadel.ext import db
from citadel.libs.datas... |
import base64
import json
import StringIO
from django import forms
import happyforms
from tastypie.validation import CleanedDataFormValidation
from tower import ugettext_lazy as _lazy
import amo
from addons.models import Addon, AddonDeviceType, Category
from files.models import FileUpload
from mkt.developers.forms i... |
# pure-python module for adb interaction
from ppadb.client import Client
# for time.sleep(sec)
import time
# Classic os module for interaction with os, here for file check
import os
# Import the width and height of user's phone
from config import PHONE_WIDTH, PHONE_HEIGHT, COUNTRY_CODE, PHONE_HAS_LOCK, PHONE_LOCK_PASSW... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
#!/usr/bin/env python
"""Convert astronomical positions between various coordinate systems.
The CnvObj code is getting ugly enough (I had to add ICRS<->ICRS2000 cases
to handle the proper motion) that I'm wondering if it wouldn't be better
to just hand code the converter as I did in the TCC. I hate all those
if/then/... |
'''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] <NAME>, <NAME>, <NAME>, <NAME>
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
class BasicBlock(nn.Mod... |
from flask import Flask, render_template, request, Response, send_file
import matplotlib
import io
import base64
from PIL import Image
from textwrap import wrap
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
import matplotlib.colors as pltcolors
import matplotlib.ticker as ticker
from mp... |
# coding: utf-8
# author: <NAME>
import requests
import pandas as pd
import time
import datetime
import json
import sys, re, os
from PIL import Image
import io
import matplotlib.pyplot as plt
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
# https://github.co... |
import os
import pandas as pd
import openmatrix as omx
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='check activitysim raw_data')
parser.add_argument('raw_data_directory', metavar='raw_data_directory', type=str, nargs=1,
help=f"path to raw data directory")
pars... |
import argparse
import io
import json
import pathlib
import sys
import typing
from . import __version__
from . import api
from . import element_types
def bytes_escape(bs: bytes, *, quote: typing.Optional[str] = None) -> str:
"""Convert a bytestring to an ASCII string,
with non-ASCII characters hex-escaped.
(We ... |
# Copyright (c) 2017 pandas-gbq Authors All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import datetime
import decimal
import collections
import random
import db_dtypes
import pandas
import pandas.testing
import pytest
pytest.importorskip("g... |
# -*- coding: utf-8 -*-
import json
from collections import OrderedDict
from subprocess import Popen, PIPE
import traceback
import pandas as pd
import logging
from tornado import web, escape, httpclient
from factornado.utils import ArgParseError, MissingArgError
factornado_logger = logging.getLogger('factornado')
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import *
from django.db import models
from mptt.models import MPTTModel
from uuslug import slugify
# Create your models here.
class User(AbstractUser):
nickname = models.CharField(verbose_name='昵称', max_length=32)
... |
"""
nn.py
=====
Utility functions for working with NN weights and classes.
Includes utility function for monitoring GPU usage during NN training.
Created by: <NAME> (<EMAIL>)
"""
import copy
import subprocess
from typing import Dict, List, Tuple, Type
import numpy as np
import torch
from torch.nn import (BatchNorm1... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
import time
import ctypes
import inspect
import threading
class DispatchOnce(threading.Thread):
"""
Execute a target function once in a thread with the abbility to cancel.
This is a bit hacky extension that allows terminating a running thread.
Te... |
"""
Server module intended for runtime.
DL-JWTSERVER,
by hereticSibyl, <EMAIL>
A light-weight JWT authentication server.
"""
import configparser
from os.path import isfile
from os import remove
from typing import Literal, Optional, Union, Tuple
from base64 import b64decode, b64encode
from random import choice
from st... |
from tequila.circuit.pyzx import convert_to_pyzx, convert_from_pyzx
from tequila.circuit.gates import *
from tequila.simulators.simulator_api import simulate
from tequila import TequilaException
import numpy
import pytest
HAS_PYZX = True
try:
import pyzx
HAS_PYZX = True
except ImportError:
HAS_PYZX = False
... |
from functools import partial
import numpy as np
import torch
import torch.nn as nn
# Taken from: https://github.dev/computational-imaging/ACORN/
class Sine(nn.Module):
def __init__(self, w0=30):
super().__init__()
self.w0 = w0
def forward(self, input):
return torch.sin(self.w0 * inp... |
from ipaddress import IPv4Address, IPv4Network
import jsonschema
import os
import subprocess
import yaml
import command
import resource
import template
import util
def get_project(create_dir_if_missing=False) -> str:
project_dir = os.getenv("HOMEWORLD_DIR")
if project_dir is None:
command.fail("no HO... |
"""
Based on SignalConvND from tensorflow/compression
TODO: add proper refernce
"""
import tensorflow as tf
import numpy as np
from scipy.fftpack import rfft, irfft
tfl = tf.keras.layers
__all__ = [
"SignalConv2D"
]
class SignalConv2D(tfl.Layer):
def __init__(self,
filters,
... |
'''
thonny-py5mode.
py5 plugin for Thonny.
# NOTES TO SELF:
* documentation: https://github.com/thonny/thonny/wiki/Plugins
* maybe look at how Run > Pygame Zero Mode is programmed?
'''
import os
import pathlib
import shutil
import subprocess
import site
import sys
import threading
import time
from distutils.sysconfi... |
import warnings
import pandas as pd
import numpy as np
__all__ = ['Pandas2numpy']
def assert_list_contains_all(l, l_subset):
"Raise a warning if some columns from `l_subset` do not exist in `l`."
non_existing_columns = set(l_subset).difference(l)
if len(non_existing_columns) > 0:
non_existing_colu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 2 16:06:07 2019
@author: asabater
"""
import json
import numpy as np
#from eyolo import EYOLO
#from pycocotools.coco import COCO
#from pycocotools.cocoeval import COCOeval
#import pyperclip
#import matplotlib.pyplot as plt
import random
import... |
import math
import pytest
import numpy as np
from photons import utils
def test_decimals():
assert utils.get_decimals(0.) == 0
assert utils.get_decimals(0) == 0
assert utils.get_decimals(1) == 0
assert utils.get_decimals(1.0) == 0
assert utils.get_decimals(-1) == 0
assert utils.get_decimals(... |
#first bot
import pyautogui
import time
import random
import sys
from login import login
from track import track
from drop import dropAll
from movement import bezier3
from movement import bezier4
from password import get_pwd
import sand
def toggleRun():
pass
def pos():
while(1):
print(pyautogu... |
import os
import sentencepiece as spm
import sys
from argparse import ArgumentParser
from tqdm import tqdm
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.code_tokenizer import INDENT_MARKER, DEDENT_MARKER, BEGIN_COMMENT_MARKER, END_COMMENT_MARKER, END_LINE_MARKER, MISSING_MARKE... |
import os
import platform
import subprocess
def _sysctl(stat):
return ["sysctl", "-n", stat]
MUST_BE_INTS = [
"cpu_core_count",
"cpu_thread_count",
"cpu_frequency_max_hz",
"cpu_l1d_cache_bytes",
"cpu_l1i_cache_bytes",
"cpu_l2_cache_bytes",
"cpu_l3_cache_bytes",
"memory_bytes",
... |
from odmlib import odm_loader as OL, loader as LO
import odmlib.odm_1_3_2.model as ODM
import odmlib.odm_1_3_2.rules.oid_ref as OID
import xml.etree.ElementTree as ET
import odmlib.odm_parser as P
import os
import datetime
# update this path to point to your ODM1-3-2 schema file
SCHEMA_FILE = os.path.join(os.sep, 'hom... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_noop, ugettext_lazy
from django.utils.translation import ugettext as _
from corehq.apps.es import users as user_es, filters
from corehq.apps.domain.models import Domain
from corehq.apps.groups.models import Group
from corehq.app... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import gzip
import sys
import glob
import logging
import collections
from optparse import OptionParser
# protoc --python_out=. ./appsinstalled.proto
import appsinstalled_pb2
import pymemcache
from multiprocessing import Pool, TimeoutError
from threading import Th... |
import argparse
import os
import pathlib
import re
from typing import Any, Dict, List
import attr
import snakemake
# We define Path here in addition to pathlib to put both variables in globals()
# This way, users specifying a path type in their config.yaml can indicate
# either Path or pathlib.Path
Path = pathlib.Pat... |
#!/usr/bin/env python
"""
See the 'EPILOG' variable below, or (better) run with --help for help.
"""
from __future__ import print_function
import os
import sys
from Bio import SeqIO
DEFAULT_BLAST_ARGS = ''
DEFAULT_BLAST_DB = 'nt'
DEFAULT_BLAST_DB_DIR = '/usr/local/dark-matter/blast-dbs'
DEFAULT_EMAIL = '<EMAIL>'
DE... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 16:27:22 2020
@author: aarid
Analysis blind docking results
"""
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from pathlib import Path
import argparse
import logging
#""" Load separated results into individual dataframes and then conca... |
# -*- coding: UTF-8 -*-
from datetime import datetime
import os
from PIL import Image
brand_ru = 'Питомник немецких овчарок «Фонте Фиделити» г. Тольятти'
brand_en = 'Питомник немецких овчарок «Fonte Fideliti» г. Тольятти'
menu = [('Главная', ''),
('Производители', 'males/'),
('Производительницы', 'fe... |
"""
Copyright (C) Cortic Technology Corp. - All Rights Reserved
Written by <NAME> <<EMAIL>>, 2021
Implementation reference:
https://github.com/geaxgx/depthai_hand_tracker
"""
from curt.modules.vision.oakd_processing import OAKDProcessingWorker
import depthai as dai
from curt.modules.vision.utils import *
import c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.