text stringlengths 3.07k 12.6k |
|---|
import numpy as np
import scipy.io as scio
import os.path
import numpy.ma as ma
import datetime as dt
import pickle
from Helper_Functions.File_Ops import save_data
def process_data(in_directory, out_directory, start_time, stop_time):
print('Processing data files.')
# Track number of days of data
n_days... |
#
# Please note that this file has been modified by Unbound Tech
#
""" Functional tests for signature / verification"""
import logging
import pytest
from pypkcs11.sign_verify import c_sign, c_verify
from pypkcs11.key_generator import c_generate_key_pair, c_generate_key, c_destroy_object
from pypkcs11.defines import *
... |
import json
import re
import numpy as np
import os
import cv2
import argparse
import sys
import tensorflow as tf
import keras
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
def main(argv):
parser = argparse.ArgumentParser()
# Required arguments.
... |
"""
SocketIO-based rcstream client.
(c) 2014 <NAME>
This file is part of the Pywikibot framework, and is licensed under the MIT license.
This module requires socketIO_client to be installed:
pip install socketIO_client
"""
from __future__ import unicode_literals
import sys
import threading
if sys.version_info[... |
import json
from airone.lib.types import AttrTypeValue
from airone.celery import app
from entity.models import Entity, EntityAttr
from user.models import User
from job.models import Job
@app.task(bind=True)
def create_entity(self, job_id):
job = Job.objects.get(id=job_id)
if job.proceed_if_ready():
... |
import datetime
from ajax_select.fields import AutoCompleteSelectMultipleField
from crispy_forms.bootstrap import FormActions, Tab, TabHolder
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Button, Field, Layout, Submit, HTML
from django import forms
from django.db.models import Q
from djang... |
import os
from docx import Document
from flask import render_template, request, send_file, abort
from sqlalchemy import func
from functools import wraps
from jacowvalidator import app, document_docx, db
from flask_login import current_user, login_required
from jacowvalidator.models import AppUser, Conference, Lo... |
from flask import Flask, render_template
from flask import request, redirect
from db_connector.db_connector import connect_to_database, execute_query
# create the web application
webapp = Flask(__name__)
@webapp.route('/')
def home():
return render_template('home.html');
@webapp.route("/about_us")
def about_us... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import time
import json
import yaml
import requests
from multiprocessing.dummy import Pool
import subprocess
import argparse
try:
import queue
except ImportError:
import Queue
queue = Queue
local_zuul_status = False
config = {}
worker_... |
from uuid import UUID
from djangotoolbox.db.base import (
NonrelDatabaseFeatures,
NonrelDatabaseOperations,
NonrelDatabaseWrapper,
NonrelDatabaseClient,
NonrelDatabaseValidation
)
from cassandra import (
ConsistencyLevel
)
from cassandra.metadata import (
SimpleStrategy
)
from cassandra.c... |
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
"""
PyTorch has created a package called torchvision for vision tasks that has data loaders for dataset... |
import requests
import unicodedata
import re
from bs4 import BeautifulSoup
def remove_control_characters(s):
return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C")
def scrape_disciplina(URL):
disciplina = {}
labels = ['unidade', 'departamento', 'nome_en']
labels_br = ['CA', 'CT', 'CH... |
from epics import caget, caput
from time import sleep
from IEX_29id.devices.slits import SetSlit_BL
from IEX_29id.utils.misc import dateandtime
from IEX_29id.devices.beamline_energy import SetMono
from IEX_29id.devices.eps import Open_MainShutter
from IEX_29id.devices.eps import Close_MainShutter
def Reset_Mono_Limi... |
"""
This module provides routines for applying solar rotation functions to
map sequences.
"""
import numpy as np
import astropy.units as u
from sunpy.image.coalignment import apply_shifts
from sunpy.physics.differential_rotation import solar_rotate_coordinate
__author__ = '<NAME>'
__all__ = ['calculate_solar_rotat... |
import os
import numpy as np
import pytest
from tensorflow.keras.optimizers import Adam
from multiml import logger
from multiml.saver import Saver
from multiml.storegate import StoreGate
from multiml.task.keras import EnsembleTask, MLPTask
from multiml.task.keras.modules import DARTSModel, SumTensor
from multiml.task... |
import time
from py42.services.storage.restore import PushRestoreExistingFiles
from py42.services.storage.restore import PushRestoreLocation
from py42.settings import debug
from py42.util import format_dict
def create_restore_job_manager(
storage_archive_service, device_guid, archive_session_id
):
return Res... |
import json
from collections import defaultdict
from threading import Lock
from jsonschema import validate, ValidationError
from weavelib.exceptions import AuthenticationFailed, Unauthorized
from weavelib.exceptions import SchemaValidationFailed
from .messaging_utils import get_required_field
from .authorizers impor... |
import json
import logging
import os
from collections import defaultdict
from py2neo import Node, Relationship
from .multihetnet import MultiHetNet
from ..constants import COLOR, ANNOTATIONS, TYPE
log = logging.getLogger(__name__)
log.setLevel(logging.WARNING)
def get_resources(resources):
if isinstance(resour... |
# SPDX-License-Identifier: MIT
"""
.. module:: impactgen
:platform: Windows
:synopsis: Impactgen module to handle conversion of images to materials
usable in BeamNG.tech, image similarity matrix computation, and
distinct image selection.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
imp... |
from urllib.parse import urlparse, urlencode, urlunparse
from django.contrib import admin
from django.contrib.admin.options import ModelAdmin
from django.http import (HttpResponseForbidden, HttpResponseBadRequest, HttpResponseRedirect, QueryDict)
from django.urls import reverse
from django.urls import re_path
from dja... |
import numpy as np
import rasterio as rio
import geopandas as gpd
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from shapely.ops import cascaded_union
from shapely.geometry.polygon import Polygon
from cartopy.feature import ShapelyFeature
import matplotlib.patches as mpatches
def generate_handles(labels,... |
"""Flow-specific parameters for the ring scenario."""
import os
import numpy as np
from flow.controllers import IDMController
from flow.controllers import ContinuousRouter
from flow.controllers import RLController
from flow.core.params import SumoParams
from flow.core.params import EnvParams
from flow.core.params impo... |
import geocoder
from SPARQLWrapper import SPARQLWrapper, JSON
import geopy.distance
def get_location(name):
loc = geocoder.geonames(name, key="travelrec")
if loc.code == 'PCLI':
return 'COUNTRY_CODE', loc.country_code
else:
return 'COORD', loc.lat, loc.lng
def get_predicates_declaration... |
"""
config_prod_example.py
- settings for the flask application object
"""
import os
from datetime import timedelta
class BaseConfig(object):
CODE_LINK = "<a target='_blank' href='https://github.com/co-demos/toktok'>TokTok</a>"
RUN_MODE = "dev"
DEBUG = True
TEMPLATES_FOLDER = "/templates"
R... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}
import sys
sys.path.insert(1, '../')
import json
import pandas as pd
import numpy as np
from sklearn import preprocessing
from tqdm import tqdm
from STFE import Models, DataPreparer
from tensorflow.keras import optimizers
from pickle import ... |
#!/usr/bin/python3
import os
from pathlib import Path
from pathlib import PurePosixPath
from pathlib import PurePath
import shutil
import re
import subprocess
import glob
def checkVersion():
with open("RepoVivadoVersion", "r") as f:
repoVersion = f.read().strip()
if repoVersion == None:
print(... |
# Copyright (c) 2015 Uber Technologies, Inc.
#
# 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, merge, publ... |
#!/usr/bin/env python
import argparse
import csv
import datetime
import logging
import re
from bs4 import BeautifulSoup
import requests
import six
# Setup logging
logger = logging.getLogger('tickets-londontheatre-bot')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter("%(l... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from lxml import etree
class Request:
def __init__(self, key=""):
self.el_fbixml = etree.Element('FbiXml')
self.el_ticket = etree.SubElement(self.el_fbixml, 'Ticket')
self.el_key = etree.SubElement(self.el_ticket, 'Key')
self.el_key.text = key
self.el_fbimsgsrq = e... |
import os
import imgaug.augmenters as iaa
import json
import cv2
mode = "train" # Perform augmentation for dataset
qty = 200 # Size of dataset after augmentation
# ================================================================================== #
path = r"E:\PyProjects\Report\Faster_RCNN/data/" + m... |
"""Fitting peaks data with theoretical curve: 'A_0 + A · (t - t_0) · exp(- k · (t - t_0))'.
Fitting peaks data with theoretical curve: 'A_0 + A · (t - t_0) · exp(- k · (t - t_0))' using
Levenberg–Marquardt (LM) algorithm
(see. https://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm).
Typical usage exa... |
import torch
import torch.nn as nn
from models.modules import (
build_mlp,
SoftAttention,
PositionalEncoding,
ScaledDotProductAttention,
create_mask,
proj_masking,
PositionalEncoding,
)
from models.film import FiLMGenerator, FiLMedResBlocks, FiLMTail
class SelfMonitoring(nn.Module):
"... |
"""
Further in creationKeys() function will be used alphabetic variables.
I will explain the meaning of each of them.
They were used for convenience.
[p], [q] - two prime numbers.
[n] - the product of [p] on [q].
[f] - euler function of [n].
[e] - an open exponent is such that ([e] is prime) and (e < f) and (f m... |
import logging as log
import sys
import time
import os.path as osp
import cv2
import numpy as np
from openvino.inference_engine import IENetwork
from argparse import ArgumentParser
from utils.ie_module import InferenceContext
from core.semantic_detection import SemanticSegmentation
#Global
DEVICE_KINDS = ['CPU', 'G... |
from oggm_edu import GlacierBed, Glacier, MassBalance, GlacierCollection
import pytest
mb = MassBalance(ela=3000, gradient=8)
bed = GlacierBed(top=3700, bottom=1500, width=600)
glacier1 = Glacier(bed=bed, mass_balance=mb)
glacier2 = Glacier(bed=bed, mass_balance=mb)
bed_new = GlacierBed(top=3700, bottom=2500, width=30... |
# -*- coding: utf-8 -*-
import time
import re
import mechanize
from bs4 import BeautifulSoup
print(''' ... |
"""
Copyright 2017-present, Airbnb Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sof... |
import sys
import numpy as np
from PIL import Image
from scipy.misc import imresize
from scipy.ndimage import rotate
def mirror(img, label=None):
img = img[:, ::-1, :]
if label is not None:
label = label[:, ::-1, :]
return img, label
def flip(img, label=None):
img = img[::-1, :, :]
if ... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache 2.0 License.
import infra.network
from ccf.ledger import NodeStatus
import http
import suite.test_requirements as reqs
from loguru import logger as LOG
@reqs.description("Primary and redirection")
@reqs.at_least_n_nodes(2)
def t... |
# Author: <NAME>
# Last Edited: 12/30/2017
"""
Takes in some text file and calculates the freguency of each character.
Using the frequency it constructs a min-heap implementation of a Huffamn Tree
wich will be used to create a Huffman Coding. After encoding, returns a
compressed file and a codebook with locations spec... |
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from collections import deque
import PIL
import random
import matplotlib.pyplot as plt
import flloat
from flloat.parser.ltlf import LTLfParser
from tqdm import tqdm
from gym_minigrid.wrappers import *
# from models.utils import *
# from mod... |
import unittest
from datetime import datetime
from jsonweb.validators import Dict, List, String, Regex, Integer, Float, \
Number, OneOf, SubSetOf, DateTime, Boolean, EnsureType, ValidationError
class TestEachValidator(unittest.TestCase):
def test_string_validator(self):
v = String()
self.asse... |
from os import startfile
from sys import exit
import pygame as pg
from labirintos import labirinto1
from variavel import *
pg.init()
## Classe do personagem
class Personagem(pg.sprite.Sprite):
def __init__(self, imagem, blocos):
pg.sprite.Sprite.__init__(self)
self.im = imagem
self.im... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 22:51:18 2019
@author: sachin_sharma
"""
# Adding georefrences to probability patches
from osgeo import gdal
from osgeo import gdal_array
from osgeo import osr
import subprocess
import argparse
import os, glob
import errno
import cv2
from io im... |
# Copyright 2020 EMBL - European Bioinformatics Institute
#
# 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... |
# System documented in https://zulip.readthedocs.io/en/latest/subsystems/logging.html
from collections import defaultdict
from typing import Any, Dict
from django.conf import settings
from django.core.mail import mail_admins
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from ... |
# NOTE: THIS FILE IS INTENTIONALLY NAMED TO BE RUN LAST. SEE test_shutdown_host().
import logging
import pprint
import pytest
import sdk_cmd
import sdk_install
import sdk_marathon
import sdk_plan
import sdk_tasks
import shakedown
from tests import config
RECOVERY_TIMEOUT_SECONDS = 20 * 60
log = logging.getLogger(__... |
import math
### START SETTINGS ###
app.colors = {
'appBackground': rgb(20, 21, 38),
'speedBackground': rgb(35, 47, 78),
'downloadSpeed': rgb(102, 204, 255),
'uploadSpeed': rgb(75, 75, 255)
}
app.background = app.colors['appBackground']
app.stepsPerSecond = 60
app.steps = 0
seed(17754977) # Debugging... |
"""Supporting functions for the text/tabular-reporting commands.
Namely: breaks, genemetrics.
"""
from __future__ import absolute_import, division
from builtins import str
import collections
import math
import sys
import numpy as np
import pandas as pd
from . import params
from .segmetrics import segment_mean
iteri... |
# mlxtend Machine Learning Library Extensions
# Author: <NAME> <<EMAIL>>
#
# License: BSD 3 clause
import collections
import math
from ..frequent_patterns import fpcommon as fpc
def fpmax(df, min_support=0.5, use_colnames=False, max_len=None, verbose=0):
"""Get maximal frequent itemsets from a one-hot DataFrame
... |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2014, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of con... |
from __future__ import annotations
import inspect
from functools import partial
from typing import TYPE_CHECKING, Any, Callable, Optional, Union
from magicgui.widgets import FunctionGui, MainFunctionGui
if TYPE_CHECKING:
from magicgui.application import AppRef
__all__ = ["magicgui", "magic_factory", "MagicFacto... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 19-3-8 上午10:46
# @Author : MaybeShewill-CV
# @Site : https://github.com/MaybeShewill-CV/attentive-gan-derainnet
# @File : export_tf_saved_model.py
# @IDE: PyCharm
"""
Export tensorflow saved model
"""
import os.path as ops
import argparse
import cv2
im... |
#from __future__ import print_function
import numpy as np
import random
shapes = {
'T': [(0, 0), (-1, 0), (1, 0), (0, -1)],
'J': [(0, 0), (-1, 0), (0, -1), (0, -2)],
'L': [(0, 0), (1, 0), (0, -1), (0, -2)],
'Z': [(0, 0), (-1, 0), (0, -1), (1, -1)],
'S': [(0, 0), (-1, -1), (0, -1), (1, 0)],
'I'... |
import numpy as np
import glob
import pandas as pd
from tqdm import tqdm
import matplotlib.pyplot as plt
from scipy.spatial import distance
import dlib
import cv2
from model import create_model
from align import AlignDlib
import RPi.GPIO as GPIO
import time
import os
# Setup the GPIO PIN
GPIO.setmode(GPIO.BOARD)
GPIO.... |
"""Build the CloudFormation template for the Accretion replication listener."""
import itertools
from functools import partial
from typing import Callable
from accretion_common.constants import ARTIFACT_MANIFESTS_PREFIX, ARTIFACTS_PREFIX, LAYER_MANIFESTS_PREFIX
from awacs import s3 as S3
from troposphere import (
... |
from pytest import fixture
import os
from requests_flask_adapter import Session
import tenacity
from kirby.api.ext import kafka_retry_args
from kirby.web import app_maker
from kirby.models import (
db,
Environment,
JobType,
Job,
Context,
Schedule,
NotificationGroup,
NotificationEmail,
... |
import base64
import time
import logging
import zlib
from functools import partial
import raven
from raven.base import Client
from raven.utils import get_auth_header
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from raven.contrib.tornado import SentryMixin
from dorthy.json import jsonify
from dorthy... |
from pathlib import Path
from threading import TIMEOUT_MAX
from typing import List, Optional
import fire # type: ignore
import numpy as np
from joblib import Parallel, delayed # type: ignore
from numpy.random import default_rng
from elicitation import append, load, make_mode_reward
from sampling import Sampler
from... |
import cv2
import sys
import os
import pickle
import numpy as np
from pathlib import Path
from PIL import Image
from tricks import *
from ai import *
from tqdm import tqdm
import argparse
def go_flipped_vector(x):
a = go_vector(x)
b = np.fliplr(go_vector(np.fliplr(x)))
c = np.flipud(go_vector(np.flipud(x)... |
#! /usr/bin/env python3
import numpy as np
import argparse
from collections import Counter
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import eigsh
from scipy.linalg import svd
from scipy.linalg import orthogonal_procrustes as proc
###########################################################
## Reprodu... |
# coding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License... |
"""
Copyright 2017-2019 Fizyr (https://fizyr.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... |
from timm.models.vision_transformer import Block, VisionTransformer, Attention
from torch import nn
import torch
import torch.nn.functional as F
class NystromAttention(Attention):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., num_landmarks=64):
super().__i... |
#.........................................................................................................................................
import sys
class createNewMap:
def __init__(self):
self.nameOfTheMap=""
self.stationList=[] # Describe all the name of th... |
""" Utilities for Computational Assyriology """
import requests
from tqdm.auto import tqdm
import os
import zipfile
import json
import pandas as pd
def format_project_list(projects):
project_list = projects.lower().strip().split(',')
project_list = [project.strip() for project in project_list]
return(proje... |
#!/usr/bin/env python3
#
# Copyright (c) 2021, General Electric Company, Inc.
#
# All Rights Reserved
#
# This material is based upon work supported by the Defense Advanced Research
# Projects Agency (DARPA) under Contract No. FA8750-20-C-0203.
#
# Any opinions, findings and conclusions or recommendations expressed in ... |
"""A minimal command-line utility which samples counter values around the
machine.
Installed as "rig-counters" by setuptools.
"""
import sys
import argparse
import subprocess
import time
import rig
from six import iteritems
from six.moves import input
from rig.machine_control import MachineController
from rig.mac... |
from sys import getrefcount
from genutility.test import MyTestCase, parametrize
from hattrie import HatTrieMap
def get_key(i):
return b"Key " + str(i).encode("ascii")
def get_value(i):
return b"Value " + str(i).encode("ascii")
def get_filled_map(nb_elements, burst_threshold):
map = HatTrieMap()
map.burst_thres... |
# -*- coding: utf-8 -*-
import dill
import numpy as np
from collections import defaultdict
from pathlib import Path
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import PCA
import logging
import logging.config
# from embedding.investigate import tsne_plot
def _get_logger()... |
"""Contains default values and models."""
from decimal import Decimal
from enum import auto
from enum import Enum
from typing import Optional
from box import Box
from awattprice import defaults
class Region(str, Enum):
"""Identify a region (country)."""
DE = "DE"
AT = "AT"
@property
def tax(se... |
# this_file = "venv/bin/activate_this.py"
# exec(open(this_file).read(), {'__file__': this_file})
import os
import math
import io
from flask import Flask, render_template, send_file, abort, request
from PIL import Image
(MIN_X, MAX_X, MIN_Y, MAX_Y) = (-343646, 1704354, 5619537, 7667537)
MAX_TILE_SIZE = 500 * math.pow... |
# -*- coding: utf-8 -*-
import logging
from spaceone.core.error import *
from spaceone.core.service import *
#from spaceone.plugin.model import Supervisor, SupervisorRef
from spaceone.plugin.manager.plugin_manager import *
from spaceone.plugin.manager.supervisor_manager import *
_LOGGER = logging.getLogger(__name__)... |
# import argparse
import tkinter as tk
from cropper import crop
import traceback
def str2bool(string):
positive = ['true',
't',
'y',
'yes',
'1',
'correct',
'accept',
'positive'
]
if string.lower() in positive:
return True
... |
import torch
from torch.autograd.function import Function
class SyncBatchNorm(Function):
@staticmethod
def forward(self, input, weight, bias, running_mean, running_var, eps, momentum, process_group, world_size):
input = input.contiguous()
count = torch.Tensor([input.numel() // input.size(1)])... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... |
import os
from skimage import io, transform
import torch
import torchvision
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms#, utils
# import torch.optim as optim
import numpy as np
from PIL imp... |
# Copyright (C) 2017 Network Device Education Foundation, Inc. ("NetDEF")
#
# 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... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
import sys
import os
import numpy as np
from PIL import Image
import torchvision
from torch.utils.data.dataset import Subset
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
import torch
import torch.nn.functional as F
import random
def fix_seed(seed=777):
np.random.seed(see... |
"""
raven.contrib.flask
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
try:
from flask_login import current_user
except ImportError:
has_flask_login = False
else:
has_f... |
import logging
import base64
import hashlib
from Cryptodome.PublicKey import RSA
from .exceptions import CephNodeHasRolesException, CephNodeFqdnResolvesToLoopbackException
from .salt_utils import SaltClient, GrainsManager, PillarManager
logger = logging.getLogger(__name__)
CEPH_SALT_GRAIN_KEY = 'ceph-salt'
clas... |
import numpy as np
import scipy
def compute_smoothed_firing_rate(spike_times, tt, sigma_in_secs):
"""Evaluate gaussian smoothing of spike_times at uniformly spaced array t
Args:
spike_times:
A 1D numpy ndarray of spike times
tt:
1D array, uniformly spaced, e.g. the output of np... |
# factor 计算
import pendulum
# from ENIAC import Timer
import toolkit
if toolkit.__version__=="1.7.20":
from toolkit.managers import Timer
else:
from toolkit.tools.managers import Timer
from sanic import Blueprint
from sanic import response
from sanic_openapi import doc
import pymysql
import pandas as pd
import ... |
#coding=utf-8
import json
from handlers.base.base_handler import BaseHandler
from libs.article.article_libs import (
article_list_lib,
get_tags_categorys,
add_article_lib,
add_category_tag_lib,
del_category_tag_lib,
article_content_lib,
add_comment_lib,
add_second_comment_li... |
bl_info = {
"name": "One Key Export",
"version": (0, 4, 2),
"blender": (2, 80, 0),
"category": "Export",
"author": "<NAME>",
}
import bpy
import os, time, re
# --- --- --- #
class Snowdrop_OneKeyExport(bpy.types.Operator):
"""One Key Export - Snowdrop""" # Use this as a tool... |
#!/usr/bin/env python3
import argparse
import sys
from os import path
from typing import Optional, Tuple, List, Dict
from tqdm import tqdm
from openpyxl import load_workbook
from openpyxl.workbook import Workbook
from openpyxl.utils.cell import range_to_tuple
from openpyxl.worksheet.worksheet import Worksheet
from o... |
###############################################################################
# Language Modeling on Penn Tree Bank
#
# This file generates new sentences sampled from the language model
#
###############################################################################
import argparse
import sys
import os
import _pick... |
# -*- encoding: utf-8 -*-
"""
keri.help.ogling module
Provides python stdlib logging module support
"""
import os
import logging
import tempfile
import shutil
ogler = None # module global ogler instance used by all for keri console logging
def initOgler(level=logging.CRITICAL, **kwa):
"""
Initialize the o... |
'''
content defines the logic for the sub commands make load list edit drop.
It also defines the abilty for file and fold to export content.
'''
import os
import re
import requests
from mold.util import fs, system, query
# TODO: v0.2.0 have each task handler return an exit code from the ctx
# then refactor main to ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 1 18:53:05 2020
@author: shino
"""
import numpy as np
import pandas as pd
from pyntcloud import PyntCloud
import binvox_rw
import colorsys
import collections
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotli... |
import os
import sys
import subprocess
import spacy_udpipe
from Pedigree import Pedigree
def rel_to_linkage(path_to_file, nlp, out_dir):
""" Transform entity and relation annotation tags into LINKAGE format
and save it to a .ped file .
"""
ped = Pedigree()
path, file_name = os.path.split(path_to_... |
from .agents import Agent
from utils import try_to_move, get_train_data, conv_to_onehot, ReplayMemory, Transition
import numpy as np
import torch
import torch.nn
import torch.nn.functional as F
import torch.optim
from model import nn2048, nn2048_2, nn2048_3
from .expectimax import board_to_move
DEFAULT_PATH0 = 'model3... |
import os
import torch
import logging
import sys
import numpy as np
from collections import defaultdict
from scipy.spatial.distance import euclidean
from fastdtw import fastdtw
import matplotlib
matplotlib.use('cairo')
from matplotlib import pyplot as plt
import matplotlib.font_manager as mfm
import pickle
def set_log... |
import multiprocessing as mp
import winsound
import time
import math
import threading
import os
import sys
import json
class Sound:
'''
Highest level sound interface for winsound
Unfortunately, winsound always adds a small gap between the beeps. I'm leaving this code in case I need it in the future, b... |
"""Using annotated onsets, segment source audio files into individual
audio files, with each containing a single 'note'.
Usage:
segment_audio.py [options] <segment_index> <note_index> <note_audio_dir>
Example:
Arguments:
segment_index Input index file, as generated by `collect_data.py`.
note_index csv file... |
"""
Contains the implementation of the :class:`ReservoirSampling` abstract base class of all unweighted reservoir sampling
algorithms and the :class:`AbstractReservoirSampling` abstract class that simplifies the implementation of
:class:`ReservoirSampling` using the concept of skips.
"""
from abc import ABC, abstractm... |
import csv
import time
import click
import pandas as pd
from jinja2 import Template
from slack_sdk.errors import SlackApiError
from .utils import die, load_csv
from .client import client, list_channels
def create_or_update_channel(channels, channel_name, topic=None, purpose=None, dry_run=False, is_private=False, jo... |
import re
"""
By <NAME> <<EMAIL>>
Database of alt coin parameters
"""
class CoinInfo:
def __init__(self, **kw):
for k,v in kw.items():
setattr(self,k, v)
def matchname(self, name):
return re.search(name, self.names, re.IGNORECASE) is not None
def matchlevel(self, name):
... |
# <NAME>'s attempt to visualise the Collatz conjecture as inspired by a numberphile video
# inspiration here: https://www.youtube.com/watch?v=LqKpkdRRLZw
#
# Consider the following rules for an arbitrary chosen positive integer:
# - If the number is EVEN, half it
# - If the number is ODD, triple it and add one... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.