content
stringlengths
5
1.05M
######## # 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...
import platform import textwrap import pytest from conan.tools.files import load_toolchain_args from conans.client.tools.apple import XCRun, to_apple_arch from conans.test.assets.autotools import gen_makefile_am, gen_configure_ac from conans.test.assets.sources import gen_function_cpp from conans.test.utils.tools imp...
class MonoBasicPackage (GitHubTarballPackage): def __init__ (self): GitHubTarballPackage.__init__ (self, 'mono', 'mono-basic', '4.0.1', 'b8011b2f274606323da0927214ed98336465f467', configure = './configure --prefix="%{staged_profile}"') def install (self): self.sh ('./configure --prefix="%{staged_prefix}"') ...
# -*- coding: utf-8 -*- ################################################ ### #### # # # # # # # coded by => Cihat Altiparmak # # # # # # creating_date => 19.05.2018 # ...
import sys sys.path.append('C:/Users/dmccloskey-sbrg/Google Drive/SBaaS_base') from SBaaS_base.postgresql_settings import postgresql_settings from SBaaS_base.postgresql_orm import postgresql_orm # read in the settings file filename = 'C:/Users/dmccloskey-sbrg/Google Drive/SBaaS_base/settings_1.ini'; pg_settings = post...
""" Main function of the kalmus software """ from kalmus.barcodes.BarcodeGenerator import BarcodeGenerator from kalmus.tkinter_windows.MainWindowVersion2 import MainWindow from kalmus.tkinter_windows.gui_utils import resource_path # Instantiate the barcode generator object barcode_gn = BarcodeGenerator() # Build the...
import pytest import base64 import json import gzip import test_constants import forwardjsonlogs @pytest.fixture def mock_firehose(mocker): mocker.patch.object(forwardjsonlogs, 'FIREHOSE') return forwardjsonlogs.FIREHOSE def test_handler_valid_json(mock_firehose): log_message = '{"a":1,"b":"foo"}' ...
import sys import numpy def main(): script = sys.argv[0] if len(sys.argv) == 1: # no arguments, so print help message print('Usage: python readings_08.py action filenames\n' 'action must be one of --min --mean --max\n' 'if filenames is blank, input is taken from stdin;\n' ...
import os import tempfile import unittest from multiprocessing.pool import Pool from etl.common.store import IndexStore, MergeStore class TestMergeStore(unittest.TestCase): store = MergeStore('source', 'entity') def test_add_get(self): TestMergeStore.store.add({'entityDbId': '42', ...
# -*- coding: utf-8 -*- import optparse from argparse import ArgumentError from rsatools import utils DEFAULT_EXP = 65537 def main(): parser = optparse.OptionParser() parser.add_option('-g', dest='generate', help='generate key with # of bits', type='int') parser.add_option('--hex', help='display values...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module defines classes to estimate the background and background RMS in an array of any dimension. """ import abc from astropy.stats import (biweight_location, biweight_scale, mad_std, SigmaClip) import numpy as np SI...
import re ALLOWED_CHARS_PATTERN = re.compile(r'[^-a-z0-9]+') DUPLICATE_DASH_PATTERN = re.compile(r'-{2,}') NUMBERS_PATTERN = re.compile(r'(?<=\d),(?=\d)') DEFAULT_SEPARATOR = '-' class Str: @staticmethod def camel(value: str) -> str: value = re.sub('([A-Z]+)', r' \1', value) value = re.sub(r"...
import tensorflow as tf import os import numpy as np import augmentations import histogram import data_processing AUTOTUNE = tf.data.experimental.AUTOTUNE IMG_HEIGHT = 512 IMG_WIDTH = 1024 TRAIN = 'train' TEST = 'test' VALID = 'valid' fax = os.name != 'nt' SATURATION_POINT = 2**14 - 2 MASK = np.ones((1732, 2601, 3)) M...
import data import matplotlib.pyplot as plt def pie_chart(): df, emails, timestamp = data.get_data() # queries to filter responses by social media, labels are self-explanatory tiktok = df[df["Social Media"] == "Tiktok"] instagram = df[df["Social Media"] == "Instagram"] youtube = df[df["Social Med...
__all__ = ["Lexer", "LexerImpl", "LexicalError"] import abc import typing as t from bfpy.core.lexer.token import Token, TokenType, Lexeme class LexicalError(Exception): pass class Lexer(metaclass=abc.ABCMeta): @abc.abstractmethod def tokenize(self, text: t.Text) -> t.Sequence[Token]: ... class Lexer...
from flask_restful import Resource from flask import render_template, make_response import constants class QueueResource(Resource): def get(self): return make_response(render_template('queue.html', env=constants.env), 200, {'Content-Type': 'text/html'})
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def size(self): l = self.left.size() if self.left else 0 r = self.right.size() if self.right else 0 return l + r + 1 def depth(self): left_depth = self.left.dep...
# This file is part of the Reproducible and Reusable Data Analysis Workflow # Server (flowServ). # # Copyright (C) 2019-2021 NYU. # # flowServ is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Implementation of the file store that use...
# #!/usr/bin/env python # # -*- coding: utf-8 -*- # """ # Created on Jul 25, 2014 04:50 # @author: <'Ronny Eichler'> ronny.eichler@gmail.com # # Generator tests... # """ # # import os # import time # import numpy as np # # SIZE_HEADER = 1024 # size of header in B # NUM_SAMPLES = 1024 # number of samples per record # ...
import numpy as np import math import copy class Puyo: def __init__(self, game_rows = 12, game_col = 6, game_n_color = 5, game_nblock = 2): # game_rows = number of rows in the game space # game_col = number of columns in the game space # game_n_color = number of puyo c...
import streamlit as st import pandas as pd import plotly.express as px # pip install plotly-express import base64 # Standard Python Module from io import StringIO, BytesIO # Standard Python Module def generate_excel_download_link(df): # Credit Excel: https://discuss.streamlit.io/t/how-to-add-a-download...
#!/usr/bin/env python3 ''' Meant to run on the reMarkable. Opens a server on 10.11.99.1:33333 (or any wifi ip) and sends all event data to the next client. ''' import socket server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('0.0.0.0', 33333)) server.listen() while True: print('Waiting for clie...
import os from datetime import datetime from typing import List from boto3.session import Session from lib_pushing.aws_client.aws_client import upload_file_to_s3_bucket def get_local_files_folder_path() -> str: return os.path.join(os.getcwd(), "resources\\files") def get_all_file_names(folder_path: str) -> Li...
from typing import TYPE_CHECKING from openwater.schedule.store import ScheduleStore if TYPE_CHECKING: from openwater.core import OpenWater class ScheduleManager: def __init__(self, ow: "OpenWater"): self.store = ScheduleStore(ow)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 12/18/2018 4:12 PM # @Author : Xiang Chen (Richard) # @File : split_abnormal_ais_per_day.py # @Software: PyCharm import glob import pandas as pd """ The split_abnorma_ais_per_day is used to split the AIS data per day. Due to the AIS devices uneven samp...
if math.sqrt(villain.age * hero.age) < 10: hero.age += 2 villain.age -= 1 else: hero.age -= 2 villain.age += 1
from typing import List from rest_framework import routers from rest_framework.parsers import FileUploadParser from rest_framework.request import Request from rest_framework.response import Response from ufdl.json.core import FileMetadata from ...exceptions import JSONParseFailure from ...renderers import BinaryFile...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Cancel Journal Entries', 'version': '1.1', 'category': 'Accounting', 'description': """ Allows canceling accounting entries. ==================================== This module adds a checkbox on...
from sqlalchemy import create_engine, Float, ForeignKey, Column, Date, DateTime, String from sqlalchemy.ext.declarative import declarative_base db = create_engine('sqlite:///mke_adj_db/mke_adj_rec.db', echo = False) Base = declarative_base() class MkeMuniCourt(Base): __tablename__ = 'mke_muni_court' # Defen...
# -*- coding: utf-8 -*- """Tests for the data_handling submodule."""
from dependencies import * def update_json(db_file): json_file = open(db_file, "r+") json_data=json_file.read() data = json.loads(json_data) list(update_ratios(site) for site in data["sites"]) json_file.seek(0) json_file.write(json.dumps(data, indent=2)) json_file.truncate() def update_ratios(site): e...
from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError from FlaskApplication.models import User from flask_login import...
from .user import User from .cryptobot import Cryptobot from .binance_account import BinanceAccount from .telegram import Telegram
# coding: utf-8 from __future__ import absolute_import import unittest from flask import json from six import BytesIO from openapi_server.models.capabilities import Capabilities # noqa: E501 from openapi_server.models.error import Error # noqa: E501 from openapi_server.models.server_info import ServerInfo # noqa:...
# -------------------------------------------------------------------------------------- # Copyright (c) 2013-2022, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # --------------------------------------...
import sys # https://stackoverflow.com/questions/32234156/how-to-unimport-a-python-module-which-is-already-imported #cheap hack to update frames def deimport(module_object=None,module=None,verbose=False): try: _deimport(module_object,module,verbose) except: _deimport(module_object,module,verbos...
"""hide.py Hides or unhides an application with the given PID. """ from __future__ import print_function import sys import accessibility as acc try: sys.argv[1] except IndexError: print('Usage: appinfo.py PID') sys.exit(1) app = acc.create_application_ref(pid = int(sys.argv[1])) if app['AXRole'] != 'A...
from django.db import models from ... import mixins class Zendesk(mixins.SoundcheckBaseModel): """Store git data.""" nb_tickets = models.PositiveIntegerField() nb_urgent_tickets = models.PositiveIntegerField() nb_high_tickets = models.PositiveIntegerField() nb_normal_tickets = models.PositiveInte...
def test(): assert "for ent in doc.ents" in __solution__, "¿Estás iterando sobre las entidades?" assert ( "print(ent.text, ent.label_)" in __solution__ ), "¿Estás imprimiendo en pantalla el texto y el label?" __msg__.good( "¡Muy buen trabajo! Hasta ahora el modelo a estado correcto toda...
from django.conf import settings from django.contrib.auth.models import User class MissingSuperuserException(Exception): pass try: first_superuser = User.objects.filter(is_superuser=True)[0] except: raise MissingSuperuserException('django-todo requires at least one superuser in the database') STAFF_ONLY = getatt...
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2014-2017 Alex Forencich 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...
__author__ = 'Smruti P Mohanty' """ Company : VMWare Inc. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ This is my Hobby Project. There is no guarentee of delivery. """
from builtins import input import json import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np import subprocess import argparse class AnimatedLineGraph: def __init__(self, row, horizon, max_val=1.0): self.row = row self.horizon = horizon fig, axs = plt.s...
import dash import dash_bootstrap_components as dbc app = dash.Dash( __name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.BOOTSTRAP], external_scripts=[ { "src": "https://kit.fontawesome.com/d4bac8c420.js", "crossOrigin": "anonymous" }, ...
# -*- coding: utf-8 -*- """ CLI Resource Integration tests This test file handles the main test flows for the user/host command """ # Builtins import io from contextlib import redirect_stderr from unittest.mock import patch # Internals from conjur.constants import DEFAULT_NETRC_FILE from conjur.data_object import Co...
from pyrolysis.client import checker from pyrolysis.common import errors class SwaggerParameter: def __init__(self, pos, name, required, default_val, doc, checker, encoding, type, enum, parent): self.default_val = default_val self.required = required self.name = name self.pos = pos...
class SampleSource: raw_data = [ """ 1 0 0 0 """, """ 1<0 ^ v 0>0 """, """ 0>0 v ^ 0<0 """, """ 0 0<3<0 0 0 0 0 ^ 0>0 0 0 ^ 0 0 0<0 """, """ 0>3 5 1 0 0 2 0 5 0 ^ 0 0 0 0 0 0 5 0 3 0 0 4 3 2<0 """, """ 0>0 5 0 0 0 2 0 0 0 ^ 0 0 0 0 0 0 0 0 3 0 0 0 0 2<0 """, """ 0 0<0 0<0 ^ 0 0>0 ...
""" Write a KGTK edge or node file in TSV format. """ from argparse import ArgumentParser import attr import bz2 from enum import Enum import errno import gzip import json import lz4 # type: ignore import lzma from pathlib import Path from multiprocessing import Queue import sys import typing from kgtk.kgtkformat im...
#%% from tpot import TPOTClassifier from sklearn.cross_validation import train_test_split import pandas as pd import numpy as np # Load the data telescope = pd.read_csv('../data/magic04.data.csv') # Clean the data telescope_shuffle = telescope.iloc[np.random.permutation(len(telescope))] tele = telescope_shuffle.reset...
##################################################################### # # clock.py # # Copyright (c) 2015, Eran Egozy # # Released under the MIT License (http://opensource.org/licenses/MIT) # ##################################################################### import time import numpy as np from .audio import Audio ...
# -*- coding: utf-8 -*- """ Created on Sat Nov 11 18:49:22 2017 @author: Caasar """ from .base import KNOWN_ARCHIVES, WrapperIOError __all__ = ['KNOWN_ARCHIVES', 'WrapperIOError']
from typing import * from grapl_analyzerlib.nodes.comparators import IntCmp, _int_cmps from grapl_analyzerlib.nodes.types import PropertyT from grapl_analyzerlib.nodes.viewable import EdgeViewT, ForwardEdgeView from grapl_analyzerlib.prelude import ( DynamicNodeQuery, DynamicNodeView, ProcessQuery, Pro...
from nn import relu, sigmoid, tanh, softmax from nn.model import Model from nn.layers import Layer from nn.losses import CrossEntropyLoss, BinaryCrossEntropyLoss from nn.pipeline import DataLoader import numpy as np import pandas as pd import time t = time.process_time() from sklearn.datasets import load_breast_cance...
import my_package.my_functions as mf # This is a user defined package import cv2 import matplotlib.pyplot as plt import numpy as np from scipy import signal import scipy.fft as sfft #-----------------MODULATION--------------------------------- #time frequency axis defination Fs=1000 T=1/Fs L=1001 # Keep...
import sys import zlib import random import base64 from io import BytesIO from PIL import Image __version__ = '0.1.0' class TermImage(object): def __init__(self, data: str): """Creates a new TermImage object using base64 encoded image data""" # The raw base64 encoded data self._r...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from architectures import DENOISERS_ARCHITECTURES, get_architecture, IMAGENET_CLASSIFIERS from datasets import get_dataset, DATASETS from torch.utils.data import DataLoader from torchvision.transforms import ToPILImage import argparse import os i...
import sqlite3 conn = sqlite3.connect('database.db') cursor = conn.cursor() cursor.execute(""" CREATE TABLE contatos ( id INTEGER NOT NULL PRIMARY KEY, nome TEXT NOT NULL, email TEXT NOT NULL ); """) print('Tabela criada') conn.close()
# -*- coding: utf-8 -*- import scipy.optimize import torch import torch.nn.functional as F import numpy as np import multiprocessing def hungarian_loss(predictions, targets, thread_pool): # predictions and targets shape :: (n, c, s) predictions, targets = outer(predictions, targets) # squared_error shape ...
class Node: def __init__(self,key): self.left = None self.right = None self.val = key def printInorder(root): if root: printInorder(root.left) print(root.val), printInorder(root.right) root = Node(1) root.left = Node(2) root.right = N...
print 'first num ?', age = raw_input() print 'second num ?', height = raw_input() print "So you're %r old , %r tall ."%(age, height)
import pytest import subprocess as sp def test_black_formatting(): try: sp.check_output( "black --check gimmemotifs/ setup.py scripts/", stderr=sp.STDOUT, shell=True ) except sp.CalledProcessError as e: msg = e.output.decode("utf-8") msg = msg.split("\n")[:-3] ...
import numpy as np def nextperm(a): n = a.shape[0] j = n - 1 while j > 0 and a[j - 1, 0] >= a[j, 0]: j = j - 1 if j > 0: l = n while a[j - 1, 0] >= a[l - 1, 0]: l = l - 1 tmp = a[j - 1, :].copy() a[j - 1, :] = a[l - 1, :].copy() a[l - 1, :]...
""" Algorithms :: Notes - Writing Better Solutions """ cache = {0: 1, 1: 1} def rec_fib(n: int) -> int: # Base case is in cache if n in cache: return cache[n] # If not in the cache, calculate it n_minus_1 = rec_fib(n - 1) n_minus_2 = rec_fib(n - 2) cache[n] = n_minus_1 + n_minus_2 ...
# Generated from grammar.g4 by ANTLR 4.8 from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\25") buf.write("\u0118\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6...
import sys from clint.textui import puts from clint.textui import colored from clint.textui import progress from clint.textui import columns TTY_COLUMN_SIZE = 80 isatty = lambda : sys.stdout.isatty() def print_colored(txt, color): if isatty(): puts(color(txt)) print_error = lambda txt: print_colored...
import unittest import tensorflow as tf import hoomd import hoomd.md import hoomd.htf import build_examples class test_force_gpu(unittest.TestCase): def test_force_overwrite(self): model = build_examples.BenchmarkNonlistModel(0) tfcompute = hoomd.htf.tfcompute(model) hoomd.context.initiali...
from django.contrib import admin # Register your models here. from django.contrib import admin from .models import Comments @admin.register(Comments) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'mesg') list_filter = ('active', 'created_on')
"""Support for Renault devices.""" import voluptuous as vol from .const import CONF_KAMEREON_ACCOUNT_ID, DOMAIN, SUPPORTED_PLATFORMS from .pyzeproxy import PyzeProxy from .services import async_setup_services, async_unload_services CONFIG_SCHEMA = vol.Schema( {DOMAIN: vol.Schema({}, extra=vol.ALLOW_EXTRA)}, extra...
import unittest import os import numpy.testing as np_tst import pkg_resources from chemml.chem.magpie_python.vassal.data.Atom import Atom from chemml.chem.magpie_python.vassal.data.Cell import Cell from chemml.chem.magpie_python.vassal.io.VASP5IO import VASP5IO class testVASP5IO(unittest.TestCase): def test_conve...
""" Custom menus for DRKCM License: MIT """ from gluon import current from core import * from s3layouts import * try: from .layouts import * except ImportError: pass import s3menus as default from .uioptions import get_ui_options # ====================================================================...
from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy from feincms._internal import ct_render_to_string from . import appsettings class ButtonContent(models.Model): """ Pager item, to show a previous/next page. The pages are...
# -*-coding:utf8-*- import sys reload(sys) sys.setdefaultencoding("utf-8") import mongoengine mongoengine.connect('the_my_zhihu_data') class Zhihu_User_Profile(mongoengine.Document): user_name = mongoengine.StringField() user_be_agreed = mongoengine.StringField() user_be_thanked = mongoengine.StringFie...
import asyncio import time import pytest import py_vsys as pv from test.func_test import conftest as cft class TestVSwapCtrt: """ TestVSwapCtrt is the collection of functional tests of V Swap contract. """ TOK_MAX = 1_000_000_000 HALF_TOK_MAX = TOK_MAX // 2 TOK_UNIT = 1_000 MIN_LIQ = 10...
import oneflow as flow import oneflow.nn as nn from typing import Union, List, Dict, Any, cast from collections import namedtuple __all__ = [ "vgg16", "vgg16_bn", "vgg19_bn", "vgg19", ] # 31 is the raw depth of vgg16, while 37 is the raw depth of vgg19 slice_pos = {31: [4, 9, 16, 23], 37: [4, 9, 18, 2...
#!/usr/bin/env python2 import sys, os, json, logging sys.path.append(os.path.abspath(".")) import gevent import msgflo class Repeat(msgflo.Participant): def __init__(self, role): d = { 'component': 'PythonRepeat', 'label': 'Repeat input data without change', 'inports': [ { 'id': 'in',...
import os import inspect import logging from init import config class ScmLogger: def __init__(self, logger_name, log_function_name=True): self.logger = logging.getLogger(logger_name) self.handler = logging.FileHandler(config['DEFAULT']['log_file']) self.fo...
import datetime from python_helper.api.src.domain import Constant as c from python_helper.api.src.service import ObjectHelper, StringHelper, RandomHelper DEFAULT_DATETIME_PATTERN = '%Y-%m-%d %H:%M:%S' DEFAULT_DATE_PATTERN = '%Y-%m-%d' DEFAULT_TIME_PATTERN = '%H:%M:%S' DATETIME_FULL_PATTERN = '%Y-%m-%d %H:%M:%S.%f' TI...
# Import const module import const # Variables people = food_cost = drinks_cost = deco_cost = catering = total = 0 # Format as a function m_format = "{:,.2f}".format # Inputs try: people = int(input("¿Cantidad de invitados? ")) except Exception as e: print("\nSe produjo la siguiente excepción: " + str(e)) # Pro...
from django.db import migrations ######################################### # Default Roles # ######################################### ROLES = ( ['writer'], ['story'], ['artist'], ['cover'], ['lines'], ['inker'], ['colorist'], ['post'], ['letterer'], ...
from __future__ import (print_function) import logging from interval_tree import IntervalTree def get_haploblocks(variant_batch, individuals): """ Take a variant batch and return the haploblocks for each of the individuals. The haploblocks are dictionaries with individual trees as keys. If a varia...
import factory import pytest from flask import Flask from foundation.value_objects import Color from marshmallow import ValidationError from pytest_lazyfixture import lazy_fixture from web_app.utils import get_file_url class TestColorField: def test_serialized_value_is_color_hex(self, color_field_sample_schema): ...
import os import numpy as np def mkdir(path): """ Create a directory if there isn't one already. """ try: os.mkdir(path) except OSError: pass def paa(sample, w=None): w = sample.shape[0] // 20 if w is None else w l = len(sample) stepfloat = l / w step = int(np.ceil(stepfloa...
from django.apps import AppConfig class ApilearnsConfig(AppConfig): name = 'apilearns'
import json import logging from urllib import parse as urlparse from datetime import datetime from django.db.models.signals import post_save from channels.generic.websocket import JsonWebsocketConsumer from .models import Datapoint from .apps import EmpAppsCache from .utils import datetime_to_pretty_str logger = log...
''' Created on Mar 8, 2016 @author: PJ ''' from BaseScouting.api_scraper.the_blue_alliance.PopulateResultsFromApi import PopulateResultsFromApi from Scouting2017.api_scraper.PopulateRegionalResultsMixin import PopulateRegionalResultsMixin class PopulateResultsFromApi2017(PopulateRegionalResultsMixin, PopulateResults...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'set_parameters_gui.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog...
# 1 and 9 TERMINAL_INDICES = [0, 8, 9, 17, 18, 26] # dragons and winds EAST = 27 SOUTH = 28 WEST = 29 NORTH = 30 HAKU = 31 HATSU = 32 CHUN = 33 WINDS = [EAST, SOUTH, WEST, NORTH] HONOR_INDICES = WINDS + [HAKU, HATSU, CHUN] FIVE_RED_MAN = 16 FIVE_RED_PIN = 52 FIVE_RED_SOU = 88 AKA_DORA_LIST = [FIVE_RED_MAN, FIVE_RED...
import datetime import random from unittest import mock import pytest from statue.cache import Cache from statue.exceptions import CacheError from tests.util import dummy_time_stamps, successful_evaluation_mock def test_save_evaluation(tmp_path, mock_evaluation_load_from_file): timestamp = 12300566 cache_di...
import os os.environ['DISPLAY'] = ':0'; import numpy as np import pandas as pd import cv2 as cv import os import argparse import time import pickle as pkl import tensorflow as tf import keras from keras.models import model_from_json import sklearn import torch import torch.nn as nn from torch.autograd import Variable ...
# vim: ts=4:sw=4:expandtabs __author__ = 'zach.mott@gmail.com' class NavLocationMixin(object): location = None def get_context_data(self, **kw): context = super(NavLocationMixin, self).get_context_data(**kw) context['location'] = self.location return context
# !/usr/bin/env python # -*- coding: UTF-8 -*- from base import BaseObject class DictionaryLoader(BaseObject): """ Load dictionaries by Ontology """ _base_names = ['base', 'cendant'] _biotech_names = ['biotech'] def __init__(self, ontology_name: str, is_debug: bo...
from matplotlib import pyplot as plt def graphpolardist(polarlist): neut, low, plow, shigh, phigh, pgdp, = 0, 0, 0, 0, 0, 0 xlabs = ['Neutral', 'low', 'pretty low','slightly high','pretty high','pretty gosh darn high'] for p in polarlist: if p == 0: neut = neut + 1 elif abs(p) > ...
from pymoo.optimize import minimize from pymoo.util import plotting from pymoo.util.reference_direction import UniformReferenceDirectionFactory from pymop.factory import get_problem problem = get_problem("dtlz2", n_var=12, n_obj=3) # create the reference directions to be used for the optimization ref_dirs = UniformRe...
from .. import standardize_crashes from data.util import write_geocode_cache from jsonschema import validate import json import os import csv import pandas as pd from pandas.util.testing import assert_frame_equal import geopandas as gpd from shapely.geometry import Point import pytz import pytest TEST_FP = os.path.dir...
import unittest from azlyrics import artists, songs, lyrics class AzlyricsTests(unittest.TestCase): def test_artists(self): a = artists("T") self.assertIsNotNone(a) self.assertIn('Taylor Swift', a) def test_songs(self): s = songs("Taylor Swift") self.assertIsNotNone(s...
import json import imutil import numpy as np import time import os from s2clientprotocol import sc2api_pb2 as sc_pb import sc2env.xai_replay.ui.viz.py_backend.proto.explanation_pb2 as expl_pb from pysc2.lib import features import sys REPLAY_DIR_PATH = "../sc2env/sc2env/xai_replay/ui/viz/replays" class XaiReplayRecord...
# -*- coding: utf-8 -*- import sys sys.path.insert(0, "../..") from domonic import * from domonic.html import * from domonic.dQuery import º from domonic.components import Input # create some vars to pass into the templates APPNAME = "pixl" # TOOLBAR_COLUMNS = 1 # https://materialdesignicons.com/ # wand # crop #...
dummy_papers = [ { "abstract": "This is an abstract.", "authors": ["Yi Zhu", "Shawn Newsam"], "category": "cs.CV", "comment": "WACV 2017 camera ready, minor updates about test time efficiency", "img": "/static/thumbs/1612.07403v2.pdf.jpg", "link": "http://arxiv.org/ab...
import os import cv2 import numpy as np from torch.utils.data import Dataset class RegDataSet(Dataset): def __init__(self, dataset_root, anno_txt_path, lexicon_path, target_size=(200, 32), characters="'-' + '0123456789'", transform=None): super(RegDataSet, self).__init__() self.dataset_root = data...
import unittest from app import CONFIG from app.decrypt import decrypt_comment class TestDecrypt(unittest.TestCase): def setUp(self): CONFIG.DECRYPT_COMMENT_KEY = "E3rjFT2i9ALcvc99Pe3YqjIGrzm3LdMsCXc8nUaOEbc=" def test_decrypt_comment_009(self): data = '''gAAAAABgCE5W1uIF-eNt96wT7sOOwgQyBoM...