text
stringlengths
3.07k
12.6k
""" Various functions for generating large random numbers and testing them for primality. """ import random import secrets import math import util small_primes = [ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 83, 89, 97,101,103,107,109,113,127,131,137,139,1...
""" Yiff Autoposter for Telegram Copyright (c) August 2020-present File: bot.py Description: The bot's source code, which runs the bot and creates a cron scheduler to post yiff every hour (i.e: 06:00) from sorts of APIs. You can make a PR and add it in yiffposter/api, it must extend the [APIRepo] class under yiffpo...
import sys import time import json import argparse from contextlib import contextmanager #--- def formatElapsedTime(dt): s = dt days = s // (24*3600); s %= (24*3600) hours = s // 3600; s %= 3600 minutes = s // 60; s %= 60 if dt > 3600*24: return '{0:2g} days {0...
import os import json import time import argparse import logging from decimal import Decimal from collections import defaultdict import pandas as pd os.environ.setdefault("DJANGO_SETTINGS_MODULE", "prs_project.settings") import django django.setup() from recs.funksvd_recommender import FunkSVDRecs f...
# TOKENS PROGRAM = 'PROGRAM' MINUS = 'MINUS' PLUS = 'PLUS' MUL = 'MUL' BEGIN = 'BEGIN' END = 'END' VAR = 'VAR' INTEGER = 'INTEGER' ASSIGN = 'ASSIGN' REAL = 'REAL' ID = 'ID' DOT = 'DOT' EOF = 'EOF' INTEGER_CONST = 'INTEGER_CONST' REAL_CONST = 'REAL_CONST' LPAREN = 'LPAREN' RPAREN = 'RPAREN' SEMI = 'SEMI' COLON = 'COLON...
# SPDX-License-Identifier: AFL-3.0 from typing import Any, List import os import sys import inspect sys.path.append(os.path.dirname(os.path.realpath(__file__))) import vis lldb = __import__("lldb") printers = {} def __lldb_init_module(debugger, internal_dict): global printers printers = vis.register() ...
#!/usr/bin/python3 # # SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2019-2021 Xilinx, Inc # import ctypes.util import sys import time import math # Following found in PYTHONPATH setup by XRT from xrt_binding import * from ert_binding import * import pyxrt # utils_binding.py sys.path.append('../') from util...
import json import numpy as np import tensorflow as tf from TextExtraction.tools.utils import _get_tokenizer from TextExtraction.tools.utils import _load_dataframe def _tokenization_dataframe(dataframe, tokenizer, max_length, sentim...
from __future__ import absolute_import, division, print_function import pytest import tensorflow as tf import numpy as np from lucid.optvis import objectives, param, render, transform from lucid.modelzoo.vision_models import InceptionV1 np.random.seed(42) NUM_STEPS = 3 @pytest.fixture def inceptionv1(): retu...
#!/usr/bin/env python3 from bluepy import btle import logging log = logging.getLogger(__name__) class MiaoMiaoScanner(btle.DefaultDelegate): def __init__(self, sensitivity=False): super().__init__() self.miaomiaos = {} self.sensitivity = sensitivity def handleDiscovery(self, scanent...
"Functions to edit and insert a section placeholder" import re # a search for anything none-alphanumeric and not an underscore _AN = re.compile('[^\w_]') from ... import FailPage, ValidateError, GoTo, ServerError from ....skilift import part_info, editsection, item_info from ....ski.project_class_definition impor...
__source__ = 'https://leetcode.com/problems/knight-dialer/' # Time: O(N) # Space: O(1) # # Description: Leetcode # 935. Knight Dialer # # A chess knight can move as indicated in the chess diagram below: # # This time, we place our chess knight on any numbered key of a phone pad (indicated above), # and the knight make...
import os import sys import numpy as np current_path = os.path.dirname(os.path.realpath(__file__)) convert_tfrecords = os.path.join(current_path, '../util/convert_tfrecords.py') def from_colored_annotated_data_to_default_ply(root_dir, data_dir, sample_pts=None, parallel=False): ply_dir = 'ply100000' if sample_p...
# -*- encoding: utf-8 -*- """ Ending Module ReST endpoints """ from __future__ import generator_stop from collections import OrderedDict as ODict, deque import enum import time try: import simplejson as json except ImportError: import json import falcon from ioflo.aid.sixing import * from ioflo.aid.timing...
#!/usr/bin/python # this defaults to python 2 on my machine # (c) 2017 Treadco software. # # Regularized image sharpening library # # MRC file version # # rbm is trained on image, then reconstruction is used to generate a new one. # # type 2 fuzzy used in this version # license = ''' Copyright (c) 2017 Treadco LLC, <...
# coding: utf-8 # Distributed under the terms of the MIT License. import itertools import numpy as np import spglib from functools import reduce from progressbar import ProgressBar # import pdb from itertools import product from ababe.stru.scaffold import GeneralCell class SuperLatticeCell(object): """ The ...
import pysam import numpy as np import subprocess from xopen import xopen from collections import defaultdict from itertools import groupby from celescope.tools.step import Step, s_common import celescope.tools.utils as utils @utils.add_log def sort_fastq(fq, fq_tmp_file, outdir): tmp_dir = f'{outdir}/tmp' c...
#!/usr/bin/env python3 import telepot import telepot.aio import re import binascii import random import cgi from capstone import * from keystone import * class BotException(Exception): """Base class for exceptions raised by the bot""" pass class AssemblyBot(telepot.aio.Bot): UNRECOGNIZED_CONTENT_TYPES...
from flask import Blueprint, request, abort, jsonify from . import admin_token_required, db @admin_token_required def delete_students_from_class(): if not request.is_json: abort(400, "Expected json") if (not "class_id" in request.json or type(request.json["class_id"]) != int): abor...
import json from datetime import datetime from flask import Blueprint from anubis.models import db, TheiaSession from anubis.rpc.theia import reap_theia_sessions_in_course from anubis.utils.auth.http import require_admin from anubis.utils.auth.user import current_user from anubis.utils.data import req_assert from anu...
""" Copyright Government of Canada 2020-2021 Written by: <NAME>, National Microbiology Laboratory, Public Health Agency of Canada Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License at: http:...
import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np from .augment import random_affine, random_photometric from .flow_util import flow_to_color from .util import resize_area, resize_bilinear from .losses import compute_losses, create_border_mask from ..ops import downsample from .image_wa...
import math import sys import time import numpy as np import torch from torchvision import datasets, transforms TOTAL_BAR_LENGTH = 80 LAST_T = time.time() BEGIN_T = LAST_T def get_layerWise_norms(net): w = [] g = [] for p in net.parameters(): if p.requires_grad: w.append(p.view(...
''' --- Day 7: Handy Haversacks --- You land at the regional airport in time for your next flight. In fact, it looks like you'll even have time to grab some food: all flights are currently delayed due to issues in luggage processing. Due to recent aviation regulations, many rules (your puzzle input) are being enforced...
import numpy as np import pandas as pd from typing import Tuple, List, Callable, Type from IMLearn import BaseModule from IMLearn.desent_methods import GradientDescent, FixedLR, ExponentialLR from IMLearn.desent_methods.modules import L1, L2 from IMLearn.learners.classifiers.logistic_regression import LogisticRegressi...
""" Parses evaluator from the "Natural Language Processing" course by <NAME> https://class.coursera.org/nlangp-001/class """ from __future__ import division import re from collections import defaultdict class ParseError(Exception): def __init__(self, value): self.value = value def __str__(self):...
from django import forms from django.forms import ModelForm, Textarea, TextInput, Select, FileInput, CheckboxInput from iseteam.staff.models import Staff, JoinUs, JoinUs2 class NewMemberForm(forms.Form): username = forms.CharField( widget = TextInput(attrs={'class':'form-control'}) ) first_name = forms.CharFie...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """BatchNorm (BN) utility functions and custom batch-size BN implementations""" import torch import torch.distributed as dist import torch.nn as nn from torch.autograd.function import Function from ..utils import distribut...
# Copyright (c) 2021. <NAME>. All Rights Reserved import json from datetime import datetime from typing import Optional import swagger_client from flask_login import current_user from swagger_client.rest import ApiException from iobrocker import dbutil def swagger_get_athlete(token: str) -> swagger_client.models...
#!/usr/bin/env python2 """ A standalone replication of Clang's verify diagnostics option (-verify). Implementation is very dummy (e.g. doesn't care about multiline comments), but works. Usage: cc test.c 2>&1 | py VerifyDiagnosticConsumer.py test.c For documentation: http://clang.llvm....
import sys from interface.battery import *; from PyQt5 import QtCore, QtGui, QtWidgets import pandas as pd import sqlite3, datetime import os import interface.funcion_tabla as ft class Battery(QtWidgets.QDialog): def __init__(self, parent=None): from PyQt5 import QtWidgets QtWidgets.QDialog.__ini...
import json import sys import os import numpy as np import unicodedata import string import re import random from getAllEDHSub import getAllEDHSub import pickle import logging from collections import defaultdict # from teach.logger import create_logger SOS_token = 0 EOS_token = 1 # logger = create_logger(__name__...
# 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-2.0 # # Unless required by applicable law or agreed to ...
# -*- coding: utf-8 -*- import numpy as np from conf import conf SIZE = conf['SIZE'] SWAP_INDEX = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14] def index2coord(index): y = index // SIZE x = index - SIZE * y return x, y def coord2index(x, y): return y * SIZE + x def legal_moves(board): #...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re from dataclasses import dataclass, field from pathlib import Path from typing import Dict, List, NewType, Optional, Pattern, Sequenc...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import json from abc import ABCMeta, abstractmethod from decimal import Decimal from enum import Enum from typing import Iterator, List, Any, Union, Optional, Dict from . import _converters from .exceptions import KustoMultiApiError, KustoStream...
#!/usr/bin/python3 """This script expects to augment a FSDB stream (or file) with additional information found in another FSDB file. The second file is loaded entirely into memory in order to accomplish this. Any row in the stream file that has exactly matching keys in the second file will be augmented t...
# -*- coding: utf-8 -*- # # Copyright (C) 2008 <NAME> <<EMAIL>> # Copyright (C) 2013-2015 <NAME> <<EMAIL>> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # Author: <NAME> <<EMAIL>> from trac.admin.api import IAdmin...
"""Fit ellipse to stomate identified using x,y coordinates.""" import os import os.path import argparse import numpy as np import scipy.misc import cv2 import skimage.morphology from jicimagelib.io import AutoName, AutoWrite from jicimagelib.region import Region from jicimagelib.util.array import normalise from jic...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import torch import numpy as np from progress.bar import Bar from opendr.perception.object_tracking_2d.fair_mot.algorithm.lib.models.data_parallel import ( DataParallel, ) from opendr.perceptio...
import json from mudpi.exceptions import MudPiError from mudpi.constants import FONT_YELLOW, FONT_RESET from mudpi.logger.Logger import Logger, LOG_LEVEL class Registry: """ Key-Value database for managing object instances """ def __init__(self, mudpi, name): self.mudpi = mudpi self.name = name...
import pandas as pd import psycopg2 import pickle import numpy as np # counterS = 0 # global counterS # global valGlob # from sqlalchemy import create_engine # -*- coding: utf-8 -*- import os import sys import copy # fileName = '/Users/alessandro/Documents/PhD/OntoHistory/WDTaxo_October2014.csv' # connection paramet...
# Lint as: python3 # # Copyright 2020 The XLS 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 applicable law...
# Copyright (C) 2018 Google 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 writ...
# Copyright 2018 Google Inc. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # #...
#!/usr/local/bin/python3 """ Author: <NAME>, January 2020 """ import copy import random ''' Function to initialize the game. ''' def initialize_game(size=4): game = [[' ' for _ in range(size)] for _ in range(size)] game[random.randint(0, size-1)][random.randint(0, size-1)] = 2 return GameLogic(game) ...
def find_commensurate(max, ratio): comm = 1 for value in range(ratio,max+1): if value%ratio == 0 : comm = value return comm def balance_tasks(mpi, a, b, ratio = 2): r = ratio c = mpi d = 1 while c%r != 0 and r < mpi: r = r+1 while r*d <= b and c%r == 0:...
from django.db import models from django.db.models import ( Q, Count, Max, F, Case, When, CharField, Value, OuterRef, Subquery, ) from django.conf import settings from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank from django.utils import timezone ...
import logging import os import warnings from delairstack.apis.client.analytics.analyticsimpl import AnalyticsImpl from delairstack.apis.client.analytics.productsimpl import ProductsImpl from delairstack.apis.client.annotations.annotationsimpl import AnnotationsImpl from delairstack.apis.client.comments.commentsimpl i...
import sys import os import json import builtins import io import keyword import token from tokenize import tokenize import ast import pickle as pkl import random import astor def t_rename_fields(the_ast, all_sites=False): """ all_sites=True: a single, randomly selected, referenced field (self.field in P...
from pathlib import Path import re import geoip2.database from geoip2.errors import AddressNotFoundError import ipaddress import json import urllib.request from urllib.error import HTTPError, URLError import shutil import os from http.server import HTTPServer, SimpleHTTPRequestHandler from pprint import pformat from l...
# # Copyright 2018-2021 Elyra 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 applicable law or agreed to in writ...
# -*- coding: utf-8 -*- import lemoncheesecake.api as lcc from lemoncheesecake.matching import check_that_in, check_that, has_length, has_entry, is_str from common.base_test import BaseTest from project import BASE_ASSET_SYMBOL SUITE = { "description": "Method 'get_config'" } @lcc.prop("main", "type") @lcc.prop...
# Copyright 2021 The TF-Coder 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 applicable law or agreed to in...
import ipaddress import socket import os def execute_sysctl_command(params): print("-> sysctl "+params) os.system('sysctl ' + params) def ip_string_to_unsigned_int(ip): ip_ = 0 bytes_ = ip.split(".") if len(bytes_) == 4: ip_ = socket.htonl((int(bytes_[0]) << 24) + (int(bytes_[1]) << 16) +...
from PySide2.QtCore import QItemSelectionModel, QObject, Signal from PySide2.QtWidgets import QDialog, QTableWidgetItem, QVBoxLayout from hexrd.ui.ui_loader import UiLoader from hexrd.ui.utils import block_signals, unique_name class ListEditor(QObject): """A string list editor that doesn't allow duplicates""" ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import shutil import time from importlib import import_module import chainer import yaml from chainer import iterators from chainer import serializers from chainer import training from chainer.training import extensions from chainer.training import tri...
# Copyright (c) 2013-2015 Centre for Advanced Internet Architectures, # Swinburne University of Technology. All rights reserved. # # Author: <NAME> (<EMAIL>) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redist...
"""JavaScript install module provide functions to install/uninstall a JavaScript Earth Enginemodule. """ import pathlib import re import urllib.request import pkg_resources def _convert_path_to_ee_sources(path: str) -> str: """Get the remote module path from the 'ee-sources' GCS bucket. Args: path:...
# -*- coding: utf-8 -*- from gensim import corpora,models,similarities from collections import defaultdict from collections import Counter import codecs import json import numpy as np def make_dictionary(): with codecs.open("t_author_paper.json","r","utf-8") as fid: t_author_paper = json.load(fid) au...
#BT3051 Assignment 1b #Roll number: BE17B007 #Collaborators: - #Time: 2 hours import sys import doctest def read_FASTA(fname): """ (str) -> (list of tuples) Input: fname name of the file that is to be read Output: sequences tuple of sequence names and sequences Working: data Used to store the complete ...
#!/usr/bin/env python3 # # Copyright 2014 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility to get release image and firmware version.""" import argparse import logging import os import re from cros.factory.h...
#!/usr/bin/env python3 import os import re import sys import subprocess import signal import tempfile import requests import getpass PID_FILE = '/run/nvpn.pid' OVPN_CONFIGS = '/etc/openvpn' CREDENTIALS_FILE = '/etc/openvpn/login.conf' def show_help(cmd=None): print("Usage: vpn [up|down|update|status] <server nam...
#!/usr/bin/env python from __future__ import print_function import numpy as np import subprocess import argparse import os import astropy.io.fits as pyfits def run_cmd(cmd): """Run cmd command""" header = '\n' + '*'*20 + '\n' + cmd + '\n' + '*'*20 + '\n' print(header) ret = subprocess.call(cmd, shell...
''' Created on Jan 6, 2017 @author: <NAME> ''' import Game as gm import tkinter.filedialog as fd import tkinter.messagebox as mb import tkinter as tk import pickle from PIL import Image, ImageTk, ImageDraw from _overlapped import NULL from Game import Game import webbrowser #TODO: # Hint UI #Globals BLOCKSIZE = 50 I...
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__ = '<NAME>' r''' python C:\Users\cwu\Desktop\Software\Papers\pH_effect\plot_ph_effect_contour\plot_contour.py ''' import os import numpy as np import pandas as pd import matplotlib.pyplot as plt EPCS_FILE = 'path\to\epcs.xlsx' DGPS_FILE = 'path\to\dgps.xls...
import numpy as np from scipy import signal from scipy.io import wavfile import librosa _mel_basis = None _inv_mel_basis = None def save_wav(wav, path, sr): wav *= 32767 / max(0.01, np.max(np.abs(wav))) #proposed by @dsmiller --> libosa type error(bug) 극복 wavfile.write(path, sr, wav.astype(np.int16)) ...
from itertools import product from typing import List, Tuple import numpy as np from numpy import pi from qutip import Qobj, identity, sigmax, sigmay, sigmaz, tensor from scipy.linalg import pinv from pyquil import Program from pyquil.gates import H, X, RX from quara.interface.qutip.conversion import convert_povm_qua...
from typing import List, Optional import re import spacy import nltk import numpy as np import tensorflow as tf def load_glove(filepath: str): """Load GLoVe data""" wv = {} with open(filepath, 'rt') as f: for line in f: tokens = line.strip().split(' ') wv[tokens[0]] = [float...
#!/usr/bin/env python3 # Copyright (c) 2020 SiFive Inc. # SPDX-License-Identifier: Apache-2.0 """Generate linker scripts from devicetree source files""" import argparse import sys import jinja2 import pydevicetree from memory_map import get_memories, get_ram_memories, get_load_map TEMPLATES_PATH = "templates" # S...
# -*- coding: utf-8 -*- """ License ---------- Copyright (c) 2016 <NAME> <EMAIL> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this...
# -*- coding: utf-8 -*- """ Created on Sat Oct 21 00:17:33 2017 @author: lauri.kangas """ import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np from scipy.optimize import fmin from tycho2 import tycho2 from projections import stereographic, unity, rectilinear import coordinate_transform...
#!/usr/bin/env python3 # # Copyright 2014 <NAME> # # 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...
""" devnet_skill.py Purpose: lambda hander for the DevNet Alexa Data Center Skill Author: <NAME> (<EMAIL>) Cisco Systems, Inc. """ from __future__ import print_function # Import the UCS Management functions import ucsm_operations # --------------- Helpers that build all of the responses ---...
# -*- coding: utf-8 -*- import re from django import forms from django.utils.translation import ugettext_lazy as _ from services.models import Alias from datetime import datetime, date, timedelta # User login format validation regex VALID_USERNAME_RE = r"^[a-z][a-z0-9_]*[a-z0-9]$" MAX_AGE = 80 class LoginField(fo...
import os.path from collections import defaultdict class MiniFileNotFoundError(Exception): pass class HMMPOSTagger: def __init__(self, conll2000_path): self.observations = [] self.observations_no = {} self.labels = [] self.labels_no = {} self.transition = {} ...
# -*- coding: utf-8 -*- # @Brief: 骨干网络 from tensorflow.keras import layers, regularizers from nets.DropBlock import DropBlock2D import tensorflow as tf import config.config as cfg class Mish(layers.Layer): """ Mish激活函数 公式: mish(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + e^{x})) Shape: ...
# Copyright (c) 2010-2014 openpyxl import datetime import os.path import pytest from openpyxl.worksheet.iter_worksheet import read_dimension from openpyxl.reader.excel import load_workbook from openpyxl.compat import range, zip def test_open_many_sheets(datadir): datadir.join("reader").chdir() wb = load_wo...
# CAM(Class Activation Mapping) Visualization / modified https://github.com/metalbubble/CAM/blob/master/pytorch_CAM.py from PIL import Image from torchvision import models, transforms from torch.autograd import Variable from torch.nn import functional as F import numpy as np import cv2, torch import os, pickle from m...
import urllib from google.appengine.ext import blobstore import flask import flask_wtf import wtforms import auth import config import model import util from main import app class GuideUpdateForm(flask_wtf.FlaskForm): name = wtforms.StringField('Name', [wtforms.validators.required()]) bio = wtforms.TextAreaFiel...
import os from collections import defaultdict import numpy as np import random from sklearn import svm from sklearn.externals import joblib from utils.utils import load_train_valid_labels from utils.LogHandler import LogHandler class _MNA(object): def __init__(self, graph, anchorfile, valid_prop, neg_ratio, log_fil...
# for making bounding boxes pretty COLORS = ((244, 67, 54), (233, 30, 99), (156, 39, 176), (103, 58, 183), (63, 81, 181), (33, 150, 243), (3, 169, 244), (0, 188, 212), (0, 150, 136), (76, 175, 80), (139, 195, 74), ...
import requests from pprint import pprint url = 'http://localhost:8000' def start(user, problem, count): uri = url + '/start' + '/' + user + '/' + str(problem) + '/' + str(count) print('start', user, problem, count, uri) return requests.post(uri).json() def oncalls(token): uri = url + '/oncalls' ...
#from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import random import json import jsonlines import torch from torch.utils.data import Dataset from transformers import RobertaTokenizerFast logger = logging.getLogger(__name__) class LOUVREData...
from copy import deepcopy as copy from math import ceil from math import log2 as log from random import randint, choice from phon import * import sys class cognateSet(object): def __init__(self): """Cognate sets have a list of cognates, non-cognate score, counts for lang1 and lang2 segments and ...
import os from Deployment.ConsumerWorker import celery_worker_app from Deployment.server_config import IS_TEST, OCR_TRITON_URL, OCR_TRITON_PORT from Operators.ExampleTextDetectOperator import GeneralDBDetect from Operators.ExampleTextRecognizeOperator import GeneralCRNN from Operators.ExampleTextOrientationClassificat...
''' Copyright 2020 <NAME> 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...
import sys import argparse import logging import os, glob import re logging.basicConfig(format='%(levelname)s:%(asctime)s:%(filename)s: %(message)s') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # visualization import numpy as np from sklearn.decomposition import PCA from sklearn.manifold import...
"""Collection of reusable python toolkit functions.""" # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-statements # pylint: disable=too-many-arguments import os import json from math import floor, ceil from itertools import product import requests import numpy as np from numpy.random import...
# Copyright 2020, The TensorFlow Federated 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 applicable law o...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. r""" Basic training script for PyTorch """ # Set up custom environment before nearly anything else is imported # NOTE: this should be the first import (no not reorder) from maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:s...
#!/usr/bin/env python # coding: utf-8 # # Deterministic Optimal Economic Growth Model # # **<NAME>, PhD** # # This demo is based on the original Matlab demo accompanying the <a href="https://mitpress.mit.edu/books/applied-computational-economics-and-finance">Computational Economics and Finance</a> 2001 textbook by ...
# kmeans.py using any of the 20-odd metrics in scipy.spatial.distance # kmeanssample 2 pass, first sample sqrt(N) import random import logging import numpy as np from scipy.spatial.distance import cdist # $scipy/spatial/distance.py # http://docs.scipy.org/doc/scipy/reference/spatial.html from scipy.sparse import...
# -*- coding: utf-8 -*- # pylint: disable=unused-argument,pointless-statement """Tests for the `UpfFamily` class.""" import copy import pytest from aiida_pseudo.groups.family.upf import UpfFamily def test_type_string(clear_db): """Verify the `_type_string` class attribute is correctly set to the corresponding e...
#!/usr/bin/env python3 import argparse import hashlib import pathlib import sys import yaml from utils import patch_series_flag def parse_args(trees): parser = argparse.ArgumentParser( description="Generate GitHub Action Workflow YAML.") parser.add_argument("tree", help="The ...
import json import logger import os import random from datetime import date from dotenv import load_dotenv from sys import exit import discord from discord.ext import commands, tasks from discord.utils import get log = logger.setup_applevel_logger(file_name = 'app_debug.log') load_dotenv() TOKEN = os.getenv('DISC...
from flask import Flask, render_template, request, session, redirect, url_for import cv2 import create_stamps import confirm_pdf import create_pdf import remove_images app = Flask(__name__) app.secret_key = "aaa" @app.route('/') def top(): # session.init_session() remove_images.remove_images() return render_templ...
from treys import Card, Evaluator, Deck # https://github.com/ihendley/treys from random import randint # evaluator = Evaluator() # setup game isHUMAN_vs_AI = True # True = human vs AI, False= AI vs AI HUMAN_PLAYER_NAME = 'Valdas' AI1_PLAYER_NAME = 'Student' AI2_PLAYER_NAME = 'Master' DEALER_NAME = 'Dealer' # Texas H...
''' Author: <NAME> Date Created: 13-Oct-2021 ''' from index import index from timed import timing from pymongo import MongoClient import argparse import re import ast class Query: def __init__(self) -> None: self.index = {} ''' { "butter" : (1,2) "search"...
# coding: utf-8 # Distributed under the terms of the MIT License. """ This file implements some light wrappers to the pymatgen, via ASE. """ import pickle import os import getpass import copy from typing import Union from pymatgen.io.ase import AseAtomsAdaptor from pymatgen.ext.matproj import MPRester from pymatgen...