text
stringlengths
3.07k
12.6k
import datetime import json import logging import sys import traceback import flask import flask_admin import flask_appbuilder import pendulum from airflow.configuration import conf from airflow.models import DagModel from airflow.plugins_manager import AirflowPlugin from airflow.utils.db import provide_session from ...
import sys import os import random import datetime from datetime import timedelta from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession from pyspark.sql.types import * from pyspark.sql import SQLContext from pyspark.sql import Row from simplekml import Kml, Model, AltitudeMode, Orientation,...
"""Model training.""" import datetime import os import random import time import numpy as np import pandas as pd import pytz import sklearn import torch import torch.nn as nn from sklearn.model_selection import GroupKFold from torch.utils.data import DataLoader import src.metrics as metrics import src.results as res...
from typing import Any, List, Tuple import rclpy import rclpy.node import conveyor_msgs.msg from conveyor_msgs.srv import AddPack, SetBeltSpeed from std_srvs.srv import Empty from std_msgs.msg import UInt8 from .utils import Map, Belt, PositionOnBelt from dataclasses import dataclass @dataclass class Package: ui...
import copy import math import torch import torch.nn as nn import torch.nn.functional as F from data import Collate class PositionalEncoding(nn.Module): def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dro...
import numpy as np import random from collections import defaultdict REWARD = -0.1 GAMMA = 0.7 DISCOUNT = 0.9 # discount 1 takes forever MAX_ERROR = 10**(-3) # Parameters for MC EPISODES = 10 START = (3,2) TERMINAL_STATES = [(3,0),(0,3),(3,2)] ACTIONS = [(1, 0), (0, -1), (-1, 0), (0, 1)] # actions which can be D, L...
from __future__ import division import re from math import sqrt, sin, cos, log, tan, acos, asin, atan, e, pi from operator import truediv as div from operator import add, sub, mul, pow from .numbers import NumberService class MathService(object): __constants__ = { 'e': e, 'E': e, 'EE': e,...
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt from QR_method.QR_algorithm import QR_algorithm def make_A_matrix(n,k,m): A = np.zeros((n,n)) for i in range(1,n): ki = k(i) ki_plus = k(i+1) A[i-1,i-1] = ki + ki_plus A[(i-1),(i-1)+1] = A[(i-1)+1,(i-1)]...
import json from collections import deque from dataclasses import dataclass from pathlib import Path from typing import Set, List, Union, Tuple from machines.TuringMachine import Symbol, State Variable = str Terminal = str Sentence = List[str] @dataclass class Production: head: List[Union[Terminal, Variable]] ...
import os import logging import numpy as np import pandas as pd from riiid.core.data import DataLoader, preprocess_questions, preprocess_lectures, save_pkl, load_pkl from riiid.core.model import RiiidModel from riiid.validation import merge_test from riiid.utils import configure_console_logging from riiid.config import...
import json import elasticsearch from elasticsearch.exceptions import RequestError, ElasticsearchException from daybed import logger class SearchError(Exception): """Exception raised on request error to indexer. """ def __init__(self, *args): self.status_code, self.error, self.info = args[:3] ...
from __future__ import print_function import sys sys.path.append('..') from Game import Game from TicTacToeLogic import Board import numpy as np """ Game class implementation for the game of TicTacToe. Based on the OthelloGame then getGameEnded() was adapted to new rules. Author: <NAME>, github.com/evg-tyurin Date: J...
from model import get_model import json import numpy as np from bert4keras.snippets import sequence_padding import sys import random import os path_source,path_target,path_model,config_path,checkpoint_path,dict_path = sys.argv[1:] if checkpoint_path=='None': checkpoint_path = None def _is_chinese_char(char): ""...
# pylint: skip-file import datetime import re import requests from sqlalchemy import exc import pandas as pd from dms_daemon import CONFIG, nemweb_requests, orm def slack_dms_webhook(message): json_text = "{0} \n ({1})".format( message, datetime.datetime.now().strftime("%Y-%m-%d %H:%M") ) reques...
# Copyright (c) 2020 PaddlePaddle 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 required by appli...
# pylint: disable=no-member import json import time from urllib.parse import urlparse from flask import current_app from networktables import NetworkTables, NetworkTablesInstance class Unit: units = {} api = None def __init__(self, unit_id, camera_inums): self.cameras = {} self.id = uni...
# # BSD 3-Clause License # # Copyright (c) 2017 xxxx # All rights reserved. # Copyright 2021 Huawei Technologies Co., Ltd # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 16 15:46:45 2020 @author: laura, sarah """ #Idee: Heterogene Agenten mit unterschiedlichem Nutzen import sys; sys.path.insert(0, './python') import numpy as np from economists import Economist # Wenn ihr eine andere Klasse aus diesem File verwenden ...
# Copyright 2022 <NAME> (@singletongue) # # 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 i...
from datetime import timedelta from application.models.utils import ( get_credentials_from_wrdsbusername, get_team_members, get_wrdsbusername_from_id, getteamname, getteamid, isadmin, ) from . import database, loginmanager login_manager = loginmanager.get_login_manager() class User: def...
import itertools import logging import sys import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision from sklearn import metrics from torch.utils.data import DataLoader, Dataset from torchvision import models from model import CompatModel from polyvore_dataset import Cat...
from subprocess import call import mne import numpy as np import os import sys from mne import find_events from mne.io import edf, set_eeg_reference, make_eeg_average_ref_proj from mne.channels import read_montage from ..utils import logger, deprecated, verbose @deprecated('May fail depending on MNE version! Use impo...
#!/usr/bin/env python import argparse import codecs, sys import re import requests from bs4 import BeautifulSoup import json from pypinyin import pinyin, Style COURSE_URL = "/course/977288/korean-grammar-in-use-11/" CARD_COLUMNS = ("col_a", "col_b") def lazy_property(fn): """Decorator that makes a property lazy-...
import numpy as np import cv2 import argparse parse = argparse.ArgumentParser() parse.add_argument("-i","--image",required=True,help="Provide path to image") args = vars(parse.parse_args()) try: image = cv2.imread(args["image"]) gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) global_blurred = cv2.blur(gray...
# -*- coding: utf-8 -*- import uuid # pragma: no cover import yaml # pragma: no cover import os # pragma: no cover import re # pragma: no cover import pytest # pragma: no cover from _pytest import fixtures # pragma: no cover from _pytest.fixtures import ( ...
#coding: utf-8 import matplotlib.pyplot as plt from plotly.subplots import make_subplots from matplotlib.colors import Colormap from matplotlib.axes import Axes from plotly.graph_objects import Trace from matplotlib.figure import Figure as mplFigure from plotly.graph_objs import Figure as plotlyFigure from matplotlib....
import hashlib import hmac import time import requests import json from enum import Enum from datetime import timedelta, datetime class CandleInterval(Enum): MINUTE_1 = timedelta(minutes=1) MINUTE_5 = timedelta(minutes=5) HOUR_1 = timedelta(hours=1) DAY_1 = timedelta(days=1) valid_times = 'FILL_OR_K...
import collections import datetime from typing import List, Optional, Dict, Any, Tuple from jiras.etl.types import Event, Field, JiraIssue, TimelineItem _STATUS = 'status' _ASSIGNEE = 'assignee' _VAL_RESOLUTION = 'resolution' def _parse_datetime(value: str) -> datetime.datetime: return datetime.datetime.strptim...
import os import random import subprocess import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from dja...
#!/usr/bin/env python3 """ RFC.py - A python module that downloads Request For Comments from the Internet Engineering Task Force into a Sqlite database for offline reading. Includes full text search, RFC number search and bookmarking capabilities and weekly updates inline with the IETF policy of weekly...
import pandas as pd import os import sys sys.path.append('../../') from models.indirect.policy_learning_thresholding import get_iat_broad from utils.evaluation_utils import calculate_ci def get_best_case_idsa_baseline(resist_df, switch_props, option='doc',...
# Copyright 2014 Cloudbase Solutions Srl # # 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 l...
#!/usr/bin/env python3 '''This script is assumed to run from the project root''' import subprocess as sp import os.path as op import os import sys import json from pathlib import Path from util import * from itertools import groupby from collections import defaultdict import platform os.chdir(op.join(os.environ['MESON...
from django.db import models from django.contrib.auth.models import User from django.contrib.postgres.fields import JSONField import logging django_log = logging.getLogger('django') class Profile(models.Model): ''' Extends the Django-provided User model. Stores the users preferred topics and stations, an...
#!/home/kjell/envs/vol-env/bin/python import discord from discord.ext import commands import traceback import sys import logging import asyncio import asyncpg import auth_token import aiohttp # set up logging logger = logging.getLogger('discord') logger.setLevel(logging.INFO) handler = logging.FileHandler( file...
# -*- coding: utf-8 -*- """ A baseline authorship attribution method based on a character n-gram representation and a linear SVM classifier for Python 2.7 Questions/comments: <EMAIL> It can be applied to datasets of PAN-18 cross-domain authorship attribution task See details here: http://pan.webis.de...
# -*- coding: utf-8 -*- """ unpacking - a module for detecting packers and unpacking packed files Part of D&C-Clustering-POC Copyright (c) 2020 <NAME> External dependencies: * diec: Manual installation: https://github.com/horsicq/Detect-It-Easy * clamav: apt-get install clamav * libclamunrar9: ...
import json import pprint import ijson.backends.yajl2_cffi as ijson import datetime from datetime import datetime as cl_datetime from collections.abc import Mapping, Iterable from base64 import b64encode, b64decode from decimal import Decimal from uuid import UUID JSON_ENCODER_LAMBDAS = { bytes: lambda o: "~b%s" %...
import itertools import torch import torch.nn as nn import torch.nn.functional as F from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy class DeepMutualLoss(nn.Module): def __init__(self, base_criterion, w, temperature=1.0): super().__init__() self.base_criterion = base_crit...
#!/usr/bin/env python3 import os import json import numpy as np import matplotlib.pyplot as plt def sigmoid(x): """Compute 1 / (1 + e^(-x)). Arguments: x (numpy.ndarray): A matrix of real numbers. Returns: numpy.ndarray: A matrix of real numbers such that for every element x_i in x...
###################################################################### # Author: <NAME> & <NAME> TODO: <NAME> & <NAME> # Username: heggens & lovelle TODO: Jamalie & Alfarozaalae # # T15: Events and GUIs # # Purpose: Show interactive DNA strand copying using the turtle library. # This program also uses ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import io import logging import os import sys import subprocess from os.path import expanduser from contextlib import contextmanager from io import StringIO from dotenv import dotenv_values from .compat import PY2, StringIO, to_env from .version import ...
import json import logging import re from datetime import datetime, time from django.conf import settings from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.db import connection from django.db.models import Count from django.http import JsonResponse from django.utils import timezone...
#------------------------------------------------------------------------------- # Name: CM_Formatter # Purpose: # # Author: BenPc # # Created: 16-07-2019 # Copyright: (c) BenPc 2019 # Licence: <your licence> #------------------------------------------------------------------------------- import G...
# -*- coding: utf-8 -*- """Database model for Bio2BEL Phosphosite.""" from sqlalchemy import Column, ForeignKey, Index, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import backref, relationship from pybel import BELGraph from pybel.constants import HAS_VARIANT, REGULATE...
# Copyright (c) 2020, <NAME> <<EMAIL>> # Licenced under the BSD 2-Clause License. """ Main results for 1-word perturbation """ import sys, os, json, pdb, argparse def load_result(filename): with open(filename) as file: return json.loads(file.read()) def print_small_float(x): str = "%.1E" % x idx ...
"""Local settings for epidemic forecasting.""" import epifx import pypfilt import epifx.summary import pypfilt.summary import datetime import errno import os.path def get_start_date(year): """Begin forecasts on the first of January.""" return datetime.datetime(year, 1, 1) def get_until_date(year): ""...
""" Code taken from https://github.com/microsoft/recommenders """ from functools import lru_cache, wraps import logging import pandas as pd import numpy as np from constants import ( DEFAULT_USER_COL, DEFAULT_ITEM_COL, DEFAULT_RATING_COL, DEFAULT_LABEL_COL, ) from utils.decorator_utils import timing...
# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fil...
#coding=utf-8 import re import sys import os import subprocess from git import Repo #脚本环境: #brew install pyenv #pyenv init (需要按提示修改相应文件) #pyenv install 3.7.0 #pyenv shell 3.7.0 #pip install GitPython #将该脚本放置工程spec同级目录 #python podPackage.py #pod私有库打版本脚本 #主要流程: # 1、查找当前路径所有spec,输入人选择上传的spec # 2、根据输入新的版本号,修改spec文件 # 3...
import ctypes import math import sys import time from .UART import UART from .CAN import CAN # @name: toCharArray_c # @desc: takes the items in a class and outputs them to an array with sizes no larger # than a char in the order that is defined in X_MESSAGE_0::dataPacketToArray # @param: none # @retu...
""" ==================== The qc.passqc module ==================== The qc.passqc module contains functions for determining which NPs pass a set of quality control conditions. """ import pandas as pd def get_reference(condition_ref_string, stats_df): """ If condition_ref_string matches a column in stats_df,...
import functools import time import inspect import pandas as pd import datetime from sachima.log import logger def timer(func): """Print the runtime of the decorated function""" @functools.wraps(func) def wrapper_timer(*args, **kwargs): start_time = time.perf_counter() # 1 value = func(*...
import copy import logging import os import pathlib import sys from typing import Dict, List, Optional import psycopg import testing.postgresql import yaml from jsonschema import validate from psycopg.rows import dict_row from src.mqtt_client import MqttConfKey, MQTT_JSONSCHEMA from src.schema_creator import SchemaCr...
import json import os import logging import redis from wtforms import StringField, IntegerField from .base import BaseStorage, BaseForm logger = logging.getLogger(__name__) def get_redis_connection(db = None, redis_config={}): """Get a redis connection from the provided arguments. Args: db (int): Da...
""" Script by <NAME>, November 2020 Used to finetune models trained on pathology images (pre-chunked) on External Images """ import numpy as np import tables import pickle import neptune from neptunecontrib.monitoring.keras import NeptuneMonitor import collections from sklearn.utils import class_weight import cv2 fr...
"""The auto-rebuild system is an optional part of webassets that can be used during development, and can also be quite convenient on small sites that don't have the performance requirements where a rebuild-check on every request is fatal. This module contains classes that help determine whether a rebuild is required f...
#encoding:utf-8 from flask import render_template, redirect, url_for, abort, flash, request,\ current_app, session, g from flask.ext.login import login_required, current_user from ..models import Permission, Role, User, Post, Comment, Message, Category, Star, Webpush from ..decorators import admin_required, permiss...
import os from typing import Any import covertreec import numpy as np from d3m import container, utils from d3m.metadata import hyperparams, base as metadata_base from d3m.metadata import params from d3m.primitive_interfaces import base from d3m.primitive_interfaces.supervised_learning import SupervisedLearnerPrimitiv...
import importlib import Bot import requests import Moduleloader import logging import json import time #import ts3.Events as Events # from utility import parse_json, save_to_txt, read_from_json, wipe_json_file bot = None API_KEY = "<KEY>" @Moduleloader.setup def vt_setup(ts3bot): global bot bot = ts3bot ...
# coding=utf-8 # Copyright 2019 The TensorFlow Datasets 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 appl...
""" As the name indicates, generates a "simple" dyadic Graph based on the term co-occurrences. We skip parts of the LOAD model, as for example the direct linking of sentences and documents, and instead treat that part as "further available meta-information", but restrict our graph specifically to the terms, or respecti...
import argparse import os import sys ############################################## parser = argparse.ArgumentParser() parser.add_argument('--epochs', type=int, default=100) parser.add_argument('--batch_size', type=int, default=5) parser.add_argument('--gpu', type=int, default=0) parser.add_argument('--lr', type=flo...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2019, <NAME> (<EMAIL>) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = """ --- module: offense_note short_description: Cr...
import numpy as np from pathlib import Path from argparse import ArgumentParser import matplotlib.pyplot as plt import matplotlib.cm as cm from configparser import ConfigParser class ConfigParser_with_eval(ConfigParser): def get(self, *argv, **kwargs): import numpy val = super(ConfigParser_with_ev...
import re from math import exp import random _error_threshold = 0.0001 class HMMException(Exception): def __init__(self, msg = ""): self.msg = msg def __str__(self): return self.msg _blank = re.compile("^\s*\n$") def _next_line(fp): """Return the next line of fp that is not either em...
################################################################################# # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed under the Apache License, Version 2.0 (the "License"). ...
import numpy as np import matplotlib.pyplot as plt from matplotlib.lines import Line2D def perpendicular_distance(point, line_points, projectors): diff = line_points-point[:, 0] # (a - p) temp = np.matmul(projectors, diff[:, :, np.newaxis]) # (I - nnT)(a - p) squared_distances = np.matmul(diff[:, np.n...
###################################### # Import and initialize the librarys # ###################################### from random import randint from code.api.core import os, log, screens, coreFunc, PgEss from code.api.events import gameEvent from code.api.actions import Runclass ################# # Setup logging # ##...
import numpy as np from modpy.random import UniformDist, JointDistribution from modpy.optimize.benchmarks.benchmark_suite import FiveUnevenPeakTrap, EqualMaxima, UnevenDecreasingMaxima,\ Himmelblau, SixHumpCamelBack, ModifiedRastrigin, CrossInTray, HolderTable, Shubert, Vincent from modpy.optimize import mm...
import shlex, shutil, json class enable_menu_build_flowEventListener(enable_menu_project_typeEventListener): path = os.path.join(PROJECT_FOLDER, "flow", "Main.sublime-menu") path_disabled = os.path.join(PROJECT_FOLDER, "flow", "Main_disabled.sublime-menu") class build_flowCommand(manage_cliCommand): isNode = T...
import pandas as pd from bs4 import BeautifulSoup, Comment import requests import unicodedata, unidecode def get_player_url(name): ''' Builds and returns the URL extension for a given player. Parameters: name (string): The name of an NBA player (e.g. '<NAME>') Returns: A list containing the U...
from __future__ import division import glob, os from dxtbx.model.experiment_list import ExperimentListFactory from libtbx import easy_pickle try: import resource import platform def get_memory_usage(): # getrusage returns kb on linux, bytes on mac units_per_mb = 1024 if platform.system() == "Darwin":...
import torch.nn as nn import copy import torch from relogic.logickit.modules.rnn import dynamic_rnn # class PredictionModule(nn.Module): # def __init__(self, config, task_name, n_classes, activate=True): # super(PredictionModule, self).__init__() # self.config = config # self.task_name = task_name # ...
from collections import OrderedDict import re from serial_protocol.events import Event START_MESSAGE = b'!' RECEIVER_TYPE = b'1' END_MESSAGE = b'\x0d\x0a' EOF = b'\x1a' _MESSAGES = OrderedDict() def get_event_for(data, requests): code = data[2:5] if code not in _MESSAGES: return None, None ...
import torch import torchvision import torch.nn.functional as F # import os # dirname = os.path.dirname(__file__) # filename = os.path.join(dirname, 'relative/path/to/file/you/want') def test_manual_data(): from pathlib import Path import requests DATA_PATH = Path("data") PATH = DATA_PATH / "mnist" ...
# -*- coding: utf-8 -*- import os import torch import timm #%% class CheckpointSaver: def __init__(self, get_save_path, device, max_saved=5): """ get_save_path: function from score to file path device: 'cpu' or 'cuda' max_saved: number of best weights to save """ se...
import torch import torch.nn as nn import torch.nn.functional as F def label_smoothing_loss(inputs, targets, alpha): log_probs = torch.nn.functional.log_softmax(inputs, dim=1, _stacklevel=5) kl = -log_probs.mean(dim=1) xent = torch.nn.functional.nll_loss(log_probs, targets, reduction="none") loss = (1...
# pylint: disable=missing-module-docstring # # Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >. # # This file is part of < https://github.com/UsergeTeam/Userge > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/uaudith/Userge/blob/master/LIC...
import re import logging from typing import Set, Tuple, List SENT_RE = re.compile(r'[^\.?!…]+[\.?!…]*["»“ ]*') _LAST_WORD = re.compile(r'(?:\b|\d)([a-zа-я]+)\.$', re.IGNORECASE) _FIRST_WORD = re.compile(r'^\W*(\w+)') _ENDS_WITH_ONE_LETTER_LAT_AND_DOT = re.compile(r'(\d|\W|\b)([a-zA-Z])\.$') _HAS_DOT_INSIDE = re.compi...
#!/usr/bin/env python3 # areq.py """Asynchronously get links embedded in multiple pages' HMTL.""" import copy import asyncio import logging import re import sys from typing import IO import urllib.error import urllib.parse import os import aiofiles import aiohttp from aiohttp import ClientSession from crawly.identif...
""" 733. Flood Fill Easy An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and newColor. You should perform a flood fill on the image starting from the pixel image[sr][sc]. To perform a flood fill, consider the...
from __future__ import print_function # import ## batteries from itertools import product,cycle ## 3rd party import numpy as np ## package from pyTecanFluent import Utils from pyTecanFluent import Fluent from pyTecanFluent import Labware # functions def pip_Tn5_mastermix(df_map, gwl, mm_volume, ...
import re import string from flask import ( Blueprint, request, render_template, redirect, url_for, abort, flash, current_app ) from flask.ext.wtf import Form from flask.ext.login import current_user from wtforms import TextField, IntegerField, FloatField, validators from template_maker.users.models import Us...
# -*- coding: utf-8 -*- from email.header import Header import commonware.log from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from ffclub.settings import DEFAULT_FROM_EMAIL, SITE_URL, DEFAULT_REPLY_EMAIL, DEFAULT_NOTIFY_EMAIL, BEDROCK_PATH, FFCLUB_URL from ffclub....
#!/usr/bin/env python3 ''' This script runs rllab or gym environments. To run RLLAB, use the format rllab.<env_name> as env name, otherwise gym will be used. ''' # Common imports import sys, re, os, time, logging from collections import defaultdict # Framework imports import gym import tensorflow as tf import ...
""" side package to store some useful functions for more complex integers manipulation like factorization, check if two numbers are coprimes, get fast GCD and LCM of two or more integers ecc """ # Imports from itertools import chain, count from math import gcd as math_gcd from functools import reduce from fractions i...
import bpy from sklearn.cluster import DBSCAN, OPTICS bl_info = { "name": "Clustering", "author": "<NAME>, <NAME> (Wakeone)", "version": (0, 1), "blender": (2, 80, 0), "description": "Runs a clustering algorithm on the selected objects.", "category": "Object", } clustering_algorithm = [ 'D...
""" Admin interface implementation step-related models """ from itertools import chain, count from typing import Optional from django import forms from django.contrib import admin from django.db import IntegrityError from django.db.models import OuterRef, Subquery from ..utils.admin_utils import StepInCollectionFilte...
import sys import numpy import scipy.ndimage.measurements from skimage.morphology import watershed from clarity.Analysis.Voxelization import voxelizePixel from clarity.ImageProcessing.StackProcessing import writeSubStack from clarity.Utils.Timer import Timer from clarity.Utils.ParameterTools import getParameter, writeP...
# coding: utf-8 # In[8]: ''' MSCOCO14 dataset classes Made using voc0712.py as reference. ''' # In[1]: import os import os.path import sys import torch import torch.utils.data as data import torchvision.transforms as transforms from PIL import Image, ImageDraw, ImageFont import cv2 import numpy as np import jso...
from account.serializer import UserSerializer from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.views import ( LoginView, LogoutView, PasswordChangeView, PasswordChangeDoneView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, Pa...
import os import sys import math import time import argparse import torch import numpy as np from tqdm import tqdm from parameters import set_args from data_utils import load_data from utils import compute_micro_f1, get_GNN, custom_loss_function, get_version, get_auxiliary, seed #%% 日志格式设置,全局变量初始化 version = None epsilo...
#!/usr/bin/env python3 # Generate and save data for testing. Run this from the tests directory # before running the unit tests. import numpy as np import os from aistats2019_ij_paper import regression_lib as reg_lib from aistats2019_ij_paper import regression_mixture_lib as rm_lib from aistats2019_ij_paper import s...
############################################################ # -*- coding: utf-8 -*- # # # # # # # # # ## ## # ## # # # # # # # # # # # # # # # ## # ## ## ###### # # # # # # # # # Python-based Tool for interaction with the 10micron mounts # GUI with PyQT5 fo...
import curses import math import webbrowser from .api.client import Client rows_in_entry = 5 class SelectionWindow: def __init__(self, data, stdscr, window): client = Client() self.window_box = window self.stdscr = stdscr self.rows, self.cols = stdscr.getmaxyx() extendedDa...
import json import tweepy import datetime, time import MySQLdb from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener consumer_key = '####' consumer_secret = '####' access_token = '####' access_secret = '####' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_...
"""Explore a directory and print its structure as graphviz graph.""" import os import sys import pygraphviz as pgv from nodes import Node from PIL import ImageFont EXCLUDE = ['.git', '__pycache__'] SHARED_ATTRIBUTES = ", style=filled, colorscheme=ylgnbu" GRAPHVIZ_DPI = 60. FONT_SIZE = 14 class FileNode(Node): ...
# !/usr/bin/env python # coding: utf-8 import os import re import sys import json import string import logging from random import sample from batchcompute import Client, ClientError from batchcompute import CN_BEIJING from batchcompute.resources import ( Configs, Networks, VPC, AutoCluster, J...
import torch from src.data.utils import TextEncoder import src.data.data as data import src.models.models as models from src.evaluate.sampler import BeamSampler, GreedySampler, TopKSampler from config import settings import utils.utils as utils def load_model_file(model_file): model_stuff = data.load_checkpoin...