text stringlengths 3.07k 22.1k |
|---|
import re, uuid
from threatspec import data, threatmodel, config
from graphviz import Digraph
class Reporter():
def __init__(self, project: config.Project, threatmodel: threatmodel.ThreatModel):
self.project = project
self.threatmodel = threatmodel
self.components = {}
self.compone... |
# -*- coding: utf-8 -*-
'''
__author__ = "b0tm4r"
__credits__ = ["https://github.com/joanby - <NAME>"]
__version__ = "1.0.1"
__maintainer__ = "b0tm4r"
__email__ = "<EMAIL>"
__status__ = "Testing"
Basado en https://github.com/joanby/deeplearning-az/blob/master/datasets/Part%203%20-%20Recurrent%20Neural%20Networks%20(R... |
import pickle
from github import Github
from gitcloner import commits, repository, users
def repository_add(repository, user, file):
repo_dict = {}
repo_dict['name'] = repository.repo_name() # str
repo_dict['stargazers'] = repository.repo_stargazers() # int
repo_dict['watchers'] = repository.repo_wa... |
import asyncio
import json
from contextlib import suppress
from datetime import datetime
from discord import Client, Message, Embed
from BasicBot.basic import BasicBot, log
from StalkyDroid.webscraper import WebScraper
envConfig = 'StalkyDroid/resources/environment.config'
envChecked = 'StalkyDroid/resources/checked... |
"""Manage release repository (not source repository)."""
__all__ = [
'BuilderImageDir',
'EnvsDir',
'ImageDir',
'PodDir',
'VolumeDir',
'XarDir',
'get_current_image_versions',
'merge_dict_of_sets',
]
import collections
from pathlib import Path
import foreman
from g1 import scripts
from... |
from migen import Module, Signal, Instance, ClockDomain, If
from litex.build.lattice.platform import LatticePlatform
from litex.soc.cores import up5kspram, spi_flash
from litex_boards.targets.fomu import _CRG
import litex.soc.doc as lxsocdoc
import spibone
from ..romgen import RandomFirmwareROM, FirmwareROM
from .... |
#!/usr/bin/env python3
"""Test the functions found in the Snakefile"""
import sys, os, re
import unittest
import logging
from itertools import takewhile
from pprint import pprint
from unittest.mock import Mock, patch
SNAKEFILE = os.path.abspath(os.path.dirname(__file__) + '/../Snakefile.main')
DATA_DIR = os.path.abs... |
"""
Simple REST API for CRUD operations, when identity is Mongo's ObjectId and is part of database model.
Actually it's a most complicated scenario, there are many subtle points in this matter (see link below),
and all those points are out of scope of PyMotyc, which is only manages app<->database communication,
while ... |
"""
The ``mlflow.google`` module provides an API for deploying MLflow models to
Google Cloud AI Platforom.
"""
import docker
import google.auth
import logging
from google.cloud.aiplatform.gapic import ModelServiceClient
from mlflow.models.cli import _get_flavor_backend
from mlflow.utils.annotations import experimental... |
import os, time, cStringIO, subprocess
import libpry
import libqtile, libqtile.layout, libqtile.bar, libqtile.widget, libqtile.manager
import utils
theme = libqtile.manager.Theme()
class TestConfig:
groups = ["a", "b", "c", "d"]
layouts = [
libqtile.layout.stack.Stack(stacks=1),
... |
# -*- coding: utf-8 -*-
from django.views.generic import (
CreateView,
DeleteView,
DetailView,
UpdateView,
ListView
)
from django.http import HttpResponse
from django.shortcuts import render, redirect
import json
from pprint import pprint
from .models import (
#================================... |
#!/usr/bin/env python2
# ~*~ coding: utf-8 ~*~
# OTRS Customer Mailing Helper Script
#
# Copyright © 2014, <NAME> <<EMAIL>>
# tarent solutions GmbH <<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... |
import collections
import contextlib
import os.path
import re
import sys
class ValidationError(ValueError):
def __init__(self, error_msg, ctx=None):
super().__init__(error_msg)
self.error_msg = error_msg
self.ctx = ctx
def __str__(self):
out = '\n'
err = self
w... |
import os
import numpy as np
from rich import print
from rich.progress import track
from norfair import Detection
try:
import motmetrics as mm
import pandas as pd
except ImportError:
from .utils import DummyMOTMetricsImport
mm = DummyMOTMetricsImport()
pandas = DummyMOTMetricsImport()
from colle... |
from __future__ import division
import logging
import jax.numpy as np
import jax
import numpy as raw_np
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.preprocessing import label_binarize
import scipy
import scipy.optimize
import scipy.linalg
from ..utils import clip_jax
from jax.config import ... |
#!/usr/bin/env python3
# Copyright 2018 <NAME>
#
# Licensed under the modified BSD (3-clause BSD) License.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implie... |
"""
We are going to focus at first on the Nasdaq100. We are going to scrape each trading day in the past 20 years.
The scope is to create a strategy which is able to beat the market. We are going to base our analisys on:
1. Technical indicators
2. Differrent stocks for the correlation
3. Dil... |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import sugartensor as tf
import numpy as np
import re as regex # REGular EXpression
import csv, string, codecs, random, librosa, time
from collections import Counter
from six.moves import cPickle, reduce, map
import sys
tr... |
from __future__ import absolute_import, division, print_function
import argparse
import logging
import os
import random
import sys
from io import open
import numpy as np
import torch
from torch.utils.data import (DataLoader, RandomSampler, TensorDataset)
from tqdm import tqdm, trange
from models.modeling_bert import... |
from generator.actions import Actions
import random
import string
import struct
import numpy as np
import math
import datetime as dt
MAX_NAME = 20
MAX_DESC = 200
def random_word(max_size=7, min_size=3):
characters = string.letters
max_size = max_size if max_size >= min_size else min_size
max_size = random... |
import re
from pygments.lexer import Lexer, RegexLexer, ExtendedRegexLexer, \
LexerContext, include, combined, do_insertions, bygroups, using
from pygments.token import Error, Text, \
Comment, Operator, Keyword, Name, String, Number, Generic, Punctuation
from pygments.util import get_bool_opt, get_list_opt, ... |
"""
Copyright (C) 2010 CNRS
Author: <NAME>, <NAME>
"""
from __future__ import print_function
import types
from enum import Enum
from . import signal_base, wrap
from .attrpath import setattrpath
if 'display' not in globals().keys():
def display(s):
print(s)
# --- FACTORY --------------------------... |
# Copyright 2016-2021 Blue Marble Analytics LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
"""Test login handler."""
import unittest
from unittest import mock
from requests import exceptions
from blinkpy.auth import (
Auth,
LoginError,
TokenRefreshFailed,
BlinkBadResponse,
UnauthorizedError,
)
import blinkpy.helpers.constants as const
import tests.mock_responses as mresp
USERNAME = "foo... |
import csv
import json
import zipfile
from typing import Dict
from pathlib import Path
from collections import Counter
from datetime import datetime, timezone
from dateutil import tz
from api import artwork, lookup, song_info
SKIP_FACTOR = 0.3
THIS_YEAR = datetime.now().year
class Track:
amid: int
artist: ... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
import copy
import logging
from model import util, work_path
CONF_JSON = util.load_json(work_path.in_project('./model/conf/rank_coef.json'))
SCORE_COEF = CONF_JSON["data"]
MAX_VAL = CONF_JSON["scale_max"]
def get_key_sea_count(all_key, text, unique=False):
if type(text) != set:
f_c = set(text) if unique ... |
#!/usr/bin/env -S python3 -i
# pylint: disable=invalid-name
'''
A graph data structure
'''
import typing;
import itertools as its;
import functools as fts;
from ..funcs import kd;
from ..shared import funcChain, _slots, objName;
Or = typing.Union;
_Vertex: type = int;
class Vertex: #(int):
'A vertex class'... |
# Heroku manager for your Dragons-Userbot
# CC- @refundisillegal\nSyntax:-\n.get var NAME\n.del var NAME\n.set var NAME
# Copyright (C) 2020 <NAME>.
# All rights reserved.
import asyncio
import math
import os
import heroku3
import requests
import urllib3
from dragons import drgub
from ..Config import Config
from ... |
"""
Unit and regression test for the alchemicalitp package.
"""
# Import package, test suite, and other packages as needed
import alchemicalitp
import pytest
import os
from pkg_resources import resource_filename
from tempfile import NamedTemporaryFile
@pytest.fixture
def urea():
return alchemicalitp.top.Topology(... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2016, Anaconda, Inc. All rights reserved.
#
# Licensed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------... |
import sys
import os
import requests
from urllib.parse import urlparse
from . import err
from .cursors import Cursor
from .optionfile import Parser
from . import converters
from ._compat import PY2, range_type, text_type, str_type, JYTHON, IRONPYTHON
DEBUG = False
VERBOSE = False
class Connection(object):
"""
... |
#!/usr/bin/env python3
from sys import argv
from struct import pack, unpack
from enum import Enum
from os import listdir, path
from template import header
class ImageDataDirectory(Enum):
IMAGE_DIRECTORY_ENTRY_EXPORT = 0,
IMAGE_DIRECTORY_ENTRY_IMPORT = 1,
IMAGE_DIRECTORY_ENTRY_RESOURCE = 2,
IMAGE_DIREC... |
# Software Name: AIVC
# SPDX-FileCopyrightText: Copyright (c) 2021 Orange
# SPDX-License-Identifier: BSD 3-Clause "New"
#
# This software is distributed under the BSD-3-Clause license.
#
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
"""
Define different gop structure in this file.
A GOP is a dictionnary of ... |
from viztools.sequence import WellSequence
import viztools as vz
import matplotlib.pyplot as plt
import cv2, copy
import numpy as np
import matplotlib.patches as mpatches
import math
import matplotlib.cm as cm
import matplotlib.animation as animation
def get_default_rc_params(dpi = 150):
rc = { 'figure.dpi' : 150... |
# coding=utf-8
# @Time:2021/6/210:11
# @author: SinGaln
"""处理加载数据"""
import os
import ast
import copy
import json
import torch
import logging
from utils import get_labels
from torch.utils.data import TensorDataset
logger = logging.getLogger(__name__)
class InputExample(object):
"""
输入的为两个句子,利用[SEP]进行分隔
... |
#!/usr/bin/python
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = r'''
module: import_eks
short_description: Import an AWS EKS cluster into an ACM Hub cluster
author:... |
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import difflib
import os
import re
import unittest
from strict_enum_value_checker import StrictEnumValueChecker
class MockLogging(obj... |
from typing import cast, List, Dict, Set, Optional
from spec_random import SPEC_RANDOM
from spec_basis import Rand, Kobj, Lego, Syscall, Program, Executable
from util_bean import Bean
class RandVector(Rand):
meta: List[int]
class KobjVector(Kobj):
pass
class LegoVector(Lego[RandVector, KobjVector]):
... |
# coding=utf-8
# Copyright 2019 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
from enum import Enum
import time
import logging
import asyncio
import socket
import struct
import random
import types
WIRELESS_PORT = 27016
MCAST_IPADDR = "192.168.3.11"
REGISTER_PDU = 1
RESPONSE_PDU = 2
DATA_PDU = 3
def is_mcast(ipaddr):
addr = socket.inet_aton(ipaddr)
if addr >= socket.inet_aton('192... |
#!/usr/bin/env python
# cardinal_pythonlib/modules.py
"""
===============================================================================
Original code copyright (C) 2009-2020 <NAME> (<EMAIL>).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version 2.0 (the "License");
y... |
import keras.backend as K
from keras.layers import Dense, Dropout, BatchNormalization, Activation, Lambda, Multiply, Masking
import matplotlib.pyplot as plt
import numpy as np
VERY_BIG_NUMBER = 1e30
VERY_SMALL_NUMBER = 1e-30
VERY_POSITIVE_NUMBER = VERY_BIG_NUMBER
VERY_NEGATIVE_NUMBER = -VERY_BIG_NUMBER
def disan(rep_... |
import json
import os
import re
from typing import List
import attr
from attr.validators import instance_of
from .util import find_data_dir
DATA_DIR = find_data_dir('DSTC10-SIMMC') # give root folder name of simmc2 as argument. Ex) find_data_dir('DSTC10-SIMMC')
'''
Fashion Metadata
'''
FASHION_SIZES = [
"... |
# -*- coding: utf-8 -*-
import argparse
import logging
import os
from pathlib import Path
import sys
lgr = logging.getLogger('abagen')
def _resolve_path(path):
""" Helper function for get_parser() to resolve paths
"""
if path is not None:
try:
return str(Path(path).expanduser().reso... |
#!/usr/bin/env python
"""Client actions dealing with memory."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import collections
import io
import os
import re
import shutil
from future.builtins import str
import psutil
from typing import Iterable
fro... |
"""
Item 61: Know How to Port Threaded I/O to asyncio
This item shows how to port code that does threaded, blocking I/O over coroutines and asynchronous I/O.
Slaitkin implements a TCP-based server (Transfer Control Protocol. See https://en.wikipedia.org/wiki/Transmission_Control_Protocol)
for guessing a number. Th... |
import os
import numpy as np
import pickle
from sklearn.decomposition import PCA
import argparse
import matplotlib
matplotlib.use('AGG')
import matplotlib.pyplot as plt
import umap
def fit_PCA(train_data, weights_dir, labels, conditions):
""" Fit a PCA model accounting for top 50% variance to the train_data,
a... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Ericsson AB
#
# 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 ... |
import os
import time
import itertools
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
tqdm.monitor_interval = 0
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
#from tensorboard_logger import configure, log_value
from torch.utils.data.... |
# -*- coding: utf-8 -*-
import re
import gsxws
from django.db.models import Q
from django.core.cache import cache
from django.contrib import messages
from django.shortcuts import render, redirect
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.http import QueryDict, Htt... |
# BS mark.1-55
# /* coding: utf-8 */
# BlackSmith Extension Manager
# This plugin distributed under Apache 2.0 license.
# (c) simpleApps, 2012 — 2013.
## NOTICE:
## All plugins that depend from another plugins or files (not help files that placed in help dir)
## Must be contain this code: #-extmanager-depends:de... |
"""cogeo_mosaic.overviews: create low resolution image from a mosaic."""
import random
from concurrent import futures
from contextlib import ExitStack
from typing import Any, Dict, List, Tuple
import click
import mercantile
import numpy
import rasterio
from affine import Affine
from rasterio.io import MemoryFile
from... |
from tkinter import *
from tkinter import scrolledtext
import PIL.Image
import PIL.ImageTk
import cv2
from time import time
class monitor:
# Parameter: bit_mess: bit seqence to be sent (in string form)
def __init__(self, master, bit_mess):
'''
Defines the monitor window.
... |
#!/usr/bin/env python
# coding: utf-8
import os
from pathlib import Path
import pathlib
import numpy as np
from ALOS.process import *
class ALOS2_pre_post():
def __init__(self,directory,project_name):
self.directory = directory
self.project_name = project_name
self.pre_img_list ... |
# Copyright <NAME> 2013-2020
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#-------------------------------------------------------------------------------
# RunProcessTest
#--------------... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
############### TF Version: 1.13.1/Python Version: 3.7 ###############
"""
import os
import glob
import random
import shutil
import tensorflow as tf
from datetime import date, timedelta
from tensorflow_estimator import estimator
from model_local import lr, fm, deepcrossin... |
import copy
import logging
from collections import defaultdict
from sklearn.linear_model import LogisticRegression, LinearRegression
from ...constants import AG_ARGS, AG_ARGS_FIT, BINARY, MULTICLASS, REGRESSION, SOFTCLASS, PROBLEM_TYPES_CLASSIFICATION
from ...models.abstract.abstract_model import AbstractModel
from .... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.db import DataError
from ApiManager.models import ProjectInfo, ModuleInfo, TestCaseInfo, UserInfo, EnvInfo
logger = logging.getLogger('HttpRunnerManager')
'''用户注册信息落地'''
def add_register_data(**kwargs):
user_info = UserInfo.object... |
#!/usr/bin/env python
################################################################################
# COPYRIGHT(c) 2018 STMicroelectronics #
# #
# Redistribution and use in source and binary forms, w... |
#!/usr/bin/env python3
import ccxt
from configparser import ConfigParser
import json
import os
import pickle
import redis
import socket
import tempfile
import time
import threading
import zlib
import numpy as np
import talib.abstract as ta
from pandas import DataFrame, Series
from requests_futures.sessions import Futu... |
# This file contains NodeFlow samplers.
import sys
import numpy as np
import threading
import random
import traceback
from ... import utils
from ...node_flow import NodeFlow
from ... import backend as F
try:
import Queue as queue
except ImportError:
import queue
__all__ = ['NeighborSampler', 'LayerSampler']
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 11 11:09:56 2014
@author: Greg
Taxonomy Parser
Much faster than the version in taxonomy.py
Does everything in memory instead of through mongodb (~2-3 hrs > ~30 sec)
To import manually:
cat tax.json | parallel -j8 --pipe mongoimport -d taxonomy -c taxonomy
mongo taxon... |
from nwbwidgets import view
import matplotlib.pyplot as plt
from ipywidgets import widgets
from IPython import display
from collections.abc import Iterable
from pynwb import ProcessingModule
from pynwb.core import NWBDataInterface
from matplotlib.pyplot import Figure
from datetime import datetime
from typing import Uni... |
#
# Copyright 2015, 2016 Hewlett Packard Enterprise Development Company LP
# Copyright 2016 Cray Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICE... |
import datetime
import os
import threading
from typing import Optional, List
import requests
from sqlalchemy import create_engine, Column, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from platypush.backend import Backend
from platyp... |
import numpy as np
import math
import time
from PIL import Image
from skimage.transform import hough_line, hough_line_peaks
from PIL import Image, ImageEnhance
from comm_handler import TypeID
import matplotlib.pyplot as plt
ShowHoughTransformResult = False
# old version: red -> background1, white -> background2
BACKG... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''A simple HTTP accessible database for IoT projects.'''
__author__ = 'luphord'
__email__ = '<EMAIL>'
__version__ = '0.4.0'
import json
import sqlite3
import urllib.parse
from datetime import datetime, date, timedelta
from typing import Dict, Union, Any, Callable, Iter... |
import logging
import os
import re
import shutil
import sys
import tempfile
import xml.etree.ElementTree
from argparse import ArgumentParser
import yaml
from . import checkers
from . import misc
from . import problems
from . import results
from ._version import __version__
class ProcessError(Exception):
pass
... |
# Standard library
import argparse
import enum
import glob
import os
import subprocess
import time
from typing import Any, Callable, Dict, Iterable, List, Optional, Union
# PyPI
import serial
from dmppl.base import verb, asrtNumber
from dmppl.bytePipe import BpAddrs, BpAddrValues, BpMem, \
bpReadSequential, bpWr... |
import matplotlib.pyplot as plt
import numpy as np
import os
import json
import seaborn as sns
import re
sns.set(style="darkgrid")
num_params_list = [10, 2010, 4010, 6010, 8010, 10010, 20010, 30010, 40010]
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
... |
import numpy as np
import pandas as pd
import os.path
import sys, traceback
import random
import re
import string
import pickle
import string
from nltk.probability import FreqDist
MAX_TOKENS = 512
MAX_WORDS = 400
def truncate(text):
"""Truncate the text."""
# TODO fix this to use a variable instead of 511... |
#!/usr/bin/env python
"""
This program implements some touch screen tapping feature extraction methods.
Elias's R code translated by Arno to Python.
Authors:
- <NAME>, 2015 (<EMAIL>)
- <NAME>, 2015 (<EMAIL>) http://binarybottle.com
Copyright 2015, Sage Bionetworks (http://sagebase.org) Apache v2.0 Licens... |
from datetime import date, timedelta
from django.db.models import Count, Q, Avg
from django.db.models.functions import TruncMonth
from extlinks.links.models import LinkEvent
from logging import getLogger
logger = getLogger('django')
def get_date_count(dates, check_date):
"""
Find the number of events on a... |
import logging
import re
import socket
import threading
import time
from collections import deque
import six
from requests import ConnectionError
from requests.exceptions import ChunkedEncodingError
from ..errors import Etcd3WatchCanceled
from ..models import EventEventType
from ..utils import check_param
from ..util... |
# Copyright 2019 <NAME>
# Licensed under the Apache License, Version 2.0 (the "License")
import math
import numpy as np
import torch
class Beam(object):
def __init__(self, max_node=10, init_state=[1], len_norm=True):
self.max_node = max_node
self.len_norm = len_norm
self.adv_scores ... |
# python3.7
"""Contains the function to build optimizer for runner."""
import math
import os
import torch
import sys
sys.path.append(os.getcwd())
from idinvert_pytorch.models.stylegan_generator_idinvert import StyleGANGeneratorIdinvert
__all__ = ['build_optimizer', 'build_optimizers']
_ALLOWED_OPT_TYPES = ['SGD', 'A... |
from __future__ import division
from __future__ import print_function
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from pygcn.utils import load_data, accuracy
from pygcn.models import GCN
from collections import OrderedDict
# Training setti... |
"""
Strain Analysis of Flower in Washington State
Copyright (c) 2022 Cannlytics
Authors: <NAME> <<EMAIL>>
Created: 2/17/2022
Updated: 2/17/2022
License: MIT License <https://opensource.org/licenses/MIT>
Description: This script calculates various statistics about strains from the
Washington State traceability data (2... |
import os
from flask import (
Flask, flash, render_template,
redirect, request, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
import urllib.reques... |
import json
import uuid
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model, login, logout
import requests
from rest_framework import permissions, views, response, status
from . import exceptions
from . import models
from . import serializers
FACEBOOK_API_BASE_URL = 'https... |
# -*- coding: utf-8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.conf import settings
from django.urls import reverse
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
from rand... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import time
import argparse
import sys
import numpy as np
import torch
import torch.optim as optim
from tqdm import tqdm
from network.BEV_Unet import BEV_Unet
from network.ptBEV import ptBEVnet
from dataloader.dataset import collate_fn_BEV,SemKITTI,SemKITTI_labe... |
import time
import csv
import random
# branje_preferenc(dat):
# Funkcija, ki prebere preference posameznikov, zapisane v csv datoteki.
# Prva številka v posamezni vrstici ponazarja posameznika, ostale pa njegove preference od najbolj zaželjene,
# do najmanj zaželjene osebe.
def branje_preferenc(dat): ... |
import typing
import math
from collections.abc import Iterable
import numpy as np
import sacrebleu
from rouge_score import rouge_scorer
import sklearn.metrics
import random
from lm_eval.metric_impls import sari as sari_impl
def mean(arr):
return sum(arr) / len(arr)
def pop_stddev(arr):
mu = mean(arr)
re... |
from fastapi import FastAPI,Body, Request, File, UploadFile, BackgroundTasks, Form
from fastapi.templating import Jinja2Templates
import shutil
import os
import json
from csv import writer
from datetime import datetime
from typing import Optional, List
import shutil
import pandas as pd
import requests
from scrapy imp... |
from celery import shared_task, current_task, states
from datetime import datetime, timezone, timedelta
from django.db import transaction
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.core import mail
from .models import Summoner, Storage, MonsterInstance, Monst... |
"""XML parser"""
from xml.dom.minidom import Node
from tonnikala.ir.nodes import Element, If, For, Define, Import, \
EscapedText, Block, Extends, Expression, Code, With, EmptyAttrVal
from ..expr import handle_text_node # TODO: move this elsewhere.
from ..ir.generate import BaseDOMIRGenerator
from .docparser impor... |
"""IDL coding."""
from dataclasses import make_dataclass, asdict, fields as dc_fields
from types import MappingProxyType
from keyword import kwlist
from typing import Mapping, Optional, cast, Type
from solana.publickey import PublicKey
from construct import Construct
from borsh_construct import (
CStruct,
Vec,... |
# coding=utf-8
import enum
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (
Column, Integer, String, CHAR, SmallInteger, ForeignKey, Boolean, Enum
)
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
engine = None
Session = None
... |
import numpy as np
from sklearn import preprocessing
from datetime import datetime
def _corr(C):
R=np.empty_like(C)
#compute correlation from covariance
for i,ci in enumerate(C):
for j,cij in enumerate(ci):
R[i,j] = cij / np.sqrt(C[i,i] * C[j,j])
return R
def pcaFun(x, whiten=False,e=0, type='cov', method='s... |
from a2c import a2c
from gym_minigrid.wrappers import *
from gym_minigrid.envs.empty import *
import torch
import os
import time
import glob
from collections import deque
from a2c_ppo_acktr import algo as algorithm
from a2c_ppo_acktr.arguments import get_args
from a2c_ppo_acktr.envs import *
from a2c_ppo_acktr.model im... |
# conftest.py --- for use with pytest
#
# This file is part of scqubits: a Python package for superconducting qubits,
# arXiv:2107.08552 (2021). https://arxiv.org/abs/2107.08552
#
# Copyright (c) 2019 and later, <NAME> and <NAME>
# All rights reserved.
#
# This source code is licensed under the BSD-style lic... |
import numpy as np
import itertools
import random
import json
import pickle
import os
from copy import deepcopy
# hvo preprocess methods
def pad_to_match_max_seq_len(hvo_seq, max_len):
pad_count = max(max_len - hvo_seq.hvo.shape[0], 0)
hvo_seq.hvo = np.pad(hvo_seq.hvo, ((0, pad_count), (0, 0)), 'constant')
... |
import re
from collections import defaultdict
import json
from nltk.corpus import stopwords
import pickle
########## FUNCTIONS RELATED TO COREFERENCE PROCESSING #########################
def get_sentence_offsets(doc):
"""Get a list of (start, end) offsets of the sentence documents."""
sent_offsets=[]
for ... |
# This tools are modified from
# https://github.com/anucvml/ddn/blob/master/apps/classification/image/main.py
# developed by
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
import shutil
import time
import numpy as np
import torch
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distr... |
# -*- coding: utf-8 -*-
"""
file: module_liemdframe_test.py
Test pylie filter functions and workflows
"""
import os
import glob
import unittest
from pandas import DataFrame
from pylie import LIEMDFrame
from pylie.methods.fileio import read_gromacs_energy_file
from pylie.filters.filtersplines import FilterSplines
... |
# -*- coding: future_annotations -*-
import ast
import inspect
import logging
import symtable
from typing import cast, TYPE_CHECKING
from IPython import get_ipython
from nbsafety.analysis.symbol_ref import SymbolRef, Atom
from nbsafety.data_model.data_symbol import DataSymbol, DataSymbolType
from nbsafety.utils.misc_... |
######
# process_video.py
#
# Split a video into frames, run the frames through run_tf_detector_batch.py, and
# optionally stitch together results into a new video with detection boxes.
#
######
#%% Constants, imports, environment
import os
import tempfile
import shutil
import argparse
import itertools
from detectio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.