content
stringlengths
5
1.05M
import os import torch import numpy as np from sentence_transformers import SentenceTransformer from experiment.qa.evaluation import BasicQAEvaluation class QAEvaluationSBert(BasicQAEvaluation): def __init__(self, config, config_global, logger): super(QAEvaluationSBert, self).__init__(config, config_glo...
"""Test Home Assistant ulid util methods.""" import uuid import homeassistant.util.ulid as ulid_util async def test_ulid_util_uuid_hex(): """Verify we can generate a ulid.""" assert len(ulid_util.ulid_hex()) == 32 assert uuid.UUID(ulid_util.ulid_hex())
from flask import Flask, render_template, request, Response from Models import db, SensorData, CustomSensor from flask.json import jsonify from Arduino import serial_port from threading import Thread from Helpers import search_sensor from Constants import DataTypes import os.path db_path = os.path.join('sqlite://', o...
#basic program of finding the SECOND LARGEST VALUE among the given list of value #finding the RUNNER UP in other words #used map(),split(),sorted() #the sorted()function here creates a new set returns a sorted list of the specified iterable object. if __name__ == '__main__': #getting the number of scores you are g...
from collections import namedtuple ButtonOptions = namedtuple('ButtonOptions', ['activebackground', 'activeforeground', 'anchor', 'background', 'bitmap', 'borderwidth', 'disabledforeground', 'font', 'foreground', 'highlightbackground', 'highlightcolor', ...
"""Constants for the Thruk Livestatus sensor integration.""" # This is the internal name of the integration, it should also match the directory # name for the integration. DOMAIN = "thruk_livestatus" HOST_COUNT = "Host count" NUM_SERVICES_CRIT = "Services CRITICAL" NUM_SERVICES_WARN = "Services WARNING" NUM_SERVICES_...
import decoder inp_fn = raw_input("Enter the file name to decode:") sp_fn_a = inp_fn.split('.') sp_fn_b = sp_fn_a[0].split('_') inp_fs = open(inp_fn,"r") out_fs = open("decoded_"+sp_fn_b[1]+'.'+sp_fn_b[2],"wb+") enc_ln = int(inp_fs.readline()) st_to_dec = inp_fs.readline() while st_to_dec!='': out_fs.write(decoder....
"""Plants tests"""
import time, sys, random from pygame import mixer from PyQt5.QtWidgets import QDialog, QApplication from PyQt5 import QtWidgets, QtCore from src.ui.controlPenalUI import Ui_controlPenal from src.songScreen import picWindow class controlPenal(QDialog): def __init__(self): super().__init__() ...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
import sys import argparse import json import logging import os from TrainFace import TrainFace from InferFace import InferFace if __name__ == "__main__": # Read the input information by the user on the command line parser = argparse.ArgumentParser() parser.add_argument("--config_file", help="co...
class Solution(object): def defangIPaddr(self, address): """ :type address: str :rtype: str """ return address.replace(".", "[.]") if __name__ == '__main__': address = "0.0.0.0" obj = Solution() obj.defangIPaddr(address)
#!/usr/bin/env python # coding:utf-8 import os import sys current_path = os.path.dirname(os.path.abspath(__file__)) helper_path = os.path.join(current_path, os.pardir, os.pardir, os.pardir, 'data', 'launcher', 'helper') if __name__ == "__main__": python_path = os.path.abspath( os.path.join(current_path, os.pardi...
#!/usr/bin/python3 import argparse import getpass import glob import os import socket import subprocess import time import sys script_description = ( "Prepare current system for migrate attack, output XSS payload\n" "Requires to be run with sudo/root privs for writing files to system dirs" ) def is_port_op...
import typing from core import scriptercore class LinuxDisplayPwnedMsgBox(scriptercore.Scripter): AUTHOR: str = "Danakane" def __init__(self): super(LinuxDisplayPwnedMsgBox, self).__init__() self.__title__: str = "" self.__text__: str = "" self.customize({"title": "The title...
# -*- coding: utf-8 -*- """ Пример распаковки/упаковки контейнеров (cf/epf/ert) при помощи onec_dtools Функционал аналогичен C++ версии v8unpack Copyright (c) 2016 infactum """ import argparse import sys from onec_dtools import extract, build def main(): parser = argparse.ArgumentParser() group = parser.ad...
__author__ = "MetaCarta" __copyright__ = "Copyright (c) 2006-2008 MetaCarta" __license__ = "Clear BSD" __version__ = "$Id: VersionedPostGIS.py 496 2008-05-18 13:01:13Z crschmidt $" from FeatureServer.DataSource import DataSource from vectorformats.Feature import Feature from FeatureServer.DataSource.PostGIS import P...
import requests as reqs import base64 import logging import re import json # 调用淘宝识图请求接口,获取商品源和标签 def taobao_pic_recognize(pic_dir,pic_name,cookie): # with open(pic_dir+'/'+pic_name, "rb") as f: # # b64encode:编码,b64decode: 解码 # base64_data = base64.b64encode(f.read()) imagefile={ "file": (pic_n...
from flask import Flask, request, redirect from twilio.twiml.messaging_response import MessagingResponse import pandas as pd import datetime import pytz # the below import is only needed for forwarding the sms, in case the client sends KONTAKT from twilio.rest import Client account_sid = '###################...
from src.bert_classifier.model import Model from src.bert_classifier.fit import fit
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from telegram.ext import Updater, MessageHandler, Filters import traceback as tb import json import random import threading START_MESSAGE = (''' Loop message in chat / group / channel. add - /add message: add message to loop. list - /list: list message inside the loop....
# Copyright 2019 Google LLC. 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 applicable law or a...
from setuptools import setup setup( name="backbones", version="0.1", description="Common neural network architectures implemented in PyTorch.", url="https://github.com/bentaculum/backbones", author="Benjamin Gallusser", author_email="benjamin.gallusser@epfl.ch", license="MIT", install_r...
from typing import List, Tuple, Callable, Optional import numpy as np import tweedie from gluonts.model.forecast import SampleForecast, QuantileForecast from scipy.optimize import fmin_l_bfgs_b from scipy.special import gammaln, factorial, psi from scipy.stats import norm, beta, gamma, nbinom, poisson from sklearn.pre...
import argparse import os import time from keystoneauth1 import loading from keystoneauth1 import session from heatclient import client _TERMINAL = [ 'CREATE_FAILED', 'CREATE_COMPLETE', 'UPDATE_FAILED', 'UPDATE_COMPLETE' ] _INTERVAL = 20 def get_session(): """Get a keystone session :returns...
from pydantic import BaseModel #fastapi接口的数据模型 class User(BaseModel): first_name: str last_name: str age: int class Config: orm_mode = True
import sys import getpass from mlflow.tracking.context.abstract_context import RunContextProvider from mlflow.entities import SourceType from mlflow.utils.mlflow_tags import ( MLFLOW_USER, MLFLOW_SOURCE_TYPE, MLFLOW_SOURCE_NAME, ) _DEFAULT_USER = "unknown" def _get_user(): """Get the current comput...
import numpy as np import torch from torch.utils.data import Dataset from torch.utils.data.dataloader import default_collate from fairseq.data.fairseq_dataset import FairseqDataset def sine(phase, amplitude, x): return np.sin(x + phase) * amplitude class SineDataset(Dataset): def __init__(self, split, phas...
import socket server = "localhost" #settings channel = "#domino" botnick = "firestorck_bot" print("Server : ", server) print("Channel : ", channel) print("Name : ", botnick) irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket print ("connecting to: "+server) irc.connect((server, 6667)) ...
import numpy as np import copy as cp DIRECTIONS = [np.array((0, 1)), np.array((1, 0)), np.array((1, 1)), np.array((0, -1)), np.array((-1, 0)), np.array((-1, -1)), np.array((1, -1)), np.array((-1, 1))] class State: def __init__(self, grid=None, previous_skip=False, side=2, master_side=2): if...
import os import glob import shutil import tempfile import numpy as np import common import features import folds from audio_toolbox import ffmpeg, sox from constants import * def normalize(input_file): temp_dir = tempfile.mkdtemp() transcoded_file = os.path.join(temp_dir, 'transcoded.flac') ffmpeg.tra...
import django_describer.actions import django_describer.datatypes import django_describer.permissions import django_describer.describers import django_describer.utils import django_describer.adapters name = "django_describer"
from ctypes import * from .jenv import * from . import Object from . import ClassUtils from . import Executable from . import String from . import Modifier class Method(Executable.Executable, Modifier.Modifier): _isInit = None _Class = None _getName = None _getReturnType = None _count = 0 def ...
"""Tests for the ResourceTracker class""" import errno import gc import os import pytest import re import signal import subprocess import sys import time import warnings import weakref from loky import ProcessPoolExecutor import loky.backend.resource_tracker as resource_tracker from loky.backend.context import get_con...
from abc import ABC, abstractmethod from datetime import datetime from typing import List, Optional, Tuple, Any, Dict, Iterable, Generator import yaml from smart_open import smart_open from blurr.core import logging from blurr.core.aggregate_block import BlockAggregate, TimeAggregate from blurr.core.errors import Pr...
from .base_requests import AnymailRequestsBackend, RequestsPayload from ..exceptions import AnymailRequestsAPIError from ..message import AnymailRecipientStatus from ..utils import get_anymail_setting class EmailBackend(AnymailRequestsBackend): """ Postal v1 API Email Backend """ esp_name = "Postal" ...
# encoding: utf-8 # module NationalInstruments.RFmx calls itself RFmx # from NationalInstruments.RFmx.InstrMX.Fx40, Version=19.1.0.49152, Culture=neutral, PublicKeyToken=dc6ad606294fc298 # by generator 1.145 # no doc # no imports # no functions # no classes # variables with complex values
from ..mime import GlueMimeListWidget, LAYERS_MIME_TYPE class TestGlueMimeListWidget(object): def setup_method(self, method): self.w = GlueMimeListWidget() def test_mime_type(self): assert self.w.mimeTypes() == [LAYERS_MIME_TYPE] def test_mime_data(self): self.w.set_data(3, 'tes...
# Generated by Django 2.0.5 on 2018-05-07 13:56 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Ticket', fields=[ ...
import torch import torch.nn.functional as F import random class NGDSAC: ''' Neural-Guided DSAC to robustly fit lines. ''' def __init__(self, hyps, inlier_thresh, inlier_beta, inlier_alpha, loss_function, invalid_loss): ''' Constructor. hyps -- number of line hypotheses sampled for each image inlier_thr...
import Signatures class Tx: inputs = None #input addreses outputs = None #output addreses sigs = None # signatures reqd = None #required signatures that are not inputs def __init__(self): self.inputs = [] self.outputs = [] self.sigs = [] self.reqd = [] def add_inp...
from rest_framework import serializers from rest_framework.fields import SerializerMethodField from .models import content_choice, visibility_choice from .models import Post as Post from backend.settings import SITE_ADDRESS from author.serializers import AuthorSerializer from comment.serializers import ChoiceField, Co...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import time import requests from bs4 import BeautifulSoup session = requests.session() session.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0' words = [] for page in range(1, 94+1): if pa...
import torch import torch.nn as nn from einops.layers.torch import Rearrange # This model is modified from https://github.com/lucidrains/vit-pytorch class ViT(nn.Module): def __init__(self, image_size, patch_size, dim, transformer, num_classes, channels=3, joint=True): super().__init__() num_patch...
import os import signal import asyncio import datetime import json import logging import edgefarm_application as ef from schema_loader import schema_read # # Using the ads_producer/encoder, you can publish a message towards ADS # ads_producer = None ads_encoder = None async def temperature_handler(msg): """This ...
import datetime import unittest import isce from isceobj.Orbit.Orbit import StateVector class StateVectorTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testEqualCompare(self): """ Test that __cmp__ returns true when the times are the s...
"""Batching Lambda function - puts all S3 objects into SQS to be re-analyzed.""" # Expects the following environment variables: # BATCH_LAMBDA_NAME: The name of this Lambda function. # BATCH_LAMBDA_QUALIFIER: The qualifier (alias) which is used to invoke this function. # OBJECTS_PER_MESSAGE: The number of S3 obje...
from cmanager import CreditManager
# -*- coding: utf-8 -*- import ldap #import ldap.modlist as modlist from brie.config import ldap_config from brie.lib.log_helper import BrieLogging from brie.model.ldap import Groupes class Groups(object): __groups = list() def __init__(self, groups): self.__groups = groups #end def def __g...
import sys import json import twint import threading import lzma import glob import instaloader import os import shutil from datetime import datetime from googleapiclient.discovery import build from facebook_scraper import get_posts from PySide2.QtQml import QQmlApplicationEngine from PySide2.QtCore import QObject, Slo...
from _Framework.ButtonSliderElement import ButtonSliderElement SLIDER_MODE_OFF = 0 SLIDER_MODE_TOGGLE = 1 SLIDER_MODE_SLIDER = 2 SLIDER_MODE_PRECISION_SLIDER = 3 SLIDER_MODE_SMALL_ENUM = 4 SLIDER_MODE_BIG_ENUM = 5 #TODO: repeat buttons. # not exact / rounding values in slider and precision slider class DeviceContr...
from selenium.webdriver.common.by import By class MainPageLocators(): SEARCH_STRING = (By.ID, 'text') SUGGEST = (By.CSS_SELECTOR, '[role=listbox]') IMAGES = (By.CSS_SELECTOR, '[data-statlog="services_new.item.images.2"]') class ResultPageLocators(): FIRST_RESULT = (By.CSS_SELECTOR, '[data-cid="0"] .organic__path...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function def env_or_default(name, d): from os import environ try: a = environ[name] if a: return type(d)(a) else: return d except Exception: return d def print_stats(steps, t_diff, dl): from time import strf...
import glob, os, numpy from music21 import converter, instrument, note, chord from itertools import chain import json import pickle PATH = '../Bach-Two_Part_Inventions_MIDI_Transposed/txt' OUTPUT_PATH = '../Bach-Two_Part_Inventions_MIDI_Transposed/txt_tokenized' CHUNK_SIZE = 4 # MEASURES def write_pickle(filename,...
import webbrowser import os import re # Styles and scripting for the page main_page_head = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="Learn To Code Pakistan ...
# demo - opencv import cv2 # Black and White (gray scale) img = cv2.imread ('lotus.jpg', 1 ) cv2.imshow('lotus', img) cv2.waitKey(0) # cv2.waitKey(2000) cv2.destroyAllWindows()
''' import data here and have utility functions that could help ''' import pandas as pd import pickle from thefuzz import fuzz, process ratings = pd.read_csv('./data/ml-latest-small/ratings.csv') movies = pd.read_csv('./data/ml-latest-small/movies.csv') # import nmf model with open('./nmf_recommender.pkl', 'rb') ...
from bs4 import BeautifulSoup import requests import pprint headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'} base_url = 'https://news.ycombinator.com/news' response = requests.get(base_url, headers=headers) soup = Beautiful...
#!/usr/bin/env python3 # # __main__.py """ CLI entry point. """ # # Copyright (c) 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk> # # 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...
from typing import Any, Union from bot.event import Event, EventType from pydantic.utils import deep_update def event( event_data: Union[str, dict[str, Any]], event_type: EventType = EventType.NEW_MESSAGE, ) -> Event: default = { "chat": {"chatId": "test"}, "from": "someone@mail.ru", ...
import cv2 from matplotlib import pyplot as plt img = cv2.imread('open')
from pathlib import Path from flask import current_app from flask_marshmallow import Marshmallow from PIL import Image from flask_app.commons.util import pil_to_base64 from flask_app.database.database import Version, Card ma = Marshmallow() class VersionSchema(ma.SQLAlchemyAutoSchema): class Meta: mode...
# coding=utf-8 #!/bin/python3 # 这个插件用来去掉Equation的xor系列混淆 # 仅仅支持python 3,只在ida pro 7.7下测试过 # 将本文件放到IDA安装目录的plugins目录下,然后启动ida,在ida View中把光标放在解码函数开始,就可以在 Edit->Plugings->Xor Batch Deobfuscation # 也可以使用快捷键Ctrl+Shift+D进行反混淆 import sys try: import idaapi import idc import idautils import flare_emu # imp...
__all__ = ['App'] import control_characters import mdfind import os import plistlib import stat import subprocess import sys from writable_property import writable_property """ path/to/<name>.py class Name(mac_app.App) output: ~/Applications/.mac-app-generator/<name>.app ...
from pymongo import MongoClient client = MongoClient() def get_db(): return client['parallel_chat']
import numpy as np import os # Readme_2_data_abstracts showed how the data abstracts work. # Technically, they embody all functionality to work with data # This part introduces the dataset class, which is based on a dictseqabstract # This means that you can use it in a similar way. # However it has additional function...
from .model import EfficientUnetPlusPlus
import machine import time import json # GPIO connections on test fixture gpio_conn = [ { 'out': 2, 'io': (23, 32) }, { 'out': 1, 'io': (33, 34) }, { 'out': 2, 'io': (5, 12, 35) }, { 'out': 2, 'io': (4, 18) }, { 'out': 2, 'io': (13, 15) }, { 'out': 2, 'io': (2, 14) } ] def testGPIO(): # List of problem ...
import os import re import sqlite3 import configparser from helpers.logger import Logger from helpers.match import MatchDatabase, MatchSource from helpers.searchwords import Searchwords class File: config = configparser.ConfigParser() config.read("config.ini") non_regex_indicator = config.get("ProgramCo...
#!/usr/bin/env python3 """ Interpret all transforms, thereby flattening cairo operations to just a few primitives, such as move_to line_to and curve_to. """ import sys from math import sin, cos, pi from bruhat.argv import argv from bruhat.render import back from bruhat.render.base import Context class Flatten(Cont...
"""REPL server for inspecting and hot-patching a running Python process. This module makes your Python app serve up a REPL (read-eval-print-loop) over TCP, somewhat like the Swank server in Common Lisp. In a REPL session, you can inspect and mutate the global state of your running program. You can e.g. replace top-le...
# standard from collections import defaultdict, OrderedDict import csv import sys import tempfile import unittest class File: ''' An abstract class simplifying file access through the use of only two functions: - read (file) - write (data, file): ''' @classmethod def read(cls, filename): ...
from setuptools import setup, find_packages setup( name="users", version="0.1.0", description="Stoic authentication service", license="Apache", packages=find_packages(), )
from __future__ import print_function # for Python 2/3 compatibility try: import queue except ImportError: import Queue as queue import logging import serial import time import threading from binascii import hexlify, unhexlify from uuid import UUID from enum import Enum from collections import defaultdict f...
# Problem description: http://www.geeksforgeeks.org/dynamic-programming-set-31-optimal-strategy-for-a-game/ def optimal_strategy(coins): if len(coins) == 1: return coins[0] elif len(coins) == 2: return max(coins[0], coins[1]) else: return max(coins[0] + min(optimal_strategy(coins[2:...
import sys from twython import Twython import time import json import os import re import dropbox import subprocess # Secret Keys apiKey = "" apiSecret = "" accessToken = "" accessTokenSecret = "" api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret) tweet = api.get_mentions_timeline() results = api.search(q...
# -*- coding: utf-8 -*- # @Author: Sam Zhang # @Date: 2020-04-12 15:36:23 # @Last Modified by: Sam Zhang # @Last Modified time: 2020-04-14 11:27:50 from flask import render_template, request, redirect, url_for from ..utils import google_search from . import google @google.route('/', methods=['GET', 'POST']) def ...
""" Merge spotify playlists. """ import argparse import logging from playlist import Playlist def spunify(destination_playlist: str, source_playlists: set[str]): """ Merge the source playlists into the destination playlist. :param destination_playlist: The url of the playlist where the tracks w...
#!/usr/bin/python3 import random import math import numpy as np """ Constants """ variance = 0.01 CHECKERBOARD_SIZE = 0.2 """ Functions """ # def get_swiss_roll_dataset(numOfSamples): # sample_list = [] # label_list = [] # for x in range(0, numOfSamples): # # noise_test = random.random() # ...
#take1 pre = '581634BED11C647479ED07B47702E21EFE8147CFA57BF08E105A81852F70CF2ADD01B9E8191622AA5CAB3129D7B5F9EB007C2AA98E48E6E4793BD624F94D40B6B07072A17748A96153C6681716D8593261DD8E5CD6ADEE644D432BD282CB521FA4EBF64109D79A60EFA887D7E8EBE5EB9B43F16F84CBC705D12D1CD429B0166B' get = ['7rJ1loTd72z8fyA71JWAYODTEPL1TEIbBSXd0O...
# -*- coding: utf-8 -*- """ DEPRECATED """ from __future__ import division, print_function import numpy as np from theano import gof import theano.tensor as tt __all__ = ["tensordotDOp"] class tensordotDOp(tt.Op): def __init__(self, func): self.func = func self._grad_op = tensordotDGradientOp(...
# -*- coding: utf-8 -*- """ magic is a wrapper around the libmagic file identification library. See README for more information. Usage: >>> import magic >>> magic.from_file("testdata/test.pdf") 'PDF document, version 1.2' >>> magic.from_file("testdata/test.pdf", mime=True) 'application/pdf' >>> magic.fr...
# Copyright 2017 The Bazel 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 applicable la...
# -*- coding: utf-8 -*- from __future__ import absolute_import # -- stdlib -- # -- third party -- import gevent # -- own -- # -- code -- def instantiate(cls): return cls() def spawn_autorestart(*args, **kwargs): def restart(g): gevent.sleep(1) spawn_autorestart(*args, **kwargs) gevent...
from rest_framework.exceptions import MethodNotAllowed from api.sparse.serializers import SparseNodeSerializer, SparseRegistrationSerializer from api.nodes.views import ( NodeDetail, NodeChildrenList, NodeList, LinkedNodesList, NodeLinkedRegistrationsList, ) from api.registrations.views import Regi...
# The sole purpose of this method is to convert the .dbf file that we have # received which contains all addresses in the city to a .csv file import dbfread as dbf #To read our .dbf file import csv #To write to .csv def convert_addresses_to_csv(): with open('addresses.csv', 'wb') as csvfile: headere...
# pylint:disable=inconsistent-return-statements """ This module provides a class to visualise Click CLI structures """ import io from contextlib import redirect_stdout from copy import deepcopy from typing import Union, Dict, Any, List import treelib from click import Group, MultiCommand from click_tree_viz.click_...
from pprint import pformat import click import py42.sdk.queries.fileevents.filters as f from click import echo from pandas import DataFrame from py42.exceptions import Py42InvalidPageTokenError from py42.sdk.queries.fileevents.file_event_query import FileEventQuery from py42.sdk.queries.fileevents.filters import Inser...
import os import sys sys.path.append(".") from Utils.HTMLTestRunner import * from Testcases.test_login import Login from Testcases.test_02 import Test02 # get the directory path to output report file dir = os.getcwd() # get all tests from Login class login1 = unittest.TestLoader().loadTestsFromTestCase(Login) test02...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import dictc class DictCTest(unittest.TestCase): def setUp(self): pass class BaseDictTest(unittest.TestCase): def setUp(self): from DictC.BaseDict import strip_tags self.strip_tags = strip_tags import re se...
from .clusterer import Clusterer class ClusterMerge(): def __init__(self, config): self.clusterer = Clusterer(**config) self.pattern_generator = self.clusterer.pattern_generator def merge(self, base_list, other_list): for [reprA, countA, patternA, linesA] in other_list: ex...
from setuptools import setup, find_namespace_packages setup(name='sog', version='0.1', description='A creative remake of the 80s MUD', url='', author='Jason Newblanc', author_email='<first>.<last>(at)gmail.com', license='CC0 1.0', packages=find_namespace_packages(include=['sog...
''' Util module to initialize SimpleML and configure database management ''' __author__ = 'Elisha Yadgaran' # Import table models to register in DeclaritiveBase from simpleml.persistables.base_persistable import Persistable import simpleml.datasets.base_dataset import simpleml.pipelines.base_pipeline import simpleml...
""" Functions and objects describing electro-optic components. """ from arch.block import Block from arch.models.model import Linear, SymbolicModel from sympy import Matrix, sqrt, exp, I, pi import arch.port as port class Switch2x2(Block): """ extinction_ratio: ratio of desired signal to undesired signal from wron...
# """ # All operations for the Electricity Spot Market # Based on the role ClearIterativeCO2AndElectricitySpotMarketTwoCountryRole # # Jim Hommes - 25-3-2021 # """ # import json # from modules.marketmodule import MarketModule # from util.repository import Repository # # # class ElectricitySpotMarketSubmitBids(MarketMod...
""" Simple integration tests on the API itself. We make actual ajax requests to the running docker container. """ import os import json import unittest import requests from dotenv import load_dotenv load_dotenv('.env') # The URL of the running server from within the docker container url = 'http://web:5000' service_...
# -*- coding: utf-8 -*- """ Python File Template """ import os import string from onmt.keyphrase.pke.utils import compute_document_frequency exec('from __future__ import unicode_literals') import os import sys import random module_path = os.path.abspath(os.path.join('../')) if module_path not in sys.path: sys...
#!/usr/bin/env python3 # test_app.py import unittest from unittest.mock import patch from snakegame import app from snakegame.player import Player class TestApp(unittest.TestCase): def setUp(self): self.name = "Bob" self.score = 0 self.high_score_name = "John" self.high_score =...
"""Add table for datapath Revision ID: ce8079bf4ab7 Revises: None Create Date: 2017-08-26 21:42:40.469444 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ce8079bf4ab7' down_revision = None branch_labels = None depends_on = None def upgrade(): op.create_t...
"""Mock objects for testing""" SUBMISSION_POST_DATA = { "submission": { "_id": "random_string_from_formio", "data": { "project_name": "123 Market St.", "email": "test@test.com", "phone": "415-867-5309", "name": "Jenny" } } }