text
stringlengths
3.07k
12.6k
import os import sys from flask import Flask, request, abort, jsonify from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS # To be able to recognize relative imports sys.path.append(os.path.dirname(os.path.realpath(__file__))) from models import setup_db, create_all, Actor, Movie from auth import AuthE...
from PIL import Image import numpy as np import time import pygame import math from stl import mesh import stl image = Image.open("frame.png") pixelLocations = [] def drawRect(): pygame.init() surface = pygame.display.set_mode((1200,1200)) surface.fill((255,255,255)) color = (0,0,0) for rect in pixe...
#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2009 Fermi Research Alliance, LLC # SPDX-License-Identifier: Apache-2.0 import os import platform import random import string import sys import tempfile import unittest # We assume that this module is in the unittest directory module_globals = globals() unittest_dir =...
import json import logging from collections import OrderedDict from django.conf import settings from django.utils.text import slugify from django.views.generic import TemplateView from django.templatetags.static import static from django.contrib.auth import get_user_model from django.core.exceptions import PermissionD...
# Copyright 2020 The Magenta Authors. # Modifications 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 requ...
from settings import * from methods import * from fastapi import FastAPI, Response, status, Depends, Query, File, UploadFile from typing import Optional, List from starlette.responses import FileResponse import db_models from db_connect import engine, SessionLocal from sqlalchemy.orm import Session ### DB db_models...
__source__ = 'https://leetcode.com/problems/rearrange-string-k-distance-apart/' # https://github.com/kamyu104/LeetCode/blob/master/Python/rearrange-string-k-distance-apart.py # Time: O(n) # Space: O(n) # # Description: Leetcode # 358. Rearrange String k Distance Apart # # Given a non-empty string str and an integer k,...
import numpy as np import struct from sklearn.metrics import classification_report from sklearn.decomposition import PCA from collections import Counter from multiprocessing.shared_memory import SharedMemory from multiprocessing import Process # code for binary file IO is adapted from: # https://blog.csdn.net/qq_350...
#!/usr/bin/env python ''' Author: <NAME> @ RIKEN Copyright (c) 2020 RIKEN All Rights Reserved See file LICENSE for details. ''' import os import log,traceback def parse(params, f_blast_res, outfpath): log.logger.debug('started') try: evalue_threshold=params.overhang_evalue_threshold def ...
import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler import matplotlib as mpl from sklearn.model_selection import TimeSeriesSplit import matplotlib.pyplot as plt from numpy import nan cv_splits = 3 # time series cross validator ''' Load dataset ''' def load_data(path): raw_data =...
from flask import Flask,render_template,abort,send_file,request from flask_compress import Compress from threading import Thread import datetime import os import re import twitter app = Flask(__name__) Compress(app) # Parse the Log File to get Individual Tweet Sessions def calculate_sessions(log_file_lines): final_...
#!/usr/bin/env python """ Converts 2011 Poker/Ester and 2013-2016 HiST raw data files to HDF5 for easy consumption full command example with metadata: python ConvertDMC2h5.py ~/U/irs_archive3/HSTdata/2013-04-14-HST0/2013-04-14T07-00-CamSer7196.DMCdata \ -s 2013-04-14T06:59:55Z -k 0.018867924528301886 -t 201...
class Node: def __init__(self, data): self.data = data self.height = 0 self.left = None self.right = None class AVLTree: def __str__(self): if self.root: return self.print_avl(self.root) return "" def print_avl(self, node: Node) -> str: ...
import torch import torch.nn as nn from torch.optim import Adam import os import argparse import numpy as np from tqdm import tqdm from utils import init_dataset from model import WorkStateClsModel as Model def init_model(opt): model = Model() model = model.cuda() if opt.cuda else model return model def get_ac...
"""Represent the most basic types of call number parts.""" from __future__ import unicode_literals from builtins import str import decimal import math from pycallnumber import settings from pycallnumber.template import SimpleTemplate from pycallnumber.unit import SimpleUnit from pycallnumber.exceptions import Invalid...
""" Module that define classes to convert Crypto-currency to FIAT e.g BTC to USD """ import logging import time from typing import Dict, List from coinmarketcap import Market from freqtrade.constants import SUPPORTED_FIAT logger = logging.getLogger(__name__) class CryptoFiat: """ Object to describe what ...
import argparse import logging import sys, os import requests import pandas as pd sys.path.append('..') from utils.helpers import get_parsed_data, find_folder from utils.misc import get_df_hash import glob from tqdm import tqdm USAGE_DESC = """ python main.py <command> [<args>] Available commands: prepare ...
# Licensed under the terms of the BSD-3-Clause license. # Copyright (C) 2019 <NAME> # <EMAIL> """apollon/fractal.py Tools for estimating fractal dimensions. Function: corr_dim Estimate correlation dimension. embdedding Pseudo-phase space embdedding. lorenz_attractor Simulate Lorenz sy...
from functools import wraps from selenium import webdriver from selenium.common.exceptions import WebDriverException import time import os from django.db import transaction from django.core.urlresolvers import reverse from django.test import TransactionTestCase from django.utils.html import strip_tags from django_sel...
""" there are multiple options to define layers: - using an int - using `pp.LAYER` object, with a layer per property - using `pp.layer(name, layermap)` function """ from dataclasses import dataclass from phidl.device_layout import Layer from phidl.device_layout import LayerSet as LayerSetPhidl class LayerSet(Laye...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """DigitalOcean Snapshooter. Usage: digitalocean_snapshooter.py droplet list digitalocean_snapshooter.py droplet destroy <droplet_id> digitalocean_snapshooter.py snapshot take <droplet_id> digitalocean_snapshooter.py snapshot check <snapshot_id> digitalocean_sn...
# -*- coding: utf-8 -*- """ The Maze Challenge - Functions to display plot and stats Author: prushh """ import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.colors import ListedColormap def _dark_subplots(nrows: int = 1, ncols: int = 1) -> tuple: ''' Create subplots and set d...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # === This file is part of Calamares - <https://calamares.io> === # # SPDX-FileCopyrightText: 2014 <NAME> <<EMAIL>> # SPDX-FileCopyrightText: 2015 2019-2020, <NAME> <<EMAIL>> # SPDX-FileCopyrightText: 2017 <NAME> <<EMAIL>> # SPDX-FileCopyrightText: 2019 <NAME> <<...
import os import tensorflow as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file def jaccard_distance(text1, text2): """ Measure the jaccard distance of two different text. ARGS: text1,2: list of tokens RETURN: score(float): distance between two tex...
# -*- coding: utf-8 -*- import asyncio import hashlib import io import struct import threading import traceback from asyncio import StreamWriter, StreamReader from typing import Generic, TypeVar, Optional from Crypto import Random from Crypto.Cipher import AES from Crypto.PublicKey import RSA from Crypto.PublicKey.RSA...
# -*- coding: utf-8 -*- """ Created on Mon Sep 19 15:53:45 2016 @author: sure """ ''' -This is a statistic test file using the framework of unittest -This file includes the test cases for term statistics: -term frequency in doc -doc length -term frequency in collection -collection length ''' import ...
"""Test cases for functionality given by base parser.""" import unittest import apel.parsers class BaseParserTest(unittest.TestCase): """Test cases for the base APEL parser class.""" def setUp(self): self.parser = apel.parsers.Parser('testSite', 'testHost') def test_constants(self): ""...
""" Function: pre-processing of .xml file and creating pandas dataframe for each test cases' data Author: <NAME> Date: 08/11/2020 """ from bs4 import BeautifulSoup as bs import pandas as pd import yaml # xml file pre-processing def open_xml(path): """ Open and pre-process the original .xml file...
# Copyright (c) OpenMMLab. All rights reserved. # Code for GBR competition metric is modified from Camaro's notebook # https://www.kaggle.com/bamps53/competition-metric-implementation import numpy as np from mmcv.utils import print_log from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps from .builder import ...
# To avoid pulling in the entire Home Assistant library, this was ripped and adapted from # https://github.com/home-assistant/core/blob/c07646db5dcfe290d8b1e11c696629cbd14c1f8c/homeassistant/helpers/entityfilter.py """Helper class to implement include/exclude of entities and domains.""" import fnmatch import re from ...
from math import * import numpy as np import cv2 as cv # This function draws a board. It is currently not used in main.py. def drawBoard(img, board, width, height, border=32, gridSize=128, gridSpacing=8, showExit=True, colors=[(0, 95, 130), (0, 140, 191), (0, 187, 255)]): drawRects(img, convertToRects(board, border,...
from typing import final from datasets import load_dataset from sklearn.utils import shuffle import nltk.data import pandas as pd from tqdm import tqdm import os import argparse import torch from torch.utils import data from torch.utils.data import Dataset, DataLoader from transformers import AutoTokenizer, BertForMa...
import numpy as np import pyqtgraph as pg from matplotlib.colors import LinearSegmentedColormap import sys import os from acconeer_utils.clients import SocketClient, SPIClient, UARTClient from acconeer_utils.clients import configs from acconeer_utils import example_utils from acconeer_utils.pg_process import PGProcess...
from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse from django.conf import settings from photo.forms import User from django.contrib import admin from django.forms import ModelForm from PIL import Image # from webcam.fields import CameraField # from webcam....
from typing import * from typing import _GenericAlias import astroid from python_ta.typecheck.base import _get_name, _gorg, TypeConstraints ############################################################################### # Operator translations into dunder method name and English name. ################################...
import os import requests import bz2 from time import sleep import numpy as np import pandas as pd from astropy.io import fits from astropy import wcs def fits_file_name(rerun, run, camcol, field, band): """ SDSS FITS files are named, e.g., 'frame-g-001000-1-0027.fits.bz2'. We will uncompress this and sav...
# -*- Mode: Python2; coding: utf-8; indent-tabs-mpythoode: nil; tab-width: 4 -*- ''' Colors experience ========= View the pixel ordering experience. New layer will be created with the image pixel by pixel. Use Numpy. ''' # Py 2.7 import os import sys import datetime from array import array # Co...
# 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...
#!/usr/bin/env python # import sys # sys.path.insert(1, 'C:\Users\ai329e\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine') # sys.path.insert(1, 'C:\Users\ai329e\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\yaml\lib') #sys.path.insert(1, 'myapp/lib') from googl...
import re from datetime import date as python_date from datetime import datetime as python_datetime import json as python_json COLOR_RE = re.compile(r'^\s*#[0-9a-f]{3}([0-9a-f]{3})?\s*$', re.IGNORECASE) DATE_RE = re.compile(r'^\s*(\d{4})-(\d\d)-(\d\d)\s*$') DATETIME_RE = re.compile(r'^\s*(\d{4})(?:-(\d\d)(?:-(\d\d)(?:...
from src.data import Data import numpy as np from scipy.optimize import minimize import matplotlib.pyplot as plt # area of ellipse def f(x): return 1 / (x[0] ** 4 * x[1] ** 4) def gradf(x): res = np.zeros(5) res[0] = - 4 / (x[0]**5 * x[1]**4) res[1] = - 4 / (x[0]**4 * x[1]**5) return res class...
import gym from gym import error, spaces, utils from gym.utils import seeding from gym.envs.registration import register import json from pprint import pprint import math import numpy as np from typing import List, Iterator, Callable import config as cfg class Action: def __init__(self, name,...
import datetime import requests import lxml.html as lh import pandas as pd import json from tide import Tide import constituent as cons import numpy as np def retrieve_constituents(stationID): #Forms URL url = 'https://tidesandcurrents.noaa.gov/harcon.html?unit=0&timezone=0&id={}'.format(stationID) #Requ...
import os from datetime import datetime import aiosqlite import ujson from sanic import json, HTTPResponse, Request from sanic.log import logger from bot.caching import CACHE from bot.senders import send_msg, forward_msg proxy_to = int(os.environ.get('PROXY_TO')) async def health(request: Request) -> json: ret...
try: import pygame, os, time except: print('cmd run: pip3 install pygame -i https://mirrors.aliyun.com/pypi/simple') exit() from pygame.locals import * from game import Game from ai import Ai from config import * config = Development() FPS = config.FPS SIZE = config.SIZE DEBUG = config.DEBUG colors = conf...
from cybox.objects.domain_name_object import DomainName from cybox.objects.address_object import Address from cybox.objects.file_object import File import logging import string import ipaddress import uuid logger = logging.getLogger(__name__) # # Used by validate_domain_name function # domain_allowed_chars = string....
# Copyright 2022 The EvoJAX 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 w...
# prototyping custom build command. import sublime, sublime_plugin, subprocess, os, re import threading class RunSasProgramCommand(sublime_plugin.WindowCommand): def run(self): self.window.active_view().run_command('save') self.window.active_view().show_popup('Submitting to SAS.') prg_filename = self.win...
import copy import os import random import tempfile import zipfile import CelledImage from mutations import MUTATIONS PATTERN_FILE = "pattern.txt" IMAGE_NAME = "image" class NotEnoughLettersError(Exception): pass class Rearranger: """Class for handling the automated rearranging of letters in an image.""" ...
# # Copyright (c) 2018 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import pecan from pecan import rest from inventory.api.controllers.v1 import base from inventory.api.controllers.v1 import cpu from inventory.api.controllers.v1 import ethernet_port from inventory.api.controllers.v1 import host...
import pytest import platform import numpy as np import re import ray from ray._private.test_utils import wait_for_condition from ray.cluster_utils import AutoscalingCluster # Triggers the addition of a worker node. @ray.remote(num_cpus=1) class Actor: def __init__(self): self.data = [] def f(self):...
import torch import torch.nn as nn import torch.nn.parallel import torch.utils.data from torch.autograd import Variable import numpy as np import torch.nn.functional as F import torch.autograd as grad # removed the secound Linear layer and its batch_norm, and the remaning Linears are skinnier class STN3d(n...
from scipy.optimize import curve_fit import numpy as np import xarray as xr import dask import dask.array as darray # define the model last_trend_parm = 4 nparm = 8 def poly_harm(t, mu, b1, b2, b3, a1, phi1, a2, phi2): """Linear trend plus harmonics.""" return (mu + b1 * t + b2 * t**2 + b3 * t**3 + ...
#!/usr/bin/env python from automerge import getstatusoutput,AutoMerger,add_common_args,cd import os,re import config as c import argparse # scenarios, edge cases # a. some parent modules do not have branch # b. some child modules do not have branch # c. source branch masks def perform(args,am): tocom...
''' ----------------------------------------------- File Name: predict-seg$ Description: Author: Jing$ Date: 7/17/2021$ ----------------------------------------------- ''' import cv2 as cv import numpy as np import math import os from keras.models import load_model #from tensorflow.keras.models import lo...
""" circa-survive-lyric-machine API. """ from __future__ import annotations import uuid import json import logging import os import sys from typing import Any, Dict import numpy as np # type: ignore import tensorflow as tf # type: ignore from multiprocessing import Process from flask import Flask, Response, jsonif...
#!/usr/bin/python # started from code from Ransom, and then changed it to not recursively query groups in groups HELP = "Extracts the emails from every group list in a given domain.\n\ Usage: python groups.py DOMAIN [CSV] [TEXT] \n\ DOMAIN - the domain to use, e.g mydomain.com\n\ optional out...
# -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version 3.10.1) ## http://www.wxformbuilder.org/ ## ## PLEASE DO *NOT* EDIT THIS FILE! ########################################################################### import wx ...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You ma...
import os import re import subprocess import sys import fiona as fiona import rasterio from rasterio.windows import Window import rasterio.features import rasterio.warp import rasterio.mask from lxml import etree import shutil def create_roi(product_path, vector_file, window): print('Crop window', window) fil...
## # Copyright 2021 IBM Corp. All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 ## from typing import Set, Tuple, Dict, Union import torch import lnn from .constants import Fact, World, Direction class AssertWorld: """AssertWorld(world: World) Raised when world not given as World object """...
import asyncio import collections import logging """ The event class is a lightweight container which stores the event name, a timestamp that should indicate when the event occured, and a payload. Events are produced by publishers and consumed by subscribers. The payload can be any type that you wish, although a JSO...
import argparse import hashlib import math import os import time import numpy as np import torch import data from utils import batchify, get_batch, repackage_hidden parser = argparse.ArgumentParser(description='PyTorch PennTreeBank RNN/LSTM Language Model') parser.add_argument('--data', type=str, default='data/penn/...
import json import sys import os import netlib.utils from . import flow, filt, utils from .protocol import http class DumpError(Exception): pass class Options(object): attributes = [ "app", "app_host", "app_port", "anticache", "anticomp", "client_replay", ...
# -*- coding: utf-8 -*- """ Created on Thu Dec 3 08:48:50 2020 @author: ebuit Inspired in examples taken from: https://dash.plotly.com/dash-core-components/input https://stackoverflow.com/questions/51407191/python-dash-get-value-from-input-text https://github.com/AdamSpannbauer/app_rasa_chat_bot/b...
import numpy as np import matplotlib.pyplot as plt import xarray as xr from scipy import stats import cartopy.crs as ccrs from cartopy.io.shapereader import Reader from cartopy.feature import ShapelyFeature import cartopy.feature as cfeature # Preparation for the ideal C-C scaling background plots # TODO - i...
#!/usr/bin/env python from __future__ import print_function import csv import sys import os from os import listdir from os.path import isfile, join from shutil import copyfile class MyDialect(csv.Dialect): strict = True skipinitialspace = True quoting = csv.QUOTE_ALL delimiter = ';' quotechar = '"...
""" utils.py Contains helper functions. """ import math import os import numpy as np import torch import torch.nn.functional as F EPSILON_DOUBLE = torch.tensor(2.220446049250313e-16, dtype=torch.float64) EPSILON_SINGLE = torch.tensor(1.19209290E-07, dtype=torch.float32) SQRT_TWO_DOUBLE = torch.tensor(math.sqrt(2),...
#!/usr/bin/env python3 import json import os from loguru import logger DEFAULT_CONF = { "task_info": { "label_type": "multi_label", "hierarchical": True, "hierar_taxonomy": "data/custom.taxonomy", "hierar_penalty": 0.000001, }, "device": "cuda", "model_name": "Transfor...
from __future__ import print_function import numpy as np import time # Go to the next pick type (in alphabetical order) def togglePickMode(*args,**kwargs): curMode=args[0] availPickModes=sorted([str(key) for key in args[1].keys()]) if curMode in availPickModes: idx=availPickModes.index(cur...
import os import pickle from pathlib import Path import numpy as np import open3d as o3d import plac from open3d.open3d_pybind.camera import PinholeCameraIntrinsic from open3d.open3d_pybind.geometry import RGBDImage, PointCloud, TriangleMesh, Image from open3d.open3d_pybind.io import write_point_cloud, write_triangle_...
from django.db import models from utils import db_utils class GoodsCategory(db_utils.BaseModel): """商品类别""" name = models.CharField(max_length=10, verbose_name='名称') parent = db_utils.ForeignKey( 'self', related_name='subs', null=True, blank=True, on_delete=models.CASCADE, verbose_name='父类别') ...
########################################################################### ############################# General Imports ############################# ########################################################################### from evaluation import wer_eval, preds_to_integer, show, my_collate, AverageMeter import pdb...
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch, math from mmcv.cnn import constant_init, kaiming_init from mmcv.utils.parrots_wrapper import _BatchNorm def default_init_weights(module, scale=1): """Initialize network weights. Args: modules (nn.Module): Modules to b...
#!/usr/bin/python2.5 # # Copyright 2014 <NAME>. # # Author: <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 limitation the rights # t...
#!/usr/bin/env python # MIT License # # Copyright (c) 2017 <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 limitation the rights #...
# coding=utf-8 # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from nose.tools import raises, eq_, ok_ from werkzeug.test import Client from werkzeug.wrappers import BaseResponse from clastic import Application, render_basic from clastic.application import BaseApplication from clastic.route import BaseRoute, Route...
import datetime as dt from sqlalchemy import UniqueConstraint from run4it.app.database import Column, SurrogatePK, reference_col, relationship, db class GoalCategory(SurrogatePK, db.Model): __tablename__ = 'training_goal_categories' id = Column(db.Integer, primary_key=True, index=True) name = Column(db.String(32),...
import os, subprocess, re from tuner import FlagInfo, Evaluator, FLOAT_MAX from tuner import RandomTuner, SRTuner # Define GCC flags class GCCFlagInfo(FlagInfo): def __init__(self, name, configs, isParametric, stdOptLv): super().__init__(name, configs) self.isParametric = isParametric self...
# SPDX-License-Identifier: MIT import os import re import hashlib from waflib.TaskGen import feature from waflib import Context, Errors, Logs, Task, Utils from waflib.Tools import waf_unit_test ERROR_WORDS = ["error:", "FAILED"] def summary(bld): lst = getattr(bld, "utest_results", []) if not lst: ...
#!/usr/bin/env python3 # Copyright 2017 <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, pu...
# -*- coding: utf-8 -*- """ /*************************************************************************** qgridder_time_utils Part of Qgridder - A QGIS plugin Builds 2D grids for finite difference ------------------- begin : 2013-04-08 ...
""" 区别于股票代码,指数代码请添加"I",如000300(沪深300),其符号I000300 """ import pandas as pd from cswd.utils import ensure_list, sanitize_dates #from cswd.sqldata.stock_daily import StockDailyData from cswd.sqldata.query import query_adjusted_pricing from cswd.sqldata.stock_index_daily import StockIndexDailyData from zipline.assets._ass...
from collections import Iterable, MutableMapping from types import MethodType import functools import inspect from calculate.calculate import ManagedClass, ffi import calculate.exception as exception import calculate.calculate as calculate __all__ = [ 'Function', 'Operator', 'ConstantFactory', 'Func...
import autofit as af from autofit.mock.mock import MockSearch, MockSamples from autoarray.mock.mock import MockMask, MockDataset, MockFit as AAMockFit from autogalaxy.mock.mock import MockLightProfile, MockMassProfile class MockResult(af.MockResult): def __init__( self, samples=None, ...
#Cek typo per kata - ED + Bayes import re import glob import csv import requests import json from urllib.request import urlopen from collections import Counter # path = 'C:/Users/USER/Desktop/Parallel Corpus/*.txt' def words(text): return re.findall(r'\w+', text.lower()) import os preproc_dir = os.path.dirname(os.p...
from __future__ import annotations import logging import os import re from pathlib import Path from typing import Dict import anndata as ad import pandas as pd from sqlalchemy.orm import Session from histocat.core.acquisition import service as acquisition_service from histocat.core.dataset import service as dataset_...
import copy import os # we already use worker threads, limit each process to 1 thread! from functools import partial from numbers import Number from typing import Optional, Sequence from trw.basic_typing import Stride, KernelSize from trw.layers import LayerConfig, BlockConv, BlockConvNormActivation, default_layer_con...
#!/usr/bin/python from __future__ import division from functools import lru_cache from persistent_lru_cache import persistent_lru_cache import timeit @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) @persistent_lru_cache(filename='fib.db', maxsize=None) def pfib(n):...
from collections import OrderedDict from rlkit.core.timer import timer from rlkit.core import logger from rlkit.data_management.replay_buffer import ReplayBuffer from rlkit.misc import eval_util from rlkit.samplers.data_collector.path_collector import PathCollector from rlkit.core.rl_algorithm import BaseRLAlgorithm ...
import torch import numpy as np import torch.nn.functional as F from PIL import Image import os from scipy.io import loadmat import matplotlib.pyplot as plt from torch.autograd import Variable import collections import torchvision.transforms as transforms def visualize_maps(maps, name): x = maps.cpu() dim = i...
# -*- coding: utf-8 -*- # Copyright 2020 The PsiZ Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
import numpy as np import pyautogui import time import cv2 from game_frame_detector import GameFrameDetector from scrollbar_detector import ScrollbarDetector from kai_recognizer import KaiRecognizer from rarity_recognizer import RarityRecognizer from common import Point, Size, Rect def takeScreenshot(): raw_captur...
# Write your code here :-) import board import alarm import audiomixer import time import busio import adafruit_aw9523 import digitalio from digitalio import DigitalInOut from audiocore import WaveFile from digitalio import DigitalInOut, Direction, Pull from random import randint from audiomp3 import MP3Decoder try: ...
#!/usr/bin/env python """ test_facet.py """ # Copyright (c) 2011 <NAME>, Real Programmers. All rights reserved. import json import unittest from OR_Client_Library.openrefine_client.google.refine.facet import * class CamelTest(unittest.TestCase): def test_to_camel(self): pairs = ( ('this', '...
import unittest import numpy as np import torch from kcd.kcd import KCD from graphio.graphio import GraphIO from graphutils.graphutils import GraphUtils from glob import glob import os.path import re class TestMutliArange(unittest.TestCase): def test_numpy(self): print("Testing Multi-arange Function in ...
# Releasy Abstract data model from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from .miner import AbstractReleaseMiner from typing import List import re class Tag: """Tag Attributes: name: tag name commit: tagged commit time: tag time ...
import re from serilizer_lib.parsers.json.json_config import * from serilizer_lib.parsers.json.exceptions import * def dump(obj, fp): s = dumps(obj) fp.write(s) def dumps(obj): def dump_complex(complex_obj): ans = "" tp = type(complex_obj) if tp == dict: ans += OBJE...
import json import decimal import datetime from django.conf import settings from django.http import HttpResponse from django.utils import timezone from django.shortcuts import get_object_or_404 from django.core.exceptions import PermissionDenied from .models import Competitor, Setting, Task, TaskView def _authenticat...