text
stringlengths
3.07k
12.6k
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import sympy.physics.units as spu from scipy import constants as sc from sympy.matrices import eye from sympy.physics.matrices import msigma from sympy.physics.quantum import TensorProduct as kron from types import SimpleName...
""" Ideas implemented in this script comes from here: https://www.youtube.com/watch?v=SsnWM1xWDu4. This script should be run after executing the `notebook/Generate_Pseudo.ipynb` notebook. Also, take note of the `pseudo_df` variable in the `get_dataloader()` function. """ import argparse import numpy as np import album...
from torchvision.datasets import ImageFolder from base.torchvision_dataset import TorchvisionDataset from PIL.ImageFilter import GaussianBlur import torch import torchvision.transforms as transforms import random class ImageNet22K_Dataset(TorchvisionDataset): def __init__(self, root: str, data_augmentation: boo...
"""Define sparse embedding and optimizer.""" from .. import backend as F from .. import utils from .dist_tensor import DistTensor class DistEmbedding: '''Distributed embeddings. DGL provides a distributed embedding to support models that require learnable embeddings. DGL's distributed embeddings are main...
import logging import json from common import settings, fields, fields as f, taxonomy from common.main_elastic_client import elastic_client from common.elastic_connection_with_retries import elastic_search_with_retry from common.taxonomy import tax_type, annons_key_to_jobtech_taxonomy_key log = logging.getLogger(__nam...
import random import sqlite3 from dataclasses import dataclass from pathlib import Path from typing import List, Type, Union from loguru import logger from lorem_text import lorem random.seed(420) # Source: https://github.com/smashew/NameDatabases this_folder = Path(__file__).parent with (this_folder / 'first_names....
import pytest from ..field import Field from ..interface import Interface from ..objecttype import ObjectType from ..scalars import String from ..schema import Schema from ..structures import NonNull from ..unmountedtype import UnmountedType class MyType(Interface): pass class Container(ObjectType): field1...
import glob import os import pathlib import re import matplotlib.pyplot as plt from matplotlib import colors import numpy as np # include the path here to a folder full of rasters that QGIS can load path_to_rasters = "." # folder for output sections as PNGs path_for_outputs = "." def parse_raster_layer_depths(rfi...
# coding: utf-8 # pywebaudioplayer for Jupyter Notebook. Loads external javascript libraries with RequireJS and uses built-in Bootstrap, jQuery and font-awesome. from .core import Image, _id, _js, _figure_margins, _write_samples, waveform_playlist def wavesurfer(audio_path=None, controls={}, display={}, behaviour={}...
import torch import numpy as np from lib.utils.misc import NestedTensor import matplotlib.pyplot as plt import os class Preprocessor(object): def __init__(self): self.mean = torch.tensor([0.485, 0.456, 0.406]).view((1, 3, 1, 1)).cuda() self.std = torch.tensor([0.229, 0.224, 0.225]).view((1, 3, 1, 1...
#!/usr/bin/env python ## # File: ConfigInfoDataSetExec.py # Author: jdw # Date: 23-Aug-2016 # Version: 0.001 # # Updates: ## """ Execuction wrapper for data set site alternate location mapping cache. """ __docformat__ = "restructuredtext en" __author__ = "<NAME>" __email__ = "<EMAIL>" __license__ = "Creative Co...
""" This is the base class for zones. Every zone in the game will inherit from this class. """ from models.quests.loader import load_quests from models.creatures.loader import load_monsters, load_npcs class Zone: # the _map that shows us where we can go from our current subzone zone_map = {} # type: dict - k...
from flakon import JsonBlueprint from flask import request from kbsbot.compose_engine.compose_utils import * from kbsbot.compose_engine.services import * import logging comp = JsonBlueprint('comp', __name__) TRAINING_TOOL = "http://example.com/train" logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s...
# <NAME>, <EMAIL> # ITP 115, Fall 2020 # Assignment 9 # Description: # this program creates a fake user's music library and allows them to edit it like they normally would # importing necessary modules import MusicLibraryHelper import random import string # display the menu with basic print statement def displayMenu(...
# <NAME> # July 27, 2020 # This file contains utility functions for parsing CSV and TXT files import json import os from typing import Any, Dict, List, Tuple def file_parser(file_path: str, key_col: int, key_type: Any, val_col: int, val_type: Any, delimiter: str=',', rows_to_skip: int=0) -> Dict[Any, ...
import numpy import pytest def test_sum_int_2d_trivial(): from pymdspan import sum_int_2d a = numpy.array([[1, 2, 3, 4]]) assert sum_int_2d(a) == 10 a = numpy.array([[1], [2], [3], [4]]) assert sum_int_2d(a) == 10 a = numpy.array...
from abc import ABCMeta, abstractmethod from datetime import date from typing import List, Union #################### ### EXCEPTIONS ### #################### class FilterLookupError(LookupError): """ When a developer is filtering by a lookup not supported in sql API. """ class FieldTypeNotSupportedError(Excep...
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to ...
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
import numpy as np from utils import * def cosine_similarity(u, v): """ Cosine similarity reflects the degree of similariy between u and v Arguments: u -- a word vector of shape (n,) v -- a word vector of shape (n,) Returns: cosine_similarity -- the cosine simila...
######## # Copyright (c) 2013 GigaSpaces Technologies Ltd. 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...
#!/usr/bin/python # # Copyright (c) 2019 <NAME> (@yungezz) # # 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 ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': [...
#!/usr/bin/python # Classification (U) """Program: blackbox_test.py Description: Blackbox testing of package_admin.py program. Usage: test/blackbox/package_admin/blackbox_test.py Arguments: """ # Libraries and Global Variables # Standard import os import sys import datetime import shutil im...
# Copyright 2019 ZTE corporation. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ This is a sample for Adlik_serving prediction """ import argparse import os from PIL import Image from adlik_serving import PredictContext, model_config_pb2, tensor_dtype_to_np_dtype import numpy as np FLAGS = None de...
import logging import numpy as np MARK_PAD = "<PAD>" MARK_UNK = "<UNK>" MARK_EOS = "<EOS>" MARK_GO = "<GO>" MARKS = [MARK_PAD, MARK_UNK, MARK_EOS, MARK_GO] ID_PAD = 0 ID_UNK = 1 ID_EOS = 2 ID_GO = 3 def load_dict(dict_path, max_vocab=None): logging.info("Try load dict from {}.".format(dict_path)) try: ...
from typing import Optional import nextcord from nextcord import Embed from nextcord.ext import menus from nextcord.ext.commands import Cog, command class buildHelpmenu(menus.ListPageSource): def __init__(self, data, thumbnail, botname): super().__init__(data, per_page=5) self.thumbnail = thumbna...
import pandas as pd import numpy as np from matplotlib import pyplot as plt import seaborn as sns from sklearn.base import BaseEstimator, TransformerMixin from sklearn import metrics from mpl_toolkits import mplot3d sns.set() def argmedian(arr): """return index of median in an array""" return np.argpartiti...
# -*- coding: utf-8 -*- import datetime from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase import pdfmetrics from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch from tqdm import...
# Common definitions for 'loc2yaml' and 'loctrans' tools # https://github.com/sergeuz/locode # # This file is subject to the terms and conditions defined in LICENSE file, # which is part of this source code package. import yaml, shutil, os, sys from collections import OrderedDict # Placeholder region code used when p...
# # patent_lim: Linguistically informed masking for representation learning in the patent domain # # Copyright (c) Siemens AG, 2020 # # SPDX-License-Identifier: Apache-2.0 # import pandas as pd import os import pickle from definitions import ROOT_DIR from ling_ana.ipc_cpc_class_occurences import get_top_n_subclasses ...
import os import sys root_path = "/".join(os.path.realpath(__file__).split("/")[:-2]) print(f'root_path is {root_path}') if root_path not in sys.path: sys.path.insert(0, root_path) import mmcv import os.path as osp data_root = 'data/FakeBookpages/' train_img_root = osp.join(data_root, 'train/img/') train_ann_ro...
#!/usr/bin/python """ Copyright (c) 2017-2018 Starwolf Ltd and <NAME>. 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://www.apache.org/licenses/LICENSE-2.0 or in the "license"...
import copy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class Encoder_Decoder(nn.Module): def __init__(self, state_dim, action_dim): super(Encoder_Decoder, self).__init__() self.e1 = nn.Linear(state...
import pandas as pd from ..spec.interval import * class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Padding(metaclass=Singl...
import six from .models import Model, BufferModel from .fields import DateField, StringField from .engines import MergeTree from .utils import escape from six.moves import zip from six import iteritems import logging logger = logging.getLogger('migrations') class Operation(object): ''' Base class for migra...
from discord.ext.commands import Bot, Cog, Context from discord import Message, Member, Game, Reaction, Embed from discord.ext.commands.errors import * from discord.errors import * from discord.utils import get, find from os.path import basename from random import randint from datetime import datetime, timedel...
from faktura import app from flask import request, render_template, send_file, redirect, make_response, session from faktura.models import db, Customer, Invoice, InvoiceRow, TemplateVariable from decimal import Decimal from faktura.breadcrumbs import breadcrumbs from datetime import datetime import pdfkit import os fro...
import pickle import os import numpy as np import nibabel as nib from utils import Parser import time args = Parser() patch_shapes = [ (22, 22, 22), (25, 25, 25), (28, 28, 28) ] modalities = ('flair', 't1ce', 't1', 't2') def nib_load(file_name): if not os.path.exists(file_name):...
import click import sys import logging from google.protobuf.symbol_database import Default from dacirco.grpc_service.server import run_server from dacirco.scheduler.dacirco_dataclasses import ( VMParameters, MinIoParameters, RunnerType, SchedulerParameters, AlgorithmType, ) def log_config(verbose...
from pddlgym.parser import PDDLDomainParser, PDDLProblemParser from pddlgym.structs import Predicate, Literal, Type, Not, Anti, LiteralConjunction, State from pddlgym.spaces import LiteralSpace from pddlgym.core import PDDLEnv import os import time def test_hierarchical_spaces(): dir_path = os.path.dirname(os.pa...
""" kblayouttool This is a utility program for working with Windows keyboard layouts. It can function as a sort of command-line replacement for the Windows language bar. """ # pylint: disable=E0401 # This file imports Win32-only modules. import argparse import logging import time import win32api import win32con im...
# Copyright 2012 VPAC, http://www.vpac.org # Copyright 2013-2016 <NAME> <<EMAIL>> # # This file is part of Patchman. # # Patchman is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 only. # # Patchman is...
import argparse import json import logging import os from typing import Dict from xml.etree import ElementTree import pandas as pd import tensorflow as tf import cvdata.common from cvdata.utils import matching_ids # ------------------------------------------------------------------------------ # set up a basic, glo...
from datetime import datetime import json __author__ = 'mstipanov' class DateFormatIso8601(object): @classmethod def strftime(cls, d): s = "%04d-%02d-%02dT%02d:%02d:%02d.%03d" % ( d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond / 1000) tzinfo = d.tzinfo ...
#!/usr/bin/env python2.7 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "...
#!/usr/bin/env python # -*- coding: utf8 -*- # ==================== # Set-up # ==================== # Import required modules from amed.functions import * # Set locale to assist with sorting locale.setlocale(locale.LC_ALL, '') # Set threshold for garbage collection (helps prevent the program run ...
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015, 2016, 2017 <NAME> # Copyright (C) 2017 <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Bioindustrial-Park: BioSTEAM's Premier Biorefinery Models and Results # Copyright (C) 2022-, <NAME> <<EMAIL>> # # Part of this module is based on the oilcane biorefinery: # https://github.com/BioSTEAMDevelopmentGroup/Bioindustrial-Park/tree/master/BioSTEAM%202.x.x/bioref...
#!/usr/bin/env python # -*- coding: utf-8 -*- # This code is in the public domain, so as to serve as a template for # real-world plugins. # or, at the choice of the licensee, # Copyright 2019 <NAME> # SPDX-License-Identifier: MIT # Metadata parsed by GDAL C++ code at driver pre-loading, starting with '# gdal: ' # Requ...
import webbrowser import json import boto3 import io from io import BytesIO import sys from pprint import pprint import pdf2image import os import csv import shutil def extract_jpg(file_name,csv_output_file): table_csv = get_table_csv_results(file_name) with open(csv_output_file, "w") as fout: fout.wri...
#!/usr/bin/env python3 # ------------------------------------------------------------------- # @copyright 2017 DennyZhang.com # Licensed under MIT # https://www.dennyzhang.com/wp-content/mit_license.txt # # File : monitor-docker-slack.py # Author : Denny <https://www.dennyzhang.com/contact> # Description : # -- # Cre...
#!/usr/bin/env python """ Created on 26/01/21 Author: <NAME> Emails: <EMAIL> - <EMAIL> Description: this file extracts image(s) annotations (both visual and textual) from Flickr30k. """ import xml.etree.ElementTree as ET import argparse import model_code.utils as utils import numpy as np def Flickr30k_annotations(fli...
"""Реализация базовых команд для асинхронного запроса к базе данных Postgres через Django ORM. """ from ast import Sub from genericpath import exists import os import sys from pathlib import Path from typing import List, Optional, Union from asgiref.sync import sync_to_async ROOT_DIR = Path(__file__).parents[3] MODE...
import sys import numpy as np import rospy from sensor_msgs.msg import JointState import kinematics as kin from std_msgs.msg import Empty,Float64 class ArmController(): def __init__(self): # Topics to control arm joints self.goal_topic = '/goal_dynamixel_position' self.joint_state_topic = ...
import numpy as np import os import cv2 import glob import shutil import pytesseract import re import time import argparse from statistics import mode from pdf2image import convert_from_path import imutils import tempfile from PIL import Image output_dir = "D:\\test" def apply_threshold(img, argument...
# -*- coding:utf-8 -*- import os import requests import hashlib import time import copy import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # API_URL LIKIE_URL = "http://c.tieba.baidu.com/c/f/forum/like" TBS_URL = "http://tieb...
from Tkinter import Tk, StringVar import tkMessageBox import ttk from Tkinter import * import os ## THIS PYTHON CODE IS WRITTEN IN PYTHON 2.7.12, PLEASE CONVERT IT TO PYTHON 3 USING ONLINE CONVERTER FIRST IF YOU'RE ## USING PYTHON 3.x BECAUSE A LOT OF LIBRARY HAS BEEN CHANGED SINCE PYTHON 3 CAME OUT. THANK YOU. -warne...
import requests import os from openpyxl import Workbook from openpyxl import load_workbook import json import constant from openpyxl.styles import Side, Border, PatternFill, Font, Alignment import datetime def get_giteepkg(headers,token,owner): i = 1 pkglist = [] while True: pkg_params = { ...
from ctypes import * """ Nintendo Entertainment System (NES) loader module ------------------------------------------------------ Copyright 2006, <NAME> (<EMAIL>) """ # ---------------------------------------------------------------------- # # general NES info: # RAM_START_ADDRESS = 0x0 RAM_SIZE...
from __future__ import absolute_import import os.path import os import re import textwrap try: import urlparse except ImportError: import urllib.parse as urlparse from django.conf import settings from django.core.exceptions import ImproperlyConfigured try: from django.contrib.staticfiles.storage import s...
import json import re from collections import defaultdict import click from eth_utils import encode_hex, function_abi_to_4byte_selector from web3.utils.abi import abi_to_signature from .constants import TYPE_MAPPINGS, Mapping from .test_data import compile_contract_test def generate_extern_c(data): return ''' ...
import numpy as np import math from mgcpy.independence_tests.utils.transform_matrices import \ transform_matrices import scipy.io import os def power(independence_test, sample_generator, num_samples=100, num_dimensions=1, theta=0, noise=0.0, repeats=1000, alpha=.05, simulation_type=''): ''' Estimate power...
""" ftr_lexical ----------- Implements lexical features (string similarities, IDF scores, ...). @author: <NAME> @author: <NAME> """ from __future__ import division import argparse # import jellyfish as jf from math import sqrt from statistics import mean from scipy import spatial import numpy as np from nordlys.con...
import json from enum import Enum, auto from collections import Counter def read_json(file_path): with open(file_path, encoding='UTF8') as json_file: json_data = json.load(json_file) return json_data def write_json(data, file_path): with open(file_path, 'w') as cur_json: json.dump(da...
import PySide as ps import pyqtgraph as pg import collections import time, datetime import numpy as np import logging as log import threading class WatchVariable: def __init__(self, value_buffer_size=100, name='To Be Filled by <NAME>.', address=None): self.buf_size = value_buffer_size self.name =...
#! /usr/bin/env python2.7 """ Module: test_dev_PBS_1675.py Package: pbs.prescription.tests Description: **Dangerous** testing This test suite must only be conducted on a pre-existing test database. Difficulties forming a temporary database have forced me to this. """ from __future__ import print_function, division, un...
#!/usr/bin/python3 import re import sys import os import subprocess from dataclasses import dataclass, field # <REGEX DEFINITIONS> # identifying the start, end, and properties of code-blocks block_start = re.compile("^```(" \ "python|lua|js|javascript|bash|zsh|brainfuck" \ "|c|rust|cpp|c\+\+|go|java|...
import numpy as np from abc import ABCMeta, abstractmethod class loss(metaclass=ABCMeta): ''' The abstract base class for loss function. For each loss, the gradient should be specified. ''' def obj(self,pred,true): pass def gradient(self,pred,true): pass class ms...
FROM_BASE64 = { 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25, 'a': 26, 'b': 27, 'c': 28, 'd': 29, 'e': 30, 'f': ...
import numpy as np import multiprocessing as mp import imageio import scipy.ndimage import skimage.color import sklearn.cluster import scipy.spatial.distance import os,time import matplotlib.pyplot as plt import util import random def extract_filter_responses(image): ''' Extracts the filter responses f...
""" --- Day 21: Fractal Art --- You find a program trying to generate some art. It uses a strange process that involves repeatedly enhancing the detail of an image through a set of rules. The image consists of a two-dimensional square grid of pixels that are either on (#) or off (.). The program always begins with th...
import os import numpy as np import pandas as pd def _apply_stop_names(skim, result_file, scenario='build', mode='fg', period='pk'): root_skim_path = _root_skim_path(result_file, scenario, mode, '', period) dtypes = { 'stop_no': np.int16, 'orig_stop_id': str, 'stop_name': str } ...
from .Base import Stylable from .Errors import GraphJsonFormatError from .Node import Node, NodeSet, MutableNodeSet from .Edge import Edge, EdgeSet, MutableEdgeSet, NodeTuple, EdgeIDTuple import json from typing import Iterable, Union, Optional, Mapping from enum import Enum class GraphLayout(Enum): dagre = {'na...
#!/usr/bin/env python import argparse import os import sys import copy import random import numpy as np from rdkit import Chem from rdkit import DataStructs from rdkit.Chem import rdFMCS, AllChem, rdShapeHelpers, rdmolops, rdForceFieldHelpers from rdkit.Chem.Fingerprints import FingerprintMols def file_path(string...
"""file serverwidget.py provide base class for developing widget job object and widgetContainer for connecting to router to use, extend BaseWidget and override run ``` import serverwidget as sw class MyServerWidget(sw.BaseWidget): def run(self): pass if __name__=="__main__": sw.connect(u'ws:127.0.0...
from distutils.version import StrictVersion from rocker.restclient import Request, SocketError import getopt import json import os import pkg_resources import sys MIN_LABELS_VERSION = "1.17" # Source: https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py # TODO Maybe use a libra...
import os import numpy as np import seaborn as sns import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # needed to plot 3-D surfaces import matplotlib.pyplot as plt import seaborn as sns def plotData(x, y): """ Plots the data points x and y into a new figure. Plots the data points and ...
#=================================== # <NAME> # # <EMAIL> # # University of Texas at Austin # #=================================== # Generate tinker prm file for new atomtype txyz ''' python matchPRM.py template.prm template.txyz dealwith.txyz energyterm''' import os,sys,subproce...
""" Provides useful functions to scripts to fetch and return information related to accounts, transactions, and clients. Also contains functions that can process various requests such as changing account balances or creating objects. This is not a complete set of functions as others will be added in the future. """ ...
import os from pytest import raises from sandhill.utils import generic from sandhill import app def test_is_none(): # Test dictionary path assert generic.ifnone(None, "key", "default") == "default" assert generic.ifnone("non-dict", "key", "default") == "default" assert generic.ifnone(1, "key", "default...
import argparse import shutil import subprocess from pathlib import Path from typing import List, Optional, Union import matplotlib import matplotlib.figure import matplotlib.pyplot from matplotlib.backend_bases import LocationEvent from matplotlib.figure import Figure from mlxtk.log import get_logger from mlxtk.plot...
import pygame from jumper.entity import Entity from jumper.game_helper import show_text from jumper.entities.ui.name_input_frame import NameInputFrame from jumper.timer import parse_time from jumper.db.database import Database from jumper.resource import R from math import copysign WHITE = (255, 255, 255) BLACK = (0, ...
""" Combine multiple popular python security tools and generate reports or output into different formats Plugins (these require the plugin executable in the system path. e.g. bandit requires bandit to be in the system path...) - bandit - safety - dodgy - dlint - semgrep Formats - ansi (for terminal) - json - markdo...
#!/usr/bin/env python3 import itertools import re import sys import urllib.request import html FILTER_BASICS = True basics = ['Plains', 'Island', 'Swamp', 'Mountain', 'Forest'] def usage(): print("Usage:") def print_price_list(price_list): t = sorted(price_list, key=lambda val: val[3]) print('-' * 8...
#!/usr/bin/env python import logging import datetime import email import ssl import hollywood.actor import hollywood.net.socks class BadRequestError(Exception): """Unable to properly parse the request.""" pass class Request(object): """ Attributes: method: GET, POST pa...
import time import datetime import re import smtplib import ssl from imbox import Imbox from requests_html import HTMLSession # e-mail info for the bot sender_email = "<EMAIL>" receiver_email = "<EMAIL>" # For SSL port = 465 # Create a secure SSL context context = ssl.create_default_context() password = '' # func...
# ================================================================ # Created by <NAME> (https://github.com/Algomorph). # Copyright (c) 2021 <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 Lic...
# encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> """ import argparse import glob import os import cv2 import numpy as np import pycuda.driver as cuda import tensorrt as trt import tqdm TRT_LOGGER = trt.Logger() def get_parser(): parser = argparse.ArgumentParser(description="trt model inference") pa...
# Copyright 2000-2020 JetBrains s.r.o. # Use of this source code is governed by the Apache 2.0 license that can be found # in the LICENSE file. """Run config generation stuff""" import configparser import io from os import mkdir, stat, chmod from os.path import join, isdir from shlex import quote from typing impor...
""" Models module """ import datetime from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ from site_app.models import ModelTimestampMixin class Location(ModelTimestampMixin, models.Model): """Location""" class Meta: ...
import operator from collections import Counter, defaultdict from telegram.ext import CallbackContext, CommandHandler, ConversationHandler from telegram.update import Update from autonomia.core import bot_handler CHOICES, VOTING = range(2) class AlreadyVotedError(Exception): pass class Poll: def __init__...
# https://deeplearningcourses.com/c/unsupervised-machine-learning-hidden-markov-models-in-python # https://udemy.com/unsupervised-machine-learning-hidden-markov-models-in-python # http://lazyprogrammer.me # Continuous-observation HMM in Theano using gradient descent. from __future__ import print_function, division from...
###################################################### ### Code builds a simple, one-layer ### ### Uses: justifications_clean_text_ohe.csv ### ###### Collapses justifications to 6 categories. ### ###### Stems and tokenizes words ### ###### Trains a basic neural network ...
""" Removes old versions of Lambda functions. """ from __future__ import print_function import argparse import boto3 try: import queue except ImportError: import Queue as queue from boto3.session import Session from botocore.exceptions import ClientError LATEST = '$LATEST' def list_available_lambda_regions(...
from nextcord.ext import commands import nextcordSuperUtils from nextcordSuperUtils import LavalinkMusicManager import nextcord import time client_id = "" client_secret = "" bot = commands.Bot(command_prefix="-", intents=nextcord.Intents.all()) # MusicManager = LavalinkMusicManager(bot, spotify_support=False) Musi...
#!/usr/bin/env python3 # Copyright 2018 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse from datetime import datetime import re import subprocess import sys from pathlib import Path import logging from mu...
import numpy as np import cv2 import os import matplotlib.pyplot as plt from scipy.stats import multivariate_normal from sklearn.datasets import make_spd_matrix import argparse import colors class GMM_EM: def __init__(self, data, clusters, color="test", max_itr=400, eps=1e-8): self.train_data = data ...
from collections import defaultdict import re def read_input(): f = open("input_day20.txt") #f = open("example02.txt") return [l.strip('\n') for l in f] def horizontal_portals(inp): portals = defaultdict(list) for (y,_) in enumerate(inp): for x in range(len(inp[y]) - 2): if inp...
from django.http import HttpResponse, JsonResponse from django.shortcuts import render from django.conf import settings from django.contrib import messages from django.utils.html import format_html from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls impo...
""" vmagnify_picture.py : class for the processing of the picture. """ from datetime import datetime from multiprocessing import Lock import os import threading from typing import List import cv2 from cv2 import dnn_superres import requests from vmagnify.vmagnify import VMagnify class PictureData: """ PictureData...