text
stringlengths
3.07k
12.6k
import unittest from datetime import datetime from botocore.stub import Stubber from freezegun import freeze_time from datahub.ingestion.api.common import PipelineContext from datahub.ingestion.source.glue import GlueSource, GlueSourceConfig, get_column_type from datahub.ingestion.source.metadata_common import Metada...
import torch import torch.nn.functional as F def mm_normalize(x, min=0, max=1): x_min = x.min() x_max = x.max() x_range = x_max - x_min x_z = (x - x_min) / x_range x_out = x_z * (max - min) + min return x_out def rand_range(size, min, max): return torch.rand(size)*(max-min)+min def ran...
import os import unittest import numpy as np import h5py as h5 from pandas.util.testing import assert_frame_equal from ifcb.tests.utils import withfile, test_dir from ifcb.data.h5utils import hdf2pd, hdfopen from ifcb.data.adc import AdcFile from ifcb.data.roi import RoiFile from ifcb.data.hdr import parse_hdr_file ...
import logging import os from collections import defaultdict from ke.utils.gpu_selector import get_available_gpu from ke.utils.hparams import Hparams from ke.utils.logger import logging_config os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'} def test(model_name, data_set, _tqdm=True): from ke....
# -*- coding: utf-8 -*- # # Copyright 2015 Canonical Ltd. # # Authors: # <NAME> <<EMAIL>> # try: from StringIO import StringIO except Exception: from io import StringIO import os import shutil import tempfile import unittest from mock import patch from charmhelpers.core.unitdata import Storage, HookData, kv...
# -*- coding: utf-8 -*- """ Created on sat Nov 21 18:09:37 2020 @author: Jalaj """ """ A Recommender System model based on the Collaborative filtering concepts. An Item-Item based collaborative filtering is used to find similar items which then is used to predict rating a user might give to a mo...
import decimal from hypothesis import given from hypothesis import strategies as st import pytest from eth_utils.currency import MAX_WEI, MIN_WEI, from_wei, to_wei, units @given( amount_in_wei=st.integers(min_value=MIN_WEI, max_value=MAX_WEI), intermediate_unit=st.sampled_from(tuple(units.keys())), ) def te...
import math from drafting.geometry.edge import Edge from fontTools.misc.arrayTools import sectRect, unionRect MINYISMAXY = False #https://stackoverflow.com/questions/20677795/how-do-i-compute-the-intersection-point-of-two-lines def line_intersection(line1, line2): xdiff = (line1[0][0] - line1[1][0], line2[0][0]...
import heapq def get_moves(): return [(0, 1), (1, 0), (0, -1), (-1, 0)] def update_snake_tail(snake_tail, position): new_snake_tail = snake_tail.copy() if snake_tail: new_snake_tail.popleft() new_snake_tail.append((position[0] * 51, position[1] * 51)) return new_snake_tail class PlanSt...
from functools import reduce from operator import ior from typing import List, Optional from qtpy.QtCore import Qt from qtpy.QtWidgets import ( QDockWidget, QFrame, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget, ) from .utils import combine_widgets, qt_signals_blocked class QtVi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.db.models import Q, Prefetch from django.db.models.functions import Substr, Upper from django.contrib.staticfiles.templatetags.staticfiles...
import objects import logging import sqlite3 import threading import json import serverprotocol import sqlite3 import base64 import socket tileset = [] SCODE_NEEDAUTH = 0 SCODE_BANNED = 1 SCODE_BADAUTH = 2 SCODE_BADREG = 3 class TileType(object): def __init__(self, sprite="nulltile", functions=()): sel...
import numpy as np import pandas as pd import random import os from sentence_transformers import SentenceTransformer, util import torch from torch import nn from torch.backends import cudnn from MultipleFieldsNet import MultipleFieldsNet import argparse DEVICE = torch.device("cuda") if torch.cuda.is_available() else t...
import numpy as np import scipy as sp import scipy.ndimage as ndimage import math from skimage import exposure,filters from matplotlib import pyplot as plt import cv2 import matplotlib.pyplot as plt from skimage.transform import hough_circle, hough_circle_peaks,hough_ellipse from skimage.feature import canny from skim...
########################################################################## # # pgAdmin 4 - PostgreSQL Tools # # Copyright (C) 2013 - 2020, The pgAdmin Development Team # This software is released under the PostgreSQL Licence # ########################################################################## """ Implements Ut...
#!/usr/bin/en python import os import sys import glob import json import numpy as np import pandas as pd from lxml import objectify def read_xml_sidecar(filepath): """ Read a CMTK xml sidecar file. Returns ======= lxml.objectify """ abs_path = os.path.abspath(filepath) with open(abs_p...
import argparse import datetime import multiprocessing import os import pathlib import pickle import shutil import sys from wrfhydropy.core.ensemble_tools import mute import yaml def parallel_update_job(arg_dict): # This function currently does 2 things # 1) if 'n_hours': is in the arg_dict: if extends an exi...
import sys from geom2d import Vector def generate_baltimore_structure( spans: int, span: float, height: float, cross_sec: float, young: float, node_load: Vector ): """ Generates and prints to the standard output a Baltimore truss structure with the given number of spans, s...
# source:https://github.com/zhuogege1943/dgc/blob/439fde259c/layers.py # arxiv:https://arxiv.org/abs/2007.04242 import torch import torch.nn as nn import torch.nn.functional as F class DynamicMultiHeadConv(nn.Module): global_progress = 0.0 def __init__(self, in_channels, out_channels, kernel_size, stride=1, ...
import os from AlphaGo.training.reinforcement_policy_trainer import \ run_training, _make_training_pair, BatchedReinforcementLearningSGD, log_loss import unittest import numpy as np import numpy.testing as npt import keras.backend as K from AlphaGo.models.policy import CNNPolicy from AlphaGo.go import GameState c...
import utils import directories import timer from collections import defaultdict import numpy as np import evaluation from collections import Counter class Document: def __init__(self, did, mentions, gold, mention_to_gold): self.did = did self.mentions = mentions self.gold = gold s...
import argparse import os import sys import urlparse import jinja2 import requests import yaml credentials = 'your_zendesk_email', '<PASSWORD>' zendesk = 'https://your_subdomain.zendesk.com' language = 'some_locale' def ensuredir(dir_name): try: os.makedirs(dir_name) except OSError: if not o...
# convenience wrapper for urllib2 & friends import cookielib import json import urllib import urllib2 import urlparse import re from urllib import quote, quote_plus as _quote_plus from lxml import etree, html from bs4 import BeautifulSoup # used in plugins that import this from urllib2 import URLError, HTTPError u...
# coding: utf-8 import os import itertools import torch from tqdm import tqdm import numpy as np import toolz as tz import napari from napari.qt import thread_worker from skimage.exposure import rescale_intensity from . import unet from . import watershed as ws u_state_fn = os.path.join( os.path.dirname(__fi...
""" Code based on: https://github.com/coreylynch/async-rl/blob/master/atari_environment.py """ """ The MIT License (MIT) Copyright (c) 2016 <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 t...
""" Apple Push Notification Service Documentation is available on the iOS Developer Library: https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html """ import time from apns2 import client as apns2_client from apns2 import credentials as apns2_c...
import torch from copy import deepcopy import os from tensorboardX import SummaryWriter class Callback(object): """ Abstract base class used to build new callbacks. """ def __init__(self): self.trainer = None self.estimator = None self.metrics_collection = None ...
# project: fuzzprj # Copyright (C) 6/25/18 - 6:54 PM # Author: bbrighttaer import numpy as np import tensorflow as tf import gym import matplotlib.pyplot as plt import keras.backend as K import fuzzrl.core.ga.schedule as sch import fuzzrl.core.plot.analysis as ana import random # registers the environment to use the ...
import json from pathlib import Path import numpy as np import tensorflow as tf from PIL import Image from tqdm import tqdm tfe = tf.contrib.eager tf.enable_eager_execution() def prepare_cifar(src_dir, dst_dir, n_train=50_000): src_dir = Path(src_dir) bin_paths = sorted(list(src_dir.glob('*.bin'))) dst_...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Filename : DeleteTiebaFatie.py # @Author : QCHighing # @Date : 2018/06/12 0012 08:06 # @Site : https://github.com/QCHighing # @Software : PyCharm import requests import re import test # 个人账户配置 # 在此处增加账号cookie和百度ID,以实现自动登录 cookie = '' user_name = '' # 如张三 # ...
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Communication Release: DSTU2 Version: 1.0.2 Revision: 7202 """ from typing import Any, Dict from typing import List as ListType from pydantic import Field, root_validator from . import fhirtypes from .backboneelement import BackboneElement f...
import json import cv2 from skimage import util import random import os import argparse import logging import numpy as np parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Perform Data Augmentation') parser.add_argument('-i', '--img',...
from spefit import BinnedNLL, ChargeContainer, SiPMModifiedPoisson, minimize_with_iminuit, UnbinnedNLL from sstcam_sandbox.d201202_tutorial_material import poi, matched_voltage, nsb from CHECLabPy.core.io import HDF5Reader, HDF5Writer from sstcam_sandbox import get_data, get_plot import numpy as np from numpy.polynomia...
import pytest @pytest.fixture def c(w3, get_contract): with open('examples/stock/company.vy') as f: contract_code = f.read() contract = get_contract(contract_code, *[w3.eth.accounts[0], 1000, 10**6]) return contract def test_overbuy(w3, c, assert_tx_failed): # If all the stock has been b...
import argparse import os from neurAD.pytorch.examples.utils import save_params, get_timestamp from NN import Optimus import torch from losses import loss from datasets import PointCloudDataset from torch.utils.data import DataLoader from models import pointnet_classifier_git0, pointnet_classifier_git1, pointne...
import conf import errors from api import get, post, delete, put, AdminApi, API_ALL, API_CABINET, request_api_type from model import News, Customer, MessageTemplate from model import display, autocommit from api.admin.role import TokenManager, TokenId from api.check_params import check_params from api.validator import ...
# -*- coding: utf-8 -*- """ Created on Tue Aug 4 11:01:16 2015 @author: hehu """ import matplotlib.pyplot as plt import numpy as np from sklearn.neighbors import KNeighborsClassifier from sklearn.lda import LDA from sklearn.svm import SVC, LinearSVC from sklearn.linear_model import LogisticRegression from sklearn.na...
import json import subprocess from pathlib import Path import luigi from luigi.util import inherits, requires from luigi.contrib.sqla import SQLAlchemyTarget import pipeline.models.db_manager from ..tools import tools from .targets import TargetList from .helpers import meets_requirements, is_inscope from ..models.ta...
import qgate.model as model from .runtime_operator import Observable, Gate, ControlledGate, Reset, Prob, Decohere from .runtime_operator import Observer from .rop_executor import RopExecutor from .value_store import ValueStoreSetter import numpy.random as np_random class ValueObserver(Observer) : def __init__(self...
import threading from robocorp_ls_core.protocols import IEndPoint, IDirCache, IProgressReporter from contextlib import contextmanager from typing import Optional, Iterator from robocorp_ls_core.robotframework_log import get_logger from robocorp_ls_core.basic import implements log = get_logger(__name__) def _next_i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Name: Reformat dna Author: <NAME> (<EMAIL>) Description: Does a reformat of a given file into format fasta. Details: If a line starts with symbol '>' it is taken as a start of a new sequence Arguments: Script takes at least one argument - name of the input file If seco...
from __future__ import print_function import logging import os import sys import traceback try: _debug_env = int(os.environ.get("DEBUG")) except: _debug_env = 0 try: _nested_env = int(os.environ.get("LVL")) except: _nested_env = 0 os.environ["LVL"] = str(_nested_env + 1) class Core(object): LOG_...
# Copyright 2019 Xanadu Quantum Technologies 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 agre...
import math class _AbstractEvent: name = "Generic MIDI Event" def __init__(self, tick): self._tick = tick @property def tick(self): return self._tick def __cmp__(self, other): return self._tick - other._tick def __baserepr__(self, keys=[]): keys = ['tick'] + ...
from Note import Pitch, Note from enum import Enum from utils import parse_num_frac, raiseError from copy import copy, deepcopy class ChordType: def __init__(self, name: str, symbol: str, semitones: tuple): self.semitones: tuple = semitones self.type: str = symbol self.name: str = name ...
from __future__ import annotations from copy import deepcopy from dataclasses import dataclass from typing import Dict, List, Tuple import vigorish.database as db from vigorish.data.metrics.pitchfx.pitchfx_metrics import PitchFxMetrics from vigorish.enums import PitchType PitchFxByPitchTypeResults = Tuple[PitchFxMet...
import os import glob import pyregion import numpy as np import argparse import subprocess import logging logger = logging.getLogger(__name__) def link_overwrite(src, dst): if os.path.islink(dst): logger.info("Unlinking pre-existing sym link {}".format(dst)) os.unlink(dst) logger.info("Linkin...
import os, sys import torch def read_policy(filename, section='init', debug=False, verbose=print): if not os.path.isfile(filename): verbose("file no exist: %s" % filename) return [] policies = [] attr = None valid = False found = False # found policy for the section with open...
#!/usr/bin/env python """ CLI for the .gbk plotting tool that supports specification of which colours to assign to features, how long the lines of features should be, and the spacings between features and lines. Specify feature:colour pairs with comma-seperated values. For example: -c 'membrane:(1.0,1.0,1.0),terminat...
#!/usr/bin/env python # coding=utf-8 from __future__ import print_function import os import sys import imp import optparse import logging import inspect import socket import time import traceback from multiprocessing import Process, Event from six import binary_type from six import b as bytes # Python 2.6 compat if ...
import os import pytest import time from django.core.files.base import ContentFile from django.core.files.storage import default_storage from django.utils.translation import gettext as _ from pretix.presale.style import regenerate_css from pretix.presale.style import regenerate_css from ..utils import screenshot @...
import argparse import collections import datetime import json import os import logging import itertools import time import _jsonnet import attr import numpy as np import torch import wandb from tensor2struct.commands import train from tensor2struct.training import maml from tensor2struct.utils import registry, rand...
"""Functions to check the status of an existing game on BGA.""" import datetime import logging from logging.handlers import RotatingFileHandler from bga_account import BGAAccount from bga_game_list import get_game_list from bga_game_list import update_games_cache from creds_iface import get_discord_id from utils impor...
#!/usr/bin/env python3 # # Copyright (c) 2018 Institute for Basic Science # # 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 u...
import logging, sys from flask import Flask from flask import request from flask import g from flask_httpauth import HTTPBasicAuth from aldap import Aldap from cache import Cache from os import environ # --- Logging -------------------------------------------------------------------- loglevel_map = { 'DEBUG': logging....
# encoding: utf-8 # -*- test-case-name: IPython.kernel.test.test_pendingdeferred -*- """Classes to manage pending Deferreds. A pending deferred is a deferred that may or may not have fired. This module is useful for taking a class whose methods return deferreds and wrapping it to provide API that keeps track of thos...
import ray from typing import List, Tuple, Union, Any, Dict, Callable, Optional from ray.experimental.workflow import workflow_context from ray.experimental.workflow import serialization_context from ray.experimental.workflow.common import ( RRef, Workflow, StepID, WorkflowOutputType, WorkflowInputTuple) from ray....
# calculate tracklengths and recoil spectra induced by WIMP scattering for one sort of nuclei in a mineral # results saved in "Data/Tracklengths_recoilrates" import numpy as np import matplotlib.pyplot as plt import scipy.special as sp import scipy.integrate as integrate from scipy.interpolate import interp1d ...
# Copyright 2018, 2019, 2020 CNRS - Airbus SAS # Author: <NAME>, <NAME>, and <NAME> # # 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 l...
import pytz import datetime from collections import OrderedDict from django.db import models from django.db.models import Q from django.utils import timezone from django.core.exceptions import SuspiciousOperation from rest_framework import serializers from perftracker.models.hw_farm_node import HwFarmNodeModel, HwFa...
""" ========================== Model Complexity Influence ========================== Demonstrate how model complexity influences both prediction accuracy and computational performance. The dataset is the Boston Housing dataset (resp. 20 Newsgroups) for regression (resp. classification). For each class of models we m...
#!/usr/bin/python # Copyright (c) 2020, 2021 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright 2016 <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 require...
#!/usr/bin/env python # Copyright (C) 2013 The Android Open Source Project # # 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...
''' Created on Oct, 2017 @author: hugo ''' import re, string import numpy as np from rapidfuzz import fuzz, process from .utils import dump_ndarray, tokenize from core import config question_word_list = 'who, when, what, where, how, which, why, whom, whose'.split(', ') def find_parent(x, tree, conn='<-'): roo...
import math from itertools import combinations from typing import Optional from cvat.apps.engine.ddln.geometry import Line, Point, get_angle_between ANGLE_THRESHOLD = 5 * math.pi / 180 ERROR_THRESHOLD = 30 class Runway: def __init__( self, id: str, left_line: Optional[Line], righ...
#!/usr/bin/env python ################################################################################ # The Sandbox Libraries (Python) - Sample Script # # # # Copyright (C) 2009-2013 <NAME>, <<EMAIL>> ...
import pyttsx3 import datetime import speech_recognition as sr import pyaudio import wikipedia import webbrowser import subprocess import re import urllib from urllib.request import urlopen from bs4 import BeautifulSoup as soup import os import psutil import sys import calendar import weather import ap...
import git import PyInquirer import in_place import pathlib import subprocess import datetime root = pathlib.Path().absolute() def isRootFolder(): return root[-10:] == "codecharta" def confirm(message, printMessage): confirm = [{ "type": "confirm", "name": "confirmed", "message": m...
import shutil import logging import zipfile import pathlib from pprint import pprint # noqa from normality import safe_filename, stringify from followthemoney import model from servicelayer.archive.util import ensure_path from ingestors.ingestor import Ingestor from ingestors.support.xml import XMLSupport from ingest...
# Copyright (c) 2019 Microsoft Corporation # Distributed under the MIT software license from ..data import ClassHistogram, Marginal from ..perf import ROC, PR, RegressionPerf from ..blackbox import LimeTabular from ..blackbox import ShapKernel from ..blackbox import MorrisSensitivity from ..blackbox import PartialDep...
""" This module provides a name_to_constructor dict for all models/estimators in scikit-learn, plus a couple test models and error handling functions """ import warnings import inspect import sklearn.base import sklearn.utils.testing from sklearn.externals import joblib import numpy as np import xgboost as xgb impor...
""" mongo ----- Tools for working with MongoDB. @author: <NAME> @author: <NAME> """ import argparse from nordlys.config import MONGO_DB, MONGO_HOST from pymongo import MongoClient class Mongo(object): """Manages the MongoDB connection and operations.""" ID_FIELD = "_id" def __init__(self, host, db, co...
# -*- coding: utf-8 -*- # # Copyright © 2009- The Spyder Development Team # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """External System Shell widget: execute terminal in a separate process""" # Standard library imports import os import sys # Third party import...
import os from sys import exit from .log import get_logger logger = get_logger() def get_workspace(): from ROOT import RooWorkspace return RooWorkspace('workspace') def filter_content(lines): lineno = 0 for line in lines: line = line.strip() if line and not line.startswith('#'): ...
from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.shortcuts import reverse from django.conf import settings from django.http.response import JsonResponse, HttpResponse from django.views.decorators.csrf import csrf_exempt from djan...
#!/usr/bin/env python # -*- coding: utf-8 # Copyright 2017-2019 The FIAAS 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 # # Unle...
# -*- coding: utf-8 -*- import glob import os import pandas as pd from glassimaging.dataloading.niftidataset import NiftiDataset import logging import json import nibabel as nib import numpy as np from torch.utils.data import Dataset class TissueDataloader(NiftiDataset): available_sequences = ['flair', 't1', 't...
from ..general_imports import * from math import radians def is_3_by_3(U): """ U is a [3 x 3] matrix """ return isinstance(U, np.ndarray) and U.shape is not (3, 3) def pos_def_sym(U): """ check if U is [3 x 3] positive definite and symmetric """ dU = (U - U.T).reshape(9) # return i...
#!/usr/bin/env python3 import subprocess as sp import tempfile, os, json from pathlib import Path from copy import deepcopy import yaml import click import neurodocker as ndr # default setting for specific neurodocker keys, # this value will not have to be set in the parameters.yml, but can be overwritten DEFAULT_INST...
import argparse import os from pathlib import Path from typing import Dict, Any, List import pytorch_lightning as pl import torch import yaml from albumentations.core.serialization import from_dict from iglovikov_helper_functions.config_parsing.utils import object_from_dict from iglovikov_helper_functions.dl.pytorch.l...
import torch import torch.nn as nn import torch.nn.functional as F targetLabels = [] predsMade = [] def accuracy(outputs, labels): """ Calculate model accuracy * :param outputs(torch.tensor): Pytorch weights tensor * :param labels(list(str)): List of known labels :return (torch.tensor): P...
import asyncio import pprint import sqlite3 from typing import Dict, List, Tuple, Union from dependencies import Injector from loguru import logger from telethon import TelegramClient, events from telethon.errors import UserIsBlockedError from telethon.events import NewMessage from telethon.tl.types import User from ...
# make a basic 3D unet architecture ... simple 3D vanilla unet ... from torch import nn from .additions import ProjectExciteLayer, GridAttention, DeformConv3D import torch # idea is to iterate through all our data. Split patients by Disease site # save .csv image path, with center of mass of GTV... # then for that sli...
from tkinter import * from plyer import notification import psutil import os btn_state = True #functions def cpucheck(): cpu = psutil.cpu_percent() lbl1.config(text=str(cpu)+'%') lbl1.after(1000, cpucheck) def ramcheck(): per_ram = psutil.virtual_memory().percent lbl2.config(text=s...
import random from collections import Counter import pytest from agents.DQN_agents.DQN_HER import DQN_HER from agents.DQN_agents.DDQN import DDQN from agents.DQN_agents.DDQN_With_Prioritised_Experience_Replay import DDQN_With_Prioritised_Experience_Replay from agents.DQN_agents.DQN_With_Fixed_Q_Targets import DQN_Wit...
#!/usr/bin/python3 ''' [ RN2483 Library ] Python library for RN2483 LoRaWAN transceiver This implementation is meant to be used on Raspberry Pi. [-------------------------------------------------------] Version: [0.1]: + Changes: - Completed command set dict...
import json import os from dataclasses import dataclass import aiohttp from bs4 import BeautifulSoup import config from checking.marks.compares import file_compares, get_discipline_objs_from_diff import utils from utils.json_files import JsonFile from utils.notify_to_user import SendToTelegram from utils.make_request...
# -*- coding: utf-8 -*- import os import pytest from mock import Mock from six.moves import urllib from gtts.tts import gTTS, gTTSError from gtts.langs import _main_langs from gtts.lang import _extra_langs # Testing all languages takes some time. # Set TEST_LANGS envvar to choose languages to test. # * 'main': Langu...
""" 2021 Day 17 https://adventofcode.com/2021/day/17 """ from typing import Dict, Set, Tuple import aocd # type: ignore def read_target(text: str) -> Tuple[int, int, int, int]: parts = [ [int(val) for val in part[2:].split("..")] for part in text[13:].split(", ") ] return parts[0][0], parts[0][1...
import numpy as np import math def data_regularize(data, type="spherical", divs=10): limits = np.array([ [min(data[:, 0]), max(data[:, 0])], [min(data[:, 1]), max(data[:, 1])], [min(data[:, 2]), max(data[:, 2])]]) regularized = [] if type == "cubic": # take mean from poi...
from ...utils import human_time, profile_lookup from datetime import datetime import pytz from itertools import groupby def average(timestamp, timestep, inputs): if len(inputs) == 1: vals = [x[2] for x in next(iter(inputs.values()))] if vals: return [(timestamp, timestep, sum(vals) / ...
import random import string import unittest from cn_v2.manager.watcher import * CONFIG_FILE = "../config/test.yaml" class TestCourseManager(unittest.TestCase): def test_run(self): m = CourseManager(CONFIG_FILE, BaseManager.DA) m.update_course_collection() def test_update_course_collection(...
from math import isclose import pytest from sympy import symbols, nsimplify, integrate from rcdesign.is456.stressblock import LSMStressBlock from rcdesign.is456 import ecy, ecu def a_p(z1: float, z2: float, k: float) -> float: zcy = k - 3 / 7 return (z2 ** 2 - z1 ** 2) / zcy - (z2 ** 3 - z1 ** 3) / (3 * zcy ...
#!/usr/bin/env python # This is a standalone git server implementation in python import argparse from argparse import RawTextHelpFormatter import hashlib import logging import os import re import shutil import sys import zipfile if sys.version_info[0] == 2: print('Not supported on Python 2.x') sys.exit(1) # ...
""" Plugin annotation and partitioning. This determines according to a set of rules which plugin to use for which operation. """ from __future__ import absolute_import, division, print_function from collections import defaultdict import datashape from ..ir import FuncArg from ...strategy import CKERNEL from ....io.s...
# -*- coding: utf-8 -*- """ Created on Tue Mar 22 10:43:29 2016 @author: rob """ import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix sess = tf.InteractiveSession() ##Load the data #data_train = np.genfromtxt('ModelingTrain.csv',delimiter=',',skip_he...
# -*- coding: utf-8 -*- import random kadinisimler=["Nuray","Nehi̇r","Hali̇me","Ayşenur","Ayten","Rabi̇a","Duygu","Gülay","Ni̇sanur","Necla","Ebru","Arzu", "Sudenaz","Derya","Edanur","Seda","Si̇bel","Emel","Damla","İlayda","Hava", "Meli̇ke","Sevi̇m","Fatma","Zehra","Nurten","Hacer","Türkan","Gamze","Ayşe", "Sema",...
import numpy as np import pandas as pd import os from os import listdir from os.path import isfile, join, getsize, dirname from collections import Counter, OrderedDict import shutil import warnings import hickle import h5py import pickle import random import feather import time import gc import matplotlib.pyplot as plt...
import numpy as np import scipy.stats as sps from skimage.transform import rotate from skimage.morphology import disk, opening, closing def get_max_proy(img, theta=False, circle=False, f1=np.sum, f2=np.sum): cvs = [] img = np.array(img, copy=True).T if (theta is False): theta = np.linspace(0., 180., 181, ...