text stringlengths 3.07k 12.6k |
|---|
from pathlib import Path
from thinc.model import serialize_attr
import typer
import spacy
from spacy.tokens import DocBin
import json
from typing import Optional, List, Dict, Tuple
from wasabi import Printer
from pathlib import Path
import re
import srsly
from thinc.api import fix_random_seed
from thinc.types import Ra... |
import numpy as np
import random
import sys
from collections import defaultdict
from para import Params, Data_nocat, Data
SOS = 1
EOS = 2
OOV = 3
def loadFile(filename, maxLen = 50, chars = False):
if filename == '-':
fh = sys.stdin
else:
fh = open(filename, 'r')
result = []
tokFreqs = defaultdict(int)
... |
# -*- coding: utf-8 -*-
"""
logbook._stringfmt
~~~~~~~~~~~~~~~~~~
Advanced string formatting for Python >= 2.4.
This is a stripped version of 'stringformat', available at
* http://pypi.python.org/pypi/StringFormat
:copyright: (c) 2010 by <NAME>, <NAME>, <NAME>.
:license: BSD, see LICENSE ... |
from __future__ import absolute_import, division, unicode_literals
import matplotlib.pyplot as plt
import pandas as pd
# import seaborn as sb
import sys
import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
def norm(x, ts):
return (x - ts['mean']) / ts['std']
def... |
# Copyright 2017,2018,2019,2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... |
# Copyright 2018 - <NAME>
# <EMAIL>
# This was a quick script to generate a dally dragonfly topology for use with dragonfly custom model
import sys
from enum import Enum
import struct
import numpy as np
argv = sys.argv
DRYRUN = 0
if sys.version_info[0] < 3:
raise Exception("Python 3 or a more recent version is r... |
'''
amazon.py: interface to Amazon network services Rekognition and Textract
Authors
-------
<NAME> <<EMAIL>> -- Caltech Library
Copyright
---------
Copyright (c) 2018-2021 by the California Institute of Technology. This code
is open-source software released under a 3-clause BSD license. Please see the
file "LICE... |
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.views import APIView
from rest_framework import status
from django.utils.translation import ugettext_lazy ... |
import paho.mqtt.client as mqtt
import ssl
import logging
logger = logging.getLogger(__name__)
CONNECTION_RETURN_STATUS = {
0: 'Connection successful',
1: 'Connection refused - incorrect protocol version',
2: 'Connection refused - invalid client identifier',
3: 'Connection refused - server unavailable... |
## load environment
import streamlit as st
import pickle
import re
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
wnl = WordNetLemmatizer()
from pandas import DataFrame
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import Ridge
from numpy import c... |
import socket
import json
import logging
import os
import base64
from concurrent.futures import ThreadPoolExecutor
from time import sleep
from FtpMessage import FtpMessage
from FtpMessage import FtpData
from FtpMessage import FtpMessageEncoder
from FtpMessage import FtpResult
class FtpServer:
MAX_BYTES = 65536... |
import os.path, re
from waflib.TaskGen import feature, before_method, after_method
from waflib.Configure import conf
from waflib import Utils, Logs, Task, Context, Errors
@feature('*')
@before_method('process_source')
def default_variant(self):
if not self.env.VARIANT:
return
features = set(Utils.to_list(self.fea... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pickle
import numpy as np
from pathlib import Path
import pkg_resources
import random
# Load the names of the regions of the indicated connectome
def get_names(data_name, path_to_connectome_folder = None):
'''
Load the names of the regions of the indicated... |
"""Create Agronomic Sheets"""
import pyiem.cscap_utils as util
def has_or_create_worksheet(ssclient, sheet, title, rows, cols):
sheet.get_worksheets()
if title not in sheet.worksheets:
print("Adding worksheet with title: %s" % (title,))
ssclient.add_worksheet(sheet.id, title, rows, cols)
... |
"""
Pedagogical implementation of word2vec.
References
https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/models/word2vec.py
https://github.com/cbellei/word2veclite
cbow:
predict target word from context word(s)
skipgram:
predict context word(s) from target word
"""
from collections import Counter... |
import json
from rest_framework import status
from parameterized import parameterized
from core.entity.entry_points.authorizations import AuthorizationModule
from core.entity.user import UserSet
from .base_test_class import BaseTestClass
def profile_set_provider():
"""
Returns the tested data for PUT/PATCH ... |
#!/usr/bin/env python3
# Compatible also with Python2.7
'''
Author <NAME>
Date 08/2020
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 requir... |
from __future__ import annotations
from dataclasses import dataclass
import dingus.tree.hasher as hasher
from .errors import *
from dingus.utils import hash
from .constants import (
DEFAULT_KEY_LENGTH,
LEAF_PREFIX,
INTERNAL_LEAF_PREFIX,
BRANCH_PREFIX,
EMPTY_HASH,
NODE_HASH_SIZE,
DEFAULT_SUB... |
'''
Native support of MultitouchSupport framework for MacBook (MaxOSX platform)
===========================================================================
'''
__all__ = ('MacMotionEventProvider', )
import ctypes
import threading
import collections
import os
from nuiinput.provider import MotionEventProvider
from nuii... |
# Librerías de mensajes
from petsitter_custom_interface.srv import ScanMsg
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
# Liberías de python para ROS2
import rclpy
from rclpy.node import Node
from rclpy.qos import ReliabilityPolicy, QoSProfile
class SlamService(Node):
"""
Nodo que ... |
import sqlite3
from transformers.transformer import Transformer
from openapi_server.models.element import Element
from openapi_server.models.names import Names
from openapi_server.models.attribute import Attribute
from openapi_server.models.connection import Connection
class CTRPTransformer(Transformer):
varia... |
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
from classifier.resnetw import resnet20
global dist
dist = [ torch.Tensor([]).to('cuda') for _ in range(10) ]
#resnet_real_feats, indices = get_real_feats('resnet20')
##Compu... |
import flask
import dash
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
from data import frames
from data.frames import Frame
external_stylesheets = [
'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.... |
'''
__author__ = "<NAME>"
__copyright__ = "Copyright 2021, <NAME>"
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "1.0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Beta"
'''
import discord, datetime
from dotenv import load_dotenv
from keep_alive import ke... |
"""Test files containging all the test cases for bnf grammar expansion."""
from unittest import TestCase
from swarms.lib.agent import Agent
from swarms.lib.model import Model
from swarms.lib.time import SimultaneousActivation
from swarms.lib.space import Grid
from swarms.behaviors.scbehaviors import (
CompositeDro... |
import json
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
class BaseFeature(object):
def __init__(self, name, idx):
self.name = name
self.idx = idx
def get_feature_value(self, instance, use_tensor, space='z'):
raise RuntimeError('get_feature_value undef... |
# Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software an... |
import datetime
from textwrap import shorten
from re import split
from asciimatics.screen import Screen
from time import sleep
import os
class Event():
totalEvents = 0
def __init__(self, date=datetime.date.today(), time="HH:MM AM", name="name", info="information") -> None:
self.date = date
se... |
from discord.ext import commands
from random import choice
import aiohttp
import re
import urllib
class AdvancedGoogle:
def __init__(self, bot):
self.bot = bot
self.session = aiohttp.ClientSession()
def __unload(self):
self.session.close()
@commands.command(pass_context=... |
# Copyright 2020-2021 Canonical Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
# Copyright (C) 2018-2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distrib... |
from datetime import datetime
def expand_tweet(status):
'''Given a tweepy Status object, expands the text of the tweet
If the status object represents a retweet, then this
function sets "full_tweet" to the full text of the
retweeted tweet (i.e. the part after the "RT @handle:")
If the s... |
from collections import defaultdict
from nltk.tokenize import sent_tokenize, word_tokenize
from typing import NamedTuple
from ast import literal_eval
from math import log2
Unigram = str
Bigram = NamedTuple('Bigram', [('prev_word', str), ('word', str)])
uniques = set()
uniques_count = 135576
class CountDict(dict):... |
from pathlib import Path
import click
from .. import config
from ..proc_util import run_process, concurrent
import asyncio
import tempfile
import json
import os
import sys
import shutil
from datetime import datetime
import re
import shlex
from typing import List
def dir_must_exist(ctx, param, value):
value = Path... |
__author__ = '<NAME>'
notes = '''
These features make creating lists, dicts and sets from other sequences easy and compact.
lc -> list comprehensions
dc -> dict comprehensions
sc -> set comprehensions
In python, these have largely replaced the usage of map and filter.
'''
from placeholders import *
... |
import numpy
from . import geometry
from . import interpolate
def arc_length(tck, num_points=None):
"""Approximate the arc-length of spline (t,c,k) by evaluating it at num_points
positions and calculating the length of the resulting polyline.
If num_points is None, try to guess a sane default."""
poin... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with t... |
#!/usr/bin/env python3
"""Search for an update to Python for a given OS.
For Windows, we search for updates using NuGet.
For Mac OS X, we search for updates using pyenv.
Usage:
update_python.py win64
(can be run on any platform)
update_python.py osx
(must be run on Mac OS X)
"""
import updat... |
import sys, os, os.path as osp
import shutil
import subprocess
PY2 = sys.version_info.major == 2
def iteritems(dict_, **kwargs):
if PY2:
iterator = dict_.iteritems()
else:
iterator = iter(dict_.items(), **kwargs)
return iterator
def remove(*paths, recursive = False, raise_err = True):
... |
from datetime import datetime
from os import makedirs
from os.path import join
from textwrap import dedent
from pony import orm
from slugify import slugify
from .helpers import get_config
db = orm.Database()
config = get_config()
db.bind(provider=config['DATABASE']['provider'], database=config['DATABASE']['database'... |
# --------------------------------------------------------------------------
# Source file provided under Apache License, Version 2.0, January 2004,
# http://www.apache.org/licenses/
# (c) Copyright IBM Corp. 2015, 2016
# --------------------------------------------------------------------------
"""
This is a problem ... |
"""
Parser for pw.x bands output files.
"""
import re
from pathlib import Path
import numpy as np
from pwproc.util import parse_vector
def group(it, n):
# type: (Iterable[T], Integral) -> Iterator[Tuple[T, ...]]
"""Split iterable into groups of n"""
from collections import deque
it = iter(it)
q... |
import pandas as pd
import re
import psycopg2
import sys
from subreddits.pushshift import *
from datetime import datetime as dt
from datetime import timedelta as td
from datetime import timezone as tz
joke_file_base = 'data_%%%%.csv'
record_file_base = 'data_%%%%.txt'
base_URL = 'https://api.pushshift.io/reddit/submi... |
import pandas as pd
# import cairo
import matplotlib.pylab as plt
import math
import numpy as np
from numpy import *
import glob
import os
import os.path
import time
import cv2
import random
import ast
from PIL import Image
from math import *
import networkx as nx
import matplotlib.cm as cm
from matplo... |
import os
from collections import OrderedDict
import cv2
import numpy as np
import torch
from torch.utils import model_zoo
from torchvision import transforms
from . import networks
from .utils.transforms import get_affine_transform, transform_logits
DATASET_SETTINGS = {
'lip': {
'input_size': [473, 473]... |
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2022/3/14 21:23
# @Author : dodo
# @Version:V 0.1
# @desc : 对数据库history_total_jinzhi进行管理
import sqlite3
import time
import json
from dz_utils.dz_utils import read_json_file, dict_only_get, time_str2int, get_current_time
db_name: str = 'history_total_jinzhi.db'... |
"""Useful decorators for modifying the behavior of test functions as well as :class:`unittest.TestCase` classes."""
from typing import *
import os
import abc
from functools import wraps
from unittest import skip, SkipTest
def tag(*tags: str) -> Callable:
"""
Apply a set of tags to a subclass of :class:`unitte... |
### News scraping을 위한 함수 ###
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
import requests
from urllib import parse
from collections import Counter
import time
import re
def joongang_scrape(word_list):
## 원하는 word List의 제목을 가진 기사를 모두 scrape하는 함수 ##
articleList = [] # parse 결과 담는 list
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
from collections import deque, namedtuple
import numpy as np
import re
from typing import List
from textworld.logic import Placeholder, Variable
_WHITESPACE = re.compile(r"\s+")
_ID = re.compile(r"[\w/']+")
_PUNCT = ["::"... |
import collections
from bs4 import BeautifulSoup
from helpers import get_style_rules, get_styles_from_dict, get_distinct_styles, get_all_colors
def get_tableau_styles(workbook_file):
# Create Beautiful Soup XML object from .twb file
wb_xml = BeautifulSoup(workbook_file, 'lxml')
#
# Call parsing funct... |
# Copyright 2013 Google Inc. All Rights Reserved.
"""gcloud command line tool."""
import os
import signal
import sys
# If we're in a virtualenv, import site packages.
if os.environ.get('VIRTUAL_ENV'):
# pylint:disable=unused-import
# pylint:disable=g-import-not-at-top
import site
def _SetPriorityCloudSDKPath... |
import functools
import math
import platform
import random
import numpy
import torch
import torch.utils.data
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import Registry, build_from_cfg
if platform.system() != 'Windows':
import resource
hard_limit = resource.getrlim... |
import aiofiles
import os
from pathlib import Path
from bson.objectid import ObjectId
from async_files.utils import async_wraps
from sanic import Blueprint
from sanic.log import logger
from sanic.views import HTTPMethodView
from sanic.response import json, file, html
from sanic_openapi import doc
from app.main.util.d... |
"""This Python library defines a helper for building a dependency injection
framework.
Installation
------------
:py:mod:`dependency_injection` is available on `GitHub`_ and on `PyPI`_::
$ pip install dependency_injection
We `test <https://travis-ci.org/AspenWeb/dependency_injection.py>`_ against
Python 2.6, 2... |
import dgl
import dgl.function as fn
import torch
import torch.nn as nn
import torch.nn.functional as F
from ogb.graphproppred.mol_encoder import AtomEncoder, BondEncoder
class MLPLayer(nn.Module):
def __init__(self, input_dim, output_dim, dropout=0.0, batch_norm=True, residual=True, **kwargs):
super().__... |
# Circulant acoustic
import numpy as np
from scipy.linalg import toeplitz
def circ_1_level_acoustic(Toep, L, M, N, on_off):
import numpy as np
from scipy.linalg import toeplitz
# Create 1-level circulant approximation to Toeplitz operator
circ_L_opToep = np.zeros((L, M, N), dtype=np.complex128)
A ... |
from __future__ import unicode_literals
import logging
import threading
from binascii import hexlify
from decimal import Decimal
import pendulum
from bluepy import btle
def _get_bit(src, index):
return (src >> index) & 1 == 1
class Mastech(threading.Thread):
# MEASUREMENT_CHARACTERISTIC_UUID = '0000ffb2-00... |
"""
Planner for model-based RL
"""
import numpy as np
import torch
from torchlib.common import convert_to_tensor, FloatTensor
from torchlib.deep_rl import BaseAgent
from torchlib.utils.random.sampler import BaseSampler, IntSampler
from .world_model import WorldModel
class Planner(BaseAgent):
"""
Planner pre... |
#!/usr/bin/env python3
# jopleet.py, Copyright (c) 2020 <NAME> <<EMAIL>>
# Obtain text and images from individual tweet URLs and submit as
# new notes to a Joplin notebook.
import configparser
from string import Template
from bs4 import BeautifulSoup
import tweepy
import os
import sys
import json
import requests
impo... |
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
from models.features import Features
__all__ = ['ResNet', 'resnet50']
class Bottleneck(Features):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1):
super(Bottleneck, self).__init__()
self.conv1... |
#
# 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"); you may not us... |
from fenics import *
from fenics_adjoint import *
import numpy as np
from pyadjoint import Block
from pyadjoint.overloaded_function import overload_function
import scipy.interpolate
def read_rosco_curves():
filename = "Cp_Ct_Cq.DTU10MW.txt"
with open(filename, "r") as f:
datafile = f.readlines()
fo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import subprocess
import linecache
import click
# Number of problems present in problems.txt
TOTAL_PROBLEMS = 202
def get_filename(problem):
"""Returns filename in the form `001.py`"""
return '{:03d}.py'.format(problem)
def get_solution(p... |
# -*- coding: utf-8 -*-
import random
import os
import logging
import datetime
import json
####################################################################
### DEB : Déclaration des variables
###-----------------------------------------------------------------
# Chemin
pathFolder = os.getcwd()
pa... |
import copy
import types
import torch
import torch.nn as nn
import torch.nn.functional as F
def GraSP_fetch_data(dataloader, num_classes, samples_per_class):
datas = [[] for _ in range(num_classes)]
labels = [[] for _ in range(num_classes)]
mark = dict()
dataloader_iter = iter(dataloader)
while True:
inputs, ... |
from collections import defaultdict
from statistics import mean
from record_helper import *
import vcfpy
def generate_sv_record(records, comparison_result, sample_names):
"""
This method generates a single SV record after a call has been made over a set of input records
:param records: the input records i... |
#! /usr/bin/python
# Distributed under the MIT license.
# Copyright (c) 2013 <NAME> (<EMAIL>)
# 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 limitati... |
# coding=utf-8
import os
import json
import re
from norsourceparser.core.config import config
def open_resources_file(name):
fp = open(os.path.join(os.path.dirname(__file__), '../resources/%s.json' % name), 'r')
return json.load(fp)
verb_lex = open_resources_file('verb_lex')
verb_corrlist = open_resources_fi... |
import itertools
import json
import linecache
import math
import os
import pickle
import socket
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List, Tuple, Union
import git
import numpy as np
import torch
import torch.distributed as dist
from rouge_score import roug... |
from flask import Blueprint
from flask import request
from sqlalchemy_blender import QueryBuffer
from sqlalchemy_blender.helpers import related
from sqlalchemy_blender.helpers import serialize
from sqlalchemy_blender.helpers import iserialize
from sqlalchemy_blender.helpers import columns
from sqlalchemy_blender.helpe... |
import collections
import contextlib
import hashlib
import os
import subprocess
import shutil
import zipfile
try:
from urllib.request import (
urlopen,
urlretrieve,
)
except ImportError:
from urllib2 import urlopen
from urllib import urlretrieve
def read(fh, block_sz=8192):
while ... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
# modified by <NAME>
import inspect
import os
import sys
import logging
from loguru import logger
import time
from collections import Counter
import warnings
from termcolor import colored
from functools import parti... |
"""Database model for the application."""
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from sqlalchemy import MetaData
# Set the naming convention for database columns
convention = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_n... |
import logging
import os
import typing as t
from pathlib import Path
from nr.util.singleton import NotSet
from slap.application import IO, Application, argument, option
from slap.ext.application.venv import VenvAwareCommand
from slap.plugins import ApplicationPlugin
from slap.project import Project
logger = logging.... |
# Start of BODY
'''
TestStruct::
testcase_id [int] ID of the test-case
testcase_input_path [str] File path to test-case input
testcase_output_path [str] File path to test-case output generated by the problem solver
testcase_expected_output_path [str] File path to test-case expected... |
import base64
import os
from pathlib import Path
from urllib.parse import urlparse
import threading
import requests
class TileService:
'''A web service that fetches slippy map tiles in OSM format.'''
def __init__(self, name, url_pattern, api_keys):
self.name = name
self.url_pattern = url_pat... |
import tensorflow as tf
def scaled_dot_product_attention(q, k, v, mask):
"""Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ah... |
from houdini import handlers
from houdini.handlers import XTPacket
from houdini.data import db
from houdini.data.penguin import Penguin
from houdini.data.buddy import IgnoreList
from houdini.data.mail import PenguinPostcard
import time
import random
import datetime
@handlers.handler(XTPacket('l', 'mst'))
@handlers.... |
import math
from numba import cuda
SQRT_TWOPI = 2.506628274631
@cuda.jit
def get_mhat(mag, err, sed, sed_err, output):
pos, col = cuda.grid(2)
if col >= len(sed) or pos >= len(mag):
return
part1 = 0
part2 = 0
for i in range(sed.shape[1]):
if not math.isnan(mag[pos, i]) and not mat... |
import ui
import time
#TODO: Add logging
#TODO: Add finished when stopped or reach timer
#TODO: Add adjustment of goal time
#TODO: Add beep or voice every min / 30 sec , etc
#TODO: Add warm-up count-down
class CustomUIView(ui.View):
def __init__(self):
#self.color = 'red'
#touch event are limited to this area (... |
# Copyright 2015 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 contextlib
import datetime
import logging
import os
import posixpath
import random
import time
PASS = 'PASS'
FAIL = 'FAIL'
SKIP = 'SKIP'
def _Forma... |
"""
一个生成光栅和莫尔条纹仿真的函数
将会得到1.jpg和2.jpg
data.dat中的数据:
1~5 : moire间距(像素),斜率1,斜率2,垂直运动距离(像素)1,距离2,
6~11 : a,b,c,d,新c,新d,
12~15 : 光栅水平位移,线数参数,像素参数,光栅转动角度
"""
import numpy as np
import cv2
import skimage.util as skut
a, b, c, d, distance, = 0.3, 4.0, 0.938083, 3.9, 14.142
linenum, pix, xita = 60, 500, (np.... |
""" FutureWarnings catch uncomment below and use python -W error ocli.cli/cli.py
# import traceback
# import warnings
# import sys
#
# def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
#
# log = file if hasattr(file,'write') else sys.stderr
# traceback.print_stack(file=log)
#... |
import os
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pickle
from segmentation_models import AccuracyHistory, get_unet_128
import tensorflow as tf
from keras_preprocessing.image import ImageDataGenerator
from util import OUTPUT_DIR, load_te... |
#!/usr/bin/env python3
import codecs
import collections
import unicodedata
from mylib.easy import *
CR = '\r'
LF = '\n'
CRLF = '\r\n'
def visual_len(s: str):
eaw = unicodedata.east_asian_width
n = len(s)
n += sum([1 for c in s if eaw(c) == 'W'])
return n
def list2col_str(x: T.Iterable, width, *, h... |
import json
from peewee import SQL
from data.database import (
Notification,
NotificationKind,
User,
Team,
TeamMember,
TeamRole,
RepositoryNotification,
ExternalNotificationEvent,
Repository,
ExternalNotificationMethod,
Namespace,
db_for_update,
)
from data.model import... |
# vim: expandtab:ts=4:sw=4
from math import sqrt, fabs
class TrackState:
"""
Enumeration type for the single target track state. Newly created tracks are
classified as `tentative` until enough evidence has been collected. Then,
the track state is changed to `confirmed`. Tracks that are no longer alive... |
####################################
# Created by <NAME>, <NAME>, and <NAME>
# HackTJ 2020 12/13/20
# MIT License
####################################
import pygame as pg
import random
class Directions():
"""
Stores the Matricies for each cardinal direction
Determines if two given directions are perpendicu... |
import mxnet as mx
from mxnet.gluon import nn
class capsDens(nn.HybridBlock):
def __init__(self, dim_c=8, lbl_num=21, input_dim=512, batch_size=128, name='capsnet', stddev=0.01, eps=1e-4):
super(capsDens, self).__init__()
self.dim_c = dim_c
self.lbl_num = lbl_num
self.input_dim = i... |
import jsonpickle
from skills import *
@dataclass(slots=True)
class MageSpell:
_name: str = ""
description: str = ""
circle: int = 0
mana_cost: int = 0
difficulty: Difficulty = None
macro: list[str] = field(default_factory=list)
is_scroll: bool = False
@property
def as_scroll(sel... |
from functools import reduce
# Make APB, BWR and RMB
VALID_NMEA_CHARS = [chr(x) for x in range(ord('A'), ord('Z'))]
def nmea_name(name):
good_name = ''
for c in name.upper():
if c in VALID_NMEA_CHARS:
good_name += c
else:
good_name += '_'
if len(good_name) > 6... |
from __future__ import print_function, absolute_import
import torch
from torch.optim.lr_scheduler import _LRScheduler
from bisect import bisect_right
AVAI_SCH = ['single_step', 'multi_step', 'cosine', 'multi_step_warmup']
def build_lr_scheduler(optimizer,
lr_scheduler='single_step',
... |
import numpy as np
import os
from keras.models import load_model
from src.python.dataset import dataset
CONSENSUS_SUMMARY_CMD_1 = '{}/mummer3.23/dnadiff -p {}/dnadiff-output {} {} ' \
'2>> {}/err'
CONSENSUS_SUMMARY_CMD_2 = 'head -n 24 {}/dnadiff-output.report | tail -n 20'
RESULT_CMD_1 = 'm... |
import json
from cliente import Cliente
import random
from caixa_eletronico import CaixaEletronico
caixa = CaixaEletronico()
notas_valores = [200, 100, 50, 20, 10, 5, 2]
def main():
a = input('Bem vindo ao Banco Itauã.\nDigite 1 para fazer login'
'\nDigite 2 para cadastrar um cliente\nDigi... |
# Microsoft Azure Linux Agent
#
# Copyright 2018 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
from typing import Optional, Union, Dict, List, Set
from abc import ABC, abstractmethod
from pathlib import Path
import platform
import hashlib
from pydantic import BaseModel, Field
import requests
from woke.a_config import WokeConfig, UnsupportedPlatformError
class ChecksumError(Exception):
"""
Checksum of... |
import json
import os
import re
import string
from collections import Counter
import pytorch_lightning as pl
import torch
from pytorch_lightning.loggers import WandbLogger
from src.models.drqa.drqa import DocumentReader
from src.models.drqa.drqa_dataset import DRQADataset
from src.models.drqa.drqa_lightning import dr... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# <NAME>
# California Institute of Technology
# (C) 2007 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
"""
geolocate parser
Programmed by: <NAME>
email: <EMAIL>
"""
import re
import sys
import collections
import geolocate.classes.exceptions as exceptions
class GeolocateInputParser(object):
_VERBOSITY_FIELDS = ["continent_name",
"country_name",
"city_name",
... |
# import required packages
import numpy as np
import scipy.io as sio
import pandas as pd
import pickle
from datetime import datetime
from scipy.integrate import odeint
from pymcmcstat import MCMC, structures, plotting, propagation
import matlab.engine
import matplotlib.pyplot as plt
np.seterr(over='ignore')
bt_data ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.