text stringlengths 3.07k 22.1k |
|---|
#encoding=utf8
'''
Detection with SSD
In this example, we will load a SSD model and use it to detect objects.
'''
import os
import sys
import argparse
import numpy as np
from PIL import Image, ImageDraw
# Make sure that caffe is on the python path:
caffe_root = './'
os.chdir(caffe_root)
sys.path.insert(0, os.path.join... |
#!/usr/bin/env python
import pandas
import json
def ParseReadStats(pathToMashLog, pathToTotalBp):
for s in read(pathToMashLog):
if (s.find("Estimated genome size:") > -1 ):
_size = float(s[s.index(": ")+2:])
_totalbp = float(read(pathToTotalBp)[0])
_depth = _totalbp / _size
_depth ... |
import traceback
from parsing import parse_expr_to_list
from circuit_creator_helper_methods import *
from circuit_creator_static_variables import *
from truth_table import split_to_list, getVariables
LINE_WIDTH = 0
DRAW_NOT = False
def connect_lines(lines, var_count, idx_var0, idx_var1):
idx0 = idx_var0 * 2
... |
def orient(tile, degrees):
out_tile = ''
for i in range(len(tile)):
for j in range(len(tile[i])):
if degrees == 0:
out_tile += tile[i][j]
elif degrees == 90:
out_tile += tile[-(j+1)][i]
elif degrees == 180:
out_tile += tile[-(i+1)][-(j+1)]
elif degrees == 270:
out_tile += tile... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2016 Mag. <NAME> All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. <EMAIL>
# #*** <License> ************************************************************#
# This module is part of the package GTW.RST.MOM.
#
# This module is licensed under the terms of the BSD 3-C... |
import hmac
import hashlib
from io import BytesIO
from typing import List, Any, Generator
import btc_hd_wallet.bech32 as bech32
BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
TWO_WEEKS = 60 * 60 * 24 * 14
def chunks(lst: List[Any], n: int) -> Generator[List[Any], None, None]:
""... |
from __future__ import absolute_import, division
import numpy as np
import cv2
from . import Tracker
from ..utils import dict2tuple
from ..utils.complex import real, fft2, ifft2, complex_add, complex_mul, complex_div, fftshift
from ..descriptors.fhog import fast_hog
class TrackerKCF(Tracker):
def __init__(self... |
# Standard Library
import asyncio
import json
import logging
import os
import time
# Third Party
import kubernetes.client
from kubernetes import client, config
from kubernetes.client.rest import ApiException
from nats_wrapper import NatsWrapper
from prepare_training_logs import PrepareTrainingLogs
MINIO_SERVER_URL = ... |
from __future__ import print_function
import datetime
import glob
import json
import multiprocessing
import os
import pickle
import sys
import warnings
from collections import Counter, defaultdict
from string import digits
import re
import plotly.plotly as py
from plotly.graph_objs import *
from plotly.offline import ... |
# -*- coding: UTF-8 -*-
# Copyright 2011-2018 Rumma & Ko Ltd
#
# License: BSD (see file COPYING for details)
"""Database models for `lino_xl.lib.stars`.
"""
from django.db import models
from django.contrib.contenttypes.models import ContentType
from lino.api import dd, rt, _
from lino.core.gfks import gfk2lookup
fr... |
import math
from . import lia
V3 = lia.Vector3
M3 = lia.Matrix3
class HSL:
def __init__(self, h=0.0, s=0.0, l=0.0):
self.h = h # 0 .. 1.0, Hue
self.s = s # 0 .. 1.0, Saturation
self.l = l # 0 .. 1.0, Lightness
def hue6(self):
return math.floor(self.h * 6)
def calcMd... |
import numpy as np
import tensorflow as tf
import tensorflow.contrib.layers as layers
from utils import sigmoid
class Model:
def __init__(self, name, depth, width):
self.depth = depth
self.width = width
self.name = name
class Classifier(Model):
def __init__(self, name, depth=2, wi... |
import os
import csv
import random
import collections
import datasets
from datasets.acner import Acner
from tflearn.data_utils import to_categorical
class Germeval(Acner):
def __init__(self, train_validate_split=None, test_split=None,
use_defaults=False, shuffle=True):
# It makes less sense t... |
import numpy as np
import matplotlib.pyplot as plt
import astropy.io.fits as fits
import os
import poppy
from .main import GeminiPrimary
# Classes for dealing with AO Telemetry sets
class GPI_Globals(object):
""" Container for same constants as gpilib's gpi_globals,
with same variable names to ease porting o... |
#from https://github.com/pytorch/examples/blob/master/mnist/main.py
from __future__ import print_function
import argparse
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
from os.path import join as oj
import torch.utils.data as utils
from torchvision import datasets, trans... |
"""
********************************
* Created by mohammed-alaa *
********************************
Here I'm training video level network based on recurrent networks(frames from CNN are concatenated into a 3d tensor and feed to RNN):
1. setting configs (considering concatenation will have feature of 4096 = 2048 *2)
... |
import os
import math
from functools import singledispatch
from typing import overload, Union
import numba
import numpy as np
from .util import (
TempFileHolder,
glue_csv,
glue_hdf,
glue_parquet,
parse_csv,
parse_hdf,
parse_parquet,
_parallel_argsort,
)
try:
import pandas as pd
... |
import random
import string
from vk_api.keyboard import VkKeyboard, VkKeyboardColor
from vk_api.bot_longpoll import VkBotEvent
from vk_api.utils import get_random_id
from FusionBotMODULES import ModuleManager, Logger, Fusion
import datetime
load_module = False
def distance(a, b):
n, m = len(a), len(b)
if n... |
from datetime import datetime, timedelta
from typing import Dict
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy
from django.db.models import Q
from django.http import HttpRequest, HttpResp... |
# logic_solver.py: a propositional logic solving system
import math
from pprint import pprint
from time import perf_counter
import itertools
class LogicSolver:
def __init__(self, verbose=False):
self._verbose = verbose
# Prepare for the run start by enumerating sets & initial clues
self... |
# python3 Steven
import random
import numpy as np
from svg.file import SVGFileV2
from svg.basic import clip_float, draw_only_path, add_style_path, draw_path
from svg.basic import draw_circle, draw_any, random_color
from svgFunction import circleFuc, getCirclePoints, heartFuc, getRectanglePoints
from svg.geo_transformat... |
"""
Test that all modules can read and write the things they say they can.
"""
import json
import os
import warnings
from pathlib import Path
import pytest
from .base_test import BaseTest, ExpectedWarning
from .util import finalize_version
from .version_modules import CONFIG_DATA
# We are testing the public interfa... |
"""
Module to create and delete shelf tabs.
See the create_shelf doctstring and EXAMPLE_SHELF below for how to use.
Features:
- Python and mel commands.
- Python commands can be strings or executable objects.
- Left and right mouse button menus.
"""
__author__ = '<NAME>'
__copyright__ = 'DreamWall'
__lice... |
"""This module implements utility functions."""
import os
import sys
import re
from platform import platform
import collections
import errno
import logging
from swak.exception import UnsupportedPython, ConfigError
test_logger_inited = False
# Simple log format for test
LOG_FMT = logging.Formatter('%(asctime)s [%(le... |
""" Run weighted retraining for shapes with the optimal model """
import sys
import logging
import itertools
from tqdm.auto import tqdm
import argparse
from pathlib import Path
import numpy as np
import torch
import pytorch_lightning as pl
# My imports
from weighted_retraining.shapes.shapes_data import WeightedNumpyD... |
params = [
('epochs', [75]),
('batch_size', [64]),
('validation_split', [0.]),
('filters', [128, 256]),
('kernel_size', [5]),
('conv_activation', ['relu', 'tanh']),
('conv_l2_regularizer', [0.001]),
('dropout_rate', [0., 0.2, 0.5]),
('dense_activation', ['relu', 'tanh']),
('dense... |
# Copyright 2015 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
"""
Get variables from or print information of a netcdf file
This module was written by <NAME> while at Department of
Computational Hydrosystems, Helmholtz Centre for Environmental
Research - UFZ, Leipzig, Germany, and continued while at Institut
National de Recherche pour l'Agriculture, l'Alimen... |
from collections import defaultdict, namedtuple
from collections.abc import Set
from dataclasses import dataclass
# unused?
from enum import Enum
from inspect import isclass
from itertools import chain, product
# remove after dev
from pprint import pprint
from typing import List
from uuid import UUID, uuid4
from warni... |
# -*- coding: utf-8 -*-
# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)
# <NAME> (<EMAIL>), Blue Yonder Gmbh, 2016
"""
Contains a feature selection method that evaluates the importance of the different extracted features. To do so,
for every feature the influenc... |
import csv
import re
try:
import StringIO #for python 2.x
except:
from io import StringIO #for python 3.x.
def indent(s_in="", lvl=1):
ret = ""
tabstr = ""
for i in range(0,lvl):
tabstr += "\t"
for ln in s_in.split('\n'):
ret += tabstr + ln + "\n"
return chopnewline(ret)
def chopnewline(s_in):
if len(s_... |
# -*- coding: cp1252 -*-
from pylab import *
from matplotlib.pyplot import *
from numpy import *
import os.path as osp
DIR_NAME = osp.dirname(osp.abspath(__file__))
def get_freqs_data(filename, Trace=1, unit='MHz', dirname=None):
if unit == 'Hz':
fact = 1
elif unit == 'kHz':
fact =... |
from collections import Counter, OrderedDict
from itertools import chain
from functools import partial
class OrderedCounter(Counter, OrderedDict):
pass
class OutOfVocabularyError(LookupError):
pass
def _add_special_tokens(tokens, bos=None, eos=None):
tokens = list(tokens)
if bos is not None:
... |
import numpy as np
import random
from numba import jit
def indicator(S, n):
x = np.zeros(n)
x[list(S)] = 1
return x
def sample_live_icm(g, num_graphs):
'''
Returns num_graphs live edge graphs sampled from the ICM on g. Assumes that
each edge has a propagation probability accessible via g[u][v]... |
import sys
boold = True
# =============== MEMORIA - STACK ===============
class Stack():
def __init__(self):
"""
Simula lo stack.
__memory simula celle di memoria
"""
self.__memory = []
def push(self, data):
"""
Inserisce <data> nello stack.
... |
#!/usr/bin/env python3
######################################################
##
## Testing OBSTACLE_DISTANCE messages with ArduPilot and Mission Planner
##
######################################################
# Set MAVLink protocol to 2.
import os
os.environ["MAVLINK20"] = "1"
# Import the libraries
import sys
i... |
import os
import numpy as np
import time
import datetime
import torch
import torchvision
import gc
from torch import optim
from torch.autograd import Variable
import torch.nn.functional as F
from evaluation import *
from loss_function import *
from network import DCU_Net_16, DCGRU_Net_16, DCGRU_Net_22, LDCGRU_Net_16, D... |
# Step 4 Perform Parameter Tuning
print("Prepare parameter tuning")
def remove_near_labels(timestamps, labels, window_size=4 * 60 * 60):
labels.sort_index(inplace=True)
labels = labels[labels.group < 3]
label_timestamps = labels["end"]
selected_indices = []
for i in range(len(timestamps)):
... |
import json
import logging
import threading
import uuid
import pika
import pika.exceptions
from core_entities.configuration import Configuration
class WSClient:
def __init__(self, task_configuration: dict, host: str, port: int):
"""
Worker Service client, that uses pika library to communicate wi... |
from concurrent.futures import CancelledError
import logging
import os
from aiohttp.web import FileResponse, HTTPFound, Response
from jinja2 import Template
from flamingo.core.data_model import ContentSet, Content
from flamingo.core.utils.pprint import pformat
TEMPLATE_ROOT = os.path.join(os.path.dirname(__file__),... |
#!/usr/local/bin/managed_python3
"""
CLI Application to streamline the creation of PKGInfo files
for printer deployment in Munki.
Created by <NAME> for Syracuse University, 2014 - <EMAIL>
Bug squashing assistance from <NAME>
Much code reused from Printer PKG deploy scripts by:
<NAME>, SUNY Purchase, 2010
<NAME>, 2... |
def plot_histogram(data, outpath):
print('Plotting histogram to outfile: %s' % outpath)
import matplotlib.pyplot as plt
plt.hist(x=data, bins=50) # bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85
plt.grid(axis='y') # , alpha=0.75
plt.xlabel('Relative Gene Position')
plt.ylabel('Fr... |
import datetime
from codecs import utf_8_decode
from codecs import utf_8_encode
import hashlib
import os
import time
from wsgiref.handlers import _monthname # Locale-independent, RFC-2616
from wsgiref.handlers import _weekdayname # Locale-independent, RFC-2616
try:
from urllib.parse import urlencode, parse_qs... |
import numpy as np
from numpy import random
from compound_poisson import time_series
class TimeSeriesGd(time_series.TimeSeries):
"""Compound Poisson Time Series with ARMA behaviour
Attributes:
ln_l_array: the joint log likelihood after calling the method fit()
step_size: the step size for... |
import numpy as np
def sigmoid(z):
return 1/(1 + np.exp(-z))
def sigmoid_gradient(z):
"""
Derivative of sigmoid(z)
"""
sigmoid_grad = sigmoid(z)*(1 - sigmoid(z))
return sigmoid_grad
def roll(nn_params, layer_sizes):
"""
nn_params: long array of weights
layer_sizes: vector of l... |
# https://github.com/tonylins/pytorch-mobilenet-v2
import torch.nn as nn
import math
import numpy as np
import torch.utils.model_zoo as model_zoo
BN_MOMENTUM = 0.1
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.R... |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ train.py ]
# Synopsis [ Trainining script for Tacotron speech synthesis model ]
# Author [ <NAME> (Andi611) ]
# Copyright [ Copyleft(c), Speech Lab, NTU, Ta... |
from operator import (add,
itemgetter)
from typing import (List,
Optional,
Sequence,
Tuple)
from hypothesis import strategies
from ground.base import (Context,
Orientation)
from ground.hints import (Box,
... |
from argparse import ArgumentParser
from loguru import logger
from weakly_supervised_parser.settings import TRAINED_MODEL_PATH
from weakly_supervised_parser.utils.prepare_dataset import DataLoaderHelper
from weakly_supervised_parser.utils.populate_chart import PopulateCKYChart
from weakly_supervised_parser.tree.evalua... |
from django.core.paginator import Paginator
from django.db import transaction, DatabaseError
from django.db.models import ProtectedError
from django.forms import model_to_dict
from brainstorm.settings import OUTPUT_LOG
from utils.decorators import *
from brainstorm import settings
import os
import pandas as pd
from ut... |
#!/usr/bin/python
# -*-coding:utf-8 -*-
u"""
:创建时间: 2020/5/27 23:26
:作者: 苍之幻灵
:我的主页: https://cpcgskill.com
:QQ: 2921251087
:爱发电: https://afdian.net/@Phantom_of_the_Cang
:aboutcg: https://www.aboutcg.org/teacher/54335
:bilibili: https://space.bilibili.com/351598127
一个提供了Python开发中的便利功能的模块
"""
import re
import sys
import... |
import argparse
import glob
import logging
import os
from pydoc import doc
import random
import numpy as np
import torch
from more_itertools import chunked
from attack_util import find_func_beginning
from transformers import (RobertaConfig,
RobertaForSequenceClassification,
... |
#Plot
import matplotlib.pyplot as plt
import seaborn as sns
from bleu import file_bleu
#Data Packages
import math
import pandas as pd
import numpy as np
#Progress bar
from tqdm import tqdm
#Counter
from collections import Counter
#Operation
import operator
#Natural Language Processing Packages
import re
import nltk... |
import warnings as test_warnings
from unittest.mock import patch
import pytest
import requests
from rotkehlchen.assets.asset import WORLD_TO_GEMINI
from rotkehlchen.assets.converters import UNSUPPORTED_GEMINI_ASSETS
from rotkehlchen.constants.assets import A_BCH, A_BTC, A_ETH, A_LINK, A_LTC, A_USD
from rotkehlchen.co... |
import numpy
import seaborn
import torch
from sklearn.preprocessing import MinMaxScaler
from torch import nn
num_epochs = 20
learning_rate = 0.01
# https://www.jessicayung.com/lstms-for-time-series-in-pytorch/
# Here we define our model as a class
class LSTM(nn.Module):
def __init__(self, input_size, hidden_la... |
import os
import sys
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
if len(sys.argv) != 2:
print(
"Usage: [100, biscotti_output_file_dir, biscotti_input_file_dir, fedsys_output_file_dir, fedsys_input_file_dir]")
sys.exit()
# Example Usage: python generateResults.py 100... |
"""
fasttext.py
FastText Baseline (running as judge - takes debate logs as input, returns persuasiveness accuracy)
"""
from sklearn.metrics.pairwise import cosine_similarity
from spacy.language import Language
from tqdm import tqdm
import argparse
import json
import numpy as np
import os
ANS2IDX = {'A': 0, 'B': 1, '... |
import numpy as np
from copy import copy, deepcopy
from itertools import product
from envs.env import DeterministicEnv, Direction
class TrainState(object):
'''
state of the environment; describes positions of all objects in the env.
'''
def __init__(self, agent_pos, vase_states, train_pos, train_inta... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
from math import pi as PI
from scipy import signal
import IPython.display as ipd
# <b>Zadanie 2.1.a)<b>
# In[103]:
y = [0]*41
y[0] = 1
y[40] = 1
plt.figure(figsize= (12,4), dpi= 100)
plt.title("Impuls oraz impuls ... |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from archfinch.utils import render_to_response
from django.template.defaultfilters import slugify
from django.core.urlresolvers import reverse
from django.utils.http import base36_to_int
from django.template import... |
import os
import numpy as np
import keras
from keras.callbacks import EarlyStopping
from sklearn.utils import shuffle
from src.util import load_wm_model_from_file, save_wm_model_to_file, \
load_blackbox_model_from_file, save_blackbox_model_to_file, merge_histories, predict_with_uncertainty
from src.models import g... |
"""Data module."""
import math
import os
from typing import Collection, Dict, Iterable, List
import numpy as np
import pandas as pd
import torch
from gsea_api.molecular_signatures_db import (
GeneSet,
GeneSets,
MolecularSignaturesDatabase,
)
from spexlvm import config
# logging stuff
logger = config.logg... |
import connexion
import six
import json
import sqlite3
from flask import jsonify
import random
# import gpt_2_simple as gpt2
from swagger_server.models.likes import Likes # noqa: E501
from swagger_server.models.pickup_lines import PickupLines # noqa: E501
from swagger_server.models.profiles import Profiles # noqa:... |
"""
Provides helping function for flagging arguments.
"""
import logging
from typing import Union, Optional
import transaction
from dbas.database import DBDiscussionSession
from dbas.database.discussion_model import ReviewDeleteReason, ReviewDelete, ReviewOptimization, \
User, ReviewDuplicate, ReviewSplit, Revie... |
# Tindar class version 0:
# copied the jupyter notebook
# grouped cells into functions
# converted global variables to object
# attributes by adding self.___ where appropriate
# TODO: Naming error for n>10
from pulp import *
import numpy as np
from pathlib import Path
PROJECT_DIR = str(Path(__file__).resolve().paren... |
import subprocess
import pathlib
import os
import signal
import sys
from typing import Sequence, Optional
import conductor.context as c # pylint: disable=unused-import
import conductor.filename as f
from conductor.errors import TaskFailed, TaskNonZeroExit, ConductorAbort
from conductor.execution.version_index import ... |
#!/usr/bin/python
"""
Create a heapq python implementation.
this works:
import heapq
alist = [21, 44, 37, 38, 24, 2, 10, 44]
heapq.heapify(alist)
print alist
alist = [21, 44, 37, 38, 24, 2, 10, 44]
build_heap(alist)
print alist
alist = [21, 44, 37, 38, 24, 2, 10, 44]
build_heap(alis... |
# Copyright (c) 2015 Scality
# 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 a... |
import numpy as np
import cmath as cm
"""
Implementation of the theoretical formulations of reflection and trasmission of plane waves described in SEISMIC WAVE THEORY by <NAME>
"""
def snell(theta1, v1, v2):
"takes theta1 in rad, wave propagating from medium 1 to medium 2"
theta2 = cm.asin((v2 / v1) ... |
#!/usr/bin/python3
# Simple MQTT publishing of Modbus TCP sources
#
# Written and (C) 2018 by <NAME> <<EMAIL>>
# Provided under the terms of the MIT license
#
# Requires:
# - pyModbusTCP - https://github.com/sourceperl/pyModbusTCP
# - Eclipse Paho for Python - http://www.eclipse.org/paho/clients/python/
# frequency b... |
"""
Generate plots of model averaged convergence diagnostics.
"""
# License: MIT
from __future__ import absolute_import, division
import argparse
import glob
import os
import re
import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import xarray as xr
import reanalysis_dbns.mod... |
#/*
# * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
# * contributor license agreements. See the NOTICE file distributed with
# * this work for additional information regarding copyright ownership.
# * The OpenAirInterface Software Alliance licenses this file to You under
# * the OAI Publ... |
import csv
import pathlib
import pickle
import os
from collections.abc import Iterable
import numpy as np
import pandas as pd
import scipy.stats as stats
def processed_expression_table(df):
df.index.name = 'genes'
return df.groupby('genes').mean()
def expression_ranks(expression_table_df, ascending, rank_... |
# MIT License
#
# Copyright (c) 2017-2018 Udacity, Inc
# Copyright (c) Modifications 2018, 2019 <NAME> (pablo.rodriguez-palafox [at] tum.de)
#
# 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 Softwa... |
#!/usr/bin/env python
#
# Cachelot vs Memcached server memory consumption test
#
import sys
import string
import random
import os
import subprocess
import shlex
import time
import logging
import atexit
import memcached
log = logging.getLogger()
toMb = lambda b: b*1.0/1024/1024
SELF, _ = os.path.splitext(os.path.bas... |
#!/usr/bin/env python3
import time
import argparse
import sys
import structlog
import logging
import CloudFlare
import requests
import ipaddress
from requests.adapters import HTTPAdapter
logger = structlog.get_logger()
# https://techoverflow.net/2020/09/27/bitwise-operation-with-ipv6-addresses-and-networks-in-python/... |
'''
InstaCompOne is an older compression scheme used in the installer SDK
of the classic Mac OS. Like the famous Deflate algorithm, InstaCompOne
combines LZ77 with Huffman coding but uses a different bitstream format.
Author: <NAME> 2018
'''
import struct
from math import ceil, log2
LIT_MAX_LEN = 63... |
from flask import Flask, flash, redirect, render_template, request, session, abort
from flask import request,url_for # For flask implementation
from bson import ObjectId # For ObjectId to work
from flask import Flask, current_app
from pymongo import MongoClient
import os
import json
app = Flask(__name__)
#variables g... |
import json
import os
from datetime import datetime
from uuid import UUID, uuid4
from extensions.html_parser import HtmlParser
from extensions.accumulator import Accumulator
from extensions.word_cloud import WordCloudGenerator
from extensions.pos_tagger import PosTagger
from extensions.csv_loader import CsvLoader
from ... |
#!/usr/bin/env python3
from __future__ import absolute_import, division, print_function, unicode_literals
import matplotlib.pyplot as plt
import numpy as np
import argparse
import math
import re
import os
png_programs = ['stepic', 'lsbsteg']
jpg_programs = ['f5', 'steghide', 'outguess']
programs = png_programs + jpg_... |
# Cray-provided controllers for the Boot Orchestration Service
# Copyright 2019-2021 Hewlett Packard Enterprise Development LP
#
# 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 restri... |
"""
[summary]
[extended_summary]
"""
# region [Imports]
import gc
import os
import unicodedata
from typing import TYPE_CHECKING, Union
from inspect import getdoc, getsourcefile, getsourcelines
import discord
import inspect
from discord.ext import commands, tasks
import gidlogger as glog
from antipetros_discordbot.in... |
import pymortar
import os
import pandas as pd
def _query_and_qualify(sensor):
"""
Build query to return zone air temperature measurements and qualify
which site can run this application
Parameters
----------
sensor : sensor name type to evaluate e.g. Zone_Air_Temperature
Returns
-----... |
import pandas as pd
import numpy as np
import random
import csv
import pprint
#データフレームのダウンロード
def make_df(csv):
df = pd.read_csv(csv)
#'/Users/masato/Desktop/UTTdata/prog/PyProgramming/sinhuri2018.csv'
# print(df)
df_col = list(df.columns)[4::]
df_collist = []
for i in range(0, 24, 6):
... |
import re
import os
from pathlib import Path
import gdgen
from gdgen import common
from gdgen import methods
from gdgen import gdtypes
class TemplateWriter:
src = ''
dest = ''
def __init__(self, src, dest):
self.src = src
self.dest = dest
def write_out(self, template={}):
with open(self.src, 'r') as s... |
"""
Started from:
https://gist.github.com/arkadiyt/5d764c32baa43fc486ca16cb8488169a
https://medium.com/swlh/free-ssl-certificates-with-certbot-in-aws-lambda-991eb24ac1f3
https://github.com/vittorio-nardone/certbot-lambda
Expects the following environment variables:
LETSENCRYPT_DOMAINS
LETSENCRYPT_EMAIL
NOTIFICATION_S... |
from copy import deepcopy
import numpy as np
def complete_mol(self, labels):
"""
Take a cell and complete certain molecules
The objective is to end up with a unit cell where the molecules of interest
are complete. The rest of the atoms of the cell must remain intact. Note that
the input atoms are... |
# Copyright 2019 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file acc... |
import vapoursynth as vs
import kagefunc as kgf
import lvsfunc as lvf
import vardefunc as vdf
from awsmfunc import bbmod
from debandshit import f3kbilateral
from functools import partial
from lvsfunc.aa import upscaled_sraa
from lvsfunc.denoise import bm3d
from lvsfunc.misc import replace_ranges, scale_thresh
from lvs... |
import math
import cv2
import numpy as np
from dtld_parsing.calibration import CalibrationData
from typing import Tuple
__author__ = "<NAME>, <NAME> and <NAME>"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
class ThreeDPosition(object):
"""
Three dimensional position with respect to a defined frame_id.
... |
#!/usr/bin/env python3
'''
==============================================================================
Associative Memory (AM) classifier for binary Hyperdimensional (HD) Comuputing
==============================================================================
'''
import time
import sys
import torch as t
import nu... |
import logging
import os
from swagger_server.database.models.people import FabricPeople
from swagger_server.database.models.prefs_and_profiles import ProfilesKeywords, ProfilesReferences
from swagger_server.database.models.projects import FabricProjects, ProjectsTags
from swagger_server.models.inline_response2003 impo... |
import numpy as np
from itertools import product
from analysis.utils import one_hot_to_int
def get_oq_keys(X_i, task, to_int=True):
"""extract obs/query keys from the input matrix, for one sample
Parameters
----------
X_i : np array
a sample from SequenceLearning task
task : object
... |
import os
import pickle
from time import time
import itertools as it
import argparse
import operator
from tqdm import tqdm
from word2word import Word2word
from word2word.utils import (
download_or_load, download_os2018, get_savedir
)
from word2word.tokenization import (
load_tokenizer, get_sents, get_vocab, up... |
from collections import Counter
from collections import defaultdict
from dataclasses import dataclass
from itertools import product
from math import ceil
from math import exp
from math import floor
from math import isclose
from math import log2
from math import sqrt
from typing import List
from typing import Tuple
imp... |
import abc
import os
import SimpleITK as sitk
import numpy as np
import pymia.data.conversion as conversion
import common.evalutation.numpyfunctions as np_fn
import common.utils.labelhelper as lh
import rechun.eval.helper as helper
import rechun.eval.evaldata as evdata
import rechun.directories as dirs
class Loader... |
#!/usr/bin/env python
"""
############################
Incident Package Data Module
############################
"""
# -*- coding: utf-8 -*-
#
# rtk.incident.Incident.py is part of The RTK Project
#
# All rights reserved.
# Copyright 2007 - 2017 <NAME> <EMAIL>rew.rowland <AT> reliaqual <DOT> com
#
# Redistributi... |
# -*- coding: utf-8 -*-
"""
Classes for achieving the name mangling effect.
"""
from __future__ import unicode_literals
import logging
from operator import itemgetter
from itertools import count
from itertools import product
from calmjs.parse.ruletypes import PushScope
from calmjs.parse.ruletypes import PopScope
fro... |
import torch.nn.functional as F
from torch import nn
from networks.layers.basic import DropPath, GroupNorm1D, GNActDWConv2d, seq_to_2d
from networks.layers.attention import MultiheadAttention, MultiheadLocalAttentionV2, MultiheadLocalAttentionV3
def _get_norm(indim, type='ln', groups=8):
if type == 'gn':
... |
"""Contains helper functions for train.py used for train and evaluating model """
import torch.nn as nn
import torch
import numpy as np
import itertools
import matplotlib.pyplot as plt
import seaborn as sn
import pandas as pd
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import confus... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.